@innovatorved/code-lab 0.3.1 → 0.3.2

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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
package/dist/shell.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -3022,6 +3022,13 @@ var CodeLabLogger = (() => {
3022
3022
  return out;
3023
3023
  }
3024
3024
 
3025
+ function quoteShellArg(arg) {
3026
+ const s = String(arg ?? '');
3027
+ if (s.length === 0) return "''";
3028
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
3029
+ return "'" + s.replace(/'/g, "'\\''") + "'";
3030
+ }
3031
+
3025
3032
  async function runPackageScript(scriptName, scriptArgs, ctx) {
3026
3033
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
3027
3034
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -3029,7 +3036,7 @@ var CodeLabLogger = (() => {
3029
3036
  }
3030
3037
  let cmd = pkgData.scripts[scriptName];
3031
3038
  if (scriptArgs && scriptArgs.length > 0) {
3032
- cmd += ' ' + scriptArgs.join(' ');
3039
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
3033
3040
  }
3034
3041
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
3035
3042
  if (fallback) return fallback;
@@ -3282,6 +3289,11 @@ var CodeLabLogger = (() => {
3282
3289
  const isFile = (p) => exists(p) && !isDir(p);
3283
3290
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3284
3291
 
3292
+ const isWithinRoot = (p) => {
3293
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3294
+ return p === rootDir || p.startsWith(rootPrefix);
3295
+ };
3296
+
3285
3297
  const resolveLocalTarget = (baseDir, rawSpec) => {
3286
3298
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3287
3299
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3289,6 +3301,7 @@ var CodeLabLogger = (() => {
3289
3301
  const candidateBase = clean.startsWith('/')
3290
3302
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3291
3303
  : PosixPath.join(baseDir, clean);
3304
+ if (!isWithinRoot(candidateBase)) return null;
3292
3305
  if (isFile(candidateBase)) return candidateBase;
3293
3306
  const cands = [
3294
3307
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3297,7 +3310,7 @@ var CodeLabLogger = (() => {
3297
3310
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3298
3311
  ];
3299
3312
  for (const c of cands) {
3300
- if (isFile(c)) return c;
3313
+ if (isWithinRoot(c) && isFile(c)) return c;
3301
3314
  }
3302
3315
  return null;
3303
3316
  };
@@ -3426,7 +3439,7 @@ var CodeLabLogger = (() => {
3426
3439
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3427
3440
  needsTailwindBrowser = true;
3428
3441
  }
3429
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3442
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3430
3443
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3431
3444
  });
3432
3445
 
@@ -3438,7 +3451,7 @@ var CodeLabLogger = (() => {
3438
3451
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3439
3452
  const rawScript = readText(scriptTarget);
3440
3453
  if (rawScript === null) return fullTag;
3441
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3454
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3442
3455
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3443
3456
  const typeAttr = isMod ? ' type="module"' : '';
3444
3457
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3461,6 +3474,12 @@ var CodeLabLogger = (() => {
3461
3474
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3462
3475
  const rel = pathname.replace(/^\/+/, '');
3463
3476
  let target = PosixPath.join(rootDir, rel);
3477
+ if (!isWithinRoot(target)) {
3478
+ return new Response(
3479
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3480
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3481
+ );
3482
+ }
3464
3483
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3465
3484
 
3466
3485
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3485,8 +3504,13 @@ var CodeLabLogger = (() => {
3485
3504
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3486
3505
  }
3487
3506
  if (!exists(target)) {
3507
+ const safePath = String(pathname)
3508
+ .replace(/&/g, '&amp;')
3509
+ .replace(/</g, '&lt;')
3510
+ .replace(/>/g, '&gt;')
3511
+ .replace(/"/g, '&quot;');
3488
3512
  return new Response(
3489
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3513
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3490
3514
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3491
3515
  );
3492
3516
  }
@@ -5637,13 +5661,17 @@ var CodeLabLogger = (() => {
5637
5661
 
5638
5662
  const count = Math.max(1, result.filesWritten);
5639
5663
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5664
+ if (!enumeratedEmitted) {
5665
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5666
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5667
+ }
5640
5668
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5641
5669
  const stdout =
5642
5670
  `Cloning into '${dirDisplayName}'...\n` +
5643
5671
  `remote: Enumerating objects: ${count}, done.\n` +
5644
5672
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5645
5673
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5646
- return { code: 0, stdout, stderr: '' };
5674
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5647
5675
  } catch (err) {
5648
5676
  if (ctx.signal && ctx.signal.aborted) {
5649
5677
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -6706,7 +6734,8 @@ var CodeLabLogger = (() => {
6706
6734
  if (ctx.vfs.existsSync(binPath)) {
6707
6735
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6708
6736
  }
6709
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6737
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6738
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6710
6739
  },
6711
6740
 
6712
6741
  async bunx(args, ctx) {
@@ -6777,7 +6806,8 @@ var CodeLabLogger = (() => {
6777
6806
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6778
6807
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6779
6808
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6780
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6809
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6810
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6781
6811
  }
6782
6812
 
6783
6813
  if (sub === 'dlx') {
@@ -7960,18 +7990,27 @@ var CodeLabLogger = (() => {
7960
7990
  if (item.background) {
7961
7991
  const pid = this.nextPid++;
7962
7992
  const jobId = this.nextJobId++;
7993
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7963
7994
  const job = {
7964
7995
  id: jobId,
7965
7996
  pid,
7966
7997
  command: trimmed,
7967
7998
  status: 'Running',
7968
- startTime: Date.now()
7999
+ startTime: Date.now(),
8000
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7969
8001
  };
7970
8002
  this.jobs.set(jobId, job);
7971
8003
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7972
8004
 
7973
- // Run in background promise
7974
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
8005
+ // Run in background promise with its own independent AbortSignal
8006
+ this._executeAstNode(item.node, {
8007
+ ...execOptions,
8008
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8009
+ env: Object.assign({}, this.env, currentEnv),
8010
+ cwd: this.cwd,
8011
+ pid,
8012
+ isBackground: true
8013
+ })
7975
8014
  .then(res => {
7976
8015
  if (job.status !== 'Terminated') {
7977
8016
  job.status = 'Done';
@@ -8125,17 +8164,24 @@ var CodeLabLogger = (() => {
8125
8164
  if (item.background) {
8126
8165
  const pid = this.nextPid++;
8127
8166
  const jobId = this.nextJobId++;
8167
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8128
8168
  const job = {
8129
8169
  id: jobId,
8130
8170
  pid,
8131
8171
  command: 'background',
8132
8172
  status: 'Running',
8133
- startTime: Date.now()
8173
+ startTime: Date.now(),
8174
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8134
8175
  };
8135
8176
  this.jobs.set(jobId, job);
8136
8177
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8137
8178
 
8138
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8179
+ this._executeAstNode(item.node, {
8180
+ ...context,
8181
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8182
+ pid,
8183
+ isBackground: true
8184
+ })
8139
8185
  .then(res => {
8140
8186
  if (job.status !== 'Terminated') {
8141
8187
  job.status = 'Done';
@@ -8251,7 +8297,11 @@ var CodeLabLogger = (() => {
8251
8297
  wordItems.push(...(innerCtx.positionalArgs || []));
8252
8298
  }
8253
8299
 
8300
+ let loopIter = 0;
8254
8301
  for (const val of wordItems) {
8302
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8303
+ await new Promise((r) => setTimeout(r, 0));
8304
+ }
8255
8305
  if (innerCtx.signal && innerCtx.signal.aborted) {
8256
8306
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8257
8307
  }
@@ -8296,7 +8346,11 @@ var CodeLabLogger = (() => {
8296
8346
  let combinedStderr = '';
8297
8347
  let lastCode = 0;
8298
8348
 
8349
+ let loopIter = 0;
8299
8350
  while (true) {
8351
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8352
+ await new Promise((r) => setTimeout(r, 0));
8353
+ }
8300
8354
  if (innerCtx.signal && innerCtx.signal.aborted) {
8301
8355
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8302
8356
  }
@@ -8763,7 +8817,9 @@ var CodeLabLogger = (() => {
8763
8817
 
8764
8818
  // Route any remaining unstreamed output
8765
8819
  if (res.stdout) {
8766
- if (streamedStdoutBytes > 0) {
8820
+ if (res.alreadyStreamed) {
8821
+ stdoutOut = res.stdout;
8822
+ } else if (streamedStdoutBytes > 0) {
8767
8823
  if (res.stdout.length > streamedStdoutBytes) {
8768
8824
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8769
8825
  }
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -422,6 +422,14 @@ var CodeLabLogger = (() => {
422
422
 
423
423
  const parseAnsiToHtml = ansiToHtml;
424
424
 
425
+ const MAX_SCROLLBACK = 2000;
426
+ const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
427
+
428
+ function sanitizeLogType(type) {
429
+ const t = String(type || 'stdout').trim();
430
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
431
+ }
432
+
425
433
  class PTYTerminalEngine {
426
434
  constructor(container, options = {}) {
427
435
  if (
@@ -436,6 +444,9 @@ var CodeLabLogger = (() => {
436
444
  }
437
445
  this.container = container || null;
438
446
  this.options = options || {};
447
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
448
+ ? this.options.maxScrollback
449
+ : MAX_SCROLLBACK;
439
450
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
440
451
  this.cwd = this.options.cwd || '/workspace';
441
452
  this.replMode = Boolean(this.options.replMode);
@@ -449,6 +460,7 @@ var CodeLabLogger = (() => {
449
460
  this.searchQuery = '';
450
461
  this.searchMatchIdx = -1;
451
462
  this._readLineQueue = [];
463
+ this.isBusy = false;
452
464
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
453
465
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
454
466
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -599,13 +611,40 @@ var CodeLabLogger = (() => {
599
611
  this.writeStreamChunk(String(data) + '\n', type);
600
612
  }
601
613
 
614
+ isCommandRunning() {
615
+ return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
616
+ }
617
+
618
+ _pushLog(entry) {
619
+ const normalized = {
620
+ type: sanitizeLogType(entry && entry.type),
621
+ text: String(entry && entry.text != null ? entry.text : '')
622
+ };
623
+ this.logs.push(normalized);
624
+ if (this.logs.length > this.maxScrollback) {
625
+ const excess = this.logs.length - this.maxScrollback;
626
+ this.logs.splice(0, excess);
627
+ if (this._targetLineIdx >= 0) {
628
+ this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
629
+ }
630
+ if (this.container && typeof this.container.querySelector === 'function') {
631
+ const logEl = this.container.querySelector('#cl-terminal-log');
632
+ if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
633
+ while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
634
+ logEl.removeChild(logEl.firstChild);
635
+ }
636
+ }
637
+ }
638
+ }
639
+ return normalized;
640
+ }
641
+
602
642
  _getActiveLine(type) {
603
643
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
604
644
  return this.logs[this._targetLineIdx];
605
645
  }
606
646
  if (this._activeLineCommitted || this.logs.length === 0) {
607
- const newLine = { text: '', type };
608
- this.logs.push(newLine);
647
+ const newLine = this._pushLog({ text: '', type });
609
648
  this._activeLineCommitted = false;
610
649
  this._cursorCol = 0;
611
650
  this._targetLineIdx = this.logs.length - 1;
@@ -622,7 +661,7 @@ var CodeLabLogger = (() => {
622
661
  const logEl = this.container.querySelector('#cl-terminal-log');
623
662
  if (!logEl) return;
624
663
  const lineEl = document.createElement('div');
625
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
664
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
626
665
  lineEl.innerHTML = ansiToHtml(line.text);
627
666
  logEl.appendChild(lineEl);
628
667
  this._activeLineEl = lineEl;
@@ -645,7 +684,7 @@ var CodeLabLogger = (() => {
645
684
  }
646
685
  }
647
686
  if (lineEl) {
648
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
687
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
649
688
  lineEl.innerHTML = ansiToHtml(line.text);
650
689
  }
651
690
  }
@@ -684,17 +723,29 @@ var CodeLabLogger = (() => {
684
723
  return [...this.history];
685
724
  }
686
725
 
687
- readLine(promptText = '') {
688
- const prevPrompt = this.promptOverride;
689
- if (promptText) {
690
- this.setPrompt(promptText);
726
+ _activateNextReadLine() {
727
+ if (!this._readLineQueue || this._readLineQueue.length === 0) return;
728
+ const head = this._readLineQueue[0];
729
+ if (head && typeof head === 'object' && !head._activated) {
730
+ head._activated = true;
731
+ head.prevPrompt = this.promptOverride;
732
+ if (head.promptText) {
733
+ this.promptOverride = head.promptText;
734
+ }
691
735
  }
736
+ }
737
+
738
+ readLine(promptText = '') {
692
739
  return new Promise((resolve) => {
693
- this._readLineQueue.push((line) => {
694
- this.promptOverride = prevPrompt;
695
- this.updateActiveLine();
696
- resolve(line);
697
- });
740
+ const item = {
741
+ promptText: String(promptText || ''),
742
+ prevPrompt: null,
743
+ _activated: false,
744
+ resolve
745
+ };
746
+ this._readLineQueue.push(item);
747
+ this._activateNextReadLine();
748
+ this.updateActiveLine();
698
749
  });
699
750
  }
700
751
 
@@ -764,6 +815,10 @@ var CodeLabLogger = (() => {
764
815
  if (input) {
765
816
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
766
817
  this._addListener(input, 'input', () => {
818
+ if (this.isCommandRunning()) {
819
+ input.value = '';
820
+ return;
821
+ }
767
822
  if (input.value !== this.buffer) {
768
823
  this.buffer = input.value;
769
824
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -805,6 +860,35 @@ var CodeLabLogger = (() => {
805
860
  const key = e.key;
806
861
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
807
862
 
863
+ if (isCtrl && (key === 'l' || key === 'L')) {
864
+ if (e.preventDefault) e.preventDefault();
865
+ this.clear();
866
+ return;
867
+ }
868
+
869
+ if (isCtrl && (key === 'c' || key === 'C')) {
870
+ if (e.preventDefault) e.preventDefault();
871
+ const wasBusy = this.isBusy;
872
+ this.isBusy = false;
873
+ this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
874
+ this.buffer = '';
875
+ this.cursor = 0;
876
+ this.historyIdx = -1;
877
+ if (this.replMode) {
878
+ this.replMode = false;
879
+ }
880
+ if (this.onInterrupt) {
881
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
882
+ }
883
+ this.render();
884
+ return;
885
+ }
886
+
887
+ if (this.isCommandRunning()) {
888
+ if (e.preventDefault) e.preventDefault();
889
+ return;
890
+ }
891
+
808
892
  if (isCtrl && (key === 'r' || key === 'R')) {
809
893
  if (e.preventDefault) e.preventDefault();
810
894
  if (!this.searchMode) {
@@ -936,33 +1020,11 @@ var CodeLabLogger = (() => {
936
1020
  return;
937
1021
  }
938
1022
 
939
- if (isCtrl && (key === 'l' || key === 'L')) {
940
- if (e.preventDefault) e.preventDefault();
941
- this.clear();
942
- return;
943
- }
944
-
945
- if (isCtrl && (key === 'c' || key === 'C')) {
946
- if (e.preventDefault) e.preventDefault();
947
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
948
- this.buffer = '';
949
- this.cursor = 0;
950
- this.historyIdx = -1;
951
- if (this.replMode) {
952
- this.replMode = false;
953
- }
954
- if (this.onInterrupt) {
955
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
956
- }
957
- this.render();
958
- return;
959
- }
960
-
961
1023
  if (isCtrl && (key === 'd' || key === 'D')) {
962
1024
  if (this.buffer === '') {
963
1025
  if (e.preventDefault) e.preventDefault();
964
1026
  if (this.replMode) {
965
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
1027
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
966
1028
  this.replMode = false;
967
1029
  this.render();
968
1030
  return;
@@ -1056,14 +1118,41 @@ var CodeLabLogger = (() => {
1056
1118
  }
1057
1119
 
1058
1120
  // Print candidate matches
1059
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1060
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
1121
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1122
+ this._pushLog({ type: 'stdout', text: matches.join(' ') });
1061
1123
  this.render();
1062
1124
  }
1063
1125
  }
1064
1126
 
1065
1127
  submitLine() {
1128
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
1129
+ const line = this.buffer;
1130
+ this.buffer = '';
1131
+ this.cursor = 0;
1132
+ this.historyIdx = -1;
1133
+ this.searchMode = false;
1134
+ this.searchQuery = '';
1135
+ this.searchMatchIdx = -1;
1136
+
1137
+ const entry = this._readLineQueue.shift();
1138
+ if (typeof entry === 'function') {
1139
+ this.updateActiveLine();
1140
+ entry(line);
1141
+ } else if (entry && typeof entry.resolve === 'function') {
1142
+ this.promptOverride = entry.prevPrompt;
1143
+ this._activateNextReadLine();
1144
+ this.updateActiveLine();
1145
+ entry.resolve(line);
1146
+ }
1147
+ return;
1148
+ }
1149
+
1150
+ if (this.isBusy) {
1151
+ return;
1152
+ }
1153
+
1066
1154
  const line = this.buffer;
1155
+ const promptSnap = this.getPrompt();
1067
1156
  this.buffer = '';
1068
1157
  this.cursor = 0;
1069
1158
  this.historyIdx = -1;
@@ -1071,22 +1160,49 @@ var CodeLabLogger = (() => {
1071
1160
  this.searchQuery = '';
1072
1161
  this.searchMatchIdx = -1;
1073
1162
 
1163
+ const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1164
+ this._activeLineCommitted = true;
1165
+ this._cursorCol = 0;
1166
+ this._targetLineIdx = -1;
1167
+ this._needsRewrite = false;
1168
+ this._appendDomLine(echoed);
1169
+ this._activeLineEl = null;
1170
+
1074
1171
  if (line.trim()) {
1075
1172
  if (this.history[this.history.length - 1] !== line.trim()) {
1076
1173
  this.history.push(line.trim());
1077
1174
  }
1078
1175
  }
1079
1176
 
1080
- if (this._readLineQueue && this._readLineQueue.length > 0) {
1081
- const resolver = this._readLineQueue.shift();
1177
+ if (!this.onCommand) {
1082
1178
  this.updateActiveLine();
1083
- resolver(line);
1084
1179
  return;
1085
1180
  }
1086
1181
 
1182
+ this.isBusy = true;
1087
1183
  this.updateActiveLine();
1088
- if (this.onCommand) {
1089
- this.onCommand(line);
1184
+
1185
+ let cmdResult;
1186
+ try {
1187
+ cmdResult = this.onCommand(line);
1188
+ } catch (err) {
1189
+ this.isBusy = false;
1190
+ this.updateActiveLine();
1191
+ throw err;
1192
+ }
1193
+
1194
+ if (cmdResult && typeof cmdResult.then === 'function') {
1195
+ Promise.resolve(cmdResult)
1196
+ .catch((err) => {
1197
+ _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1198
+ })
1199
+ .finally(() => {
1200
+ this.isBusy = false;
1201
+ this.updateActiveLine();
1202
+ });
1203
+ } else {
1204
+ this.isBusy = false;
1205
+ this.updateActiveLine();
1090
1206
  }
1091
1207
  }
1092
1208
 
@@ -1099,6 +1215,16 @@ var CodeLabLogger = (() => {
1099
1215
  const lineEl = this.container.querySelector('#cl-pty-active-line');
1100
1216
  if (!lineEl) return;
1101
1217
 
1218
+ if (this.isCommandRunning()) {
1219
+ if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1220
+ if (lineEl.style) lineEl.style.display = 'none';
1221
+ lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
1222
+ return;
1223
+ }
1224
+
1225
+ if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1226
+ if (lineEl.style) lineEl.style.display = '';
1227
+
1102
1228
  const prompt = this.searchMode
1103
1229
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
1104
1230
  : this.getPrompt();
@@ -1119,21 +1245,24 @@ var CodeLabLogger = (() => {
1119
1245
  );
1120
1246
 
1121
1247
  const logsHtml = this.logs
1122
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
1248
+ .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1123
1249
  .join('');
1124
1250
 
1125
- const prompt = this.searchMode
1126
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1127
- : this.getPrompt();
1128
- const before = this.buffer.slice(0, this.cursor);
1129
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1130
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1251
+ const busy = this.isCommandRunning();
1252
+ const prompt = busy
1253
+ ? ''
1254
+ : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1255
+ const before = busy ? '' : this.buffer.slice(0, this.cursor);
1256
+ const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1257
+ const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1258
+ const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1259
+ const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1131
1260
 
1132
1261
  this.container.innerHTML = `
1133
1262
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1134
1263
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1135
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
1136
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1264
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1265
+ <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1137
1266
  </div>
1138
1267
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1139
1268
  <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">