@innovatorved/code-lab 0.1.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,1083 @@
1
+ /**
2
+ * ============================================================
3
+ * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
4
+ * ============================================================
5
+ * Features:
6
+ * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
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)
9
+ * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
+ * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
+ * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
12
+ * - Modular Opt-In Guided Lab Extension (stepper, hints, solution diff, JS/TS switcher)
13
+ * - Zero-Auth Public GitHub Repository Cloning (git clone, workbench.cloneRepo, <code-lab repo="...">)
14
+ * - Third-Party Imperative SDK (getFiles, setFiles, getFile, setFile, cloneRepo, on, off, use, exportWorkspace)
15
+ * ============================================================
16
+ */
17
+ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
18
+ (function () {
19
+ /**
20
+ * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
21
+ *
22
+ * High-fidelity, self-contained terminal emulator engine providing:
23
+ * - Inline prompt with cwd awareness (codelab:${cwd}$ )
24
+ * - Interactive REPL sub-mode (> ) with .exit and Ctrl+D/Ctrl+C
25
+ * - Character-by-character editing with cursor navigation:
26
+ * ArrowLeft, ArrowRight, Home, End, Ctrl+A, Ctrl+E, Ctrl+U, Ctrl+K, Backspace, Delete
27
+ * - Tab auto-completion for built-in commands and VFS filesystem paths
28
+ * - History navigation (ArrowUp, ArrowDown)
29
+ * - ANSI 16/256 SGR escape sequence translation to styled Geist HTML spans
30
+ * - Headless DOM safety (defensive guards for Node.js test environments)
31
+ *
32
+ * (C) 2026 InnovatorVed / CodeLab. MIT License.
33
+ */
34
+
35
+ (function (root, factory) {
36
+ const exports = factory();
37
+ if (root) {
38
+ root.CodeLabTerminal = exports;
39
+ root.PTYTerminalEngine = exports.PTYTerminalEngine;
40
+ root.createPTYTerminalEngine = exports.createPTYTerminalEngine;
41
+ root.createTerminal = exports.createTerminal;
42
+ root.ansiToHtml = exports.ansiToHtml;
43
+ root.parseAnsiToHtml = exports.parseAnsiToHtml;
44
+ }
45
+ if (typeof module !== 'undefined' && module.exports) {
46
+ module.exports = exports;
47
+ } else if (typeof define === 'function' && define.amd) {
48
+ define([], function () { return exports; });
49
+ }
50
+ })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
51
+ 'use strict';
52
+
53
+ const ANSI_CODE_MAP = {
54
+ 1: 'cl-ansi-bold',
55
+ 2: 'cl-ansi-dim',
56
+ 3: 'cl-ansi-italic',
57
+ 4: 'cl-ansi-underline',
58
+ 30: 'cl-ansi-black',
59
+ 31: 'cl-ansi-red',
60
+ 32: 'cl-ansi-green',
61
+ 33: 'cl-ansi-yellow',
62
+ 34: 'cl-ansi-blue',
63
+ 35: 'cl-ansi-magenta',
64
+ 36: 'cl-ansi-cyan',
65
+ 37: 'cl-ansi-white',
66
+ 90: 'cl-ansi-gray',
67
+ 91: 'cl-ansi-bright-red',
68
+ 92: 'cl-ansi-bright-green',
69
+ 93: 'cl-ansi-bright-yellow',
70
+ 94: 'cl-ansi-bright-blue',
71
+ 95: 'cl-ansi-bright-magenta',
72
+ 96: 'cl-ansi-bright-cyan',
73
+ 97: 'cl-ansi-bright-white',
74
+ 40: 'cl-ansi-bg-black',
75
+ 41: 'cl-ansi-bg-red',
76
+ 42: 'cl-ansi-bg-green',
77
+ 43: 'cl-ansi-bg-yellow',
78
+ 44: 'cl-ansi-bg-blue',
79
+ 45: 'cl-ansi-bg-magenta',
80
+ 46: 'cl-ansi-bg-cyan',
81
+ 47: 'cl-ansi-bg-white',
82
+ 100: 'cl-ansi-bg-bright-black',
83
+ 101: 'cl-ansi-bg-bright-red',
84
+ 102: 'cl-ansi-bg-bright-green',
85
+ 103: 'cl-ansi-bg-bright-yellow',
86
+ 104: 'cl-ansi-bg-bright-blue',
87
+ 105: 'cl-ansi-bg-bright-magenta',
88
+ 106: 'cl-ansi-bg-bright-cyan',
89
+ 107: 'cl-ansi-bg-bright-white'
90
+ };
91
+
92
+ const ANSI_256_PALETTE = [
93
+ '#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
94
+ '#666666', '#f14c4c', '#23d18b', '#f5f543', '#3b8eea', '#d670d6', '#29b8db', '#ffffff'
95
+ ];
96
+
97
+ function ansi256ToColor(n) {
98
+ const idx = Number(n);
99
+ if (!Number.isFinite(idx) || idx < 0 || idx > 255) return null;
100
+ if (idx < 16) return ANSI_256_PALETTE[idx];
101
+ if (idx < 232) {
102
+ const c = idx - 16;
103
+ const r = Math.floor(c / 36);
104
+ const g = Math.floor((c % 36) / 6);
105
+ const b = c % 6;
106
+ const toChannel = v => (v === 0 ? 0 : 55 + v * 40);
107
+ return `rgb(${toChannel(r)}, ${toChannel(g)}, ${toChannel(b)})`;
108
+ }
109
+ const gray = 8 + (idx - 232) * 10;
110
+ return `rgb(${gray}, ${gray}, ${gray})`;
111
+ }
112
+
113
+ function escapeHtml(str) {
114
+ if (str == null) return '';
115
+ return String(str)
116
+ .replace(/&/g, '&amp;')
117
+ .replace(/</g, '&lt;')
118
+ .replace(/>/g, '&gt;')
119
+ .replace(/"/g, '&quot;')
120
+ .replace(/'/g, '&#39;');
121
+ }
122
+
123
+ function resolveAnsiControlCodes(raw) {
124
+ if (!raw) return '';
125
+ const s = String(raw);
126
+ if (!s.includes('\x1b') && !s.includes('\r')) return s;
127
+
128
+ let text = s;
129
+ const lastClearScreen = text.lastIndexOf('\x1b[2J');
130
+ if (lastClearScreen !== -1) {
131
+ text = text.slice(lastClearScreen + 4);
132
+ text = text.replace(/^\x1b\[(?:1;1)?H/, '');
133
+ }
134
+
135
+ text = text.replace(/\r\n/g, '\n');
136
+ const rawLines = text.split('\n');
137
+ const resolvedLines = [];
138
+
139
+ for (let l = 0; l < rawLines.length; l++) {
140
+ let line = rawLines[l];
141
+
142
+ while (/\x1b\[(?:1)?A/.test(line)) {
143
+ const upMatch = /\x1b\[(?:1)?A/.exec(line);
144
+ const beforeUp = line.slice(0, upMatch.index);
145
+ let afterUp = line.slice(upMatch.index + upMatch[0].length);
146
+ if (resolvedLines.length > 0) {
147
+ if (afterUp.includes('\x1b[2K')) {
148
+ afterUp = afterUp.slice(afterUp.lastIndexOf('\x1b[2K') + 4);
149
+ resolvedLines[resolvedLines.length - 1] = afterUp;
150
+ } else if (afterUp.includes('\r')) {
151
+ const parts = afterUp.split('\r');
152
+ resolvedLines[resolvedLines.length - 1] = parts[parts.length - 1];
153
+ } else {
154
+ resolvedLines[resolvedLines.length - 1] = afterUp;
155
+ }
156
+ line = beforeUp;
157
+ } else {
158
+ line = beforeUp + afterUp;
159
+ }
160
+ }
161
+
162
+ if (line.includes('\x1b[2K')) {
163
+ const idx = line.lastIndexOf('\x1b[2K');
164
+ line = line.slice(idx + 4);
165
+ }
166
+
167
+ if (line.includes('\r')) {
168
+ const parts = line.split('\r');
169
+ line = parts[parts.length - 1];
170
+ }
171
+
172
+ line = line.replace(/\x1b\[[0]?K/g, '');
173
+ line = line.replace(/\x1b\[(?:1)?G/g, '');
174
+ resolvedLines.push(line);
175
+ }
176
+
177
+ return resolvedLines.join('\n');
178
+ }
179
+
180
+ function ansiToHtml(str) {
181
+ if (!str) return '';
182
+ const resolved = resolveAnsiControlCodes(String(str));
183
+ if (!resolved.includes('\x1b[')) {
184
+ return escapeHtml(resolved);
185
+ }
186
+
187
+ // Strip non-color cursor control sequences without stripping lowercase 'm' SGR codes
188
+ const cleaned = resolved.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g, '');
189
+
190
+ const tokenRegex = /\x1b\[([0-9;]*)m/g;
191
+ let result = '';
192
+ let lastIdx = 0;
193
+ let match;
194
+
195
+ const state = {
196
+ bold: false,
197
+ dim: false,
198
+ italic: false,
199
+ underline: false,
200
+ fgClass: null,
201
+ bgClass: null,
202
+ fgColor: null,
203
+ bgColor: null
204
+ };
205
+
206
+ const resetState = () => {
207
+ state.bold = false;
208
+ state.dim = false;
209
+ state.italic = false;
210
+ state.underline = false;
211
+ state.fgClass = null;
212
+ state.bgClass = null;
213
+ state.fgColor = null;
214
+ state.bgColor = null;
215
+ };
216
+
217
+ const renderChunk = (rawText) => {
218
+ if (!rawText) return '';
219
+ const escaped = escapeHtml(rawText);
220
+ const classes = [];
221
+ if (state.bold) classes.push('cl-ansi-bold');
222
+ if (state.dim) classes.push('cl-ansi-dim');
223
+ if (state.italic) classes.push('cl-ansi-italic');
224
+ if (state.underline) classes.push('cl-ansi-underline');
225
+ if (state.fgClass) classes.push(state.fgClass);
226
+ if (state.bgClass) classes.push(state.bgClass);
227
+
228
+ const styles = [];
229
+ if (state.fgColor) styles.push(`color:${state.fgColor}`);
230
+ if (state.bgColor) styles.push(`background-color:${state.bgColor}`);
231
+
232
+ if (classes.length === 0 && styles.length === 0) {
233
+ return escaped;
234
+ }
235
+ const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
236
+ const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
237
+ return `<span${classAttr}${styleAttr}>${escaped}</span>`;
238
+ };
239
+
240
+ while ((match = tokenRegex.exec(cleaned)) !== null) {
241
+ const rawText = cleaned.slice(lastIdx, match.index);
242
+ if (rawText) result += renderChunk(rawText);
243
+ lastIdx = tokenRegex.lastIndex;
244
+
245
+ const codes = match[1] ? match[1].split(';').map(Number) : [0];
246
+ for (let i = 0; i < codes.length; i++) {
247
+ const code = codes[i];
248
+ if (code === 0 || Number.isNaN(code)) {
249
+ resetState();
250
+ } else if (code === 1) {
251
+ state.bold = true;
252
+ } else if (code === 2) {
253
+ state.dim = true;
254
+ } else if (code === 3) {
255
+ state.italic = true;
256
+ } else if (code === 4) {
257
+ state.underline = true;
258
+ } else if (code === 22) {
259
+ state.bold = false;
260
+ state.dim = false;
261
+ } else if (code === 23) {
262
+ state.italic = false;
263
+ } else if (code === 24) {
264
+ state.underline = false;
265
+ } else if (code === 39) {
266
+ state.fgClass = null;
267
+ state.fgColor = null;
268
+ } else if (code === 49) {
269
+ state.bgClass = null;
270
+ state.bgColor = null;
271
+ } else if ((code === 38 || code === 48) && codes[i + 1] === 5 && i + 2 < codes.length) {
272
+ const color = ansi256ToColor(codes[i + 2]);
273
+ if (color) {
274
+ if (code === 38) {
275
+ state.fgClass = null;
276
+ state.fgColor = color;
277
+ } else {
278
+ state.bgClass = null;
279
+ state.bgColor = color;
280
+ }
281
+ }
282
+ i += 2;
283
+ } else if ((code === 38 || code === 48) && codes[i + 1] === 2 && i + 4 < codes.length) {
284
+ const r = Math.max(0, Math.min(255, Number(codes[i + 2]) || 0));
285
+ const g = Math.max(0, Math.min(255, Number(codes[i + 3]) || 0));
286
+ const b = Math.max(0, Math.min(255, Number(codes[i + 4]) || 0));
287
+ const color = `rgb(${r}, ${g}, ${b})`;
288
+ if (code === 38) {
289
+ state.fgClass = null;
290
+ state.fgColor = color;
291
+ } else {
292
+ state.bgClass = null;
293
+ state.bgColor = color;
294
+ }
295
+ i += 4;
296
+ } else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
297
+ state.fgClass = ANSI_CODE_MAP[code] || null;
298
+ state.fgColor = null;
299
+ } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
300
+ state.bgClass = ANSI_CODE_MAP[code] || null;
301
+ state.bgColor = null;
302
+ }
303
+ }
304
+ }
305
+
306
+ const remaining = cleaned.slice(lastIdx);
307
+ if (remaining) result += renderChunk(remaining);
308
+ return result;
309
+ }
310
+
311
+ const parseAnsiToHtml = ansiToHtml;
312
+
313
+ class PTYTerminalEngine {
314
+ constructor(container, options = {}) {
315
+ if (
316
+ container &&
317
+ typeof container === 'object' &&
318
+ typeof container.querySelector !== 'function' &&
319
+ typeof container.appendChild !== 'function' &&
320
+ arguments.length === 1
321
+ ) {
322
+ options = container;
323
+ container = options.container || null;
324
+ }
325
+ this.container = container || null;
326
+ this.options = options || {};
327
+ this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
328
+ this.cwd = this.options.cwd || '/workspace';
329
+ this.replMode = Boolean(this.options.replMode);
330
+ this.promptOverride = this.options.prompt || null;
331
+ this.history = Array.isArray(this.options.history) ? this.options.history : [];
332
+ this.historyIdx = -1;
333
+ this.savedBuffer = '';
334
+ this.buffer = '';
335
+ this.cursor = 0;
336
+ this.searchMode = false;
337
+ this.searchQuery = '';
338
+ this.searchMatchIdx = -1;
339
+ this._readLineQueue = [];
340
+ this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
341
+ this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
342
+ this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
343
+ this.onInterrupt = typeof this.options.onInterrupt === 'function' ? this.options.onInterrupt : null;
344
+
345
+ // Stream & active line buffering state
346
+ this._activeLineCommitted = true;
347
+ this._cursorCol = 0;
348
+ this._pendingEscape = '';
349
+ this._targetLineIdx = -1;
350
+ this._needsRewrite = false;
351
+ this._activeLineEl = null;
352
+
353
+ this._mounted = false;
354
+ this._listeners = [];
355
+
356
+ if (this.container) {
357
+ this.mount(this.container);
358
+ }
359
+ }
360
+
361
+ getPrompt() {
362
+ if (this.promptOverride) return this.promptOverride;
363
+ if (this.replMode) return '> ';
364
+ const cwd = this.cwd || '/workspace';
365
+ return `codelab:${cwd}$ `;
366
+ }
367
+
368
+ setPrompt(p) {
369
+ this.promptOverride = p;
370
+ this.updateActiveLine();
371
+ }
372
+
373
+ setCwd(cwd) {
374
+ this.cwd = cwd;
375
+ this.updateActiveLine();
376
+ }
377
+
378
+ setReplMode(enabled) {
379
+ this.replMode = Boolean(enabled);
380
+ this.updateActiveLine();
381
+ }
382
+
383
+ writeStreamChunk(data, type = 'stdout') {
384
+ let str = String(data != null ? data : '');
385
+ if (!str) return;
386
+
387
+ if (this._pendingEscape) {
388
+ str = this._pendingEscape + str;
389
+ this._pendingEscape = '';
390
+ }
391
+
392
+ let modified = false;
393
+ let i = 0;
394
+
395
+ while (i < str.length) {
396
+ if (str[i] === '\x1b') {
397
+ const rest = str.slice(i);
398
+ if (/^\x1b(?:\[[0-9;?]*)?$/.test(rest)) {
399
+ this._pendingEscape = rest;
400
+ break;
401
+ }
402
+
403
+ const csiMatch = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(rest);
404
+ if (csiMatch) {
405
+ const params = csiMatch[1];
406
+ const cmd = csiMatch[2];
407
+ const seq = csiMatch[0];
408
+ i += seq.length;
409
+
410
+ if (cmd === 'K') {
411
+ const cur = this._getActiveLine(type);
412
+ if (params === '2') {
413
+ cur.text = '';
414
+ this._cursorCol = 0;
415
+ this._needsRewrite = false;
416
+ } else {
417
+ cur.text = cur.text.slice(0, this._cursorCol);
418
+ this._needsRewrite = false;
419
+ }
420
+ modified = true;
421
+ } else if (cmd === 'A') {
422
+ const count = parseInt(params, 10) || 1;
423
+ if (this.logs.length > 0) {
424
+ const baseIdx = this._activeLineCommitted ? this.logs.length : this.logs.length - 1;
425
+ this._targetLineIdx = Math.max(0, baseIdx - count);
426
+ this._activeLineCommitted = false;
427
+ this._cursorCol = 0;
428
+ this._needsRewrite = false;
429
+ const targetLine = this.logs[this._targetLineIdx];
430
+ if (targetLine) targetLine.text = '';
431
+ this._activeLineEl = null;
432
+ }
433
+ } else if (cmd === 'G') {
434
+ this._cursorCol = 0;
435
+ this._needsRewrite = true;
436
+ } else if (cmd === 'J' && params === '2') {
437
+ this.clear();
438
+ } else if (cmd === 'm') {
439
+ const cur = this._getActiveLine(type);
440
+ cur.text += seq;
441
+ modified = true;
442
+ }
443
+ continue;
444
+ }
445
+ }
446
+
447
+ const ch = str[i];
448
+ if (ch === '\r') {
449
+ this._cursorCol = 0;
450
+ this._needsRewrite = true;
451
+ i++;
452
+ } else if (ch === '\n') {
453
+ const cur = this._getActiveLine(type);
454
+ cur.text += '\n';
455
+ this._activeLineCommitted = true;
456
+ this._cursorCol = 0;
457
+ this._targetLineIdx = -1;
458
+ this._needsRewrite = false;
459
+ this._activeLineEl = null;
460
+ modified = true;
461
+ i++;
462
+ } else {
463
+ const cur = this._getActiveLine(type);
464
+ if (this._needsRewrite && this._cursorCol === 0 && cur.text.length > 0 && !cur.text.endsWith('\n')) {
465
+ cur.text = ch;
466
+ this._needsRewrite = false;
467
+ } else {
468
+ cur.text += ch;
469
+ }
470
+ this._cursorCol++;
471
+ modified = true;
472
+ i++;
473
+ }
474
+ }
475
+
476
+ if (modified) {
477
+ this._updateActiveDomLine();
478
+ }
479
+ this._scrollToBottom();
480
+ }
481
+
482
+ write(data, type = 'stdout') {
483
+ this.writeStreamChunk(data, type);
484
+ }
485
+
486
+ writeln(data, type = 'stdout') {
487
+ this.writeStreamChunk(String(data) + '\n', type);
488
+ }
489
+
490
+ _getActiveLine(type) {
491
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
492
+ return this.logs[this._targetLineIdx];
493
+ }
494
+ if (this._activeLineCommitted || this.logs.length === 0) {
495
+ const newLine = { text: '', type };
496
+ this.logs.push(newLine);
497
+ this._activeLineCommitted = false;
498
+ this._cursorCol = 0;
499
+ this._targetLineIdx = this.logs.length - 1;
500
+ this._needsRewrite = false;
501
+ this._appendDomLine(newLine);
502
+ return newLine;
503
+ }
504
+ this._targetLineIdx = this.logs.length - 1;
505
+ return this.logs[this.logs.length - 1];
506
+ }
507
+
508
+ _appendDomLine(line) {
509
+ if (!this.container || typeof document === 'undefined') return;
510
+ const logEl = this.container.querySelector('#cl-terminal-log');
511
+ if (!logEl) return;
512
+ const lineEl = document.createElement('div');
513
+ lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
514
+ lineEl.innerHTML = ansiToHtml(line.text);
515
+ logEl.appendChild(lineEl);
516
+ this._activeLineEl = lineEl;
517
+ }
518
+
519
+ _updateActiveDomLine() {
520
+ if (!this.container || typeof document === 'undefined') return;
521
+ const line = this._getActiveLineSync();
522
+ if (!line) return;
523
+ let lineEl = this._activeLineEl;
524
+ if (!lineEl || !lineEl.parentNode) {
525
+ const logEl = this.container.querySelector('#cl-terminal-log');
526
+ if (logEl) {
527
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < logEl.children.length) {
528
+ lineEl = logEl.children[this._targetLineIdx];
529
+ } else {
530
+ lineEl = logEl.children[logEl.children.length - 1];
531
+ }
532
+ this._activeLineEl = lineEl;
533
+ }
534
+ }
535
+ if (lineEl) {
536
+ lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
537
+ lineEl.innerHTML = ansiToHtml(line.text);
538
+ }
539
+ }
540
+
541
+ _getActiveLineSync() {
542
+ if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
543
+ return this.logs[this._targetLineIdx];
544
+ }
545
+ return this.logs[this.logs.length - 1] || null;
546
+ }
547
+
548
+ _scrollToBottom() {
549
+ if (!this.container) return;
550
+ const surface = this.container.querySelector('#cl-terminal-surface') || this.container;
551
+ if (surface && typeof surface.scrollTop === 'number' && typeof surface.scrollHeight === 'number') {
552
+ surface.scrollTop = surface.scrollHeight;
553
+ }
554
+ }
555
+
556
+ clear() {
557
+ this.logs.length = 0;
558
+ this._activeLineCommitted = true;
559
+ this._cursorCol = 0;
560
+ this._targetLineIdx = -1;
561
+ this._needsRewrite = false;
562
+ this._activeLineEl = null;
563
+ if (this.container && typeof this.container.querySelector === 'function') {
564
+ const logEl = this.container.querySelector('#cl-terminal-log');
565
+ if (logEl) {
566
+ logEl.innerHTML = '';
567
+ }
568
+ }
569
+ }
570
+
571
+ getHistory() {
572
+ return [...this.history];
573
+ }
574
+
575
+ readLine(promptText = '') {
576
+ const prevPrompt = this.promptOverride;
577
+ if (promptText) {
578
+ this.setPrompt(promptText);
579
+ }
580
+ return new Promise((resolve) => {
581
+ this._readLineQueue.push((line) => {
582
+ this.promptOverride = prevPrompt;
583
+ this.updateActiveLine();
584
+ resolve(line);
585
+ });
586
+ });
587
+ }
588
+
589
+ focus() {
590
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
591
+ const input = this.container.querySelector('#cl-repl-input');
592
+ if (input && typeof input.focus === 'function') {
593
+ try { input.focus(); } catch (_) {}
594
+ }
595
+ }
596
+
597
+ mount(container) {
598
+ if (typeof container === 'string' && typeof document !== 'undefined') {
599
+ container = document.querySelector(container);
600
+ }
601
+ this.container = container || null;
602
+ if (!this.container || typeof this.container.querySelector !== 'function') {
603
+ this._mounted = false;
604
+ return;
605
+ }
606
+ this._mounted = true;
607
+ this.render();
608
+ }
609
+
610
+ _cleanupListeners() {
611
+ if (!Array.isArray(this._listeners)) {
612
+ this._listeners = [];
613
+ return;
614
+ }
615
+ for (const entry of this._listeners) {
616
+ if (typeof entry === 'function') {
617
+ try { entry(); } catch (_) {}
618
+ } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
619
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
620
+ }
621
+ }
622
+ this._listeners = [];
623
+ }
624
+
625
+ destroy() {
626
+ this._cleanupListeners();
627
+ this._mounted = false;
628
+ }
629
+
630
+ _addListener(target, type, handler) {
631
+ if (target && typeof target.addEventListener === 'function') {
632
+ target.addEventListener(type, handler);
633
+ this._listeners.push({ target, type, handler });
634
+ }
635
+ }
636
+
637
+ _bindEvents() {
638
+ this._cleanupListeners();
639
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
640
+ const termSurface = this.container.querySelector('#cl-terminal-surface') || this.container;
641
+ const input = this.container.querySelector('#cl-repl-input');
642
+ const form = this.container.querySelector('#cl-repl-form');
643
+
644
+ if (termSurface) {
645
+ this._addListener(termSurface, 'click', (e) => {
646
+ if (e && e.target === input) return;
647
+ const hasSelection = typeof window !== 'undefined' && window.getSelection && String(window.getSelection());
648
+ if (!hasSelection) this.focus();
649
+ });
650
+ }
651
+
652
+ if (input) {
653
+ this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
654
+ this._addListener(input, 'input', () => {
655
+ if (input.value !== this.buffer) {
656
+ this.buffer = input.value;
657
+ this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
658
+ this.updateActiveLine();
659
+ }
660
+ });
661
+ }
662
+
663
+ if (form) {
664
+ this._addListener(form, 'submit', (e) => {
665
+ if (e && typeof e.preventDefault === 'function') e.preventDefault();
666
+ this.submitLine();
667
+ });
668
+ }
669
+ }
670
+
671
+ _findReverseSearchMatch(query, startIdx) {
672
+ if (!query || !this.history.length) return -1;
673
+ const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
674
+ for (let i = from; i >= 0; i--) {
675
+ if (this.history[i] && this.history[i].includes(query)) {
676
+ return i;
677
+ }
678
+ }
679
+ return -1;
680
+ }
681
+
682
+ handleKeyDown(e) {
683
+ if (!e) return;
684
+ if (this.onKey) {
685
+ try {
686
+ const res = this.onKey(e);
687
+ if (res === false) return;
688
+ } catch (_) {}
689
+ }
690
+
691
+ const key = e.key;
692
+ const isCtrl = Boolean(e.ctrlKey || e.metaKey);
693
+
694
+ if (isCtrl && (key === 'r' || key === 'R')) {
695
+ if (e.preventDefault) e.preventDefault();
696
+ if (!this.searchMode) {
697
+ this.searchMode = true;
698
+ this.searchQuery = '';
699
+ this.searchMatchIdx = -1;
700
+ } else if (this.searchQuery) {
701
+ const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
702
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
703
+ if (matchIdx !== -1) {
704
+ this.searchMatchIdx = matchIdx;
705
+ this.buffer = this.history[matchIdx];
706
+ this.cursor = this.buffer.length;
707
+ }
708
+ }
709
+ this.updateActiveLine();
710
+ return;
711
+ }
712
+
713
+ if (this.searchMode) {
714
+ if (key === 'Escape' || (isCtrl && (key === 'g' || key === 'G'))) {
715
+ if (e.preventDefault) e.preventDefault();
716
+ this.searchMode = false;
717
+ this.searchQuery = '';
718
+ this.searchMatchIdx = -1;
719
+ this.updateActiveLine();
720
+ return;
721
+ }
722
+ if (key === 'Backspace') {
723
+ if (e.preventDefault) e.preventDefault();
724
+ this.searchQuery = this.searchQuery.slice(0, -1);
725
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
726
+ this.searchMatchIdx = matchIdx;
727
+ if (matchIdx !== -1) {
728
+ this.buffer = this.history[matchIdx];
729
+ this.cursor = this.buffer.length;
730
+ }
731
+ this.updateActiveLine();
732
+ return;
733
+ }
734
+ if (key === 'Enter') {
735
+ if (e.preventDefault) e.preventDefault();
736
+ this.searchMode = false;
737
+ this.searchQuery = '';
738
+ this.searchMatchIdx = -1;
739
+ this.submitLine();
740
+ return;
741
+ }
742
+ if (key && key.length === 1 && !isCtrl && !e.altKey) {
743
+ if (e.preventDefault) e.preventDefault();
744
+ this.searchQuery += key;
745
+ const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
746
+ this.searchMatchIdx = matchIdx;
747
+ if (matchIdx !== -1) {
748
+ this.buffer = this.history[matchIdx];
749
+ this.cursor = this.buffer.length;
750
+ }
751
+ this.updateActiveLine();
752
+ return;
753
+ }
754
+ this.searchMode = false;
755
+ this.searchQuery = '';
756
+ this.searchMatchIdx = -1;
757
+ }
758
+
759
+ if (key === 'ArrowLeft') {
760
+ if (e.preventDefault) e.preventDefault();
761
+ if (this.cursor > 0) {
762
+ this.cursor--;
763
+ this.updateActiveLine();
764
+ }
765
+ return;
766
+ }
767
+
768
+ if (key === 'ArrowRight') {
769
+ if (e.preventDefault) e.preventDefault();
770
+ if (this.cursor < this.buffer.length) {
771
+ this.cursor++;
772
+ this.updateActiveLine();
773
+ }
774
+ return;
775
+ }
776
+
777
+ if (key === 'Home' || (isCtrl && (key === 'a' || key === 'A'))) {
778
+ if (e.preventDefault) e.preventDefault();
779
+ this.cursor = 0;
780
+ this.updateActiveLine();
781
+ return;
782
+ }
783
+
784
+ if (key === 'End' || (isCtrl && (key === 'e' || key === 'E'))) {
785
+ if (e.preventDefault) e.preventDefault();
786
+ this.cursor = this.buffer.length;
787
+ this.updateActiveLine();
788
+ return;
789
+ }
790
+
791
+ if (isCtrl && (key === 'u' || key === 'U')) {
792
+ if (e.preventDefault) e.preventDefault();
793
+ this.buffer = this.buffer.slice(this.cursor);
794
+ this.cursor = 0;
795
+ this.updateActiveLine();
796
+ return;
797
+ }
798
+
799
+ if (isCtrl && (key === 'k' || key === 'K')) {
800
+ if (e.preventDefault) e.preventDefault();
801
+ this.buffer = this.buffer.slice(0, this.cursor);
802
+ this.updateActiveLine();
803
+ return;
804
+ }
805
+
806
+ if (key === 'Backspace') {
807
+ if (e.preventDefault) e.preventDefault();
808
+ if (this.cursor > 0) {
809
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
810
+ this.cursor--;
811
+ this.updateActiveLine();
812
+ }
813
+ return;
814
+ }
815
+
816
+ if (key === 'Delete') {
817
+ if (e.preventDefault) e.preventDefault();
818
+ if (this.cursor < this.buffer.length) {
819
+ this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
820
+ this.updateActiveLine();
821
+ }
822
+ return;
823
+ }
824
+
825
+ if (isCtrl && (key === 'l' || key === 'L')) {
826
+ if (e.preventDefault) e.preventDefault();
827
+ this.clear();
828
+ return;
829
+ }
830
+
831
+ if (isCtrl && (key === 'c' || key === 'C')) {
832
+ if (e.preventDefault) e.preventDefault();
833
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
834
+ this.buffer = '';
835
+ this.cursor = 0;
836
+ this.historyIdx = -1;
837
+ if (this.replMode) {
838
+ this.replMode = false;
839
+ }
840
+ if (this.onInterrupt) {
841
+ try { this.onInterrupt(); } catch (_) {}
842
+ }
843
+ this.render();
844
+ return;
845
+ }
846
+
847
+ if (isCtrl && (key === 'd' || key === 'D')) {
848
+ if (this.buffer === '') {
849
+ if (e.preventDefault) e.preventDefault();
850
+ if (this.replMode) {
851
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
852
+ this.replMode = false;
853
+ this.render();
854
+ return;
855
+ }
856
+ }
857
+ }
858
+
859
+ if (key === 'ArrowUp') {
860
+ if (e.preventDefault) e.preventDefault();
861
+ if (!this.history.length) return;
862
+ if (this.historyIdx === -1) {
863
+ this.savedBuffer = this.buffer;
864
+ this.historyIdx = this.history.length - 1;
865
+ } else if (this.historyIdx > 0) {
866
+ this.historyIdx--;
867
+ }
868
+ this.buffer = this.history[this.historyIdx] || '';
869
+ this.cursor = this.buffer.length;
870
+ this.updateActiveLine();
871
+ return;
872
+ }
873
+
874
+ if (key === 'ArrowDown') {
875
+ if (e.preventDefault) e.preventDefault();
876
+ if (this.historyIdx !== -1) {
877
+ if (this.historyIdx < this.history.length - 1) {
878
+ this.historyIdx++;
879
+ this.buffer = this.history[this.historyIdx] || '';
880
+ } else {
881
+ this.historyIdx = -1;
882
+ this.buffer = this.savedBuffer || '';
883
+ }
884
+ this.cursor = this.buffer.length;
885
+ this.updateActiveLine();
886
+ }
887
+ return;
888
+ }
889
+
890
+ if (key === 'Tab') {
891
+ if (e.preventDefault) e.preventDefault();
892
+ this.autoComplete();
893
+ return;
894
+ }
895
+
896
+ if (key === 'Enter') {
897
+ if (e.preventDefault) e.preventDefault();
898
+ this.submitLine();
899
+ return;
900
+ }
901
+
902
+ // Printable character
903
+ if (key && key.length === 1 && !isCtrl && !e.altKey) {
904
+ if (e.preventDefault) e.preventDefault();
905
+ this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
906
+ this.cursor++;
907
+ this.updateActiveLine();
908
+ }
909
+ }
910
+
911
+ autoComplete() {
912
+ if (!this.getCompletions) return;
913
+ const res = this.getCompletions(this.buffer, this.cursor);
914
+ if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
915
+
916
+ const matches = res.matches;
917
+ if (matches.length === 1) {
918
+ const match = matches[0];
919
+ const isDir = match.endsWith('/');
920
+ const appendChar = isDir ? '' : ' ';
921
+ const before = this.buffer.slice(0, res.tokenStart);
922
+ const after = this.buffer.slice(this.cursor);
923
+ this.buffer = before + match + appendChar + after;
924
+ this.cursor = before.length + match.length + appendChar.length;
925
+ this.updateActiveLine();
926
+ } else {
927
+ // Find longest common prefix
928
+ let lcp = matches[0];
929
+ for (let i = 1; i < matches.length; i++) {
930
+ let j = 0;
931
+ while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
932
+ j++;
933
+ }
934
+ lcp = lcp.slice(0, j);
935
+ }
936
+
937
+ if (lcp.length > res.token.length) {
938
+ const before = this.buffer.slice(0, res.tokenStart);
939
+ const after = this.buffer.slice(this.cursor);
940
+ this.buffer = before + lcp + after;
941
+ this.cursor = before.length + lcp.length;
942
+ }
943
+
944
+ // Print candidate matches
945
+ this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
946
+ this.logs.push({ type: 'stdout', text: matches.join(' ') });
947
+ this.render();
948
+ }
949
+ }
950
+
951
+ submitLine() {
952
+ const line = this.buffer;
953
+ this.buffer = '';
954
+ this.cursor = 0;
955
+ this.historyIdx = -1;
956
+ this.searchMode = false;
957
+ this.searchQuery = '';
958
+ this.searchMatchIdx = -1;
959
+
960
+ if (line.trim()) {
961
+ if (this.history[this.history.length - 1] !== line.trim()) {
962
+ this.history.push(line.trim());
963
+ }
964
+ }
965
+
966
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
967
+ const resolver = this._readLineQueue.shift();
968
+ this.updateActiveLine();
969
+ resolver(line);
970
+ return;
971
+ }
972
+
973
+ this.updateActiveLine();
974
+ if (this.onCommand) {
975
+ this.onCommand(line);
976
+ }
977
+ }
978
+
979
+ updateActiveLine() {
980
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
981
+ const input = this.container.querySelector('#cl-repl-input');
982
+ if (input && input.value !== this.buffer) {
983
+ input.value = this.buffer;
984
+ }
985
+ const lineEl = this.container.querySelector('#cl-pty-active-line');
986
+ if (!lineEl) return;
987
+
988
+ const prompt = this.searchMode
989
+ ? `(reverse-i-search)\`${this.searchQuery}\`: `
990
+ : this.getPrompt();
991
+ const before = this.buffer.slice(0, this.cursor);
992
+ const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
993
+ const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
994
+
995
+ lineEl.innerHTML = `<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>`;
996
+ }
997
+
998
+ render() {
999
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
1000
+ const prevInput = this.container.querySelector('#cl-repl-input');
1001
+ const hadFocus = Boolean(
1002
+ prevInput &&
1003
+ typeof document !== 'undefined' &&
1004
+ document.activeElement === prevInput
1005
+ );
1006
+
1007
+ const logsHtml = this.logs
1008
+ .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
1009
+ .join('');
1010
+
1011
+ const prompt = this.searchMode
1012
+ ? `(reverse-i-search)\`${this.searchQuery}\`: `
1013
+ : this.getPrompt();
1014
+ const before = this.buffer.slice(0, this.cursor);
1015
+ const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1016
+ const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1017
+
1018
+ this.container.innerHTML = `
1019
+ <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1020
+ <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1021
+ <div class="codelab-pty__active-line" id="cl-pty-active-line">
1022
+ <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>
1023
+ </div>
1024
+ <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1025
+ <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
1026
+ </form>
1027
+ </div>
1028
+ `;
1029
+
1030
+ this._scrollToBottom();
1031
+
1032
+ this._bindEvents();
1033
+
1034
+ if (hadFocus) {
1035
+ const nextInput = this.container.querySelector('#cl-repl-input');
1036
+ if (nextInput && typeof nextInput.focus === 'function') {
1037
+ try {
1038
+ nextInput.focus();
1039
+ if (typeof nextInput.setSelectionRange === 'function') {
1040
+ nextInput.setSelectionRange(this.cursor, this.cursor);
1041
+ }
1042
+ } catch (_) {}
1043
+ }
1044
+ }
1045
+ }
1046
+ }
1047
+
1048
+ function createTerminal(container, options = {}) {
1049
+ return new PTYTerminalEngine(container, options);
1050
+ }
1051
+
1052
+ const createPTYTerminalEngine = createTerminal;
1053
+
1054
+ return {
1055
+ PTYTerminalEngine,
1056
+ createPTYTerminalEngine,
1057
+ createTerminal,
1058
+ ansiToHtml,
1059
+ parseAnsiToHtml,
1060
+ escapeHtml,
1061
+ ANSI_CODE_MAP,
1062
+ resolveAnsiControlCodes
1063
+ };
1064
+ });
1065
+
1066
+ })();
1067
+
1068
+ const CodeLabTerminal = _root.CodeLabTerminal;
1069
+ const PTYTerminalEngine = CodeLabTerminal.PTYTerminalEngine;
1070
+ const createTerminal = CodeLabTerminal.createTerminal;
1071
+ const createPTYTerminalEngine = CodeLabTerminal.createPTYTerminalEngine;
1072
+ const ansiToHtml = CodeLabTerminal.ansiToHtml;
1073
+ const parseAnsiToHtml = CodeLabTerminal.parseAnsiToHtml;
1074
+
1075
+ export {
1076
+ CodeLabTerminal,
1077
+ PTYTerminalEngine,
1078
+ createTerminal,
1079
+ createPTYTerminalEngine,
1080
+ ansiToHtml,
1081
+ parseAnsiToHtml
1082
+ };
1083
+ export default CodeLabTerminal;