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