brsh 3.1.4 → 3.3.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.
package/index.js CHANGED
@@ -460,54 +460,192 @@ class Shell extends EventEmitter {
460
460
  }
461
461
 
462
462
  if (!args.length) return;
463
- let bin = args.shift().value;
464
463
 
465
- // Bare variable assignment: VAR=value (only when no additional args)
466
- if (args.length === 0 && /^[A-Za-z_]\w*=/.test(bin)) {
467
- const eqIdx = bin.indexOf('=');
468
- this.context.setVar(bin.slice(0, eqIdx), bin.slice(eqIdx + 1));
469
- this.lastCode = 0;
470
- this.emit('exitCode', 0);
464
+ // Parse negation operator (!)
465
+ let negate = false;
466
+ while (args.length > 0 && !args[0].hasQuote && args[0].value === '!') {
467
+ negate = !negate;
468
+ args.shift();
469
+ }
470
+
471
+ if (!args.length) {
472
+ this.lastCode = negate ? 1 : 0;
473
+ this.emit('exitCode', this.lastCode);
471
474
  return;
472
475
  }
473
476
 
474
- // Parse output redirection (> and >>)
477
+ // Parse file descriptor & stream redirections (> and >>, 1>, 2>, 2>&1, &>, etc.)
475
478
  // Quoted tokens (hasQuote: true) are never treated as redirects.
476
- let redirectPath = null;
477
- let appendMode = false;
478
- const filteredArgs = [];
479
+ let stdoutDest = { type: 'stdout' };
480
+ let stderrDest = { type: 'stderr' };
481
+ const positionalArgs = [];
482
+
479
483
  for (let i = 0; i < args.length; i++) {
480
484
  const { value: arg, hasQuote } = args[i];
481
- if (!hasQuote && (arg === '>>' || arg === '>') && i + 1 < args.length) {
482
- appendMode = arg === '>>';
483
- redirectPath = args[++i].value;
484
- } else if (!hasQuote && arg.startsWith('>>') && arg.length > 2) {
485
- appendMode = true;
486
- redirectPath = arg.slice(2);
487
- } else if (!hasQuote && arg.startsWith('>') && arg.length > 1) {
488
- appendMode = false;
489
- redirectPath = arg.slice(1);
490
- } else {
491
- filteredArgs.push(arg);
485
+ if (hasQuote) {
486
+ positionalArgs.push(arg);
487
+ continue;
488
+ }
489
+
490
+ // fd duplication / close
491
+ if (arg === '2>&1') {
492
+ stderrDest = { ...stdoutDest };
493
+ continue;
494
+ }
495
+ if (arg === '1>&2') {
496
+ stdoutDest = { ...stderrDest };
497
+ continue;
498
+ }
499
+ if (arg === '2>&-') {
500
+ stderrDest = { type: 'null' };
501
+ continue;
502
+ }
503
+ if (arg === '1>&-' || arg === '>&-') {
504
+ stdoutDest = { type: 'null' };
505
+ continue;
506
+ }
507
+
508
+ // Both stdout & stderr redirect: &>, &>>, >&
509
+ if (arg === '&>>') {
510
+ if (i + 1 < args.length) {
511
+ const target = args[++i].value;
512
+ const dest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
513
+ stdoutDest = dest;
514
+ stderrDest = dest;
515
+ }
516
+ continue;
517
+ }
518
+ if (arg === '&>' || arg === '>&') {
519
+ if (i + 1 < args.length) {
520
+ const target = args[++i].value;
521
+ const dest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
522
+ stdoutDest = dest;
523
+ stderrDest = dest;
524
+ }
525
+ continue;
526
+ }
527
+ if (arg.startsWith('&>>') && arg.length > 3) {
528
+ const target = arg.slice(3);
529
+ const dest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
530
+ stdoutDest = dest;
531
+ stderrDest = dest;
532
+ continue;
533
+ }
534
+ if ((arg.startsWith('&>') || arg.startsWith('>&')) && arg.length > 2) {
535
+ const target = arg.slice(2);
536
+ const dest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
537
+ stdoutDest = dest;
538
+ stderrDest = dest;
539
+ continue;
540
+ }
541
+
542
+ // Stderr redirect: 2>, 2>>
543
+ if (arg === '2>>') {
544
+ if (i + 1 < args.length) {
545
+ const target = args[++i].value;
546
+ stderrDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
547
+ }
548
+ continue;
549
+ }
550
+ if (arg === '2>') {
551
+ if (i + 1 < args.length) {
552
+ const target = args[++i].value;
553
+ stderrDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
554
+ }
555
+ continue;
556
+ }
557
+ if (arg.startsWith('2>>') && arg.length > 3) {
558
+ const target = arg.slice(3);
559
+ stderrDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
560
+ continue;
561
+ }
562
+ if (arg.startsWith('2>') && arg.length > 2) {
563
+ const target = arg.slice(2);
564
+ stderrDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
565
+ continue;
566
+ }
567
+
568
+ // Stdout redirect: 1>, 1>>, >, >>
569
+ if (arg === '1>>' || arg === '>>') {
570
+ if (i + 1 < args.length) {
571
+ const target = args[++i].value;
572
+ stdoutDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
573
+ }
574
+ continue;
575
+ }
576
+ if (arg === '1>' || arg === '>') {
577
+ if (i + 1 < args.length) {
578
+ const target = args[++i].value;
579
+ stdoutDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
580
+ }
581
+ continue;
582
+ }
583
+ if ((arg.startsWith('1>>') || arg.startsWith('>>')) && arg.length > (arg.startsWith('1>>') ? 3 : 2)) {
584
+ const target = arg.slice(arg.startsWith('1>>') ? 3 : 2);
585
+ stdoutDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: true };
586
+ continue;
587
+ }
588
+ if ((arg.startsWith('1>') || arg.startsWith('>')) && arg.length > (arg.startsWith('1>') ? 2 : 1)) {
589
+ const target = arg.slice(arg.startsWith('1>') ? 2 : 1);
590
+ stdoutDest = target === '/dev/null' ? { type: 'null' } : { type: 'file', file: target, append: false };
591
+ continue;
592
+ }
593
+
594
+ positionalArgs.push(arg);
595
+ }
596
+
597
+ if (!positionalArgs.length) {
598
+ for (const dest of [stdoutDest, stderrDest]) {
599
+ if (dest.type === 'file' && dest.file !== '/dev/null') {
600
+ try {
601
+ const abs = this.context.fs.absolutePath(dest.file);
602
+ const existing = this.context.fs._getFileRaw(abs);
603
+ if (!dest.append || existing === undefined) {
604
+ this.context.fs.setFileByPath(abs, existing || '', true);
605
+ }
606
+ } catch (e) {
607
+ this.emit('stdErr', `${dest.file}: Permission denied`);
608
+ this.lastCode = negate ? 0 : 1;
609
+ this.emit('exitCode', this.lastCode);
610
+ return;
611
+ }
612
+ }
492
613
  }
614
+ this.lastCode = negate ? 1 : 0;
615
+ this.emit('exitCode', this.lastCode);
616
+ return;
617
+ }
618
+
619
+ let bin = positionalArgs.shift();
620
+ args = positionalArgs;
621
+
622
+ // Bare variable assignment: VAR=value (only when no additional args)
623
+ if (args.length === 0 && /^[A-Za-z_]\w*=/.test(bin)) {
624
+ const eqIdx = bin.indexOf('=');
625
+ this.context.setVar(bin.slice(0, eqIdx), bin.slice(eqIdx + 1));
626
+ this.lastCode = negate ? 1 : 0;
627
+ this.emit('exitCode', this.lastCode);
628
+ return;
493
629
  }
494
- args = filteredArgs;
495
630
 
496
- //short circuit for aliases
631
+ // Short circuit for aliases
497
632
  const alias = this.context.getAlias(bin);
498
633
  if(alias) {
499
- return this.onCommand(alias, false);
634
+ return this.onCommand(alias, false).then(() => {
635
+ if (negate) {
636
+ this.lastCode = this.lastCode === 0 ? 1 : 0;
637
+ this.emit('exitCode', this.lastCode);
638
+ }
639
+ });
500
640
  }
501
641
 
502
642
  let Cmd;
503
643
  try {
504
644
  Cmd = this._parseCommand(
505
- (bin.startsWith('/') || bin.startsWith('./')) ? bin : bin.toLowerCase()
506
- );
645
+ (bin.startsWith('/') || bin.startsWith('./')) ? bin : bin.toLowerCase()
646
+ );
507
647
  } catch(e) {
508
- this.emit('stdErr', e.message);
509
- this.lastCode = 1;
510
- this.emit('exitCode', this.lastCode);
648
+ this._handleCommandError(e.message, stderrDest, negate);
511
649
  return;
512
650
  }
