brsh 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/Readme.md +127 -0
- package/bin/Readme.md +6 -3
- package/bin/brsh-shell.js +53 -8
- package/bin/exportFileSystem.js +192 -80
- package/dist/shell.es.js +2419 -1277
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +21 -14
- package/dist/shell.min.js.map +1 -1
- package/dist/terminal.es.js +2475 -1333
- package/dist/terminal.es.js.map +1 -1
- package/dist/terminal.min.js +23 -16
- package/dist/terminal.min.js.map +1 -1
- package/dist/wbt.es.js +9449 -0
- package/dist/wbt.es.js.map +1 -0
- package/dist/wbt.min.js +24 -0
- package/dist/wbt.min.js.map +1 -0
- package/index.js +131 -20
- package/lib/BinaryContainer.js +528 -0
- package/lib/Command.js +2 -1
- package/lib/FileSystem.js +31 -0
- package/lib/NodeFileSystem.js +19 -9
- package/lib/ReplCommand.js +520 -0
- package/lib/ScriptCommand.js +1 -1
- package/lib/WasmCommand.js +1123 -35
- package/lib/buildFilesystemStructure.js +15 -4
- package/lib/wbt/daemon.js +264 -0
- package/lib/wbt/index.js +779 -0
- package/lib/wbt/packages/pglite.js +590 -0
- package/lib/wbt/registry.js +190 -0
- package/lib/wbt/utils.js +118 -0
- package/package.json +9 -2
- package/test/binary-filesystem.test.js +248 -0
- package/test/exportFileSystem.test.js +78 -0
- package/test/wbt.test.js +1084 -0
- package/vite.config.demo.js +4 -0
- package/vite.config.js +4 -0
- package/vite.config.wbt.js +21 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
# [2.7.0](https://github.com/eliotstocker/Brsh-JS/compare/v2.6.0...v2.7.0) (2026-11-07)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* add optional Web Binary Tool (wbt) WASM package manager ([#25](https://github.com/eliotstocker/Brsh-JS/issues/25)) ([3407c84](https://github.com/eliotstocker/Brsh-JS/commit/3407c84557f45c927778ca160e79ca057290e9e3))
|
|
7
|
+
|
|
1
8
|
# [2.6.0](https://github.com/eliotstocker/Brsh-JS/compare/v2.5.6...v2.6.0) (2026-11-07)
|
|
2
9
|
|
|
3
10
|
|
package/Readme.md
CHANGED
|
@@ -208,6 +208,133 @@ Scripts run in a sub-shell and do not share context with the parent. To persist
|
|
|
208
208
|
|
|
209
209
|
**Note:** when using [exportFileSystem](bin/Readme.md), do not give scripts a `.js` extension — that causes them to be loaded as JavaScript modules rather than script strings.
|
|
210
210
|
|
|
211
|
+
## Web Binary Tool (`wbt`) — Optional WASM Binary Manager
|
|
212
|
+
|
|
213
|
+
`wbt` is an optional, APT-style binary manager for `brsh` that lets users install and run WebAssembly binaries (such as `pglite`, `sqlite3`, `assemblyscript` / `asc`, `jq`, `python3`, `duckdb`, `graphviz`, `ffmpeg`, `wabt`, `quickjs`, `lua`, or custom `.wasm`/`.wat` URLs). It is **not** included in the default shell bundle unless you explicitly register it.
|
|
214
|
+
|
|
215
|
+
### Enabling `wbt`
|
|
216
|
+
|
|
217
|
+
```js
|
|
218
|
+
// ESM
|
|
219
|
+
import Terminal from 'brsh/terminal';
|
|
220
|
+
import Wbt from 'brsh/wbt';
|
|
221
|
+
|
|
222
|
+
const term = new Terminal({ el: document.body });
|
|
223
|
+
term.cli.context.setCommand(Wbt);
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
```js
|
|
227
|
+
// CJS
|
|
228
|
+
const Shell = require('brsh');
|
|
229
|
+
const Wbt = require('brsh/wbt');
|
|
230
|
+
|
|
231
|
+
const shell = new Shell({ filesystem: {} });
|
|
232
|
+
shell.context.setCommand(Wbt);
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Usage in the shell
|
|
236
|
+
|
|
237
|
+
```sh
|
|
238
|
+
# List available or installed WASM packages
|
|
239
|
+
wbt list
|
|
240
|
+
wbt list --installed
|
|
241
|
+
|
|
242
|
+
# Search and inspect packages
|
|
243
|
+
wbt search postgres
|
|
244
|
+
wbt show pglite
|
|
245
|
+
|
|
246
|
+
# Install curated WASM packages into /bin
|
|
247
|
+
wbt install pglite sqlite3 assemblyscript jq python3 duckdb graphviz ffmpeg
|
|
248
|
+
|
|
249
|
+
# Run PGlite as a one-shot query, interactive REPL, or a background server daemon!
|
|
250
|
+
pglite -d /home/pgdata -c "CREATE TABLE users (id INT, name TEXT); INSERT INTO users VALUES (1, 'Ada');"
|
|
251
|
+
pglite # launches interactive PostgreSQL REPL
|
|
252
|
+
|
|
253
|
+
# Start a PGlite background daemon on localhost:5432 and query it via HTTP (curl / fetch) or psql
|
|
254
|
+
pg_ctl start -D /home/pgdata -p 5432
|
|
255
|
+
wbt services
|
|
256
|
+
curl -s -X POST -d "SELECT * FROM users;" http://localhost:5432/query
|
|
257
|
+
psql -p 5432 -c "SELECT * FROM users;"
|
|
258
|
+
pg_ctl stop -p 5432
|
|
259
|
+
|
|
260
|
+
# Run SQLite3 (persists database files directly in the brsh filesystem)
|
|
261
|
+
sqlite3 /home/app.db "CREATE TABLE notes (id INT, body TEXT); INSERT INTO notes VALUES (1, 'Hello WASM');"
|
|
262
|
+
sqlite3 -table /home/app.db "SELECT * FROM notes;"
|
|
263
|
+
echo "SELECT * FROM notes;" | sqlite3 -csv /home/app.db
|
|
264
|
+
|
|
265
|
+
# Run AssemblyScript directly like ts-node / node (`asrun` / `asnode`), or compile to .wasm (`asc`)
|
|
266
|
+
asrun -e "console.log('Hello from AssemblyScript!')"
|
|
267
|
+
asrun /home/script.ts
|
|
268
|
+
asc /home/hello.ts -o /home/hello.wasm && /home/hello.wasm
|
|
269
|
+
|
|
270
|
+
# Other built-in WASM tools: jq, python3 (Pyodide), duckdb, dot (Graphviz), ffmpeg
|
|
271
|
+
cat data.json | jq -r ".user.name"
|
|
272
|
+
python3 -c "print([x * x for x in range(5)])"
|
|
273
|
+
duckdb -c "SELECT 42 AS answer"
|
|
274
|
+
dot -Tsvg graph.dot -o graph.svg
|
|
275
|
+
ffmpeg -i input.mp4 output.webm
|
|
276
|
+
|
|
277
|
+
# Install any generic Emscripten / WASI package or custom .wasm URL at runtime (no custom wrapper needed!)
|
|
278
|
+
wbt install npm:cowsay-wasm
|
|
279
|
+
wbt install mytool https://example.com/mytool.wasm
|
|
280
|
+
mytool
|
|
281
|
+
|
|
282
|
+
# Remove an installed binary
|
|
283
|
+
wbt remove sqlite3
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Binary Filesystem Container (`.brfs`) & Client-Side Persistence
|
|
287
|
+
|
|
288
|
+
While `brsh` continues to support standard JS object filesystems (and legacy `.brsh` compressed JS bundles), it also supports an **Indexed Binary Container (`.brfs`)** format (`BRFS` magic header + JSON metadata/permissions index + contiguous raw binary payload with zero base64 overhead) as well as **IndexedDB client-side persistence**.
|
|
289
|
+
|
|
290
|
+
### Exporting a `.brfs` Binary Container
|
|
291
|
+
|
|
292
|
+
```shell
|
|
293
|
+
# Standalone .brfs binary container (load via fetch('/fs.brfs').then(r => r.arrayBuffer()))
|
|
294
|
+
exportFileSystem ./filesystem -o ./fs.brfs
|
|
295
|
+
|
|
296
|
+
# Or generate a JS loader that fetches and mounts ./fs.brfs automatically
|
|
297
|
+
exportFileSystem ./filesystem -o ./fs.js -v fs --binary
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Mounting & Snapshot Serialization
|
|
301
|
+
|
|
302
|
+
```js
|
|
303
|
+
// Pass a .brfs URL directly to Terminal or Shell (no JS loader needed!):
|
|
304
|
+
const term = new Terminal({
|
|
305
|
+
el: document.body,
|
|
306
|
+
filesystem: '/fs.brfs'
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// Or pass a pre-fetched ArrayBuffer / Uint8Array (raw or gzip-compressed):
|
|
310
|
+
const bytes = new Uint8Array(await (await fetch('/fs.brfs')).arrayBuffer());
|
|
311
|
+
const shell = new Shell({ filesystem: bytes });
|
|
312
|
+
|
|
313
|
+
// Export the live filesystem (including runtime changes, permissions, symlinks, and binaries) to a .brfs Uint8Array:
|
|
314
|
+
const snapshot = shell.context.fs.toBinaryContainer();
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
### Client-Side Persistence (IndexedDB)
|
|
318
|
+
|
|
319
|
+
Use `Shell.Storage` (`FilesystemStorage`) to persist user changes across page reloads in IndexedDB:
|
|
320
|
+
|
|
321
|
+
```js
|
|
322
|
+
const Terminal = require('brsh/terminal');
|
|
323
|
+
const Shell = require('brsh');
|
|
324
|
+
|
|
325
|
+
const term = new Terminal({
|
|
326
|
+
el: document.body,
|
|
327
|
+
// Loads saved snapshot from IndexedDB if present, otherwise fetches '/fs.brfs'
|
|
328
|
+
filesystem: Shell.Storage.loadOrFetch('my-app', '/fs.brfs'),
|
|
329
|
+
// Automatically persists binary container to IndexedDB whenever files or permissions change
|
|
330
|
+
onFsChange: Shell.Storage.createAutoSave('my-app')
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
// Or manually save/load at any time:
|
|
334
|
+
await Shell.Storage.save(term.cli, 'my-app');
|
|
335
|
+
const savedFs = await Shell.Storage.load('my-app');
|
|
336
|
+
```
|
|
337
|
+
|
|
211
338
|
## More Examples
|
|
212
339
|
On my website I have extended the functionality adding some simple extra utilities such as an ANSI image viewer and a markdown parser based on open-source node CLI utilities.
|
|
213
340
|
|
package/bin/Readme.md
CHANGED
|
@@ -7,8 +7,9 @@ the export file system command can be used to export a local folder structure fo
|
|
|
7
7
|
it will travers the directory structure from the provided base path, and import all files based on the following rules:
|
|
8
8
|
|
|
9
9
|
* Javascript files (.js): imported as node modules, whatever they export will be available to Shell JS, this is really useful for adding new commands just make sure you set module.exports to your Command class
|
|
10
|
-
*
|
|
11
|
-
*
|
|
10
|
+
* WebAssembly files (.wasm): automatically wrapped as executable `WasmCommand` binaries (especially when placed in `/bin`) or stored as raw binary files
|
|
11
|
+
* Binary files (.jpg, .png, .bmp, .pdf, .zip, etc.): stored as `BinaryFile` instances (or raw zero-overhead byte slices when using `--binary` / `.brfs`)
|
|
12
|
+
* all other files: imported as UTF-8 string representations of the data inside (preserving Unix file permissions and symlinks)
|
|
12
13
|
|
|
13
14
|
## CLI options
|
|
14
15
|
|
|
@@ -16,7 +17,9 @@ it will travers the directory structure from the provided base path, and import
|
|
|
16
17
|
| ---- | ----- | -------- | ----------- |
|
|
17
18
|
| root | | `String` path | also the default option, this is the path to the root of your file system |
|
|
18
19
|
| variable | v | `String` name | final variable output name for instance if set to `filesystem` when this file is loaded in a browser it will be accessible at `window.filesystem` |
|
|
19
|
-
| output | o | `String` path | path for the output
|
|
20
|
+
| output | o | `String` path | path for the output file (`.js` bundle or standalone `.brfs` binary container; if not set will output to stdout) |
|
|
21
|
+
| binary | b | | emit an indexed `BRFS` binary container (`.brfs`) with raw binary payloads, permissions, and symlinks instead of base64-in-JS |
|
|
22
|
+
| compress | c | | emit a gzip-compressed bundle alongside a browser decompression loader (legacy `.brsh` / `.brfs` mode) |
|
|
20
23
|
| pretty | p | | if pretty is set we will disable code uglification and pretify the json directory structure |
|
|
21
24
|
| hyperlinks | h | | enable experimental hyperlink support for application (this will pass through an environment variable to your filesystem FORCE_HYPERLINK some libraries will pick up on this and pass back ansi links) |
|
|
22
25
|
|
package/bin/brsh-shell.js
CHANGED
|
@@ -11,9 +11,27 @@
|
|
|
11
11
|
// brsh-shell -i -c "cmd" force interactive after running -c
|
|
12
12
|
|
|
13
13
|
const Shell = require('../index.js');
|
|
14
|
+
const Wbt = require('../lib/wbt');
|
|
15
|
+
const Pico = require('../demo/pico');
|
|
16
|
+
const { buildStructure } = require('../lib/buildFilesystemStructure');
|
|
14
17
|
const readline = require('readline');
|
|
15
18
|
const nodePath = require('path');
|
|
16
19
|
|
|
20
|
+
function resolveRequireNodes(node) {
|
|
21
|
+
if (!node || typeof node !== 'object') return node;
|
|
22
|
+
for (const [k, v] of Object.entries(node)) {
|
|
23
|
+
if (typeof v === 'string') {
|
|
24
|
+
const m = v.match(/^require\('(.*)'\)$/);
|
|
25
|
+
if (m) {
|
|
26
|
+
try { node[k] = require(m[1]); } catch { /* ignore */ }
|
|
27
|
+
}
|
|
28
|
+
} else if (v && typeof v === 'object') {
|
|
29
|
+
resolveRequireNodes(v);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return node;
|
|
33
|
+
}
|
|
34
|
+
|
|
17
35
|
// ── CLI argument parsing ──────────────────────────────────────────────────────
|
|
18
36
|
|
|
19
37
|
const argv = process.argv.slice(2);
|
|
@@ -22,6 +40,7 @@ let scriptFile = null; // positional script path
|
|
|
22
40
|
let scriptArgs = []; // args after the script filename
|
|
23
41
|
const shellFlags = []; // single-char flags to activate via `set`
|
|
24
42
|
let forceInteractive = false;
|
|
43
|
+
let demoMode = false;
|
|
25
44
|
|
|
26
45
|
for (let i = 0; i < argv.length; i++) {
|
|
27
46
|
const arg = argv[i];
|
|
@@ -29,6 +48,10 @@ for (let i = 0; i < argv.length; i++) {
|
|
|
29
48
|
if (scriptFile) scriptArgs = argv.slice(i + 1);
|
|
30
49
|
break;
|
|
31
50
|
}
|
|
51
|
+
if (arg === '--demo') {
|
|
52
|
+
demoMode = true;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
32
55
|
if (arg === '-c') {
|
|
33
56
|
commandString = argv[++i] !== undefined ? argv[i] : '';
|
|
34
57
|
continue;
|
|
@@ -52,11 +75,29 @@ const isInteractive = forceInteractive || (commandString === null && scriptFile
|
|
|
52
75
|
|
|
53
76
|
// ── Shell setup ───────────────────────────────────────────────────────────────
|
|
54
77
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
78
|
+
let shellOptions;
|
|
79
|
+
if (demoMode) {
|
|
80
|
+
const demoDir = nodePath.resolve(__dirname, '../demo/filesystem');
|
|
81
|
+
const { filesystem, permissions } = buildStructure(demoDir);
|
|
82
|
+
resolveRequireNodes(filesystem);
|
|
83
|
+
shellOptions = {
|
|
84
|
+
filesystem,
|
|
85
|
+
permissions,
|
|
86
|
+
profile: '/root/.profile',
|
|
87
|
+
cwd: '/root',
|
|
88
|
+
hostname: 'brsh'
|
|
89
|
+
};
|
|
90
|
+
} else {
|
|
91
|
+
shellOptions = {
|
|
92
|
+
useRealFilesystem: true,
|
|
93
|
+
cwd: process.cwd(),
|
|
94
|
+
hostname: require('os').hostname().split('.')[0]
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const shell = new Shell(shellOptions);
|
|
99
|
+
shell.context.setCommand(Wbt);
|
|
100
|
+
shell.context.setCommand(Pico);
|
|
60
101
|
|
|
61
102
|
let destroyed = false;
|
|
62
103
|
let rl;
|
|
@@ -118,9 +159,13 @@ async function runNonInteractive() {
|
|
|
118
159
|
}
|
|
119
160
|
|
|
120
161
|
if (!isInteractive) {
|
|
121
|
-
|
|
122
|
-
if (status === Shell.STATUS_READY)
|
|
123
|
-
|
|
162
|
+
const onReady = status => {
|
|
163
|
+
if (status === Shell.STATUS_READY) {
|
|
164
|
+
shell.removeListener('status', onReady);
|
|
165
|
+
runNonInteractive();
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
shell.on('status', onReady);
|
|
124
169
|
return;
|
|
125
170
|
}
|
|
126
171
|
|
package/bin/exportFileSystem.js
CHANGED
|
@@ -9,6 +9,7 @@ const cla = require('command-line-args');
|
|
|
9
9
|
const tmp = require('tmp');
|
|
10
10
|
const { polyfillNode } = require('esbuild-plugin-polyfill-node');
|
|
11
11
|
const { buildStructure } = require('../lib/buildFilesystemStructure');
|
|
12
|
+
const { serializeBinaryFilesystem } = require('../lib/BinaryContainer');
|
|
12
13
|
|
|
13
14
|
let options;
|
|
14
15
|
try {
|
|
@@ -22,7 +23,7 @@ try {
|
|
|
22
23
|
{
|
|
23
24
|
name: 'variable',
|
|
24
25
|
alias: 'v',
|
|
25
|
-
required:
|
|
26
|
+
required: false,
|
|
26
27
|
type: String
|
|
27
28
|
},
|
|
28
29
|
{
|
|
@@ -44,6 +45,11 @@ try {
|
|
|
44
45
|
name: 'compress',
|
|
45
46
|
alias: 'c',
|
|
46
47
|
type: Boolean
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: 'binary',
|
|
51
|
+
alias: 'b',
|
|
52
|
+
type: Boolean
|
|
47
53
|
}
|
|
48
54
|
]);
|
|
49
55
|
} catch(e) {
|
|
@@ -56,7 +62,10 @@ if(!options.root) {
|
|
|
56
62
|
process.exit(1);
|
|
57
63
|
}
|
|
58
64
|
|
|
59
|
-
|
|
65
|
+
const isStandaloneBrfsOutput = Boolean(options.output && options.output.endsWith('.brfs'));
|
|
66
|
+
const useBinaryContainer = Boolean(options.binary || isStandaloneBrfsOutput);
|
|
67
|
+
|
|
68
|
+
if(!options.variable && !isStandaloneBrfsOutput) {
|
|
60
69
|
console.log('missing required --variable (-v) flag');
|
|
61
70
|
process.exit(1);
|
|
62
71
|
}
|
|
@@ -77,20 +86,11 @@ try {
|
|
|
77
86
|
}
|
|
78
87
|
const { filesystem, permissions } = struct;
|
|
79
88
|
|
|
80
|
-
if (options.compress && !options.output) {
|
|
81
|
-
console.log('--compress requires --output (-o) to be set');
|
|
89
|
+
if ((options.compress || options.binary) && !options.output) {
|
|
90
|
+
console.log('--compress / --binary requires --output (-o) to be set');
|
|
82
91
|
process.exit(1);
|
|
83
92
|
}
|
|
84
93
|
|
|
85
|
-
const fsJson = JSON.stringify(filesystem, null, options.pretty ? 2 : null);
|
|
86
|
-
const permJson = JSON.stringify(permissions, null, options.pretty ? 2 : null);
|
|
87
|
-
const fsJS = fsJson.replace(/"(require\('.*?'\))"/gm, '$1');
|
|
88
|
-
|
|
89
|
-
const JS = `module.exports = { filesystem: ${fsJS}, permissions: ${permJson} }`;
|
|
90
|
-
|
|
91
|
-
const tf = tmp.fileSync({ postfix: '.tmp.js' });
|
|
92
|
-
fs.writeFileSync(tf.name, JS);
|
|
93
|
-
|
|
94
94
|
const alias = {
|
|
95
95
|
'supports-color': 'supports-color/index',
|
|
96
96
|
};
|
|
@@ -114,6 +114,7 @@ const textLoaderPlugin = {
|
|
|
114
114
|
&& !filename.endsWith('.bmp')
|
|
115
115
|
&& !filename.endsWith('.webp')
|
|
116
116
|
&& !filename.endsWith('.ico')
|
|
117
|
+
&& !filename.endsWith('.wasm')
|
|
117
118
|
) {
|
|
118
119
|
const contents = await fs.promises.readFile(args.path, 'utf8');
|
|
119
120
|
return { contents, loader: 'text' };
|
|
@@ -122,73 +123,184 @@ const textLoaderPlugin = {
|
|
|
122
123
|
}
|
|
123
124
|
};
|
|
124
125
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
'.png': 'binary',
|
|
139
|
-
'.jpg': 'binary',
|
|
140
|
-
'.jpeg': 'binary',
|
|
141
|
-
'.bmp': 'binary',
|
|
142
|
-
'.webp': 'binary',
|
|
143
|
-
'.ico': 'binary'
|
|
144
|
-
},
|
|
145
|
-
plugins: [
|
|
146
|
-
textLoaderPlugin,
|
|
147
|
-
polyfillNode()
|
|
148
|
-
],
|
|
149
|
-
define: {
|
|
150
|
-
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
151
|
-
'process.env.COLORTERM': JSON.stringify('truecolor'),
|
|
152
|
-
'process.env.TERM': JSON.stringify('color'),
|
|
153
|
-
'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
|
|
154
|
-
},
|
|
155
|
-
alias,
|
|
156
|
-
})
|
|
157
|
-
.then(() => {
|
|
158
|
-
if (options.compress) {
|
|
159
|
-
// Post-process: gzip the entire esbuild output.
|
|
160
|
-
// The compressed bytes are written to <output>.gz as raw binary.
|
|
161
|
-
// The JS file is replaced with a tiny loader that fetches the .gz,
|
|
162
|
-
// decompresses it, and executes it — no base64 overhead.
|
|
163
|
-
const bundle = fs.readFileSync(options.output, 'utf8');
|
|
164
|
-
// Append a return statement so new Function() can hand back the value
|
|
165
|
-
const codeToCompress = bundle + `\nreturn ${options.variable};`;
|
|
166
|
-
const compressed = zlib.gzipSync(Buffer.from(codeToCompress, 'utf8'));
|
|
167
|
-
const gzPath = options.output.replace(/\.js$/, '') + '.brfs';
|
|
168
|
-
fs.writeFileSync(gzPath, compressed);
|
|
169
|
-
|
|
170
|
-
const varName = options.variable;
|
|
171
|
-
// The loader captures document.currentScript.src synchronously
|
|
172
|
-
// (unavailable once the async IIFE runs) and derives the .brfs URL.
|
|
173
|
-
const loader =
|
|
174
|
-
`globalThis.${varName}=(function(){` +
|
|
175
|
-
`var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
|
|
176
|
-
`typeof location!=="undefined"?location.href:null;` +
|
|
177
|
-
`if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
|
|
178
|
-
`var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
|
|
179
|
-
`return fetch(u)` +
|
|
180
|
-
`.then(function(r){return r.arrayBuffer();})` +
|
|
181
|
-
`.then(function(b){` +
|
|
182
|
-
`var ds=new DecompressionStream("gzip");` +
|
|
183
|
-
`var w=ds.writable.getWriter();` +
|
|
184
|
-
`w.write(new Uint8Array(b));` +
|
|
185
|
-
`w.close();` +
|
|
186
|
-
`return new Response(ds.readable).text();` +
|
|
187
|
-
`})` +
|
|
188
|
-
`.then(function(code){return new Function(code)();});` +
|
|
189
|
-
`})();`;
|
|
190
|
-
fs.writeFileSync(options.output, loader);
|
|
191
|
-
console.log(`Compressed bundle written to ${gzPath}`);
|
|
126
|
+
/**
|
|
127
|
+
* Extracts all `require('...')` JS command entries from `filesystem`, replaces them with dummy
|
|
128
|
+
* function markers in `filesystem` so `serializeBinaryFilesystem` emits `{ "$c": virtualPath }`,
|
|
129
|
+
* and returns a Map of `virtualPath -> require('...')` for esbuild bundling.
|
|
130
|
+
*/
|
|
131
|
+
function extractJsCommandsForBinary(node, prefix = '', map = {}) {
|
|
132
|
+
for (const [k, v] of Object.entries(node)) {
|
|
133
|
+
const vPath = `${prefix}/${k}`;
|
|
134
|
+
if (typeof v === 'string' && /^require\('.*'\)$/.test(v)) {
|
|
135
|
+
map[vPath] = v;
|
|
136
|
+
node[k] = function __brfsCommandPlaceholder() {};
|
|
137
|
+
} else if (v && typeof v === 'object' && !(v instanceof Uint8Array)) {
|
|
138
|
+
extractJsCommandsForBinary(v, vPath, map);
|
|
192
139
|
}
|
|
140
|
+
}
|
|
141
|
+
return map;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function buildBinaryContainerMode() {
|
|
145
|
+
const cmdMap = extractJsCommandsForBinary(filesystem);
|
|
146
|
+
let commandsBundle = null;
|
|
147
|
+
|
|
148
|
+
if (Object.keys(cmdMap).length > 0) {
|
|
149
|
+
const entriesCode = Object.entries(cmdMap)
|
|
150
|
+
.map(([vPath, reqExpr]) => `${JSON.stringify(vPath)}: ${reqExpr}`)
|
|
151
|
+
.join(',\n');
|
|
152
|
+
const cmdEntryJs = `module.exports = {\n${entriesCode}\n};`;
|
|
153
|
+
const tfCmd = tmp.fileSync({ postfix: '.cmd.tmp.js' });
|
|
154
|
+
const tfOut = tmp.fileSync({ postfix: '.cmd.out.js' });
|
|
155
|
+
fs.writeFileSync(tfCmd.name, cmdEntryJs);
|
|
156
|
+
|
|
157
|
+
await esbuild.build({
|
|
158
|
+
entryPoints: [tfCmd.name],
|
|
159
|
+
bundle: true,
|
|
160
|
+
format: 'iife',
|
|
161
|
+
platform: 'browser',
|
|
162
|
+
treeShaking: true,
|
|
163
|
+
outfile: tfOut.name,
|
|
164
|
+
allowOverwrite: true,
|
|
165
|
+
globalName: '__brfs_cmds',
|
|
166
|
+
minify: !options.pretty,
|
|
167
|
+
sourcemap: false,
|
|
168
|
+
plugins: [textLoaderPlugin, polyfillNode()],
|
|
169
|
+
define: {
|
|
170
|
+
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
171
|
+
'process.env.COLORTERM': JSON.stringify('truecolor'),
|
|
172
|
+
'process.env.TERM': JSON.stringify('color'),
|
|
173
|
+
'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
|
|
174
|
+
},
|
|
175
|
+
alias,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
commandsBundle = fs.readFileSync(tfOut.name, 'utf8') + '\nreturn __brfs_cmds;';
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const rawContainer = serializeBinaryFilesystem(filesystem, permissions, { commandsBundle });
|
|
182
|
+
const finalBytes = options.compress ? zlib.gzipSync(Buffer.from(rawContainer)) : Buffer.from(rawContainer);
|
|
183
|
+
|
|
184
|
+
if (isStandaloneBrfsOutput) {
|
|
185
|
+
fs.writeFileSync(options.output, finalBytes);
|
|
186
|
+
console.log(`Binary container written to ${options.output}`);
|
|
193
187
|
console.log('Build succeeded');
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Output is a `.js` file with `--binary`: write `.brfs` alongside a tiny browser loader
|
|
192
|
+
const brfsPath = options.output.replace(/\.js$/, '') + '.brfs';
|
|
193
|
+
fs.writeFileSync(brfsPath, finalBytes);
|
|
194
|
+
|
|
195
|
+
const varName = options.variable;
|
|
196
|
+
const loader =
|
|
197
|
+
`globalThis.${varName}=(function(){` +
|
|
198
|
+
`var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
|
|
199
|
+
`typeof location!=="undefined"?location.href:null;` +
|
|
200
|
+
`if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
|
|
201
|
+
`var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
|
|
202
|
+
`return fetch(u)` +
|
|
203
|
+
`.then(function(r){return r.arrayBuffer();})` +
|
|
204
|
+
`.then(function(b){` +
|
|
205
|
+
`var u8=new Uint8Array(b);` +
|
|
206
|
+
`if(u8[0]===0x1f&&u8[1]===0x8b){` +
|
|
207
|
+
`var ds=new DecompressionStream("gzip");` +
|
|
208
|
+
`var w=ds.writable.getWriter();` +
|
|
209
|
+
`w.write(u8);w.close();` +
|
|
210
|
+
`return new Response(ds.readable).arrayBuffer().then(function(ab){return {filesystem:new Uint8Array(ab),permissions:{}};});` +
|
|
211
|
+
`}` +
|
|
212
|
+
`return {filesystem:u8,permissions:{}};` +
|
|
213
|
+
`});` +
|
|
214
|
+
`})();`;
|
|
215
|
+
fs.writeFileSync(options.output, loader);
|
|
216
|
+
console.log(`Binary container written to ${brfsPath}`);
|
|
217
|
+
console.log('Build succeeded');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (useBinaryContainer) {
|
|
221
|
+
buildBinaryContainerMode().catch(err => {
|
|
222
|
+
console.error(err);
|
|
223
|
+
process.exit(1);
|
|
194
224
|
});
|
|
225
|
+
} else {
|
|
226
|
+
const fsJson = JSON.stringify(filesystem, null, options.pretty ? 2 : null);
|
|
227
|
+
const permJson = JSON.stringify(permissions, null, options.pretty ? 2 : null);
|
|
228
|
+
const fsJS = fsJson.replace(/"(require\('.*?'\))"/gm, '$1');
|
|
229
|
+
|
|
230
|
+
const JS = `module.exports = { filesystem: ${fsJS}, permissions: ${permJson} }`;
|
|
231
|
+
|
|
232
|
+
const tf = tmp.fileSync({ postfix: '.tmp.js' });
|
|
233
|
+
fs.writeFileSync(tf.name, JS);
|
|
234
|
+
|
|
235
|
+
esbuild.build({
|
|
236
|
+
entryPoints: [tf.name],
|
|
237
|
+
bundle: true,
|
|
238
|
+
format: 'iife',
|
|
239
|
+
platform: 'browser',
|
|
240
|
+
treeShaking: true,
|
|
241
|
+
outfile: options.output,
|
|
242
|
+
allowOverwrite: true,
|
|
243
|
+
globalName: options.variable,
|
|
244
|
+
minify: true,
|
|
245
|
+
sourcemap: false,
|
|
246
|
+
loader: {
|
|
247
|
+
'.gif': 'binary',
|
|
248
|
+
'.png': 'binary',
|
|
249
|
+
'.jpg': 'binary',
|
|
250
|
+
'.jpeg': 'binary',
|
|
251
|
+
'.bmp': 'binary',
|
|
252
|
+
'.webp': 'binary',
|
|
253
|
+
'.ico': 'binary',
|
|
254
|
+
'.wasm': 'binary'
|
|
255
|
+
},
|
|
256
|
+
plugins: [
|
|
257
|
+
textLoaderPlugin,
|
|
258
|
+
polyfillNode()
|
|
259
|
+
],
|
|
260
|
+
define: {
|
|
261
|
+
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
262
|
+
'process.env.COLORTERM': JSON.stringify('truecolor'),
|
|
263
|
+
'process.env.TERM': JSON.stringify('color'),
|
|
264
|
+
'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
|
|
265
|
+
},
|
|
266
|
+
alias,
|
|
267
|
+
})
|
|
268
|
+
.then(() => {
|
|
269
|
+
if (options.compress) {
|
|
270
|
+
// Post-process: gzip the entire esbuild output.
|
|
271
|
+
// The compressed bytes are written to <output>.brfs as raw binary.
|
|
272
|
+
// The JS file is replaced with a tiny loader that fetches the .brfs,
|
|
273
|
+
// decompresses it, and executes it — no base64 overhead.
|
|
274
|
+
const bundle = fs.readFileSync(options.output, 'utf8');
|
|
275
|
+
// Append a return statement so new Function() can hand back the value
|
|
276
|
+
const codeToCompress = bundle + `\nreturn ${options.variable};`;
|
|
277
|
+
const compressed = zlib.gzipSync(Buffer.from(codeToCompress, 'utf8'));
|
|
278
|
+
const gzPath = options.output.replace(/\.js$/, '') + '.brfs';
|
|
279
|
+
fs.writeFileSync(gzPath, compressed);
|
|
280
|
+
|
|
281
|
+
const varName = options.variable;
|
|
282
|
+
// The loader captures document.currentScript.src synchronously
|
|
283
|
+
// (unavailable once the async IIFE runs) and derives the .brfs URL.
|
|
284
|
+
const loader =
|
|
285
|
+
`globalThis.${varName}=(function(){` +
|
|
286
|
+
`var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
|
|
287
|
+
`typeof location!=="undefined"?location.href:null;` +
|
|
288
|
+
`if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
|
|
289
|
+
`var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
|
|
290
|
+
`return fetch(u)` +
|
|
291
|
+
`.then(function(r){return r.arrayBuffer();})` +
|
|
292
|
+
`.then(function(b){` +
|
|
293
|
+
`var ds=new DecompressionStream("gzip");` +
|
|
294
|
+
`var w=ds.writable.getWriter();` +
|
|
295
|
+
`w.write(new Uint8Array(b));` +
|
|
296
|
+
`w.close();` +
|
|
297
|
+
`return new Response(ds.readable).text();` +
|
|
298
|
+
`})` +
|
|
299
|
+
`.then(function(code){return new Function(code)();});` +
|
|
300
|
+
`})();`;
|
|
301
|
+
fs.writeFileSync(options.output, loader);
|
|
302
|
+
console.log(`Compressed bundle written to ${gzPath}`);
|
|
303
|
+
}
|
|
304
|
+
console.log('Build succeeded');
|
|
305
|
+
});
|
|
306
|
+
}
|