brsh 2.6.0 → 2.8.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 (46) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/Readme.md +145 -1
  3. package/bin/Readme.md +6 -3
  4. package/bin/brsh-shell.js +68 -9
  5. package/bin/exportFileSystem.js +192 -80
  6. package/dist/shell.es.js +2497 -1300
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +21 -14
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +101 -0
  11. package/dist/terminal.cjs.js.map +1 -0
  12. package/dist/terminal.es.js +290 -6965
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +4 -25
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3974 -0
  17. package/dist/wbt.es.js.map +1 -0
  18. package/dist/wbt.min.js +10 -0
  19. package/dist/wbt.min.js.map +1 -0
  20. package/index.js +160 -20
  21. package/lib/BinaryContainer.js +528 -0
  22. package/lib/Command.js +2 -1
  23. package/lib/FileSystem.js +31 -0
  24. package/lib/NodeFileSystem.js +19 -9
  25. package/lib/ReplCommand.js +520 -0
  26. package/lib/ScriptCommand.js +1 -1
  27. package/lib/Terminal.js +45 -10
  28. package/lib/WasmCommand.js +1123 -35
  29. package/lib/buildFilesystemStructure.js +15 -4
  30. package/lib/local/curl.js +60 -2
  31. package/lib/wbt/index.js +756 -0
  32. package/lib/wbt/packages/wllama.js +1051 -0
  33. package/lib/wbt/registry.js +193 -0
  34. package/lib/wbt/utils.js +118 -0
  35. package/package.json +11 -3
  36. package/test/binary-filesystem.test.js +248 -0
  37. package/test/curl.test.js +166 -0
  38. package/test/exportFileSystem.test.js +78 -0
  39. package/test/terminal.test.js +113 -0
  40. package/test/wasm-cli.test.js +127 -0
  41. package/test/wbt.test.js +1175 -0
  42. package/vite.config.demo.js +4 -0
  43. package/vite.config.js +4 -0
  44. package/vite.config.terminal.js +16 -12
  45. package/vite.config.wbt.js +21 -0
  46. package/vitest.config.js +6 -0