513
651
 
@@ -518,9 +656,7 @@ class Shell extends EventEmitter {
518
656
  } else if(isCommandClass(Cmd)) {
519
657
  instance = new Cmd(args, this._readonlyContext);
520
658
  } else {
521
- this.emit('stdErr', `${bin}: Command not found`);
522
- this.lastCode = 1;
523
- this.emit('exitCode', this.lastCode);
659
+ this._handleCommandError(`${bin}: Command not found`, stderrDest, negate);
524
660
  return;
525
661
  }
526
662
 
@@ -532,21 +668,64 @@ class Shell extends EventEmitter {
532
668
  instance.stdin = this._stdin;
533
669
  }
534
670
 
671
+ const fileOutputs = new Map();
672
+ const routeLine = ({ type, string }) => {
673
+ const dest = type === 'out' ? stdoutDest : stderrDest;
674
+ if (dest.type === 'stdout') {
675
+ this.emit('stdOut', string);
676
+ } else if (dest.type === 'stderr') {
677
+ this.emit('stdErr', string);
678
+ } else if (dest.type === 'file') {
679
+ if (dest.file !== '/dev/null') {
680
+ let entry = fileOutputs.get(dest.file);
681
+ if (!entry) {
682
+ entry = { append: dest.append, lines: [] };
683
+ fileOutputs.set(dest.file, entry);
684
+ }
685
+ entry.lines.push(string);
686
+ }
687
+ }
688
+ };
689
+
535
690
  this.runningCommand = instance;
