brsh 1.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.github/workflows/busybox-compat.yml +166 -0
  2. package/.github/workflows/release.yml +40 -0
  3. package/.releaserc.json +18 -0
  4. package/CHANGELOG.md +355 -0
  5. package/bin/brsh-cmd.js +78 -0
  6. package/bin/exportFileSystem.js +81 -156
  7. package/busybox-testsuite/cat.tests +49 -0
  8. package/busybox-testsuite/cp.tests +206 -0
  9. package/busybox-testsuite/grep.tests +237 -0
  10. package/busybox-testsuite/testing.sh +180 -0
  11. package/dist/brsh.css +2 -0
  12. package/dist/shell.es.js +5667 -0
  13. package/dist/shell.es.js.map +1 -0
  14. package/dist/shell.min.js +14 -219
  15. package/dist/shell.min.js.map +1 -147
  16. package/dist/terminal.es.js +6228 -0
  17. package/dist/terminal.es.js.map +1 -0
  18. package/dist/terminal.min.js +113 -18
  19. package/dist/terminal.min.js.map +1 -21
  20. package/index.js +231 -56
  21. package/lib/Command.js +12 -1
  22. package/lib/Context.js +12 -4
  23. package/lib/FileSystem.js +99 -6
  24. package/lib/NodeFileSystem.js +238 -0
  25. package/lib/Result.js +6 -0
  26. package/lib/ScriptCommand.js +193 -15
  27. package/lib/Terminal.js +192 -11
  28. package/lib/WasmCommand.js +252 -0
  29. package/lib/buildFilesystemStructure.js +58 -0
  30. package/lib/builtins/cat.js +67 -9
  31. package/lib/builtins/echo.js +36 -5
  32. package/lib/builtins/false.js +13 -0
  33. package/lib/builtins/grep.js +267 -0
  34. package/lib/builtins/index.js +9 -2
  35. package/lib/builtins/ls.js +86 -18
  36. package/lib/builtins/test.js +105 -0
  37. package/lib/builtins/true.js +10 -0
  38. package/lib/local/chmod.js +72 -0
  39. package/lib/local/cp.js +156 -0
  40. package/lib/local/index.js +9 -1
  41. package/lib/local/jsfunction.js +58 -0
  42. package/lib/local/mkdir.js +44 -0
  43. package/lib/local/mv.js +96 -0
  44. package/lib/local/pwd.js +13 -0
  45. package/lib/local/read.js +107 -0
  46. package/lib/local/rm.js +71 -0
  47. package/lib/local/which.js +2 -2
  48. package/package.json +31 -34
  49. package/test/builtins.test.js +505 -0
  50. package/test/exportFileSystem.test.js +226 -0
  51. package/test/helpers.js +35 -0
  52. package/test/local-commands.test.js +593 -0
  53. package/test/node-filesystem.test.js +133 -0
  54. package/test/scripts.test.js +277 -0
  55. package/test/shell.test.js +245 -0
  56. package/test/streaming.test.js +113 -0
  57. package/vite.config.shell.js +21 -0
  58. package/vite.config.terminal.js +27 -0
  59. package/vitest.config.js +15 -0
package/index.js CHANGED
@@ -5,6 +5,7 @@ const EventEmitter = require('events');
5
5
  const Context = require('./lib/Context');
6
6
  const LocalCommand = require('./lib/local/LocalCommand');
7
7
  const ScriptCommand = require('./lib/ScriptCommand');
8
+ const WasmCommand = require('./lib/WasmCommand');
8
9
  const Command = require('./lib/Command');
9
10
 
10
11
  const builtins = require('./lib/builtins');
