brsh 3.5.0 → 3.6.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.
@@ -34,6 +34,93 @@ class WasmCommand extends ScriptCommand {
34
34
  get name() { return 'wasm'; }
35
35
  get requiresFilesystem() { return true; }
36
36
 
37
+ get interactive() {
38
+ const isHelpOrVersion = (this.arguments || []).some(a => a === '--help' || a === '-h' || a === '--version' || a === '-V' || a === '-v');
39
+ if (isHelpOrVersion) return false;
40
+ if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
41
+ if (this._pkgMeta && this._pkgMeta.interactive !== undefined) return Boolean(this._pkgMeta.interactive);
42
+ const name = (this.script || this.name || '').toLowerCase();
43
+ return name === 'nano' || name.endsWith('/nano') || name.endsWith('nano.wasm');
44
+ }
45
+
46
+ get captureInput() {
47
+ return this.interactive;
48
+ }
49
+
50
+ _enterAltScreen() {
51
+ if (this._inAltScreen) return;
52
+ this._inAltScreen = true;
53
+ if (this.stdinStream && typeof this.stdinStream.setRawMode === 'function') {
54
+ this.stdinStream.setRawMode(true);
55
+ }
56
+ if (this.stdout && typeof this.stdout.write === 'function') {
57
+ this.stdout.write('\x1b[?1049h\x1b[2J\x1b[H');
58
+ }
59
+ }
60
+
61
+ _exitAltScreen() {
62
+ if (!this._inAltScreen) return;
63
+ this._inAltScreen = false;
64
+ if (this.stdinStream && typeof this.stdinStream.setRawMode === 'function') {
65
+ this.stdinStream.setRawMode(false);
66
+ }
67
+ if (this.stdout && typeof this.stdout.write === 'function') {
68
+ this.stdout.write('\x1b[?1049l\x1b[?25h');
69
+ }
70
+ }
71
+
72
+ _keyToBytes(key) {
73
+ if (!key) return null;
74
+ if (typeof key !== 'string') {
75
+ if (key instanceof Uint8Array) return key;
76
+ return new Uint8Array([Number(key) & 0xff]);
77
+ }
78
+ const ctrlMatch = key.match(/^\^([A-Za-z@\[\\\]^_?])$/);
79
+ if (ctrlMatch) {
80
+ const ch = ctrlMatch[1].toUpperCase();
81
+ if (ch === '?') return new Uint8Array([0x7f]);
82
+ return new Uint8Array([ch.charCodeAt(0) - 64]);
83
+ }
84
+ const map = {
85
+ 'Enter': '\r',
86
+ 'Return': '\r',
87
+ 'Backspace': '\x7f',
88
+ 'Tab': '\t',
89
+ 'Escape': '\x1b',
90
+ 'ArrowUp': '\x1b[A',
91
+ 'ArrowDown': '\x1b[B',
92
+ 'ArrowRight': '\x1b[C',
93
+ 'ArrowLeft': '\x1b[D',
94
+ 'Home': '\x1b[H',
95
+ 'End': '\x1b[F',
96
+ 'PageUp': '\x1b[5~',
97
+ 'PageDown': '\x1b[6~',
98
+ 'Delete': '\x1b[3~',
99
+ 'Insert': '\x1b[2~',
100
+ };
101
+ if (map[key]) return new TextEncoder().encode(map[key]);
102
+ return new TextEncoder().encode(key);
103
+ }
104
+
105
+ onInput(key) {
106
+ if (this._handlingStreamData) return;
107
+ if (typeof this._externalKeyHandler === 'function') {
108
+ this._externalKeyHandler(key);
109
+ return;
110
+ }
111
+ if (this.stdinStream && this.stdinStream.isRaw) {
112
+ return;
113
+ }
114
+ }
115
+
116
+ runCommand() {
117
+ return super.runCommand().finally(() => {
118
+ if (this._inAltScreen) {
119
+ this._exitAltScreen();
120
+ }
121
+ });
122
+ }
123
+
37
124
  run() {
38
125
  const filepath = this.script;
39
126
  const nodeFs = (() => { try { return require('fs'); } catch { return null; } })();
@@ -121,8 +208,30 @@ class WasmCommand extends ScriptCommand {
121
208
  const decoder = new TextDecoder();
122
209
  const encoder = new TextEncoder();
123
210
  let memRef = null;
211
+ let instance = null;
212
+ let hasAsyncify = false;
213
+ let asyncifyDataAddr = 0;
214
+ let asyncifyPromise = null;
215
+ let pendingReadResolve = null;
216
+ let onResize = null;
217
+ let onStreamData = null;
218
+
219
+ const isInteractive = Boolean(
220
+ this.interactive &&
221
+ (this.stdin === undefined || this.stdin === null || this.stdin === this.stdinStream)
222
+ );
124
223
 
125
224
  const writeFd = (fd, text) => {
225
+ if (isInteractive && (fd === 1 || fd === 2)) {
226
+ if (fd === 1 && this.stdout) {
227
+ this.stdout.write(text);
228
+ return;
229
+ }
230
+ if (fd === 2 && this.stderr) {
231
+ this.stderr.write(text);
232
+ return;
233
+ }
234
+ }
126
235
  outBuf[fd] = (outBuf[fd] || '') + text;
127
236
  const lines = outBuf[fd].split('\n');
128
237
  outBuf[fd] = lines.pop();
@@ -133,15 +242,63 @@ class WasmCommand extends ScriptCommand {
133
242
  };
134
243
 
135
244
  const flushFd = () => {
136
- if (outBuf[1]) { this.stdOut = outBuf[1]; outBuf[1] = ''; }
137
- if (outBuf[2]) { this.stdErr = outBuf[2]; outBuf[2] = ''; }
245
+ if (outBuf[1]) {
246
+ if (isInteractive && this.stdout) this.stdout.write(outBuf[1]);
247
+ else this.stdOut = outBuf[1];
248
+ outBuf[1] = '';
249
+ }
250
+ if (outBuf[2]) {
251
+ if (isInteractive && this.stderr) this.stderr.write(outBuf[2]);
252
+ else this.stdErr = outBuf[2];
253
+ outBuf[2] = '';
254
+ }
255
+ };
256
+
257
+ const inputQueue = [];
258
+
259
+ const enqueueBytes = (b) => {
260
+ if (!b || b.length === 0) return;
261
+ for (let i = 0; i < b.length; i++) {
262
+ inputQueue.push(b[i]);
263
+ }
264
+ if (pendingReadResolve) {
265
+ const r = pendingReadResolve;
266
+ pendingReadResolve = null;
267
+ r();
268
+ }
269
+ };
270
+
271
+ onStreamData = (chunk) => {
272
+ this._handlingStreamData = true;
273
+ try {
274
+ const b = typeof chunk === 'string'
275
+ ? encoder.encode(chunk)
276
+ : (chunk instanceof Uint8Array
277
+ ? chunk
278
+ : (typeof Buffer !== 'undefined' && Buffer.isBuffer(chunk)
279
+ ? new Uint8Array(chunk)
280
+ : encoder.encode(String(chunk ?? ''))));
281
+ enqueueBytes(b);
282
+ } finally {
283
+ this._handlingStreamData = false;
284
+ }
285
+ };
286
+
287
+ this._externalKeyHandler = (key) => {
288
+ if (this._handlingStreamData) return;
289
+ const b = this._keyToBytes(key);
290
+ if (b) enqueueBytes(b);
138
291
  };
139
292
 
140
- const stdinBytes = typeof this.stdin === 'string'
293
+ if (isInteractive && this.stdinStream && typeof this.stdinStream.on === 'function') {
294
+ this.stdinStream.on('data', onStreamData);
295
+ }
296
+
297
+ const stdinBytes = (!isInteractive && typeof this.stdin === 'string')
141
298
  ? encoder.encode(this.stdin)
142
- : (this.stdin instanceof Uint8Array
299
+ : (!isInteractive && this.stdin instanceof Uint8Array
143
300
  ? this.stdin
144
- : (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.stdin) ? new Uint8Array(this.stdin) : new Uint8Array(0)));
301
+ : (!isInteractive && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.stdin) ? new Uint8Array(this.stdin) : new Uint8Array(0)));
145
302
  let stdinPos = 0;
146
303
 
147
304
  // ── Virtual WASI file descriptor table backed by this.context.fs ──
@@ -159,6 +316,7 @@ class WasmCommand extends ScriptCommand {
159
316
  const dirEntry = fdTable.get(dirFd);
160
317
  if (!dirEntry || (dirEntry.type !== 'preopen' && dirEntry.type !== 'dir')) return null;
161
318
  if (relPath.startsWith('/')) return fs.absolutePath(relPath);
319
+ if (!relPath || relPath === '.') return fs.absolutePath(dirEntry.path);
162
320
  const base = dirEntry.path.endsWith('/') ? dirEntry.path : dirEntry.path + '/';
163
321
  return fs.absolutePath(base + relPath);
164
322
  };
@@ -185,9 +343,15 @@ class WasmCommand extends ScriptCommand {
185
343
  }
186
344
  };
187
345
 
188
- // Environment variables from context.vars
189
- const envPairs = Object.entries((this.context && this.context.vars) || {})
190
- .map(([k, v]) => `${k}=${v}`);
346
+ // Environment variables from context.vars with terminal defaults
347
+ const termVars = {
348
+ TERM: 'xterm-256color',
349
+ COLORTERM: 'truecolor',
350
+ COLUMNS: String((this.stdout && this.stdout.columns) || (this.context && typeof this.context.getVar === 'function' && this.context.getVar('COLUMNS')) || 80),
351
+ LINES: String((this.stdout && this.stdout.rows) || (this.context && typeof this.context.getVar === 'function' && this.context.getVar('LINES')) || 24),
352
+ ...((this.context && this.context.vars) || {})
353
+ };
354
+ const envPairs = Object.entries(termVars).map(([k, v]) => `${k}=${v}`);
191
355
 
192
356
  const wasi = {
193
357
  fd_write: (fd, iovs, iovs_len, nwritten_ptr) => {
@@ -236,6 +400,48 @@ class WasmCommand extends ScriptCommand {
236
400
  const view = new DataView(memRef.buffer);
237
401
 
238
402
  if (fd === 0) {
403
+ if (isInteractive && hasAsyncify) {
404
+ const state = (typeof instance?.exports?.asyncify_get_state === 'function')
405
+ ? instance.exports.asyncify_get_state()
406
+ : 0;
407
+
408
+ if (state === 2) {
409
+ instance.exports.asyncify_stop_rewind();
410
+ let total = 0;
411
+ for (let i = 0; i < iovs_len && inputQueue.length > 0; i++) {
412
+ const ptr = view.getUint32(iovs + i * 8, true);
413
+ const len = view.getUint32(iovs + i * 8 + 4, true);
414
+ const chunk = Math.min(len, inputQueue.length);
415
+ const slice = inputQueue.splice(0, chunk);
416
+ new Uint8Array(memRef.buffer).set(slice, ptr);
417
+ total += chunk;
418
+ }
419
+ view.setUint32(nread_ptr, total, true);
420
+ return ERRNO_SUCCESS;
421
+ }
422
+
423
+ if (inputQueue.length > 0) {
424
+ let total = 0;
425
+ for (let i = 0; i < iovs_len && inputQueue.length > 0; i++) {
426
+ const ptr = view.getUint32(iovs + i * 8, true);
427
+ const len = view.getUint32(iovs + i * 8 + 4, true);
428
+ const chunk = Math.min(len, inputQueue.length);
429
+ const slice = inputQueue.splice(0, chunk);
430
+ new Uint8Array(memRef.buffer).set(slice, ptr);
431
+ total += chunk;
432
+ }
433
+ view.setUint32(nread_ptr, total, true);
434
+ return ERRNO_SUCCESS;
435
+ }
436
+
437
+ instance.exports.asyncify_start_unwind(asyncifyDataAddr);
438
+ asyncifyPromise = new Promise(resolve => {
439
+ pendingReadResolve = resolve;
440
+ });
441
+ view.setUint32(nread_ptr, 0, true);
442
+ return ERRNO_SUCCESS;
443
+ }
444
+
239
445
  let total = 0;
240
446
  for (let i = 0; i < iovs_len && stdinPos < stdinBytes.length; i++) {
241
447
  const ptr = view.getUint32(iovs + i * 8, true);
@@ -481,6 +687,31 @@ class WasmCommand extends ScriptCommand {
481
687
  return ERRNO_INVAL;
482
688
  }
483
689
  },
690
+ path_rename: (old_dirfd, old_path_ptr, old_path_len, new_dirfd, new_path_ptr, new_path_len) => {
691
+ if (!memRef || !fs) return ERRNO_BADF;
692
+ const oldRel = decoder.decode(new Uint8Array(memRef.buffer, old_path_ptr, old_path_len));
693
+ const newRel = decoder.decode(new Uint8Array(memRef.buffer, new_path_ptr, new_path_len));
694
+ const oldAbs = resolveGuestPath(old_dirfd, oldRel);
695
+ const newAbs = resolveGuestPath(new_dirfd, newRel);
696
+ if (!oldAbs || !newAbs) return ERRNO_BADF;
697
+ if (!fs.exists(oldAbs)) return ERRNO_NOENT;
698
+
699
+ for (const entry of fdTable.values()) {
700
+ if (entry.path === oldAbs) {
701
+ flushOpenFile(entry);
702
+ entry.path = newAbs;
703
+ }
704
+ }
705
+
706
+ try {
707
+ const content = fs.getFileByPath(oldAbs);
708
+ fs.setFileByPath(newAbs, content, true);
709
+ fs.deleteFileByPath(oldAbs);
710
+ return ERRNO_SUCCESS;
711
+ } catch {
712
+ return ERRNO_INVAL;
713
+ }
714
+ },
484
715
  proc_exit: (code) => {
485
716
  if (code !== 0) this.exitCode = code;
486
717
  throw { _wasmExit: true, code };
@@ -597,11 +828,47 @@ class WasmCommand extends ScriptCommand {
597
828
  }
598
829
  }
599
830
 
600
- const instance = await WebAssembly.instantiate(module, imports);
831
+ instance = await WebAssembly.instantiate(module, imports);
601
832
 
602
833
  // Prefer the module's own exported memory
603
834
  if (instance.exports.memory) memRef = instance.exports.memory;
604
835
 
836
+ hasAsyncify = Boolean(instance.exports.asyncify_start_unwind && instance.exports.asyncify_stop_unwind);
837
+ if (hasAsyncify && memRef) {
838
+ try {
839
+ const prevPages = memRef.grow(1);
840
+ asyncifyDataAddr = prevPages * 65536;
841
+ } catch {
842
+ asyncifyDataAddr = 16;
843
+ }
844
+ const dataStart = asyncifyDataAddr + 8;
845
+ const dataEnd = asyncifyDataAddr + 65536 - 8;
846
+ new Int32Array(memRef.buffer, asyncifyDataAddr, 2).set([dataStart, dataEnd]);
847
+ }
848
+
849
+ if (isInteractive) {
850
+ this._enterAltScreen();
851
+ const cols = (this.stdout && this.stdout.columns) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10)) || 80;
852
+ const rows = (this.stdout && this.stdout.rows) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10)) || 24;
853
+ if (typeof instance.exports.set_terminal_size === 'function') {
854
+ try { instance.exports.set_terminal_size(cols, rows); } catch {}
855
+ }
856
+
857
+ onResize = () => {
858
+ const c = (this.stdout && this.stdout.columns) || 80;
859
+ const r = (this.stdout && this.stdout.rows) || 24;
860
+ if (typeof instance?.exports?.set_terminal_size === 'function') {
861
+ try { instance.exports.set_terminal_size(c, r); } catch {}
862
+ }
863
+ };
864
+ if (this.stdout && typeof this.stdout.on === 'function') {
865
+ this.stdout.on('resize', onResize);
866
+ }
867
+ if (this.stdinStream && typeof this.stdinStream.on === 'function') {
868
+ this.stdinStream.on('resize', onResize);
869
+ }
870
+ }
871
+
605
872
  const start = instance.exports._start
606
873
  || instance.exports.__wasi_command
607
874
  || instance.exports.main
@@ -618,7 +885,19 @@ class WasmCommand extends ScriptCommand {
618
885
  this.exitCode = 1;
619
886
  } else {
620
887
  try {
621
- await start();
888
+ let res = start();
889
+ if (res && typeof res.then === 'function') res = await res;
890
+
891
+ while (hasAsyncify && typeof instance.exports.asyncify_get_state === 'function' && instance.exports.asyncify_get_state() === 1) {
892
+ instance.exports.asyncify_stop_unwind();
893
+ if (asyncifyPromise) {
894
+ await asyncifyPromise;
895
+ asyncifyPromise = null;
896
+ }
897
+ instance.exports.asyncify_start_rewind(asyncifyDataAddr);
898
+ res = start();
899
+ if (res && typeof res.then === 'function') res = await res;
900
+ }
622
901
  } catch(e) {
623
902
  if (!e || !e._wasmExit) {
624
903
  this.stdErr = `${this.script}: runtime error: ${e?.message || String(e)}`;
@@ -632,6 +911,18 @@ class WasmCommand extends ScriptCommand {
632
911
  this.exitCode = 1;
633
912
  }
634
913
  } finally {
914
+ if (isInteractive) {
915
+ this._exitAltScreen();
916
+ }
917
+ if (isInteractive && onStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
918
+ this.stdinStream.off('data', onStreamData);
919
+ }
920
+ if (onResize) {
921
+ if (this.stdout && typeof this.stdout.off === 'function') this.stdout.off('resize', onResize);
922
+ if (this.stdinStream && typeof this.stdinStream.off === 'function') this.stdinStream.off('resize', onResize);
923
+ }
924
+ this._externalKeyHandler = null;
925
+
635
926
  // Flush any open dirty WASI file descriptors back to the brsh filesystem
636
927
  for (const entry of fdTable.values()) {
637
928
  flushOpenFile(entry);
package/lib/wbt/index.js CHANGED
@@ -19,6 +19,17 @@ function createCustomWasmBinCommand(binName, wasmPath, pkgMeta = {}) {
19
19
  get name() { return binName; }
20
20
  get requiresFilesystem() { return true; }
21
21
 
22
+ get interactive() {
23
+ const isHelpOrVersion = (this.arguments || []).some(a => a === '--help' || a === '-h' || a === '--version' || a === '-V' || a === '-v');
24
+ if (isHelpOrVersion) return false;
25
+ if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
26
+ return Boolean(pkgMeta.interactive || binName === 'nano');
27
+ }
28
+
29
+ get captureInput() {
30
+ return this.interactive;
31
+ }
32
+
22
33
  constructor(args, context) {
23
34
  super(wasmPath, args, context);
24
35
  this.script = wasmPath;
@@ -178,7 +178,8 @@ const DEFAULT_REGISTRY = {
178
178
  cdnUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm',
179
179
  wasmUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm',
180
180
  type: 'custom-wasm',
181
- size: '574 KB'
181
+ interactive: true,
182
+ size: '680 KB'
182
183
  }
183
184
  };
184
185
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.5.0",
3
+ "version": "3.6.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",
Binary file
package/test/wbt.test.js CHANGED
@@ -8,9 +8,13 @@ const fs = require('fs');
8
8
  const Wbt = require('../lib/wbt/index.js');
9
9
  const { wllamaInstances, DEFAULT_MODEL_URL, MODEL_ALIASES, resolveModelSpec } = require('../lib/wbt/packages/wllama.js');
10
10
 
11
+ const FIXTURE_NANO_WASM = path.resolve(import.meta.dirname, 'fixtures/nano.wasm');
11
12
  const NANO_WASM_PATH = path.resolve(import.meta.dirname, '../../nano-wasm/dist/nano.wasm');
12
13
  const NANO_WASM_BYTES = (() => {
13
14
  try {
15
+ if (fs.existsSync(FIXTURE_NANO_WASM)) {
16
+ return new Uint8Array(fs.readFileSync(FIXTURE_NANO_WASM));
17
+ }
14
18
  if (fs.existsSync(NANO_WASM_PATH)) {
15
19
  return new Uint8Array(fs.readFileSync(NANO_WASM_PATH));
16
20
  }
@@ -1415,6 +1419,46 @@ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1415
1419
  expect(res.getExitCode()).toBe(0);
1416
1420
  expect(res.getStdOutput().map(l => l.string).join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.0.*wasm/i);
1417
1421
  });
1422
+
1423
+ it('runs nano interactively, accepts text input, writes out file, and exits cleanly', async () => {
1424
+ if (!NANO_WASM_BYTES) return;
1425
+ await run(shell, 'wbt install nano');
1426
+
1427
+ const stdoutChunks = [];
1428
+ const onData = (chunk) => stdoutChunks.push(chunk);
1429
+ shell.stdout.on('data', onData);
1430
+
1431
+ const cmdPromise = shell.onCommand('nano /test.txt');
1432
+
1433
+ // Allow nano to initialize, query terminal size, enter alt-screen, and render initial UI
1434
+ await new Promise(r => setTimeout(r, 60));
1435
+
1436
+ // Type text into nano
1437
+ for (const ch of 'Hello from nano!') {
1438
+ shell.onInput(ch);
1439
+ }
1440
+ await new Promise(r => setTimeout(r, 30));
1441
+
1442
+ // Save file: Ctrl+O, then Enter to confirm filename
1443
+ shell.onInput('^O');
1444
+ await new Promise(r => setTimeout(r, 30));
1445
+ shell.onInput('Enter');
1446
+ await new Promise(r => setTimeout(r, 30));
1447
+
1448
+ // Exit nano: Ctrl+X
1449
+ shell.onInput('^X');
1450
+
1451
+ await cmdPromise;
1452
+ shell.stdout.off('data', onData);
1453
+
1454
+ const saved = shell.context.fs.getFileByPath('/test.txt');
1455
+ const joinedOutput = stdoutChunks.join('');
1456
+
1457
+ expect(shell.lastCode).toBe(0);
1458
+ expect(saved).toContain('Hello from nano!');
1459
+ expect(joinedOutput).toContain('\x1b[?1049h'); // entered alt screen
1460
+ expect(joinedOutput).toContain('\x1b[?1049l'); // exited alt screen
1461
+ });
1418
1462
  });
1419
1463
 
1420
1464