536
691
  if(this.runningCommand.on) {
537
692
  this.runningCommand.on('flush', lines => {
538
- this._emitOutput(lines);
693
+ lines.forEach(routeLine);
539
694
  });
540
695
  this.runningCommand.on('stdout', chunk => {
541
- if (redirectPath) {
542
- instance.stdOut = String(chunk ?? '');
696
+ if (stdoutDest.type === 'file') {
697
+ if (!instance._streamedStdout) {
698
+ instance.stdOut = String(chunk ?? '');
699
+ }
700
+ } else if (stdoutDest.type === 'stderr') {
701
+ this.stderr.write(chunk);
702
+ } else if (stdoutDest.type === 'null') {
703
+ // discard
543
704
  } else {
544
705
  this.stdout.write(chunk);
545
706
  this.emit('stdOutRaw', chunk);
546
707
  }
547
708
  });
709
+ this.runningCommand.on('token', token => {
710
+ this.emit('token', token);
711
+ });
548
712
  this.runningCommand.on('stderr', chunk => {
549
- this.stderr.write(chunk);
713
+ if (stderrDest.type === 'file') {
714
+ instance.stdErr = String(chunk ?? '');
715
+ } else if (stderrDest.type === 'stdout') {
716
+ if (stdoutDest.type === 'file') {
717
+ instance.stdOut = String(chunk ?? '');
718
+ } else if (stdoutDest.type === 'null') {
719
+ // discard
720
+ } else {
721
+ this.stdout.write(chunk);
722
+ this.emit('stdOutRaw', chunk);
723
+ }
724
+ } else if (stderrDest.type === 'null') {
725
+ // discard
726
+ } else {
727
+ this.stderr.write(chunk);
728
+ }
550
729
  });
551
730
  }
552
731
  if (instance.interactive) {
@@ -555,38 +734,63 @@ class Shell extends EventEmitter {
555
734
 
556
735
  return instance.runCommand().then(result => {
557
736
  const stdOutput = result.getStdOutput();
737
+ stdOutput.forEach(routeLine);
738
+
739
+ for (const dest of [stdoutDest, stderrDest]) {
740
+ if (dest.type === 'file' && dest.file !== '/dev/null' && !fileOutputs.has(dest.file)) {
741
+ fileOutputs.set(dest.file, { append: dest.append, lines: [] });
742
+ }
743
+ }
558
744
 
559
- if (redirectPath) {
560
- const absTarget = this.context.fs.absolutePath(redirectPath);
561
- const outLines = stdOutput.filter(l => l.type === 'out').map(l => l.string);
562
- const content = appendMode
563
- ? (() => {
564
- const existing = this.context.fs._getFileRaw(absTarget);
565
- return typeof existing === 'string'
566
- ? existing + '\n' + outLines.join('\n')
567
- : outLines.join('\n');
568
- })()
569
- : outLines.join('\n');
745
+ for (const [filePath, { append, lines }] of fileOutputs) {
746
+ const absTarget = this.context.fs.absolutePath(filePath);
747
+ const content = lines.join('\n');
748
+ let finalContent = content;
749
+ if (append) {
750
+ const existing = this.context.fs._getFileRaw(absTarget);
751
+ finalContent = typeof existing === 'string'
752
+ ? (existing.length > 0 ? existing + '\n' + content : content)
753
+ : content;
754
+ }
570
755
  try {
571
- this.context.fs.setFileByPath(absTarget, content, true);
756
+ this.context.fs.setFileByPath(absTarget, finalContent, true);
572
757
  } catch (e) {
573
- this.emit('stdErr', `${redirectPath}: Permission denied`);
574
- this.lastCode = 1;
758
+ this.emit('stdErr', `${filePath}: Permission denied`);
759
+ this.lastCode = negate ? 0 : 1;
575
760
  this.emit('exitCode', this.lastCode);
576
761
  delete this.runningCommand;
577
762
  return;
578
763
  }
579
- this._emitOutput(stdOutput.filter(l => l.type === 'err'));
580
- } else {
581
- this._emitOutput(stdOutput);
582
764
  }
583
765
 
584
- this.lastCode = result.getExitCode();
766
+ const rawExitCode = result.getExitCode();
767
+ this.lastCode = negate ? (rawExitCode === 0 ? 1 : 0) : rawExitCode;
585
768
  this.emit('exitCode', this.lastCode);
586
769
  delete this.runningCommand;
587
770
  });
588
771
  }
589
772
 
773
+ _handleCommandError(message, stderrDest, negate) {
774
+ if (stderrDest.type === 'stdout') {
775
+ this.emit('stdOut', message);
776
+ } else if (stderrDest.type === 'file') {
777
+ if (stderrDest.file !== '/dev/null') {
778
+ try {
779
+ const absTarget = this.context.fs.absolutePath(stderrDest.file);
780
+ const existing = this.context.fs._getFileRaw(absTarget);
781
+ const content = stderrDest.append && typeof existing === 'string'
782
+ ? (existing.length > 0 ? existing + '\n' + message : message)
783
+ : message;
784
+ this.context.fs.setFileByPath(absTarget, content, true);
785
+ } catch (_) {}
786
+ }
787
+ } else if (stderrDest.type === 'stderr') {
788
+ this.emit('stdErr', message);
789
+ }
790
+ this.lastCode = negate ? 0 : 1;
791
+ this.emit('exitCode', this.lastCode);
792
+ }
793
+
590
794
  _emitOutput(lines) {
591
795
  lines.forEach(({type, string}) => {
592
796
  if(type === 'out') {
@@ -617,8 +821,10 @@ class Shell extends EventEmitter {
617
821
 
618
822
  _setupTtyStreams() {
619
823
  this.on('stdOut', line => {
620
- if (this.runningCommand && (this.runningCommand.interactive || this.runningCommand._inAltScreen)) {
621
- this.stdout.write(String(line ?? ''));
824
+ if (this.runningCommand && (this.runningCommand.interactive || this.runningCommand._inAltScreen || this.runningCommand._streamedStdout)) {
825
+ if (this.runningCommand.interactive || this.runningCommand._inAltScreen) {
826
+ this.stdout.write(String(line ?? ''));
827
+ }
622
828
  return;
623
829
  }
624
830
  if (typeof line === 'string' && line.startsWith('\r')) {
@@ -1237,6 +1443,23 @@ class Shell extends EventEmitter {
1237
1443
  if (commands.length === 1) {
1238
1444
  return this._runCommand(commands[0]);
1239
1445
  }
1446
+
1447
+ let negatePipeline = false;
1448
+ try {
1449
+ const firstParts = Shell._splitCommand(commands[0]);
1450
+ let strippedCmd0 = commands[0];
1451
+ let hasNegation = false;
1452
+ while (firstParts.length > 0 && !firstParts[0].hasQuote && firstParts[0].value === '!') {
1453
+ negatePipeline = !negatePipeline;
1454
+ hasNegation = true;
1455
+ firstParts.shift();
1456
+ strippedCmd0 = strippedCmd0.replace(/^\s*!\s*/, '');
1457
+ }
1458
+ if (hasNegation) {
1459
+ commands = [strippedCmd0, ...commands.slice(1)];
1460
+ }
1461
+ } catch (_) {}
1462
+
1240
1463
  let stdinData = undefined;
1241
1464
  for (let i = 0; i < commands.length; i++) {
1242
1465
  const isLast = i === commands.length - 1;
@@ -1251,6 +1474,11 @@ class Shell extends EventEmitter {
1251
1474
  stdinData = await this._captureForPipe(commands[i], stdinData);
1252
1475
  }
1253
1476
  }
1477
+
1478
+ if (negatePipeline) {
1479
+ this.lastCode = this.lastCode === 0 ? 1 : 0;
1480
+ this.emit('exitCode', this.lastCode);
1481
+ }
1254
1482
  }
1255
1483
 
1256
1484
  async _captureForPipe(cmd, stdin) {
@@ -130,6 +130,23 @@ class ReplCommand extends InteractiveCommand {
130
130
  this._scrollOffset = 0;
131
131
  }
132
132
 
133
+ streamReplChunk(chunk, type = 'out') {
134
+ if (!chunk) return;
135
+ if (this._replLog.length === 0 || this._replLog[this._replLog.length - 1].type !== type || !this._replStreamingActive) {
136
+ this._replLog.push({ text: '', type });
137
+ this._replStreamingActive = true;
138
+ }
139
+ const last = this._replLog[this._replLog.length - 1];
140
+ const combined = last.text + chunk;
141
+ const lines = combined.split(/\r?\n/);
142
+ last.text = lines[0];
143
+ for (let i = 1; i < lines.length; i++) {
144
+ this._replLog.push({ text: lines[i], type });
145
+ }
146
+ this._scrollOffset = 0;
147
+ this._renderRepl();
148
+ }
149
+
133
150
  onInput(key) {
134
151
  if (!this.shouldBeInteractive()) return;
135
152
 
@@ -205,12 +222,15 @@ class ReplCommand extends InteractiveCommand {
205
222
  .then(() => this.evaluateReplLine(codeToEval))
206
223
  .then((res) => {
207
224
  this._replBusy = false;
225
+ this._replStreamingActive = false;
208
226
  this._replStatus = '^D / .exit: Quit | ^L: Clear | Up/Down: History';
209
227
  if (res) {
210
228
  if (res.clear) {
211
229
  this._replLog = [];
212
230
  }
213
- if (Array.isArray(res.output)) {
231
+ if (res.streamed) {
232
+ // Output was already streamed incrementally via streamReplChunk
233
+ } else if (Array.isArray(res.output)) {
214
234
  for (const outLine of res.output) {
215
235
  this._appendReplLog(outLine, 'out');
216
236
  }
@@ -88,7 +88,108 @@ class ScriptCommand extends LocalCommand {
88
88
  });
89
89
  }
90
90
 
91
+ /**
92
+ * POSIX sh requires logical lines to span multiple physical lines when quotes
93
+ * (' or ") remain unclosed or when a line ends with an unescaped backslash
94
+ * line continuation. This accumulates the raw script lines into complete
95
+ * logical lines before block parsing and tokenization occur.
96
+ */
97
+ _accumulateLines(lines) {
98
+ const accumulated = [];
99
+ let current = null;
100
+ let inSingle = false;
101
+ let inDouble = false;
102
+ let lastWasContinuation = false;
103
+
104
+ for (let i = 0; i < lines.length; i++) {
105
+ const rawLine = lines[i];
106
+
107
+ if (current === null) {
108
+ current = rawLine;
109
+ } else {
110
+ if (lastWasContinuation) {
111
+ current += rawLine;
112
+ } else if (inSingle || inDouble) {
113
+ current += '\n' + rawLine;
114
+ } else {
115
+ current += rawLine;
116
+ }
117
+ }
118
+
119
+ let j = 0;
120
+ let isContinuation = false;
121
+ let isComment = false;
122
+
123
+ while (j < rawLine.length) {
124
+ const ch = rawLine[j];
125
+ if (inSingle) {
126
+ if (ch === "'") {
127
+ inSingle = false;
128
+ }
129
+ j++;
130
+ } else if (inDouble) {
131
+ if (ch === '\\' && j + 1 < rawLine.length) {
132
+ j += 2;
133
+ } else if (ch === '\\' && j + 1 === rawLine.length) {
134
+ isContinuation = true;
135
+ j++;
136
+ } else if (ch === '"') {
137
+ inDouble = false;
138
+ j++;
139
+ } else {
140
+ j++;
141
+ }
142
+ } else {
143
+ if (ch === '#' && (j === 0 || /\s/.test(rawLine[j - 1]))) {
144
+ isComment = true;
145
+ break;
146
+ }
147
+ if (ch === '\\' && j + 1 < rawLine.length) {
148
+ j += 2;
149
+ } else if (ch === '\\' && j + 1 === rawLine.length) {
150
+ isContinuation = true;
151
+ j++;
152
+ } else if (ch === "'") {
153
+ inSingle = true;
154
+ j++;
155
+ } else if (ch === '"') {
156
+ inDouble = true;
157
+ j++;
158
+ } else {
159
+ j++;
160
+ }
161
+ }
162
+ }
163
+
164
+ if (!inSingle && !isContinuation && !isComment) {
165
+ const match = rawLine.match(/(\\+)\s*$/);
166
+ if (match && match[1].length % 2 === 1) {
167
+ isContinuation = true;
168
+ }
169
+ }
170
+
171
+ lastWasContinuation = isContinuation;
172
+
173
+ if (isContinuation) {
174
+ current = current.replace(/\\\s*$/, '');
175
+ }
176
+
177
+ if (!inSingle && !inDouble && !isContinuation) {
178
+ accumulated.push(current);
179
+ current = null;
180
+ lastWasContinuation = false;
181
+ }
182
+ }
183
+
184
+ if (current !== null) {
185
+ accumulated.push(current);
186
+ }
187
+
188
+ return accumulated;
189
+ }
190
+
91
191
  _parseLines(lines) {
192
+ lines = this._accumulateLines(lines);
92
193
  const nodes = [];
93
194
  let i = 0;
94
195
  while (i < lines.length) {