brsh 2.8.0 → 3.0.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.
Files changed (45) hide show
  1. package/.github/workflows/release.yml +3 -1
  2. package/CHANGELOG.md +32 -0
  3. package/bin/brsh-shell.js +16 -131
  4. package/bin/exportFileSystem.js +4 -0
  5. package/bin/zsh-server.js +261 -0
  6. package/dist/brsh.css +1 -1
  7. package/dist/shell.es.js +943 -499
  8. package/dist/shell.es.js.map +1 -1
  9. package/dist/shell.min.js +31 -16
  10. package/dist/shell.min.js.map +1 -1
  11. package/dist/terminal.cjs.js +77 -100
  12. package/dist/terminal.cjs.js.map +1 -1
  13. package/dist/terminal.es.js +1382 -603
  14. package/dist/terminal.es.js.map +1 -1
  15. package/dist/terminal.min.js +77 -100
  16. package/dist/terminal.min.js.map +1 -1
  17. package/dist/wbt.es.js +1863 -752
  18. package/dist/wbt.es.js.map +1 -1
  19. package/dist/wbt.min.js +8 -6
  20. package/dist/wbt.min.js.map +1 -1
  21. package/index.js +472 -0
  22. package/lib/BaseFileSystem.js +40 -0
  23. package/lib/BinaryContainer.js +1 -1
  24. package/lib/Command.js +30 -0
  25. package/lib/FileSystem.js +1 -38
  26. package/lib/InteractiveCommand.js +28 -0
  27. package/lib/NodeFileSystem.js +4 -2
  28. package/lib/ReplCommand.js +15 -0
  29. package/lib/Terminal.js +769 -510
  30. package/lib/TtyStream.js +181 -0
  31. package/lib/WasmCommand.js +168 -18
  32. package/lib/builtins/cat.js +2 -2
  33. package/lib/builtins/grep.js +2 -2
  34. package/lib/local/clear.js +3 -0
  35. package/lib/terminal/DomRenderer.js +325 -0
  36. package/lib/terminal/PtyBridge.js +169 -0
  37. package/lib/terminal/ScreenBuffer.js +594 -0
  38. package/lib/terminal/VtParser.js +728 -0
  39. package/lib/wbt/index.js +270 -14
  40. package/lib/wbt/packages/wllama.js +12 -2
  41. package/lib/wbt/registry.js +11 -2
  42. package/package.json +4 -2
  43. package/styles/terminal.css +33 -4
  44. package/test/terminal.test.js +762 -40
  45. package/test/wbt.test.js +24 -5
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+
3
+ const events = require('events');
4
+ const EventEmitter = events.EventEmitter || events.default || events;
5
+
6
+ function parseVtKeys(seq) {
7
+ if (!seq) return [];
8
+ const str = typeof seq === 'string'
9
+ ? seq
10
+ : (seq instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(seq)))
11
+ ? new TextDecoder().decode(seq)
12
+ : String(seq);
13
+
14
+ const keys = [];
15
+ let i = 0;
16
+
17
+ while (i < str.length) {
18
+ const ch = str[i];
19
+ const code = str.charCodeAt(i);
20
+
21
+ if (code === 0x1b) {
22
+ if (str.charCodeAt(i + 1) === 0x7f || str.charCodeAt(i + 1) === 0x08) {
23
+ keys.push('^W');
24
+ i += 2;
25
+ continue;
26
+ }
27
+ if (str[i + 1] === '[' || str[i + 1] === 'O') {
28
+ let j = i + 2;
29
+ while (j < str.length && str.charCodeAt(j) >= 0x20 && str.charCodeAt(j) <= 0x3f) {
30
+ j++;
31
+ }
32
+ if (j < str.length) {
33
+ const body = str.slice(i + 2, j + 1);
34
+ const map = {
35
+ A: 'ArrowUp',
36
+ B: 'ArrowDown',
37
+ C: 'ArrowRight',
38
+ D: 'ArrowLeft',
39
+ H: 'Home',
40
+ F: 'End',
41
+ '1~': 'Home',
42
+ '3~': 'Delete',
43
+ '4~': 'End',
44
+ '5~': 'PageUp',
45
+ '6~': 'PageDown',
46
+ '7~': 'Home',
47
+ '8~': 'End'
48
+ };
49
+ if (map[body]) {
50
+ keys.push(map[body]);
51
+ }
52
+ i = j + 1;
53
+ continue;
54
+ }
55
+ }
56
+ keys.push('Escape');
57
+ i++;
58
+ continue;
59
+ }
60
+
61
+ if (code === 0x0d || code === 0x0a) {
62
+ keys.push('Enter');
63
+ if (code === 0x0d && str[i + 1] === '\n') i++;
64
+ i++;
65
+ continue;
66
+ }
67
+ if (code === 0x7f || code === 0x08) {
68
+ keys.push('Backspace');
69
+ i++;
70
+ continue;
71
+ }
72
+ if (code === 0x09) {
73
+ keys.push('Tab');
74
+ i++;
75
+ continue;
76
+ }
77
+ if (code >= 0x01 && code <= 0x1a) {
78
+ keys.push('^' + String.fromCharCode(code + 0x40));
79
+ i++;
80
+ continue;
81
+ }
82
+ keys.push(ch);
83
+ i++;
84
+ }
85
+ return keys;
86
+ }
87
+
88
+ class TtyStream extends EventEmitter {
89
+ constructor(options = {}) {
90
+ super();
91
+ this.isTTY = options.isTTY !== false;
92
+ this.readable = true;
93
+ this.writable = true;
94
+ this.columns = options.columns || 80;
95
+ this.rows = options.rows || 24;
96
+ this.isRaw = false;
97
+ this._encoding = null;
98
+ this._onWrite = options.onWrite || null;
99
+ }
100
+
101
+ write(chunk, encoding, callback) {
102
+ if (chunk == null) return true;
103
+ if (typeof this._onWrite === 'function') {
104
+ this._onWrite(chunk);
105
+ }
106
+ this.emit('data', this._formatChunk(chunk));
107
+ if (typeof encoding === 'function') encoding();
108
+ else if (typeof callback === 'function') callback();
109
+ return true;
110
+ }
111
+
112
+ pushData(chunk) {
113
+ if (chunk == null) return;
114
+ this.emit('data', this._formatChunk(chunk));
115
+ }
116
+
117
+ _formatChunk(chunk) {
118
+ if (this._encoding) {
119
+ if (typeof chunk === 'string') return chunk;
120
+ if (chunk instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(chunk))) {
121
+ return new TextDecoder().decode(chunk);
122
+ }
123
+ return String(chunk);
124
+ }
125
+ return chunk;
126
+ }
127
+
128
+ setRawMode(flag) {
129
+ this.isRaw = Boolean(flag);
130
+ return this;
131
+ }
132
+
133
+ setEncoding(enc) {
134
+ this._encoding = enc;
135
+ return this;
136
+ }
137
+
138
+ getWindowSize() {
139
+ return [this.columns, this.rows];
140
+ }
141
+
142
+ resize(cols, rows) {
143
+ this.columns = cols;
144
+ this.rows = rows;
145
+ this.emit('resize');
146
+ }
147
+
148
+ resume() { return this; }
149
+ pause() { return this; }
150
+ pipe(dest) {
151
+ this.on('data', chunk => dest.write(chunk));
152
+ return dest;
153
+ }
154
+ unpipe() { return this; }
155
+ end(chunk, encoding, cb) {
156
+ if (chunk != null) {
157
+ this.write(chunk, typeof encoding === 'string' ? encoding : undefined);
158
+ }
159
+ this.emit('end');
160
+ if (typeof encoding === 'function') encoding();
161
+ else if (typeof cb === 'function') cb();
162
+ return this;
163
+ }
164
+
165
+ destroy() {
166
+ this.removeAllListeners();
167
+ }
168
+
169
+ toString() {
170
+ return '';
171
+ }
172
+
173
+ valueOf() {
174
+ return '';
175
+ }
176
+ }
177
+
178
+ module.exports = {
179
+ TtyStream,
180
+ parseVtKeys
181
+ };
@@ -671,7 +671,7 @@ function readBytesFromFs(fs, filepath) {
671
671
  const nodeFs = require('fs');
672
672
  return new Uint8Array(nodeFs.readFileSync(fs.absolutePath(filepath)));
673
673
  } catch {
674
- return null;
674
+ // Fall through to virtual file map if stored in _virtualFiles
675
675
  }
