brsh 2.4.1 → 2.5.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/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;
package/lib/FileSystem.js CHANGED
@@ -2,9 +2,67 @@
2
2
 
3
3
  const BaseFileSystem = require('./BaseFileSystem');
4
4
 
5
+ /**
6
+ * Represents a binary file stored as raw bytes in the virtual filesystem.
7
+ * Extends Uint8Array so binary-aware commands can access bytes directly,
8
+ * while text-based commands (cat, grep, etc.) get the original data URI
9
+ * via toString() — avoiding the 33% base64 memory overhead at runtime.
10
+ */
11
+ class BinaryFile extends Uint8Array {
12
+ constructor(buffer, mimeType) {
13
+ super(buffer);
14
+ Object.defineProperty(this, 'mimeType', { value: mimeType, enumerable: false, configurable: false, writable: false });
15
+ }
16
+
17
+ toString() {
18
+ if (typeof Buffer !== 'undefined') {
19
+ return `data:${this.mimeType};base64,${Buffer.from(this).toString('base64')}`;
20
+ }
21
+ // Browser path — chunked to avoid stack overflow on large files
22
+ let binary = '';
23
+ const chunk = 8192;
24
+ for (let i = 0; i < this.length; i += chunk) {
25
+ binary += String.fromCharCode(...this.subarray(i, i + chunk));
26
+ }
27
+ return `data:${this.mimeType};base64,${btoa(binary)}`;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
33
+ * node to BinaryFile instances (Uint8Array subclass), saving the ~33%
34
+ * memory overhead of storing base64-encoded binary data as UTF-16 strings.
35
+ * Mutates the node in-place.
36
+ */
37
+ function decodeBinaryFiles(node) {
38
+ for (const key of Object.keys(node)) {
39
+ const value = node[key];
40
+ if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array)) {
41
+ decodeBinaryFiles(value);
42
+ } else if (typeof value === 'string' && value.startsWith('data:')) {
43
+ const semicolon = value.indexOf(';');
44
+ const comma = value.indexOf(',', semicolon);
45
+ if (semicolon !== -1 && comma !== -1 && value.slice(semicolon + 1, comma) === 'base64') {
46
+ const mimeType = value.slice(5, semicolon);
47
+ const b64 = value.slice(comma + 1);
48
+ let bytes;
49
+ if (typeof Buffer !== 'undefined') {
50
+ bytes = new Uint8Array(Buffer.from(b64, 'base64'));
51
+ } else {
52
+ const binary = atob(b64);
53
+ bytes = new Uint8Array(binary.length);
54
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
55
+ }
56
+ node[key] = new BinaryFile(bytes.buffer, mimeType);
57
+ }
58
+ }
59
+ }
60
+ }
61
+
5
62
  class FileSystem extends BaseFileSystem {
6
63
  constructor(cwd = '/', filesystem = {}, permissions = {}, onChange = null) {
7
64
  super();
65
+ decodeBinaryFiles(filesystem);
8
66
  this.fileSystem = filesystem;
9
67
  this.permissions = Object.assign({}, permissions);
10
68
  this.cwd = cwd;
@@ -39,8 +97,9 @@ class FileSystem extends BaseFileSystem {
39
97
  if (file === null || file === undefined) return null;
40
98
  return {
41
99
  isDirectory: file.constructor === Object,
42
- isFile: typeof file === 'string',
43
- isCommand: typeof file === 'function'
100
+ isFile: typeof file === 'string' || file instanceof Uint8Array,
101
+ isCommand: typeof file === 'function',
102
+ isBinary: file instanceof Uint8Array,
44
103
  };
45
104
  }
46
105
 
@@ -191,6 +250,7 @@ class FileSystem extends BaseFileSystem {
191
250
  const file = this._getFileByAbsolutePath(absolute);
192
251
  if (file === null || file === undefined) return 0;
193
252
  if (file.constructor === Object) return JSON.stringify(file).length;
253
+ if (file instanceof Uint8Array) return file.length;
194
254
  return file.toString().length;
195
255
  }
196
256
 
@@ -250,3 +310,4 @@ class FileSystem extends BaseFileSystem {
250
310
 
251
311
 
252
312
  module.exports = FileSystem;
313
+ module.exports.BinaryFile = BinaryFile;
@@ -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;
@@ -238,7 +238,7 @@ class NodeFileSystem extends BaseFileSystem {
238
238
  const abs = this.absolutePath(path);
239
239
  if (this._virtualFiles[abs] !== undefined) {
240
240
  const v = this._virtualFiles[abs];
241
- return { isDirectory: v !== null && v !== undefined && v.constructor === Object, isFile: typeof v === 'string', isCommand: typeof v === 'function' };
241
+ return { isDirectory: v !== null && v !== undefined && v.constructor === Object, isFile: typeof v === 'string' || v instanceof Uint8Array, isCommand: typeof v === 'function', isBinary: v instanceof Uint8Array };
242
242
  }
243
243
  try {
244
244
  const s = nodeFs.statSync(abs);
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.1",
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
 
@@ -0,0 +1,91 @@
1
+ import { createRequire } from 'module';
2
+ import { describe, it, expect } from 'vitest';
3
+ import { createShell, run } from './helpers.js';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const FileSystem = require('../lib/FileSystem.js');
7
+ const { BinaryFile } = require('../lib/FileSystem.js');
8
+
9
+ // Small 1x1 red PNG (base64)
10
+ const RED_PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwADhQGAWjR9awAAAABJRU5ErkJggg==';
11
+ const RED_PNG_DATA_URI = `data:image/png;base64,${RED_PNG_B64}`;
12
+
13
+ // Helper: create BinaryFile from base64 without Buffer pool issues
14
+ function binaryFileFromB64(b64, mime) {
15
+ const bytes = new Uint8Array(Buffer.from(b64, 'base64'));
16
+ return new BinaryFile(bytes.buffer, mime);
17
+ }
18
+
19
+ describe('BinaryFile class', () => {
20
+ it('is a subclass of Uint8Array', () => {
21
+ const bf = binaryFileFromB64(RED_PNG_B64, 'image/png');
22
+ expect(bf instanceof Uint8Array).toBe(true);
23
+ expect(bf instanceof BinaryFile).toBe(true);
24
+ });
25
+
26
+ it('stores mimeType as non-enumerable property', () => {
27
+ const bf = binaryFileFromB64(RED_PNG_B64, 'image/png');
28
+ expect(bf.mimeType).toBe('image/png');
29
+ expect(Object.keys(bf)).not.toContain('mimeType');
30
+ });
31
+
32
+ it('toString() reconstructs the original data URI', () => {
33
+ const bf = binaryFileFromB64(RED_PNG_B64, 'image/png');
34
+ expect(bf.toString()).toBe(RED_PNG_DATA_URI);
35
+ });
36
+
37
+ it('has the correct byte length', () => {
38
+ const bf = binaryFileFromB64(RED_PNG_B64, 'image/png');
39
+ const expectedLen = Buffer.from(RED_PNG_B64, 'base64').length;
40
+ expect(bf.length).toBe(expectedLen);
41
+ });
42
+ });
43
+
44
+ describe('FileSystem binary conversion', () => {
45
+ it('converts data URI strings to BinaryFile on construction', () => {
46
+ const fs = new FileSystem('/', { img: RED_PNG_DATA_URI });
47
+ const file = fs.getFileByPath('/img');
48
+ expect(file instanceof BinaryFile).toBe(true);
49
+ });
50
+
51
+ it('does not modify non-data-URI strings', () => {
52
+ const fs = new FileSystem('/', { readme: 'hello world' });
53
+ const file = fs.getFileByPath('/readme');
54
+ expect(typeof file).toBe('string');
55
+ expect(file).toBe('hello world');
56
+ });
57
+
58
+ it('recurses into subdirectories', () => {
59
+ const fs = new FileSystem('/', { subdir: { img: RED_PNG_DATA_URI } });
60
+ const file = fs.getFileByPath('/subdir/img');
61
+ expect(file instanceof BinaryFile).toBe(true);
62
+ });
63
+
64
+ it('stat() reports isBinary:true for converted images', () => {
65
+ const fs = new FileSystem('/', { img: RED_PNG_DATA_URI });
66
+ const s = fs.stat('/img');
67
+ expect(s.isFile).toBe(true);
68
+ expect(s.isBinary).toBe(true);
69
+ expect(s.isDirectory).toBe(false);
70
+ expect(s.isCommand).toBe(false);
71
+ });
72
+
73
+ it('stat() reports isBinary:false for text files', () => {
74
+ const fs = new FileSystem('/', { readme: 'hello' });
75
+ const s = fs.stat('/readme');
76
+ expect(s.isFile).toBe(true);
77
+ expect(s.isBinary).toBe(false);
78
+ });
79
+
80
+ it('getSize() returns byte count for binary files', () => {
81
+ const fs = new FileSystem('/', { img: RED_PNG_DATA_URI });
82
+ const bytes = Buffer.from(RED_PNG_B64, 'base64');
83
+ expect(fs.getSize('/img')).toBe(bytes.length);
84
+ });
85
+
86
+ it('BinaryFile toString() is backward-compatible via cat', async () => {
87
+ const shell = await createShell({ filesystem: { img: RED_PNG_DATA_URI } });
88
+ const { output } = await run(shell, 'cat /img');
89
+ expect(output.join('')).toBe(RED_PNG_DATA_URI);
90
+ });
91
+ });
@@ -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, existsSync } from 'fs';
5
5
  import { tmpdir } from 'os';
6
6
  import { join, resolve } from 'path';
7
7
  import { fileURLToPath } from 'url';
8
+ import { gunzipSync } from 'zlib';
8
9
 
9
10
  const require = createRequire(import.meta.url);
10
11
  const { buildStructure } = require('../lib/buildFilesystemStructure.js');
@@ -244,3 +245,105 @@ 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('writes a .brfs binary file alongside the .js loader', () => {
277
+ const outFile = join(outDir, 'fs.js');
278
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
279
+ expect(existsSync(outFile)).toBe(true);
280
+ expect(existsSync(join(outDir, 'fs.brfs'))).toBe(true);
281
+ });
282
+
283
+ it('the .js loader is valid JavaScript', () => {
284
+ const outFile = join(outDir, 'fs.js');
285
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
286
+ const content = readFileSync(outFile, 'utf8');
287
+ expect(() => new Function(content)).not.toThrow();
288
+ });
289
+
290
+ it('the .js loader references DecompressionStream and fetch', () => {
291
+ const outFile = join(outDir, 'fs.js');
292
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
293
+ const content = readFileSync(outFile, 'utf8');
294
+ expect(content).toContain('DecompressionStream');
295
+ expect(content).toContain('fetch');
296
+ expect(content).toContain('.brfs');
297
+ });
298
+
299
+ it('the .js loader does not contain any filesystem content', () => {
300
+ const outFile = join(outDir, 'fs.js');
301
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
302
+ const content = readFileSync(outFile, 'utf8');
303
+ expect(content).not.toContain('Hello World');
304
+ });
305
+
306
+ it('the .brfs file is smaller than the uncompressed .js bundle for text-heavy filesystem', () => {
307
+ const textRoot = tmpDir();
308
+ try {
309
+ for (let i = 0; i < 20; i++) {
310
+ writeFileSync(join(textRoot, `doc${i}.txt`), `${'Content line repeated many times.\n'.repeat(200)} document ${i}`);
311
+ }
312
+ const compressedOut = join(outDir, 'compressed.js');
313
+ const uncompressedOut = join(outDir, 'uncompressed.js');
314
+ runCLI([textRoot, '-v', 'FS', '-o', compressedOut, '--compress']);
315
+ runCLI([textRoot, '-v', 'FS', '-o', uncompressedOut]);
316
+ expect(statSync(join(outDir, 'compressed.brfs')).size).toBeLessThan(statSync(uncompressedOut).size);
317
+ } finally {
318
+ rmSync(textRoot, { recursive: true, force: true });
319
+ }
320
+ });
321
+
322
+ it('the .brfs file is valid gzip that decompresses to executable JS', () => {
323
+ const outFile = join(outDir, 'fs.js');
324
+ runCLI([root, '-v', 'TestFS', '-o', outFile, '--compress']);
325
+ const brfsData = readFileSync(join(outDir, 'fs.brfs'));
326
+ const code = gunzipSync(brfsData).toString('utf8');
327
+ expect(() => new Function(code)).not.toThrow();
328
+ });
329
+
330
+ it('the .brfs bundle resolves to an object with filesystem and permissions', () => {
331
+ const outFile = join(outDir, 'fs.js');
332
+ runCLI([root, '-v', 'TestFS', '-o', outFile, '--compress']);
333
+ const brfsData = readFileSync(join(outDir, 'fs.brfs'));
334
+ const code = gunzipSync(brfsData).toString('utf8');
335
+ const result = new Function(code)();
336
+ expect(result).toHaveProperty('filesystem');
337
+ expect(result).toHaveProperty('permissions');
338
+ expect(result.filesystem['hello.txt']).toBe('Hello World');
339
+ });
340
+
341
+ it('the .brfs bundle contains JS command code', () => {
342
+ const outFile = join(outDir, 'fs.js');
343
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
344
+ const brfsData = readFileSync(join(outDir, 'fs.brfs'));
345
+ const code = gunzipSync(brfsData).toString('utf8');
346
+ // app.js exports a function – its compiled form must be in the bundle
347
+ expect(code.length).toBeGreaterThan(100);
348
+ });
349
+ });