@innovatorved/code-lab 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +3 -3
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -7273
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4669 -74678
  9. package/dist/code-lab.js +4655 -74665
  10. package/dist/code-lab.umd.js +4655 -74665
  11. package/dist/extensions/cpp.d.ts +2 -2
  12. package/dist/extensions/cpp.esm.js +1788 -14707
  13. package/dist/extensions/cpp.js +1788 -14707
  14. package/dist/extensions/guided-lab.esm.js +2938 -16127
  15. package/dist/extensions/guided-lab.js +2938 -16127
  16. package/dist/extensions/python.d.ts +2 -2
  17. package/dist/extensions/python.esm.js +1769 -14701
  18. package/dist/extensions/python.js +1769 -14701
  19. package/dist/index.d.ts +1 -1
  20. package/dist/preview-sw.js +4 -188
  21. package/dist/runtime.esm.js +109 -10284
  22. package/dist/runtime.js +107 -10284
  23. package/dist/schemas.d.ts +2 -2
  24. package/dist/schemas.esm.js +2938 -16127
  25. package/dist/schemas.js +2941 -16130
  26. package/dist/scm.d.ts +221 -20
  27. package/dist/shell.esm.js +811 -10002
  28. package/dist/shell.js +811 -10002
  29. package/dist/storage.d.ts +9 -0
  30. package/dist/terminal.esm.js +20 -1347
  31. package/dist/terminal.js +20 -1347
  32. package/dist/workbench/command-palette.d.ts +16 -1
  33. package/dist/workbench/diff-editor.d.ts +27 -1
  34. package/dist/workbench/icons.d.ts +6 -2
  35. package/dist/workbench/index.d.ts +32 -0
  36. package/dist/workbench/intellisense.d.ts +194 -0
  37. package/dist/workbench/xterm-adapter.d.ts +122 -0
  38. package/package.json +7 -1
  39. package/packages/commands/package.json +1 -1
  40. package/packages/core/package.json +1 -1
  41. package/packages/editor/package.json +1 -1
  42. package/packages/fs/package.json +1 -1
  43. package/packages/preview/package.json +1 -1
  44. package/packages/runtime/package.json +1 -1
  45. package/packages/settings/package.json +1 -1
  46. package/packages/sql/package.json +1 -1
  47. package/packages/terminal/package.json +1 -1
  48. package/packages/ui/package.json +1 -1
  49. package/packages/ui/src/settings-dialog.ts +36 -24
  50. package/packages/ui/src/themes.ts +89 -23
  51. package/src/code-lab.css +1345 -481
  52. package/src/extensions/cpp.ts +304 -38
  53. package/src/extensions/python.ts +342 -43
  54. package/src/index.ts +1 -1
  55. package/src/runtime.ts +272 -43
  56. package/src/schemas.ts +2 -2
  57. package/src/scm.ts +1467 -92
  58. package/src/shell.ts +1075 -93
  59. package/src/storage.ts +66 -3
  60. package/src/terminal.ts +148 -12
  61. package/src/workbench/command-palette.ts +289 -48
  62. package/src/workbench/diff-editor.ts +240 -78
  63. package/src/workbench/icons.ts +250 -53
  64. package/src/workbench/index.ts +7 -1
  65. package/src/workbench/intellisense.ts +1859 -0
  66. package/src/workbench/xterm-adapter.ts +1566 -0
  67. package/src/workbench.ts +1605 -236