@@ -0,0 +1,166 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { createShell, run } from './helpers.js';
3
+ import { BinaryFile } from '../lib/FileSystem.js';
4
+
5
+ describe('curl command', () => {
6
+ let shell;
7
+ let originalFetch;
8
+
9
+ beforeEach(async () => {
10
+ shell = await createShell({
11
+ filesystem: {
12
+ home: {}
13
+ }
14
+ });
15
+ originalFetch = globalThis.fetch;
16
+ });
17
+
18
+ afterEach(() => {
19
+ globalThis.fetch = originalFetch;
20
+ });
21
+
22
+ it('fetches text and prints to stdout', async () => {
23
+ globalThis.fetch = vi.fn().mockResolvedValue({
24
+ ok: true,
25
+ status: 200,
26
+ statusText: 'OK',
27
+ headers: new Headers({ 'content-type': 'text/plain' }),
28
+ text: async () => 'Hello, world!\nLine 2',
29
+ arrayBuffer: async () => new TextEncoder().encode('Hello, world!\nLine 2').buffer
30
+ });
31
+
32
+ const res = await run(shell, 'curl https://example.com/hello.txt');
33
+ expect(res.exitCode).toBe(0);
34
+ expect(res.output).toEqual(['Hello, world!', 'Line 2']);
35
+ });
36
+
37
+ it('includes response headers with -i', async () => {
38
+ globalThis.fetch = vi.fn().mockResolvedValue({
39
+ ok: true,
40
+ status: 200,
41
+ statusText: 'OK',
42
+ headers: new Headers({
43
+ 'content-type': 'text/plain',
44
+ 'x-custom-header': 'test-val'
45
+ }),
46
+ text: async () => 'response body',
47
+ arrayBuffer: async () => new TextEncoder().encode('response body').buffer
48
+ });
49
+
50
+ const res = await run(shell, 'curl -i https://example.com');
51
+ expect(res.exitCode).toBe(0);
52
+ expect(res.output).toContain('HTTP/1.1 200 OK');
53
+ expect(res.output).toContain('x-custom-header: test-val');
54
+ expect(res.output).toContain('response body');
55
+ });
56
+
57
+ it('downloads binary data to a file without UTF-8 corruption', async () => {
58
+ // Raw bytes with non-UTF8 sequences (e.g. WASM or GGUF magic headers)
59
+ const binaryBytes = new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0xff, 0xfe, 0x80]);
60
+
61
+ globalThis.fetch = vi.fn().mockResolvedValue({
62
+ ok: true,
63
+ status: 200,
64
+ statusText: 'OK',
65
+ headers: new Headers({
66
+ 'content-type': 'application/octet-stream',
67
+ 'content-length': String(binaryBytes.length)
68
+ }),
69
+ arrayBuffer: async () => binaryBytes.buffer
70
+ });
71
+
72
+ const res = await run(shell, 'curl -s -o /home/model.wasm https://example.com/model.wasm');
73
+ expect(res.exitCode).toBe(0);
74
+
75
+ const savedFile = shell.context.fs.getFileByPath('/home/model.wasm');
76
+ expect(savedFile).toBeDefined();
77
+ expect(savedFile instanceof BinaryFile || savedFile instanceof Uint8Array).toBe(true);
78
+ expect(new Uint8Array(savedFile)).toEqual(binaryBytes);
79
+ });
80
+
81
+ it('emits live carriage return progress bar during streaming download to a file', async () => {
82
+ const chunk1 = new Uint8Array([1, 2, 3, 4, 5]);
83
+ const chunk2 = new Uint8Array([6, 7, 8, 9, 10]);
84
+ let readCount = 0;
85
+
86
+ const mockReader = {
87
+ read: vi.fn().mockImplementation(async () => {
88
+ readCount++;
89
+ if (readCount === 1) return { done: false, value: chunk1 };
90
+ if (readCount === 2) return { done: false, value: chunk2 };
91
+ return { done: true, value: undefined };
92
+ })
93
+ };
94
+
95
+ globalThis.fetch = vi.fn().mockResolvedValue({
96
+ ok: true,
97
+ status: 200,
98
+ statusText: 'OK',
99
+ headers: new Headers({
100
+ 'content-type': 'application/octet-stream',
101
+ 'content-length': '10'
102
+ }),
103
+ body: {
104
+ getReader: () => mockReader
105
+ }
106
+ });
107
+
108
+ const res = await run(shell, 'curl -o /home/stream.bin https://example.com/stream.bin');
109
+ expect(res.exitCode).toBe(0);
110
+
111
+ // Verify progress updates with \r were emitted
112
+ const progressLines = res.output.filter(l => l.startsWith('\r'));
113
+ expect(progressLines.length).toBeGreaterThan(0);
114
+ expect(progressLines.some(l => l.includes('50%'))).toBe(true);
115
+ expect(progressLines.some(l => l.includes('100%'))).toBe(true);
116
+
117
+ const savedFile = shell.context.fs.getFileByPath('/home/stream.bin');
118
+ expect(new Uint8Array(savedFile)).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
119
+ });
120
+
121
+ it('suppresses progress bar when -s / --silent is passed', async () => {
122
+ const chunk = new Uint8Array([1, 2, 3, 4, 5]);
123
+ let done = false;
124
+
125
+ const mockReader = {
126
+ read: vi.fn().mockImplementation(async () => {
127
+ if (!done) {
128
+ done = true;
129
+ return { done: false, value: chunk };
130
+ }
131
+ return { done: true, value: undefined };
132
+ })
133
+ };
134
+
135
+ globalThis.fetch = vi.fn().mockResolvedValue({
136
+ ok: true,
137
+ status: 200,
138
+ statusText: 'OK',
139
+ headers: new Headers({
140
+ 'content-type': 'application/octet-stream',
141
+ 'content-length': '5'
142
+ }),
143
+ body: {
144
+ getReader: () => mockReader
145
+ }
146
+ });
147
+
148
+ const res = await run(shell, 'curl -s -o /home/quiet.bin https://example.com/quiet.bin');
149
+ expect(res.exitCode).toBe(0);
150
+ expect(res.output.some(l => l.startsWith('\r'))).toBe(false);
151
+ });
152
+
153
+ it('automatically creates parent directories for output files', async () => {
154
+ globalThis.fetch = vi.fn().mockResolvedValue({
155
+ ok: true,
156
+ status: 200,
157
+ statusText: 'OK',
158
+ headers: new Headers({ 'content-type': 'text/plain' }),
159
+ arrayBuffer: async () => new TextEncoder().encode('nested data').buffer
160
+ });
161
+
162
+ const res = await run(shell, 'curl -s -o /home/nested/sub/dir/app.txt https://example.com/app.txt');
163
+ expect(res.exitCode).toBe(0);
164
+ expect(shell.context.fs.getFileByPath('/home/nested/sub/dir/app.txt')).toBe('nested data');
165
+ });
166
+ });
@@ -137,6 +137,18 @@ describe('buildStructure', () => {
137
137
  const { permissions } = buildStructure(root);
138
138
  expect(permissions['/bin/tool.sh']).toBe(0o755);
139
139
  });
