brsh 2.7.0 → 2.8.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.
- package/CHANGELOG.md +20 -0
- package/Readme.md +33 -16
- package/bin/brsh-shell.js +15 -1
- package/dist/shell.es.js +243 -109
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +7 -7
- package/dist/shell.min.js.map +1 -1
- package/dist/terminal.cjs.js +101 -0
- package/dist/terminal.cjs.js.map +1 -0
- package/dist/terminal.es.js +290 -8107
- package/dist/terminal.es.js.map +1 -1
- package/dist/terminal.min.js +4 -32
- package/dist/terminal.min.js.map +1 -1
- package/dist/wbt.es.js +1619 -6133
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +6 -20
- package/dist/wbt.min.js.map +1 -1
- package/index.js +29 -0
- package/lib/BaseFileSystem.js +40 -0
- package/lib/BinaryContainer.js +1 -1
- package/lib/FileSystem.js +1 -38
- package/lib/NodeFileSystem.js +4 -2
- package/lib/Terminal.js +45 -10
- package/lib/WasmCommand.js +168 -18
- package/lib/local/curl.js +60 -2
- package/lib/wbt/index.js +297 -64
- package/lib/wbt/packages/wllama.js +1061 -0
- package/lib/wbt/registry.js +31 -19
- package/package.json +3 -2
- package/test/curl.test.js +166 -0
- package/test/terminal.test.js +113 -0
- package/test/wasm-cli.test.js +127 -0
- package/test/wbt.test.js +342 -232
- package/vite.config.terminal.js +16 -12
- package/vitest.config.js +6 -0
- package/lib/wbt/daemon.js +0 -264
- package/lib/wbt/packages/pglite.js +0 -590
package/index.js
CHANGED
|
@@ -646,6 +646,9 @@ class Shell extends EventEmitter {
|
|
|
646
646
|
|
|
647
647
|
const binLocation = `${this.path}/${cmdName}`;
|
|
648
648
|
if (this._isWasmFile(binLocation, cmd)) {
|
|
649
|
+
if (!this.context.fs.isExecutable(binLocation)) {
|
|
650
|
+
throw new Error(`${command}: permission denied`);
|
|
651
|
+
}
|
|
649
652
|
return WasmCommand.bind(null, binLocation);
|
|
650
653
|
}
|
|
651
654
|
|
|
@@ -872,6 +875,30 @@ class Shell extends EventEmitter {
|
|
|
872
875
|
static _escapeRegExp(string) {
|
|
873
876
|
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
874
877
|
}
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Asynchronously creates and boots a Shell instance.
|
|
881
|
+
* Pre-resolves any async filesystem sources (URLs, Promises, .brfs containers, or IndexedDB)
|
|
882
|
+
* before returning the fully initialized shell.
|
|
883
|
+
*/
|
|
884
|
+
static async create(options = {}) {
|
|
885
|
+
let { filesystem, permissions, ...rest } = options;
|
|
886
|
+
if (isAsyncFilesystemSource(filesystem) || (filesystem && typeof filesystem === 'object' && isAsyncFilesystemSource(filesystem.filesystem))) {
|
|
887
|
+
const resolved = await resolveFilesystemSource(filesystem, permissions);
|
|
888
|
+
filesystem = resolved.filesystem;
|
|
889
|
+
permissions = resolved.permissions;
|
|
890
|
+
}
|
|
891
|
+
const shell = new Shell(Object.assign({}, rest, { filesystem, permissions }));
|
|
892
|
+
await shell.ready;
|
|
893
|
+
return shell;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Helper to create a Shell directly from a .brfs container (URL, Uint8Array, or Promise).
|
|
898
|
+
*/
|
|
899
|
+
static async fromContainer(source, options = {}) {
|
|
900
|
+
return Shell.create(Object.assign({}, options, { filesystem: source }));
|
|
901
|
+
}
|
|
875
902
|
}
|
|
876
903
|
|
|
877
904
|
Shell.STATUS_READY = 'READY';
|
|
@@ -881,10 +908,12 @@ Shell.STATUS_DESTROYED = 'DESTROYED';
|
|
|
881
908
|
Shell.Command = Command;
|
|
882
909
|
Shell.InteractiveCommand = InteractiveCommand;
|
|
883
910
|
Shell.WasmCommand = WasmCommand;
|
|
911
|
+
Shell.createWasmCommand = WasmCommand.createGenericWasmCommand || WasmCommand.createCommand;
|
|
884
912
|
Shell.ReplCommand = require('./lib/ReplCommand');
|
|
885
913
|
Shell.FS = BaseFileSystem;
|
|
886
914
|
Shell.BinaryContainer = require('./lib/BinaryContainer');
|
|
887
915
|
Shell.Storage = Shell.BinaryContainer.FilesystemStorage;
|
|
888
916
|
|
|
889
917
|
globalThis.shell = Shell;
|
|
918
|
+
globalThis.Shell = Shell;
|
|
890
919
|
module.exports = Shell;
|
package/lib/BaseFileSystem.js
CHANGED
|
@@ -79,4 +79,44 @@ class BaseFileSystem {
|
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Represents a binary file stored as raw bytes in the virtual filesystem.
|
|
84
|
+
* Extends Uint8Array so binary-aware commands can access bytes directly,
|
|
85
|
+
* while text-based commands (cat, grep, etc.) get the original data URI
|
|
86
|
+
* via toString() — avoiding the 33% base64 memory overhead at runtime.
|
|
87
|
+
*/
|
|
88
|
+
class BinaryFile extends Uint8Array {
|
|
89
|
+
constructor(buffer, mimeType) {
|
|
90
|
+
super(buffer);
|
|
91
|
+
Object.defineProperty(this, 'mimeType', { value: mimeType, enumerable: false, configurable: false, writable: false });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
toString() {
|
|
95
|
+
if (typeof Buffer !== 'undefined') {
|
|
96
|
+
return `data:${this.mimeType};base64,${Buffer.from(this).toString('base64')}`;
|
|
97
|
+
}
|
|
98
|
+
// Browser path — chunked to avoid stack overflow on large files
|
|
99
|
+
let binary = '';
|
|
100
|
+
const chunk = 8192;
|
|
101
|
+
for (let i = 0; i < this.length; i += chunk) {
|
|
102
|
+
binary += String.fromCharCode(...this.subarray(i, i + chunk));
|
|
103
|
+
}
|
|
104
|
+
return `data:${this.mimeType};base64,${btoa(binary)}`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Represents a symbolic link stored in the virtual filesystem.
|
|
110
|
+
* Acts as an opaque marker: `_resolveByAbsolutePath` follows these
|
|
111
|
+
* transparently during file access, while lstat-like calls return the
|
|
112
|
+
* SymlinkRef itself so callers can detect and report symlinks.
|
|
113
|
+
*/
|
|
114
|
+
class SymlinkRef {
|
|
115
|
+
constructor(target) {
|
|
116
|
+
this.target = target;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
82
120
|
module.exports = BaseFileSystem;
|
|
121
|
+
module.exports.BinaryFile = BinaryFile;
|
|
122
|
+
module.exports.SymlinkRef = SymlinkRef;
|
package/lib/BinaryContainer.js
CHANGED
package/lib/FileSystem.js
CHANGED
|
@@ -1,44 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const BaseFileSystem = require('./BaseFileSystem');
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Represents a binary file stored as raw bytes in the virtual filesystem.
|
|
7
|
-
* Extends Uint8Array so binary-aware commands can access bytes directly,
|
|
8
|
-
* while text-based commands (cat, grep, etc.) get the original data URI
|
|
9
|
-
* via toString() — avoiding the 33% base64 memory overhead at runtime.
|
|
10
|
-
*/
|
|
11
|
-
class BinaryFile extends Uint8Array {
|
|
12
|
-
constructor(buffer, mimeType) {
|
|
13
|
-
super(buffer);
|
|
14
|
-
Object.defineProperty(this, 'mimeType', { value: mimeType, enumerable: false, configurable: false, writable: false });
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
toString() {
|
|
18
|
-
if (typeof Buffer !== 'undefined') {
|
|
19
|
-
return `data:${this.mimeType};base64,${Buffer.from(this).toString('base64')}`;
|
|
20
|
-
}
|
|
21
|
-
// Browser path — chunked to avoid stack overflow on large files
|
|
22
|
-
let binary = '';
|
|
23
|
-
const chunk = 8192;
|
|
24
|
-
for (let i = 0; i < this.length; i += chunk) {
|
|
25
|
-
binary += String.fromCharCode(...this.subarray(i, i + chunk));
|
|
26
|
-
}
|
|
27
|
-
return `data:${this.mimeType};base64,${btoa(binary)}`;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Represents a symbolic link stored in the virtual filesystem.
|
|
33
|
-
* Acts as an opaque marker: `_resolveByAbsolutePath` follows these
|
|
34
|
-
* transparently during file access, while lstat-like calls return the
|
|
35
|
-
* SymlinkRef itself so callers can detect and report symlinks.
|
|
36
|
-
*/
|
|
37
|
-
class SymlinkRef {
|
|
38
|
-
constructor(target) {
|
|
39
|
-
this.target = target;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
4
|
+
const { BinaryFile, SymlinkRef } = BaseFileSystem;
|
|
42
5
|
|
|
43
6
|
/**
|
|
44
7
|
* Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
|
package/lib/NodeFileSystem.js
CHANGED
|
@@ -140,8 +140,10 @@ class NodeFileSystem extends BaseFileSystem {
|
|
|
140
140
|
if (this._virtualFiles[abs] !== undefined) {
|
|
141
141
|
return;
|
|
142
142
|
}
|
|
143
|
-
|
|
144
|
-
|
|
143
|
+
try {
|
|
144
|
+
nodeFs.chmodSync(abs, mode);
|
|
145
|
+
this._triggerChange();
|
|
146
|
+
} catch (e) { /* ignore chmod errors on virtualized paths */ }
|
|
145
147
|
}
|
|
146
148
|
|
|
147
149
|
getSize(path) {
|
package/lib/Terminal.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
import _Shell from 'brsh';
|
|
4
|
+
import _AnsiUp from 'ansi_up';
|
|
5
|
+
import '../styles/terminal.css';
|
|
6
|
+
|
|
7
|
+
const ImportedShell = _Shell?.default ?? _Shell;
|
|
6
8
|
const AnsiUp = _AnsiUp?.default ?? _AnsiUp;
|
|
7
9
|
|
|
8
10
|
const HISTORY_FILE = '/.brsh_history';
|
|
@@ -44,7 +46,19 @@ class Terminal {
|
|
|
44
46
|
this._lineWrap = lineWrap;
|
|
45
47
|
this._working = true;
|
|
46
48
|
this._pendingCommands = [];
|
|
47
|
-
|
|
49
|
+
|
|
50
|
+
let ShellClass = null;
|
|
51
|
+
if (options.Shell !== false && options.Shell !== null) {
|
|
52
|
+
ShellClass = options.Shell || (typeof globalThis !== 'undefined' && (globalThis.Shell || globalThis.shell)) || (typeof ImportedShell === 'function' ? ImportedShell : null);
|
|
53
|
+
}
|
|
54
|
+
this.cli = options.cli || options.shell;
|
|
55
|
+
if (!this.cli) {
|
|
56
|
+
if (!ShellClass) {
|
|
57
|
+
throw new Error('Shell is required by Terminal. Please import Shell from "brsh" or include shell.min.js before terminal.min.js.');
|
|
58
|
+
}
|
|
59
|
+
this.cli = new ShellClass(Object.assign({}, options, { command: undefined }));
|
|
60
|
+
}
|
|
61
|
+
|
|
48
62
|
this._buffer = [];
|
|
49
63
|
this._cursorPos = 0;
|
|
50
64
|
this._history = [];
|
|
@@ -182,6 +196,8 @@ class Terminal {
|
|
|
182
196
|
}
|
|
183
197
|
|
|
184
198
|
_newPrompt(callback) {
|
|
199
|
+
if (typeof document === 'undefined' || !this._cmdList) return;
|
|
200
|
+
this._progressLine = null;
|
|
185
201
|
this._clearCursor();
|
|
186
202
|
this._currentLine = document.createElement('li');
|
|
187
203
|
this._cmdList.appendChild(this._currentLine);
|
|
@@ -192,6 +208,24 @@ class Terminal {
|
|
|
192
208
|
}
|
|
193
209
|
|
|
194
210
|
_print(data, type = 'out') {
|
|
211
|
+
if (typeof data === 'string' && data.startsWith('\r')) {
|
|
212
|
+
const clean = data.slice(1);
|
|
213
|
+
if (this._progressLine && this._progressLine.parentNode === this._cmdList) {
|
|
214
|
+
this._progressLine.innerHTML = this._ansi.ansi_to_html(clean);
|
|
215
|
+
this._autoScroll();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const line = document.createElement('li');
|
|
219
|
+
line.classList.add('terminal__line');
|
|
220
|
+
line.classList.add(type);
|
|
221
|
+
line.innerHTML = this._ansi.ansi_to_html(clean);
|
|
222
|
+
this._cmdList.appendChild(line);
|
|
223
|
+
this._progressLine = line;
|
|
224
|
+
this._autoScroll();
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
this._progressLine = null;
|
|
195
229
|
if(this._outputAnimation === 'none') {
|
|
196
230
|
const line = document.createElement('li');
|
|
197
231
|
line.classList.add('terminal__line');
|
|
@@ -308,7 +342,8 @@ class Terminal {
|
|
|
308
342
|
}
|
|
309
343
|
|
|
310
344
|
_statusCheck(status) {
|
|
311
|
-
|
|
345
|
+
const readyStatus = this.cli?.constructor?.STATUS_READY || ImportedShell?.STATUS_READY || globalThis.Shell?.STATUS_READY || globalThis.shell?.STATUS_READY || 'READY';
|
|
346
|
+
if(status === readyStatus) {
|
|
312
347
|
if (this._interactive) {
|
|
313
348
|
this._exitInteractiveMode();
|
|
314
349
|
}
|
|
@@ -644,8 +679,8 @@ class Terminal {
|
|
|
644
679
|
}
|
|
645
680
|
}
|
|
646
681
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
682
|
+
Terminal.Terminal = Terminal;
|
|
683
|
+
if (typeof globalThis !== 'undefined') {
|
|
684
|
+
globalThis.Terminal = Terminal;
|
|
685
|
+
}
|
|
686
|
+
export default Terminal;
|
package/lib/WasmCommand.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
945
|
-
|
|
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
|
-
|
package/lib/local/curl.js
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
const LocalCommand = require('./LocalCommand');
|
|
4
4
|
|
|
5
|
+
function formatBytes(bytes) {
|
|
6
|
+
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
|
|
7
|
+
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
|
8
|
+
return bytes + ' B';
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
class Curl extends LocalCommand {
|
|
6
12
|
static get name() { return 'curl'; }
|
|
7
13
|
get requiresFilesystem() { return true; }
|
|
@@ -49,6 +55,9 @@ class Curl extends LocalCommand {
|
|
|
49
55
|
case '-s': case '--silent':
|
|
50
56
|
silent = true;
|
|
51
57
|
break;
|
|
58
|
+
case '-#': case '--progress-bar':
|
|
59
|
+
// Accepted — progress bar is displayed when downloading to output file
|
|
60
|
+
break;
|
|
52
61
|
case '-L': case '--location':
|
|
53
62
|
// fetch follows redirects by default — accepted and ignored
|
|
54
63
|
break;
|
|
@@ -91,16 +100,65 @@ class Curl extends LocalCommand {
|
|
|
91
100
|
this.stdOut = '';
|
|
92
101
|
}
|
|
93
102
|
|
|
94
|
-
|
|
103
|
+
let bytes = null;
|
|
104
|
+
const total = Number(res.headers.get('content-length') || 0);
|
|
105
|
+
|
|
106
|
+
if (res.body && typeof res.body.getReader === 'function') {
|
|
107
|
+
const reader = res.body.getReader();
|
|
108
|
+
const chunks = [];
|
|
109
|
+
let loaded = 0;
|
|
110
|
+
while (true) {
|
|
111
|
+
const { done, value } = await reader.read();
|
|
112
|
+
if (done) break;
|
|
113
|
+
chunks.push(value);
|
|
114
|
+
loaded += value.length;
|
|
115
|
+
if (outputFile && !silent) {
|
|
116
|
+
if (total > 0) {
|
|
117
|
+
const pct = Math.min(100, Math.floor((loaded / total) * 100));
|
|
118
|
+
const width = 20;
|
|
119
|
+
const filled = Math.min(width, Math.round((loaded / total) * width));
|
|
120
|
+
const bar = '='.repeat(Math.max(0, filled - 1)) + (filled > 0 ? '>' : '') + ' '.repeat(Math.max(0, width - filled));
|
|
121
|
+
this.stdOut = `\r[${bar}] ${pct}% (${formatBytes(loaded)} / ${formatBytes(total)})`;
|
|
122
|
+
} else {
|
|
123
|
+
this.stdOut = `\rDownloading: ${formatBytes(loaded)}`;
|
|
124
|
+
}
|
|
125
|
+
this.flush();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
bytes = new Uint8Array(loaded);
|
|
129
|
+
let offset = 0;
|
|
130
|
+
for (const chunk of chunks) {
|
|
131
|
+
bytes.set(chunk, offset);
|
|
132
|
+
offset += chunk.length;
|
|
133
|
+
}
|
|
134
|
+
if (outputFile && !silent && loaded > 0) {
|
|
135
|
+
const finalTotal = total || loaded;
|
|
136
|
+
this.stdOut = `\r[${'='.repeat(20)}] 100% (${formatBytes(loaded)} / ${formatBytes(finalTotal)})`;
|
|
137
|
+
this.flush();
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
const buf = await res.arrayBuffer();
|
|
141
|
+
bytes = new Uint8Array(buf);
|
|
142
|
+
}
|
|
95
143
|
|
|
96
144
|
if (outputFile) {
|
|
97
145
|
try {
|
|
98
|
-
|
|
146
|
+
const contentType = res.headers.get('content-type') || '';
|
|
147
|
+
const isText = /^text\/|application\/(json|javascript|xml|x-sh)/i.test(contentType);
|
|
148
|
+
if (isText) {
|
|
149
|
+
const text = new TextDecoder().decode(bytes);
|
|
150
|
+
this.fs.setFileByPath(outputFile, text, true);
|
|
151
|
+
} else {
|
|
152
|
+
const { BinaryFile } = require('../FileSystem');
|
|
153
|
+
const fileObj = BinaryFile ? new BinaryFile(bytes.buffer, contentType || 'application/octet-stream') : bytes;
|
|
154
|
+
this.fs.setFileByPath(outputFile, fileObj, true);
|
|
155
|
+
}
|
|
99
156
|
} catch(e) {
|
|
100
157
|
this.stdErr = `curl: cannot write to '${outputFile}': ${e.message}`;
|
|
101
158
|
this.exitCode = 1;
|
|
102
159
|
}
|
|
103
160
|
} else {
|
|
161
|
+
const text = new TextDecoder().decode(bytes);
|
|
104
162
|
text.split(/\r?\n/).forEach(line => { this.stdOut = line; });
|
|
105
163
|
}
|
|
106
164
|
|