brsh 2.5.6 → 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.
@@ -0,0 +1,520 @@
1
+ 'use strict';
2
+
3
+ const InteractiveCommand = require('./InteractiveCommand');
4
+ const { createGenericWasmCommand } = require('./WasmCommand');
5
+
6
+ const CLEAR_SCREEN = '\x1b[2J\x1b[H';
7
+ const RESET = '\x1b[0m';
8
+ const INVERT = '\x1b[7m';
9
+ const BOLD = '\x1b[1m';
10
+ const DIM = '\x1b[2m';
11
+ const CYAN = '\x1b[36m';
12
+ const RED = '\x1b[31m';
13
+ const GREEN = '\x1b[32m';
14
+
15
+ /**
16
+ * Base class for commands that support both:
17
+ * 1. Non-interactive CLI / piped stdin / one-shot flag mode (`runNonInteractive()`)
18
+ * 2. Full-screen interactive REPL mode (`run()`) when invoked with no query/script
19
+ */
20
+ class ReplCommand extends InteractiveCommand {
21
+ get requiresFilesystem() {
22
+ return true;
23
+ }
24
+
25
+ get interactive() {
26
+ return this.shouldBeInteractive();
27
+ }
28
+
29
+ get captureInput() {
30
+ return this.shouldBeInteractive();
31
+ }
32
+
33
+ shouldBeInteractive() {
34
+ return Boolean(this._dynamicReplActive);
35
+ }
36
+
37
+ getReplTitle() {
38
+ return (this._dynamicReplOpts && this._dynamicReplOpts.title) || `${this.name} interactive shell`;
39
+ }
40
+
41
+ getReplPrompt() {
42
+ if (this._dynamicReplMultiline && this._dynamicReplOpts && this._dynamicReplOpts.continuePrompt) {
43
+ return this._dynamicReplOpts.continuePrompt;
44
+ }
45
+ return (this._dynamicReplOpts && this._dynamicReplOpts.prompt) || `${this.name}> `;
46
+ }
47
+
48
+ getReplWelcome() {
49
+ return (this._dynamicReplOpts && this._dynamicReplOpts.banner) || [`Welcome to ${this.name}. Type .exit or Ctrl+D to quit.`];
50
+ }
51
+
52
+ async initRepl() {}
53
+
54
+ async evaluateReplLine(line) {
55
+ if (this._dynamicReplOpts && typeof this._dynamicReplOpts.onEvaluate === 'function') {
56
+ const out = await this._dynamicReplOpts.onEvaluate(line);
57
+ return { output: Array.isArray(out) ? out : (out != null ? [String(out)] : []) };
58
+ }
59
+ return { output: [] };
60
+ }
61
+
62
+ async cleanupRepl() {
63
+ if (this._dynamicReplOpts && typeof this._dynamicReplOpts.onClose === 'function') {
64
+ await this._dynamicReplOpts.onClose();
65
+ }
66
+ }
67
+
68
+ async runNonInteractive() {}
69
+
70
+ /**
71
+ * Dynamically enters interactive REPL mode with the provided options:
72
+ * `{ title, banner, prompt, continuePrompt, needsMoreInput, isExitCommand, onEvaluate, onClose }`
73
+ */
74
+ startRepl(opts = {}) {
75
+ this._dynamicReplActive = true;
76
+ this._dynamicReplOpts = opts;
77
+ this._dynamicReplBuffer = '';
78
+ this._dynamicReplMultiline = false;
79
+ return this._launchInteractiveReplLoop();
80
+ }
81
+
82
+ run() {
83
+ if (!this.shouldBeInteractive()) {
84
+ return Promise.resolve(this.runNonInteractive());
85
+ }
86
+ return this._launchInteractiveReplLoop();
87
+ }
88
+
89
+ _launchInteractiveReplLoop() {
90
+ this._replHistory = [];
91
+ this._replHistoryIdx = null;
92
+ this._replInput = '';
93
+ this._replCursor = 0;
94
+ this._replLog = [];
95
+ this._replBusy = true;
96
+ this._replStatus = 'Initializing WASM runtime...';
97
+ this._scrollOffset = 0;
98
+
99
+ this._renderRepl();
100
+
101
+ return new Promise((resolve) => {
102
+ this._replResolve = resolve;
103
+ Promise.resolve()
104
+ .then(() => this.initRepl())
105
+ .then(() => {
106
+ this._replBusy = false;
107
+ this._replStatus = '^D / .exit: Quit | ^L: Clear | Up/Down: History';
108
+ for (const line of this.getReplWelcome()) {
109
+ this._appendReplLog(line, 'info');
110
+ }
111
+ this._renderRepl();
112
+ })
113
+ .catch((err) => {
114
+ this._replBusy = false;
115
+ this.stdErr = err.message || String(err);
116
+ this.exitCode = 1;
117
+ this._exitRepl();
118
+ });
119
+ });
120
+ }
121
+
122
+ _appendReplLog(text, type = 'out') {
123
+ const lines = String(text ?? '').split(/\r?\n/);
124
+ for (const line of lines) {
125
+ this._replLog.push({ text: line, type });
126
+ }
127
+ this._scrollOffset = 0;
128
+ }
129
+
130
+ onInput(key) {
131
+ if (!this.shouldBeInteractive()) return;
132
+
133
+ if (key === '^D' || key === '^X') {
134
+ this._exitRepl();
135
+ return;
136
+ }
137
+ if (key === '^C') {
138
+ if (this._replInput.length > 0 || this._dynamicReplBuffer) {
139
+ this._appendReplLog(`${this.getReplPrompt()}${this._replInput}^C`, 'prompt');
140
+ this._replInput = '';
141
+ this._replCursor = 0;
142
+ this._dynamicReplBuffer = '';
143
+ this._dynamicReplMultiline = false;
144
+ this._renderRepl();
145
+ } else {
146
+ this._exitRepl();
147
+ }
148
+ return;
149
+ }
150
+
151
+ if (this._replBusy) return;
152
+
153
+ if (key === '^L') {
154
+ this._replLog = [];
155
+ this._scrollOffset = 0;
156
+ this._renderRepl();
157
+ return;
158
+ }
159
+
160
+ if (key === 'Enter') {
161
+ const line = this._replInput;
162
+ this._replInput = '';
163
+ this._replCursor = 0;
164
+ this._replHistoryIdx = null;
165
+ if (line.trim()) {
166
+ this._replHistory.push(line);
167
+ }
168
+ this._appendReplLog(`${this.getReplPrompt()}${line}`, 'prompt');
169
+
170
+ const trimmed = line.trim();
171
+ const customExit = this._dynamicReplOpts && typeof this._dynamicReplOpts.isExitCommand === 'function'
172
+ ? this._dynamicReplOpts.isExitCommand(trimmed)
173
+ : false;
174
+ if (customExit || trimmed === '.exit' || trimmed === '.quit' || trimmed === '\\q' || trimmed === 'exit' || trimmed === 'quit' || trimmed === 'exit()' || trimmed === 'quit()') {
175
+ this._exitRepl();
176
+ return;
177
+ }
178
+ if (trimmed === '.clear' || trimmed === '\\! clear') {
179
+ this._replLog = [];
180
+ this._renderRepl();
181
+ return;
182
+ }
183
+
184
+ if (this._dynamicReplOpts && typeof this._dynamicReplOpts.needsMoreInput === 'function') {
185
+ this._dynamicReplBuffer = this._dynamicReplBuffer ? `${this._dynamicReplBuffer}\n${line}` : line;
186
+ if (this._dynamicReplOpts.needsMoreInput(this._dynamicReplBuffer)) {
187
+ this._dynamicReplMultiline = true;
188
+ this._renderRepl();
189
+ return;
190
+ }
191
+ }
192
+
193
+ const codeToEval = this._dynamicReplBuffer || line;
194
+ this._dynamicReplBuffer = '';
195
+ this._dynamicReplMultiline = false;
196
+
197
+ this._replBusy = true;
198
+ this._replStatus = 'Running...';
199
+ this._renderRepl();
200
+
201
+ Promise.resolve()
202
+ .then(() => this.evaluateReplLine(codeToEval))
203
+ .then((res) => {
204
+ this._replBusy = false;
205
+ this._replStatus = '^D / .exit: Quit | ^L: Clear | Up/Down: History';
206
+ if (res) {
207
+ if (res.clear) {
208
+ this._replLog = [];
209
+ }
210
+ if (Array.isArray(res.output)) {
211
+ for (const outLine of res.output) {
212
+ this._appendReplLog(outLine, 'out');
213
+ }
214
+ } else if (typeof res.output === 'string' && res.output.length > 0) {
215
+ this._appendReplLog(res.output, 'out');
216
+ }
217
+ if (res.error) {
218
+ this._appendReplLog(res.error, 'err');
219
+ }
220
+ if (res.exit) {
221
+ this._exitRepl();
222
+ return;
223
+ }
224
+ }
225
+ this._renderRepl();
226
+ })
227
+ .catch((err) => {
228
+ this._replBusy = false;
229
+ this._replStatus = '^D / .exit: Quit | ^L: Clear | Up/Down: History';
230
+ this._appendReplLog(`Error: ${err.message || err}`, 'err');
231
+ this._renderRepl();
232
+ });
233
+ return;
234
+ }
235
+
236
+ if (key === 'Backspace') {
237
+ if (this._replCursor > 0) {
238
+ this._replInput =
239
+ this._replInput.slice(0, this._replCursor - 1) +
240
+ this._replInput.slice(this._replCursor);
241
+ this._replCursor--;
242
+ this._renderRepl();
243
+ }
244
+ return;
245
+ }
246
+
247
+ if (key === 'Delete') {
248
+ if (this._replCursor < this._replInput.length) {
249
+ this._replInput =
250
+ this._replInput.slice(0, this._replCursor) +
251
+ this._replInput.slice(this._replCursor + 1);
252
+ this._renderRepl();
253
+ }
254
+ return;
255
+ }
256
+
257
+ if (key === 'ArrowLeft') {
258
+ if (this._replCursor > 0) {
259
+ this._replCursor--;
260
+ this._renderRepl();
261
+ }
262
+ return;
263
+ }
264
+
265
+ if (key === 'ArrowRight') {
266
+ if (this._replCursor < this._replInput.length) {
267
+ this._replCursor++;
268
+ this._renderRepl();
269
+ }
270
+ return;
271
+ }
272
+
273
+ if (key === 'Home' || key === '^A') {
274
+ this._replCursor = 0;
275
+ this._renderRepl();
276
+ return;
277
+ }
278
+
279
+ if (key === 'End' || key === '^E') {
280
+ this._replCursor = this._replInput.length;
281
+ this._renderRepl();
282
+ return;
283
+ }
284
+
285
+ if (key === 'ArrowUp') {
286
+ if (this._replHistory.length === 0) return;
287
+ if (this._replHistoryIdx === null) {
288
+ this._replHistoryIdx = this._replHistory.length - 1;
289
+ } else if (this._replHistoryIdx > 0) {
290
+ this._replHistoryIdx--;
291
+ }
292
+ this._replInput = this._replHistory[this._replHistoryIdx];
293
+ this._replCursor = this._replInput.length;
294
+ this._renderRepl();
295
+ return;
296
+ }
297
+
298
+ if (key === 'ArrowDown') {
299
+ if (this._replHistoryIdx === null) return;
300
+ if (this._replHistoryIdx < this._replHistory.length - 1) {
301
+ this._replHistoryIdx++;
302
+ this._replInput = this._replHistory[this._replHistoryIdx];
303
+ } else {
304
+ this._replHistoryIdx = null;
305
+ this._replInput = '';
306
+ }
307
+ this._replCursor = this._replInput.length;
308
+ this._renderRepl();
309
+ return;
310
+ }
311
+
312
+ if (key === 'PageUp') {
313
+ const maxScroll = Math.max(0, this._replLog.length - 5);
314
+ this._scrollOffset = Math.min(maxScroll, this._scrollOffset + 5);
315
+ this._renderRepl();
316
+ return;
317
+ }
318
+
319
+ if (key === 'PageDown') {
320
+ this._scrollOffset = Math.max(0, this._scrollOffset - 5);
321
+ this._renderRepl();
322
+ return;
323
+ }
324
+
325
+ if (key.length === 1 && !key.startsWith('^')) {
326
+ this._replInput =
327
+ this._replInput.slice(0, this._replCursor) +
328
+ key +
329
+ this._replInput.slice(this._replCursor);
330
+ this._replCursor++;
331
+ this._renderRepl();
332
+ }
333
+ }
334
+
335
+ _renderRepl() {
336
+ const { cols, rows } = this.terminalSize;
337
+ const bodyRows = Math.max(3, rows - 3);
338
+
339
+ const title = ` ${this.getReplTitle()} `;
340
+ const headerBar = `${INVERT}${BOLD}${title.padEnd(cols).slice(0, cols)}${RESET}`;
341
+
342
+ const totalLog = this._replLog.length;
343
+ const endIdx = Math.max(0, totalLog - this._scrollOffset);
344
+ const startIdx = Math.max(0, endIdx - bodyRows);
345
+ const visibleLog = this._replLog.slice(startIdx, endIdx);
346
+
347
+ const renderedBody = [];
348
+ for (let i = 0; i < bodyRows; i++) {
349
+ const entry = visibleLog[i];
350
+ if (!entry) {
351
+ renderedBody.push('');
352
+ continue;
353
+ }
354
+ if (entry.type === 'prompt') {
355
+ renderedBody.push(`${CYAN}${entry.text}${RESET}`);
356
+ } else if (entry.type === 'err') {
357
+ renderedBody.push(`${RED}${entry.text}${RESET}`);
358
+ } else if (entry.type === 'info') {
359
+ renderedBody.push(`${DIM}${entry.text}${RESET}`);
360
+ } else {
361
+ renderedBody.push(entry.text);
362
+ }
363
+ }
364
+
365
+ const promptStr = this.getReplPrompt();
366
+ const before = this._replInput.slice(0, this._replCursor);
367
+ const cursorChar = this._replCursor < this._replInput.length ? this._replInput[this._replCursor] : ' ';
368
+ const after = this._replCursor < this._replInput.length ? this._replInput.slice(this._replCursor + 1) : '';
369
+ const inputLine = this._replBusy
370
+ ? `${DIM}${this._replStatus}${RESET}`
371
+ : `${GREEN}${BOLD}${promptStr}${RESET}${before}${INVERT}${cursorChar}${RESET}${after}`;
372
+
373
+ const footerText = ` ${this._replStatus} `;
374
+ const footerBar = `${INVERT}${footerText.padEnd(cols).slice(0, cols)}${RESET}`;
375
+
376
+ const screen = [
377
+ CLEAR_SCREEN + headerBar,
378
+ ...renderedBody,
379
+ inputLine,
380
+ footerBar
381
+ ].join('\n');
382
+
383
+ this.stdOut = screen;
384
+ this.flush();
385
+ }
386
+
387
+ _exitRepl() {
388
+ Promise.resolve()
389
+ .then(() => this.cleanupRepl())
390
+ .catch(() => {})
391
+ .finally(() => {
392
+ if (this._replResolve) {
393
+ const r = this._replResolve;
394
+ this._replResolve = null;
395
+ r();
396
+ }
397
+ });
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Generic REPL extension of `WasmCommand.createGenericWasmCommand` for WASM packages with `repl` configured.
403
+ *
404
+ * - Non-interactive invocations (flags, script files, inline queries, or piped `stdin`) delegate
405
+ * directly to the base generic WASM runtime (`createGenericWasmCommand`).
406
+ * - Interactive invocations (no script/eval arguments and no piped `stdin`) launch the terminal
407
+ * REPL via `ReplCommand` and evaluate each entered line through the generic WASM command.
408
+ */
409
+ function createReplWasmCommand(pkgMeta, config = {}, binNameOverride = null) {
410
+ const binName = (binNameOverride || pkgMeta.bin || pkgMeta.name).toLowerCase();
411
+ const BaseWasmCmd = createGenericWasmCommand(pkgMeta, config, binName);
412
+ const replCfg = (pkgMeta && typeof pkgMeta.repl === 'object') ? pkgMeta.repl : {};
413
+
414
+ class ReplWasmCommand extends ReplCommand {
415
+ static get name() { return binName; }
416
+ get name() { return binName; }
417
+
418
+ constructor(args, context) {
419
+ super(args, context);
420
+ this._sessionArgs = [];
421
+ this._isInteractiveMode = this._detectInteractiveMode(args || []);
422
+ }
423
+
424
+ _detectInteractiveMode(args) {
425
+ if (args.includes('--help') || args.includes('-h') || args.includes('--version') || args.includes('-V') || args.includes('-v')) {
426
+ return false;
427
+ }
428
+ if (args.length === 0) {
429
+ return true;
430
+ }
431
+ // If `sessionArg: true` is configured (e.g. `sqlite3 /path/to/db.sqlite`), a single
432
+ // target file path argument with no inline query opens an interactive REPL bound to that target.
433
+ if (replCfg.sessionArg && args.length === 1 && !args[0].startsWith('-')) {
434
+ const arg = args[0].trim();
435
+ const looksLikeQuery = /^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(arg);
436
+ if (!looksLikeQuery) {
437
+ this._sessionArgs = [args[0]];
438
+ return true;
439
+ }
440
+ }
441
+ return false;
442
+ }
443
+
444
+ shouldBeInteractive() {
445
+ if (this._dynamicReplActive) return true;
446
+ if (this.stdin !== undefined && this.stdin !== null && String(this.stdin).trim().length > 0) {
447
+ return false;
448
+ }
449
+ return this._isInteractiveMode;
450
+ }
451
+
452
+ getReplTitle() {
453
+ const suffix = this._sessionArgs.length > 0 ? ` — ${this._sessionArgs.join(' ')}` : '';
454
+ return replCfg.title || `${binName} (${pkgMeta.name} ${pkgMeta.version || 'wasm'})${suffix}`;
455
+ }
456
+
457
+ getReplPrompt() {
458
+ if (this._dynamicReplMultiline && replCfg.continuePrompt) {
459
+ return replCfg.continuePrompt;
460
+ }
461
+ return replCfg.prompt || `${binName}> `;
462
+ }
463
+
464
+ getReplWelcome() {
465
+ return replCfg.banner || [
466
+ `${pkgMeta.name} (${pkgMeta.version || 'wasm'}) interactive shell`,
467
+ `Type ".exit" or Ctrl+D to quit.`
468
+ ];
469
+ }
470
+
471
+ async evaluateReplLine(line) {
472
+ const evalFlag = replCfg.evalFlag;
473
+ const invokeArgs = evalFlag
474
+ ? [...this._sessionArgs, evalFlag, line]
475
+ : [...this._sessionArgs, line];
476
+ const stdinText = evalFlag ? undefined : line;
477
+ const { out, err } = await this._captureBaseWasmOutput(invokeArgs, stdinText);
478
+ return {
479
+ output: out,
480
+ error: err.length > 0 ? err.join('\n') : undefined
481
+ };
482
+ }
483
+
484
+ async runNonInteractive() {
485
+ await this._delegateToBaseWasm([...(this.arguments || [])]);
486
+ }
487
+
488
+ async _delegateToBaseWasm(args) {
489
+ const base = new BaseWasmCmd(args, this.context);
490
+ base.fs = this.fs;
491
+ if (this.stdin !== undefined) base.stdin = this.stdin;
492
+ await base.run();
493
+ for (const line of base.result.getStdOutput()) {
494
+ if (line.type === 'out') this.stdOut = line.string;
495
+ else if (line.type === 'err') this.stdErr = line.string;
496
+ }
497
+ this.exitCode = base.exitCode || base.result.getExitCode();
498
+ }
499
+
500
+ async _captureBaseWasmOutput(args, stdinText) {
501
+ const base = new BaseWasmCmd(args, this.context);
502
+ base.fs = this.fs;
503
+ if (stdinText !== undefined) base.stdin = stdinText;
504
+ await base.run();
505
+ const out = [];
506
+ const err = [];
507
+ for (const line of base.result.getStdOutput()) {
508
+ if (line.type === 'err') err.push(line.string);
509
+ else out.push(line.string);
510
+ }
511
+ return { out, err };
512
+ }
513
+ }
514
+
515
+ return ReplWasmCommand;
516
+ }
517
+
518
+ ReplCommand.createReplWasmCommand = createReplWasmCommand;
519
+ ReplCommand.createCommand = createReplWasmCommand;
520
+ module.exports = ReplCommand;
@@ -36,9 +36,10 @@ class ScriptCommand extends LocalCommand {
36
36
  const fsOpts = this.context.fs.isRealFilesystem
37
37
  ? { useRealFilesystem: true }
38
38
  : { filesystem: this.context.fs.getRaw(), permissions: this.context.fs.getRawPermissions() };
39
- this.sandbox = new global.shell({
39
+ this.sandbox = new globalThis.shell({
40
40
  cwd: this.context.fs.cwd,
41
- ...fsOpts
41
+ ...fsOpts,
42
+ subshell: true
42
43
  });
43
44
  this.sandbox.context.source(this.context);
44
45
 
package/lib/Terminal.js CHANGED
@@ -17,7 +17,8 @@ class Terminal {
17
17
  animateSpeed = 1,
18
18
  onExit = null,
19
19
  mobileInput = 'click',
20
- lineWrap = false
20
+ lineWrap = false,
21
+ command = null
21
22
  } = options;
22
23
 
23
24
  if(!el) {
@@ -41,8 +42,9 @@ class Terminal {
41
42
  this._outputAnimation = outputAnimation;
42
43
  this._animateSpeed = animateSpeed;
43
44
  this._lineWrap = lineWrap;
44
- this._working = false;
45
- this.cli = new Shell(options);
45
+ this._working = true;
46
+ this._pendingCommands = [];
47
+ this.cli = new Shell(Object.assign({}, options, { command: undefined }));
46
48
  this._buffer = [];
47
49
  this._cursorPos = 0;
48
50
  this._history = [];
@@ -63,6 +65,10 @@ class Terminal {
63
65
  this._setupDom(this._el, font);
64
66
  this._attachShellListeners();
65
67
 
68
+ if (command) {
69
+ this.onCommand(command);
70
+ }
71
+
66
72
  if(mobileInput === 'click') {
67
73
  this._mobileInput();
68
74
  }
@@ -82,7 +88,11 @@ class Terminal {
82
88
 
83
89
  onCommand(command) {
84
90
  if(!this._currentLine) {
85
- return setTimeout(this.onCommand.bind(this, command), 10);
91
+ if (this.cli) {
92
+ this.cli.suppressMotd();
93
+ }
94
+ this._pendingCommands.push(command);
95
+ return;
86
96
  }
87
97
 
88
98
  const onUpdate = this._setCurrentLine.bind(this);
@@ -311,6 +321,16 @@ class Terminal {
311
321
  return requestAnimationFrame(this._statusCheck.bind(this, status));
312
322
  }
313
323
  this._newPrompt(this._setCurrentLine.bind(this, this._buffer));
324
+ if (this._pendingCommands && this._pendingCommands.length > 0) {
325
+ const nextCmd = this._pendingCommands.shift();
326
+ if (this._pendingCommands.length === 0 && this.cli) {
327
+ const flags = this.cli.context.getVar('-');
328
+ if (flags.includes('c')) {
329
+ this.cli.context.setVar('-', flags.replace(/c/g, ''));
330
+ }
331
+ }
332
+ this.onCommand(nextCmd);
333
+ }
314
334
  } else {
315
335
  this._clearCursor();
316
336
  this._working = true;