brsh 3.9.0 → 3.10.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/Readme.md +22 -4
  3. package/bin/Readme.md +33 -3
  4. package/bin/exportFileSystem.js +127 -110
  5. package/bin/wbt.js +118 -0
  6. package/dist/shell.es.js +4074 -3717
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +26 -25
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +3 -3
  11. package/dist/terminal.cjs.js.map +1 -1
  12. package/dist/terminal.es.js +55 -33
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +3 -3
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3082 -2710
  17. package/dist/wbt.es.js.map +1 -1
  18. package/dist/wbt.min.js +16 -12
  19. package/dist/wbt.min.js.map +1 -1
  20. package/index.js +102 -80
  21. package/lib/BaseFileSystem.js +57 -2
  22. package/lib/BinaryContainer.js +1 -1
  23. package/lib/Command.js +1 -1
  24. package/lib/Context.js +4 -3
  25. package/lib/FileSystem.js +4 -2
  26. package/lib/InteractiveCommand.js +9 -8
  27. package/lib/JsCommand.js +113 -0
  28. package/lib/NodeFileSystem.js +164 -30
  29. package/lib/Readme.md +1 -0
  30. package/lib/ScriptCommand.js +148 -8
  31. package/lib/Terminal.js +60 -6
  32. package/lib/TtyStream.js +36 -2
  33. package/lib/WasmCommand.js +313 -66
  34. package/lib/buildFilesystemStructure.js +38 -24
  35. package/lib/isUtf8Text.js +47 -0
  36. package/lib/local/which.js +8 -3
  37. package/lib/wbt/index.js +473 -175
  38. package/lib/wbt/registry.js +21 -1
  39. package/package.json +3 -2
  40. package/test/devices-signals.test.js +112 -0
  41. package/test/doom.test.js +7 -4
  42. package/test/exportFileSystem.test.js +37 -15
  43. package/test/js-command.test.js +125 -0
  44. package/test/node-filesystem.test.js +7 -0
  45. package/test/scripts.test.js +30 -0
  46. package/test/terminal.test.js +148 -0
  47. package/test/wasm-cli.test.js +76 -0
  48. package/test/wbt.test.js +418 -10
  49. package/test/wbtCli.test.js +160 -0
@@ -180,6 +180,23 @@ const DEFAULT_REGISTRY = {
180
180
  type: 'custom-wasm',
181
181
  interactive: true,
182
182
  size: '680 KB'
183
+ },
184
+ doom: {
185
+ name: 'doom',
186
+ bin: 'doom',
187
+ aliases: ['doom-wasm', 'doom-ascii'],
188
+ scripts: {
189
+ freedoom: 'https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/bin/freedoom'
190
+ },
191
+ version: '1.0.0',
192
+ description: 'Classic Doom (1993) compiled to WebAssembly with 24-bit ANSI rendering',
193
+ details: 'Classic Doom engine compiled to WebAssembly (wasm32-wasip1) with 24-bit TrueColor ANSI terminal graphics, wasi-termios-brsh terminal shim, and Asyncify real-time frame loop. Includes the `freedoom` launcher script which automatically downloads and caches Freedoom Phase 1/2 WADs into /usr/share/games/doom/.',
194
+ homepage: 'https://github.com/eliotstocker/doom-wasm',
195
+ cdnUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm',
196
+ wasmUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/doom-wasm@main/dist/doom.wasm',
197
+ type: 'custom-wasm',
198
+ interactive: true,
199
+ size: '1.0 MB'
183
200
  }
184
201
  };
185
202
 
@@ -201,7 +218,10 @@ const PACKAGE_ALIASES = {
201
218
  'llama-cli': 'wllama',
202
219
  'llama.cpp': 'wllama',
203
220
  '@wllama/wllama': 'wllama',
204
- 'nano-wasm': 'nano'
221
+ 'nano-wasm': 'nano',
222
+ 'doom-wasm': 'doom',
223
+ 'doom-ascii': 'doom',
224
+ freedoom: 'doom'
205
225
  };
206
226
 
207
227
  function resolvePackageName(name) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.9.0",
3
+ "version": "3.10.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",
@@ -23,7 +23,8 @@
23
23
  },
