brsh 3.6.1 → 3.7.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.
@@ -3,6 +3,7 @@
3
3
  // The set of methods exposed to command instances via sandbox().
4
4
  // Anything not in this list is inaccessible to user-supplied commands.
5
5
  const SANDBOX_ALLOWED = new Set([
6
+ 'cwd',
6
7
  'getFileByPath', 'setFileByPath', 'deleteFileByPath',
7
8
  'exists', 'stat', 'absolutePath',
8
9
  'getMode', 'setMode',
package/lib/FileSystem.js CHANGED
@@ -55,7 +55,7 @@ class FileSystem extends BaseFileSystem {
55
55
  decodeBinaryFiles(filesystem);
56
56
  this.fileSystem = filesystem;
57
57
  this.permissions = Object.assign({}, permissions);
58
- this.cwd = cwd;
58
+ this.cwd = cwd.endsWith('/') ? cwd : (cwd + '/');
59
59
  this._onChange = onChange;
60
60
  this._changeScheduled = false;
61
61
  }
@@ -130,7 +130,8 @@ class FileSystem extends BaseFileSystem {
130
130
  path = path.substring(2);
131
131
  }
132
132
  if(!path.startsWith('/')) {
133
- path = this.cwd + path;
133
+ const base = (this.cwd && this.cwd.endsWith('/')) ? this.cwd : (this.cwd ? this.cwd + '/' : '/');
134
+ path = base + path;
134
135
  }
135
136
  return this._traverseComplexAbsolutePath(path);
136
137
  }
@@ -309,19 +309,55 @@ class WasmCommand extends ScriptCommand {
309
309
  // fd 3: pre-opened root directory '/'
310
310
  // fd 4: pre-opened current working directory '.'
311
311
  const fs = this.context && this.context.fs ? this.context.fs : this.fs;
312
+ const rawCwd = (this.context && this.context.fs && this.context.fs.cwd)
313
+ || (this.fs && this.fs.cwd)
314
+ || (this.context && typeof this.context.getVar === 'function' && this.context.getVar('PWD'))
315
+ || (fs && fs.cwd)
316
+ || '/';
317
+ const cwd = rawCwd.length > 1 && rawCwd.endsWith('/') ? rawCwd.slice(0, -1) : rawCwd;
312
318
  let nextFd = 5;
313
319
  const fdTable = new Map([
314
320
  [3, { type: 'preopen', path: '/', guestName: '/' }],
315
- [4, { type: 'preopen', path: (fs && fs.cwd) || '/', guestName: '.' }]
321
+ [4, { type: 'preopen', path: cwd, guestName: '.' }]
316
322
  ]);
317
323
 
324
+ const getParentPath = (p) => {
325
+ const parts = p.split('/').filter(Boolean);
326
+ parts.pop();
327
+ return '/' + parts.join('/');
328
+ };
329
+
318
330
  const resolveGuestPath = (dirFd, relPath) => {
319
331
  const dirEntry = fdTable.get(dirFd);
320
332
  if (!dirEntry || (dirEntry.type !== 'preopen' && dirEntry.type !== 'dir')) return null;
321
333
  if (relPath.startsWith('/')) return fs.absolutePath(relPath);
322
334
  if (!relPath || relPath === '.') return fs.absolutePath(dirEntry.path);
335
+
323
336
  const base = dirEntry.path.endsWith('/') ? dirEntry.path : dirEntry.path + '/';
324
- return fs.absolutePath(base + relPath);
337
+ const directPath = fs.absolutePath(base + relPath);
338
+ const rootPath = fs.absolutePath('/' + relPath);
339
+
340
+ // If dirEntry is not '/', wasi-libc may have stripped the leading '/'
341
+ // from an absolute path (e.g. 'root/ansitest.js' or 'etc/hosts')
342
+ if (dirEntry.path !== '/') {
343
+ if (fs.exists(directPath)) return directPath;
344
+ if (fs.exists(rootPath)) return rootPath;
345
+
346
+ // When file doesn't exist yet (e.g. creating new file), check parent directories
347
+ const directParent = fs.exists(getParentPath(directPath));
348
+ const rootParent = fs.exists(getParentPath(rootPath));
349
+ if (rootParent && !directParent) return rootPath;
350
+ if (directParent && !rootParent) return directPath;
351
+
352
+ return directPath;
353
+ }
354
+
355
+ // dirEntry.path is '/'
356
+ if (fs.exists(directPath)) return directPath;
357
+ const cwdCandidate = fs.absolutePath(relPath);
358
+ if (fs.exists(cwdCandidate)) return cwdCandidate;
359
+
360
+ return directPath;
325
361
  };
326
362
 
327
363
  const flushOpenFile = (entry) => {
@@ -23,6 +23,11 @@ function cloneCell(cell) {
23
23
  };
24
24
  }
25
25
 
26
+ function isCellEmpty(cell) {
27
+ if (!cell) return true;
28
+ return cell.ch === ' ' && cell.fg === null && cell.bg === null && cell.flags === 0 && cell.link === null;
29
+ }
30
+
26
31
  class ScreenBuffer {
27
32
  constructor(cols = 80, rows = 24, options = {}) {
28
33
  this.cols = Math.max(1, cols);
@@ -74,6 +79,7 @@ class ScreenBuffer {
74
79
  for (let c = 0; c < cols; c++) {
75
80
  row[c] = createCell(' ', fg, bg, flags, null);
76
81
  }
82
+ row.isWrapped = false;
77
83
  return row;
78
84
  }
79
85
 
@@ -264,6 +270,10 @@ class ScreenBuffer {
264
270
  putChar(ch) {
265
271
  if (this.pendingWrap) {
266
272
  if (this.autoWrap) {
273
+ const prevRow = this.grid[this.cursorRow];
274
+ if (prevRow) {
275
+ prevRow.isWrapped = true;
276
+ }
267
277
  this.cursorCol = 0;
268
278
  this.pendingWrap = false;
269
279
  this._indexDown();
@@ -364,7 +374,9 @@ class ScreenBuffer {
364
374
  for (let i = 0; i < n; i++) {
365
375
  const removed = g[top];
366
376
  if (!this.isAltScreen && top === 0 && this.maxScrollback > 0) {
367
- this.scrollback.push(removed.map(cloneCell));
377
+ const cloned = removed.map(cloneCell);
378
+ cloned.isWrapped = Boolean(removed.isWrapped);
379
+ this.scrollback.push(cloned);
368
380
  if (this.scrollback.length > this.maxScrollback) {
369
381
  this.scrollback.shift();
370
382
  }
@@ -402,7 +414,12 @@ class ScreenBuffer {
402
414
  return;
403
415
  }
404
416
  for (let c = start; c <= end; c++) {
405
- row[c] = createCell(' ', this.curFg, this.curBg, this.curFlags, null);
417
+ if (c < row.length) {
418
+ row[c] = createCell(' ', this.curFg, this.curBg, this.curFlags, null);
419
+ }
420
+ }
421
+ if (mode === 2 || (mode === 0 && this.cursorCol === 0)) {
422
+ row.isWrapped = false;
406
423
  }
407
424
  this.pendingWrap = false;
408
425
  this._markRowDirty(this.cursorRow);
@@ -493,33 +510,199 @@ class ScreenBuffer {
493
510
  const rows = Math.max(1, newRows);
494
511
  if (cols === this.cols && rows === this.rows) return;
495
512
 
496
- const resizeGrid = (oldGrid) => {
497
- const nextGrid = new Array(rows);
498
- for (let r = 0; r < rows; r++) {
499
- const newRow = new Array(cols);
500
- const oldRow = r < oldGrid.length ? oldGrid[r] : null;
501
- for (let c = 0; c < cols; c++) {
502
- newRow[c] = oldRow && c < oldRow.length
503
- ? oldRow[c]
504
- : createCell(' ', null, null, 0, null);
513
+ if (this.isAltScreen) {
514
+ const resizeGrid = (oldGrid) => {
515
+ const nextGrid = new Array(rows);
516
+ for (let r = 0; r < rows; r++) {
517
+ const newRow = new Array(cols);
518
+ const oldRow = r < oldGrid.length ? oldGrid[r] : null;
519
+ for (let c = 0; c < cols; c++) {
520
+ newRow[c] = oldRow && c < oldRow.length
521
+ ? oldRow[c]
522
+ : createCell(' ', null, null, 0, null);
523
+ }
524
+ newRow.isWrapped = false;
525
+ nextGrid[r] = newRow;
505
526
  }
506
- nextGrid[r] = newRow;
527
+ return nextGrid;
528
+ };
529
+ this.altGrid = resizeGrid(this.altGrid);
530
+ this.cols = cols;
531
+ this.rows = rows;
532
+ this.scrollTop = 0;
533
+ this.scrollBottom = rows - 1;
534
+ this.cursorRow = Math.min(rows - 1, this.cursorRow);
535
+ this.cursorCol = Math.min(cols - 1, this.cursorCol);
536
+ this.pendingWrap = false;
537
+ this._markAllDirty();
538
+ return;
539
+ }
540
+
541
+ const reflowResult = this._reflowPrimaryBuffer(cols, rows);
542
+ this.scrollback = reflowResult.scrollback;
543
+ this.primaryGrid = reflowResult.primaryGrid;
544
+ this.cursorRow = reflowResult.cursorRow;
545
+ this.cursorCol = reflowResult.cursorCol;
546
+
547
+ // Resize altGrid directly so dimensions stay in sync
548
+ const nextAlt = new Array(rows);
549
+ for (let r = 0; r < rows; r++) {
550
+ const row = new Array(cols);
551
+ const oldRow = r < this.altGrid.length ? this.altGrid[r] : null;
552
+ for (let c = 0; c < cols; c++) {
553
+ row[c] = oldRow && c < oldRow.length
554
+ ? oldRow[c]
555
+ : createCell(' ', null, null, 0, null);
507
556
  }
508
- return nextGrid;
509
- };
557
+ row.isWrapped = false;
558
+ nextAlt[r] = row;
559
+ }
560
+ this.altGrid = nextAlt;
510
561
 
511
- this.primaryGrid = resizeGrid(this.primaryGrid);
512
- this.altGrid = resizeGrid(this.altGrid);
513
562
  this.cols = cols;
514
563
  this.rows = rows;
515
564
  this.scrollTop = 0;
516
565
  this.scrollBottom = rows - 1;
517
- this.cursorRow = Math.min(rows - 1, this.cursorRow);
518
- this.cursorCol = Math.min(cols - 1, this.cursorCol);
519
566
  this.pendingWrap = false;
567
+ this.viewportOffset = Math.min(this.scrollback.length, this.viewportOffset);
520
568
  this._markAllDirty();
521
569
  }
522
570
 
571
+ _reflowPrimaryBuffer(newCols, newRows) {
572
+ const oldCols = this.cols;
573
+ const fullBuffer = [...this.scrollback, ...this.primaryGrid];
574
+ const cursorAbsRow = this.scrollback.length + this.cursorRow;
575
+ const cursorAbsCol = this.cursorCol;
576
+
577
+ let lastActiveRow = cursorAbsRow;
578
+ for (let r = fullBuffer.length - 1; r >= 0; r--) {
579
+ const row = fullBuffer[r];
580
+ if (row && (row.isWrapped || row.some(c => !isCellEmpty(c)))) {
581
+ lastActiveRow = Math.max(lastActiveRow, r);
582
+ break;
583
+ }
584
+ }
585
+
586
+ const activeBuffer = fullBuffer.slice(0, lastActiveRow + 1);
587
+
588
+ const logicalLines = [];
589
+ let currentLine = null;
590
+
591
+ for (let r = 0; r < activeBuffer.length; r++) {
592
+ const row = activeBuffer[r];
593
+ const isCursorRow = (r === cursorAbsRow);
594
+
595
+ if (!currentLine) {
596
+ currentLine = { cells: [], cursorPos: null, isWrapped: false };
597
+ }
598
+
599
+ let lastMeaningfulCol = -1;
600
+ for (let c = row.length - 1; c >= 0; c--) {
601
+ if (!isCellEmpty(row[c])) {
602
+ lastMeaningfulCol = c;
603
+ break;
604
+ }
605
+ }
606
+
607
+ let takeCols = row.isWrapped ? oldCols : lastMeaningfulCol + 1;
608
+ if (isCursorRow && cursorAbsCol >= takeCols) {
609
+ takeCols = cursorAbsCol + 1;
610
+ }
611
+
612
+ const baseOffset = currentLine.cells.length;
613
+ if (isCursorRow) {
614
+ currentLine.cursorPos = baseOffset + cursorAbsCol;
615
+ }
616
+
617
+ for (let c = 0; c < takeCols; c++) {
618
+ currentLine.cells.push(c < row.length ? cloneCell(row[c]) : createCell(' '));
619
+ }
620
+
621
+ currentLine.isWrapped = Boolean(row.isWrapped);
622
+ if (!row.isWrapped) {
623
+ logicalLines.push(currentLine);
624
+ currentLine = null;
625
+ }
626
+ }
627
+ if (currentLine) {
628
+ logicalLines.push(currentLine);
629
+ }
630
+
631
+ const newRowsList = [];
632
+ let newCursorRow = null;
633
+ let newCursorCol = null;
634
+
635
+ for (const line of logicalLines) {
636
+ const cells = line.cells;
637
+ const totalCells = cells.length;
638
+
639
+ if (totalCells === 0) {
640
+ const emptyRow = this._createRow(newCols);
641
+ if (line.cursorPos !== null) {
642
+ newCursorRow = newRowsList.length;
643
+ newCursorCol = 0;
644
+ }
645
+ newRowsList.push(emptyRow);
646
+ continue;
647
+ }
648
+
649
+ let offset = 0;
650
+ while (offset < totalCells) {
651
+ const chunkLen = Math.min(newCols, totalCells - offset);
652
+ const row = new Array(newCols);
653
+ for (let c = 0; c < newCols; c++) {
654
+ if (c < chunkLen) {
655
+ row[c] = cells[offset + c];
656
+ } else {
657
+ row[c] = createCell(' ');
658
+ }
659
+ }
660
+
661
+ const isLastChunk = (offset + chunkLen >= totalCells);
662
+ row.isWrapped = !isLastChunk ? true : line.isWrapped;
663
+
664
+ if (line.cursorPos !== null && line.cursorPos >= offset && (line.cursorPos < offset + newCols || isLastChunk)) {
665
+ newCursorRow = newRowsList.length;
666
+ newCursorCol = Math.min(newCols - 1, line.cursorPos - offset);
667
+ }
668
+
669
+ newRowsList.push(row);
670
+ offset += newCols;
671
+ }
672
+ }
673
+
674
+ if (newCursorRow === null) {
675
+ newCursorRow = Math.min(newRows - 1, newRowsList.length - 1);
676
+ newCursorCol = 0;
677
+ }
678
+
679
+ let finalScrollback = [];
680
+ let finalPrimary = [];
681
+
682
+ if (newRowsList.length <= newRows) {
683
+ finalScrollback = [];
684
+ finalPrimary = newRowsList;
685
+ while (finalPrimary.length < newRows) {
686
+ finalPrimary.push(this._createRow(newCols));
687
+ }
688
+ } else {
689
+ const excess = newRowsList.length - newRows;
690
+ finalScrollback = newRowsList.slice(0, excess);
691
+ if (this.maxScrollback > 0 && finalScrollback.length > this.maxScrollback) {
692
+ finalScrollback = finalScrollback.slice(finalScrollback.length - this.maxScrollback);
693
+ }
694
+ finalPrimary = newRowsList.slice(excess);
695
+ newCursorRow = Math.max(0, newCursorRow - excess);
696
+ }
697
+
698
+ return {
699
+ scrollback: finalScrollback,
700
+ primaryGrid: finalPrimary,
701
+ cursorRow: Math.min(newRows - 1, newCursorRow),
702
+ cursorCol: Math.min(newCols - 1, newCursorCol)
703
+ };
704
+ }
705
+
523
706
  scrollViewport(deltaLines) {
524
707
  if (this.isAltScreen) return;
525
708
  const maxOffset = this.scrollback.length;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.6.1",
3
+ "version": "3.7.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",
@@ -591,6 +591,38 @@ describe('brsh Shell Integration, Line Editing, and Full-Screen Apps', () => {
591
591
 
592
592
  expect(term.screen.isAltScreen).toBe(false);
593
593
  });
594
+
595
+ it('runs nano text editor opening a file and displaying its content', async () => {
596
+ const FIXTURE_NANO_WASM = path.resolve(import.meta.dirname, 'fixtures/nano.wasm');
597
+ if (!fs.existsSync(FIXTURE_NANO_WASM)) return;
598
+ const bytes = fs.readFileSync(FIXTURE_NANO_WASM);
599
+ const Wbt = (await import('../lib/wbt/index.js')).default.configure({
600
+ fetch: async () => ({
601
+ ok: true,
602
+ status: 200,
603
+ arrayBuffer: async () => bytes.buffer
604
+ })
605
+ });
606
+ shell.context.setCommand(Wbt);
607
+ await shell.onCommand('wbt install nano');
608
+
609
+ shell.context.fs.setFileByPath('greeting.txt', 'Hello from inside nano buffer!', true);
610
+
611
+ const nanoDone = waitForReady(shell);
612
+ shell.onCommand('nano greeting.txt');
613
+ await new Promise(r => setTimeout(r, 80));
614
+
615
+ expect(term.screen.isAltScreen).toBe(true);
616
+ expect(term.getScreenText()).toContain('greeting.txt');
617
+ expect(term.getScreenText()).toContain('Hello from inside nano buffer!');
618
+ expect(term.getScreenText()).not.toContain('does not exist');
619
+
620
+ // Exit nano with Ctrl+X
621
+ term.sendKey('x', { ctrl: true });
622
+ await nanoDone;
623
+
624
+ expect(term.screen.isAltScreen).toBe(false);
625
+ });
594
626
  });
595
627
 
596
628
  describe('TUI (blessed-style) Application over Virtual TTY & Real zsh PTY Compatibility', () => {
@@ -1039,4 +1071,74 @@ describe('Output Typing Animation Suppression', () => {
1039
1071
  term.destroy();
1040
1072
  });
1041
1073
  });
1074
+
1075
+ describe('Terminal Resizing and Content Preservation', () => {
1076
+ it('preserves line content cut off when resizing smaller, and restores it when resized bigger', () => {
1077
+ const el = document.createElement('div');
1078
+ const term = new Terminal({
1079
+ el,
1080
+ Shell: false,
1081
+ cols: 80,
1082
+ rows: 24
1083
+ });
1084
+
1085
+ const longLine = 'Email: eliot@piratemedia.tv (mailto:eliot@piratemedia.tv)';
1086
+ term.write(longLine + '\r\n');
1087
+
1088
+ expect(term.getLineText(0)).toBe(longLine);
1089
+
1090
+ // Resize down to 32 columns: reflows overflow onto next row
1091
+ term.resize(32, 24);
1092
+ expect(term.cols).toBe(32);
1093
+ expect(term.getLineText(0)).toBe(longLine.slice(0, 32));
1094
+ expect(term.getLineText(1)).toBe(longLine.slice(32));
1095
+
1096
+ // In DOM, the reflowed rows are rendered
1097
+ expect(term.renderer._rowElements[0].innerHTML).toContain('Email: eliot@piratemedia.tv (mai');
1098
+ expect(term.renderer._rowElements[1].innerHTML).toContain('lto:eliot@piratemedia.tv)');
1099
+
1100
+ // Resize back bigger to 80 columns: the cut off text unwraps and is fully restored
1101
+ term.resize(80, 24);
1102
+ expect(term.cols).toBe(80);
1103
+ expect(term.getLineText(0)).toBe(longLine);
1104
+ expect(term.getLineText(1)).toBe('');
1105
+
1106
+ // Multiple resize cycles
1107
+ term.resize(20, 24);
1108
+ expect(term.getLineText(0)).toBe(longLine.slice(0, 20));
1109
+ expect(term.getLineText(1)).toBe(longLine.slice(20, 40));
1110
+ expect(term.getLineText(2)).toBe(longLine.slice(40));
1111
+
1112
+ term.resize(100, 24);
1113
+ expect(term.getLineText(0)).toBe(longLine);
1114
+ expect(term.getLineText(1)).toBe('');
1115
+ expect(term.getLineText(2)).toBe('');
1116
+
1117
+ term.destroy();
1118
+ });
1119
+
1120
+ it('clears reflowed line when erased with erase-in-line', () => {
1121
+ const el = document.createElement('div');
1122
+ const term = new Terminal({
1123
+ el,
1124
+ Shell: false,
1125
+ cols: 80,
1126
+ rows: 24
1127
+ });
1128
+
1129
+ const longLine = 'Email: eliot@piratemedia.tv (mailto:eliot@piratemedia.tv)';
1130
+ term.write(longLine);
1131
+
1132
+ // Resize to 32 cols: wraps onto row 0 and 1
1133
+ term.resize(32, 24);
1134
+ expect(term.getLineText(0)).toBe(longLine.slice(0, 32));
1135
+ expect(term.getLineText(1)).toBe(longLine.slice(32));
1136
+
1137
+ // Move cursor to start of row 0 and erase row 0
1138
+ term.write('\x1b[H\x1b[K');
1139
+ expect(term.getLineText(0)).toBe('');
1140
+
1141
+ term.destroy();
1142
+ });
1143
+ });
1042
1144
  });