brsh 3.10.1 → 3.10.3

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
@@ -260,9 +260,25 @@ class Shell extends EventEmitter {
260
260
  }
261
261
 
262
262
  onInput(char) {
263
- if(this.runningCommand && this.runningCommand.onInput && this.runningCommand.captureInput) {
264
- this.runningCommand.onInput(char);
265
- return true;
263
+ if (this.runningCommand) {
264
+ const cmd = this.runningCommand;
265
+ if (char === '^C' || char === '\x03') {
266
+ const cmdIsRaw = Boolean(cmd.isRaw || (cmd.stdinStream && cmd.stdinStream.isRaw));
267
+ if (!cmdIsRaw) {
268
+ const wasAltOrInteractive = Boolean(cmd.interactive || cmd._inAltScreen);
269
+ if (typeof cmd.kill === 'function') {
270
+ cmd.kill('SIGINT');
271
+ }
272
+ if (!wasAltOrInteractive) {
273
+ this.stdout.write('^C\r\n');
274
+ }
275
+ return true;
276
+ }
277
+ }
278
+ if (cmd.onInput && cmd.captureInput) {
279
+ cmd.onInput(char);
280
+ return true;
281
+ }
266
282
  }
267
283
  }
268
284
 
@@ -1046,10 +1062,11 @@ class Shell extends EventEmitter {
1046
1062
 
1047
1063
  const cmdIsRaw = Boolean(cmd.isRaw || (cmd.stdinStream && cmd.stdinStream.isRaw));
1048
1064
  if (isCtrlC && !cmdIsRaw) {
1065
+ const wasAltOrInteractive = Boolean(cmd.interactive || cmd._inAltScreen);
1049
1066
  if (typeof cmd.kill === 'function') {
1050
1067
  cmd.kill('SIGINT');
1051
1068
  }
1052
- if (!cmd.interactive && !cmd._inAltScreen) {
1069
+ if (!wasAltOrInteractive) {
1053
1070
  this.stdout.write('^C\r\n');
1054
1071
  }
1055
1072
  return;
@@ -1406,15 +1423,49 @@ class Shell extends EventEmitter {
1406
1423
 
1407
1424
  async _parseCommandLine(string) {
1408
1425
  const parts = Shell._splitCommand(string);
1409
- const replaced = await Promise.all(
1410
- parts.map(({ value, hasQuote }) =>
1411
- this._replaceVariables(value).then(v => ({ value: v, hasQuote }))
1412
- )
1413
- );
1414
- // Keep tokens that are non-empty OR were explicitly quoted (preserves "" → '')
1415
- // Preserve hasQuote so redirect detection can skip quoted tokens.
1416
- return replaced
1417
- .filter(({ value, hasQuote }) => value.length > 0 || hasQuote);
1426
+ const firstToken = parts.length > 0 ? parts[0].value : '';
1427
+ const isDeclCmd = firstToken === 'export' || firstToken === 'alias' || firstToken === 'local';
1428
+
1429
+ const expandedParts = [];
1430
+ for (let i = 0; i < parts.length; i++) {
1431
+ const { value: rawValue, hasQuote } = parts[i];
1432
+
1433
+ // POSIX "$@" expansion: expands to "$1" "$2" ... as separate quoted words
1434
+ // (or zero words when $# is 0).
1435
+ if (hasQuote && rawValue === '$@') {
1436
+ const count = parseInt(this.context.getVar('#') || '0', 10) || 0;
1437
+ for (let idx = 1; idx <= count; idx++) {
1438
+ expandedParts.push({
1439
+ value: String(this.context.getVar(String(idx))),
1440
+ hasQuote: true
1441
+ });
1442
+ }
1443
+ continue;
1444
+ }
1445
+
1446
+ const expanded = await this._replaceVariables(rawValue);
1447
+
1448
+ // Variable / alias assignments (VAR=val, export VAR=val, alias foo=bar)
1449
+ // and explicitly quoted tokens do not undergo IFS field splitting.
1450
+ const isBareAssignment = parts.length === 1 && /^[A-Za-z_]\w*=/.test(rawValue);
1451
+ const isDeclAssignment = i > 0 && isDeclCmd && /^[A-Za-z_]\w*=/.test(rawValue);
1452
+
1453
+ if (hasQuote || isBareAssignment || isDeclAssignment || !rawValue.includes('$')) {
1454
+ if (expanded.length > 0 || hasQuote) {
1455
+ expandedParts.push({ value: expanded, hasQuote });
1456
+ }
1457
+ continue;
1458
+ }
1459
+
1460
+ // Unquoted parameter / command / arithmetic expansion: perform POSIX IFS word splitting.
1461
+ // Preserve leading redirect prefix if attached directly to an expansion (e.g. >$OUT).
1462
+ const fields = expanded.trim().split(/\s+/).filter(Boolean);
1463
+ for (const field of fields) {
1464
+ expandedParts.push({ value: field, hasQuote: false });
1465
+ }
1466
+ }
1467
+
1468
+ return expandedParts;
1418
1469
  }
1419
1470
 
1420
1471
  static _sanitiseCommandPart(string) {
package/lib/Command.js CHANGED
@@ -33,11 +33,12 @@ class Command extends EventEmitter {
33
33
  if (!this.captureInput) return;
34
34
  const keys = parseVtKeys(chunk);
35
35
  for (const k of keys) {
36
- if (k === '^C' && !(this.stdinStream && this.stdinStream.isRaw)) {
36
+ const isRaw = Boolean(this.isRaw || (this.stdinStream && this.stdinStream.isRaw));
37
+ if (k === '^C' && !isRaw) {
37
38
  this.kill('SIGINT');
38
39
  return;
39
40
  }
40
- if (!this.interactive && !this.stdinStream.isRaw) {
41
+ if (!this.interactive && !isRaw) {
41
42
  if (k === 'Enter') this.stdout.write('\r\n');
42
43
  else if (k === 'Backspace') this.stdout.write('\b \b');
43
44
  else if (k.length === 1) this.stdout.write(k);
@@ -39,13 +39,11 @@ class ScriptCommand extends LocalCommand {
39
39
  }
40
40
 
41
41
  get isRaw() {
42
- return Boolean(
43
- (this.stdinStream && this.stdinStream.isRaw)
44
- || (this.sandbox
45
- && this.sandbox.runningCommand
46
- && (this.sandbox.runningCommand.isRaw
47
- || (this.sandbox.runningCommand.stdinStream && this.sandbox.runningCommand.stdinStream.isRaw)))
48
- );
42
+ if (this.sandbox && this.sandbox.runningCommand) {
43
+ const child = this.sandbox.runningCommand;
44
+ return Boolean(child.isRaw || (child.stdinStream && child.stdinStream.isRaw));
45
+ }
46
+ return Boolean(this.stdinStream && this.stdinStream.isRaw);
49
47
  }
50
48
 
51
49
  get _inAltScreen() {
@@ -62,12 +60,17 @@ class ScriptCommand extends LocalCommand {
62
60
  }
63
61
 
64
62
  onInput(char) {
63
+ if ((char === '^C' || char === '\x03') && !this.isRaw) {
64
+ this.kill('SIGINT');
65
+ return;
66
+ }
65
67
  if (this.sandbox) {
66
68
  this.sandbox.onInput(char);
67
69
  }
68
70
  }
69
71
 
70
72
  kill(signal = 'SIGINT') {
73
+ this._killed = true;
71
74
  if (this.sandbox && this.sandbox.runningCommand && typeof this.sandbox.runningCommand.kill === 'function') {
72
75
  this.sandbox.runningCommand.kill(signal);
73
76
  }
@@ -120,6 +123,14 @@ class ScriptCommand extends LocalCommand {
120
123
  const onParentStdin = (chunk) => {
121
124
  if (!this.sandbox || !this.sandbox.runningCommand) return;
122
125
  const child = this.sandbox.runningCommand;
126
+ const childIsRaw = Boolean(child.isRaw || (child.stdinStream && child.stdinStream.isRaw));
127
+ const isCtrlC = (typeof chunk === 'string' && chunk === '\x03')
128
+ || (chunk instanceof Uint8Array && chunk.length === 1 && chunk[0] === 3)
129
+ || ((typeof Buffer !== 'undefined' && Buffer.isBuffer(chunk)) && chunk.length === 1 && chunk[0] === 3);
130
+ if (isCtrlC && !childIsRaw) {
131
+ this.kill('SIGINT');
132
+ return;
133
+ }
123
134
  const hasStreamListeners = hasCustomStdinListener(child);
124
135
  if (child.interactive || child._inAltScreen || hasStreamListeners) {
125
136
  if (child.stdinStream) {
@@ -128,7 +139,6 @@ class ScriptCommand extends LocalCommand {
128
139
  return;
129
140
  }
130
141
  if (child.captureInput && typeof child.onInput === 'function') {
131
- const childIsRaw = Boolean(child.isRaw || (child.stdinStream && child.stdinStream.isRaw));
132
142
  for (const k of parseVtKeys(chunk)) {
133
143
  if (k === '^C' && !childIsRaw) {
134
144
  this.kill('SIGINT');
@@ -477,11 +487,15 @@ class ScriptCommand extends LocalCommand {
477
487
 
478
488
  async _executeNodes(nodes) {
479
489
  for (const node of nodes) {
490
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) break;
480
491
  await this._executeNode(node);
481
492
  }
482
493
  }
483
494
 
484
495
  _executeNode(node) {
496
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) {
497
+ return Promise.resolve();
498
+ }
485
499
  if (node.type === 'function') {
486
500
  const funcName = node.name;
487
501
  const funcBody = node.bodyLines;
@@ -490,13 +504,25 @@ class ScriptCommand extends LocalCommand {
490
504
  const FuncCmd = class extends LocalCmdBase {
491
505
  static get name() { return funcName; }
492
506
  run() {
493
- // Set positional parameters ($1, $2, ...) from call arguments
494
- const saved = this.arguments.map((arg, i) => ({
495
- key: String(i + 1),
496
- prev: self.sandbox.context.getVar(String(i + 1))
497
- }));
498
- this.arguments.forEach((arg, i) =>
499
- self.sandbox.context.setVar(String(i + 1), arg));
507
+ // Set positional parameters ($1, $2, ..., $#, $@, $*) from call arguments
508
+ const prevCount = parseInt(self.sandbox.context.getVar('#') || '0', 10) || 0;
509
+ const maxCount = Math.max(prevCount, this.arguments.length);
510
+ const saved = [];
511
+ for (let i = 1; i <= maxCount; i++) {
512
+ const key = String(i);
513
+ saved.push({ key, prev: self.sandbox.context.getVar(key) });
514
+ if (i <= this.arguments.length) {
515
+ self.sandbox.context.setVar(key, this.arguments[i - 1]);
516
+ } else {
517
+ self.sandbox.context.unsetVar(key);
518
+ }
519
+ }
520
+ for (const key of ['#', '@', '*']) {
521
+ saved.push({ key, prev: self.sandbox.context.getVar(key) });
522
+ }
523
+ self.sandbox.context.setVar('#', String(this.arguments.length));
524
+ self.sandbox.context.setVar('@', this.arguments.join(' '));
525
+ self.sandbox.context.setVar('*', this.arguments.join(' '));
500
526
  const restore = () => saved.forEach(({ key, prev }) =>
501
527
  prev ? self.sandbox.context.setVar(key, prev)
502
528
  : self.sandbox.context.unsetVar(key));
@@ -556,19 +582,22 @@ class ScriptCommand extends LocalCommand {
556
582
 
557
583
  async _executeIf(node) {
558
584
  for (const clause of node.clauses) {
585
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) return;
559
586
  await this.sandbox.onCommand(clause.condition, false);
587
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) return;
560
588
  if (this.sandbox.lastCode === 0) {
561
589
  return this._executeNodes(this._parseLines(clause.bodyLines));
562
590
  }
563
591
  }
564
- if (node.elseLines.length > 0) {
592
+ if (node.elseLines.length > 0 && !this._killed && !(this.sandbox && this.sandbox.destroyed)) {
565
593
  return this._executeNodes(this._parseLines(node.elseLines));
566
594
  }
567
595
  }
568
596
 
569
597
  async _executeWhile(node) {
570
- while (true) {
598
+ while (!this._killed && !(this.sandbox && this.sandbox.destroyed)) {
571
599
  await this.sandbox.onCommand(node.condition, false);
600
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) break;
572
601
  if (this.sandbox.lastCode !== 0) break;
573
602
  try {
574
603
  await this._executeNodes(this._parseLines(node.bodyLines));
@@ -599,6 +628,7 @@ class ScriptCommand extends LocalCommand {
599
628
  items = expanded.split(/\s+/).filter(Boolean);
600
629
  }
601
630
  for (const value of items) {
631
+ if (this._killed || (this.sandbox && this.sandbox.destroyed)) break;
602
632
  this.sandbox.context.setVar(node.variable, value);
603
633
  try {
604
634
  await this._executeNodes(this._parseLines(node.bodyLines));
@@ -35,6 +35,9 @@ const FDFLAGS_NONBLOCK = 1 << 2;
35
35
  const FDFLAGS_RSYNC = 1 << 3;
36
36
  const FDFLAGS_SYNC = 1 << 4;
37
37
 
38
+ // POSIX termios c_lflag ISIG bit (0000001)
39
+ const TERMIOS_ISIG = 1;
40
+
38
41
  class WasmCommand extends ScriptCommand {
39
42
  // this.script = filepath (set by ScriptCommand parent constructor)
40
43
  constructor(script, args, context) {
@@ -74,6 +77,44 @@ class WasmCommand extends ScriptCommand {
74
77
  return this.interactive;
75
78
  }
76
79
 
80
+ get isRaw() {
81
+ if (typeof this._getTermiosLflag === 'function') {
82
+ try {
83
+ const raw = ((this._getTermiosLflag() >>> 0) & TERMIOS_ISIG) === 0;
84
+ if (this._inAltScreen && this.stdinStream && typeof this.stdinStream.setRawMode === 'function' && this.stdinStream.isRaw !== raw) {
85
+ this.stdinStream.setRawMode(raw);
86
+ }
87
+ return raw;
88
+ } catch (_) {}
89
+ }
90
+ const meta = this._ensurePkgMeta();
91
+ if (meta && (meta.raw !== undefined || meta.wasm?.raw !== undefined)) {
92
+ return Boolean(meta.raw ?? meta.wasm?.raw);
93
+ }
94
+ return Boolean(this.stdinStream && this.stdinStream.isRaw);
95
+ }
96
+
97
+ _syncRawMode() {
98
+ if (!this.stdinStream || typeof this.stdinStream.setRawMode !== 'function') return;
99
+ if (!this._inAltScreen && !this._isInteractive) {
100
+ if (this.stdinStream.isRaw) this.stdinStream.setRawMode(false);
101
+ return;
102
+ }
103
+ if (typeof this._getTermiosLflag === 'function') {
104
+ try {
105
+ const raw = ((this._getTermiosLflag() >>> 0) & TERMIOS_ISIG) === 0;
106
+ this.stdinStream.setRawMode(raw);
107
+ return;
108
+ } catch (_) {}
109
+ }
110
+ const meta = this._ensurePkgMeta();
111
+ if (meta && (meta.raw !== undefined || meta.wasm?.raw !== undefined)) {
112
+ this.stdinStream.setRawMode(Boolean(meta.raw ?? meta.wasm?.raw));
113
+ return;
114
+ }
115
+ this.stdinStream.setRawMode(false);
116
+ }
117
+
77
118
  kill(signal = 'SIGINT') {
78
119
  this._killed = true;
79
120
  this.exitCode = 130;
@@ -93,9 +134,7 @@ class WasmCommand extends ScriptCommand {
93
134
  _enterAltScreen() {
94
135
  if (this._inAltScreen) return;
95
136
  this._inAltScreen = true;
96
- if (this.stdinStream && typeof this.stdinStream.setRawMode === 'function') {
97
- this.stdinStream.setRawMode(true);
98
- }
137
+ this._syncRawMode();
99
138
  if (this.stdout && typeof this.stdout.write === 'function') {
100
139
  this.stdout.write('\x1b[?1049h\x1b[2J\x1b[H');
101
140
  }
@@ -343,9 +382,7 @@ class WasmCommand extends ScriptCommand {
343
382
  outBuf[2] = '';
344
383
  }
345
384
 
346
- if (this.stdinStream && typeof this.stdinStream.setRawMode === 'function') {
347
- this.stdinStream.setRawMode(true);
348
- }
385
+ this._syncRawMode();
349
386
  };
350
387
 
351
388
  const writeFd = (fd, text) => {
@@ -385,7 +422,12 @@ class WasmCommand extends ScriptCommand {
385
422
 
386
423
  const enqueueBytes = (b) => {
387
424
  if (!b || b.length === 0) return;
425
+ const raw = this.isRaw;
388
426
  for (let i = 0; i < b.length; i++) {
427
+ if (b[i] === 3 && !raw) {
428
+ this.kill('SIGINT');
429
+ return;
430
+ }
389
431
  inputQueue.push(b[i]);
390
432
  }
391
433
  if (pendingReadResolve) {
@@ -614,6 +656,7 @@ class WasmCommand extends ScriptCommand {
614
656
  if (isDevTty || fd === 2) {
615
657
  promoteToInteractive();
616
658
  }
659
+ this._syncRawMode();
617
660
  const flags = fdFlagsMap.get(fd) || 0;
618
661
  const isNonBlocking = Boolean(flags & FDFLAGS_NONBLOCK);
619
662
 
@@ -1168,7 +1211,17 @@ class WasmCommand extends ScriptCommand {
1168
1211
  }
1169
1212
 
1170
1213
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1171
- asyncifyPromise = new Promise(resolve => setTimeout(resolve, Math.max(1, sleepMs)));
1214
+ asyncifyPromise = new Promise((resolve, reject) => {
1215
+ const timer = setTimeout(() => {
1216
+ this._asyncifyReject = null;
1217
+ resolve();
1218
+ }, Math.max(1, sleepMs));
1219
+ this._asyncifyReject = (err) => {
1220
+ clearTimeout(timer);
1221
+ this._asyncifyReject = null;
1222
+ reject(err);
1223
+ };
1224
+ });
1172
1225
  return ERRNO_SUCCESS;
1173
1226
  }
1174
1227
  return ERRNO_SUCCESS;
@@ -1176,6 +1229,7 @@ class WasmCommand extends ScriptCommand {
1176
1229
  poll_oneoff: (in_ptr, out_ptr, nsubscriptions, nevents_ptr) => {
1177
1230
  if (!memRef) return ERRNO_BADF;
1178
1231
  const view = new DataView(memRef.buffer);
1232
+ this._syncRawMode();
1179
1233
 
1180
1234
  if (hasAsyncify) {
1181
1235
  const state = (typeof instance?.exports?.asyncify_get_state === 'function')
@@ -1298,7 +1352,14 @@ class WasmCommand extends ScriptCommand {
1298
1352
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1299
1353
  asyncifyPromise = new Promise((resolve, reject) => {
1300
1354
  let timer = null;
1301
- this._asyncifyReject = reject;
1355
+ this._asyncifyReject = (err) => {
1356
+ if (timer) clearTimeout(timer);
1357
+ pendingReadResolve = null;
1358
+ pendingResizeInterrupt = null;
1359
+ this._pendingReadResolve = null;
1360
+ this._asyncifyReject = null;
1361
+ reject(err);
1362
+ };
1302
1363
  const onKey = () => {
1303
1364
  if (timer) clearTimeout(timer);
1304
1365
  pollTimedOut = false;
@@ -1404,6 +1465,10 @@ class WasmCommand extends ScriptCommand {
1404
1465
  // Prefer the module's own exported memory
1405
1466
  if (instance.exports.memory) memRef = instance.exports.memory;
1406
1467
 
1468
+ this._getTermiosLflag = typeof instance.exports.get_termios_lflag === 'function'
1469
+ ? instance.exports.get_termios_lflag
1470
+ : null;
1471
+
1407
1472
  hasAsyncify = Boolean(instance.exports.asyncify_start_unwind && instance.exports.asyncify_stop_unwind);
1408
1473
  if (hasAsyncify && memRef) {
1409
1474
  try {
@@ -1423,6 +1488,7 @@ class WasmCommand extends ScriptCommand {
1423
1488
 
1424
1489
  if (isInteractive) {
1425
1490
  this._enterAltScreen();
1491
+ this._syncRawMode();
1426
1492
  }
1427
1493
 
1428
1494
  const cols = (this.stdout && this.stdout.columns)
@@ -1563,6 +1629,7 @@ class WasmCommand extends ScriptCommand {
1563
1629
  this.stdinStream.off('resize', onStdinResize);
1564
1630
  }
1565
1631
  this._externalKeyHandler = null;
1632
+ this._getTermiosLflag = null;
1566
1633
 
1567
1634
  // Flush any open dirty WASI file descriptors back to the brsh filesystem
1568
1635
  for (const entry of fdTable.values()) {
@@ -1907,10 +1974,10 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1907
1974
  }
1908
1975
 
1909
1976
  get isRaw() {
1910
- return Boolean(
1911
- (this.stdinStream && this.stdinStream.isRaw)
1912
- || (this._subCommand && (this._subCommand.isRaw || (this._subCommand.stdinStream && this._subCommand.stdinStream.isRaw)))
1913
- );
1977
+ if (this._subCommand) {
1978
+ return Boolean(this._subCommand.isRaw || (this._subCommand.stdinStream && this._subCommand.stdinStream.isRaw));
1979
+ }
1980
+ return Boolean(this.stdinStream && this.stdinStream.isRaw);
1914
1981
  }
1915
1982
 
1916
1983
  get _inAltScreen() {
package/lib/wbt/index.js CHANGED
@@ -130,10 +130,28 @@ class Wbt extends Command {
130
130
  }
131
131
 
132
132
  get isRaw() {
133
- return Boolean(
134
- (this.stdinStream && this.stdinStream.isRaw)
135
- || (this._activeSubCommand && (this._activeSubCommand.isRaw || (this._activeSubCommand.stdinStream && this._activeSubCommand.stdinStream.isRaw)))
136
- );
133
+ if (this._activeSubCommand) {
134
+ return Boolean(
135
+ this._activeSubCommand.isRaw
136
+ || (this._activeSubCommand.stdinStream && this._activeSubCommand.stdinStream.isRaw)
137
+ );
138
+ }
139
+ return Boolean(this.stdinStream && this.stdinStream.isRaw);
140
+ }
141
+
142
+ get _inAltScreen() {
143
+ return Boolean(this.__inAltScreen || (this._activeSubCommand && this._activeSubCommand._inAltScreen));
144
+ }
145
+
146
+ set _inAltScreen(val) {
147
+ this.__inAltScreen = Boolean(val);
148
+ }
149
+
150
+ kill(signal = 'SIGINT') {
151
+ if (this._activeSubCommand && typeof this._activeSubCommand.kill === 'function') {
152
+ this._activeSubCommand.kill(signal);
153
+ }
154
+ super.kill(signal);
137
155
  }
138
156
 
139
157
  onInput(key) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.10.1",
3
+ "version": "3.10.3",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",