24
24
  "bin": {
25
25
  "exportFileSystem": "bin/exportFileSystem.js",
26
- "brsh": "bin/brsh-shell.js"
26
+ "brsh": "bin/brsh-shell.js",
27
+ "wbt": "bin/wbt.js"
27
28
  },
28
29
  "scripts": {
29
30
  "start": "node bin/exportFileSystem.js ./demo/filesystem -o ./demo/fs.js -v fs --binary -c && vite --config vite.config.js demo/",
@@ -170,4 +170,116 @@ describe('WASM requirements auto-discovery', () => {
170
170
  wasmCmd2._inspectedWasm = { isInteractive: true };
171
171
  expect(wasmCmd2.interactive).toBe(true);
172
172
  });
173
+
174
+ it('encodes special keys and ignores bare modifier keys in WasmCommand._keyToBytes', () => {
175
+ const wasmCmd = new WasmCommand('game.wasm', [], {});
176
+ const dec = new TextDecoder();
177
+
178
+ expect(wasmCmd._keyToBytes('Shift')).toBeNull();
179
+ expect(wasmCmd._keyToBytes('Control')).toBeNull();
180
+ expect(wasmCmd._keyToBytes('Alt')).toBeNull();
181
+ expect(wasmCmd._keyToBytes('Meta')).toBeNull();
182
+ expect(wasmCmd._keyToBytes('CapsLock')).toBeNull();
183
+ expect(wasmCmd._keyToBytes('Unidentified')).toBeNull();
184
+
185
+ expect(dec.decode(wasmCmd._keyToBytes('Space'))).toBe(' ');
186
+ expect(dec.decode(wasmCmd._keyToBytes('Spacebar'))).toBe(' ');
187
+ expect(dec.decode(wasmCmd._keyToBytes('Up'))).toBe('\x1b[A');
188
+ expect(dec.decode(wasmCmd._keyToBytes('Down'))).toBe('\x1b[B');
189
+ expect(dec.decode(wasmCmd._keyToBytes('Right'))).toBe('\x1b[C');
190
+ expect(dec.decode(wasmCmd._keyToBytes('Left'))).toBe('\x1b[D');
191
+ expect(dec.decode(wasmCmd._keyToBytes('Esc'))).toBe('\x1b');
192
+ expect(dec.decode(wasmCmd._keyToBytes('Return'))).toBe('\r');
193
+ expect(dec.decode(wasmCmd._keyToBytes('Del'))).toBe('\x1b[3~');
194
+ expect(dec.decode(wasmCmd._keyToBytes('BackTab'))).toBe('\x1b[Z');
195
+ expect(dec.decode(wasmCmd._keyToBytes('F1'))).toBe('\x1bOP');
196
+ expect(dec.decode(wasmCmd._keyToBytes('F5'))).toBe('\x1b[15~');
197
+ expect(dec.decode(wasmCmd._keyToBytes('F12'))).toBe('\x1b[24~');
198
+ });
199
+
200
+ it('parses function keys, modified cursor sequences, and detects custom stdin listeners in TtyStream', () => {
201
+ const { parseVtKeys, hasCustomStdinListener } = require('../lib/TtyStream.js');
202
+ expect(parseVtKeys('\x1bOP\x1bOQ\x1b[15~\x1b[24~\x1b[2~\x1b[Z')).toEqual([
203
+ 'F1', 'F2', 'F5', 'F12', 'Insert', 'BackTab'
204
+ ]);
205
+ expect(parseVtKeys('\x1b[1;5A\x1b[1;2C')).toEqual(['ArrowUp', 'ArrowRight']);
206
+
207
+ const cmd = new Command([], {});
208
+ expect(hasCustomStdinListener(cmd)).toBe(false);
209
+
210
+ // Simulate WasmCommand removing default _onStdinStreamData and attaching raw data listener (listenerCount === 1)
211
+ cmd.stdinStream.off('data', cmd._onStdinStreamData);
212
+ const customFn = () => {};
213
+ cmd.stdinStream.on('data', customFn);
214
+ expect(cmd.stdinStream.listenerCount('data')).toBe(1);
215
+ expect(hasCustomStdinListener(cmd)).toBe(true);
216
+
217
+ cmd._managesOwnStdinCapture = true;
218
+ expect(hasCustomStdinListener(cmd)).toBe(false);
219
+ });
220
+
221
+ it('initializes Shell with cols/rows options and prioritizes live stream size in InteractiveCommand', async () => {
222
+ const InteractiveCommand = require('../lib/InteractiveCommand.js');
223
+ const sizedShell = new Shell({ cols: 140, rows: 45 });
224
+ expect(sizedShell.stdout.columns).toBe(140);
225
+ expect(sizedShell.stdout.rows).toBe(45);
226
+ expect(sizedShell.context.getVar('COLUMNS')).toBe('140');
227
+ expect(sizedShell.context.getVar('LINES')).toBe('45');
228
+
229
+ const icmd = new InteractiveCommand([], sizedShell.context);
230
+ sizedShell.context.setVar('COLUMNS', '80');
231
+ sizedShell.context.setVar('LINES', '24');
232
+ icmd.stdout.columns = 160;
233
+ icmd.stdout.rows = 50;
234
+ expect(icmd.terminalSize).toEqual({ cols: 160, rows: 50 });
235
+ });
236
+
237
+ it('forwards Ctrl+C (\\x03) as raw input to a raw-mode child command inside a shell script without killing the script', async () => {
238
+ const shell = await createShell({
239
+ filesystem: {
240
+ bin: {
241
+ 'run-raw': '#!/bin/sh\nrawchild\n'
242
+ }
243
+ },
244
+ permissions: {
245
+ '/bin/run-raw': 0o755
246
+ }
247
+ });
248
+
249
+ const receivedBytes = [];
250
+ class RawChildCommand extends Command {
251
+ static get name() { return 'rawchild'; }
252
+ get interactive() { return true; }
253
+ get captureInput() { return true; }
254
+ run() {
255
+ return new Promise(resolve => {
256
+ this.stdinStream.off('data', this._onStdinStreamData);
257
+ this.stdinStream.setRawMode(true);
258
+ this.stdinStream.on('data', chunk => {
259
+ const s = String(chunk);
260
+ receivedBytes.push(s);
261
+ if (s === 'q') {
262
+ this.stdinStream.setRawMode(false);
263
+ resolve();
264
+ }
265
+ });
266
+ });
267
+ }
268
+ }
269
+ shell.context.setCommand(RawChildCommand);
270
+
271
+ const p = shell.onCommand('run-raw');
272
+ await new Promise(r => setTimeout(r, 40));
273
+
274
+ // Send Ctrl+C while rawchild is in raw mode inside ScriptCommand
275
+ shell.write('\x03');
276
+ await new Promise(r => setTimeout(r, 20));
277
+ expect(receivedBytes).toContain('\x03');
278
+
279
+ // Exit rawchild cleanly
280
+ shell.write('q');
281
+ await p;
282
+ expect(shell.lastCode).toBe(0);
283
+ });
173
284
  });
