brsh 3.8.0 → 3.9.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.
@@ -44,15 +44,31 @@ class WasmCommand extends ScriptCommand {
44
44
  const isHelpOrVersion = (this.arguments || []).some(a => a === '--help' || a === '-h' || a === '--version' || a === '-V' || a === '-v');
45
45
  if (isHelpOrVersion) return false;
46
46
  if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
47
- if (this._pkgMeta && this._pkgMeta.interactive !== undefined) return Boolean(this._pkgMeta.interactive);
48
- const name = (this.script || this.name || '').toLowerCase();
49
- return name === 'nano' || name.endsWith('/nano') || name.endsWith('nano.wasm');
47
+ if (this._pkgMeta && (this._pkgMeta.interactive || this._pkgMeta.wasm?.interactive)) return true;
48
+ if (this._inspectedWasm && this._inspectedWasm.isInteractive) return true;
49
+ return false;
50
50
  }
51
51
 
52
52
  get captureInput() {
53
53
  return this.interactive;
54
54
  }
55
55
 
56
+ kill(signal = 'SIGINT') {
57
+ this._killed = true;
58
+ this.exitCode = 130;
59
+ this._exitAltScreen();
60
+ if (this._asyncifyReject) {
61
+ try { this._asyncifyReject(new Error('Interrupted by SIGINT')); } catch (_) {}
62
+ this._asyncifyReject = null;
63
+ }
64
+ if (this._pendingReadResolve) {
65
+ const r = this._pendingReadResolve;
66
+ this._pendingReadResolve = null;
67
+ try { r(); } catch (_) {}
68
+ }
69
+ super.kill(signal);
70
+ }
71
+
56
72
  _enterAltScreen() {
57
73
  if (this._inAltScreen) return;
58
74
  this._inAltScreen = true;
@@ -110,6 +126,9 @@ class WasmCommand extends ScriptCommand {
110
126
 
111
127
  onInput(key) {
112
128
  if (this._handlingStreamData) return;
129
+ if (this.stdinStream && this.stdinStream._isPushing) {
130
+ return;
131
+ }
113
132
  if (typeof this._externalKeyHandler === 'function') {
114
133
  this._externalKeyHandler(key);
115
134
  return;
@@ -142,19 +161,30 @@ class WasmCommand extends ScriptCommand {
142
161
  _loadBytes(filepath, nodeFs) {
143
162
  const fs = (this.context && this.context.fs) || this.fs;
144
163
  if (!fs) return Promise.reject(new Error(`${filepath}: Filesystem is not available`));
164
+ let p;
145
165
  if (fs.isRealFilesystem && nodeFs) {
146
166
  try {
147
167
  const buf = nodeFs.readFileSync(fs.absolutePath(filepath));
148
168
  const bytes = new Uint8Array(buf);
149
- return Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
169
+ p = Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
150
170
  } catch(e) {
151
171
  return Promise.reject(new Error(`${filepath}: ${e.message}`));
152
172
  }
173
+ } else {
174
+ const content = fs.getFileByPath(filepath);
175
+ if (content == null) return Promise.reject(new Error(`${filepath}: No such file or directory`));
176
+ const bytes = this._contentToBytes(content);
177
+ p = Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
153
178
  }
154
- const content = fs.getFileByPath(filepath);
155
- if (content == null) return Promise.reject(new Error(`${filepath}: No such file or directory`));
156
- const bytes = this._contentToBytes(content);
157
- return Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
179
+ return p.then(res => {
180
+ if (!res.isWat && res.bytes) {
181
+ this._inspectedWasm = inspectWasmBytes(res.bytes);
182
+ if (this._inspectedWasm.isInteractive) {
183
+ this._isInteractive = true;
184
+ }
185
+ }
186
+ return res;
187
+ });
158
188
  }
159
189
 
160
190
  _isWat(filepath, bytes) {
@@ -233,6 +263,8 @@ class WasmCommand extends ScriptCommand {
233
263
  isInteractive = true;
234
264
  this._isInteractive = true;
235
265
 
266
+ this._enterAltScreen();
267
+
236
268
  if (outBuf[1]) {
237
269
  if (this.stdout && typeof this.stdout.write === 'function') this.stdout.write(outBuf[1]);
238
270
  outBuf[1] = '';
@@ -316,6 +348,9 @@ class WasmCommand extends ScriptCommand {
316
348
  if (b) enqueueBytes(b);
317
349
  };
318
350
 
351
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
352
+ this.stdinStream.off('data', this._onStdinStreamData);
353
+ }
319
354
  if (isTtyEnvironment && this.stdinStream && typeof this.stdinStream.on === 'function') {
320
355
  this.stdinStream.on('data', onStreamData);
321
356
  }
@@ -539,8 +574,10 @@ class WasmCommand extends ScriptCommand {
539
574
  }
540
575
 
541
576
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
542
- asyncifyPromise = new Promise(resolve => {
577
+ asyncifyPromise = new Promise((resolve, reject) => {
543
578
  pendingReadResolve = resolve;
579
+ this._pendingReadResolve = resolve;
580
+ this._asyncifyReject = reject;
544
581
  });
545
582
  view.setUint32(nread_ptr, 0, true);
546
583
  return ERRNO_SUCCESS;
@@ -794,13 +831,21 @@ class WasmCommand extends ScriptCommand {
794
831
  new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
795
832
  return ERRNO_SUCCESS;
796
833
  }
797
- if (cleanPath === '/dev/tty') {
834
+ if (cleanPath === '/dev/tty' || cleanPath === '/dev/stdin') {
798
835
  promoteToInteractive();
799
836
  const newFd = nextFd++;
800
- fdTable.set(newFd, { type: 'dev_tty', path: '/dev/tty' });
837
+ fdTable.set(newFd, { type: 'dev_tty', path: cleanPath });
801
838
  new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
802
839
  return ERRNO_SUCCESS;
803
840
  }
841
+ if (cleanPath === '/dev/stdout') {
842
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, 1, true);
843
+ return ERRNO_SUCCESS;
844
+ }
845
+ if (cleanPath === '/dev/stderr') {
846
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, 2, true);
847
+ return ERRNO_SUCCESS;
848
+ }
804
849
 
805
850
  const st = fs.stat(absPath);
806
851
  const exists = st !== null;
@@ -855,14 +900,14 @@ class WasmCommand extends ScriptCommand {
855
900
  const absPath = resolveGuestPath(dirfd, relPath);
856
901
  if (!absPath) return ERRNO_BADF;
857
902
  const cleanPath = absPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
858
- if (cleanPath === '/dev/null' || cleanPath === '/dev/zero' || cleanPath === '/dev/urandom' || cleanPath === '/dev/random' || cleanPath === '/dev/tty') {
903
+ const st = fs.stat(absPath);
904
+ if (cleanPath === '/dev/null' || cleanPath === '/dev/zero' || cleanPath === '/dev/urandom' || cleanPath === '/dev/random' || cleanPath === '/dev/tty' || cleanPath === '/dev/stdin' || cleanPath === '/dev/stdout' || cleanPath === '/dev/stderr' || (st && (st.isDevice || st.isCharacterDevice))) {
859
905
  const view = new DataView(memRef.buffer);
860
906
  for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
861
907
  view.setUint8(buf_ptr + 16, FILETYPE_CHARACTER_DEVICE);
862
908
  view.setBigUint64(buf_ptr + 24, 1n, true);
863
909
  return ERRNO_SUCCESS;
864
910
  }
865
- const st = fs.stat(absPath);
866
911
  if (!st) return ERRNO_NOENT;
867
912
  const view = new DataView(memRef.buffer);
868
913
  for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
@@ -876,6 +921,7 @@ class WasmCommand extends ScriptCommand {
876
921
  const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
877
922
  const absPath = resolveGuestPath(dirfd, relPath);
878
923
  if (!absPath) return ERRNO_BADF;
924
+ if (fs.exists(absPath)) return ERRNO_EXIST;
879
925
  try {
880
926
  fs.setFileByPath(absPath, {}, true);
881
927
  return ERRNO_SUCCESS;
@@ -1117,17 +1163,23 @@ class WasmCommand extends ScriptCommand {
1117
1163
  }
1118
1164
 
1119
1165
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1120
- asyncifyPromise = new Promise(resolve => {
1166
+ asyncifyPromise = new Promise((resolve, reject) => {
1121
1167
  let timer = null;
1168
+ this._asyncifyReject = reject;
1122
1169
  const onKey = () => {
1123
1170
  if (timer) clearTimeout(timer);
1124
1171
  pendingReadResolve = null;
1172
+ this._pendingReadResolve = null;
1173
+ this._asyncifyReject = null;
1125
1174
  resolve();
1126
1175
  };
1127
1176
  pendingReadResolve = onKey;
1177
+ this._pendingReadResolve = onKey;
1128
1178
  if (minTimeoutMs !== Infinity) {
1129
1179
  timer = setTimeout(() => {
1130
1180
  pendingReadResolve = null;
1181
+ this._pendingReadResolve = null;
1182
+ this._asyncifyReject = null;
1131
1183
  resolve();
1132
1184
  }, Math.max(1, minTimeoutMs));
1133
1185
  }
@@ -1262,24 +1314,43 @@ class WasmCommand extends ScriptCommand {
1262
1314
  if (res && typeof res.then === 'function') res = await res;
1263
1315
 
1264
1316
  while (hasAsyncify && typeof instance.exports.asyncify_get_state === 'function' && instance.exports.asyncify_get_state() === 1) {
1317
+ if (this._killed) {
1318
+ this.exitCode = 130;
1319
+ break;
1320
+ }
1265
1321
  instance.exports.asyncify_stop_unwind();
1266
1322
  if (asyncifyPromise) {
1267
- await asyncifyPromise;
1323
+ try {
1324
+ await asyncifyPromise;
1325
+ } catch (_) {
1326
+ if (this._killed) {
1327
+ this.exitCode = 130;
1328
+ break;
1329
+ }
1330
+ }
1268
1331
  asyncifyPromise = null;
1269
1332
  }
1333
+ if (this._killed) {
1334
+ this.exitCode = 130;
1335
+ break;
1336
+ }
1270
1337
  instance.exports.asyncify_start_rewind(asyncifyDataAddr);
1271
1338
  res = start();
1272
1339
  if (res && typeof res.then === 'function') res = await res;
1273
1340
  }
1274
1341
  } catch(e) {
1275
- if (!e || !e._wasmExit) {
1342
+ if (this._killed) {
1343
+ this.exitCode = 130;
1344
+ } else if (!e || !e._wasmExit) {
1276
1345
  this.stdErr = `${this.script}: runtime error: ${e?.message || String(e)}`;
1277
1346
  this.exitCode = 1;
1278
1347
  }
1279
1348
  }
1280
1349
  }
1281
1350
  } catch(e) {
1282
- if (!e || !e._wasmExit) {
1351
+ if (this._killed) {
1352
+ this.exitCode = 130;
1353
+ } else if (!e || !e._wasmExit) {
1283
1354
  this.stdErr = `${this.script}: ${e?.message || String(e)}`;
1284
1355
  this.exitCode = 1;
1285
1356
  }
@@ -1287,10 +1358,13 @@ class WasmCommand extends ScriptCommand {
1287
1358
  if (isInteractive) {
1288
1359
  this._exitAltScreen();
1289
1360
  }
1290
- if (isInteractive && onStreamData) {
1361
+ if (onStreamData) {
1291
1362
  if (this.stdinStream && typeof this.stdinStream.off === 'function') this.stdinStream.off('data', onStreamData);
1292
1363
  if (this.stdin && typeof this.stdin.off === 'function') this.stdin.off('data', onStreamData);
1293
1364
  }
1365
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.on === 'function') {
1366
+ this.stdinStream.on('data', this._onStdinStreamData);
1367
+ }
1294
1368
  if (onResize) {
1295
1369
  if (this.stdout && typeof this.stdout.off === 'function') this.stdout.off('resize', onResize);
1296
1370
  if (this.stdinStream && typeof this.stdinStream.off === 'function') this.stdinStream.off('resize', onResize);
@@ -1498,7 +1572,9 @@ function inspectWasmBytes(bytes) {
1498
1572
  usage: null,
1499
1573
  options: [],
1500
1574
  exports: [],
1501
- wasiImports: []
1575
+ wasiImports: [],
1576
+ hasAsyncify: false,
1577
+ isInteractive: false
1502
1578
  };
1503
1579
  if (!(bytes instanceof Uint8Array) || bytes.length < 8) return info;
1504
1580
 
@@ -1511,6 +1587,11 @@ function inspectWasmBytes(bytes) {
1511
1587
  info.wasiImports = WebAssembly.Module.imports(mod)
1512
1588
  .filter(i => i.module.startsWith('wasi_'))
1513
1589
  .map(i => i.name);
1590
+
1591
+ info.hasAsyncify = info.exports.includes('asyncify_start_unwind') && info.exports.includes('asyncify_stop_unwind');
1592
+ if (info.exports.includes('set_terminal_size')) {
1593
+ info.isInteractive = true;
1594
+ }
1514
1595
  }
1515
1596
  } catch {
1516
1597
  // Ignore if bytes are WAT or non-standard
@@ -1530,7 +1611,14 @@ function inspectWasmBytes(bytes) {
1530
1611
  }
1531
1612
  if (cur.length >= 4) chunks.push(cur);
1532
1613
 
1533
- const parsed = extractHelpFromText(chunks.join('\n'), true);
1614
+ const allText = chunks.join('\n');
1615
+ if (!info.isInteractive) {
1616
+ if (allText.includes('/dev/tty') || allText.includes('\x1b[?1049h') || allText.includes('smcup') || allText.includes('xterm')) {
1617
+ info.isInteractive = true;
1618
+ }
1619
+ }
1620
+
1621
+ const parsed = extractHelpFromText(allText, true);
1534
1622
  info.usage = parsed.usage;
1535
1623
  info.options = parsed.options;
1536
1624
  } catch {
@@ -1622,6 +1710,31 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1622
1710
  get name() { return binName; }
1623
1711
  get requiresFilesystem() { return true; }
1624
1712
 
1713
+ get interactive() {
1714
+ if (this._subCommand) return this._subCommand.interactive;
1715
+ if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
1716
+ if (pkgMeta && (pkgMeta.interactive || pkgMeta.wasm?.interactive)) return true;
1717
+ if (this._inspectedWasm && this._inspectedWasm.isInteractive) return true;
1718
+ return false;
1719
+ }
1720
+
1721
+ get captureInput() {
1722
+ return this.interactive;
1723
+ }
1724
+
1725
+ kill(signal = 'SIGINT') {
1726
+ if (this._subCommand && typeof this._subCommand.kill === 'function') {
1727
+ this._subCommand.kill(signal);
1728
+ }
1729
+ super.kill(signal);
1730
+ }
1731
+
1732
+ onInput(char) {
1733
+ if (this._subCommand && typeof this._subCommand.onInput === 'function') {
1734
+ this._subCommand.onInput(char);
1735
+ }
1736
+ }
1737
+
1625
1738
  async run() {
1626
1739
  const args = [...(this.arguments || [])];
1627
1740
  const isHelp = args.includes('--help') || args.includes('-h');
@@ -1809,7 +1922,12 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1809
1922
  if (this.stdin !== undefined) {
1810
1923
  wasmCmd.stdin = this.stdin;
1811
1924
  }
1812
- await wasmCmd._runWasm(bytes);
1925
+ this._subCommand = wasmCmd;
1926
+ try {
1927
+ await wasmCmd._runWasm(bytes);
1928
+ } finally {
1929
+ this._subCommand = null;
1930
+ }
1813
1931
  for (const line of wasmCmd.result.getStdOutput()) {
1814
1932
  if (line.type === 'out') this.stdOut = line.string;
1815
1933
  else if (line.type === 'err') this.stdErr = line.string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.8.0",
3
+ "version": "3.9.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",
@@ -0,0 +1,173 @@
1
+ import { createRequire } from 'module';
2
+ import { describe, it, expect, beforeEach } from 'vitest';
3
+ import { createShell, run } from './helpers.js';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const Shell = require('../index.js');
7
+ const FileSystem = require('../lib/FileSystem.js');
8
+ const Command = require('../lib/Command.js');
9
+ const WasmCommand = require('../lib/WasmCommand.js');
10
+
11
+ describe('Virtual /dev endpoints in filesystem', () => {
12
+ let shell;
13
+
14
+ beforeEach(async () => {
15
+ shell = await createShell();
16
+ });
17
+
18
+ it('has /dev directory and standard device nodes mounted', () => {
19
+ expect(shell.context.fs.exists('/dev')).toBe(true);
20
+ expect(shell.context.fs.exists('/dev/null')).toBe(true);
21
+ expect(shell.context.fs.exists('/dev/zero')).toBe(true);
22
+ expect(shell.context.fs.exists('/dev/urandom')).toBe(true);
23
+ expect(shell.context.fs.exists('/dev/random')).toBe(true);
24
+ expect(shell.context.fs.exists('/dev/tty')).toBe(true);
25
+ expect(shell.context.fs.exists('/dev/stdin')).toBe(true);
26
+ expect(shell.context.fs.exists('/dev/stdout')).toBe(true);
27
+ expect(shell.context.fs.exists('/dev/stderr')).toBe(true);
28
+ });
29
+
30
+ it('identifies /dev character devices with stat', () => {
31
+ const nullStat = shell.context.fs.stat('/dev/null');
32
+ expect(nullStat.isCharacterDevice).toBe(true);
33
+ expect(nullStat.isDirectory).toBe(false);
34
+
35
+ const urandomStat = shell.context.fs.stat('/dev/urandom');
36
+ expect(urandomStat.isCharacterDevice).toBe(true);
37
+
38
+ const devStat = shell.context.fs.stat('/dev');
39
+ expect(devStat.isDirectory).toBe(true);
40
+ });
41
+
42
+ it('lists /dev contents using ls', async () => {
43
+ const res = await run(shell, 'ls /dev');
44
+ expect(res.output.join(' ')).toContain('null');
45
+ expect(res.output.join(' ')).toContain('zero');
46
+ expect(res.output.join(' ')).toContain('urandom');
47
+ expect(res.output.join(' ')).toContain('tty');
48
+ });
49
+
50
+ it('reads empty from /dev/null and discards writes to /dev/null', async () => {
51
+ const catRes = await run(shell, 'cat /dev/null');
52
+ expect(catRes.exitCode).toBe(0);
53
+ expect(catRes.output.join('')).toBe('');
54
+
55
+ const writeRes = await run(shell, 'echo "discarded output" > /dev/null');
56
+ expect(writeRes.exitCode).toBe(0);
57
+
58
+ const catRes2 = await run(shell, 'cat /dev/null');
59
+ expect(catRes2.exitCode).toBe(0);
60
+ expect(catRes2.output.join('')).toBe('');
61
+ });
62
+
63
+ it('reads non-empty bytes from /dev/zero and /dev/urandom', () => {
64
+ const zeroBytes = shell.context.fs.getFileByPath('/dev/zero');
65
+ expect(zeroBytes instanceof Uint8Array).toBe(true);
66
+ expect(zeroBytes.length).toBeGreaterThan(0);
67
+ expect(zeroBytes.every(b => b === 0)).toBe(true);
68
+
69
+ const randBytes = shell.context.fs.getFileByPath('/dev/urandom');
70
+ expect(randBytes instanceof Uint8Array).toBe(true);
71
+ expect(randBytes.length).toBeGreaterThan(0);
72
+ });
73
+
74
+ it('writes to /dev/tty directly to terminal stdout', async () => {
75
+ const stdoutChunks = [];
76
+ shell.stdout.on('data', chunk => stdoutChunks.push(String(chunk)));
77
+ await shell.onCommand('echo "direct tty message" > /dev/tty');
78
+ expect(stdoutChunks.join('')).toContain('direct tty message');
79
+ });
80
+
81
+ it('is an in-memory overlay that is never persisted to raw fs or binary containers', async () => {
82
+ // getRaw() must not contain dev
83
+ expect(shell.context.fs.getRaw().dev).toBeUndefined();
84
+
85
+ // writing to /dev/null must not write anything to getRaw()
86
+ await run(shell, 'echo "test" > /dev/null');
87
+ expect(shell.context.fs.getRaw().dev).toBeUndefined();
88
+
89
+ // toBinaryContainer must not serialize /dev or device nodes
90
+ const container = shell.context.fs.toBinaryContainer();
91
+ const deserialized = FileSystem.fromBinaryContainer(container);
92
+ expect(deserialized.filesystem.dev).toBeUndefined();
93
+
94
+ // Booting a fresh filesystem from this container still has /dev mounted dynamically
95
+ const freshFs = new FileSystem('/', container);
96
+ expect(freshFs.exists('/dev/null')).toBe(true);
97
+ expect(freshFs.getRaw().dev).toBeUndefined();
98
+ });
99
+ });
100
+
101
+ describe('Signal emulation and Ctrl+C (SIGINT)', () => {
102
+ let shell;
103
+
104
+ beforeEach(async () => {
105
+ shell = await createShell();
106
+ });
107
+
108
+ it('supports kill(signal) on Command with standard exit codes', () => {
109
+ const cmd = new Command([], shell.context);
110
+ let signalReceived = null;
111
+ cmd.on('signal', sig => { signalReceived = sig; });
112
+
113
+ cmd.kill('SIGINT');
114
+ expect(cmd.result.getExitCode()).toBe(130);
115
+ expect(signalReceived).toBe('SIGINT');
116
+
117
+ cmd.kill('SIGTERM');
118
+ expect(cmd.result.getExitCode()).toBe(143);
119
+ expect(signalReceived).toBe('SIGTERM');
120
+ });
121
+
122
+ it('aborts running command on Ctrl+C (\\x03) with exit code 130', async () => {
123
+ class SlowCommand extends Command {
124
+ static get name() { return 'slowcmd'; }
125
+ run() {
126
+ return new Promise(resolve => {
127
+ this._timer = setTimeout(() => resolve('done'), 5000);
128
+ });
129
+ }
130
+ kill(sig) {
131
+ if (this._timer) clearTimeout(this._timer);
132
+ super.kill(sig);
133
+ }
134
+ }
135
+
136
+ shell.context.setCommand(SlowCommand);
137
+
138
+ const runPromise = shell.onCommand('slowcmd');
139
+ // Let command start running
140
+ await new Promise(r => setTimeout(r, 50));
141
+ expect(shell.runningCommand).toBeDefined();
142
+
143
+ // Send Ctrl+C
144
+ shell.write('\x03');
145
+ await runPromise;
146
+
147
+ expect(shell.lastCode).toBe(130);
148
+ });
149
+ });
150
+
151
+ describe('WASM requirements auto-discovery', () => {
152
+ it('detects asyncify from wasm exports without hardcoded names', () => {
153
+ const fakeWasmWithAsyncify = {
154
+ name: 'custom-app',
155
+ exports: ['_start', 'asyncify_start_unwind', 'asyncify_stop_unwind']
156
+ };
157
+ const hasAsyncify = fakeWasmWithAsyncify.exports.includes('asyncify_start_unwind') &&
158
+ fakeWasmWithAsyncify.exports.includes('asyncify_stop_unwind');
159
+ expect(hasAsyncify).toBe(true);
160
+ });
161
+
162
+ it('computes interactivity from pkgMeta or inspected wasm', () => {
163
+ const wasmCmd = new WasmCommand('some-random-game.wasm', [], {});
164
+ expect(wasmCmd.interactive).toBe(false);
165
+
166
+ wasmCmd._pkgMeta = { interactive: true };
167
+ expect(wasmCmd.interactive).toBe(true);
168
+
169
+ const wasmCmd2 = new WasmCommand('another-tool.wasm', [], {});
170
+ wasmCmd2._inspectedWasm = { isInteractive: true };
171
+ expect(wasmCmd2.interactive).toBe(true);
172
+ });
173
+ });
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { createShell } from './helpers.js';
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';
9
+ const DOOM_WAD_PATH = '/tmp/doom1.wad';
10
+ const hasDoom = fs.existsSync(DOOM_WASM_PATH) && fs.existsSync(DOOM_WAD_PATH);
11
+
12
+ describe('Doom in brsh', () => {
13
+ it.skipIf(!hasDoom)('executes doom timedemo benchmark cleanly to completion', async () => {
14
+ const doomWasm = fs.readFileSync(DOOM_WASM_PATH);
15
+ const doomWad = fs.readFileSync(DOOM_WAD_PATH);
16
+ const shell = await createShell({
17
+ filesystem: {
18
+ bin: { 'doom': doomWasm },
19
+ game: { 'doom1.wad': doomWad }
20
+ },
21
+ permissions: {
22
+ '/bin/doom': 0o755
23
+ },
24
+ cwd: '/game'
25
+ });
26
+
27
+ const lines = [];
28
+ shell.stdout.on('data', chunk => lines.push(chunk.toString()));
29
+
30
+ await shell.onCommand('doom -timedemo demo1 -nosound -nodraw');
31
+ expect(shell.lastCode).toBe(0);
32
+ const allOut = lines.join('');
33
+ expect(allOut).toContain('DOOM ASCII');
34
+ expect(allOut).toContain('timed 5026 gametics');
35
+ }, 30000);
36
+ });
Binary file
package/test/wbt.test.js CHANGED
@@ -1459,6 +1459,45 @@ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1459
1459
  expect(joinedOutput).toContain('\x1b[?1049h'); // entered alt screen
1460
1460
  expect(joinedOutput).toContain('\x1b[?1049l'); // exited alt screen
1461
1461
  });
1462
+
1463
+ it('runs nano interactively via stream write (as in Terminal emulator) and does not duplicate characters', async () => {
1464
+ if (!NANO_WASM_BYTES) return;
1465
+ await run(shell, 'wbt install nano');
1466
+
1467
+ const stdoutChunks = [];
1468
+ const onData = (chunk) => stdoutChunks.push(chunk);
1469
+ shell.stdout.on('data', onData);
1470
+
1471
+ const cmdPromise = shell.onCommand('nano /stream-test.txt');
1472
+
1473
+ // Allow nano to initialize, query terminal size, enter alt-screen, and render initial UI
1474
+ await new Promise(r => setTimeout(r, 60));
1475
+
1476
+ // Type text into nano via stream write (simulating terminal emulator input)
1477
+ for (const ch of 'Hello from stream!') {
1478
+ shell.write(ch);
1479
+ await new Promise(r => setTimeout(r, 5));
1480
+ }
1481
+ await new Promise(r => setTimeout(r, 30));
1482
+
1483
+ // Save file: Ctrl+O (\x0f), then Enter (\r) to confirm filename
1484
+ shell.write('\x0f');
1485
+ await new Promise(r => setTimeout(r, 30));
1486
+ shell.write('\r');
1487
+ await new Promise(r => setTimeout(r, 30));
1488
+
1489
+ // Exit nano: Ctrl+X (\x18)
1490
+ shell.write('\x18');
1491
+
1492
+ await cmdPromise;
1493
+ shell.stdout.off('data', onData);
1494
+
1495
+ const saved = shell.context.fs.getFileByPath('/stream-test.txt');
1496
+
1497
+ expect(shell.lastCode).toBe(0);
1498
+ expect(saved).toContain('Hello from stream!');
1499
+ expect(saved).not.toContain('HHeelllloo');
1500
+ });
1462
1501
  });
1463
1502
 
1464
1503