brsh 3.9.0 → 3.10.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/Readme.md +22 -4
  3. package/bin/Readme.md +33 -3
  4. package/bin/exportFileSystem.js +127 -110
  5. package/bin/wbt.js +118 -0
  6. package/dist/shell.es.js +4074 -3717
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +26 -25
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +3 -3
  11. package/dist/terminal.cjs.js.map +1 -1
  12. package/dist/terminal.es.js +55 -33
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +3 -3
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3082 -2710
  17. package/dist/wbt.es.js.map +1 -1
  18. package/dist/wbt.min.js +16 -12
  19. package/dist/wbt.min.js.map +1 -1
  20. package/index.js +102 -80
  21. package/lib/BaseFileSystem.js +57 -2
  22. package/lib/BinaryContainer.js +1 -1
  23. package/lib/Command.js +1 -1
  24. package/lib/Context.js +4 -3
  25. package/lib/FileSystem.js +4 -2
  26. package/lib/InteractiveCommand.js +9 -8
  27. package/lib/JsCommand.js +113 -0
  28. package/lib/NodeFileSystem.js +164 -30
  29. package/lib/Readme.md +1 -0
  30. package/lib/ScriptCommand.js +148 -8
  31. package/lib/Terminal.js +60 -6
  32. package/lib/TtyStream.js +36 -2
  33. package/lib/WasmCommand.js +313 -66
  34. package/lib/buildFilesystemStructure.js +38 -24
  35. package/lib/isUtf8Text.js +47 -0
  36. package/lib/local/which.js +8 -3
  37. package/lib/wbt/index.js +473 -175
  38. package/lib/wbt/registry.js +21 -1
  39. package/package.json +3 -2
  40. package/test/devices-signals.test.js +112 -0
  41. package/test/doom.test.js +7 -4
  42. package/test/exportFileSystem.test.js +37 -15
  43. package/test/js-command.test.js +125 -0
  44. package/test/node-filesystem.test.js +7 -0
  45. package/test/scripts.test.js +30 -0
  46. package/test/terminal.test.js +148 -0
  47. package/test/wasm-cli.test.js +76 -0
  48. package/test/wbt.test.js +418 -10
  49. package/test/wbtCli.test.js +160 -0
@@ -3,29 +3,79 @@
3
3
  const nodeFs = require('fs');
4
4
  const nodePath = require('path');
5
5
  const BaseFileSystem = require('./BaseFileSystem');
6
+ const { BinaryFile, SymlinkRef, isUtf8Text } = BaseFileSystem;
6
7
 