285
+
package/test/doom.test.js CHANGED
@@ -3,9 +3,12 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { createShell } from './helpers.js';
5
5
 
6
- const DOOM_WASM_PATH = fs.existsSync('/home/antigravity/doom-ascii/dist/doom.wasm')
7
- ? '/home/antigravity/doom-ascii/dist/doom.wasm'
8
- : '/tmp/doom-asyncify.wasm';
6
+ const DOOM_WASM_CANDIDATES = [
7
+ '/home/antigravity/eliotstocker/doom-wasm/dist/doom.wasm',
8
+ '/home/antigravity/doom-ascii/dist/doom.wasm',
9
+ '/tmp/doom-asyncify.wasm'
10
+ ];
11
+ const DOOM_WASM_PATH = DOOM_WASM_CANDIDATES.find(p => fs.existsSync(p)) || DOOM_WASM_CANDIDATES[0];
9
12
  const DOOM_WAD_PATH = '/tmp/doom1.wad';
10
13
  const hasDoom = fs.existsSync(DOOM_WASM_PATH) && fs.existsSync(DOOM_WAD_PATH);
11
14
 
@@ -31,6 +34,6 @@ describe('Doom in brsh', () => {
31
34
  expect(shell.lastCode).toBe(0);
32
35
  const allOut = lines.join('');
33
36
  expect(allOut).toContain('DOOM ASCII');
34
- expect(allOut).toContain('timed 5026 gametics');
37
+ expect(allOut).toMatch(/timed \d+ gametics/);
35
38
  }, 30000);