@@ -22,16 +23,21 @@ require('string.prototype.matchall').shim();
22
23
  class Shell extends EventEmitter {
23
24
  constructor(options) {
24
25
  super();
25
- const {path = '/bin', profile, hostname = 'browser', filesystem = {}, cwd = '/'} = options;
26
+ const {path = '/bin', profile, hostname = 'browser', filesystem = {}, permissions = {}, cwd = '/', onFsChange, useRealFilesystem = false} = options;
26
27
 
27
28
  this.context = new Context(Object.assign({}, options, {
28
29
  clearFn: this.clear.bind(this),
29
- destroyFn: this.destroy.bind(this)
30
+ destroyFn: this.destroy.bind(this),
31
+ onFsChange: typeof onFsChange === 'function' ? onFsChange : null
30
32
  }));
31
33
 
32
34
  this.context.setVar('PATH', path);
33
35
  this.context.setVar('HOST', hostname);
34
- this.context.setFilesystem(filesystem);
36
+ if (useRealFilesystem) {
37
+ this.context.setNodeFilesystem(cwd);
38
+ } else {
39
+ this.context.setFilesystem(filesystem, permissions);
40
+ }
35
41
  this.context.setCwd(cwd);
36
42
 
37
43
  this._loadDefaultCommands();
@@ -59,6 +65,17 @@ class Shell extends EventEmitter {
59
65
  return this._lastCode;
60
66
  }
61
67
 
68
+ set stdin(data) {
69
+ this._stdin = data;
70
+ }
71
+
72
+ onInput(char) {
73
+ if(this.runningCommand && this.runningCommand.onInput && this.runningCommand.captureInput) {
74
+ this.runningCommand.onInput(char);
75
+ return true;
76
+ }
77
+ }
78
+
62
79
  _loadDefaultCommands() {
63
80
  localCommands.forEach(command => {
64
81
  this.context.setCommand(command);
@@ -76,21 +93,29 @@ class Shell extends EventEmitter {
76
93
  }
77
94
 
78
95
  onCommand(raw, events = true) {
79
- const commands = this._splitInput(raw);
80
-
81
- const promise = commands.reduce((chain, command) => {
82
- return chain.then(() => this._runCommand(command))
83
- .then(() => {
84
- if(this._lastCode > 0) {
85
- throw new Error('chain broken');
86
- }
87
- })
96
+ const segments = this._splitInput(raw);
97
+ let shouldRun = true;
98
+
99
+ const promise = segments.reduce((chain, { command, op }) => {
100
+ return chain.then(() => {
101
+ if (!shouldRun) {
102
+ if (op === '&&') shouldRun = this._lastCode === 0;
103
+ else if (op === '||') shouldRun = this._lastCode !== 0;
104
+ else if (op === ';') shouldRun = true;
105
+ return;
106
+ }
107
+ return this._runCommand(command).then(() => {
108
+ if (op === '&&') shouldRun = this._lastCode === 0;
109
+ else if (op === '||') shouldRun = this._lastCode !== 0;
110
+ else if (op === ';') shouldRun = true;
111
+ });
112
+ });
88
113
  }, Promise.resolve());
89
114
 
90
115
  if(events) {
91
116
  return promise.then(() => {
92
117
  if(!this.destroyed) {
93
- this.emit('status', Shell.STATUS_READY)
118
+ this.emit('status', Shell.STATUS_READY);
94
119
  }
95
120
  })
96
121
  .catch(() => this.emit('status', Shell.STATUS_READY));
@@ -103,14 +128,24 @@ class Shell extends EventEmitter {
103
128
  return this.context.fs.autoComplete(path, this.path);
104
129
  }
105
130
 
106
- _runCommand(command) {
107
- if(command.length < 1) {
108
- return Promise.resolve();
131
+ async _runCommand(command) {
132
+ if(!command || command.length < 1) {
133
+ return;
109
134
  }
110
135
 
111
136
  this.emit('status', Shell.STATUS_WORKING);
112
137
 
113
- let args = this._parseCommandLine(command);
138
+ let args;
139
+ try {
140
+ args = await this._parseCommandLine(command);
141
+ } catch(e) {
142
+ this.emit('stdErr', e.message || String(e));
143
+ this.lastCode = 1;
144
+ this.emit('exitCode', this.lastCode);
145
+ return;
146
+ }
147
+
148
+ if (!args.length) return;
114
149
  let bin = args.shift();
115
150
 
116
151
  //short circuit for aliases
@@ -121,12 +156,14 @@ class Shell extends EventEmitter {
121
156
 
122
157
  let Cmd;
123
158
  try {
124
- Cmd = this._parseCommand(bin.toLowerCase());
159
+ Cmd = this._parseCommand(
160
+ (bin.startsWith('/') || bin.startsWith('./')) ? bin : bin.toLowerCase()
161
+ );
125
162
  } catch(e) {
126
163
  this.emit('stdErr', e.message);
127
164
  this.lastCode = 1;
128
165
  this.emit('exitCode', this.lastCode);
129
- return Promise.resolve();
166
+ return;
130
167
  }
131
168
 
132
169
  let instance;
@@ -138,23 +175,39 @@ class Shell extends EventEmitter {
138
175
  this.emit('stdErr', `${bin}: Command not found`);
139
176
  this.lastCode = 1;
140
177
  this.emit('exitCode', this.lastCode);
141
- return Promise.resolve();
178
+ return;
142
179
  }
143
180
 
144
181
  if(instance.requiresFilesystem) {
145
182
  instance.fs = this.context.fs;
146
183
  }
147
184
 
148
- return instance.runCommand().then(result => {
149
- result.getStdOutput().forEach(line => {
150
- if(line.type === 'out') {
151
- this.emit('stdOut', line.string);
152
- } else if(line.type === 'err') {
153
- this.emit('stdErr', line.string);
154
- }
185
+ if (this._stdin !== undefined) {
186
+ instance.stdin = this._stdin;
187
+ }
188
+
189
+ this.runningCommand = instance;
190
+ if(this.runningCommand.on) {
191
+ this.runningCommand.on('flush', lines => {
192
+ this._emitOutput(lines);
155
193
  });
194
+ }
195
+
196
+ return instance.runCommand().then(result => {
197
+ this._emitOutput(result.getStdOutput());
156
198
  this.lastCode = result.getExitCode();
157
199
  this.emit('exitCode', this.lastCode);
200
+ delete this.runningCommand;
201
+ });
202
+ }
203
+
204
+ _emitOutput(lines) {
205
+ lines.forEach(({type, string}) => {
206
+ if(type === 'out') {
207
+ this.emit('stdOut', string);
208
+ } else if(type === 'err') {
209
+ this.emit('stdErr', string);
210
+ }
158
211
  });
159
212
  }
160
213
 
@@ -176,13 +229,38 @@ class Shell extends EventEmitter {
176
229
  }
177
230
 
178
231
  _splitInput(input) {
179
- // remove anything after hash as its a comment;
180
- let out = [input.split('#')[0]];
232
+ const commentStripped = input.split('#')[0];
233
+ return this._parseOperators(commentStripped);
234
+ }
181
235
 
182
- return out
183
- .flatMap(item => item.split('&&'))
184
- .flatMap(item => item.split(':'))
185
- .flatMap(item => item.trim());
236
+ _parseOperators(input) {
237
+ const segments = [];
238
+ let current = '';
239
+ let i = 0;
240
+ let sq = false, dq = false;
241
+
242
+ while (i < input.length) {
243
+ const ch = input[i];
244
+ if (ch === "'" && !dq) { sq = !sq; current += ch; i++; continue; }
245
+ if (ch === '"' && !sq) { dq = !dq; current += ch; i++; continue; }
246
+ if (!sq && !dq) {
247
+ if (ch === '&' && input[i + 1] === '&') {
248
+ segments.push({ command: current.trim(), op: '&&' });
249
+ current = ''; i += 2; continue;
250
+ }
251
+ if (ch === '|' && input[i + 1] === '|') {
252
+ segments.push({ command: current.trim(), op: '||' });
253
+ current = ''; i += 2; continue;
254
+ }
255
+ if (ch === ';') {
256
+ segments.push({ command: current.trim(), op: ';' });
257
+ current = ''; i++; continue;
258
+ }
259
+ }
260
+ current += ch; i++;
261
+ }
262
+ if (current.trim()) segments.push({ command: current.trim(), op: null });
263
+ return segments;
186
264
  }
187
265
 
188
266
  _parseCommand(command) {
@@ -201,9 +279,19 @@ class Shell extends EventEmitter {
201
279
  }
202
280
 
203
281
  if(handle.constructor === String && handle.startsWith('#!')) {
282
+ if (!this.context.fs.isExecutable(command)) {
283
+ throw new Error(`${command}: permission denied`);
284
+ }
204
285
  return ScriptCommand.bind(this, handle);
205
286
  }
206
287
 
288
+ if(this._isWasmFile(command, handle)) {
289
+ if (!this.context.fs.isExecutable(command)) {
290
+ throw new Error(`${command}: permission denied`);
291
+ }
292
+ return WasmCommand.bind(null, command);
293
+ }
294
+
207
295
  throw new Error(`${command}: permission denied`);
208
296
  }
209
297
  const cmd = this.context.getCommand(command);
@@ -215,16 +303,22 @@ class Shell extends EventEmitter {
215
303
  return cmd;
216
304
  }
217
305
 
218
- _parseCommandLine(string) {
219
- const parts = Shell._sanitiseArray(Shell._splitCommand(string));
220
- const replaced = parts.map(part => this._replaceVariables(part));
221
-
222
- return Shell._sanitiseArray(replaced);
306
+ async _parseCommandLine(string) {
307
+ const parts = Shell._splitCommand(string);
308
+ const replaced = await Promise.all(
309
+ parts.map(({ value, hasQuote }) =>
310
+ this._replaceVariables(value).then(v => ({ value: v, hasQuote }))
311
+ )
312
+ );
313
+ // Keep tokens that are non-empty OR were explicitly quoted (preserves "" → '')
314
+ return replaced
315
+ .filter(({ value, hasQuote }) => value.length > 0 || hasQuote)
316
+ .map(({ value }) => value);
223
317
  }
224
318
 
225
319
  static _sanitiseCommandPart(string) {
226
320
  return (string.startsWith('"') && string.endsWith('"'))
227
- || (string.startsWith('\'') && string.endsWith('\''))
321
+ || (string.startsWith("'") && string.endsWith("'"))
228
322
  ? string.substring(1, string.length - 1) : string;
229
323
  }
230
324
 
@@ -232,55 +326,136 @@ class Shell extends EventEmitter {
232
326
  return array.filter(item => item.length > 0);
233
327
  }
234
328
 
235
- _replaceVariables(part) {
236
- const matches = part.matchAll(variableRegex);
329
+ async _replaceVariables(part) {
330
+ // 1. Arithmetic substitution $(( expr ))
331
+ const arithMatches = [...part.matchAll(/\$\(\(([^)]+)\)\)/g)];
332
+ for (const m of arithMatches) {
333
+ part = part.replace(m[0], String(this._evalArithmetic(m[1])));
334
+ }
237
335
 
336
+ // 2. Command substitution $( cmd ) — negative lookahead excludes $((
337
+ const cmdMatches = [...part.matchAll(/\$\((?!\()([^)]+)\)/g)];
338
+ for (const m of cmdMatches) {
339
+ const output = await this._runAndCapture(m[1]);
340
+ part = part.replace(m[0], output);
341
+ }
342
+
343
+ // 3. Variable substitution $VAR and ${VAR}
344
+ const matches = part.matchAll(variableRegex);
238
345
  let match = matches.next();
239
346
  while (!match.done) {
240
347
  const value = this.context.getVar(match.value[1]);
241
- part = part.replace(new RegExp(Shell._escapeRegExp(match.value[0]), 'g'), value);
348
+ part = part.replace(new RegExp(Shell._escapeRegExp(match.value[0]), 'g'), String(value));
242
349
  match = matches.next();
243
350
  }
244
351
 
245
352
  return part;
246
353
  }
247
354
 
355
+ _evalArithmetic(expr) {
356
+ const expanded = expr.replace(/\${?([\w\d]+)}?/g, (m, name) =>
357
+ String(parseInt(this.context.getVar(name)) || 0));
358
+ if (!/^[\d\s+\-*/%()]+$/.test(expanded.trim())) return 0;
359
+ try {
360
+ return new Function('return (' + expanded + ')')();
361
+ } catch {
362
+ return 0;
363
+ }
364
+ }
365
+
366
+ async _runAndCapture(cmd) {
367
+ const subshell = new global.shell({
368
+ cwd: this.context.fs.cwd,
369
+ filesystem: this.context.fs.getRaw(),
370
+ permissions: this.context.fs.getRawPermissions()
371
+ });
372
+ subshell.context.source(this.context);
373
+
374
+ const lines = [];
375
+ subshell.on('stdOut', line => lines.push(line));
376
+ await subshell.onCommand(cmd, false);
377
+
378
+ return lines.join('\n').trimEnd();
379
+ }
380
+
381
+ // Returns Array<{value: string, hasQuote: boolean}>.
382
+ // hasQuote=true means the token contained an explicit quoted segment (even empty ""),
383
+ // which must be preserved even if the final value is an empty string.
248
384
  static _splitCommand(string) {
249
385
  const separator = /\s/g;
250
386
  let singleQuoteOpen = false;
251
387
  let doubleQuoteOpen = false;
388
+ let dollarDepth = 0;
252
389
  let tokenBuffer = [];
390
+ let tokenHasQuote = false;
253
391
  const parts = [];
254
392
 
255
- for (let character of string) {
256
- const matches = character.match(separator);
257
- if (character === "'" && !doubleQuoteOpen) {
393
+ for (let i = 0; i < string.length; i++) {
394
+ const ch = string[i];
395
+
396
+ // Inside $(...) or $((...)) — keep everything verbatim, track nesting
397
+ if (dollarDepth > 0) {
398
+ tokenBuffer.push(ch);
399
+ if (ch === '(') dollarDepth++;
400
+ else if (ch === ')') dollarDepth--;
401
+ continue;
402
+ }
403
+
404
+ // Quote handling
405
+ if (ch === "'" && !doubleQuoteOpen) {
258
406
  singleQuoteOpen = !singleQuoteOpen;
407
+ tokenHasQuote = true;
259
408
  continue;
260
- } else if (character === '"' && !singleQuoteOpen) {
409
+ }
410
+ if (ch === '"' && !singleQuoteOpen) {
261
411
  doubleQuoteOpen = !doubleQuoteOpen;
412
+ tokenHasQuote = true;
262
413
  continue;
263
414
  }
264
415
 
265
- if (!singleQuoteOpen && !doubleQuoteOpen && matches) {
266
- if (tokenBuffer.length > 0) {
267
- parts.push(tokenBuffer.join(''));
268
- tokenBuffer = [];
416
+ if (!singleQuoteOpen && !doubleQuoteOpen) {
417
+ // Start of $( or $(( substitution — consume the opening '(' too
418
+ if (ch === '$' && i + 1 < string.length && string[i + 1] === '(') {
419
+ dollarDepth = 1;
420
+ tokenBuffer.push('$');
421
+ tokenBuffer.push('(');
422
+ i++;
423
+ continue;
424
+ }
425
+
426
+ // Whitespace splits tokens
427
+ if (ch.match(separator)) {
428
+ if (tokenBuffer.length > 0 || tokenHasQuote) {
429
+ parts.push({ value: tokenBuffer.join(''), hasQuote: tokenHasQuote });
430
+ tokenBuffer = [];
431
+ tokenHasQuote = false;
432
+ }
433
+ continue;
269
434
  }
270
- } else {
271
- tokenBuffer.push(character);
272
435
  }
436
+
437
+ tokenBuffer.push(ch);
273
438
  }
274
- if (tokenBuffer.length > 0) {
275
- parts.push(tokenBuffer.join(''));
439
+
440
+ if (tokenBuffer.length > 0 || tokenHasQuote) {
441
+ parts.push({ value: tokenBuffer.join(''), hasQuote: tokenHasQuote });
276
442
  }
277
443
 
278
- if(singleQuoteOpen || doubleQuoteOpen) {
444
+ if (singleQuoteOpen || doubleQuoteOpen) {
279
445
  throw new Error('quote expression not closed');
280
446
  }
281
447
  return parts;
282
448
  }
283
449
 
450
+ _isWasmFile(path, content) {
451
+ if (path.endsWith('.wasm') || path.endsWith('.wat')) return true;
452
+ if (typeof content !== 'string') return false;
453
+ // Binary WASM: magic bytes \0asm
454
+ if (content.charCodeAt(0) === 0 && content.slice(1, 4) === 'asm') return true;
455
+ // WAT text format
456
+ return content.trimStart().startsWith('(module');
457
+ }
458
+
284
459
  static _escapeRegExp(string) {
285
460
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
286
461
  }
@@ -293,4 +468,4 @@ Shell.STATUS_DESTROYED = 'DESTROYED';
293
468
  Shell.Command = Command;
294
469
 
295
470
  global.shell = Shell;
296
- module.exports = Shell;
471
+ module.exports = Shell;
package/lib/Command.js CHANGED
@@ -1,9 +1,11 @@
1
1
  'use strict';
2
2
 
3
+ const EventEmitter = require('events');
3
4
  const Result = require('./Result');
4
5
 
5
- class Command {
6
+ class Command extends EventEmitter {
6
7
  constructor(args) {
8
+ super();
7
9
  this.arguments = args;
8
10
  this.result = new Result();
9
11
  }
@@ -33,6 +35,10 @@ class Command {
33
35
  });
34
36
  }
35
37
 
38
+ onInput(char) {
39
+ //ignnored by default, can be overridden in a command if needed to get input
40
+ }
41
+
36
42
  set exitCode(code) {
37
43
  this.result.exitCode = code;
38
44
  }
@@ -44,6 +50,11 @@ class Command {
44
50
  set stdErr(String) {
45
51
  this.result.addStdErrLine(String);
46
52
  }
53
+
54
+ flush() {
55
+ console.log("flush now");
56
+ this.emit('flush', this.result.flush());
57
+ }
47
58
  }
48
59
 
49
60
  module.exports = Command;
package/lib/Context.js CHANGED
@@ -5,11 +5,11 @@ const FileSystem = require('./FileSystem');
5
5
  class Context {
6
6
  constructor(options) {
7
7
  this.options = options;
8
- const {cwd = '/', clearFn, destroyFn} = this.options;
8
+ const {cwd = '/', clearFn, destroyFn, onFsChange} = this.options;
9
9
 
10
10
  this.vars = {};
11
11
  this.aliases = {};
12
- this.fs = new FileSystem(cwd);
12
+ this.fs = new FileSystem(cwd, {}, {}, onFsChange || null);
13
13
  this._clearFn = clearFn;
14
14
  this._destroyFn = destroyFn;
15
15
  }
@@ -58,9 +58,17 @@ class Context {
58
58
  return this.fs.getFileByPath(location) || null;
59
59
  }
60
60
 
61
- setFilesystem(filesystem) {
61
+ setNodeFilesystem(cwd) {
62
+ const NodeFileSystem = require('./NodeFileSystem');
63
+ const onChange = this.fs._onChange;
64
+ this.fs = new NodeFileSystem(cwd, onChange);
65
+ }
66
+
67
+ setFilesystem(filesystem, permissions = {}) {
62
68
  const commands = this.fs.getFileByPath(this.getVar('PATH')) || {};
63
- this.fs = new FileSystem(this.fs.cwd, filesystem);
69
+ const oldPermissions = this.fs.getRawPermissions();
70
+ const onChange = this.fs._onChange;
71
+ this.fs = new FileSystem(this.fs.cwd, filesystem, Object.assign({}, oldPermissions, permissions), onChange);
64
72
  this.fs.addFiles(commands);
65
73
  }
66
74
 
package/lib/FileSystem.js CHANGED
@@ -1,9 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  class FileSystem {
4
- constructor(cwd = '/', filesystem = {}) {
4
+ constructor(cwd = '/', filesystem = {}, permissions = {}, onChange = null) {
5
5
  this.fileSystem = filesystem;
6
+ this.permissions = Object.assign({}, permissions);
6
7
  this.cwd = cwd;
8
+ this._onChange = onChange;
9
+ this._changeScheduled = false;
7
10
  }
8
11
 
9
12
  getFileByPath(path) {
@@ -31,10 +34,14 @@ class FileSystem {
31
34
  return pathParts.join('/');
32
35
  }
33
36
 
37
+ absolutePath(path) {
38
+ return this._pathToAbsolute(path);
39
+ }
40
+
34
41
  setFileByPath(path, content, createDir = false) {
35
42
  const absolute = this._pathToAbsolute(path);
36
-
37
43
  this._setFileByAbsolutePath(absolute, content, createDir);
44
+ this._triggerChange();
38
45
  }
39
46
 
40
47
  _setFileByAbsolutePath(absolute, content, createDir = true) {
@@ -72,6 +79,73 @@ class FileSystem {
72
79
  }, this.fileSystem);
73
80
  }
74
81
 
82
+ deleteFileByPath(path) {
83
+ const absolute = this._pathToAbsolute(path);
84
+ this._deleteByAbsolutePath(absolute);
85
+ // Remove any explicit permissions for this path and children
86
+ const prefix = absolute + '/';
87
+ Object.keys(this.permissions).forEach(k => {
88
+ if (k === absolute || k.startsWith(prefix)) {
89
+ delete this.permissions[k];
90
+ }
91
+ });
92
+ this._triggerChange();
93
+ }
94
+
95
+ _deleteByAbsolutePath(absolute) {
96
+ const parts = absolute.split('/');
97
+ parts.shift();
98
+ if (parts[parts.length - 1] === '') parts.pop();
99
+
100
+ const filename = parts.pop();
101
+ if (!filename) return;
102
+
103
+ const parent = parts.reduce((pointer, handle) => {
104
+ if (pointer && pointer[handle]) return pointer[handle];
105
+ return null;
106
+ }, this.fileSystem);
107
+
108
+ if (parent && filename in parent) {
109
+ delete parent[filename];
110
+ }
111
+ }
112
+
113
+ getMode(path) {
114
+ const absolute = this._pathToAbsolute(path);
115
+ if (this.permissions[absolute] !== undefined) {
116
+ return this.permissions[absolute];
117
+ }
118
+ const file = this._getFileByAbsolutePath(absolute);
119
+ if (file === null || file === undefined) return null;
120
+ if (file.constructor === Object) return 0o755;
121
+ if (typeof file === 'function') return 0o755;
122
+ return 0o644;
123
+ }
124
+
125
+ setMode(path, mode) {
126
+ const absolute = this._pathToAbsolute(path);
127
+ this.permissions[absolute] = mode;
128
+ this._triggerChange();
129
+ }
130
+
131
+ isExecutable(path) {
132
+ const mode = this.getMode(path);
133
+ if (mode === null) return false;
134
+ return (mode & 0o100) !== 0;
135
+ }
136
+
137
+ getSize(path) {
138
+ const absolute = this._pathToAbsolute(path);
139
+ const file = this._getFileByAbsolutePath(absolute);
140
+ if (file === null || file === undefined) return 0;
141
+ if (file.constructor === Object) return JSON.stringify(file).length;
142
+ return file.toString().length;
143
+ }
144
+
145
+ getRawPermissions() {
146
+ return Object.assign({}, this.permissions);
147
+ }
148
+
75
149
  setCwd(cwd) {
76
150
  this.cwd = this._pathToAbsolute(cwd.endsWith('/') ? cwd : (cwd + '/'));
77
151
  }
@@ -80,6 +154,10 @@ class FileSystem {
80
154
  return this.fileSystem;
81
155
  }
82
156
 
157
+ getRawPermissions() {
158
+ return Object.assign({}, this.permissions);
159
+ }
160
+
83
161
  addFiles(commands) {
84
162
  Object.entries(commands).forEach(([path, command]) => {
85
163
  this.setFileByPath(path, command, true);
@@ -95,7 +173,7 @@ class FileSystem {
95
173
  const dir = this.getFileByPath(parts.length > 1 ? parts.join('/') : '/');
96
174
  const pathDir = this.getFileByPath(path);
97
175
 
98
- if(dir.constructor === Object) {
176
+ if(dir && dir.constructor === Object) {
99
177
  let options = Object.keys(dir).filter(item => item.startsWith(end));
100
178
  if(end.length < 1) {
101
179
  options = options.filter(item => !item.startsWith('.'));
@@ -104,19 +182,34 @@ class FileSystem {
104
182
  const initialParts = initial.split('/');
105
183
  initialParts.pop();
106
184
 
107
- if(options.length < 1 && initialParts.length < 1) {
185
+ let sourceDir = dir;
186
+ if(options.length < 1 && initialParts.length < 1 && pathDir) {
108
187
  options = Object.keys(pathDir).filter(item => item.startsWith(end));
188
+ sourceDir = pathDir;
109
189
  }
110
190
 
111
191
  if(options.length) {
112
192
  return {
113
193
  path: initialParts.length ? initialParts.join('/') : null,
114
- options: options.map(path => dir[path].constructor === Object ? path.concat('/') : path)
194
+ options: options.map(item => sourceDir[item] && sourceDir[item].constructor === Object ? item.concat('/') : item)
115
195
  };
116
196
  }
117
197
  }
118
198
  return null;
119
199
  }
200
+
201
+ // Schedules a single onChange notification per microtask tick,
202
+ // so multiple mutations in one command emit only one callback.
203
+ _triggerChange() {
204
+ if (!this._onChange || this._changeScheduled) return;
205
+ this._changeScheduled = true;
206
+ Promise.resolve().then(() => {
207
+ this._changeScheduled = false;
208
+ if (typeof this._onChange === 'function') {
209
+ this._onChange(this.getRaw(), this.getRawPermissions());
210
+ }
211
+ });
212
+ }
120
213
  }
121
214
 
122
- module.exports = FileSystem;
215
+ module.exports = FileSystem;