brsh 3.10.0 → 3.10.2

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/lib/wbt/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const path = require('path');
4
- const LocalCommand = require('../local/LocalCommand');
4
+ const Command = require('../Command');
5
5
  const WasmCommand = require('../WasmCommand');
6
6
  const ReplCommand = require('../ReplCommand');
7
7
  const { DEFAULT_REGISTRY, resolvePackageName } = require('./registry');
@@ -55,11 +55,58 @@ function createCustomWasmBinCommand(binName, wasmPath, pkgMeta = {}) {
55
55
  * const CustomWbt = Wbt.configure({ registry: { ... } });
56
56
  * shell.context.setCommand(CustomWbt);
57
57
  */
58
- class Wbt extends LocalCommand {
58
+ class Wbt extends Command {
59
59
  static get name() { return 'wbt'; }
60
60
  get name() { return 'wbt'; }
61
61
  get requiresFilesystem() { return true; }
62
62
 
63
+ get _fs() {
64
+ return this.fs || (this.context && this.context.fs) || null;
65
+ }
66
+
67
+ get _pathDir() {
68
+ return (this.context && typeof this.context.getVar === 'function' && this.context.getVar('PATH')) || '/bin';
69
+ }
70
+
71
+ _withWritableParent(targetPath, fn) {
72
+ const fs = this._fs;
73
+ if (!fs) return;
74
+ const abs = typeof fs.absolutePath === 'function' ? fs.absolutePath(targetPath) : targetPath;
75
+ const parts = abs.split('/');
76
+ parts.pop();
77
+ const parentPath = parts.join('/') || '/';
78
+ const parentMode = typeof fs.getMode === 'function' ? fs.getMode(parentPath) : null;
79
+ const needsChmod = parentMode !== null && (parentMode & 0o200) === 0;
80
+ if (needsChmod) {
81
+ try { fs.setMode(parentPath, parentMode | 0o200); } catch { /* ignore */ }
82
+ }
83
+ try {
84
+ return fn(fs);
85
+ } finally {
86
+ if (needsChmod) {
87
+ try { fs.setMode(parentPath, parentMode); } catch { /* ignore */ }
88
+ }
89
+ }
90
+ }
91
+
92
+ _writeFileSafe(targetPath, content) {
93
+ this._withWritableParent(targetPath, (fs) => {
94
+ if (fs.exists(targetPath)) {
95
+ try { fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
96
+ }
97
+ fs.setFileByPath(targetPath, content, true);
98
+ });
99
+ }
100
+
101
+ _writeBytesSafe(targetPath, bytes, mimeType = 'application/wasm') {
102
+ this._withWritableParent(targetPath, (fs) => {
103
+ if (fs.exists(targetPath)) {
104
+ try { fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
105
+ }
106
+ writeBytesToFs(fs, targetPath, bytes, mimeType);
107
+ });
108
+ }
109
+
63
110
  get interactive() {
64
111
  if (this._activeSubCommand && this._activeSubCommand.interactive !== undefined) {
65
112
  return Boolean(this._activeSubCommand.interactive);
@@ -82,6 +129,13 @@ class Wbt extends LocalCommand {
82
129
  return this.interactive;
83
130
  }
84
131
 
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
+ );
137
+ }
138
+
85
139
  onInput(key) {
86
140
  if (this._activeSubCommand && typeof this._activeSubCommand.onInput === 'function') {
87
141
  this._activeSubCommand.onInput(key);
@@ -128,7 +182,8 @@ class Wbt extends LocalCommand {
128
182
  const cfg = this.constructor._config || {};
129
183
  const base = Object.assign({}, DEFAULT_REGISTRY, cfg.registry || {});
130
184
  try {
131
- const cachedRemote = this.context.fs._getFileRaw(`${CACHE_DIR}/remote-registry.json`);
185
+ const fs = this._fs;
186
+ const cachedRemote = fs ? fs.getFileByPath(`${CACHE_DIR}/remote-registry.json`) : null;
132
187
  if (typeof cachedRemote === 'string' && cachedRemote.trim()) {
133
188
  const parsed = JSON.parse(cachedRemote);
134
189
  Object.assign(base, parsed);
@@ -141,7 +196,9 @@ class Wbt extends LocalCommand {
141
196
 
142
197
  _getInstalledPackages() {
143
198
  const pkgs = {};
144
- const usrLib = this.context.fs.getFileByPath('/usr/lib');
199
+ const fs = this._fs;
200
+ if (!fs) return pkgs;
201
+ const usrLib = fs.getFileByPath('/usr/lib');
145
202
  if (!usrLib || typeof usrLib !== 'object') {
146
203
  return pkgs;
147
204
  }
@@ -151,10 +208,10 @@ class Wbt extends LocalCommand {
151
208
  if (dirName.startsWith('.')) continue;
152
209
  const pkgName = dirName.toLowerCase();
153
210
  const reg = registry[pkgName] || Object.values(registry).find(p => p.name === pkgName || p.bin === pkgName);
154
- const dirFiles = this.context.fs.getFileByPath(`/usr/lib/${dirName}`) || {};
211
+ const dirFiles = fs.getFileByPath(`/usr/lib/${dirName}`) || {};
155
212
  const files = (typeof dirFiles === 'object') ? Object.keys(dirFiles) : [];
156
213
  const wasmFile = files.find(f => f.endsWith('.wasm') || f.endsWith('.wat'));
157
- const wasmPath = wasmFile ? `/usr/lib/${dirName}/${wasmFile}` : (this.context.fs.exists(`/usr/lib/${dirName}/${pkgName}.wasm`) ? `/usr/lib/${dirName}/${pkgName}.wasm` : null);
214
+ const wasmPath = wasmFile ? `/usr/lib/${dirName}/${wasmFile}` : (fs.exists(`/usr/lib/${dirName}/${pkgName}.wasm`) ? `/usr/lib/${dirName}/${pkgName}.wasm` : null);
158
215
 
159
216
  const primaryBin = (reg && reg.bin) || pkgName;
160
217
  const bins = [primaryBin];
@@ -202,14 +259,14 @@ class Wbt extends LocalCommand {
202
259
  if (pkgMeta.repl) {
203
260
  return `'use strict';\n` +
204
261
  `const pkgMeta = ${serializedMeta};\n` +
205
- `const ReplCommand = typeof require !== 'undefined' ? require('brsh/ReplCommand') : globalThis.ReplCommand;\n` +
206
- `module.exports = ReplCommand.createReplWasmCommand(pkgMeta, {}, ${JSON.stringify(binName)});\n`;
262
+ `const _Repl = typeof ReplCommand !== 'undefined' ? ReplCommand : (typeof require !== 'undefined' ? require('brsh/ReplCommand') : globalThis.ReplCommand);\n` +
263
+ `module.exports = _Repl.createReplWasmCommand(pkgMeta, {}, ${JSON.stringify(binName)});\n`;
207
264
  }
208
265
 
209
266
  return `'use strict';\n` +
210
267
  `const pkgMeta = ${serializedMeta};\n` +
211
- `const WasmCommand = typeof require !== 'undefined' ? require('brsh/WasmCommand') : globalThis.WasmCommand;\n` +
212
- `module.exports = WasmCommand.createGenericWasmCommand(pkgMeta, {}, ${JSON.stringify(binName)});\n`;
268
+ `const _Wasm = typeof WasmCommand !== 'undefined' ? WasmCommand : (typeof require !== 'undefined' ? require('brsh/WasmCommand') : globalThis.WasmCommand);\n` +
269
+ `module.exports = _Wasm.createGenericWasmCommand(pkgMeta, {}, ${JSON.stringify(binName)});\n`;
213
270
  }
214
271
 
215
272
  _buildCommandsForPackage(pkgMeta) {
@@ -252,15 +309,24 @@ class Wbt extends LocalCommand {
252
309
  }
253
310
 
254
311
  _registerPackageIntoContext(pkgMeta) {
255
- const pathDir = this.context.getVar('PATH') || '/bin';
312
+ const fs = this._fs;
313
+ const cfg = this.constructor._config || {};
314
+ const pathDir = this._pathDir;
256
315
  const pkgName = (pkgMeta.name || '').split('/').pop().toLowerCase();
257
316
  const primaryBin = (pkgMeta.bin || pkgName).toLowerCase();
258
317
  const targetDir = `/usr/lib/${pkgName}`;
259
318
  const entries = this._buildCommandsForPackage(pkgMeta);
260
319
  const installedBins = [];
320
+ const adapterKey = pkgMeta.adapter || pkgMeta.name;
321
+ const hasRuntimeClosure = Boolean(
322
+ cfg.moduleLoader
323
+ || cfg.fetch
324
+ || adapterKey === 'wllama'
325
+ || (this.constructor._adapters && this.constructor._adapters.has(adapterKey))
326
+ );
261
327
 
262
328
  // Check if pure wasm exists at targetDir
263
- const wasmPath = pkgMeta.wasmPath || (this.context.fs.exists(`${targetDir}/${primaryBin}.wasm`) ? `${targetDir}/${primaryBin}.wasm` : null);
329
+ const wasmPath = pkgMeta.wasmPath || (fs.exists(`${targetDir}/${primaryBin}.wasm`) ? `${targetDir}/${primaryBin}.wasm` : null);
264
330
 
265
331
  const metaPath = `${targetDir}/package.json`;
266
332
  const pkgInfo = {
@@ -268,9 +334,10 @@ class Wbt extends LocalCommand {
268
334
  version: pkgMeta.version || '1.0.0',
269
335
  bin: primaryBin,
270
336
  aliases: pkgMeta.aliases || [],
271
- description: pkgMeta.description || ''
337
+ description: pkgMeta.description || '',
338
+ ...(pkgMeta.interactive ? { interactive: true } : {})
272
339
  };
273
- this.context.fs.setFileByPath(metaPath, JSON.stringify(pkgInfo, null, 2), true);
340
+ this._writeFileSafe(metaPath, JSON.stringify(pkgInfo, null, 2));
274
341
 
275
342
  for (const { bin, Cmd } of entries) {
276
343
  const binName = bin.toLowerCase();
@@ -281,11 +348,15 @@ class Wbt extends LocalCommand {
281
348
  } else {
282
349
  targetFile = `${targetDir}/${binName}.js`;
283
350
  const jsSource = this._generateJsCommandSource(pkgMeta, binName);
284
- this.context.fs.setFileByPath(targetFile, jsSource, true);
285
- if (!this.context.fs.isRealFilesystem && typeof Cmd === 'function') {
286
- this.context.fs.setFileByPath(targetFile, Cmd, true);
351
+ if (typeof Cmd === 'function') {
352
+ Cmd.__source = jsSource;
287
353
  }
288
- try { this.context.fs.setMode(targetFile, 0o755); } catch { /* ignore */ }
354
+ if (!fs.isRealFilesystem && typeof Cmd === 'function' && hasRuntimeClosure) {
355
+ this._writeFileSafe(targetFile, Cmd);
356
+ } else {
357
+ this._writeFileSafe(targetFile, jsSource);
358
+ }
359
+ try { fs.setMode(targetFile, 0o755); } catch { /* ignore */ }
289
360
  }
290
361
 
291
362
  this._createBinSymlink(pathDir, binName, targetFile);
@@ -306,7 +377,7 @@ class Wbt extends LocalCommand {
306
377
  const scriptMap = pkgMeta.scriptPaths || {};
307
378
  for (const [scriptBin, scriptTarget] of Object.entries(scriptMap)) {
308
379
  const binLower = scriptBin.toLowerCase();
309
- if (!installedBins.includes(binLower) && this.context.fs.exists(scriptTarget)) {
380
+ if (!installedBins.includes(binLower) && fs.exists(scriptTarget)) {
310
381
  this._createBinSymlink(pathDir, binLower, scriptTarget);
311
382
  installedBins.push(binLower);
312
383
  }
@@ -315,7 +386,7 @@ class Wbt extends LocalCommand {
315
386
  for (const scriptBin of Object.keys(pkgMeta.scripts)) {
316
387
  const binLower = scriptBin.toLowerCase();
317
388
  const fallbackTarget = `${targetDir}/${binLower}`;
318
- if (!installedBins.includes(binLower) && this.context.fs.exists(fallbackTarget)) {
389
+ if (!installedBins.includes(binLower) && fs.exists(fallbackTarget)) {
319
390
  this._createBinSymlink(pathDir, binLower, fallbackTarget);
320
391
  installedBins.push(binLower);
321
392
  }
@@ -326,25 +397,23 @@ class Wbt extends LocalCommand {
326
397
  }
327
398
 
328
399
  _createBinSymlink(pathDir, binName, targetFile) {
400
+ const fs = this._fs;
329
401
  const symlinkPath = `${pathDir}/${binName.toLowerCase()}`;
330
402
  this._removeBin(pathDir, binName);
331
403
  try {
332
- this.context.fs.createSymlink(targetFile, symlinkPath);
333
- this.context.fs.setMode(symlinkPath, 0o755);
404
+ fs.createSymlink(targetFile, symlinkPath);
405
+ fs.setMode(symlinkPath, 0o755);
334
406
  } catch {
335
- this.context.fs.addFiles({ [symlinkPath]: this.context.fs.getFileByPath(targetFile) });
336
- try { this.context.fs.setMode(symlinkPath, 0o755); } catch { /* ignore */ }
407
+ this._writeFileSafe(symlinkPath, fs.getFileByPath(targetFile));
408
+ try { fs.setMode(symlinkPath, 0o755); } catch { /* ignore */ }
337
409
  }
338
410
  }
339
411
 
340
412
  _removeBin(pathDir, binName) {
341
413
  const location = `${pathDir}/${binName.toLowerCase()}`;
342
- if (this.context.fs._deleteByAbsolutePath) {
343
- this.context.fs._deleteByAbsolutePath(location);
344
- this.context.fs._triggerChange();
345
- } else {
346
- try { this.context.fs.deleteFileByPath(location); } catch { /* ignore */ }
347
- }
414
+ this._withWritableParent(location, (fs) => {
415
+ try { fs.deleteFileByPath(location); } catch { /* ignore */ }
416
+ });
348
417
  }
349
418
 
350
419
  async run() {
@@ -553,8 +622,8 @@ class Wbt extends LocalCommand {
553
622
  text = '';
554
623
  }
555
624
  const targetPath = `${destDir}/${binLower}`;
556
- this.context.fs._setFileRaw(targetPath, text, true);
557
- try { this.context.fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
625
+ this._writeFileSafe(targetPath, text);
626
+ try { this._fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
558
627
  installed[binLower] = targetPath;
559
628
  }
560
629
 
@@ -798,8 +867,8 @@ class Wbt extends LocalCommand {
798
867
  const binName = (pkgMeta.bin || pkgName).toLowerCase();
799
868
  const destDir = targetDir || `/usr/lib/${pkgName}`;
800
869
  const targetPath = `${destDir}/${binName}.wasm`;
801
- writeBytesToFs(this.context.fs, targetPath, wasmBytes, 'application/wasm');
802
- try { this.context.fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
870
+ this._writeBytesSafe(targetPath, wasmBytes, 'application/wasm');
871
+ try { this._fs.setMode(targetPath, 0o755); } catch { /* ignore */ }
803
872
  return targetPath;
804
873
  }
805
874
 
@@ -880,12 +949,12 @@ class Wbt extends LocalCommand {
880
949
 
881
950
  if (isWat) {
882
951
  const text = await res.text();
883
- this.context.fs._setFileRaw(wasmPath, text, true);
952
+ this._writeFileSafe(wasmPath, text);
884
953
  } else {
885
954
  const ab = await res.arrayBuffer();
886
- writeBytesToFs(this.fs, wasmPath, new Uint8Array(ab), 'application/wasm');
955
+ this._writeBytesSafe(wasmPath, new Uint8Array(ab), 'application/wasm');
887
956
  }
888
- this.context.fs.setMode(wasmPath, 0o755);
957
+ try { this._fs.setMode(wasmPath, 0o755); } catch { /* ignore */ }
889
958
 
890
959
  const pkgMeta = {
891
960
  name: pkgName,
@@ -916,7 +985,7 @@ class Wbt extends LocalCommand {
916
985
 
917
986
  const installed = this._getInstalledPackages();
918
987
  const registry = this._getRegistry();
919
- const pathDir = this.context.getVar('PATH') || '/bin';
988
+ const pathDir = this._pathDir;
920
989
 
921
990
  for (const rawName of positional) {
922
991
  const pkgName = resolvePackageName(rawName);
@@ -948,7 +1017,7 @@ class Wbt extends LocalCommand {
948
1017
 
949
1018
  // Remove /usr/lib/<pkgName>
950
1019
  const pkgDir = `/usr/lib/${pkgName}`;
951
- try { this.context.fs.deleteFileByPath(pkgDir); } catch { /* ignore */ }
1020
+ try { this._fs.deleteFileByPath(pkgDir); } catch { /* ignore */ }
952
1021
 
953
1022
  this.stdOut = `Removing ${record.name} (${record.version}) ...`;
954
1023
  }
@@ -1082,7 +1151,7 @@ class Wbt extends LocalCommand {
1082
1151
  }
1083
1152
 
1084
1153
  if (Object.keys(mergedRemote).length > 0) {
1085
- this.context.fs._setFileRaw(`${CACHE_DIR}/remote-registry.json`, JSON.stringify(mergedRemote, null, 2), true);
1154
+ this._writeFileSafe(`${CACHE_DIR}/remote-registry.json`, JSON.stringify(mergedRemote, null, 2));
1086
1155
  }
1087
1156
 
1088
1157
  const registry = this._getRegistry();
@@ -1120,9 +1189,9 @@ class Wbt extends LocalCommand {
1120
1189
  return;
1121
1190
  }
1122
1191
 
1192
+ const fs = this._fs;
1123
1193
  let tempDir = null;
1124
- const origPath = this.context.getVar('PATH') || '/bin';
1125
- let modifiedPath = false;
1194
+ const origPath = this._pathDir;
1126
1195
  try {
1127
1196
  if (!isInstalled) {
1128
1197
  tempDir = `/tmp/.wbt-run-${pkgName}-${Date.now()}`;
@@ -1145,7 +1214,7 @@ class Wbt extends LocalCommand {
1145
1214
  let instance;
1146
1215
  if (pkgMeta.scripts && pkgMeta.scripts[rawLower]) {
1147
1216
  let scriptPath = (pkgMeta.scriptPaths && pkgMeta.scriptPaths[rawLower]) || `/usr/lib/${pkgName}/${rawLower}`;
1148
- if (!this.context.fs.exists(scriptPath)) {
1217
+ if (!fs.exists(scriptPath)) {
1149
1218
  try {
1150
1219
  const pulledScripts = await this._pullPackageScripts(pkgMeta, true, tempDir);
1151
1220
  if (pulledScripts && pulledScripts[rawLower]) {
@@ -1157,29 +1226,68 @@ class Wbt extends LocalCommand {
1157
1226
  return;
1158
1227
  }
1159
1228
  }
1160
- if (tempDir) {
1161
- this.context.setVar('PATH', `${tempDir}:${origPath}`);
1162
- modifiedPath = true;
1163
- }
1229
+ const getCtxVar = (v) => (this.context && typeof this.context.getVar === 'function') ? this.context.getVar(v) : '';
1230
+ const effectivePath = tempDir ? `${tempDir}:${origPath}` : origPath;
1231
+ const baseVars = (this.context && this.context.vars) ? Object.assign({}, this.context.vars) : {
1232
+ HOME: getCtxVar('HOME') || '/root',
1233
+ HOST: getCtxVar('HOST') || 'browser',
1234
+ COLUMNS: String((this.stdout && this.stdout.columns) || getCtxVar('COLUMNS') || 80),
1235
+ LINES: String((this.stdout && this.stdout.rows) || getCtxVar('LINES') || 24),
1236
+ };
1237
+ baseVars.PATH = effectivePath;
1238
+ const subContext = {
1239
+ vars: baseVars,
1240
+ aliases: (this.context && this.context.aliases) || {},
1241
+ getVar: (v) => (v === 'PATH' ? effectivePath : (baseVars[v] || getCtxVar(v))),
1242
+ getAlias: (a) => (this.context && typeof this.context.getAlias === 'function') ? this.context.getAlias(a) : null,
1243
+ getCommand: (c) => (this.context && typeof this.context.getCommand === 'function') ? this.context.getCommand(c) : null,
1244
+ };
1164
1245
  const ScriptCommand = require('../ScriptCommand');
1165
- const scriptContent = this.context.fs.getFileByPath(scriptPath);
1166
- instance = new ScriptCommand(scriptContent, args, this.context);
1246
+ const scriptContent = fs.getFileByPath(scriptPath);
1247
+ instance = new ScriptCommand(scriptContent, args, subContext);
1248
+ instance.fs = fs;
1167
1249
  } else {
1168
1250
  const entries = this._buildCommandsForPackage(pkgMeta);
1169
1251
  // Find matching entry if user specified e.g. `wbt run asrun` or `wbt run wasm2wat`
1170
1252
  const matched = entries.find(e => e.bin === rawLower) || entries[0];
1171
1253
  const Cmd = matched.Cmd;
1172
1254
  instance = new Cmd(args, this.context);
1173
- }
1174
-
1175
- if (instance.requiresFilesystem) {
1176
- instance.fs = this.context.fs.sandbox();
1255
+ if (instance.requiresFilesystem) {
1256
+ instance.fs = typeof fs.sandbox === 'function' ? fs.sandbox() : fs;
1257
+ }
1177
1258
  }
1178
1259
 
1179
1260
  // Pipe I/O and forward interactivity
1180
1261
  this._activeSubCommand = instance;
1262
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
1263
+ this.stdinStream.off('data', this._onStdinStreamData);
1264
+ }
1181
1265
  instance.stdinStream = this.stdinStream;
1182
1266
  instance.stdin = (this.stdin && !this.stdin.isTTY) ? this.stdin : this.stdinStream;
1267
+ if (instance._onStdinStreamData && this.stdinStream && typeof this.stdinStream.on === 'function') {
1268
+ this.stdinStream.on('data', instance._onStdinStreamData);
1269
+ }
1270
+
1271
+ if (this.stdout && instance.stdout) {
1272
+ if (this.stdout.columns) instance.stdout.columns = this.stdout.columns;
1273
+ if (this.stdout.rows) instance.stdout.rows = this.stdout.rows;
1274
+ }
1275
+ if (this.stderr && instance.stderr) {
1276
+ if (this.stderr.columns) instance.stderr.columns = this.stderr.columns;
1277
+ if (this.stderr.rows) instance.stderr.rows = this.stderr.rows;
1278
+ }
1279
+ const onParentStdoutResize = () => {
1280
+ if (!this.stdout || !instance.stdout) return;
1281
+ if (typeof instance.stdout.resize === 'function') {
1282
+ instance.stdout.resize(this.stdout.columns, this.stdout.rows);
1283
+ } else {
1284
+ instance.stdout.columns = this.stdout.columns;
1285
+ instance.stdout.rows = this.stdout.rows;
1286
+ }
1287
+ };
1288
+ if (this.stdout && typeof this.stdout.on === 'function') {
1289
+ this.stdout.on('resize', onParentStdoutResize);
1290
+ }
1183
1291
 
1184
1292
  const onStdout = (chunk) => {
1185
1293
  if (this.stdout && typeof this.stdout.write === 'function') this.stdout.write(chunk);
@@ -1212,6 +1320,15 @@ class Wbt extends LocalCommand {
1212
1320
  res = await instance.runCommand();
1213
1321
  } finally {
1214
1322
  this._activeSubCommand = null;
1323
+ if (this.stdout && typeof this.stdout.off === 'function') {
1324
+ this.stdout.off('resize', onParentStdoutResize);
1325
+ }
1326
+ if (instance._onStdinStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
1327
+ this.stdinStream.off('data', instance._onStdinStreamData);
1328
+ }
1329
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.on === 'function') {
1330
+ this.stdinStream.on('data', this._onStdinStreamData);
1331
+ }
1215
1332
  if (instance.stdout && typeof instance.stdout.off === 'function') {
1216
1333
  instance.stdout.off('data', onStdout);
1217
1334
  }
@@ -1230,12 +1347,9 @@ class Wbt extends LocalCommand {
1230
1347
  }
1231
1348
  this.exitCode = res ? res.getExitCode() : 0;
1232
1349
  } finally {
1233
- if (modifiedPath) {
1234
- this.context.setVar('PATH', origPath);
1235
- }
1236
- if (tempDir) {
1350
+ if (tempDir && fs) {
1237
1351
  try {
1238
- this.context.fs.deleteFileByPath(tempDir);
1352
+ fs.deleteFileByPath(tempDir);
1239
1353
  } catch {
1240
1354
  // ignore
1241
1355
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.10.0",
3
+ "version": "3.10.2",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -170,4 +170,116 @@ describe('WASM requirements auto-discovery', () => {
170
170
  wasmCmd2._inspectedWasm = { isInteractive: true };
171
171
  expect(wasmCmd2.interactive).toBe(true);
172
172
  });
173
+
174
+ it('encodes special keys and ignores bare modifier keys in WasmCommand._keyToBytes', () => {
175
+ const wasmCmd = new WasmCommand('game.wasm', [], {});
176
+ const dec = new TextDecoder();
177
+
178
+ expect(wasmCmd._keyToBytes('Shift')).toBeNull();
179
+ expect(wasmCmd._keyToBytes('Control')).toBeNull();
180
+ expect(wasmCmd._keyToBytes('Alt')).toBeNull();
181
+ expect(wasmCmd._keyToBytes('Meta')).toBeNull();
182
+ expect(wasmCmd._keyToBytes('CapsLock')).toBeNull();
183
+ expect(wasmCmd._keyToBytes('Unidentified')).toBeNull();
184
+
185
+ expect(dec.decode(wasmCmd._keyToBytes('Space'))).toBe(' ');
186
+ expect(dec.decode(wasmCmd._keyToBytes('Spacebar'))).toBe(' ');
187
+ expect(dec.decode(wasmCmd._keyToBytes('Up'))).toBe('\x1b[A');
188
+ expect(dec.decode(wasmCmd._keyToBytes('Down'))).toBe('\x1b[B');
189
+ expect(dec.decode(wasmCmd._keyToBytes('Right'))).toBe('\x1b[C');
190
+ expect(dec.decode(wasmCmd._keyToBytes('Left'))).toBe('\x1b[D');
191
+ expect(dec.decode(wasmCmd._keyToBytes('Esc'))).toBe('\x1b');
192
+ expect(dec.decode(wasmCmd._keyToBytes('Return'))).toBe('\r');
193
+ expect(dec.decode(wasmCmd._keyToBytes('Del'))).toBe('\x1b[3~');
194
+ expect(dec.decode(wasmCmd._keyToBytes('BackTab'))).toBe('\x1b[Z');
195
+ expect(dec.decode(wasmCmd._keyToBytes('F1'))).toBe('\x1bOP');
196
+ expect(dec.decode(wasmCmd._keyToBytes('F5'))).toBe('\x1b[15~');
197
+ expect(dec.decode(wasmCmd._keyToBytes('F12'))).toBe('\x1b[24~');
198
+ });
199
+
200
+ it('parses function keys, modified cursor sequences, and detects custom stdin listeners in TtyStream', () => {
201
+ const { parseVtKeys, hasCustomStdinListener } = require('../lib/TtyStream.js');
202
+ expect(parseVtKeys('\x1bOP\x1bOQ\x1b[15~\x1b[24~\x1b[2~\x1b[Z')).toEqual([
203
+ 'F1', 'F2', 'F5', 'F12', 'Insert', 'BackTab'
204
+ ]);
205
+ expect(parseVtKeys('\x1b[1;5A\x1b[1;2C')).toEqual(['ArrowUp', 'ArrowRight']);
206
+
207
+ const cmd = new Command([], {});
208
+ expect(hasCustomStdinListener(cmd)).toBe(false);
209
+
210
+ // Simulate WasmCommand removing default _onStdinStreamData and attaching raw data listener (listenerCount === 1)
211
+ cmd.stdinStream.off('data', cmd._onStdinStreamData);
212
+ const customFn = () => {};
213
+ cmd.stdinStream.on('data', customFn);
214
+ expect(cmd.stdinStream.listenerCount('data')).toBe(1);
215
+ expect(hasCustomStdinListener(cmd)).toBe(true);
216
+
217
+ cmd._managesOwnStdinCapture = true;
218
+ expect(hasCustomStdinListener(cmd)).toBe(false);
219
+ });
220
+
221
+ it('initializes Shell with cols/rows options and prioritizes live stream size in InteractiveCommand', async () => {
222
+ const InteractiveCommand = require('../lib/InteractiveCommand.js');
223
+ const sizedShell = new Shell({ cols: 140, rows: 45 });
224
+ expect(sizedShell.stdout.columns).toBe(140);
225
+ expect(sizedShell.stdout.rows).toBe(45);
226
+ expect(sizedShell.context.getVar('COLUMNS')).toBe('140');
227
+ expect(sizedShell.context.getVar('LINES')).toBe('45');
228
+
229
+ const icmd = new InteractiveCommand([], sizedShell.context);
230
+ sizedShell.context.setVar('COLUMNS', '80');
231
+ sizedShell.context.setVar('LINES', '24');
232
+ icmd.stdout.columns = 160;
233
+ icmd.stdout.rows = 50;
234
+ expect(icmd.terminalSize).toEqual({ cols: 160, rows: 50 });
235
+ });
236
+
237
+ it('forwards Ctrl+C (\\x03) as raw input to a raw-mode child command inside a shell script without killing the script', async () => {
238
+ const shell = await createShell({
239
+ filesystem: {
240
+ bin: {
241
+ 'run-raw': '#!/bin/sh\nrawchild\n'
242
+ }
243
+ },
244
+ permissions: {
245
+ '/bin/run-raw': 0o755
246
+ }
247
+ });
248
+
249
+ const receivedBytes = [];
250
+ class RawChildCommand extends Command {
251
+ static get name() { return 'rawchild'; }
252
+ get interactive() { return true; }
253
+ get captureInput() { return true; }
254
+ run() {
255
+ return new Promise(resolve => {
256
+ this.stdinStream.off('data', this._onStdinStreamData);
257
+ this.stdinStream.setRawMode(true);
258
+ this.stdinStream.on('data', chunk => {
259
+ const s = String(chunk);
260
+ receivedBytes.push(s);
261
+ if (s === 'q') {
262
+ this.stdinStream.setRawMode(false);
263
+ resolve();
264
+ }
265
+ });
266
+ });
267
+ }
268
+ }
269
+ shell.context.setCommand(RawChildCommand);
270
+
271
+ const p = shell.onCommand('run-raw');
272
+ await new Promise(r => setTimeout(r, 40));
273
+
274
+ // Send Ctrl+C while rawchild is in raw mode inside ScriptCommand
275
+ shell.write('\x03');
276
+ await new Promise(r => setTimeout(r, 20));
277
+ expect(receivedBytes).toContain('\x03');
278
+
279
+ // Exit rawchild cleanly
280
+ shell.write('q');
281
+ await p;
282
+ expect(shell.lastCode).toBe(0);
283
+ });
173
284
  });
285
+
package/test/doom.test.js CHANGED
@@ -3,9 +3,12 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { createShell } from './helpers.js';
5
5
 
6
- const DOOM_WASM_PATH = fs.existsSync('/home/antigravity/doom-ascii/dist/doom.wasm')
7
- ? '/home/antigravity/doom-ascii/dist/doom.wasm'
8
- : '/tmp/doom-asyncify.wasm';
6
+ const DOOM_WASM_CANDIDATES = [
7
+ '/home/antigravity/eliotstocker/doom-wasm/dist/doom.wasm',
8
+ '/home/antigravity/doom-ascii/dist/doom.wasm',
9
+ '/tmp/doom-asyncify.wasm'
10
+ ];
11
+ const DOOM_WASM_PATH = DOOM_WASM_CANDIDATES.find(p => fs.existsSync(p)) || DOOM_WASM_CANDIDATES[0];
9
12
  const DOOM_WAD_PATH = '/tmp/doom1.wad';
10
13
  const hasDoom = fs.existsSync(DOOM_WASM_PATH) && fs.existsSync(DOOM_WAD_PATH);
11
14
 
@@ -31,6 +34,6 @@ describe('Doom in brsh', () => {
31
34
  expect(shell.lastCode).toBe(0);
32
35
  const allOut = lines.join('');
33
36
  expect(allOut).toContain('DOOM ASCII');
34
- expect(allOut).toContain('timed 5026 gametics');
37
+ expect(allOut).toMatch(/timed \d+ gametics/);
35
38
  }, 30000);
36
39
  });
@@ -561,4 +561,52 @@ describe('multiline quotes and line continuations in scripts', () => {
561
561
  expect(res.exitCode).toBe(0);
562
562
  expect(res.output).toEqual(['matched-2', 'matched-help', 'other:custom']);
563
563
  });
564
+
565
+ it('splits accumulated $EXTRA_ARGS and preserves distinct "$@" arguments in wrapper scripts', async () => {
566
+ const received = [];
567
+ class TargetApp extends Command {
568
+ static get name() { return 'target-app'; }
569
+ run() {
570
+ received.push([...this.arguments]);
571
+ return Promise.resolve();
572
+ }
573
+ }
574
+
575
+ const shell = await createShell({
576
+ filesystem: {
577
+ bin: {
578
+ 'launcher.sh': [
579
+ '#!/bin/sh',
580
+ 'EXTRA_ARGS=""',
581
+ 'for ARG in $@',
582
+ 'do',
583
+ ' case "$ARG" in',
584
+ ' --blocks|--block|-b)',
585
+ ' EXTRA_ARGS="$EXTRA_ARGS -blocks"',
586
+ ' ;;',
587
+ ' *)',
588
+ ' EXTRA_ARGS="$EXTRA_ARGS $ARG"',
589
+ ' ;;',
590
+ ' esac',
591
+ 'done',
592
+ 'target-app -iwad "/game/freedoom1.wad" -nosound $EXTRA_ARGS'
593
+ ].join('\n'),
594
+ 'passthrough.sh': '#!/bin/sh\ntarget-app "$@"\n'
595
+ }
596
+ },
597
+ permissions: execPerms('/bin/launcher.sh', '/bin/passthrough.sh')
598
+ });
599
+ shell.context.setCommand(TargetApp);
600
+
601
+ await run(shell, 'launcher.sh --blocks -scaling 2');
602
+ await run(shell, 'passthrough.sh "first with spaces" --blocks');
603
+ await run(shell, 'passthrough.sh');
604
+
605
+ expect(received).toEqual([
606
+ ['-iwad', '/game/freedoom1.wad', '-nosound', '-blocks', '-scaling', '2'],
607
+ ['first with spaces', '--blocks'],
608
+ []
609
+ ]);
610
+ });
564
611
  });
612
+