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
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { BinaryFile, SymlinkRef } = require('./FileSystem');
|
|
4
|
+
|
|
5
|
+
// 4-byte magic: "BRFS" (0x42, 0x52, 0x46, 0x53)
|
|
6
|
+
const MAGIC = new Uint8Array([0x42, 0x52, 0x46, 0x53]);
|
|
7
|
+
const FORMAT_VERSION = 2;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Checks whether an ArrayBuffer or Uint8Array starts with the 4-byte "BRFS" magic header.
|
|
11
|
+
*/
|
|
12
|
+
function isBinaryContainer(input) {
|
|
13
|
+
if (!input) return false;
|
|
14
|
+
const bytes = input instanceof Uint8Array
|
|
15
|
+
? input
|
|
16
|
+
: (input instanceof ArrayBuffer || ArrayBuffer.isView(input))
|
|
17
|
+
? new Uint8Array(input.buffer || input, input.byteOffset || 0, input.byteLength)
|
|
18
|
+
: null;
|
|
19
|
+
if (!bytes || bytes.length < 12) return false;
|
|
20
|
+
return (
|
|
21
|
+
bytes[0] === MAGIC[0] &&
|
|
22
|
+
bytes[1] === MAGIC[1] &&
|
|
23
|
+
bytes[2] === MAGIC[2] &&
|
|
24
|
+
bytes[3] === MAGIC[3]
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Serializes a `{ filesystem, permissions, commandsBundle }` structure into a single
|
|
30
|
+
* binary container (`Uint8Array`) with layout:
|
|
31
|
+
* [0..3] Magic "BRFS" (4 bytes)
|
|
32
|
+
* [4..7] Version (uint32 LE, currently 2)
|
|
33
|
+
* [8..11] Header JSON byte length (uint32 LE)
|
|
34
|
+
* [12..12+headerLen] UTF-8 JSON header: { tree, permissions, hasCommandsBundle }
|
|
35
|
+
* [12+headerLen..] Contiguous raw payload bytes (files, strings, optional commands JS bundle)
|
|
36
|
+
*
|
|
37
|
+
* Inside `header.tree`:
|
|
38
|
+
* - Directories: `{ "$d": { ...children } }` (or plain object without reserved `$` keys)
|
|
39
|
+
* - Text files: `{ "$t": [offset, byteLength] }`
|
|
40
|
+
* - Binary files: `{ "$b": [offset, byteLength, mimeType] }`
|
|
41
|
+
* - Symlinks: `{ "$l": targetPath }`
|
|
42
|
+
* - JS Commands: `{ "$c": commandKey }` (resolved from `commandsBundle` or serialized function)
|
|
43
|
+
*/
|
|
44
|
+
function serializeBinaryFilesystem(filesystem = {}, permissions = {}, options = {}) {
|
|
45
|
+
const encoder = new TextEncoder();
|
|
46
|
+
const payloadChunks = [];
|
|
47
|
+
let currentOffset = 0;
|
|
48
|
+
|
|
49
|
+
const appendPayload = (bytes) => {
|
|
50
|
+
const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
51
|
+
const start = currentOffset;
|
|
52
|
+
payloadChunks.push(u8);
|
|
53
|
+
currentOffset += u8.byteLength;
|
|
54
|
+
return [start, u8.byteLength];
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const inlineCommandSources = {};
|
|
58
|
+
|
|
59
|
+
const encodeNode = (node, virtualPath) => {
|
|
60
|
+
if (node === null || node === undefined) return null;
|
|
61
|
+
|
|
62
|
+
if (node instanceof SymlinkRef) {
|
|
63
|
+
return { $l: node.target };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (node instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(node))) {
|
|
67
|
+
const u8 = node instanceof Uint8Array
|
|
68
|
+
? new Uint8Array(node.buffer, node.byteOffset, node.byteLength)
|
|
69
|
+
: new Uint8Array(node);
|
|
70
|
+
const mime = node.mimeType || (virtualPath.endsWith('.wasm') ? 'application/wasm' : 'application/octet-stream');
|
|
71
|
+
const [off, len] = appendPayload(u8);
|
|
72
|
+
return { $b: [off, len, mime] };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (typeof node === 'function') {
|
|
76
|
+
// If an external commandsBundle is provided, reference by virtualPath;
|
|
77
|
+
// otherwise store the function's source code so client-side persistence works standalone!
|
|
78
|
+
if (!options.commandsBundle) {
|
|
79
|
+
inlineCommandSources[virtualPath] = node.toString();
|
|
80
|
+
}
|
|
81
|
+
return { $c: virtualPath };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (typeof node === 'string') {
|
|
85
|
+
// Check if string is a data:<mime>;base64,... URI — if so, decode to raw binary!
|
|
86
|
+
if (node.startsWith('data:')) {
|
|
87
|
+
const semi = node.indexOf(';');
|
|
88
|
+
const comma = node.indexOf(',', semi);
|
|
89
|
+
if (semi !== -1 && comma !== -1 && node.slice(semi + 1, comma) === 'base64') {
|
|
90
|
+
const mime = node.slice(5, semi);
|
|
91
|
+
const b64 = node.slice(comma + 1);
|
|
92
|
+
let rawBytes;
|
|
93
|
+
if (typeof Buffer !== 'undefined') {
|
|
94
|
+
rawBytes = new Uint8Array(Buffer.from(b64, 'base64'));
|
|
95
|
+
} else {
|
|
96
|
+
const bin = atob(b64);
|
|
97
|
+
rawBytes = new Uint8Array(bin.length);
|
|
98
|
+
for (let i = 0; i < bin.length; i++) rawBytes[i] = bin.charCodeAt(i);
|
|
99
|
+
}
|
|
100
|
+
const [off, len] = appendPayload(rawBytes);
|
|
101
|
+
return { $b: [off, len, mime] };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const strBytes = encoder.encode(node);
|
|
106
|
+
const [off, len] = appendPayload(strBytes);
|
|
107
|
+
return { $t: [off, len] };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (typeof node === 'object') {
|
|
111
|
+
const children = {};
|
|
112
|
+
for (const key of Object.keys(node)) {
|
|
113
|
+
const childPath = `${virtualPath}/${key}`;
|
|
114
|
+
const encoded = encodeNode(node[key], childPath);
|
|
115
|
+
if (encoded !== null) {
|
|
116
|
+
children[key] = encoded;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { $d: children };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return null;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const tree = encodeNode(filesystem, '') || { $d: {} };
|
|
126
|
+
|
|
127
|
+
let commandsSlice = null;
|
|
128
|
+
if (options.commandsBundle && typeof options.commandsBundle === 'string') {
|
|
129
|
+
const cmdBytes = encoder.encode(options.commandsBundle);
|
|
130
|
+
commandsSlice = appendPayload(cmdBytes);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const headerObj = {
|
|
134
|
+
v: FORMAT_VERSION,
|
|
135
|
+
tree,
|
|
136
|
+
permissions: Object.assign({}, permissions),
|
|
137
|
+
};
|
|
138
|
+
if (commandsSlice) {
|
|
139
|
+
headerObj.commandsSlice = commandsSlice;
|
|
140
|
+
}
|
|
141
|
+
if (Object.keys(inlineCommandSources).length > 0) {
|
|
142
|
+
headerObj.inlineCommands = inlineCommandSources;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const headerBytes = encoder.encode(JSON.stringify(headerObj));
|
|
146
|
+
const totalLength = 12 + headerBytes.byteLength + currentOffset;
|
|
147
|
+
|
|
148
|
+
const out = new Uint8Array(totalLength);
|
|
149
|
+
out.set(MAGIC, 0);
|
|
150
|
+
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
|
151
|
+
view.setUint32(4, FORMAT_VERSION, true);
|
|
152
|
+
view.setUint32(8, headerBytes.byteLength, true);
|
|
153
|
+
out.set(headerBytes, 12);
|
|
154
|
+
|
|
155
|
+
let writePos = 12 + headerBytes.byteLength;
|
|
156
|
+
for (const chunk of payloadChunks) {
|
|
157
|
+
out.set(chunk, writePos);
|
|
158
|
+
writePos += chunk.byteLength;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Deserializes a binary container (`Uint8Array` or `ArrayBuffer`) back into
|
|
166
|
+
* `{ filesystem, permissions }` using zero-copy `BinaryFile` subarray views.
|
|
167
|
+
*/
|
|
168
|
+
function deserializeBinaryFilesystem(input, customCommandMap = {}) {
|
|
169
|
+
const bytes = input instanceof Uint8Array
|
|
170
|
+
? input
|
|
171
|
+
: new Uint8Array(input.buffer || input, input.byteOffset || 0, input.byteLength);
|
|
172
|
+
|
|
173
|
+
if (!isBinaryContainer(bytes)) {
|
|
174
|
+
throw new Error('Invalid BRFS binary container (missing BRFS magic header)');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
178
|
+
const version = view.getUint32(4, true);
|
|
179
|
+
if (version > FORMAT_VERSION) {
|
|
180
|
+
throw new Error(`Unsupported BRFS container version: ${version}`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const headerLen = view.getUint32(8, true);
|
|
184
|
+
const payloadStart = 12 + headerLen;
|
|
185
|
+
if (payloadStart > bytes.byteLength) {
|
|
186
|
+
throw new Error('Corrupt BRFS binary container (header length exceeds buffer)');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const decoder = new TextDecoder();
|
|
190
|
+
const headerJson = decoder.decode(bytes.subarray(12, payloadStart));
|
|
191
|
+
const header = JSON.parse(headerJson);
|
|
192
|
+
|
|
193
|
+
// Ensure we have a clean underlying ArrayBuffer slice for zero-copy BinaryFile views
|
|
194
|
+
const payloadBytes = bytes.subarray(payloadStart);
|
|
195
|
+
|
|
196
|
+
let bundledCommands = Object.assign({}, customCommandMap);
|
|
197
|
+
if (Array.isArray(header.commandsSlice)) {
|
|
198
|
+
const [off, len] = header.commandsSlice;
|
|
199
|
+
const jsCode = decoder.decode(payloadBytes.subarray(off, off + len));
|
|
200
|
+
try {
|
|
201
|
+
const evaluated = new Function(jsCode)();
|
|
202
|
+
if (evaluated && typeof evaluated === 'object') {
|
|
203
|
+
Object.assign(bundledCommands, evaluated);
|
|
204
|
+
}
|
|
205
|
+
} catch {
|
|
206
|
+
// ignore bundle evaluation error
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const decodeNode = (entry) => {
|
|
211
|
+
if (!entry || typeof entry !== 'object') return entry;
|
|
212
|
+
|
|
213
|
+
if ('$t' in entry) {
|
|
214
|
+
const [off, len] = entry.$t;
|
|
215
|
+
return decoder.decode(payloadBytes.subarray(off, off + len));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if ('$b' in entry) {
|
|
219
|
+
const [off, len, mime] = entry.$b;
|
|
220
|
+
const slice = payloadBytes.slice(off, off + len);
|
|
221
|
+
return new BinaryFile(slice.buffer, mime || 'application/octet-stream');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if ('$l' in entry) {
|
|
225
|
+
return new SymlinkRef(entry.$l);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if ('$c' in entry) {
|
|
229
|
+
const cmdPath = entry.$c;
|
|
230
|
+
if (bundledCommands[cmdPath]) {
|
|
231
|
+
return bundledCommands[cmdPath];
|
|
232
|
+
}
|
|
233
|
+
if (header.inlineCommands && header.inlineCommands[cmdPath]) {
|
|
234
|
+
try {
|
|
235
|
+
const Command = require('./Command');
|
|
236
|
+
const InteractiveCommand = require('./InteractiveCommand');
|
|
237
|
+
const fn = new Function('Command', 'InteractiveCommand', `return (${header.inlineCommands[cmdPath]});`);
|
|
238
|
+
return fn(Command, InteractiveCommand);
|
|
239
|
+
} catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if ('$d' in entry) {
|
|
247
|
+
const dir = {};
|
|
248
|
+
for (const [k, v] of Object.entries(entry.$d)) {
|
|
249
|
+
const decoded = decodeNode(v);
|
|
250
|
+
if (decoded !== null) {
|
|
251
|
+
dir[k] = decoded;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return dir;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return entry;
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
const filesystem = decodeNode(header.tree) || {};
|
|
261
|
+
const permissions = Object.assign({}, header.permissions || {});
|
|
262
|
+
|
|
263
|
+
return { filesystem, permissions };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Checks whether a byte buffer starts with the gzip magic header (0x1f 0x8b).
|
|
268
|
+
*/
|
|
269
|
+
function isGzipBytes(input) {
|
|
270
|
+
if (!input) return false;
|
|
271
|
+
const u8 = input instanceof Uint8Array
|
|
272
|
+
? input
|
|
273
|
+
: (input instanceof ArrayBuffer ? new Uint8Array(input) : (ArrayBuffer.isView(input) ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) : null));
|
|
274
|
+
return Boolean(u8 && u8.byteLength >= 2 && u8[0] === 0x1f && u8[1] === 0x8b);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Decompresses gzip-compressed bytes in Browser or Node (`DecompressionStream` or `zlib`).
|
|
279
|
+
*/
|
|
280
|
+
async function decompressGzipBytes(u8) {
|
|
281
|
+
if (typeof DecompressionStream !== 'undefined' && typeof Response !== 'undefined') {
|
|
282
|
+
const ds = new DecompressionStream('gzip');
|
|
283
|
+
const stream = new Blob([u8]).stream().pipeThrough(ds);
|
|
284
|
+
const ab = await new Response(stream).arrayBuffer();
|
|
285
|
+
return new Uint8Array(ab);
|
|
286
|
+
}
|
|
287
|
+
if (typeof process !== 'undefined' && typeof process.getBuiltinModule === 'function') {
|
|
288
|
+
const zlib = process.getBuiltinModule('zlib');
|
|
289
|
+
if (zlib) {
|
|
290
|
+
return new Uint8Array(zlib.gunzipSync(Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength)));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
throw new Error('Gzip decompression is not supported in this environment');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Checks whether a `filesystem` option passed to `new Shell({ filesystem })` requires asynchronous resolution
|
|
298
|
+
* (e.g., a URL/file path string, a Promise, a fetch Response, or gzip-compressed bytes).
|
|
299
|
+
*/
|
|
300
|
+
function isAsyncFilesystemSource(source) {
|
|
301
|
+
if (!source) return false;
|
|
302
|
+
if (typeof source === 'string') return true;
|
|
303
|
+
if (typeof source.then === 'function') return true;
|
|
304
|
+
if (typeof source.arrayBuffer === 'function') return true;
|
|
305
|
+
if (isGzipBytes(source)) return true;
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Resolves any filesystem source (URL/path string, Promise, fetch Response, raw or gzipped `.brfs` bytes,
|
|
311
|
+
* or plain `{ filesystem, permissions }` object) into `{ filesystem, permissions }`.
|
|
312
|
+
*/
|
|
313
|
+
async function resolveFilesystemSource(source, defaultPermissions = {}) {
|
|
314
|
+
if (!source) {
|
|
315
|
+
return { filesystem: {}, permissions: defaultPermissions };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (typeof source.then === 'function') {
|
|
319
|
+
const awaited = await source;
|
|
320
|
+
return resolveFilesystemSource(awaited, defaultPermissions);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (typeof source.arrayBuffer === 'function') {
|
|
324
|
+
const ab = await source.arrayBuffer();
|
|
325
|
+
return resolveFilesystemSource(new Uint8Array(ab), defaultPermissions);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (typeof source === 'string') {
|
|
329
|
+
// In Node.js, support local file paths directly if not an http(s) URL
|
|
330
|
+
if (
|
|
331
|
+
!/^https?:\/\//i.test(source) &&
|
|
332
|
+
typeof process !== 'undefined' &&
|
|
333
|
+
typeof process.getBuiltinModule === 'function' &&
|
|
334
|
+
typeof window === 'undefined'
|
|
335
|
+
) {
|
|
336
|
+
try {
|
|
337
|
+
const fs = process.getBuiltinModule('fs');
|
|
338
|
+
if (fs && fs.existsSync(source)) {
|
|
339
|
+
const buf = await fs.promises.readFile(source);
|
|
340
|
+
return resolveFilesystemSource(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), defaultPermissions);
|
|
341
|
+
}
|
|
342
|
+
} catch (_) {
|
|
343
|
+
// Fall back to fetch() below
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const res = await fetch(source);
|
|
348
|
+
if (!res.ok) {
|
|
349
|
+
throw new Error(`Failed to load filesystem from ${source}: HTTP ${res.status}`);
|
|
350
|
+
}
|
|
351
|
+
const ab = await res.arrayBuffer();
|
|
352
|
+
return resolveFilesystemSource(new Uint8Array(ab), defaultPermissions);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
|
|
356
|
+
let u8 = source instanceof Uint8Array
|
|
357
|
+
? source
|
|
358
|
+
: (source instanceof ArrayBuffer
|
|
359
|
+
? new Uint8Array(source)
|
|
360
|
+
: new Uint8Array(source.buffer, source.byteOffset, source.byteLength));
|
|
361
|
+
|
|
362
|
+
if (isGzipBytes(u8)) {
|
|
363
|
+
u8 = await decompressGzipBytes(u8);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (isBinaryContainer(u8)) {
|
|
367
|
+
const unpacked = deserializeBinaryFilesystem(u8);
|
|
368
|
+
return {
|
|
369
|
+
filesystem: unpacked.filesystem,
|
|
370
|
+
permissions: Object.assign({}, unpacked.permissions, defaultPermissions)
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Legacy compressed JS bundle or JSON text fallback
|
|
375
|
+
const text = new TextDecoder('utf-8').decode(u8);
|
|
376
|
+
try {
|
|
377
|
+
const parsed = JSON.parse(text);
|
|
378
|
+
if (parsed && typeof parsed === 'object' && parsed.filesystem && typeof parsed.permissions === 'object') {
|
|
379
|
+
return {
|
|
380
|
+
filesystem: parsed.filesystem,
|
|
381
|
+
permissions: Object.assign({}, parsed.permissions, defaultPermissions)
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
return { filesystem: parsed, permissions: defaultPermissions };
|
|
385
|
+
} catch (_) {
|
|
386
|
+
const evaluated = new Function('return ' + text)();
|
|
387
|
+
if (evaluated && typeof evaluated === 'object' && evaluated.filesystem && typeof evaluated.permissions === 'object') {
|
|
388
|
+
return {
|
|
389
|
+
filesystem: evaluated.filesystem,
|
|
390
|
+
permissions: Object.assign({}, evaluated.permissions, defaultPermissions)
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
return { filesystem: evaluated || {}, permissions: defaultPermissions };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (typeof source === 'object' && source.filesystem && typeof source.permissions === 'object') {
|
|
398
|
+
if (isAsyncFilesystemSource(source.filesystem) || isBinaryContainer(source.filesystem)) {
|
|
399
|
+
return resolveFilesystemSource(source.filesystem, Object.assign({}, source.permissions, defaultPermissions));
|
|
400
|
+
}
|
|
401
|
+
return {
|
|
402
|
+
filesystem: source.filesystem,
|
|
403
|
+
permissions: Object.assign({}, source.permissions, defaultPermissions)
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return {
|
|
408
|
+
filesystem: source,
|
|
409
|
+
permissions: defaultPermissions
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Browser / Node IndexedDB + OPFS / LocalStorage persistence helper for `brsh` filesystems.
|
|
415
|
+
*
|
|
416
|
+
* Allows saving and restoring the entire `FileSystem` state (including binary `.wasm` files,
|
|
417
|
+
* SQLite `.db` databases, permissions, and symlinks) as a single compact `BRFS` binary blob!
|
|
418
|
+
*/
|
|
419
|
+
class FilesystemStorage {
|
|
420
|
+
/**
|
|
421
|
+
* Saves a Shell or FileSystem instance's current state into IndexedDB (browser)
|
|
422
|
+
* or returns the binary `Uint8Array` snapshot.
|
|
423
|
+
*/
|
|
424
|
+
static async save(shellOrFs, key = 'brsh-rootfs') {
|
|
425
|
+
const fs = shellOrFs.context ? shellOrFs.context.fs : shellOrFs;
|
|
426
|
+
const snapshot = serializeBinaryFilesystem(fs.getRaw(), fs.getRawPermissions());
|
|
427
|
+
|
|
428
|
+
if (typeof indexedDB !== 'undefined') {
|
|
429
|
+
await this._idbPut(key, snapshot);
|
|
430
|
+
}
|
|
431
|
+
return snapshot;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Loads a previously saved binary filesystem snapshot from IndexedDB (or from a `Uint8Array` / URL)
|
|
436
|
+
* and returns `{ filesystem, permissions }`.
|
|
437
|
+
*/
|
|
438
|
+
static async load(keyOrBytesOrUrl = 'brsh-rootfs') {
|
|
439
|
+
if (keyOrBytesOrUrl instanceof Uint8Array || keyOrBytesOrUrl instanceof ArrayBuffer) {
|
|
440
|
+
return resolveFilesystemSource(keyOrBytesOrUrl);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (typeof keyOrBytesOrUrl === 'string' && (/^https?:\/\//i.test(keyOrBytesOrUrl) || keyOrBytesOrUrl.endsWith('.brfs'))) {
|
|
444
|
+
return resolveFilesystemSource(keyOrBytesOrUrl);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (typeof indexedDB !== 'undefined' && typeof keyOrBytesOrUrl === 'string') {
|
|
448
|
+
const data = await this._idbGet(keyOrBytesOrUrl);
|
|
449
|
+
if (data && isBinaryContainer(data)) {
|
|
450
|
+
return deserializeBinaryFilesystem(data);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Loads a saved filesystem snapshot from IndexedDB if one exists for `key`,
|
|
459
|
+
* or falls back to loading `fallbackSource` (such as a `'/fs.brfs'` URL or initial object).
|
|
460
|
+
* Can be passed directly to `new Shell({ filesystem: Shell.Storage.loadOrFetch('my-app', '/fs.brfs') })`.
|
|
461
|
+
*/
|
|
462
|
+
static async loadOrFetch(key = 'brsh-rootfs', fallbackSource = {}) {
|
|
463
|
+
const saved = await this.load(key);
|
|
464
|
+
if (saved) {
|
|
465
|
+
return saved;
|
|
466
|
+
}
|
|
467
|
+
return resolveFilesystemSource(fallbackSource);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Creates an `onFsChange` callback that automatically persists the binary container
|
|
472
|
+
* to IndexedDB (and optionally calls a user callback with `{ bytes, filesystem, permissions }`).
|
|
473
|
+
*/
|
|
474
|
+
static createAutoSave(key = 'brsh-rootfs', onSaved = null) {
|
|
475
|
+
return (rawFs, rawPerms) => {
|
|
476
|
+
const bytes = serializeBinaryFilesystem(rawFs, rawPerms);
|
|
477
|
+
if (typeof indexedDB !== 'undefined') {
|
|
478
|
+
this._idbPut(key, bytes).catch(() => {});
|
|
479
|
+
}
|
|
480
|
+
if (typeof onSaved === 'function') {
|
|
481
|
+
onSaved(bytes, rawFs, rawPerms);
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
static _openIdb() {
|
|
487
|
+
return new Promise((resolve, reject) => {
|
|
488
|
+
const req = indexedDB.open('brsh_fs_storage', 1);
|
|
489
|
+
req.onupgradeneeded = () => {
|
|
490
|
+
req.result.createObjectStore('snapshots');
|
|
491
|
+
};
|
|
492
|
+
req.onsuccess = () => resolve(req.result);
|
|
493
|
+
req.onerror = () => reject(req.error);
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
static async _idbPut(key, val) {
|
|
498
|
+
const db = await this._openIdb();
|
|
499
|
+
return new Promise((resolve, reject) => {
|
|
500
|
+
const tx = db.transaction('snapshots', 'readwrite');
|
|
501
|
+
tx.objectStore('snapshots').put(val, key);
|
|
502
|
+
tx.oncomplete = () => { db.close(); resolve(); };
|
|
503
|
+
tx.onerror = () => { db.close(); reject(tx.error); };
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
static async _idbGet(key) {
|
|
508
|
+
const db = await this._openIdb();
|
|
509
|
+
return new Promise((resolve, reject) => {
|
|
510
|
+
const tx = db.transaction('snapshots', 'readonly');
|
|
511
|
+
const req = tx.objectStore('snapshots').get(key);
|
|
512
|
+
req.onsuccess = () => { db.close(); resolve(req.result || null); };
|
|
513
|
+
req.onerror = () => { db.close(); reject(req.error); };
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
module.exports = {
|
|
519
|
+
MAGIC,
|
|
520
|
+
FORMAT_VERSION,
|
|
521
|
+
isBinaryContainer,
|
|
522
|
+
isGzipBytes,
|
|
523
|
+
isAsyncFilesystemSource,
|
|
524
|
+
resolveFilesystemSource,
|
|
525
|
+
serializeBinaryFilesystem,
|
|
526
|
+
deserializeBinaryFilesystem,
|
|
527
|
+
FilesystemStorage
|
|
528
|
+
};
|
package/lib/Command.js
CHANGED
package/lib/FileSystem.js
CHANGED
|
@@ -74,6 +74,21 @@ function decodeBinaryFiles(node) {
|
|
|
74
74
|
class FileSystem extends BaseFileSystem {
|
|
75
75
|
constructor(cwd = '/', filesystem = {}, permissions = {}, onChange = null) {
|
|
76
76
|
super();
|
|
77
|
+
if (filesystem instanceof Uint8Array || filesystem instanceof ArrayBuffer) {
|
|
78
|
+
const { deserializeBinaryFilesystem } = require('./BinaryContainer');
|
|
79
|
+
const decoded = deserializeBinaryFilesystem(filesystem);
|
|
80
|
+
filesystem = decoded.filesystem;
|
|
81
|
+
permissions = Object.assign({}, decoded.permissions, permissions);
|
|
82
|
+
} else if (filesystem && typeof filesystem === 'object' && filesystem.filesystem && (filesystem.filesystem instanceof Uint8Array || typeof filesystem.filesystem === 'object')) {
|
|
83
|
+
permissions = Object.assign({}, filesystem.permissions || {}, permissions);
|
|
84
|
+
filesystem = filesystem.filesystem;
|
|
85
|
+
if (filesystem instanceof Uint8Array || filesystem instanceof ArrayBuffer) {
|
|
86
|
+
const { deserializeBinaryFilesystem } = require('./BinaryContainer');
|
|
87
|
+
const decoded = deserializeBinaryFilesystem(filesystem);
|
|
88
|
+
filesystem = decoded.filesystem;
|
|
89
|
+
permissions = Object.assign({}, decoded.permissions, permissions);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
77
92
|
decodeBinaryFiles(filesystem);
|
|
78
93
|
this.fileSystem = filesystem;
|
|
79
94
|
this.permissions = Object.assign({}, permissions);
|
|
@@ -82,6 +97,22 @@ class FileSystem extends BaseFileSystem {
|
|
|
82
97
|
this._changeScheduled = false;
|
|
83
98
|
}
|
|
84
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Exports the current virtual filesystem and permissions to a compact BRFS binary container (`Uint8Array`).
|
|
102
|
+
*/
|
|
103
|
+
toBinaryContainer(options = {}) {
|
|
104
|
+
const { serializeBinaryFilesystem } = require('./BinaryContainer');
|
|
105
|
+
return serializeBinaryFilesystem(this.fileSystem, this.permissions, options);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Deserializes a BRFS binary container (`Uint8Array` or `ArrayBuffer`) into `{ filesystem, permissions }`.
|
|
110
|
+
*/
|
|
111
|
+
static fromBinaryContainer(bytes, customCommandMap = {}) {
|
|
112
|
+
const { deserializeBinaryFilesystem } = require('./BinaryContainer');
|
|
113
|
+
return deserializeBinaryFilesystem(bytes, customCommandMap);
|
|
114
|
+
}
|
|
115
|
+
|
|
85
116
|
// Returns file content if the path exists AND is readable; null otherwise.
|
|
86
117
|
// Follows symlinks transparently. Use exists() or stat() for permission-free checks.
|
|
87
118
|
getFileByPath(path) {
|
package/lib/NodeFileSystem.js
CHANGED
|
@@ -83,22 +83,30 @@ class NodeFileSystem extends BaseFileSystem {
|
|
|
83
83
|
setFileByPath(path, content, createDir = false) {
|
|
84
84
|
const abs = this.absolutePath(path);
|
|
85
85
|
|
|
86
|
-
if (typeof content === 'function') {
|
|
86
|
+
if (typeof content === 'function' || content instanceof Uint8Array) {
|
|
87
87
|
this._virtualFiles[abs] = content;
|
|
88
88
|
return;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
if (content !== null && content !== undefined && content.constructor === Object) {
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
try {
|
|
93
|
+
nodeFs.mkdirSync(abs, { recursive: createDir });
|
|
94
|
+
this._triggerChange();
|
|
95
|
+
} catch (e) {
|
|
96
|
+
this._virtualFiles[abs] = content;
|
|
97
|
+
}
|
|
94
98
|
return;
|
|
95
99
|
}
|
|
96
100
|
|
|
97
|
-
|
|
98
|
-
|
|
101
|
+
try {
|
|
102
|
+
if (createDir) {
|
|
103
|
+
nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
|
|
104
|
+
}
|
|
105
|
+
nodeFs.writeFileSync(abs, String(content));
|
|
106
|
+
this._triggerChange();
|
|
107
|
+
} catch (e) {
|
|
108
|
+
this._virtualFiles[abs] = String(content);
|
|
99
109
|
}
|
|
100
|
-
nodeFs.writeFileSync(abs, String(content));
|
|
101
|
-
this._triggerChange();
|
|
102
110
|
}
|
|
103
111
|
|
|
104
112
|
deleteFileByPath(path) {
|
|
@@ -228,6 +236,10 @@ class NodeFileSystem extends BaseFileSystem {
|
|
|
228
236
|
return this.getFileByPath(path);
|
|
229
237
|
}
|
|
230
238
|
|
|
239
|
+
_setFileRaw(path, content, createDir = false) {
|
|
240
|
+
return this.setFileByPath(path, content, createDir);
|
|
241
|
+
}
|
|
242
|
+
|
|
231
243
|
exists(path) {
|
|
232
244
|
const abs = this.absolutePath(path);
|
|
233
245
|
if (this._virtualFiles[abs] !== undefined) return true;
|
|
@@ -248,5 +260,3 @@ class NodeFileSystem extends BaseFileSystem {
|
|
|
248
260
|
}
|
|
249
261
|
|
|
250
262
|
module.exports = NodeFileSystem;
|
|
251
|
-
|
|
252
|
-
module.exports = NodeFileSystem;
|