@@ -0,0 +1,1566 @@
1
+ /**
2
+ * @innovatorved/code-lab — Browser-Native xterm.js PTY Adapter
3
+ *
4
+ * Mounts a real `@xterm/xterm` terminal instance (with `@xterm/addon-fit`,
5
+ * `@xterm/addon-web-links`, and clickable `file:line:col` diagnostic navigation)
6
+ * inside `#cl-terminal-surface`, while maintaining a synchronized hidden mirror
7
+ * (`#cl-terminal-log`, `#cl-pty-active-line`, `#cl-repl-input`) so programmatic
8
+ * consumers and E2E harnesses work seamlessly alongside interactive VT100 I/O.
9
+ */
10
+
11
+ import type { Terminal, ITheme } from '@xterm/xterm';
12
+ import type { FitAddon } from '@xterm/addon-fit';
13
+ import type { WebLinksAddon } from '@xterm/addon-web-links';
14
+
15
+ interface XtermRuntimeClasses {
16
+ Terminal: typeof Terminal;
17
+ FitAddon: typeof FitAddon;
18
+ WebLinksAddon: typeof WebLinksAddon;
19
+ }
20
+
21
+ let _cachedXtermClasses: XtermRuntimeClasses | null = null;
22
+
23
+ function getXtermRuntimeClasses(): XtermRuntimeClasses {
24
+ if (!_cachedXtermClasses) {
25
+ // Lazy-require ESM builds so esbuild wraps xterm in a deferred __esm/__commonJS factory
26
+ // (keeping Node/Bun headless imports free of xterm's MessageChannel queue and ~38 KB smaller gzipped)
27
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
28
+ const xtermMod = require('@xterm/xterm/lib/xterm.mjs') as { Terminal: typeof Terminal };
29
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
30
+ const fitMod = require('@xterm/addon-fit/lib/addon-fit.mjs') as { FitAddon: typeof FitAddon };
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ const linksMod = require('@xterm/addon-web-links/lib/addon-web-links.mjs') as {
33
+ WebLinksAddon: typeof WebLinksAddon;
34
+ };
35
+ _cachedXtermClasses = {
36
+ Terminal: xtermMod.Terminal,
37
+ FitAddon: fitMod.FitAddon,
38
+ WebLinksAddon: linksMod.WebLinksAddon
39
+ };
40
+ }
41
+ return _cachedXtermClasses;
42
+ }
43
+
44
+ interface SharedTerminalHelpers {
45
+ ansiToHtml?: (text: string) => string;
46
+ escapeHtml?: (str: string) => string;
47
+ resolveAnsiControlCodes?: (text: string) => string;
48
+ }
49
+
50
+ function getTerminalHelpers(): SharedTerminalHelpers {
51
+ const g = globalThis as unknown as { CodeLabTerminal?: SharedTerminalHelpers };
52
+ return g.CodeLabTerminal || {};
53
+ }
54
+
55
+ function escapeHtml(str: string): string {
56
+ const fn = getTerminalHelpers().escapeHtml;
57
+ if (typeof fn === 'function') return fn(str);
58
+ return String(str == null ? '' : str)
59
+ .replace(/&/g, '&')
60
+ .replace(/</g, '&lt;')
61
+ .replace(/>/g, '&gt;')
62
+ .replace(/"/g, '&quot;');
63
+ }
64
+
65
+ function ansiToHtml(text: string): string {
66
+ const fn = getTerminalHelpers().ansiToHtml;
67
+ if (typeof fn === 'function') return fn(text);
68
+ return escapeHtml(String(text == null ? '' : text).replace(/\x1b\[[0-9;?]*[A-Za-z]/g, ''));
69
+ }
70
+
71
+ function resolveAnsiControlCodes(text: string): string {
72
+ const fn = getTerminalHelpers().resolveAnsiControlCodes;
73
+ if (typeof fn === 'function') return fn(text);
74
+ return String(text == null ? '' : text);
75
+ }
76
+
77
+ export interface XtermAdapterOptions {
78
+ cwd?: string;
79
+ logs?: Array<{ type: string; text: string }>;
80
+ history?: string[];
81
+ theme?: 'dark' | 'light' | 'hc' | 'high-contrast';
82
+ fontSize?: number;
83
+ fontFamily?: string;
84
+ onCommand?: (line: string) => Promise<unknown> | unknown;
85
+ getCompletions?: (
86
+ buffer: string,
87
+ cursor: number
88
+ ) => { matches: string[]; token: string; tokenStart: number } | null;
89
+ onInterrupt?: () => void;
90
+ onResize?: (cols: number, rows: number) => void;
91
+ onOpenFileLink?: (filePath: string, line: number, column: number) => void;
92
+ onOpenUrl?: (url: string) => boolean | void;
93
+ maxScrollback?: number;
94
+ initialLogs?: Array<{ type: string; text: string }>;
95
+ }
96
+
97
+ const VALID_LOG_TYPES = new Set([
98
+ 'stdout',
99
+ 'stderr',
100
+ 'system',
101
+ 'info',
102
+ 'warn',
103
+ 'error',
104
+ 'success'
105
+ ]);
106
+
107
+ function sanitizeLogType(type?: string): string {
108
+ const t = String(type || 'stdout').trim();
109
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
110
+ }
111
+
112
+ export function getXtermTheme(mode: string = 'dark'): ITheme {
113
+ if (mode === 'light') {
114
+ return {
115
+ background: '#f8f8f8',
116
+ foreground: '#3b3b3b',
117
+ cursor: '#3b3b3b',
118
+ cursorAccent: '#f8f8f8',
119
+ selectionBackground: 'rgba(0, 95, 184, 0.24)',
120
+ black: '#000000',
121
+ red: '#cd3131',
122
+ green: '#008000',
123
+ yellow: '#795e26',
124
+ blue: '#0451a5',
125
+ magenta: '#bc05bc',
126
+ cyan: '#0598bc',
127
+ white: '#555555',
128
+ brightBlack: '#666666',
129
+ brightRed: '#cd3131',
130
+ brightGreen: '#14ce14',
131
+ brightYellow: '#b5ba00',
132
+ brightBlue: '#0451a5',
133
+ brightMagenta: '#bc05bc',
134
+ brightCyan: '#0598bc',
135
+ brightWhite: '#3b3b3b'
136
+ };
137
+ }
138
+ if (mode === 'hc' || mode === 'high-contrast') {
139
+ return {
140
+ background: '#000000',
141
+ foreground: '#ffffff',
142
+ cursor: '#ffffff',
143
+ cursorAccent: '#000000',
144
+ selectionBackground: 'rgba(255, 255, 255, 0.35)',
145
+ black: '#000000',
146
+ red: '#f48771',
147
+ green: '#89d185',
148
+ yellow: '#ffd370',
149
+ blue: '#75beff',
150
+ magenta: '#b180d7',
151
+ cyan: '#4ec9b0',
152
+ white: '#ffffff',
153
+ brightBlack: '#808080',
154
+ brightRed: '#f48771',
155
+ brightGreen: '#89d185',
156
+ brightYellow: '#ffd370',
157
+ brightBlue: '#75beff',
158
+ brightMagenta: '#b180d7',
159
+ brightCyan: '#4ec9b0',
160
+ brightWhite: '#ffffff'
161
+ };
162
+ }
163
+ return {
164
+ background: '#181818',
165
+ foreground: '#cccccc',
166
+ cursor: '#cccccc',
167
+ cursorAccent: '#181818',
168
+ selectionBackground: 'rgba(38, 79, 120, 0.55)',
169
+ black: '#000000',
170
+ red: '#cd3131',
171
+ green: '#0dbc79',
172
+ yellow: '#e5e510',
173
+ blue: '#2472c8',
174
+ magenta: '#bc3fbc',
175
+ cyan: '#11a8cd',
176
+ white: '#e5e5e5',
177
+ brightBlack: '#666666',
178
+ brightRed: '#f14c4c',
179
+ brightGreen: '#23d18b',
180
+ brightYellow: '#f5f543',
181
+ brightBlue: '#3b8eea',
182
+ brightMagenta: '#d670d6',
183
+ brightCyan: '#29b8db',
184
+ brightWhite: '#ffffff'
185
+ };
186
+ }
187
+
188
+ export function canUseXtermInEnvironment(container?: unknown): boolean {
189
+ if (typeof window === 'undefined' || typeof document === 'undefined') return false;
190
+ if (typeof HTMLCanvasElement === 'undefined') return false;
191
+ if (container !== undefined && (!container || typeof (container as Element).appendChild !== 'function')) {
192
+ return false;
193
+ }
194
+ // Detect lightweight Node mock-DOMs that do not implement real Element layout APIs
195
+ const probe = document.createElement('div');
196
+ if (typeof probe.getBoundingClientRect !== 'function' || typeof window.getComputedStyle !== 'function') {
197
+ return false;
198
+ }
199
+ if (typeof navigator !== 'undefined' && /jsdom/i.test(navigator.userAgent || '')) {
200
+ return false;
201
+ }
202
+ return true;
203
+ }
204
+
205
+ interface ReadLineQueueItem {
206
+ promptText: string;
207
+ prevPrompt: string | null;
208
+ _activated: boolean;
209
+ cleanup: (() => void) | null;
210
+ resolve: (value: string | null) => void;
211
+ }
212
+
213
+ const FILE_LINK_RE =
214
+ /(?:\/workspace\/|\.\/)?([A-Za-z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|cpp|cc|cxx|h|hpp|sql|json|css|html|md))(?::(\d+)(?::(\d+))?|\((\d+),(\d+)\))/g;
215
+
216
+ export class XtermTerminalEngine {
217
+ public container: HTMLElement | null;
218
+ public options: XtermAdapterOptions;
219
+ public logs: Array<{ type: string; text: string }>;
220
+ public cwd: string;
221
+ public replMode: boolean;
222
+ public promptOverride: string | null;
223
+ public history: string[];
224
+ public historyIdx: number;
225
+ public savedBuffer: string;
226
+ public buffer: string;
227
+ public cursor: number;
228
+ public searchMode: boolean;
229
+ public searchQuery: string;
230
+ public searchMatchIdx: number;
231
+ public isBusy: boolean;
232
+ public maxScrollback: number;
233
+ public maxHistory: number;
234
+ public onCommand: ((line: string) => Promise<unknown> | unknown) | null;
235
+ public getCompletions: XtermAdapterOptions['getCompletions'] | null;
236
+ public onInterrupt: (() => void) | null;
237
+
238
+ public xterm: Terminal | null = null;
239
+ public fitAddon: FitAddon | null = null;
240
+
241
+ private _readLineQueue: ReadLineQueueItem[] = [];
242
+ private _themeMode: string;
243
+ private _resizeObserver: ResizeObserver | null = null;
244
+ private _fitRaf = 0;
245
+ private _disposed = false;
246
+ private _promptVisibleInXterm = false;
247
+ private _pendingMirrorLine = '';
248
+ private _activeMirrorEl: HTMLElement | null = null;
249
+ private _domListeners: Array<{ target: EventTarget; type: string; fn: EventListener }> = [];
250
+
251
+ constructor(container: HTMLElement | null, options: XtermAdapterOptions = {}) {
252
+ this.container = container || null;
253
+ this.options = options || {};
254
+ this.maxScrollback =
255
+ typeof options.maxScrollback === 'number' && Number.isFinite(options.maxScrollback) && options.maxScrollback > 0
256
+ ? Math.floor(options.maxScrollback)
257
+ : 3000;
258
+ this.maxHistory = 1000;
259
+ const seedLogs = Array.isArray(options.initialLogs)
260
+ ? options.initialLogs
261
+ : Array.isArray(options.logs)
262
+ ? options.logs
263
+ : [];
264
+ this.logs = [...seedLogs];
265
+ if (this.logs.length > this.maxScrollback) {
266
+ this.logs.splice(0, this.logs.length - this.maxScrollback);
267
+ }
268
+ this.cwd = options.cwd || '/workspace';
269
+ this.replMode = false;
270
+ this.promptOverride = null;
271
+ this.history = Array.isArray(options.history) ? options.history : [];
272
+ this.historyIdx = -1;
273
+ this.savedBuffer = '';
274
+ this.buffer = '';
275
+ this.cursor = 0;
276
+ this.searchMode = false;
277
+ this.searchQuery = '';
278
+ this.searchMatchIdx = -1;
279
+ this.isBusy = false;
280
+ this._themeMode = options.theme || 'dark';
281
+ this.onCommand = typeof options.onCommand === 'function' ? options.onCommand : null;
282
+ this.getCompletions = typeof options.getCompletions === 'function' ? options.getCompletions : null;
283
+ this.onInterrupt = typeof options.onInterrupt === 'function' ? options.onInterrupt : null;
284
+
285
+ if (this.container) {
286
+ this.mount(this.container);
287
+ }
288
+ }
289
+
290
+ public getPrompt(): string {
291
+ if (this.promptOverride !== null) return this.promptOverride;
292
+ if (this.replMode) return '> ';
293
+ const cwd = this.cwd || '/workspace';
294
+ return `codelab:${cwd}$ `;
295
+ }
296
+
297
+ private _getColoredPrompt(): string {
298
+ if (this.searchMode) {
299
+ return `\x1b[36m(reverse-i-search)\x1b[0m\`${this.searchQuery}': `;
300
+ }
301
+ if (this.promptOverride !== null) {
302
+ return this.promptOverride;
303
+ }
304
+ if (this.replMode) {
305
+ return '\x1b[1;32m>\x1b[0m ';
306
+ }
307
+ const rawCwd = this.cwd || '/workspace';
308
+ const displayCwd = rawCwd === '/home/codelab'
309
+ ? '~'
310
+ : rawCwd.startsWith('/home/codelab/')
311
+ ? '~' + rawCwd.slice('/home/codelab'.length)
312
+ : rawCwd;
313
+ return `\x1b[1;32mcodelab\x1b[0m:\x1b[1;34m${displayCwd}\x1b[0m$ `;
314
+ }
315
+
316
+ public setPrompt(p: string | null): void {
317
+ this.promptOverride = p;
318
+ this.updateActiveLine();
319
+ }
320
+
321
+ public setCwd(cwd: string): void {
322
+ this.cwd = cwd || '/workspace';
323
+ this.updateActiveLine();
324
+ }
325
+
326
+ public setReplMode(enabled: boolean): void {
327
+ this.replMode = Boolean(enabled);
328
+ this.updateActiveLine();
329
+ }
330
+
331
+ public setTheme(mode: 'dark' | 'light' | 'hc' | 'high-contrast'): void {
332
+ this._themeMode = mode;
333
+ if (this.xterm) {
334
+ this.xterm.options.theme = getXtermTheme(mode);
335
+ }
336
+ }
337
+
338
+ public setFontSize(fontSize: number): void {
339
+ if (Number.isFinite(fontSize) && fontSize >= 10 && fontSize <= 28) {
340
+ this.options.fontSize = fontSize;
341
+ const surface = this.container?.querySelector('#cl-terminal-surface') as HTMLElement | null;
342
+ if (surface) surface.style.fontSize = `${fontSize}px`;
343
+ if (this.xterm) {
344
+ this.xterm.options.fontSize = fontSize;
345
+ this.fit();
346
+ }
347
+ }
348
+ }
349
+
350
+ public setMaxScrollback(max: number): void {
351
+ const clamped = Number.isFinite(max) && max > 0 ? Math.floor(max) : 3000;
352
+ this.maxScrollback = clamped;
353
+ this.options.maxScrollback = clamped;
354
+ if (this.xterm) {
355
+ this.xterm.options.scrollback = clamped;
356
+ }
357
+ if (this.logs.length > clamped) {
358
+ this.logs.splice(0, this.logs.length - clamped);
359
+ }
360
+ const logEl = this.container?.querySelector('#cl-terminal-log');
361
+ if (logEl) {
362
+ while (logEl.children.length > clamped && logEl.firstChild) {
363
+ logEl.removeChild(logEl.firstChild);
364
+ }
365
+ }
366
+ }
367
+
368
+ public syncDomMirrorWithLogs(externalLogs?: Array<{ type: string; text: string }>): void {
369
+ if (Array.isArray(externalLogs) && externalLogs !== this.logs) {
370
+ this.logs.splice(0, this.logs.length, ...externalLogs);
371
+ }
372
+ if (this.logs.length > this.maxScrollback) {
373
+ this.logs.splice(0, this.logs.length - this.maxScrollback);
374
+ }
375
+ const logEl = this.container?.querySelector('#cl-terminal-log');
376
+ if (!logEl) return;
377
+ if (logEl.children.length !== this.logs.length) {
378
+ const prevCount = logEl.children.length;
379
+ logEl.innerHTML = this.logs
380
+ .map((item) => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
381
+ .join('');
382
+ if (this.xterm) {
383
+ if (this.logs.length === 0) {
384
+ this.xterm.reset();
385
+ this._promptVisibleInXterm = false;
386
+ this.updateActiveLine();
387
+ } else if (this.logs.length > prevCount) {
388
+ this._eraseXtermPromptIfVisible();
389
+ for (let i = prevCount; i < this.logs.length; i++) {
390
+ const txt = String(this.logs[i]?.text || '');
391
+ if (!txt) continue;
392
+ const withNl = txt.endsWith('\n') ? txt : txt + '\n';
393
+ this.xterm.write(this._toCrLf(withNl));
394
+ }
395
+ this._redrawXtermPromptLine();
396
+ }
397
+ }
398
+ }
399
+ }
400
+
401
+ public isCommandRunning(): boolean {
402
+ return Boolean(this.isBusy && this._readLineQueue.length === 0);
403
+ }
404
+
405
+ public fit(): void {
406
+ if (this._disposed || !this.fitAddon || !this.xterm || !this.container) return;
407
+ const rect = this.container.getBoundingClientRect();
408
+ if (rect.width < 24 || rect.height < 24) return;
409
+ try {
410
+ this.fitAddon.fit();
411
+ if (typeof this.options.onResize === 'function') {
412
+ this.options.onResize(this.xterm.cols, this.xterm.rows);
413
+ }
414
+ } catch (_err) {
415
+ void _err;
416
+ }
417
+ }
418
+
419
+ private _scheduleFit(): void {
420
+ if (this._disposed || typeof requestAnimationFrame !== 'function') return;
421
+ if (this._fitRaf) cancelAnimationFrame(this._fitRaf);
422
+ this._fitRaf = requestAnimationFrame(() => {
423
+ this._fitRaf = 0;
424
+ this.fit();
425
+ });
426
+ }
427
+
428
+ private _toCrLf(raw: string): string {
429
+ return raw.replace(/\r?\n/g, '\r\n');
430
+ }
431
+
432
+ private _eraseXtermPromptIfVisible(): void {
433
+ if (this.xterm && this._promptVisibleInXterm) {
434
+ this.xterm.write('\r\x1b[2K');
435
+ this._promptVisibleInXterm = false;
436
+ }
437
+ }
438
+
439
+ private _redrawXtermPromptLine(): void {
440
+ if (!this.xterm) return;
441
+ if (this.isCommandRunning()) {
442
+ this._promptVisibleInXterm = false;
443
+ return;
444
+ }
445
+ const coloredPrompt = this._getColoredPrompt();
446
+ const afterLen = Math.max(0, this.buffer.length - this.cursor);
447
+ const moveBack = afterLen > 0 ? `\x1b[${afterLen}D` : '';
448
+ this.xterm.write(`\r\x1b[2K${coloredPrompt}${this.buffer}${moveBack}`);
449
+ this._promptVisibleInXterm = true;
450
+ }
451
+
452
+ private _pushMirrorLog(type: string, text: string): { type: string; text: string } {
453
+ const entry = { type: sanitizeLogType(type), text };
454
+ this.logs.push(entry);
455
+ if (this.logs.length > this.maxScrollback) {
456
+ const excess = this.logs.length - this.maxScrollback;
457
+ this.logs.splice(0, excess);
458
+ }
459
+ if (this.container) {
460
+ const logEl = this.container.querySelector('#cl-terminal-log');
461
+ if (logEl) {
462
+ const lineEl = document.createElement('div');
463
+ lineEl.className = 'codelab-log-line ' + entry.type;
464
+ lineEl.innerHTML = ansiToHtml(entry.text);
465
+ logEl.appendChild(lineEl);
466
+ while (logEl.children.length > this.maxScrollback && logEl.firstChild) {
467
+ logEl.removeChild(logEl.firstChild);
468
+ }
469
+ }
470
+ }
471
+ return entry;
472
+ }
473
+
474
+ private _appendMirrorStream(chunk: string, type: string): void {
475
+ const combined = this._pendingMirrorLine + chunk;
476
+ const clearIdx2 = combined.lastIndexOf('\x1b[2J');
477
+ const clearIdx3 = combined.lastIndexOf('\x1b[3J');
478
+ const clearRis = combined.lastIndexOf('\x1bc');
479
+ const lastClear = Math.max(clearIdx2, clearIdx3, clearRis);
480
+ let working = combined;
481
+ if (lastClear !== -1) {
482
+ const skipLen = lastClear === clearRis ? 2 : 4;
483
+ working = combined.slice(lastClear + skipLen).replace(/^(?:\x1b\[[23]J|\x1b\[(?:\d+;\d+)?H)+/, '');
484
+ this._clearMirrorDomOnly();
485
+ }
486
+
487
+ const normalized = working.replace(/\r\n/g, '\n');
488
+ const parts = normalized.split('\n');
489
+ for (let i = 0; i < parts.length - 1; i++) {
490
+ const resolved = resolveAnsiControlCodes(parts[i]);
491
+ if (this._activeMirrorEl && this.logs.length > 0) {
492
+ this.logs[this.logs.length - 1].text = resolved + '\n';
493
+ this._activeMirrorEl.innerHTML = ansiToHtml(resolved);
494
+ this._activeMirrorEl = null;
495
+ } else {
496
+ this._pushMirrorLog(type, resolved + '\n');
497
+ }
498
+ }
499
+ const tail = parts[parts.length - 1];
500
+ this._pendingMirrorLine = tail;
501
+ if (tail.length > 0) {
502
+ const resolvedTail = resolveAnsiControlCodes(tail);
503
+ if (this._activeMirrorEl && this.logs.length > 0) {
504
+ this.logs[this.logs.length - 1].text = resolvedTail;
505
+ this._activeMirrorEl.innerHTML = ansiToHtml(resolvedTail);
506
+ } else {
507
+ this._pushMirrorLog(type, resolvedTail);
508
+ const logEl = this.container?.querySelector('#cl-terminal-log');
509
+ this._activeMirrorEl = (logEl?.lastElementChild as HTMLElement) || null;
510
+ }
511
+ }
512
+ }
513
+
514
+ private _clearMirrorDomOnly(): void {
515
+ this.logs.length = 0;
516
+ this._pendingMirrorLine = '';
517
+ this._activeMirrorEl = null;
518
+ const logEl = this.container?.querySelector('#cl-terminal-log');
519
+ if (logEl) logEl.innerHTML = '';
520
+ }
521
+
522
+ public writeStreamChunk(data: string, type: string = 'stdout'): void {
523
+ const str = String(data ?? '');
524
+ if (!str) return;
525
+
526
+ this._eraseXtermPromptIfVisible();
527
+
528
+ // Check if chunk contains screen-clear control codes (\x1b[2J, \x1b[3J, \x1bc)
529
+ const clearIdx2 = str.lastIndexOf('\x1b[2J');
530
+ const clearIdx3 = str.lastIndexOf('\x1b[3J');
531
+ const clearRis = str.lastIndexOf('\x1bc');
532
+ const lastClear = Math.max(clearIdx2, clearIdx3, clearRis);
533
+
534
+ if (lastClear !== -1 && this.xterm) {
535
+ const skipLen = lastClear === clearRis ? 2 : 4;
536
+ const afterClear = str
537
+ .slice(lastClear + skipLen)
538
+ .replace(/^(?:\x1b\[[23]J|\x1b\[(?:\d+;\d+)?H)+/, '');
539
+ this.xterm.reset();
540
+ this._clearMirrorDomOnly();
541
+ if (afterClear) {
542
+ const colored = type === 'stderr' && !afterClear.includes('\x1b[')
543
+ ? `\x1b[31m${this._toCrLf(afterClear)}\x1b[0m`
544
+ : this._toCrLf(afterClear);
545
+ this.xterm.write(colored);
546
+ this._appendMirrorStream(afterClear, type);
547
+ }
548
+ } else {
549
+ if (this.xterm) {
550
+ const formatted = type === 'stderr' && !str.includes('\x1b[')
551
+ ? `\x1b[31m${this._toCrLf(str)}\x1b[0m`
552
+ : this._toCrLf(str);
553
+ this.xterm.write(formatted);
554
+ }
555
+ this._appendMirrorStream(str, type);
556
+ }
557
+
558
+ if (!this.isCommandRunning()) {
559
+ // Ensure prompt appears on a fresh line if streamed output did not end with \n
560
+ if (this.xterm && this._pendingMirrorLine.length > 0) {
561
+ this.xterm.write('\r\n');
562
+ this._pendingMirrorLine = '';
563
+ this._activeMirrorEl = null;
564
+ }
565
+ this._redrawXtermPromptLine();
566
+ }
567
+ }
568
+
569
+ public write(data: string, type: string = 'stdout'): void {
570
+ this.writeStreamChunk(data, type);
571
+ }
572
+
573
+ public writeln(data: string, type: string = 'stdout'): void {
574
+ this.writeStreamChunk(String(data ?? '') + '\n', type);
575
+ }
576
+
577
+ public clear(): void {
578
+ this._clearMirrorDomOnly();
579
+ this._promptVisibleInXterm = false;
580
+ if (this.xterm) {
581
+ this.xterm.reset();
582
+ }
583
+ this.updateActiveLine();
584
+ }
585
+
586
+ public getHistory(): string[] {
587
+ return [...this.history];
588
+ }
589
+
590
+ private _activateNextReadLine(): void {
591
+ if (this._readLineQueue.length === 0) return;
592
+ const head = this._readLineQueue[0];
593
+ if (head && !head._activated) {
594
+ head._activated = true;
595
+ head.prevPrompt = this.promptOverride;
596
+ this.promptOverride = head.promptText;
597
+ }
598
+ }
599
+
600
+ private _drainReadLineQueue(result: string | null = null): void {
601
+ if (this._readLineQueue.length === 0) return;
602
+ const queued = this._readLineQueue.splice(0, this._readLineQueue.length);
603
+ let restoredPrompt: string | null | undefined = undefined;
604
+ for (const entry of queued) {
605
+ if (entry._activated && restoredPrompt === undefined) {
606
+ restoredPrompt = entry.prevPrompt;
607
+ }
608
+ if (entry.cleanup) entry.cleanup();
609
+ }
610
+ if (restoredPrompt !== undefined) {
611
+ this.promptOverride = restoredPrompt;
612
+ }
613
+ for (const entry of queued) {
614
+ try {
615
+ entry.resolve(result);
616
+ } catch (_err) {
617
+ void _err;
618
+ }
619
+ }
620
+ }
621
+
622
+ public readLine(promptText: string = '', options: { signal?: AbortSignal } = {}): Promise<string | null> {
623
+ if (options.signal?.aborted) {
624
+ return Promise.resolve(null);
625
+ }
626
+ return new Promise((resolve) => {
627
+ const item: ReadLineQueueItem = {
628
+ promptText: String(promptText ?? ''),
629
+ prevPrompt: null,
630
+ _activated: false,
631
+ cleanup: null,
632
+ resolve
633
+ };
634
+ if (options.signal) {
635
+ const onAbort = () => {
636
+ const idx = this._readLineQueue.indexOf(item);
637
+ if (idx !== -1) {
638
+ this._readLineQueue.splice(idx, 1);
639
+ if (item._activated) {
640
+ this.promptOverride = item.prevPrompt;
641
+ this._activateNextReadLine();
642
+ }
643
+ this.updateActiveLine();
644
+ resolve(null);
645
+ }
646
+ };
647
+ options.signal.addEventListener('abort', onAbort, { once: true });
648
+ item.cleanup = () => {
649
+ options.signal?.removeEventListener('abort', onAbort);
650
+ };
651
+ }
652
+ this._readLineQueue.push(item);
653
+ this._activateNextReadLine();
654
+ this.updateActiveLine();
655
+ });
656
+ }
657
+
658
+ public focus(): void {
659
+ if (this.xterm) {
660
+ try {
661
+ this.xterm.focus();
662
+ return;
663
+ } catch (_err) {
664
+ void _err;
665
+ }
666
+ }
667
+ const input = this.container?.querySelector('#cl-repl-input') as HTMLInputElement | null;
668
+ input?.focus();
669
+ }
670
+
671
+ private _addDomListener(target: EventTarget, type: string, fn: EventListener): void {
672
+ target.addEventListener(type, fn);
673
+ this._domListeners.push({ target, type, fn });
674
+ }
675
+
676
+ private _cleanupDomListeners(): void {
677
+ for (const l of this._domListeners) {
678
+ try {
679
+ l.target.removeEventListener(l.type, l.fn);
680
+ } catch (_err) {
681
+ void _err;
682
+ }
683
+ }
684
+ this._domListeners = [];
685
+ }
686
+
687
+ public mount(container: HTMLElement): void {
688
+ this.destroy();
689
+ this._disposed = false;
690
+ this.container = container;
691
+
692
+ const initialLogsHtml = this.logs
693
+ .map((item) => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
694
+ .join('');
695
+
696
+ const fontPx = this.options.fontSize || 13;
697
+ this.container.innerHTML = `
698
+ <div class="codelab-terminal codelab-terminal--xterm" id="cl-terminal-surface" tabindex="0" style="font-size:${fontPx}px;">
699
+ <div class="codelab-xterm-mount" id="cl-xterm-mount"></div>
700
+ <div class="codelab-terminal__mirror" aria-hidden="true">
701
+ <div class="codelab-terminal__log" id="cl-terminal-log">${initialLogsHtml}</div>
702
+ <div class="codelab-pty__active-line" id="cl-pty-active-line">
703
+ <span class="codelab-pty__prompt">${escapeHtml(this.getPrompt())}</span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor blink"> </span><span class="codelab-pty__after"></span>
704
+ </div>
705
+ </div>
706
+ <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;width:1px;height:1px;overflow:hidden;">
707
+ <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
708
+ </form>
709
+ </div>
710
+ `;
711
+
712
+ const xtermMount = this.container.querySelector('#cl-xterm-mount') as HTMLElement | null;
713
+ const replInput = this.container.querySelector('#cl-repl-input') as HTMLInputElement | null;
714
+ const replForm = this.container.querySelector('#cl-repl-form') as HTMLFormElement | null;
715
+ const surface = this.container.querySelector('#cl-terminal-surface') as HTMLElement | null;
716
+
717
+ if (xtermMount && canUseXtermInEnvironment(xtermMount)) {
718
+ const { Terminal: XtermTerminal, FitAddon: XtermFitAddon, WebLinksAddon: XtermWebLinksAddon } =
719
+ getXtermRuntimeClasses();
720
+ const term = new XtermTerminal({
721
+ fontFamily:
722
+ this.options.fontFamily ||
723
+ "'JetBrains Mono', 'SF Mono', Menlo, Monaco, Consolas, 'Liberation Mono', monospace",
724
+ fontSize: this.options.fontSize || 13,
725
+ lineHeight: 1.35,
726
+ cursorBlink: true,
727
+ cursorStyle: 'block',
728
+ convertEol: true,
729
+ scrollback: this.maxScrollback,
730
+ allowProposedApi: true,
731
+ theme: getXtermTheme(this._themeMode)
732
+ });
733
+
734
+ const fitAddon = new XtermFitAddon();
735
+ term.loadAddon(fitAddon);
736
+
737
+ const webLinksAddon = new XtermWebLinksAddon((_event, uri) => {
738
+ if (this.options.onOpenUrl) {
739
+ const handled = this.options.onOpenUrl(uri);
740
+ if (handled === true) return;
741
+ }
742
+ if (typeof window !== 'undefined') {
743
+ window.open(uri, '_blank', 'noopener,noreferrer');
744
+ }
745
+ });
746
+ term.loadAddon(webLinksAddon);
747
+
748
+ // Register file:line:col clickable diagnostic links
749
+ term.registerLinkProvider({
750
+ provideLinks: (bufferLineNumber, callback) => {
751
+ const line = term.buffer.active.getLine(bufferLineNumber - 1);
752
+ if (!line) {
753
+ callback(undefined);
754
+ return;
755
+ }
756
+ const lineText = line.translateToString(true);
757
+ const links: Array<{
758
+ range: { start: { x: number; y: number }; end: { x: number; y: number } };
759
+ text: string;
760
+ activate: () => void;
761
+ }> = [];
762
+ FILE_LINK_RE.lastIndex = 0;
763
+ let m: RegExpExecArray | null;
764
+ while ((m = FILE_LINK_RE.exec(lineText)) !== null) {
765
+ const fullMatch = m[0];
766
+ const relFile = m[1];
767
+ const lineNum = Number(m[2] || m[4] || 1);
768
+ const colNum = Number(m[3] || m[5] || 1);
769
+ const startX = m.index + 1;
770
+ const endX = m.index + fullMatch.length;
771
+ links.push({
772
+ range: {
773
+ start: { x: startX, y: bufferLineNumber },
774
+ end: { x: endX, y: bufferLineNumber }
775
+ },
776
+ text: fullMatch,
777
+ activate: () => {
778
+ if (this.options.onOpenFileLink) {
779
+ this.options.onOpenFileLink(relFile, lineNum, colNum);
780
+ }
781
+ }
782
+ });
783
+ }
784
+ callback(links.length > 0 ? links : undefined);
785
+ }
786
+ });
787
+
788
+ term.attachCustomKeyEventHandler((ev: KeyboardEvent) => {
789
+ if (ev.type !== 'keydown') return true;
790
+ const isMetaOnly = ev.metaKey && !ev.ctrlKey;
791
+ const isCtrlOnly = ev.ctrlKey && !ev.metaKey;
792
+ // Cmd+C (macOS) or Ctrl+Shift+C copies selection when present
793
+ if ((isMetaOnly && (ev.key === 'c' || ev.key === 'C')) || (isCtrlOnly && ev.shiftKey && (ev.key === 'c' || ev.key === 'C'))) {
794
+ if (term.hasSelection() && typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
795
+ navigator.clipboard.writeText(term.getSelection()).catch(() => {});
796
+ }
797
+ return false;
798
+ }
799
+ // Cmd+K clears terminal on macOS
800
+ if (isMetaOnly && (ev.key === 'k' || ev.key === 'K')) {
801
+ ev.preventDefault();
802
+ this.clear();
803
+ return false;
804
+ }
805
+ // Allow workbench toggle shortcuts (Ctrl+`, Cmd+J, Cmd+P, Cmd+Shift+P) to bubble to workbench
806
+ if (ev.ctrlKey && ev.key === '`') {
807
+ return false;
808
+ }
809
+ if (isMetaOnly && (ev.key === 'p' || ev.key === 'P' || ev.key === 'j' || ev.key === 'J')) {
810
+ return false;
811
+ }
812
+ return true;
813
+ });
814
+
815
+ term.open(xtermMount);
816
+ this.xterm = term;
817
+ this.fitAddon = fitAddon;
818
+
819
+ // Replay initial logs if session already had history before remount
820
+ for (const entry of this.logs) {
821
+ const txt = String(entry.text || '');
822
+ if (!txt) continue;
823
+ const withNewline = txt.endsWith('\n') ? txt : txt + '\n';
824
+ term.write(this._toCrLf(withNewline));
825
+ }
826
+
827
+ term.onData((data) => {
828
+ this._handleXtermData(data);
829
+ });
830
+
831
+ if (typeof ResizeObserver !== 'undefined') {
832
+ this._resizeObserver = new ResizeObserver(() => {
833
+ this._scheduleFit();
834
+ });
835
+ this._resizeObserver.observe(xtermMount);
836
+ }
837
+
838
+ this._scheduleFit();
839
+ this.updateActiveLine();
840
+ }
841
+
842
+ if (surface) {
843
+ this._addDomListener(surface, 'click', (e) => {
844
+ if (e.target === replInput) return;
845
+ if (this.xterm && this.xterm.hasSelection()) return;
846
+ this.focus();
847
+ });
848
+ }
849
+
850
+ if (replInput) {
851
+ const syncFromReplInput = () => {
852
+ if (this.isCommandRunning()) {
853
+ replInput.value = '';
854
+ return;
855
+ }
856
+ const nextVal = replInput.value || '';
857
+ const nextPos = typeof replInput.selectionStart === 'number' ? replInput.selectionStart : nextVal.length;
858
+ if (nextVal !== this.buffer || nextPos !== this.cursor) {
859
+ this.buffer = nextVal;
860
+ this.cursor = nextPos;
861
+ this.updateActiveLine();
862
+ }
863
+ };
864
+ this._addDomListener(replInput, 'keydown', (e) => {
865
+ this.handleKeyDown(e as KeyboardEvent);
866
+ });
867
+ this._addDomListener(replInput, 'paste', (e) => {
868
+ const ce = e as ClipboardEvent;
869
+ const text = ce.clipboardData?.getData('text/plain') || '';
870
+ if (text && text.includes('\n')) {
871
+ ce.preventDefault();
872
+ void this.pasteText(text);
873
+ }
874
+ });
875
+ this._addDomListener(replInput, 'input', syncFromReplInput);
876
+ this._addDomListener(replInput, 'change', syncFromReplInput);
877
+ this._addDomListener(replInput, 'click', syncFromReplInput);
878
+ this._addDomListener(replInput, 'keyup', (e) => {
879
+ const ke = e as KeyboardEvent;
880
+ if (ke.key === 'ArrowLeft' || ke.key === 'ArrowRight' || ke.key === 'Home' || ke.key === 'End') {
881
+ syncFromReplInput();
882
+ }
883
+ });
884
+ }
885
+
886
+ if (replForm) {
887
+ this._addDomListener(replForm, 'submit', (e) => {
888
+ e.preventDefault();
889
+ this.submitLine();
890
+ });
891
+ }
892
+ }
893
+
894
+ private _findReverseSearchMatch(query: string, startIdx?: number): number {
895
+ if (!query || !this.history.length) return -1;
896
+ const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
897
+ for (let i = from; i >= 0; i--) {
898
+ if (this.history[i] && this.history[i].includes(query)) return i;
899
+ }
900
+ return -1;
901
+ }
902
+
903
+ private _handleInterrupt(): void {
904
+ const wasBusy = this.isBusy || this._readLineQueue.length > 0;
905
+ this.isBusy = false;
906
+ if (this.xterm) {
907
+ this.xterm.write('^C\r\n');
908
+ this._promptVisibleInXterm = false;
909
+ }
910
+ this._pushMirrorLog('system', wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C`);
911
+ this.buffer = '';
912
+ this.cursor = 0;
913
+ this.historyIdx = -1;
914
+ this.searchMode = false;
915
+ this.searchQuery = '';
916
+ this.searchMatchIdx = -1;
917
+ this._drainReadLineQueue(null);
918
+ if (this.replMode) this.replMode = false;
919
+ if (this.onInterrupt) {
920
+ try {
921
+ this.onInterrupt();
922
+ } catch (_err) {
923
+ void _err;
924
+ }
925
+ }
926
+ this.updateActiveLine();
927
+ }
928
+
929
+ private _handleXtermData(data: string): void {
930
+ if (!data) return;
931
+
932
+ // Multi-char paste without ESC prefix
933
+ if (data.length > 1 && !data.startsWith('\x1b')) {
934
+ if (data.includes('\x03')) {
935
+ this._handleInterrupt();
936
+ return;
937
+ }
938
+ void this.pasteText(data);
939
+ return;
940
+ }
941
+
942
+ // Ctrl+C
943
+ if (data === '\x03') {
944
+ this._handleInterrupt();
945
+ return;
946
+ }
947
+
948
+ // Ctrl+L
949
+ if (data === '\x0c') {
950
+ this.clear();
951
+ return;
952
+ }
953
+
954
+ if (this.isCommandRunning()) {
955
+ return;
956
+ }
957
+
958
+ // Ctrl+R (reverse history search)
959
+ if (data === '\x12') {
960
+ if (!this.searchMode) {
961
+ this.searchMode = true;
962
+ this.searchQuery = '';
963
+ this.searchMatchIdx = -1;
964
+ } else if (this.searchQuery) {
965
+ const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
966
+ const mIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
967
+ if (mIdx !== -1) {
968
+ this.searchMatchIdx = mIdx;
969
+ this.buffer = this.history[mIdx];
970
+ this.cursor = this.buffer.length;
971
+ }
972
+ }
973
+ this.updateActiveLine();
974
+ return;
975
+ }
976
+
977
+ if (this.searchMode) {
978
+ if (data === '\x1b' || data === '\x07') {
979
+ this.searchMode = false;
980
+ this.searchQuery = '';
981
+ this.searchMatchIdx = -1;
982
+ this.updateActiveLine();
983
+ return;
984
+ }
985
+ if (data === '\x7f' || data === '\b') {
986
+ this.searchQuery = this.searchQuery.slice(0, -1);
987
+ const mIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
988
+ this.searchMatchIdx = mIdx;
989
+ if (mIdx !== -1) {
990
+ this.buffer = this.history[mIdx];
991
+ this.cursor = this.buffer.length;
992
+ }
993
+ this.updateActiveLine();
994
+ return;
995
+ }
996
+ if (data === '\r' || data === '\n') {
997
+ this.searchMode = false;
998
+ this.searchQuery = '';
999
+ this.searchMatchIdx = -1;
1000
+ this.submitLine();
1001
+ return;
1002
+ }
1003
+ if (data >= ' ' && !data.startsWith('\x1b')) {
1004
+ this.searchQuery += data;
1005
+ const mIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
1006
+ this.searchMatchIdx = mIdx;
1007
+ if (mIdx !== -1) {
1008
+ this.buffer = this.history[mIdx];
1009
+ this.cursor = this.buffer.length;
1010
+ }
1011
+ this.updateActiveLine();
1012
+ return;
1013
+ }
1014
+ this.searchMode = false;
1015
+ this.searchQuery = '';
1016
+ this.searchMatchIdx = -1;
1017
+ }
1018
+
1019
+ // Enter
1020
+ if (data === '\r' || data === '\n') {
1021
+ this.submitLine();
1022
+ return;
1023
+ }
1024
+
1025
+ // Ctrl+D (EOF on empty buffer)
1026
+ if (data === '\x04') {
1027
+ if (this.buffer === '') {
1028
+ if (this._readLineQueue.length > 0) {
1029
+ if (this.xterm) {
1030
+ this.xterm.write('\r\n');
1031
+ this._promptVisibleInXterm = false;
1032
+ }
1033
+ this._drainReadLineQueue(null);
1034
+ this.updateActiveLine();
1035
+ return;
1036
+ }
1037
+ if (this.replMode) {
1038
+ this.replMode = false;
1039
+ if (this.xterm) {
1040
+ this.xterm.write('\r\n');
1041
+ this._promptVisibleInXterm = false;
1042
+ }
1043
+ this.updateActiveLine();
1044
+ return;
1045
+ }
1046
+ }
1047
+ return;
1048
+ }
1049
+
1050
+ // Backspace
1051
+ if (data === '\x7f' || data === '\b') {
1052
+ if (this.cursor > 0) {
1053
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
1054
+ this.cursor--;
1055
+ this.updateActiveLine();
1056
+ }
1057
+ return;
1058
+ }
1059
+
1060
+ // Delete
1061
+ if (data === '\x1b[3~') {
1062
+ if (this.cursor < this.buffer.length) {
1063
+ this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
1064
+ this.updateActiveLine();
1065
+ }
1066
+ return;
1067
+ }
1068
+
1069
+ // Tab
1070
+ if (data === '\t') {
1071
+ this.autoComplete();
1072
+ return;
1073
+ }
1074
+
1075
+ // ArrowUp / ArrowDown
1076
+ if (data === '\x1b[A') {
1077
+ if (!this.history.length) return;
1078
+ if (this.historyIdx === -1) {
1079
+ this.savedBuffer = this.buffer;
1080
+ this.historyIdx = this.history.length - 1;
1081
+ } else if (this.historyIdx > 0) {
1082
+ this.historyIdx--;
1083
+ }
1084
+ this.buffer = this.history[this.historyIdx] || '';
1085
+ this.cursor = this.buffer.length;
1086
+ this.updateActiveLine();
1087
+ return;
1088
+ }
1089
+ if (data === '\x1b[B') {
1090
+ if (this.historyIdx !== -1) {
1091
+ if (this.historyIdx < this.history.length - 1) {
1092
+ this.historyIdx++;
1093
+ this.buffer = this.history[this.historyIdx] || '';
1094
+ } else {
1095
+ this.historyIdx = -1;
1096
+ this.buffer = this.savedBuffer || '';
1097
+ }
1098
+ this.cursor = this.buffer.length;
1099
+ this.updateActiveLine();
1100
+ }
1101
+ return;
1102
+ }
1103
+
1104
+ // ArrowLeft / ArrowRight
1105
+ if (data === '\x1b[D') {
1106
+ if (this.cursor > 0) {
1107
+ this.cursor--;
1108
+ this.updateActiveLine();
1109
+ }
1110
+ return;
1111
+ }
1112
+ if (data === '\x1b[C') {
1113
+ if (this.cursor < this.buffer.length) {
1114
+ this.cursor++;
1115
+ this.updateActiveLine();
1116
+ }
1117
+ return;
1118
+ }
1119
+
1120
+ // Word backward / forward (Alt+B / Alt+Left / Ctrl+Left, Alt+F / Alt+Right / Ctrl+Right)
1121
+ if (data === '\x1bb' || data === '\x1b[1;3D' || data === '\x1b[1;5D') {
1122
+ let pos = this.cursor;
1123
+ while (pos > 0 && /\s/.test(this.buffer[pos - 1])) pos--;
1124
+ while (pos > 0 && !/\s/.test(this.buffer[pos - 1])) pos--;
1125
+ this.cursor = pos;
1126
+ this.updateActiveLine();
1127
+ return;
1128
+ }
1129
+ if (data === '\x1bf' || data === '\x1b[1;3C' || data === '\x1b[1;5C') {
1130
+ let pos = this.cursor;
1131
+ while (pos < this.buffer.length && /\s/.test(this.buffer[pos])) pos++;
1132
+ while (pos < this.buffer.length && !/\s/.test(this.buffer[pos])) pos++;
1133
+ this.cursor = pos;
1134
+ this.updateActiveLine();
1135
+ return;
1136
+ }
1137
+
1138
+ // Home / Ctrl+A
1139
+ if (data === '\x01' || data === '\x1b[H' || data === '\x1bOH' || data === '\x1b[1~') {
1140
+ this.cursor = 0;
1141
+ this.updateActiveLine();
1142
+ return;
1143
+ }
1144
+
1145
+ // End / Ctrl+E
1146
+ if (data === '\x05' || data === '\x1b[F' || data === '\x1bOF' || data === '\x1b[4~') {
1147
+ this.cursor = this.buffer.length;
1148
+ this.updateActiveLine();
1149
+ return;
1150
+ }
1151
+
1152
+ // Ctrl+U (kill before cursor)
1153
+ if (data === '\x15') {
1154
+ this.buffer = this.buffer.slice(this.cursor);
1155
+ this.cursor = 0;
1156
+ this.updateActiveLine();
1157
+ return;
1158
+ }
1159
+
1160
+ // Ctrl+K (kill after cursor)
1161
+ if (data === '\x0b') {
1162
+ this.buffer = this.buffer.slice(0, this.cursor);
1163
+ this.updateActiveLine();
1164
+ return;
1165
+ }
1166
+
1167
+ // Ctrl+W / Alt+Backspace (delete word backward)
1168
+ if (data === '\x17' || data === '\x1b\x7f') {
1169
+ let pos = this.cursor;
1170
+ while (pos > 0 && /\s/.test(this.buffer[pos - 1])) pos--;
1171
+ while (pos > 0 && !/\s/.test(this.buffer[pos - 1])) pos--;
1172
+ this.buffer = this.buffer.slice(0, pos) + this.buffer.slice(this.cursor);
1173
+ this.cursor = pos;
1174
+ this.updateActiveLine();
1175
+ return;
1176
+ }
1177
+
1178
+ // Printable character
1179
+ if (data >= ' ' && !data.startsWith('\x1b')) {
1180
+ this.buffer = this.buffer.slice(0, this.cursor) + data + this.buffer.slice(this.cursor);
1181
+ this.cursor += data.length;
1182
+ this.updateActiveLine();
1183
+ }
1184
+ }
1185
+
1186
+ public handleKeyDown(e: KeyboardEvent): void {
1187
+ if (!e) return;
1188
+ const key = e.key;
1189
+ const isCtrlOnly = Boolean(e.ctrlKey && !e.metaKey);
1190
+ const isMetaOnly = Boolean(e.metaKey && !e.ctrlKey);
1191
+ const isCtrl = Boolean(e.ctrlKey || e.metaKey);
1192
+ const isFromReplInput = Boolean(e.target && (e.target as HTMLElement).id === 'cl-repl-input');
1193
+
1194
+ if ((isCtrl && (key === 'l' || key === 'L')) || (isMetaOnly && (key === 'k' || key === 'K'))) {
1195
+ e.preventDefault?.();
1196
+ this.clear();
1197
+ return;
1198
+ }
1199
+ if (isMetaOnly && (key === 'c' || key === 'C' || key === 'v' || key === 'V' || key === 'a' || key === 'A' || key === 'x' || key === 'X')) {
1200
+ return;
1201
+ }
1202
+ if (isCtrlOnly && (key === 'c' || key === 'C')) {
1203
+ if (e.shiftKey) return;
1204
+ e.preventDefault?.();
1205
+ this._handleInterrupt();
1206
+ return;
1207
+ }
1208
+ if (this.isCommandRunning()) {
1209
+ e.preventDefault?.();
1210
+ return;
1211
+ }
1212
+ if (isCtrl && (key === 'r' || key === 'R')) {
1213
+ e.preventDefault?.();
1214
+ this._handleXtermData('\x12');
1215
+ return;
1216
+ }
1217
+ if (key === 'Enter') {
1218
+ e.preventDefault?.();
1219
+ this._handleXtermData('\r');
1220
+ return;
1221
+ }
1222
+ if (key === 'Tab') {
1223
+ e.preventDefault?.();
1224
+ this._handleXtermData('\t');
1225
+ return;
1226
+ }
1227
+ if (key === 'ArrowUp') {
1228
+ e.preventDefault?.();
1229
+ this._handleXtermData('\x1b[A');
1230
+ return;
1231
+ }
1232
+ if (key === 'ArrowDown') {
1233
+ e.preventDefault?.();
1234
+ this._handleXtermData('\x1b[B');
1235
+ return;
1236
+ }
1237
+ if (isCtrlOnly && (key === 'u' || key === 'U')) {
1238
+ e.preventDefault?.();
1239
+ this._handleXtermData('\x15');
1240
+ return;
1241
+ }
1242
+ if (isCtrlOnly && (key === 'k' || key === 'K')) {
1243
+ e.preventDefault?.();
1244
+ this._handleXtermData('\x0b');
1245
+ return;
1246
+ }
1247
+ if (isCtrlOnly && (key === 'w' || key === 'W')) {
1248
+ e.preventDefault?.();
1249
+ this._handleXtermData('\x17');
1250
+ return;
1251
+ }
1252
+ if (isCtrlOnly && (key === 'd' || key === 'D')) {
1253
+ e.preventDefault?.();
1254
+ this._handleXtermData('\x04');
1255
+ return;
1256
+ }
1257
+ if (key === 'Escape') {
1258
+ e.preventDefault?.();
1259
+ this._handleXtermData('\x1b');
1260
+ return;
1261
+ }
1262
+ if (isFromReplInput) {
1263
+ // Allow native HTMLInputElement editing (typing, Backspace, Delete, SelectAll + fill(''), caret arrows)
1264
+ return;
1265
+ }
1266
+ if (key === 'Backspace') {
1267
+ e.preventDefault?.();
1268
+ this._handleXtermData(e.altKey ? '\x1b\x7f' : '\x7f');
1269
+ return;
1270
+ }
1271
+ if (key === 'Delete') {
1272
+ e.preventDefault?.();
1273
+ this._handleXtermData('\x1b[3~');
1274
+ return;
1275
+ }
1276
+ if (key === 'ArrowLeft') {
1277
+ e.preventDefault?.();
1278
+ this._handleXtermData(e.altKey || isCtrlOnly ? '\x1b[1;5D' : '\x1b[D');
1279
+ return;
1280
+ }
1281
+ if (key === 'ArrowRight') {
1282
+ e.preventDefault?.();
1283
+ this._handleXtermData(e.altKey || isCtrlOnly ? '\x1b[1;5C' : '\x1b[C');
1284
+ return;
1285
+ }
1286
+ if (key === 'Home' || (isCtrlOnly && (key === 'a' || key === 'A'))) {
1287
+ e.preventDefault?.();
1288
+ this._handleXtermData('\x01');
1289
+ return;
1290
+ }
1291
+ if (key === 'End' || (isCtrlOnly && (key === 'e' || key === 'E'))) {
1292
+ e.preventDefault?.();
1293
+ this._handleXtermData('\x05');
1294
+ return;
1295
+ }
1296
+ if (e.altKey && (key === 'b' || key === 'B')) {
1297
+ e.preventDefault?.();
1298
+ this._handleXtermData('\x1bb');
1299
+ return;
1300
+ }
1301
+ if (e.altKey && (key === 'f' || key === 'F')) {
1302
+ e.preventDefault?.();
1303
+ this._handleXtermData('\x1bf');
1304
+ return;
1305
+ }
1306
+ if (key && key.length === 1 && !isCtrl && !e.altKey) {
1307
+ e.preventDefault?.();
1308
+ this._handleXtermData(key);
1309
+ }
1310
+ }
1311
+
1312
+ public autoComplete(): void {
1313
+ if (!this.getCompletions) return;
1314
+ const res = this.getCompletions(this.buffer, this.cursor);
1315
+ if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
1316
+
1317
+ const matches = res.matches;
1318
+ if (matches.length === 1) {
1319
+ const match = matches[0];
1320
+ const appendChar = match.endsWith('/') ? '' : ' ';
1321
+ const before = this.buffer.slice(0, res.tokenStart);
1322
+ const after = this.buffer.slice(this.cursor);
1323
+ this.buffer = before + match + appendChar + after;
1324
+ this.cursor = before.length + match.length + appendChar.length;
1325
+ this.updateActiveLine();
1326
+ return;
1327
+ }
1328
+
1329
+ let lcp = matches[0];
1330
+ for (let i = 1; i < matches.length; i++) {
1331
+ let j = 0;
1332
+ while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) j++;
1333
+ lcp = lcp.slice(0, j);
1334
+ }
1335
+ if (lcp.length > res.token.length) {
1336
+ const before = this.buffer.slice(0, res.tokenStart);
1337
+ const after = this.buffer.slice(this.cursor);
1338
+ this.buffer = before + lcp + after;
1339
+ this.cursor = before.length + lcp.length;
1340
+ }
1341
+
1342
+ const candidatesLine = matches.join(' ');
1343
+ if (this.xterm) {
1344
+ this.xterm.write(`\r\n${candidatesLine}\r\n`);
1345
+ this._promptVisibleInXterm = false;
1346
+ }
1347
+ this._pushMirrorLog('system', `${this.getPrompt()}${this.buffer}`);
1348
+ this._pushMirrorLog('stdout', candidatesLine);
1349
+ this.updateActiveLine();
1350
+ }
1351
+
1352
+ public async pasteText(rawText: string): Promise<void> {
1353
+ if (!rawText || this.isCommandRunning()) return;
1354
+ const normalized = String(rawText).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
1355
+ if (!normalized.includes('\n')) {
1356
+ this.buffer = this.buffer.slice(0, this.cursor) + normalized + this.buffer.slice(this.cursor);
1357
+ this.cursor += normalized.length;
1358
+ this.updateActiveLine();
1359
+ return;
1360
+ }
1361
+ const parts = normalized.split('\n');
1362
+ for (let i = 0; i < parts.length; i++) {
1363
+ const seg = parts[i];
1364
+ if (i < parts.length - 1) {
1365
+ this.buffer = this.buffer.slice(0, this.cursor) + seg + this.buffer.slice(this.cursor);
1366
+ this.cursor = this.buffer.length;
1367
+ this.updateActiveLine();
1368
+ this.submitLine();
1369
+ while (this.isCommandRunning()) {
1370
+ await new Promise((r) => setTimeout(r, 10));
1371
+ }
1372
+ } else if (seg.length > 0) {
1373
+ this.buffer = seg;
1374
+ this.cursor = seg.length;
1375
+ this.updateActiveLine();
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ public submitLine(): void {
1381
+ // 1. Resolve interactive stdin readLine request if one is waiting
1382
+ if (this._readLineQueue.length > 0) {
1383
+ const line = this.buffer;
1384
+ const promptSnap = this.getPrompt();
1385
+ if (this.xterm) {
1386
+ this._redrawXtermPromptLine();
1387
+ this.xterm.write('\r\n');
1388
+ this._promptVisibleInXterm = false;
1389
+ }
1390
+ this._pushMirrorLog('system', `${promptSnap}${line}`);
1391
+ this.buffer = '';
1392
+ this.cursor = 0;
1393
+ this.historyIdx = -1;
1394
+ this.searchMode = false;
1395
+ this.searchQuery = '';
1396
+ this.searchMatchIdx = -1;
1397
+
1398
+ const entry = this._readLineQueue.shift();
1399
+ if (entry) {
1400
+ entry.cleanup?.();
1401
+ this.promptOverride = entry.prevPrompt;
1402
+ this._activateNextReadLine();
1403
+ this.updateActiveLine();
1404
+ entry.resolve(line);
1405
+ }
1406
+ return;
1407
+ }
1408
+
1409
+ if (this.isBusy) return;
1410
+
1411
+ const line = this.buffer;
1412
+ const promptSnap = this.getPrompt();
1413
+ if (this.xterm) {
1414
+ this._redrawXtermPromptLine();
1415
+ this.xterm.write('\r\n');
1416
+ this._promptVisibleInXterm = false;
1417
+ }
1418
+
1419
+ this.buffer = '';
1420
+ this.cursor = 0;
1421
+ this.historyIdx = -1;
1422
+ this.searchMode = false;
1423
+ this.searchQuery = '';
1424
+ this.searchMatchIdx = -1;
1425
+ this._pendingMirrorLine = '';
1426
+ this._activeMirrorEl = null;
1427
+
1428
+ this._pushMirrorLog('system', `${promptSnap}${line}`);
1429
+
1430
+ const trimmed = line.trim();
1431
+ if (trimmed && this.history[this.history.length - 1] !== trimmed) {
1432
+ this.history.push(trimmed);
1433
+ if (this.history.length > this.maxHistory) {
1434
+ this.history.splice(0, this.history.length - this.maxHistory);
1435
+ }
1436
+ }
1437
+
1438
+ if (!this.onCommand) {
1439
+ this.updateActiveLine();
1440
+ return;
1441
+ }
1442
+
1443
+ if (!trimmed) {
1444
+ this.updateActiveLine();
1445
+ return;
1446
+ }
1447
+
1448
+ this.isBusy = true;
1449
+ this.updateActiveLine();
1450
+
1451
+ let cmdRes: unknown;
1452
+ try {
1453
+ cmdRes = this.onCommand(line);
1454
+ } catch (err) {
1455
+ this.isBusy = false;
1456
+ this.updateActiveLine();
1457
+ throw err;
1458
+ }
1459
+
1460
+ if (cmdRes && typeof (cmdRes as Promise<unknown>).then === 'function') {
1461
+ Promise.resolve(cmdRes)
1462
+ .catch(() => {})
1463
+ .finally(() => {
1464
+ if (this._disposed) return;
1465
+ if (this.xterm && this._pendingMirrorLine.length > 0) {
1466
+ this.xterm.write('\r\n');
1467
+ this._pendingMirrorLine = '';
1468
+ this._activeMirrorEl = null;
1469
+ }
1470
+ this.isBusy = false;
1471
+ this.updateActiveLine();
1472
+ });
1473
+ } else {
1474
+ if (this.xterm && this._pendingMirrorLine.length > 0) {
1475
+ this.xterm.write('\r\n');
1476
+ this._pendingMirrorLine = '';
1477
+ this._activeMirrorEl = null;
1478
+ }
1479
+ this.isBusy = false;
1480
+ this.updateActiveLine();
1481
+ }
1482
+ }
1483
+
1484
+ public updateActiveLine(): void {
1485
+ this._redrawXtermPromptLine();
1486
+
1487
+ if (!this.container) return;
1488
+ const input = this.container.querySelector('#cl-repl-input') as HTMLInputElement | null;
1489
+ if (input) {
1490
+ if (input.value !== this.buffer) {
1491
+ input.value = this.buffer;
1492
+ }
1493
+ if (typeof document !== 'undefined' && document.activeElement === input && typeof input.setSelectionRange === 'function') {
1494
+ try {
1495
+ input.setSelectionRange(this.cursor, this.cursor);
1496
+ } catch (_err) {
1497
+ void _err;
1498
+ }
1499
+ }
1500
+ }
1501
+ const lineEl = this.container.querySelector('#cl-pty-active-line') as HTMLElement | null;
1502
+ if (!lineEl) return;
1503
+
1504
+ if (this.isCommandRunning()) {
1505
+ lineEl.setAttribute('data-busy', 'true');
1506
+ lineEl.style.display = 'none';
1507
+ lineEl.innerHTML =
1508
+ '<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>';
1509
+ return;
1510
+ }
1511
+
1512
+ lineEl.removeAttribute('data-busy');
1513
+ lineEl.style.display = '';
1514
+ const prompt = this.searchMode
1515
+ ? `(reverse-i-search)\`${this.searchQuery}\`: `
1516
+ : this.getPrompt();
1517
+ const before = this.buffer.slice(0, this.cursor);
1518
+ const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1519
+ const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1520
+ 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>`;
1521
+ }
1522
+
1523
+ public render(): void {
1524
+ if (this.container && !this.xterm) {
1525
+ this.mount(this.container);
1526
+ return;
1527
+ }
1528
+ this.updateActiveLine();
1529
+ this._scheduleFit();
1530
+ }
1531
+
1532
+ public destroy(): void {
1533
+ this._disposed = true;
1534
+ this._drainReadLineQueue(null);
1535
+ this._cleanupDomListeners();
1536
+ if (this._fitRaf && typeof cancelAnimationFrame === 'function') {
1537
+ cancelAnimationFrame(this._fitRaf);
1538
+ this._fitRaf = 0;
1539
+ }
1540
+ if (this._resizeObserver) {
1541
+ try {
1542
+ this._resizeObserver.disconnect();
1543
+ } catch (_err) {
1544
+ void _err;
1545
+ }
1546
+ this._resizeObserver = null;
1547
+ }
1548
+ if (this.xterm) {
1549
+ try {
1550
+ this.xterm.dispose();
1551
+ } catch (_err) {
1552
+ void _err;
1553
+ }
1554
+ this.xterm = null;
1555
+ }
1556
+ this.fitAddon = null;
1557
+ this._promptVisibleInXterm = false;
1558
+ }
1559
+ }
1560
+
1561
+ export function createXtermTerminalEngine(
1562
+ container: HTMLElement | null,
1563
+ options: XtermAdapterOptions = {}
1564
+ ): XtermTerminalEngine {
1565
+ return new XtermTerminalEngine(container, options);
1566
+ }