140
+
141
+ it('encodes .wasm files as data:application/wasm;base64 and strips .wasm extension', () => {
142
+ const sub = join(root, 'bin');
143
+ mkdirSync(sub);
144
+ const wasmBytes = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
145
+ writeFileSync(join(sub, 'jq.wasm'), wasmBytes);
146
+ chmodSync(join(sub, 'jq.wasm'), 0o755);
147
+ const { filesystem, permissions } = buildStructure(root);
148
+ expect(filesystem.bin).toHaveProperty('jq');
149
+ expect(filesystem.bin.jq).toBe(`data:application/wasm;base64,${wasmBytes.toString('base64')}`);
150
+ expect(permissions['/bin/jq']).toBe(0o755);
151
+ });
140
152
  });
141
153
 
142
154
  // ---------------------------------------------------------------------------
@@ -347,3 +359,69 @@ describe('exportFileSystem CLI --compress', () => {
347
359
  expect(code.length).toBeGreaterThan(100);
348
360
  });
349
361
  });
362
+
363
+ describe('exportFileSystem CLI --binary (.brfs indexed binary container)', () => {
364
+ const { isBinaryContainer, deserializeBinaryFilesystem } = require('../lib/BinaryContainer.js');
365
+ let root;
366
+ let outDir;
367
+
368
+ beforeEach(() => {
369
+ root = tmpDir();
370
+ outDir = tmpDir();
371
+ mkdirSync(join(root, 'bin'));
372
+ writeFileSync(join(root, 'hello.txt'), 'Hello Binary Container');
373
+ writeFileSync(join(root, 'bin', 'run.sh'), '#!/sh.js\necho hi');
374
+ chmodSync(join(root, 'bin', 'run.sh'), 0o755);
375
+ writeFileSync(join(root, 'bin', 'tool.wasm'), Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
376
+ chmodSync(join(root, 'bin', 'tool.wasm'), 0o755);
377
+ });
378
+
379
+ afterEach(() => {
380
+ rmSync(root, { recursive: true, force: true });
381
+ rmSync(outDir, { recursive: true, force: true });
382
+ });
383
+
384
+ it('writes a standalone BRFS v2 binary container when -o ends with .brfs', () => {
385
+ const outFile = join(outDir, 'fs.brfs');
386
+ const r = runCLI([root, '-o', outFile]);
387
+ expect(r.status).toBe(0);
388
+ expect(existsSync(outFile)).toBe(true);
389
+
390
+ const raw = new Uint8Array(readFileSync(outFile));
391
+ expect(isBinaryContainer(raw)).toBe(true);
392
+
393
+ const { filesystem, permissions } = deserializeBinaryFilesystem(raw);
394
+ expect(filesystem['hello.txt']).toBe('Hello Binary Container');
395
+ expect(filesystem.bin['run.sh']).toBe('#!/sh.js\necho hi');
396
+ expect(filesystem.bin.tool instanceof Uint8Array).toBe(true);
397
+ expect(permissions['/bin/run.sh']).toBe(0o755);
398
+ expect(permissions['/bin/tool']).toBe(0o755);
399
+ });
400
+
401
+ it('writes a JS loader and .brfs binary container when --binary (-b) is passed with -o fs.js', () => {
402
+ const outFile = join(outDir, 'fs.js');
403
+ const r = runCLI([root, '-v', 'FS', '-o', outFile, '--binary']);
404
+ expect(r.status).toBe(0);
405
+ expect(existsSync(outFile)).toBe(true);
406
+ expect(existsSync(join(outDir, 'fs.brfs'))).toBe(true);
407
+
408
+ const raw = new Uint8Array(readFileSync(join(outDir, 'fs.brfs')));
409
+ expect(isBinaryContainer(raw)).toBe(true);
410
+ });
411
+
412
+ it('boots a Shell directly from an exported .brfs file path and executes scripts inside it', async () => {
413
+ const Shell = require('../index.js');
414
+ const outFile = join(outDir, 'fs.brfs');
415
+ const r = runCLI([root, '-o', outFile]);
416
+ expect(r.status).toBe(0);
417
+
418
+ const shell = new Shell({ filesystem: outFile });
419
+ const output = [];
420
+ shell.on('stdOut', line => output.push(line));
421
+ await shell.onCommand('run.sh && cat /hello.txt');
422
+
423
+ expect(output).toContain('hi');
424
+ expect(output).toContain('Hello Binary Container');
425
+ });
426
+ });
427
+
@@ -0,0 +1,113 @@
1
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
2
+ import Shell from '../index.js';
3
+ import Terminal from '../lib/Terminal.js';
4
+
5
+ describe('Terminal decoupling and Shell resolution', () => {
6
+ let originalWindow;
7
+ let originalDocument;
8
+ let originalShell;
9
+ let originalGlobalShell;
10
+
11
+ beforeAll(() => {
12
+ originalWindow = globalThis.window;
13
+ originalDocument = globalThis.document;
14
+ originalShell = globalThis.Shell;
15
+ originalGlobalShell = globalThis.shell;
16
+
17
+ // Minimal DOM mock
18
+ globalThis.window = {
19
+ addEventListener: () => {},
20
+ removeEventListener: () => {}
21
+ };
22
+ globalThis.document = {
23
+ createElement: () => ({
24
+ style: {},
25
+ classList: { add: () => {} },
26
+ appendChild: () => {},
27
+ setAttribute: () => {},
28
+ addEventListener: () => {},
29
+ getBoundingClientRect: () => ({ width: 800, height: 600 }),
30
+ querySelectorAll: () => []
31
+ }),
32
+ head: { appendChild: () => {} }
33
+ };
34
+ });
35
+
36
+ afterAll(() => {
37
+ globalThis.window = originalWindow;
38
+ globalThis.document = originalDocument;
39
+ globalThis.Shell = originalShell;
40
+ globalThis.shell = originalGlobalShell;
41
+ });
42
+
43
+ it('instantiates with options.cli directly', () => {
44
+ delete globalThis.Shell;
45
+ delete globalThis.shell;
46
+
47
+ const customShell = new Shell({ cwd: '/test' });
48
+ const term = new Terminal({
49
+ el: document.createElement('div'),
50
+ cli: customShell
51
+ });
52
+
53
+ expect(term.cli).toBe(customShell);
54
+ });
55
+
56
+ it('instantiates with options.Shell constructor', () => {
57
+ delete globalThis.Shell;
58
+ delete globalThis.shell;
59
+
60
+ const term = new Terminal({
61
+ el: document.createElement('div'),
62
+ Shell: Shell,
63
+ cwd: '/test'
64
+ });
65
+
66
+ expect(term.cli).toBeInstanceOf(Shell);
67
+ });
68
+
69
+ it('instantiates with globalThis.Shell fallback', () => {
70
+ globalThis.Shell = Shell;
71
+
72
+ const term = new Terminal({
73
+ el: document.createElement('div'),
74
+ cwd: '/test'
75
+ });
76
+
77
+ expect(term.cli).toBeInstanceOf(Shell);
78
+ });
79
+
80
+ it('throws a helpful error when no Shell or cli is available', () => {
81
+ delete globalThis.Shell;
82
+ delete globalThis.shell;
83
+
84
+ expect(() => {
85
+ new Terminal({
86
+ el: document.createElement('div'),
87
+ Shell: null
88
+ });
89
+ }).toThrow(/Shell is required by Terminal/);
90
+ });
91
+
92
+ it('can be required as a CommonJS module via dist/terminal.cjs.js', () => {
93
+ const { createRequire } = require('module');
94
+ const fs = require('fs');
95
+ const path = require('path');
96
+ const cjsRequire = createRequire(import.meta.url);
97
+ const distFile = path.resolve(import.meta.dirname, '../dist/terminal.cjs.js');
98
+ if (!fs.existsSync(distFile)) {
99
+ const { execSync } = require('child_process');
100
+ execSync('npm run build:terminal', { stdio: 'ignore' });
101
+ }
102
+ const CjsTerminal = cjsRequire('../dist/terminal.cjs.js');
103
+ const TermClass = CjsTerminal.default || CjsTerminal;
104
+ expect(typeof TermClass).toBe('function');
105
+
106
+ const customShell = new Shell({ cwd: '/test' });
107
+ const term = new TermClass({
108
+ el: document.createElement('div'),
109
+ cli: customShell
110
+ });
111
+ expect(term.cli).toBe(customShell);
112
+ });
113
+ });
@@ -0,0 +1,127 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import Shell from '../index.js';
3
+ import { run } from './helpers.js';
4
+
5
+ // Minimal valid WASM binary that exports _start and exits with 0:
6
+ const MINIMAL_WASM_BYTES = new Uint8Array([
7
+ 0x00, 0x61, 0x73, 0x6d,
8
+ 0x01, 0x00, 0x00, 0x00,
9
+ 0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
10
+ 0x03, 0x02, 0x01, 0x00,
11
+ 0x07, 0x0a, 0x01, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x00, 0x00,
12
+ 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b
13
+ ]);
14
+
15
+ describe('Running .wasm files directly as CLI tools in base shell', () => {
16
+ it('refuses to execute a .wasm file without execute permissions (permission denied)', async () => {
17
+ const shell = new Shell({
18
+ filesystem: {
19
+ home: {
20
+ 'mytool.wasm': MINIMAL_WASM_BYTES
21
+ }
22
+ },
23
+ cwd: '/home'
24
+ });
25
+
26
+ // Default mode is 0o644 -> not executable
27
+ const res = await run(shell, './mytool.wasm');
28
+ expect(res.exitCode).toBe(1);
29
+ expect(res.errors.join('')).toContain('permission denied');
30
+ });
31
+
32
+ it('executes a .wasm file via ./mytool.wasm after chmod +x', async () => {
33
+ const shell = new Shell({
34
+ filesystem: {
35
+ home: {
36
+ 'mytool.wasm': MINIMAL_WASM_BYTES
37
+ }
38
+ },
39
+ cwd: '/home'
40
+ });
41
+
42
+ await run(shell, 'chmod +x mytool.wasm');
43
+ const res = await run(shell, './mytool.wasm');
44
+ expect(res.exitCode).toBe(0);
45
+ });
46
+
47
+ it('refuses to run a file in cwd by bare name without path (standard PATH behavior)', async () => {
48
+ const shell = new Shell({
49
+ filesystem: {
50
+ home: {
51
+ 'mytool.wasm': MINIMAL_WASM_BYTES
52
+ }
53
+ },
54
+ permissions: {
55
+ '/home/mytool.wasm': 0o755
56
+ },
57
+ cwd: '/home'
58
+ });
59
+
60
+ const res = await run(shell, 'mytool.wasm');
61
+ expect(res.exitCode).toBe(1);
62
+ expect(res.errors.join('')).toContain('Command not found');
63
+ });
64
+
65
+ it('executes an executable .wasm file placed in /bin by bare name without .wasm extension', async () => {
66
+ const shell = new Shell({
67
+ filesystem: {
68
+ bin: {
69
+ 'cowsay.wasm': MINIMAL_WASM_BYTES
70
+ }
71
+ },
72
+ permissions: {
73
+ '/bin/cowsay.wasm': 0o755
74
+ }
75
+ });
76
+
77
+ const res = await run(shell, 'cowsay');
78
+ expect(res.exitCode).toBe(0);
79
+ });
80
+
81
+ it('supports --help and --version automatically on raw .wasm binaries', async () => {
82
+ const shell = new Shell({
83
+ filesystem: {
84
+ home: {
85
+ 'mytool.wasm': MINIMAL_WASM_BYTES
86
+ }
87
+ },
88
+ permissions: {
89
+ '/home/mytool.wasm': 0o755
90
+ },
91
+ cwd: '/home'
92
+ });
93
+
94
+ const helpRes = await run(shell, './mytool.wasm --help');
95
+ expect(helpRes.exitCode).toBe(0);
96
+ const helpText = helpRes.output.join('\n');
97
+ expect(helpText).toContain('Usage: mytool.wasm');
98
+ expect(helpText).toContain('-h, --help');
99
+ expect(helpText).toContain('-V, --version');
100
+ expect(helpText).toContain('WASM Exports: _start');
101
+
102
+ const verRes = await run(shell, './mytool.wasm --version');
103
+ expect(verRes.exitCode).toBe(0);
104
+ expect(verRes.output.join('\n')).toContain('mytool.wasm');
105
+ });
106
+
107
+ it('supports piping stdin into .wasm binaries and redirecting stdout to files', async () => {
108
+ const shell = new Shell({
109
+ filesystem: {
110
+ bin: {
111
+ 'mytool.wasm': MINIMAL_WASM_BYTES
112
+ }
113
+ },
114
+ permissions: {
115
+ '/bin/mytool.wasm': 0o755
116
+ }
117
+ });
118
+
119
+ const pipeRes = await run(shell, 'echo "input data" | mytool');
120
+ expect(pipeRes.exitCode).toBe(0);
121
+
122
+ const redirRes = await run(shell, 'mytool --help > /help.txt');
123
+ expect(redirRes.exitCode).toBe(0);
124
+ expect(shell.context.fs.exists('/help.txt')).toBe(true);
125
+ expect(shell.context.fs.getFileByPath('/help.txt')).toContain('Usage: mytool.wasm');
126
+ });
127
+ });