brsh 3.8.0 → 3.9.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
@@ -142,6 +142,13 @@ class Shell extends EventEmitter {
142
142
  this._initializing = false;
143
143
  }
144
144
  }
145
+
146
+ if (this.context.fs && typeof this.context.fs.setTtyDevice === 'function') {
147
+ this.context.fs.setTtyDevice({
148
+ write: (chunk) => this.stdout.write(chunk),
149
+ read: () => ''
150
+ });
151
+ }
145
152
  }
146
153
 
147
154
  async _initAsyncFilesystem(filesystemSource, permissions, cwd) {
@@ -188,6 +195,12 @@ class Shell extends EventEmitter {
188
195
  if (savedOnChange && this.context.fs) {
189
196
  this.context.fs._onChange = () => savedOnChange(this.context.fs.getRaw(), this.context.fs.getRawPermissions());
190
197
  }
198
+ if (this.context.fs && typeof this.context.fs.setTtyDevice === 'function') {
199
+ this.context.fs.setTtyDevice({
200
+ write: (chunk) => this.stdout.write(chunk),
201
+ read: () => ''
202
+ });
203
+ }
191
204
  } catch (err) {
192
205
  this.emit('stdErr', err.message || String(err));
193
206
  } finally {
@@ -1000,6 +1013,20 @@ class Shell extends EventEmitter {
1000
1013
 
1001
1014
  if (this.runningCommand) {
1002
1015
  const cmd = this.runningCommand;
1016
+ const isCtrlC = (typeof raw === 'string' && raw === '\x03')
1017
+ || (raw instanceof Uint8Array && raw.length === 1 && raw[0] === 3)
1018
+ || ((typeof Buffer !== 'undefined' && Buffer.isBuffer(raw)) && raw.length === 1 && raw[0] === 3);
1019
+
1020
+ if (isCtrlC && (!cmd.stdinStream || !cmd.stdinStream.isRaw)) {
1021
+ if (typeof cmd.kill === 'function') {
1022
+ cmd.kill('SIGINT');
1023
+ }
1024
+ if (!cmd.interactive && !cmd._inAltScreen) {
1025
+ this.stdout.write('^C\r\n');
1026
+ }
1027
+ return;
1028
+ }
1029
+
1003
1030
  const hasStreamListeners = cmd.stdinStream && cmd.stdinStream.listenerCount('data') > 1;
1004
1031
  if (cmd.captureInput || cmd.interactive || cmd._inAltScreen || hasStreamListeners) {
1005
1032
  cmd.stdinStream.pushData(raw);
@@ -10,6 +10,7 @@ const SANDBOX_ALLOWED = new Set([
10
10
  'isReadable', 'isWritable', 'isExecutable',
11
11
  'getSize', 'autoComplete',
12
12
  'isRealFilesystem', 'isSymlink', 'readSymlink', 'createSymlink',
13
+ 'setTtyDevice',
13
14
  ]);
14
15
 
15
16
  /**
@@ -118,6 +119,25 @@ class SymlinkRef {
118
119
  }
119
120
  }
120
121
 
122
+ /**
123
+ * Represents a virtual character device node (e.g. /dev/null, /dev/zero, /dev/urandom, /dev/tty).
124
+ */
125
+ class DeviceFile {
126
+ constructor(name, options = {}) {
127
+ this.name = name;
128
+ this.read = typeof options.read === 'function' ? options.read : (() => '');
129
+ this.write = typeof options.write === 'function' ? options.write : (() => {});
130
+ this.mode = options.mode !== undefined ? options.mode : 0o666;
131
+ this.isCharacterDevice = true;
132
+ }
133
+
134
+ toString() {
135
+ const val = this.read();
136
+ return val != null ? (typeof val === 'string' ? val : val.toString()) : '';
137
+ }
138
+ }
139
+
121
140
  module.exports = BaseFileSystem;
122
141
  module.exports.BinaryFile = BinaryFile;
123
142
  module.exports.SymlinkRef = SymlinkRef;
143
+ module.exports.DeviceFile = DeviceFile;
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { BinaryFile, SymlinkRef } = require('./BaseFileSystem');
3
+ const { BinaryFile, SymlinkRef, DeviceFile } = require('./BaseFileSystem');
4
4
 
5
5
  // 4-byte magic: "BRFS" (0x42, 0x52, 0x46, 0x53)
6
6
  const MAGIC = new Uint8Array([0x42, 0x52, 0x46, 0x53]);
@@ -63,6 +63,11 @@ function serializeBinaryFilesystem(filesystem = {}, permissions = {}, options =
63
63
  return { $l: node.target };
64
64
  }
65
65
 
66
+ if (node instanceof DeviceFile) {
67
+ // Devices are in-memory virtual overlays and must never be persisted
68
+ return null;
69
+ }
70
+
66
71
  if (node instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(node))) {
67
72
  const u8 = node instanceof Uint8Array
68
73
  ? new Uint8Array(node.buffer, node.byteOffset, node.byteLength)
@@ -225,6 +230,10 @@ function deserializeBinaryFilesystem(input, customCommandMap = {}) {
225
230
  return new SymlinkRef(entry.$l);
226
231
  }
227
232
 
233
+ if ('$dev' in entry) {
234
+ return new DeviceFile(entry.$dev);
235
+ }
236
+
228
237
  if ('$c' in entry) {
229
238
  const cmdPath = entry.$c;
230
239
  if (bundledCommands[cmdPath]) {
package/lib/Command.js CHANGED
@@ -29,10 +29,14 @@ class Command extends EventEmitter {
29
29
  onWrite: (chunk) => this.emit('stderr', chunk)
30
30
  });
31
31
 
32
- this.stdinStream.on('data', (chunk) => {
32
+ this._onStdinStreamData = (chunk) => {
33
33
  if (!this.captureInput) return;
34
34
  const keys = parseVtKeys(chunk);
35
35
  for (const k of keys) {
36
+ if (k === '^C') {
37
+ this.kill('SIGINT');
38
+ return;
39
+ }
36
40
  if (!this.interactive && !this.stdinStream.isRaw) {
37
41
  if (k === 'Enter') this.stdout.write('\r\n');
38
42
  else if (k === 'Backspace') this.stdout.write('\b \b');
@@ -40,7 +44,8 @@ class Command extends EventEmitter {
40
44
  }
41
45
  this.onInput(k);
42
46
  }
43
- });
47
+ };
48
+ this.stdinStream.on('data', this._onStdinStreamData);
44
49
  }
45
50
 
46
51
  get name() {
@@ -51,28 +56,66 @@ class Command extends EventEmitter {
51
56
  return Promise.reject("Command not implemented...");
52
57
  }
53
58
 
59
+ kill(signal = 'SIGINT') {
60
+ const sigNames = {
61
+ 'SIGHUP': 129,
62
+ 'SIGINT': 130,
63
+ 'SIGQUIT': 131,
64
+ 'SIGKILL': 137,
65
+ 'SIGTERM': 143,
66
+ 'SIGWINCH': 156,
67
+ };
68
+ const code = (typeof signal === 'number') ? signal : (sigNames[signal] || 130);
69
+ this.exitCode = code;
70
+ this.emit('signal', signal);
71
+ if (signal === 'SIGINT' || signal === 'SIGTERM' || signal === 'SIGKILL' || signal === 'SIGQUIT') {
72
+ this.emit('abort');
73
+ if (this._abortController) {
74
+ this._abortController.abort();
75
+ }
76
+ }
77
+ }
78
+
54
79
  runCommand() {
55
- return Promise.resolve()
56
- .then(() => this.run())
57
- .then(d => {
58
- if(d) {
59
- d.split(/\r?\n/).forEach(line => this.stdOut = line);
60
- }
61
- return this.result;
62
- })
63
- .catch(e => {
64
- // Re-throw shell control-flow signals (break, continue, return,
65
- // errexit) so they propagate correctly through function calls
66
- // and nested script execution.
67
- if (e && e.__type) {
68
- throw e;
69
- }
70
- if(e) {
71
- this.stdErr = e.message || e;
72
- }
73
- this.exitCode = 127;
74
- return this.result;
75
- });
80
+ return new Promise((resolve) => {
81
+ let settled = false;
82
+ const onAbort = () => {
83
+ if (settled) return;
84
+ settled = true;
85
+ resolve(this.result);
86
+ };
87
+ this.once('abort', onAbort);
88
+
89
+ Promise.resolve()
90
+ .then(() => this.run())
91
+ .then(d => {
92
+ if (settled) return;
93
+ settled = true;
94
+ this.removeListener('abort', onAbort);
95
+ if(d) {
96
+ d.split(/\r?\n/).forEach(line => this.stdOut = line);
97
+ }
98
+ resolve(this.result);
99
+ })
100
+ .catch(e => {
101
+ if (settled) return;
102
+ settled = true;
103
+ this.removeListener('abort', onAbort);
104
+ // Re-throw shell control-flow signals (break, continue, return,
105
+ // errexit) so they propagate correctly through function calls
106
+ // and nested script execution.
107
+ if (e && e.__type) {
108
+ throw e;
109
+ }
110
+ if(e) {
111
+ this.stdErr = e.message || e;
112
+ }
113
+ if (this.result.getExitCode() === 0) {
114
+ this.exitCode = 127;
115
+ }
116
+ resolve(this.result);
117
+ });
118
+ });
76
119
  }
77
120
 
78
121
  onInput(char) {
package/lib/FileSystem.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const BaseFileSystem = require('./BaseFileSystem');
4
- const { BinaryFile, SymlinkRef } = BaseFileSystem;
4
+ const { BinaryFile, SymlinkRef, DeviceFile } = BaseFileSystem;
5
5
 
6
6
  /**
7
7
  * Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
@@ -12,7 +12,7 @@ const { BinaryFile, SymlinkRef } = BaseFileSystem;
12
12
  function decodeBinaryFiles(node) {
13
13
  for (const key of Object.keys(node)) {
14
14
  const value = node[key];
15
- if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef)) {
15
+ if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef) && !(value instanceof DeviceFile)) {
16
16
  decodeBinaryFiles(value);
17
17
  } else if (typeof value === 'string' && value.startsWith('data:')) {
18
18
  const semicolon = value.indexOf(';');
@@ -58,6 +58,63 @@ class FileSystem extends BaseFileSystem {
58
58
  this.cwd = cwd.endsWith('/') ? cwd : (cwd + '/');
59
59
  this._onChange = onChange;
60
60
  this._changeScheduled = false;
61
+ this._initDevices();
62
+ }
63
+
64
+ _initDevices() {
65
+ this._devices = {};
66
+ const dev = this._devices;
67
+ dev.null = new DeviceFile('null', { read: () => '', write: () => {} });
68
+ dev.zero = new DeviceFile('zero', {
69
+ read: () => new Uint8Array(4096),
70
+ write: () => {}
71
+ });
72
+ dev.urandom = new DeviceFile('urandom', {
73
+ read: () => {
74
+ const buf = new Uint8Array(256);
75
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
76
+ crypto.getRandomValues(buf);
77
+ } else {
78
+ for (let i = 0; i < buf.length; i++) buf[i] = Math.floor(Math.random() * 256);
79
+ }
80
+ return buf;
81
+ },
82
+ write: () => {}
83
+ });
84
+ dev.random = dev.urandom;
85
+ dev.tty = new DeviceFile('tty', {
86
+ read: () => '',
87
+ write: () => {}
88
+ });
89
+ dev.stdin = new SymlinkRef('/dev/tty');
90
+ dev.stdout = new SymlinkRef('/dev/tty');
91
+ dev.stderr = new SymlinkRef('/dev/tty');
92
+ }
93
+
94
+ _getDevDir() {
95
+ if (!this._devices) this._initDevices();
96
+ if (this.fileSystem && this.fileSystem.dev && typeof this.fileSystem.dev === 'object' && !(this.fileSystem.dev instanceof SymlinkRef) && !(this.fileSystem.dev instanceof Uint8Array)) {
97
+ return Object.assign({}, this.fileSystem.dev, this._devices);
98
+ }
99
+ return this._devices;
100
+ }
101
+
102
+ _getRootOverlay() {
103
+ const root = Object.assign({}, this.fileSystem);
104
+ root.dev = this._getDevDir();
105
+ return root;
106
+ }
107
+
108
+ setTtyDevice(options = {}) {
109
+ if (!this._devices) this._initDevices();
110
+ this._devices.tty = new DeviceFile('tty', {
111
+ read: options.read || (() => ''),
112
+ write: options.write || (() => {}),
113
+ mode: 0o666
114
+ });
115
+ this._devices.stdin = new SymlinkRef('/dev/tty');
116
+ this._devices.stdout = new SymlinkRef('/dev/tty');
117
+ this._devices.stderr = new SymlinkRef('/dev/tty');
61
118
  }
62
119
 
63
120
  /**
@@ -82,12 +139,15 @@ class FileSystem extends BaseFileSystem {
82
139
  const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), true);
83
140
  if (file === null || file === undefined) return null;
84
141
  if (!this.isReadable(path)) return null;
142
+ if (file instanceof DeviceFile) return file.read();
85
143
  return file;
86
144
  }
87
145
 
88
146
  // Raw read bypassing permission checks — for internal/system use only.
89
147
  _getFileRaw(path) {
90
- return this._getFileByAbsolutePath(this._pathToAbsolute(path));
148
+ const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
149
+ if (file instanceof DeviceFile) return file.read();
150
+ return file;
91
151
  }
92
152
 
93
153
  // Returns true if the path exists (and for symlinks, the target resolves too).
@@ -114,7 +174,18 @@ class FileSystem extends BaseFileSystem {
114
174
  const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), false);
115
175
  if (file === null || file === undefined) return null;
116
176
  if (file instanceof SymlinkRef) {
117
- return { isDirectory: false, isFile: false, isCommand: false, isBinary: false, isSymlink: true };
177
+ return { isDirectory: false, isFile: false, isCommand: false, isBinary: false, isSymlink: true, isDevice: false, isCharacterDevice: false };
178
+ }
179
+ if (file instanceof DeviceFile) {
180
+ return {
181
+ isDirectory: false,
182
+ isFile: true,
183
+ isCommand: false,
184
+ isBinary: file.read() instanceof Uint8Array,
185
+ isSymlink: false,
186
+ isDevice: true,
187
+ isCharacterDevice: true,
188
+ };
118
189
  }
119
190
  return {
120
191
  isDirectory: file.constructor === Object,
@@ -122,6 +193,8 @@ class FileSystem extends BaseFileSystem {
122
193
  isCommand: typeof file === 'function',
123
194
  isBinary: file instanceof Uint8Array,
124
195
  isSymlink: false,
196
+ isDevice: false,
197
+ isCharacterDevice: false,
125
198
  };
126
199
  }
127
200
 
@@ -158,6 +231,11 @@ class FileSystem extends BaseFileSystem {
158
231
  const existing = this._getFileByAbsolutePath(absolute);
159
232
  if (existing !== null && existing !== undefined) {
160
233
  if (!this.isWritable(path)) throw new Error('Permission denied');
234
+ if (existing instanceof DeviceFile) {
235
+ existing.write(content);
236
+ this._triggerChange();
237
+ return;
238
+ }
161
239
  } else {
162
240
  const parentParts = absolute.split('/');
163
241
  parentParts.pop();
@@ -181,6 +259,28 @@ class FileSystem extends BaseFileSystem {
181
259
  parts.shift();
182
260
  const filename = parts.pop();
183
261
 
262
+ if (parts.length > 0 && parts[0] === 'dev') {
263
+ let dir = this._getDevDir();
264
+ const devParts = parts.slice(1);
265
+ for (const handle of devParts) {
266
+ if (!Object.prototype.hasOwnProperty.call(dir, handle)) {
267
+ if (!createDir) throw new Error(`${handle}: No such file or directory`);
268
+ dir[handle] = {};
269
+ }
270
+ dir = dir[handle];
271
+ }
272
+ if (dir[filename] instanceof DeviceFile) {
273
+ dir[filename].write(content);
274
+ return;
275
+ }
276
+ dir[filename] = content;
277
+ return;
278
+ }
279
+
280
+ if (parts.length === 0 && filename === 'dev') {
281
+ throw new Error('dev: File exists');
282
+ }
283
+
184
284
  let dir = this.fileSystem;
185
285
  const pathSoFar = [];
186
286
  for (const handle of parts) {
@@ -203,6 +303,10 @@ class FileSystem extends BaseFileSystem {
203
303
  }
204
304
  dir = next;
205
305
  }
306
+ if (dir[filename] instanceof DeviceFile) {
307
+ dir[filename].write(content);
308
+ return;
309
+ }
206
310
  dir[filename] = content;
207
311
  }
208
312
 
@@ -217,11 +321,22 @@ class FileSystem extends BaseFileSystem {
217
321
  parts.shift();
218
322
  if (parts.length > 0 && parts[parts.length - 1].length < 1) parts.pop();
219
323
 
324
+ if (parts.length === 0) {
325
+ return this._getRootOverlay();
326
+ }
327
+
220
328
  let pointer = this.fileSystem;
221
329
  const pathSoFar = [];
222
330
  for (let i = 0; i < parts.length; i++) {
223
331
  const handle = parts[i];
224
332
  const isLast = i === parts.length - 1;
333
+
334
+ if (i === 0 && handle === 'dev') {
335
+ pointer = this._getDevDir();
336
+ pathSoFar.push(handle);
337
+ continue;
338
+ }
339
+
225
340
  if (pointer == null || typeof pointer !== 'object' || pointer instanceof SymlinkRef) return null;
226
341
  if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
227
342
  pointer = pointer[handle];
@@ -242,10 +357,24 @@ class FileSystem extends BaseFileSystem {
242
357
  const parts = absolute.split('/');
243
358
  parts.shift();
244
359
 
245
- if(parts[parts.length - 1].length < 1) {
360
+ if (parts.length > 0 && parts[parts.length - 1].length < 1) {
246
361
  parts.pop();
247
362
  }
248
363
 
364
+ if (parts.length === 0) {
365
+ return this._getRootOverlay();
366
+ }
367
+
368
+ if (parts[0] === 'dev') {
369
+ let pointer = this._getDevDir();
370
+ for (let i = 1; i < parts.length; i++) {
371
+ if (pointer == null || typeof pointer !== 'object') return null;
372
+ if (!Object.prototype.hasOwnProperty.call(pointer, parts[i])) return null;
373
+ pointer = pointer[parts[i]];
374
+ }
375
+ return pointer;
376
+ }
377
+
249
378
  return parts.reduce((pointer, handle) => {
250
379
  if (pointer == null || typeof pointer !== 'object') return null;
251
380
  if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
@@ -282,6 +411,22 @@ class FileSystem extends BaseFileSystem {
282
411
  const filename = parts.pop();
283
412
  if (!filename) return;
284
413
 
414
+ if (parts.length > 0 && parts[0] === 'dev') {
415
+ let parent = this._getDevDir();
416
+ for (let i = 1; i < parts.length; i++) {
417
+ if (!parent || typeof parent !== 'object') return;
418
+ parent = parent[parts[i]];
419
+ }
420
+ if (parent && filename in parent) {
421
+ delete parent[filename];
422
+ }
423
+ return;
424
+ }
425
+
426
+ if (parts.length === 0 && filename === 'dev') {
427
+ return;
428
+ }
429
+
285
430
  let parent = this.fileSystem;
286
431
  const pathSoFar = [];
287
432
  for (const handle of parts) {
@@ -311,6 +456,7 @@ class FileSystem extends BaseFileSystem {
311
456
  }
312
457
  const file = this._resolveByAbsolutePath(absolute, true);
313
458
  if (file === null || file === undefined) return null;
459
+ if (file instanceof DeviceFile) return file.mode || 0o666;
314
460
  if (file.constructor === Object) return 0o755;
315
461
  if (typeof file === 'function') return 0o555;
316
462
  return 0o644;
@@ -326,6 +472,11 @@ class FileSystem extends BaseFileSystem {
326
472
  const absolute = this._pathToAbsolute(path);
327
473
  const file = this._resolveByAbsolutePath(absolute, true);
328
474
  if (file === null || file === undefined) return 0;
475
+ if (file instanceof DeviceFile) {
476
+ const val = file.read();
477
+ if (val instanceof Uint8Array) return val.length;
478
+ return typeof val === 'string' ? val.length : 0;
479
+ }
329
480
  if (file.constructor === Object) return JSON.stringify(file).length;
330
481
  if (file instanceof Uint8Array) return file.length;
331
482
  return file.toString().length;
@@ -65,6 +65,11 @@ class InteractiveCommand extends Command {
65
65
  if (this.stdout) this.stdout.write('\x1b[?1049l\x1b[?25h');
66
66
  }
67
67
 
68
+ kill(signal = 'SIGINT') {
69
+ this._exitAltScreen();
70
+ super.kill(signal);
71
+ }
72
+
68
73
  runCommand() {
69
74
  if (this.interactive) {
70
75
  this._enterAltScreen();
package/lib/Readme.md CHANGED
@@ -137,6 +137,7 @@ shell.context.setCommand(MyWasmTool);
137
137
 
138
138
  * For POSIX terminal raw mode, baud rates, and `TIOCGWINSZ`, use [**`wasi-termios-brsh`**](https://github.com/eliotstocker/wasi-termios-brsh).
139
139
  * For a complete real-world reference implementation of an interactive C TUI editor with ncurses targeting `brsh`, inspect [**`nano-wasm`**](https://github.com/eliotstocker/nano-wasm).
140
+ * For an interactive game loop with non-blocking event loops, clock sleeps, and 24-bit ANSI streaming, inspect [**`doom-wasm`**](https://github.com/eliotstocker/doom-wasm).
140
141
  * For complete step-by-step instructions on compiling with `wasi-sdk`, configuring `termios`, and instrumenting with `wasm-opt --asyncify`, see [Compiling C / C++ Applications in the main Readme](../Readme.md#compiling-c--c-applications-for-brsh).
141
142
 
142
143
 
@@ -32,6 +32,16 @@ class ScriptCommand extends LocalCommand {
32
32
  }
33
33
  }
34
34
 
35
+ kill(signal = 'SIGINT') {
36
+ if (this.sandbox && this.sandbox.runningCommand && typeof this.sandbox.runningCommand.kill === 'function') {
37
+ this.sandbox.runningCommand.kill(signal);
38
+ }
39
+ if (this.sandbox && typeof this.sandbox.destroy === 'function') {
40
+ this.sandbox.destroy(130);
41
+ }
42
+ super.kill(signal);
43
+ }
44
+
35
45
  run() {
36
46
  const fs = (this.context && this.context.fs) || this.fs;
37
47
  const fsOpts = fs && fs.isRealFilesystem
package/lib/TtyStream.js CHANGED
@@ -103,7 +103,12 @@ class TtyStream extends EventEmitter {
103
103
  if (typeof this._onWrite === 'function') {
104
104
  this._onWrite(chunk);
105
105
  }
106
- this.emit('data', this._formatChunk(chunk));
106
+ this._isPushing = true;
107
+ try {
108
+ this.emit('data', this._formatChunk(chunk));
109
+ } finally {
110
+ this._isPushing = false;
111
+ }
107
112
  if (typeof encoding === 'function') encoding();
108
113
  else if (typeof callback === 'function') callback();
109
114
  return true;
@@ -111,7 +116,12 @@ class TtyStream extends EventEmitter {
111
116
 
112
117
  pushData(chunk) {
113
118
  if (chunk == null) return;
114
- this.emit('data', this._formatChunk(chunk));
119
+ this._isPushing = true;
120
+ try {
121
+ this.emit('data', this._formatChunk(chunk));
122
+ } finally {
123
+ this._isPushing = false;
124
+ }
115
125
  }
116
126
 
117
127
  _formatChunk(chunk) {