7
8
  class NodeFileSystem extends BaseFileSystem {
8
- constructor(cwd, onChange = null) {
9
+ constructor(cwd = '/', onChange = null, options = {}) {
9
10
  super();
10
11
  this._onChange = onChange;
11
12
  this._changeScheduled = false;
12
13
  this._virtualFiles = {};
13
- this.cwd = this._normalizeCwd(cwd || process.cwd());
14
+ this._rootDir = options && options.rootDir ? nodePath.resolve(options.rootDir) : null;
15
+ this.cwd = this._normalizeCwd(cwd || (this._rootDir ? '/' : process.cwd()));
14
16
  }
15
17
 
16
18
  get isRealFilesystem() { return true; }
17
19
 
20
+ get rootDir() { return this._rootDir; }
21
+
18
22
  _normalizeCwd(cwd) {
23
+ if (this._rootDir) {
24
+ let abs = cwd.startsWith('/') ? cwd : '/' + cwd;
25
+ abs = nodePath.posix.normalize(abs);
26
+ return abs === '/' ? '/' : abs + '/';
27
+ }
19
28
  const abs = nodePath.resolve(cwd);
20
29
  return abs === '/' ? '/' : abs + '/';
21
30
  }
22
31
 
23
32
  absolutePath(path) {
33
+ if (!path) return this.cwd;
24
34
  if (path.startsWith('./')) path = path.slice(2);
35
+ if (this._rootDir) {
36
+ const abs = path.startsWith('/') ? path : nodePath.posix.join(this.cwd, path);
37
+ return nodePath.posix.normalize(abs);
38
+ }
25
39
  const abs = path.startsWith('/') ? path : nodePath.join(this.cwd, path);
26
40
  return nodePath.normalize(abs);
27
41
  }
28
42
 
43
+ _toHostPath(virtualPath) {
44
+ const vAbs = this.absolutePath(virtualPath);
45
+ if (!this._rootDir) {
46
+ return nodePath.resolve(vAbs);
47
+ }
48
+ const rel = vAbs.replace(/^\/+/, '');
49
+ const hostPath = nodePath.resolve(this._rootDir, rel);
50
+ if (hostPath !== this._rootDir && !hostPath.startsWith(this._rootDir + nodePath.sep)) {
51
+ return this._rootDir;
52
+ }
53
+ return hostPath;
54
+ }
55
+
56
+ _resolveVirtualPath(virtualPath, maxHops = 10) {
57
+ let current = this.absolutePath(virtualPath);
58
+ let hops = 0;
59
+ while (hops++ < maxHops) {
60
+ const host = this._toHostPath(current);
61
+ let isLink = false;
62
+ let target = null;
63
+ try {
64
+ if (nodeFs.lstatSync(host).isSymbolicLink()) {
65
+ isLink = true;
66
+ target = nodeFs.readlinkSync(host);
67
+ }
68
+ } catch (_) {}
69
+ if (!isLink || !target) break;
70
+ if (target.startsWith('/')) {
71
+ current = this.absolutePath(target);
72
+ } else {
73
+ current = this.absolutePath(nodePath.posix.join(nodePath.posix.dirname(current), target));
74
+ }
75
+ }
76
+ return current;
77
+ }
78
+
29
79
  setCwd(cwd) {
30
80
  const trimmed = cwd.endsWith('/') ? cwd.slice(0, -1) : cwd;
31
81
  const abs = this.absolutePath(trimmed);
@@ -39,9 +89,12 @@ class NodeFileSystem extends BaseFileSystem {
39
89
  return this._virtualFiles[abs];
40
90
  }
41
91
 
92
+ const resolvedVirtual = this._resolveVirtualPath(abs);
93
+ const hostPath = this._toHostPath(resolvedVirtual);
94
+
42
95
  let stat;
43
96
  try {
44
- stat = nodeFs.statSync(abs);
97
+ stat = nodeFs.statSync(hostPath);
45
98
  } catch(e) {
46
99
  return null;
47
100
  }
@@ -49,14 +102,23 @@ class NodeFileSystem extends BaseFileSystem {
49
102
  if (stat.isDirectory()) {
50
103
  const entries = {};
51
104
  try {
52
- for (const name of nodeFs.readdirSync(abs)) {
53
- const childAbs = nodePath.join(abs, name);
105
+ for (const name of nodeFs.readdirSync(hostPath)) {
106
+ const childAbs = this.absolutePath(nodePath.posix.join(resolvedVirtual, name));
54
107
  if (this._virtualFiles[childAbs] !== undefined) {
55
108
  entries[name] = this._virtualFiles[childAbs];
56
109
  } else {
57
110
  try {
58
- entries[name] = nodeFs.statSync(childAbs).isDirectory() ? {} : '';
59
- } catch(e) { /* skip unreadable */ }
111
+ const childHost = nodePath.join(hostPath, name);
112
+ const childStat = nodeFs.statSync(childHost);
113
+ entries[name] = childStat.isDirectory() ? {} : '';
114
+ } catch(e) {
115
+ // If child is a symlink or unreadable file
116
+ try {
117
+ if (nodeFs.lstatSync(nodePath.join(hostPath, name)).isSymbolicLink()) {
118
+ entries[name] = '';
119
+ }
120
+ } catch (_) {}
121
+ }
60
122
  }
61
123
  }
62
124
  } catch(e) { /* directory unreadable */ }
@@ -74,7 +136,11 @@ class NodeFileSystem extends BaseFileSystem {
74
136
  }
75
137
 
76
138
  try {
77
- return nodeFs.readFileSync(abs, 'utf8');
139
+ const buf = nodeFs.readFileSync(hostPath);
140
+ if (isUtf8Text(buf)) {
141
+ return buf.toString('utf8');
142
+ }
143
+ return new BinaryFile(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
78
144
  } catch(e) {
79
145
  return null;
80
146
  }
@@ -83,14 +149,34 @@ class NodeFileSystem extends BaseFileSystem {
83
149
  setFileByPath(path, content, createDir = false) {
84
150
  const abs = this.absolutePath(path);
85
151
 
86
- if (typeof content === 'function' || content instanceof Uint8Array) {
152
+ if (typeof content === 'function') {
87
153
  this._virtualFiles[abs] = content;
88
154
  return;
89
155
  }
90
156
 
157
+ const hostPath = this._toHostPath(abs);
158
+
159
+ if (content instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(content))) {
160
+ const u8 = content instanceof Uint8Array
161
+ ? Buffer.from(content.buffer, content.byteOffset, content.byteLength)
162
+ : content;
163
+ try {
164
+ if (createDir) {
165
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
166
+ }
167
+ nodeFs.writeFileSync(hostPath, u8);
168
+ delete this._virtualFiles[abs];
169
+ this._triggerChange();
170
+ } catch (e) {
171
+ this._virtualFiles[abs] = content;
172
+ }
173
+ return;
174
+ }
175
+
91
176
  if (content !== null && content !== undefined && content.constructor === Object) {
92
177
  try {
93
- nodeFs.mkdirSync(abs, { recursive: createDir });
178
+ nodeFs.mkdirSync(hostPath, { recursive: createDir });
179
+ delete this._virtualFiles[abs];
94
180
  this._triggerChange();
95
181
  } catch (e) {
96
182
  this._virtualFiles[abs] = content;
@@ -100,9 +186,10 @@ class NodeFileSystem extends BaseFileSystem {
100
186
 
101
187
  try {
102
188
  if (createDir) {
103
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
189
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
104
190
  }
105
- nodeFs.writeFileSync(abs, String(content));
191
+ nodeFs.writeFileSync(hostPath, String(content));
192
+ delete this._virtualFiles[abs];
106
193
  this._triggerChange();
107
194
  } catch (e) {
108
195
  this._virtualFiles[abs] = String(content);
@@ -112,12 +199,13 @@ class NodeFileSystem extends BaseFileSystem {
112
199
  deleteFileByPath(path) {
113
200
  const abs = this.absolutePath(path);
114
201
  delete this._virtualFiles[abs];
202
+ const hostPath = this._toHostPath(abs);
115
203
  try {
116
- const stat = nodeFs.lstatSync(abs);
204
+ const stat = nodeFs.lstatSync(hostPath);
117
205
  if (stat.isDirectory()) {
118
- nodeFs.rmdirSync(abs);
206
+ nodeFs.rmSync(hostPath, { recursive: true, force: true });
119
207
  } else {
120
- nodeFs.unlinkSync(abs);
208
+ nodeFs.unlinkSync(hostPath);
121
209
  }
122
210
  this._triggerChange();
123
211
  } catch(e) { /* may not exist on real fs */ }
@@ -128,8 +216,9 @@ class NodeFileSystem extends BaseFileSystem {
128
216
  if (this._virtualFiles[abs] !== undefined) {
129
217
  return typeof this._virtualFiles[abs] === 'function' ? 0o755 : 0o644;
130
218
  }
219
+ const hostPath = this._toHostPath(abs);
131
220
  try {
132
- return nodeFs.statSync(abs).mode & 0o777;
221
+ return nodeFs.lstatSync(hostPath).mode & 0o777;
133
222
  } catch(e) {
134
223
  return null;
135
224
  }
@@ -140,17 +229,23 @@ class NodeFileSystem extends BaseFileSystem {
140
229
  if (this._virtualFiles[abs] !== undefined) {
141
230
  return;
142
231
  }
232
+ const hostPath = this._toHostPath(abs);
143
233
  try {
144
- nodeFs.chmodSync(abs, mode);
234
+ if (nodeFs.lstatSync(hostPath).isSymbolicLink()) {
235
+ return;
236
+ }
237
+ nodeFs.chmodSync(hostPath, mode);
145
238
  this._triggerChange();
146
- } catch (e) { /* ignore chmod errors on virtualized paths */ }
239
+ } catch (e) { /* ignore chmod errors */ }
147
240
  }
148
241
 
149
242
  getSize(path) {
150
243
  const abs = this.absolutePath(path);
151
244
  if (this._virtualFiles[abs] !== undefined) return 0;
245
+ const resolvedVirtual = this._resolveVirtualPath(abs);
246
+ const hostPath = this._toHostPath(resolvedVirtual);
152
247
  try {
153
- return nodeFs.statSync(abs).size;
248
+ return nodeFs.statSync(hostPath).size;
154
249
  } catch(e) {
155
250
  return 0;
156
251
  }
@@ -158,18 +253,24 @@ class NodeFileSystem extends BaseFileSystem {
158
253
 
159
254
  isSymlink(path) {
160
255
  const abs = this.absolutePath(path);
161
- try { return nodeFs.lstatSync(abs).isSymbolicLink(); } catch(e) { return false; }
256
+ const hostPath = this._toHostPath(abs);
257
+ try { return nodeFs.lstatSync(hostPath).isSymbolicLink(); } catch(e) { return false; }
162
258
  }
163
259
 
164
260
  readSymlink(path) {
165
261
  const abs = this.absolutePath(path);
166
- try { return nodeFs.readlinkSync(abs); } catch(e) { return null; }
262
+ const hostPath = this._toHostPath(abs);
263
+ try { return nodeFs.readlinkSync(hostPath); } catch(e) { return null; }
167
264
  }
168
265
 
169
266
  createSymlink(target, linkPath) {
170
267
  const abs = this.absolutePath(linkPath);
171
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
172
- nodeFs.symlinkSync(target, abs);
268
+ const hostPath = this._toHostPath(abs);
269
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
270
+ try {
271
+ nodeFs.unlinkSync(hostPath);
272
+ } catch (_) {}
273
+ nodeFs.symlinkSync(target, hostPath);
173
274
  this._triggerChange();
174
275
  }
175
276
 
@@ -192,10 +293,11 @@ class NodeFileSystem extends BaseFileSystem {
192
293
  const parts = abs.split('/');
193
294
  const end = parts.pop();
194
295
  const dirPath = parts.join('/') || '/';
296
+ const hostDirPath = this._toHostPath(dirPath);
195
297
 
196
298
  let dirEntries = [];
197
299
  try {
198
- dirEntries = nodeFs.readdirSync(dirPath);
300
+ dirEntries = nodeFs.readdirSync(hostDirPath);
199
301
  } catch(e) { /* not readable */ }
200
302
 
201
303
  const prefix = dirPath === '/' ? '/' : dirPath + '/';
@@ -224,10 +326,11 @@ class NodeFileSystem extends BaseFileSystem {
224
326
  return {
225
327
  path: initialParts.length ? initialParts.join('/') : null,
226
328
  options: options.map(name => {
227
- const fullPath = nodePath.join(dirPath, name);
228
- if (this._virtualFiles[fullPath] !== undefined) return name;
329
+ const fullVirtual = nodePath.posix.join(dirPath, name);
330
+ if (this._virtualFiles[fullVirtual] !== undefined) return name;
229
331
  try {
230
- return nodeFs.statSync(fullPath).isDirectory() ? name + '/' : name;
332
+ const fullHost = this._toHostPath(fullVirtual);
333
+ return nodeFs.statSync(fullHost).isDirectory() ? name + '/' : name;
231
334
  } catch(e) { return name; }
232
335
  })
233
336
  };
@@ -245,17 +348,48 @@ class NodeFileSystem extends BaseFileSystem {
245
348
  exists(path) {
246
349
  const abs = this.absolutePath(path);
247
350
  if (this._virtualFiles[abs] !== undefined) return true;
248
- try { nodeFs.statSync(abs); return true; } catch(e) { return false; }
351
+ const hostPath = this._toHostPath(abs);
352
+ try {
353
+ if (nodeFs.lstatSync(hostPath).isSymbolicLink()) {
354
+ const resolvedVirtual = this._resolveVirtualPath(abs);
355
+ const resolvedHost = this._toHostPath(resolvedVirtual);
356
+ return nodeFs.existsSync(resolvedHost);
357
+ }
358
+ return nodeFs.existsSync(hostPath);
359
+ } catch(e) { return false; }
360
+ }
361
+
362
+ loadModule(path) {
363
+ const abs = this.absolutePath(path);
364
+ if (this._virtualFiles[abs] !== undefined) {
365
+ const v = this._virtualFiles[abs];
366
+ if (typeof v === 'function') return v;
367
+ return super.loadModule(path);
368
+ }
369
+ const hostPath = this._toHostPath(abs);
370
+ try {
371
+ const mod = require(hostPath);
372
+ return mod && mod.default !== undefined ? mod.default : mod;
373
+ } catch (err) {
374
+ return super.loadModule(path);
375
+ }
249
376
  }
250
377
 
251
378
  stat(path) {
252
379
  const abs = this.absolutePath(path);
253
380
  if (this._virtualFiles[abs] !== undefined) {
254
381
  const v = this._virtualFiles[abs];
255
- return { isDirectory: v !== null && v !== undefined && v.constructor === Object, isFile: typeof v === 'string' || v instanceof Uint8Array, isCommand: typeof v === 'function', isBinary: v instanceof Uint8Array };
382
+ return {
383
+ isDirectory: v !== null && v !== undefined && v.constructor === Object,
384
+ isFile: typeof v === 'string' || v instanceof Uint8Array,
385
+ isCommand: typeof v === 'function',
386
+ isBinary: v instanceof Uint8Array
387
+ };
256
388
  }
389
+ const resolvedVirtual = this._resolveVirtualPath(abs);
390
+ const hostPath = this._toHostPath(resolvedVirtual);
257
391
  try {
258
- const s = nodeFs.statSync(abs);
392
+ const s = nodeFs.statSync(hostPath);
259
393
  return { isDirectory: s.isDirectory(), isFile: s.isFile(), isCommand: false };
260
394
  } catch(e) { return null; }
261
395
  }
package/lib/Readme.md CHANGED
@@ -55,6 +55,7 @@ When `get requiresFilesystem() { return true; }` is set on a command, `this.fs`
55
55
  * `exists(path)` / `stat(path)` / `getSize(path)` / `absolutePath(path)`
56
56
  * `getMode(path)` / `setMode(path, mode)` / `isReadable(path)` / `isWritable(path)` / `isExecutable(path)`
57
57
  * `isSymlink(path)` / `readSymlink(path)` / `createSymlink(target, linkPath)`
58
+ * `loadModule(path)` — evaluates a JS module from the filesystem (virtual evaluation on `FileSystem`, native `require()` on `NodeFileSystem`)
58
59
 
59
60
  ---
60
61
 
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const LocalCommand = require('./local/LocalCommand');
4
+ const { parseVtKeys, hasCustomStdinListener } = require('./TtyStream');
4
5
 
5
6
  /**
6
7
  * Returns true if the first line of a file is a shebang for a known/supported
@@ -18,12 +19,46 @@ class ScriptCommand extends LocalCommand {
18
19
  }
19
20
 
20
21
  // Only capture input when the sandbox itself has a command waiting for it
21
- // (e.g. an active `read`). This prevents swallowing keystrokes during
22
- // normal command execution.
22
+ // (e.g. an active `read` or interactive TUI/WASM app). This prevents swallowing
23
+ // keystrokes during normal non-interactive command execution.
23
24
  get captureInput() {
25
+ if (!this.sandbox || !this.sandbox.runningCommand) return false;
26
+ const child = this.sandbox.runningCommand;
27
+ return Boolean(
28
+ child.captureInput
29
+ || child.interactive
30
+ || child._inAltScreen
31
+ || hasCustomStdinListener(child)
32
+ );
33
+ }
34
+
35
+ get interactive() {
24
36
  return !!(this.sandbox
25
37
  && this.sandbox.runningCommand
26
- && this.sandbox.runningCommand.captureInput);
38
+ && this.sandbox.runningCommand.interactive);
39
+ }
40
+
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
+ );
49
+ }
50
+
51
+ get _inAltScreen() {
52
+ return Boolean(
53
+ this.__inAltScreen ||
54
+ (this.sandbox
55
+ && this.sandbox.runningCommand
56
+ && this.sandbox.runningCommand._inAltScreen)
57
+ );
58
+ }
59
+
60
+ set _inAltScreen(val) {
61
+ this.__inAltScreen = Boolean(val);
27
62
  }
28
63
 
29
64
  onInput(char) {
@@ -43,7 +78,9 @@ class ScriptCommand extends LocalCommand {
43
78
  }
44
79
 
45
80
  run() {
46
- const fs = (this.context && this.context.fs) || this.fs;
81
+ this._managesOwnStdinCapture = true;
82
+ const rawRef = (this.context && this.context.fs) || this.fs;
83
+ const fs = (rawRef && rawRef[Symbol.for('brsh.fs.target')]) || rawRef;
47
84
  const fsOpts = fs && fs.isRealFilesystem
48
85
  ? { useRealFilesystem: true }
49
86
  : { filesystem: (fs && fs.getRaw()) || {}, permissions: (fs && fs.getRawPermissions()) || {} };
@@ -54,6 +91,18 @@ class ScriptCommand extends LocalCommand {
54
91
  });
55
92
  this.sandbox.context.source(this.context);
56
93
 
94
+ const cols = (this.stdout && this.stdout.columns)
95
+ || (this.stdinStream && this.stdinStream.columns)
96
+ || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10))
97
+ || 80;
98
+ const rows = (this.stdout && this.stdout.rows)
99
+ || (this.stdinStream && this.stdinStream.rows)
100
+ || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10))
101
+ || 24;
102
+ if (typeof this.sandbox.setTerminalSize === 'function') {
103
+ this.sandbox.setTerminalSize(cols, rows);
104
+ }
105
+
57
106
  if (Array.isArray(this.arguments)) {
58
107
  this.arguments.forEach((arg, i) =>
59
108
  this.sandbox.context.setVar(String(i + 1), arg));
@@ -62,8 +111,85 @@ class ScriptCommand extends LocalCommand {
62
111
  this.sandbox.context.setVar('*', this.arguments.join(' '));
63
112
  }
64
113
 
114
+ // Remove default Command.js parsed keystroke listener so raw TTY chunks pass cleanly
115
+ // to interactive WASM/TUI child commands without double-firing onInput
116
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
117
+ this.stdinStream.off('data', this._onStdinStreamData);
118
+ }
119
+
120
+ const onParentStdin = (chunk) => {
121
+ if (!this.sandbox || !this.sandbox.runningCommand) return;
122
+ const child = this.sandbox.runningCommand;
123
+ const hasStreamListeners = hasCustomStdinListener(child);
124
+ if (child.interactive || child._inAltScreen || hasStreamListeners) {
125
+ if (child.stdinStream) {
126
+ child.stdinStream.pushData(chunk);
127
+ }
128
+ return;
129
+ }
130
+ if (child.captureInput && typeof child.onInput === 'function') {
131
+ const childIsRaw = Boolean(child.isRaw || (child.stdinStream && child.stdinStream.isRaw));
132
+ for (const k of parseVtKeys(chunk)) {
133
+ if (k === '^C' && !childIsRaw) {
134
+ this.kill('SIGINT');
135
+ return;
136
+ }
137
+ if (!childIsRaw) {
138
+ if (k === 'Enter') this.stdout.write('\r\n');
139
+ else if (k === 'Backspace') this.stdout.write('\b \b');
140
+ else if (k.length === 1) this.stdout.write(k);
141
+ }
142
+ child.onInput(k);
143
+ }
144
+ }
145
+ };
146
+
147
+ const onParentStdinResize = () => {
148
+ if (this.sandbox && typeof this.sandbox.setTerminalSize === 'function' && this.stdinStream) {
149
+ this.sandbox.setTerminalSize(this.stdinStream.columns, this.stdinStream.rows);
150
+ }
151
+ };
152
+
153
+ const onParentStdoutResize = () => {
154
+ if (this.sandbox && typeof this.sandbox.setTerminalSize === 'function' && this.stdout) {
155
+ this.sandbox.setTerminalSize(this.stdout.columns, this.stdout.rows);
156
+ }
157
+ };
158
+
159
+ const cleanupListeners = () => {
160
+ if (this.stdinStream && typeof this.stdinStream.off === 'function') {
161
+ this.stdinStream.off('data', onParentStdin);
162
+ this.stdinStream.off('resize', onParentStdinResize);
163
+ }
164
+ if (this.stdout && typeof this.stdout.off === 'function') {
165
+ this.stdout.off('resize', onParentStdoutResize);
166
+ }
167
+ };
168
+
169
+ if (this.stdinStream && typeof this.stdinStream.on === 'function') {
170
+ this.stdinStream.on('data', onParentStdin);
171
+ this.stdinStream.on('resize', onParentStdinResize);
172
+ }
173
+ if (this.stdout && this.stdout !== this.stdinStream && typeof this.stdout.on === 'function') {
174
+ this.stdout.on('resize', onParentStdoutResize);
175
+ }
176
+
65
177
  this.sandbox.on('stdOut', data => { this.stdOut = data; this.flush(); });
66
178
  this.sandbox.on('stdErr', data => { this.stdErr = data; this.flush(); });
179
+ if (this.sandbox.stdout && typeof this.sandbox.stdout.on === 'function') {
180
+ this.sandbox.stdout.on('data', chunk => {
181
+ if (this.stdout && typeof this.stdout.write === 'function') {
182
+ this.stdout.write(chunk);
183
+ }
184
+ });
185
+ }
186
+ if (this.sandbox.stderr && typeof this.sandbox.stderr.on === 'function') {
187
+ this.sandbox.stderr.on('data', chunk => {
188
+ if (this.stderr && typeof this.stderr.write === 'function') {
189
+ this.stderr.write(chunk);
190
+ }
191
+ });
192
+ }
67
193
 
68
194
  this._scriptFunctions = {};
69
195
 
@@ -73,6 +199,7 @@ class ScriptCommand extends LocalCommand {
73
199
  const interpreter = lines[0].startsWith('#!')
74
200
  ? lines[0].slice(2).split(/\s/)[0]
75
201
  : lines[0];
202
+ cleanupListeners();
76
203
  return Promise.reject(`${interpreter}: bad interpreter: No such file or directory`);
77
204
  }
78
205
 
@@ -90,6 +217,9 @@ class ScriptCommand extends LocalCommand {
90
217
  return Promise.reject(e);
91
218
  }
92
219
  })
220
+ .finally(() => {
221
+ cleanupListeners();
222
+ })
93
223
  .then(() => {
94
224
  this.exitCode = this.sandbox.lastCode;
95
225
  if(this.source) {
@@ -457,9 +587,17 @@ class ScriptCommand extends LocalCommand {
457
587
  }
458
588
 
459
589
  async _executeFor(node) {
460
- const expanded = node.list.replace(/\${?([\w\d]+)}?/g, (m, name) =>
461
- this.sandbox.context.getVar(name) || '');
462
- const items = expanded.split(/\s+/).filter(Boolean);
590
+ let items;
591
+ if (node.list.trim() === '"$@"') {
592
+ const count = parseInt(this.sandbox.context.getVar('#') || '0', 10);
593
+ items = [];
594
+ for (let idx = 1; idx <= count; idx++) {
595
+ items.push(this.sandbox.context.getVar(String(idx)) || '');
596
+ }
597
+ } else {
598
+ const expanded = await this.sandbox._replaceVariables(node.list);
599
+ items = expanded.split(/\s+/).filter(Boolean);
600
+ }
463
601
  for (const value of items) {
464
602
  this.sandbox.context.setVar(node.variable, value);
465
603
  try {
@@ -579,7 +717,9 @@ class ScriptCommand extends LocalCommand {
579
717
  ? expanded.slice(1, -1) : expanded;
580
718
 
581
719
  for (const clause of node.clauses) {
582
- if (this._matchPattern(clause.pattern, value)) {
720
+ const cleaned = clause.pattern.replace(/^\(\s*/, '');
721
+ const alternatives = cleaned.split('|').map(p => p.trim());
722
+ if (alternatives.some(alt => this._matchPattern(alt, value))) {
583
723
  return this._executeNodes(this._parseLines(clause.bodyLines));
584
724
  }
585
725
  }