676
676
  }
677
677
  const content = fs.getFileByPath(filepath);
@@ -713,17 +713,28 @@ function readBytesFromFs(fs, filepath) {
713
713
  */
714
714
  function writeBytesToFs(fs, filepath, bytes, mimeType = 'application/octet-stream') {
715
715
  const uint8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
716
- if (fs.isRealFilesystem) {
717
- const nodeFs = require('fs');
718
- const nodePath = require('path');
719
- const abs = fs.absolutePath(filepath);
720
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
721
- nodeFs.writeFileSync(abs, Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
722
- return;
723
- }
724
716
  const copy = new Uint8Array(uint8.byteLength);
725
717
  copy.set(uint8);
726
718
  const bf = new BinaryFile(copy.buffer, mimeType);
719
+ if (fs.isRealFilesystem) {
720
+ try {
721
+ const nodeFs = require('fs');
722
+ const nodePath = require('path');
723
+ const abs = fs.absolutePath(filepath);
724
+ nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
725
+ nodeFs.writeFileSync(abs, Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
726
+ return;
727
+ } catch {
728
+ if (typeof fs._setFileRaw === 'function') {
729
+ fs._setFileRaw(filepath, bf, true);
730
+ return;
731
+ }
732
+ }
733
+ }
734
+ if (typeof fs._setFileRaw === 'function' && filepath.startsWith('/var/lib/wbt/')) {
735
+ fs._setFileRaw(filepath, bf, true);
736
+ return;
737
+ }
727
738
  fs.setFileByPath(filepath, bf, true);
728
739
  }
729
740
 
@@ -748,6 +759,12 @@ async function loadModule(pkgName, cdnUrl, customLoader = null) {
748
759
  try {
749
760
  return await import(/* @vite-ignore */ cdnUrl);
750
761
  } catch (err) {
762
+ if (!/^https?:\/\/esm\.sh\//i.test(cdnUrl)) {
763
+ try {
764
+ const fallbackUrl = `https://esm.sh/${pkgName}`;
765
+ return await import(/* @vite-ignore */ fallbackUrl);
766
+ } catch { /* fall through */ }
767
+ }
751
768
  throw new Error(`Failed to load WASM package '${pkgName}' from ${cdnUrl}: ${err.message || err}`);
752
769
  }
753
770
  }
@@ -766,13 +783,19 @@ function extractHelpFromText(text, scanBareFlags = false) {
766
783
  const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
767
784
  const seenOpts = new Set();
768
785
 
769
- for (const line of lines) {
786
+ // If a "Usage:" line exists when scanning raw binary strings, prefer scanning options from that point onward
787
+ const usageIdx = scanBareFlags ? lines.findIndex(l => /^usage:\s*(.+)/i.test(l)) : -1;
788
+ const startIdx = usageIdx >= 0 ? usageIdx : 0;
789
+
790
+ for (let i = startIdx; i < lines.length; i++) {
791
+ const line = lines[i];
770
792
  if (!res.usage && /^usage:\s*(.+)/i.test(line)) {
771
793
  res.usage = line.replace(/^usage:\s*/i, '').trim();
772
794
  } else if (
773
795
  /^(?:-[a-zA-Z0-9?]|--[a-zA-Z0-9][-a-zA-Z0-9]*)(?:\s|,|=|<|\[|$)/.test(line) &&
774
796
  line.length <= 120 &&
775
- !/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(line)
797
+ !/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(line) &&
798
+ (!scanBareFlags || /^(?:-[a-zA-Z?]|--[a-zA-Z][a-zA-Z0-9-]*)(?:,\s*--?[a-zA-Z0-9-]+)?(?:\s+[<\[a-zA-Z0-9_.->\]]+)*(?:\s+[A-Za-z`'"(][A-Za-z0-9 ,.;:()'"`/<>\[\]=+$\t_-]*|)$/.test(line))
776
799
  ) {
777
800
  if (!seenOpts.has(line)) {
778
801
  seenOpts.add(line);
@@ -857,7 +880,8 @@ function formatWasmHelp(binName, pkgMeta = {}, inspected = null) {
857
880
  const desc = pkgMeta.description || 'WebAssembly binary';
858
881
  const replCfg = (pkgMeta && typeof pkgMeta.repl === 'object') ? pkgMeta.repl : (pkgMeta.repl ? {} : null);
859
882
 
860
- const detectedUsage = (inspected && inspected.usage) || pkgMeta.usage;
883
+ const rawDetectedUsage = (inspected && inspected.usage) || pkgMeta.usage;
884
+ const detectedUsage = rawDetectedUsage ? rawDetectedUsage.replace(/%s/g, binName) : null;
861
885
  const defaultUsage = replCfg
862
886
  ? `${binName} [options] ${replCfg.evalFlag ? `[${replCfg.evalFlag} <code>] ` : ''}[file] [args...]`
863
887
  : `${binName} [options] [args...]`;
@@ -932,17 +956,47 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
932
956
  const isHelp = args.includes('--help') || args.includes('-h');
933
957
  const isVersion = !isHelp && (args.includes('--version') || args.includes('-V') || args.includes('-v'));
934
958
  this._inspectedWasm = null;
959
+ this._persistedWasmBytes = pkgMeta.wasmPath
960
+ ? readBytesFromFs((this.context && this.context.fs) || this.fs, pkgMeta.wasmPath)
961
+ : null;
962
+ if (isHelp && this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0) {
963
+ this._inspectedWasm = inspectWasmBytes(this._persistedWasmBytes);
964
+ }
935
965
 
936
966
  try {
937
- // 1. Direct `.wasm` URL -> fetch and run raw WASI binary via WasmCommand
938
- if (pkgMeta.type === 'wasm' && pkgMeta.wasmUrl && !config.moduleLoader) {
939
- const bytes = await this._fetchWasmBytes(pkgMeta.wasmUrl);
967
+ // 1. Direct `.wasm` URL or persisted raw WASI binary -> run via WasmCommand
968
+ if (pkgMeta.type === 'wasm' && (this._persistedWasmBytes || pkgMeta.wasmUrl) && !config.moduleLoader) {
969
+ const bytes = this._persistedWasmBytes || await this._fetchWasmBytes(pkgMeta.wasmUrl);
940
970
  if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
941
971
  await this._runRawWasmBytes(bytes, args);
942
972
  } else {
943
973
  const cdnUrl = pkgMeta.cdnUrl || pkgMeta.wasmUrl || `https://esm.sh/${pkgMeta.name}`;
944
- const loaded = await loadModule(pkgMeta.name, cdnUrl, config.moduleLoader);
945
- const target = (loaded && loaded.default !== undefined) ? loaded.default : loaded;
974
+ const origFetch = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
975
+ if (origFetch && this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0 && typeof Response !== 'undefined') {
976
+ const wasmBytes = this._persistedWasmBytes;
977
+ const wasmUrl = pkgMeta.wasmUrl || '';
978
+ globalThis.fetch = async (input, init) => {
979
+ const reqUrl = typeof input === 'string' ? input : (input && input.url ? input.url : '');
980
+ if (reqUrl && (reqUrl === wasmUrl || (!/^https?:\/\//i.test(reqUrl) && /\.wasm(\?.*)?$/i.test(reqUrl)))) {
981
+ return new Response(wasmBytes, {
982
+ status: 200,
983
+ headers: { 'Content-Type': 'application/wasm' }
984
+ });
985
+ }
986
+ return origFetch(input, init);
987
+ };
988
+ }
989
+ let loaded;
990
+ let target;
991
+ try {
992
+ loaded = await loadModule(pkgMeta.name, cdnUrl, config.moduleLoader);
993
+ target = (loaded && loaded.default !== undefined) ? loaded.default : loaded;
994
+ if (target && typeof target.then === 'function') {
995
+ target = await target;
996
+ }
997
+ } finally {
998
+ if (origFetch) globalThis.fetch = origFetch;
999
+ }
946
1000
 
947
1001
  // 2. Raw WASM binary (Uint8Array or ArrayBuffer)
948
1002
  if (target instanceof Uint8Array || target instanceof ArrayBuffer) {
@@ -965,6 +1019,19 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
965
1019
  const entryFn = target.main || target.run || target.callMain || target.exec;
966
1020
  if (typeof entryFn === 'function') {
967
1021
  await this._invokeCliFunction(entryFn.bind(target), args);
1022
+ } else if (target.promised || typeof target.raw === 'function' || typeof target.json === 'function') {
1023
+ const jqInst = target.promised ? await target.promised : target;
1024
+ const flags = args.filter(a => a.startsWith('-'));
1025
+ const pos = args.filter(a => !a.startsWith('-'));
1026
+ const filter = pos.shift() || '.';
1027
+ const io = this._createIoBridge(args, [], []);
1028
+ const input = pos.length > 0 ? (io.readFile(pos[0]) || '') : (io.stdin || (isHelp || isVersion ? '{}' : ''));
1029
+ const out = typeof jqInst.raw === 'function'
1030
+ ? jqInst.raw(input, filter, flags)
1031
+ : (!isHelp && !isVersion ? JSON.stringify(jqInst.json(JSON.parse(input || 'null'), filter)) : null);
1032
+ if (out != null) {
1033
+ String(out).replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => { this.stdOut = l; });
1034
+ }
968
1035
  } else if (!isHelp && !isVersion) {
969
1036
  this.stdErr = `${binName}: unsupported WASM module format for '${pkgMeta.name}'`;
970
1037
  this.exitCode = 1;
@@ -1079,6 +1146,8 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1079
1146
  stdin: this.stdin !== undefined && this.stdin !== null ? String(this.stdin) : '',
1080
1147
  fs: this.fs,
1081
1148
  context: this.context,
1149
+ wasmPath: pkgMeta.wasmPath || null,
1150
+ wasmBytes: this._persistedWasmBytes || null,
1082
1151
  stdout: Object.assign((line) => outLines.push(String(line)), createStream(outLines)),
1083
1152
  stderr: Object.assign((line) => errLines.push(String(line)), createStream(errLines)),
1084
1153
  readFile: (filename, baseDir) => {
@@ -1133,6 +1202,12 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1133
1202
  const emscriptenConfig = {
1134
1203
  arguments: args,
1135
1204
  noInitialRun: true,
1205
+ ...(this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0
1206
+ ? { wasmBinary: this._persistedWasmBytes }
1207
+ : {}),
1208
+ ...(pkgMeta.wasmUrl
1209
+ ? { locateFile: (file) => (file.endsWith('.wasm') ? pkgMeta.wasmUrl : file) }
1210
+ : {}),
1136
1211
  print: (text) => { outLines.push(String(text)); },
1137
1212
  printErr: (text) => { errLines.push(String(text)); },
1138
1213
  stdin: () => (stdinPos < stdinBytes.length ? stdinBytes[stdinPos++] : null),
@@ -1191,6 +1266,8 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1191
1266
  } else if (typeof result.main === 'function' || typeof result.run === 'function') {
1192
1267
  const entry = (result.main || result.run).bind(result);
1193
1268
  await this._invokeCliFunction(entry, args, outLines, errLines);
1269
+ } else if (!isHelp && !isVersion && typeof result.Database === 'function') {
1270
+ this._runSqlJsDatabase(result, args, ioBridge, outLines);
1194
1271
  } else {
1195
1272
  if (typeof result.stdout === 'string' && result.stdout) {
1196
1273
  result.stdout.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
@@ -1216,6 +1293,80 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1216
1293
  errLines.forEach(l => { this.stdErr = l; });
1217
1294
  }
1218
1295
 
1296
+ _runSqlJsDatabase(SQL, args, io, outLines) {
1297
+ let mode = 'list';
1298
+ let dbPath = ':memory:';
1299
+ let sql = null;
1300
+ const positional = [];
1301
+
1302
+ for (let i = 0; i < args.length; i++) {
1303
+ const a = args[i];
1304
+ if (a === '-table' || a === '--table' || a === '-box') mode = 'table';
1305
+ else if (a === '-csv' || a === '--csv') mode = 'csv';
1306
+ else if (a === '-cmd' && i + 1 < args.length) sql = args[++i];
1307
+ else if (!a.startsWith('-')) positional.push(a);
1308
+ }
1309
+
1310
+ if (positional.length === 1) {
1311
+ if (/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(positional[0])) {
1312
+ sql = positional[0];
1313
+ } else {
1314
+ dbPath = positional[0];
1315
+ }
1316
+ } else if (positional.length >= 2) {
1317
+ dbPath = positional[0];
1318
+ sql = positional.slice(1).join(' ');
1319
+ }
1320
+ if (!sql && io.stdin && io.stdin.trim()) {
1321
+ sql = io.stdin.trim();
1322
+ }
1323
+ if (!sql) return;
1324
+
1325
+ const existingBytes = dbPath !== ':memory:' ? io.readBytes(dbPath) : null;
1326
+ const db = existingBytes && existingBytes.byteLength > 0
1327
+ ? new SQL.Database(existingBytes)
1328
+ : new SQL.Database();
1329
+
1330
+ try {
1331
+ if (sql.trim() === '.tables') {
1332
+ const res = db.exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");
1333
+ const names = (res[0] && res[0].values) ? res[0].values.map(r => r[0]) : [];
1334
+ if (names.length > 0) outLines.push(names.join(' '));
1335
+ } else {
1336
+ const results = db.exec(sql);
1337
+ for (const r of results) {
1338
+ const cols = (r.columns || []).map(String);
1339
+ const rows = r.values || [];
1340
+ if (mode === 'table' && cols.length > 0) {
1341
+ const widths = cols.map(c => c.length);
1342
+ const norm = rows.map(row => cols.map((_, i) => {
1343
+ const s = row[i] == null ? 'NULL' : String(row[i]);
1344
+ if (s.length > widths[i]) widths[i] = s.length;
1345
+ return s;
1346
+ }));
1347
+ outLines.push(cols.map((c, i) => ' ' + c.padEnd(widths[i]) + ' ').join('|'));
1348
+ outLines.push(widths.map(w => '-'.repeat(w + 2)).join('+'));
1349
+ norm.forEach(row => outLines.push(row.map((c, i) => ' ' + c.padEnd(widths[i]) + ' ').join('|')));
1350
+ } else if (mode === 'csv') {
1351
+ const esc = (v) => {
1352
+ const s = v == null ? '' : String(v);
1353
+ return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
1354
+ };
1355
+ if (cols.length > 0) outLines.push(cols.map(esc).join(','));
1356
+ rows.forEach(row => outLines.push(cols.map((_, i) => esc(row[i])).join(',')));
1357
+ } else {
1358
+ rows.forEach(row => outLines.push(cols.map((_, i) => (row[i] == null ? '' : String(row[i]))).join('|')));
1359
+ }
1360
+ }
1361
+ }
1362
+ if (dbPath !== ':memory:') {
1363
+ io.writeFile(dbPath, db.export());
1364
+ }
1365
+ } finally {
1366
+ db.close();
1367
+ }
1368
+ }
1369
+
1219
1370
  async _runVirtualFsInstance(instance, args, outLines, errLines) {
1220
1371
  if (typeof instance.on === 'function') {
1221
1372
  instance.on('log', ({ message }) => {
@@ -1344,4 +1495,3 @@ WasmCommand.createGenericWasmCommand = createGenericWasmCommand;
1344
1495
  WasmCommand.createCommand = createGenericWasmCommand;
1345
1496
 
1346
1497
  module.exports = WasmCommand;
1347
-
@@ -30,7 +30,7 @@ class Cat extends Command {
30
30
  const parts = [];
31
31
 
32
32
  if (paths.length === 0) {
33
- const stdinContent = this.stdin;
33
+ const stdinContent = typeof this.stdin === 'string' ? this.stdin : null;
34
34
  if (stdinContent == null) {
35
35
  this.stdErr = 'cat: no file specified';
36
36
  this.exitCode = 1;
@@ -40,7 +40,7 @@ class Cat extends Command {
40
40
  } else {
41
41
  for (const path of paths) {
42
42
  if (path === '-') {
43
- parts.push(this.stdin || '');
43
+ parts.push(typeof this.stdin === 'string' ? this.stdin : '');
44
44
  continue;
45
45
  }
46
46
  const file = this.fs.getFileByPath(path);
@@ -87,7 +87,7 @@ class Grep extends Command {
87
87
  if (patternFile !== null) {
88
88
  let pfContent = '';
89
89
  if (patternFile === '-') {
90
- pfContent = this.stdin || '';
90
+ pfContent = typeof this.stdin === 'string' ? this.stdin : '';
91
91
  } else {
92
92
  const pf = this.fs.getFileByPath(patternFile);
93
93
  if (pf === null || pf === undefined) {
@@ -136,7 +136,7 @@ class Grep extends Command {
136
136
  // Collect input sources: {label, content}
137
137
  const sources = [];
138
138
  let hasError = false;
139
- const stdinContent = this.stdin || '';
139
+ const stdinContent = typeof this.stdin === 'string' ? this.stdin : '';
140
140
 
141
141
  const collectFiles = (p, topLevel = false) => {
142
142
  const entry = this.fs.getFileByPath(p);
@@ -10,6 +10,9 @@ class Clear extends LocalCommand {
10
10
  return Promise.reject('clear does not require arguments');
11
11
  }
12
12
 
13
+ if (this.stdout) {
14
+ this.stdout.write('\x1b[2J\x1b[3J\x1b[H');
15
+ }
13
16
  this.context.clear();
14
17
 
15
18
  return Promise.resolve();