36
39
  });
@@ -58,19 +58,18 @@ describe('buildStructure', () => {
58
58
  expect(filesystem['readme.txt']).toBe('hello');
59
59
  });
60
60
 
61
- it('strips the .js extension from JavaScript file keys', () => {
61
+ it('preserves the .js extension from JavaScript file keys and stores content directly', () => {
62
62
  writeFileSync(join(root, 'app.js'), 'module.exports = {}');
63
63
  const { filesystem } = buildStructure(root);
64
- expect(filesystem).toHaveProperty('app');
65
- expect(filesystem).not.toHaveProperty('app.js');
66
- expect(filesystem['app']).toMatch(/^require\('/);
64
+ expect(filesystem).toHaveProperty('app.js');
65
+ expect(filesystem).not.toHaveProperty('app');
66
+ expect(filesystem['app.js']).toBe('module.exports = {}');
67
67
  });
68
68
 
69
- it('uses an absolute path in the require() string for JavaScript files', () => {
69
+ it('stores plain text JavaScript content for JavaScript files', () => {
70
70
  writeFileSync(join(root, 'data.js'), 'module.exports = "content"');
71
71
  const { filesystem } = buildStructure(root);
72
- const reqPath = filesystem.data.match(/require\('(.+?)'\)/)[1];
73
- expect(reqPath).toBe(resolve(root, 'data.js'));
72
+ expect(filesystem['data.js']).toBe('module.exports = "content"');
74
73
  });
75
74
 
76
75
  it('recursively includes nested directories', () => {
@@ -89,7 +88,7 @@ describe('buildStructure', () => {
89
88
  mkdirSync(b);
90
89
  writeFileSync(join(b, 'deep.js'), 'module.exports = "deep"');
91
90
  const { filesystem } = buildStructure(root);
92
- expect(filesystem.a.b['deep']).toMatch(/^require\('/);
91
+ expect(filesystem.a.b['deep.js']).toBe('module.exports = "deep"');
93
92
  });
94
93
 
95
94
  it('ignores .DS_Store files', () => {
@@ -108,7 +107,30 @@ describe('buildStructure', () => {
108
107
  expect(Object.keys(filesystem)).toHaveLength(3);
109
108
  expect(filesystem).toHaveProperty('a.txt');
110
109
  expect(filesystem).toHaveProperty('b.txt');
111
- expect(filesystem).toHaveProperty('c');
110
+ expect(filesystem).toHaveProperty('c.js');
111
+ });
112
+
113
+ it('serializes filesystem symlinks into SymlinkRef references', () => {
114
+ const { symlinkSync } = require('fs');
115
+ const { SymlinkRef } = require('../lib/BaseFileSystem.js');
116
+ mkdirSync(join(root, 'bin'));
117
+ mkdirSync(join(root, 'usr', 'lib', 'nano'), { recursive: true });
118
+ writeFileSync(join(root, 'usr', 'lib', 'nano', 'nano.wasm'), Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
119
+ symlinkSync('/usr/lib/nano/nano.wasm', join(root, 'bin', 'nano'));
120
+
121
+ const { filesystem } = buildStructure(root);
122
+ expect(filesystem.bin.nano instanceof SymlinkRef).toBe(true);
123
+ expect(filesystem.bin.nano.target).toBe('/usr/lib/nano/nano.wasm');
124
+ expect(JSON.stringify(filesystem.bin.nano)).toBe(JSON.stringify({ $l: '/usr/lib/nano/nano.wasm' }));
125
+ });
126
+
127
+ it('detects UTF-8 text vs binary bytes by content and defaults unknown binary bytes to binary URI', () => {
128
+ writeFileSync(join(root, 'unknown_text.custom'), 'Hello UTF-8 Custom Text');
129
+ writeFileSync(join(root, 'unknown_binary.custom'), Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]));
130
+
131
+ const { filesystem } = buildStructure(root);
132
+ expect(filesystem['unknown_text.custom']).toBe('Hello UTF-8 Custom Text');
133
+ expect(filesystem['unknown_binary.custom']).toMatch(/^data:application\/octet-stream;base64,/);
112
134
  });
113
135
 
114
136
  it('throws when the root directory does not exist', () => {
@@ -138,16 +160,16 @@ describe('buildStructure', () => {
138
160
  expect(permissions['/bin/tool.sh']).toBe(0o755);
139
161
  });
140
162
 
141
- it('encodes .wasm files as data:application/wasm;base64 and strips .wasm extension', () => {
163
+ it('encodes .wasm files as data:application/wasm;base64 and preserves .wasm extension', () => {
142
164
  const sub = join(root, 'bin');
143
165
  mkdirSync(sub);
144
166
  const wasmBytes = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
145
167
  writeFileSync(join(sub, 'jq.wasm'), wasmBytes);
146
168
  chmodSync(join(sub, 'jq.wasm'), 0o755);
147
169
  const { filesystem, permissions } = buildStructure(root);
148
- expect(filesystem.bin).toHaveProperty('jq');
149
- expect(filesystem.bin.jq).toBe(`data:application/wasm;base64,${wasmBytes.toString('base64')}`);
150
- expect(permissions['/bin/jq']).toBe(0o755);
170
+ expect(filesystem.bin).toHaveProperty('jq.wasm');
171
+ expect(filesystem.bin['jq.wasm']).toBe(`data:application/wasm;base64,${wasmBytes.toString('base64')}`);
172
+ expect(permissions['/bin/jq.wasm']).toBe(0o755);
151
173
  });
152
174
  });
153
175
 
@@ -393,9 +415,9 @@ describe('exportFileSystem CLI --binary (.brfs indexed binary container)', () =>
393
415
  const { filesystem, permissions } = deserializeBinaryFilesystem(raw);
394
416
  expect(filesystem['hello.txt']).toBe('Hello Binary Container');
395
417
  expect(filesystem.bin['run.sh']).toBe('#!/sh.js\necho hi');
396
- expect(filesystem.bin.tool instanceof Uint8Array).toBe(true);
418
+ expect(filesystem.bin['tool.wasm'] instanceof Uint8Array).toBe(true);
397
419
  expect(permissions['/bin/run.sh']).toBe(0o755);
398
- expect(permissions['/bin/tool']).toBe(0o755);
420
+ expect(permissions['/bin/tool.wasm']).toBe(0o755);
399
421
  });
400
422
 
401
423
  it('writes a JS loader and .brfs binary container when --binary (-b) is passed with -o fs.js', () => {
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ import { describe, it, expect } from 'vitest';
4
+ import JsCommand from '../lib/JsCommand.js';
5
+ import FileSystem from '../lib/FileSystem.js';
6
+ import LocalCommand from '../lib/local/LocalCommand.js';
7
+
8
+ describe('JsCommand (lib/JsCommand.js)', () => {
9
+ it('returns an exported Command subclass directly', () => {
10
+ class CustomCmd extends LocalCommand {
11
+ static get name() { return 'custom'; }
12
+ get name() { return 'custom'; }
13
+ run() { this.stdOut = 'custom ran'; }
14
+ }
15
+
16
+ const fs = new FileSystem('/', {
17
+ bin: {
18
+ 'custom.js': 'module.exports = class CustomCmd extends LocalCommand {}'
19
+ }
20
+ });
21
+
22
+ // Mock loadModule on fs
23
+ fs.loadModule = () => CustomCmd;
24
+
25
+ const Loaded = JsCommand.load(fs, '/bin/custom.js');
26
+ expect(Loaded).toBe(CustomCmd);
27
+ });
28
+
29
+ it('wraps an exported function or object as a generic command', () => {
30
+ const fs = new FileSystem('/', {
31
+ bin: {
32
+ 'tool.js': 'module.exports = function(args) { return "ok"; }'
33
+ }
34
+ });
35
+ fs.loadModule = () => (args) => 'ok';
36
+
37
+ const Loaded = JsCommand.load(fs, '/bin/tool.js');
38
+ expect(typeof Loaded).toBe('function');
39
+ expect(Loaded.prototype && typeof Loaded.prototype.run === 'function').toBe(true);
40
+ });
41
+
42
+ it('auto-wires sibling .wasm binary when wrapping a module', () => {
43
+ const dummyWasm = new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
44
+ const fs = new FileSystem('/', {
45
+ usr: {
46
+ lib: {
47
+ mytool: {
48
+ 'mytool.js': 'module.exports = {}',
49
+ 'mytool.wasm': dummyWasm
50
+ }
51
+ }
52
+ }
53
+ });
54
+ fs.loadModule = () => ({});
55
+
56
+ const Loaded = JsCommand.load(fs, '/usr/lib/mytool/mytool.js');
57
+ expect(typeof Loaded).toBe('function');
58
+ const instance = new Loaded([], { fs });
59
+ expect(instance.requiresFilesystem).toBe(true);
60
+ });
61
+
62
+ it('uses the cache when content matches and invalidates when content changes', () => {
63
+ const cache = new Map();
64
+ const fs = new FileSystem('/', {
65
+ bin: {
66
+ 'cached.js': 'module.exports = class V1 extends LocalCommand {}'
67
+ }
68
+ });
69
+
70
+ class V1 extends LocalCommand { static get name() { return 'v1'; } }
71
+ class V2 extends LocalCommand { static get name() { return 'v2'; } }
72
+
73
+ fs.loadModule = (p) => V1;
74
+ const First = JsCommand.load(fs, '/bin/cached.js', 'content1', cache);
75
+ expect(First).toBe(V1);
76
+ expect(cache.has('/bin/cached.js')).toBe(true);
77
+
78
+ // Second call with same content returns cached V1 without re-evaluating
79
+ fs.loadModule = (p) => V2;
80
+ const Second = JsCommand.load(fs, '/bin/cached.js', 'content1', cache);
81
+ expect(Second).toBe(V1);
82
+
83
+ // Third call with changed content re-evaluates to V2
84
+ const Third = JsCommand.load(fs, '/bin/cached.js', 'content2', cache);
85
+ expect(Third).toBe(V2);
86
+ });
87
+
88
+ it('throws a descriptive error when script evaluation fails', () => {
89
+ const fs = new FileSystem('/', {
90
+ bin: {
91
+ 'broken.js': 'syntax error !!!'
92
+ }
93
+ });
94
+ fs.loadModule = () => { throw new Error('Unexpected token'); };
95
+
96
+ expect(() => {
97
+ JsCommand.load(fs, '/bin/broken.js');
98
+ }).toThrow(/Failed to evaluate script/);
99
+ });
100
+
101
+ it('detects JS files and Command classes via static helpers', () => {
102
+ class ValidCmd extends LocalCommand {
103
+ run() {}
104
+ }
105
+ function plainFn() {}
106
+
107
+ expect(JsCommand.isCommandClass(ValidCmd)).toBe(true);
108
+ expect(JsCommand.isCommandClass(plainFn)).toBe(false);
109
+ expect(JsCommand.isJsFile('/bin/foo.js', 'console.log(1)')).toBe(true);
110
+ expect(JsCommand.isJsFile('/bin/foo', 'module.exports = {}')).toBe(true);
111
+ expect(JsCommand.isJsFile('/bin/foo', plainFn)).toBe(true);
112
+ expect(JsCommand.isJsFile('/bin/foo', '#!/bin/sh\necho hi')).toBe(false);
113
+ });
114
+
115
+ it('resolves multi-hop relative and absolute symlinks via fs.realpath', () => {
116
+ const fs = new FileSystem('/', {
117
+ usr: { lib: { pkg: { 'tool.js': 'module.exports = {}' } } },
118
+ bin: {}
119
+ });
120
+ fs.createSymlink('/usr/lib/pkg/tool.js', '/bin/tool');
121
+ fs.createSymlink('tool', '/bin/tool-alias');
122
+
123
+ expect(fs.realpath('/bin/tool-alias')).toBe('/usr/lib/pkg/tool.js');
124
+ });
125
+ });
@@ -148,6 +148,13 @@ module.exports = Hello;
148
148
  expect(exitCode).toBe(0);
149
149
  expect(output).toContain('hello from js bin');
150
150
  });
151
+
152
+ it('fs.loadModule loads CommonJS modules from disk on NodeFileSystem', async () => {
153
+ const modPath = path.join(tmpDir, 'helper.js');
154
+ fs.writeFileSync(modPath, `module.exports = { answer: 42 };\n`);
155
+ const loaded = shell.context.fs.loadModule(modPath);
156
+ expect(loaded).toEqual({ answer: 42 });
157
+ });
151
158
  });
152
159
 
153
160
  // ---------------------------------------------------------------------------
@@ -531,4 +531,34 @@ describe('multiline quotes and line continuations in scripts', () => {
531
531
  const { output } = await run(shell, '/scripts/if-not-true.sh');
532
532
  expect(output).toEqual(['expected']);
533
533
  });
534
+
535
+ it('expands $@ in for loops and matches pipe-separated alternatives in case clauses', async () => {
536
+ const shell = await createShell({
537
+ filesystem: {
538
+ scripts: {
539
+ 'args-case.sh': [
540
+ '#!/bin/sh',
541
+ 'for ARG in $@',
542
+ 'do',
543
+ ' case "$ARG" in',
544
+ ' --help|-h)',
545
+ ' echo "matched-help"',
546
+ ' ;;',
547
+ ' --phase2|-2)',
548
+ ' echo "matched-2"',
549
+ ' ;;',
550
+ ' *)',
551
+ ' echo "other:$ARG"',
552
+ ' ;;',
553
+ ' esac',
554
+ 'done'
555
+ ].join('\n')
556
+ }
557
+ },
558
+ permissions: execPerms('/scripts/args-case.sh')
559
+ });
560
+ const res = await run(shell, '/scripts/args-case.sh -2 --help custom');
561
+ expect(res.exitCode).toBe(0);
562
+ expect(res.output).toEqual(['matched-2', 'matched-help', 'other:custom']);
563
+ });
534
564
  });
@@ -1140,5 +1140,153 @@ describe('Output Typing Animation Suppression', () => {
1140
1140
 
1141
1141
  term.destroy();
1142
1142
  });
1143
+
1144
+ it('measures initial dimensions before attaching cli and subtracts CSS padding', () => {
1145
+ const el = document.createElement('div');
1146
+ el.clientWidth = 1020;
1147
+ el.clientHeight = 520;
1148
+ globalThis.window.getComputedStyle = () => ({
1149
+ paddingLeft: '10px',
1150
+ paddingRight: '10px',
1151
+ paddingTop: '14px',
1152
+ paddingBottom: '14px'
1153
+ });
1154
+ const origCreate = globalThis.document.createElement;
1155
+ globalThis.document.createElement = (tag) => {
1156
+ const node = origCreate(tag);
1157
+ if (tag === 'span') {
1158
+ node.getBoundingClientRect = () => ({ left: 0, top: 0, width: 8, height: 18 });
1159
+ }
1160
+ return node;
1161
+ };
1162
+
1163
+ try {
1164
+ const sizedShell = new Shell({ cwd: '/root' });
1165
+ const term = new Terminal({
1166
+ el,
1167
+ cli: sizedShell
1168
+ });
1169
+
1170
+ // (1020 - 20) / 8 = 125 cols; (520 - 28) / 18 = 27 rows
1171
+ expect(term.cols).toBe(125);
1172
+ expect(term.rows).toBe(27);
1173
+ expect(sizedShell.stdout.columns).toBe(125);
1174
+ expect(sizedShell.stdout.rows).toBe(27);
1175
+ expect(sizedShell.context.getVar('COLUMNS')).toBe('125');
1176
+ expect(sizedShell.context.getVar('LINES')).toBe('27');
1177
+
1178
+ term.destroy();
1179
+ } finally {
1180
+ globalThis.document.createElement = origCreate;
1181
+ delete globalThis.window.getComputedStyle;
1182
+ }
1183
+ });
1184
+
1185
+ it('does not double-emit Enter when mobile input keydown bubbles to window', () => {
1186
+ const el = document.createElement('div');
1187
+ const term = new Terminal({
1188
+ el,
1189
+ Shell: false,
1190
+ mobileInput: 'click'
1191
+ });
1192
+
1193
+ const received = [];
1194
+ term.onData((d) => received.push(d));
1195
+
1196
+ const enterEvent = {
1197
+ key: 'Enter',
1198
+ defaultPrevented: false,
1199
+ preventDefault() { this.defaultPrevented = true; }
1200
+ };
1201
+ // Dispatch on hidden <input>, then simulate DOM bubbling to window
1202
+ term._mobileInputElement.dispatchEvent('keydown', enterEvent);
1203
+ globalThis.window.dispatchEvent('keydown', enterEvent);
1204
+
1205
+ // IME composing events on window should also be ignored
1206
+ globalThis.window.dispatchEvent('keydown', { key: 'a', isComposing: true });
1207
+ globalThis.window.dispatchEvent('keydown', { key: 'a', keyCode: 229 });
1208
+
1209
+ expect(received).toEqual(['\r']);
1210
+ term.destroy();
1211
+ });
1212
+
1213
+ it('supports legacy/alias key names and ignores bare lock/unidentified keys', () => {
1214
+ const el = document.createElement('div');
1215
+ const term = new Terminal({
1216
+ el,
1217
+ Shell: false,
1218
+ cols: 80,
1219
+ rows: 24
1220
+ });
1221
+
1222
+ const received = [];
1223
+ term.onData((d) => received.push(d));
1224
+
1225
+ term.sendKey('Space');
1226
+ term.sendKey('Spacebar');
1227
+ term.sendKey('Return');
1228
+ term.sendKey('Esc');
1229
+ term.sendKey('Up');
1230
+ term.sendKey('Down');
1231
+ term.sendKey('Right');
1232
+ term.sendKey('Left');
1233
+ term.sendKey('Del');
1234
+ term.sendKey('F1');
1235
+ term.sendKey('F12');
1236
+ term.sendKey('NumLock');
1237
+ term.sendKey('ScrollLock');
1238
+ term.sendKey('CapsLock');
1239
+ term.sendKey('Dead');
1240
+ term.sendKey('Unidentified');
1241
+
1242
+ expect(received).toEqual([
1243
+ ' ', ' ', '\r', '\x1b',
1244
+ '\x1b[A', '\x1b[B', '\x1b[C', '\x1b[D',
1245
+ '\x1b[3~', '\x1bOP', '\x1b[24~'
1246
+ ]);
1247
+ term.destroy();
1248
+ });
1249
+
1250
+ it('passes Ctrl+C (^C) to raw ReplCommand to clear current input instead of killing REPL', async () => {
1251
+ class LineClearRepl extends Shell.ReplCommand {
1252
+ static get name() { return 'clearrepl'; }
1253
+ shouldBeInteractive() { return true; }
1254
+ getReplTitle() { return 'LineClear REPL'; }
1255
+ getReplPrompt() { return 'lc> '; }
1256
+ async evaluateReplLine(line) {
1257
+ return { output: [`ok:${line}`] };
1258
+ }
1259
+ }
1260
+
1261
+ const replShell = new Shell({ filesystem: { root: {} }, cwd: '/root', hostname: 'brsh' });
1262
+ const ready = waitForReady(replShell);
1263
+ const term = new Terminal({
1264
+ el: document.createElement('div'),
1265
+ cli: replShell,
1266
+ cols: 60,
1267
+ rows: 15
1268
+ });
1269
+ await ready;
1270
+
1271
+ replShell.context.setCommand(LineClearRepl);
1272
+ const replDone = waitForReady(replShell);
1273
+ replShell.onCommand('clearrepl');
1274
+ await new Promise(r => setTimeout(r, 30));
1275
+
1276
+ for (const ch of 'draft') term.sendKey(ch);
1277
+ // Send Ctrl+C while input is non-empty -> clears input line, keeps REPL alive in alt screen
1278
+ term.sendKey('c', { ctrl: true });
1279
+ await new Promise(r => setTimeout(r, 20));
1280
+
1281
+ expect(term.screen.isAltScreen).toBe(true);
1282
+ expect(term.getScreenText()).toContain('lc> draft^C');
1283
+
1284
+ // Exit cleanly with Ctrl+D
1285
+ term.sendKey('d', { ctrl: true });
1286
+ await replDone;
1287
+ expect(replShell.lastCode).toBe(0);
1288
+ term.destroy();
1289
+ });
1143
1290
  });
1144
1291
  });
1292
+