@innovatorved/code-lab 0.1.6 → 0.1.8

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