@innovatorved/code-lab 0.4.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 (82) hide show
  1. package/ARCHITECTURE.md +4 -4
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +6 -30
  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 -5818
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4655 -64400
  9. package/dist/code-lab.js +4540 -64286
  10. package/dist/code-lab.umd.js +4540 -64286
  11. package/dist/diagnostics.d.ts +3 -0
  12. package/dist/extensions/cpp.d.ts +2 -2
  13. package/dist/extensions/cpp.esm.js +1804 -14725
  14. package/dist/extensions/cpp.js +1804 -14725
  15. package/dist/extensions/guided-lab.esm.js +2938 -16127
  16. package/dist/extensions/guided-lab.js +2938 -16127
  17. package/dist/extensions/python.d.ts +2 -2
  18. package/dist/extensions/python.esm.js +1765 -14698
  19. package/dist/extensions/python.js +1765 -14698
  20. package/dist/index.d.ts +1 -1
  21. package/dist/packages/settings/src/configuration-service.d.ts +7 -0
  22. package/dist/packages/settings/src/index.d.ts +1 -1
  23. package/dist/packages/ui/src/index.d.ts +2 -2
  24. package/dist/packages/ui/src/plugin-registry.d.ts +1 -0
  25. package/dist/packages/ui/src/settings-dialog.d.ts +31 -3
  26. package/dist/packages/ui/src/themes.d.ts +5 -0
  27. package/dist/preview-sw.js +4 -188
  28. package/dist/runtime.esm.js +109 -10284
  29. package/dist/runtime.js +107 -10284
  30. package/dist/schemas.d.ts +2 -2
  31. package/dist/schemas.esm.js +2938 -16127
  32. package/dist/schemas.js +2941 -16130
  33. package/dist/scm.d.ts +296 -14
  34. package/dist/shell.esm.js +811 -9178
  35. package/dist/shell.js +811 -9178
  36. package/dist/storage.d.ts +56 -0
  37. package/dist/terminal.esm.js +20 -1347
  38. package/dist/terminal.js +20 -1347
  39. package/dist/workbench/command-palette.d.ts +16 -1
  40. package/dist/workbench/diff-editor.d.ts +27 -1
  41. package/dist/workbench/icons.d.ts +6 -2
  42. package/dist/workbench/index.d.ts +33 -1
  43. package/dist/workbench/intellisense.d.ts +194 -0
  44. package/dist/workbench/styles.d.ts +1 -1
  45. package/dist/workbench/xterm-adapter.d.ts +122 -0
  46. package/package.json +8 -2
  47. package/packages/commands/package.json +1 -1
  48. package/packages/core/package.json +1 -1
  49. package/packages/editor/package.json +1 -1
  50. package/packages/fs/package.json +1 -1
  51. package/packages/preview/package.json +1 -1
  52. package/packages/runtime/package.json +1 -1
  53. package/packages/settings/package.json +1 -1
  54. package/packages/settings/src/builtin-schemas.ts +17 -6
  55. package/packages/settings/src/configuration-service.ts +72 -6
  56. package/packages/settings/src/index.ts +1 -0
  57. package/packages/sql/package.json +1 -1
  58. package/packages/terminal/package.json +1 -1
  59. package/packages/ui/package.json +1 -1
  60. package/packages/ui/src/index.ts +4 -0
  61. package/packages/ui/src/plugin-registry.ts +17 -2
  62. package/packages/ui/src/settings-dialog.ts +393 -99
  63. package/packages/ui/src/themes.ts +183 -24
  64. package/src/code-lab.css +2763 -444
  65. package/src/diagnostics.ts +139 -7
  66. package/src/extensions/cpp.ts +337 -71
  67. package/src/extensions/python.ts +375 -75
  68. package/src/index.ts +1 -1
  69. package/src/runtime.ts +272 -43
  70. package/src/schemas.ts +2 -2
  71. package/src/scm.ts +2172 -74
  72. package/src/shell.ts +1999 -193
  73. package/src/storage.ts +401 -5
  74. package/src/terminal.ts +148 -12
  75. package/src/workbench/command-palette.ts +289 -48
  76. package/src/workbench/diff-editor.ts +240 -78
  77. package/src/workbench/icons.ts +250 -46
  78. package/src/workbench/index.ts +7 -1
  79. package/src/workbench/intellisense.ts +1859 -0
  80. package/src/workbench/styles.ts +25 -19
  81. package/src/workbench/xterm-adapter.ts +1566 -0
  82. package/src/workbench.ts +13446 -3881
package/dist/terminal.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.4.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.6.0 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 73 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -16,1358 +16,31 @@
16
16
  */
17
17
  (function (root) {
18
18
  'use strict';
19
- var CodeLabLogger = (() => {
20
- var __defProp = Object.defineProperty;
21
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
22
- var __getOwnPropNames = Object.getOwnPropertyNames;
23
- var __hasOwnProp = Object.prototype.hasOwnProperty;
24
- var __export = (target, all) => {
25
- for (var name in all)
26
- __defProp(target, name, { get: all[name], enumerable: true });
27
- };
28
- var __copyProps = (to, from, except, desc) => {
29
- if (from && typeof from === "object" || typeof from === "function") {
30
- for (let key of __getOwnPropNames(from))
31
- if (!__hasOwnProp.call(to, key) && key !== except)
32
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
- }
34
- return to;
35
- };
36
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
-
38
- // src/logger.ts
39
- var logger_exports = {};
40
- __export(logger_exports, {
41
- CodeLabError: () => CodeLabError,
42
- DEFAULT_LOGGER: () => DEFAULT_LOGGER,
43
- LOG_PREFIX: () => LOG_PREFIX,
44
- createLogger: () => createLogger,
45
- default: () => logger_default,
46
- isCodeLabError: () => isCodeLabError
47
- });
48
- var LOG_PREFIX = "[code-lab]";
49
- var CodeLabError = class extends Error {
50
- code;
51
- options;
52
- cause;
53
- recoverable;
54
- details;
55
- context;
56
- constructor(code, message, options = {}) {
57
- super(message);
58
- this.name = "CodeLabError";
59
- this.code = code;
60
- this.options = options;
61
- this.cause = options.cause;
62
- this.recoverable = options.recoverable !== false;
63
- const meta = options.details ?? options.context;
64
- if (meta !== void 0) {
65
- this.details = meta;
66
- this.context = meta;
67
- }
68
- Object.setPrototypeOf(this, new.target.prototype);
69
- }
70
- };
71
- function isCodeLabError(value) {
72
- return Boolean(
73
- value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
74
- );
75
- }
76
- function createLogger(options = {}) {
77
- const sink = options.logger ?? null;
78
- const debugEnabled = options.debug === true;
79
- const prefix = options.prefix || LOG_PREFIX;
80
- const write = (level, args) => {
81
- if (level === "debug" && !debugEnabled) return;
82
- if (sink && typeof sink[level] === "function") {
83
- let sinkError = null;
84
- try {
85
- sink[level](...args);
86
- return;
87
- } catch (err) {
88
- sinkError = err;
89
- }
90
- void sinkError;
91
- }
92
- const consoleObj = typeof console !== "undefined" ? console : null;
93
- const fn = consoleObj ? consoleObj[level] : null;
94
- if (typeof fn === "function") {
95
- fn.call(consoleObj, prefix, ...args);
96
- }
97
- };
98
- return {
99
- debug: (...args) => write("debug", args),
100
- info: (...args) => write("info", args),
101
- warn: (...args) => write("warn", args),
102
- error: (...args) => write("error", args)
103
- };
104
- }
105
- var DEFAULT_LOGGER = createLogger();
106
- var _loggerNamespace = {
107
- LOG_PREFIX,
108
- CodeLabError,
109
- isCodeLabError,
110
- createLogger,
111
- DEFAULT_LOGGER
112
- };
113
- var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
114
- if (_globalRoot && !_globalRoot.CodeLabLogger) {
115
- _globalRoot.CodeLabLogger = _loggerNamespace;
116
- }
117
- var logger_default = _loggerNamespace;
118
- return __toCommonJS(logger_exports);
119
- })();
19
+ var CodeLabLogger=(()=>{var s=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var y=(o,n)=>{for(var a in n)s(o,a,{get:n[a],enumerable:!0})},v=(o,n,a,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let e of C(n))!x.call(o,e)&&e!==a&&s(o,e,{get:()=>n[e],enumerable:!(t=p(n,e))||t.enumerable});return o};var O=o=>v(s({},"__esModule",{value:!0}),o);var h={};y(h,{CodeLabError:()=>d,DEFAULT_LOGGER:()=>w,LOG_PREFIX:()=>c,createLogger:()=>g,default:()=>_,isCodeLabError:()=>f});var c="[code-lab]",d=class extends Error{code;options;cause;recoverable;details;context;constructor(n,a,t={}){super(a),this.name="CodeLabError",this.code=n,this.options=t,this.cause=t.cause,this.recoverable=t.recoverable!==!1;let e=t.details??t.context;e!==void 0&&(this.details=e,this.context=e),Object.setPrototypeOf(this,new.target.prototype)}};function f(o){return!!(o&&typeof o=="object"&&(o instanceof d||o.name==="CodeLabError"&&typeof o.code=="string"))}function g(o={}){let n=o.logger??null,a=o.debug===!0,t=o.prefix||c,e=(r,b)=>{if(r==="debug"&&!a)return;if(n&&typeof n[r]=="function"){let L=null;try{n[r](...b);return}catch(k){L=k}}let i=typeof console<"u"?console:null,l=i?i[r]:null;typeof l=="function"&&l.call(i,t,...b)};return{debug:(...r)=>e("debug",r),info:(...r)=>e("info",r),warn:(...r)=>e("warn",r),error:(...r)=>e("error",r)}}var w=g(),E={LOG_PREFIX:c,CodeLabError:d,isCodeLabError:f,createLogger:g,DEFAULT_LOGGER:w},u=typeof globalThis<"u"?globalThis:null;u&&!u.CodeLabLogger&&(u.CodeLabLogger=E);var _=E;return O(h);})();
120
20
 
121
21
  (function () {
122
- // @ts-nocheck
123
- /**
124
- * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
125
- *
126
- * High-fidelity, self-contained terminal emulator engine providing:
127
- * - Inline prompt with cwd awareness (codelab:${cwd}$ )
128
- * - Interactive REPL sub-mode (> ) with .exit and Ctrl+D/Ctrl+C
129
- * - Character-by-character editing with cursor navigation:
130
- * ArrowLeft, ArrowRight, Home, End, Ctrl+A, Ctrl+E, Ctrl+U, Ctrl+K, Backspace, Delete
131
- * - Tab auto-completion for built-in commands and VFS filesystem paths
132
- * - History navigation (ArrowUp, ArrowDown)
133
- * - ANSI 16/256 SGR escape sequence translation to styled Geist HTML spans
134
- * - Headless DOM safety (defensive guards for Node.js test environments)
135
- *
136
- * (C) 2026 InnovatorVed / CodeLab. MIT License.
137
- */
138
-
139
- (function (root, factory) {
140
- const exports = factory();
141
- if (root) {
142
- root.CodeLabTerminal = exports;
143
- root.PTYTerminalEngine = exports.PTYTerminalEngine;
144
- root.createPTYTerminalEngine = exports.createPTYTerminalEngine;
145
- root.createTerminal = exports.createTerminal;
146
- root.ansiToHtml = exports.ansiToHtml;
147
- root.parseAnsiToHtml = exports.parseAnsiToHtml;
148
- }
149
- if (typeof module !== 'undefined' && module.exports) {
150
- module.exports = exports;
151
- } else if (typeof define === 'function' && define.amd) {
152
- define([], function () { return exports; });
153
- }
154
- })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
155
- 'use strict';
156
-
157
- const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
158
- const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
159
- ? _termRoot.CodeLabLogger.createLogger()
160
- : {
161
- debug() {},
162
- info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
163
- warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
164
- error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
165
- };
166
-
167
- const ANSI_CODE_MAP = {
168
- 1: 'cl-ansi-bold',
169
- 2: 'cl-ansi-dim',
170
- 3: 'cl-ansi-italic',
171
- 4: 'cl-ansi-underline',
172
- 30: 'cl-ansi-black',
173
- 31: 'cl-ansi-red',
174
- 32: 'cl-ansi-green',
175
- 33: 'cl-ansi-yellow',
176
- 34: 'cl-ansi-blue',
177
- 35: 'cl-ansi-magenta',
178
- 36: 'cl-ansi-cyan',
179
- 37: 'cl-ansi-white',
180
- 90: 'cl-ansi-gray',
181
- 91: 'cl-ansi-bright-red',
182
- 92: 'cl-ansi-bright-green',
183
- 93: 'cl-ansi-bright-yellow',
184
- 94: 'cl-ansi-bright-blue',
185
- 95: 'cl-ansi-bright-magenta',
186
- 96: 'cl-ansi-bright-cyan',
187
- 97: 'cl-ansi-bright-white',
188
- 40: 'cl-ansi-bg-black',
189
- 41: 'cl-ansi-bg-red',
190
- 42: 'cl-ansi-bg-green',
191
- 43: 'cl-ansi-bg-yellow',
192
- 44: 'cl-ansi-bg-blue',
193
- 45: 'cl-ansi-bg-magenta',
194
- 46: 'cl-ansi-bg-cyan',
195
- 47: 'cl-ansi-bg-white',
196
- 100: 'cl-ansi-bg-bright-black',
197
- 101: 'cl-ansi-bg-bright-red',
198
- 102: 'cl-ansi-bg-bright-green',
199
- 103: 'cl-ansi-bg-bright-yellow',
200
- 104: 'cl-ansi-bg-bright-blue',
201
- 105: 'cl-ansi-bg-bright-magenta',
202
- 106: 'cl-ansi-bg-bright-cyan',
203
- 107: 'cl-ansi-bg-bright-white'
204
- };
205
-
206
- const ANSI_256_PALETTE = [
207
- '#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#e5e5e5',
208
- '#666666', '#f14c4c', '#23d18b', '#f5f543', '#3b8eea', '#d670d6', '#29b8db', '#ffffff'
209
- ];
210
-
211
- function ansi256ToColor(n) {
212
- const idx = Number(n);
213
- if (!Number.isFinite(idx) || idx < 0 || idx > 255) return null;
214
- if (idx < 16) return ANSI_256_PALETTE[idx];
215
- if (idx < 232) {
216
- const c = idx - 16;
217
- const r = Math.floor(c / 36);
218
- const g = Math.floor((c % 36) / 6);
219
- const b = c % 6;
220
- const toChannel = v => (v === 0 ? 0 : 55 + v * 40);
221
- return `rgb(${toChannel(r)}, ${toChannel(g)}, ${toChannel(b)})`;
222
- }
223
- const gray = 8 + (idx - 232) * 10;
224
- return `rgb(${gray}, ${gray}, ${gray})`;
225
- }
226
-
227
- function escapeHtml(str) {
228
- if (str == null) return '';
229
- return String(str)
230
- .replace(/&/g, '&amp;')
231
- .replace(/</g, '&lt;')
232
- .replace(/>/g, '&gt;')
233
- .replace(/"/g, '&quot;')
234
- .replace(/'/g, '&#39;');
235
- }
236
-
237
- function resolveAnsiControlCodes(raw) {
238
- if (!raw) return '';
239
- const s = String(raw);
240
- if (!s.includes('\x1b') && !s.includes('\r')) return s;
241
-
242
- let text = s;
243
- const lastClearScreen = text.lastIndexOf('\x1b[2J');
244
- if (lastClearScreen !== -1) {
245
- text = text.slice(lastClearScreen + 4);
246
- text = text.replace(/^\x1b\[(?:1;1)?H/, '');
247
- }
248
-
249
- text = text.replace(/\r\n/g, '\n');
250
- const rawLines = text.split('\n');
251
- const resolvedLines = [];
252
-
253
- for (let l = 0; l < rawLines.length; l++) {
254
- let line = rawLines[l];
255
-
256
- while (/\x1b\[(?:1)?A/.test(line)) {
257
- const upMatch = /\x1b\[(?:1)?A/.exec(line);
258
- const beforeUp = line.slice(0, upMatch.index);
259
- let afterUp = line.slice(upMatch.index + upMatch[0].length);
260
- if (resolvedLines.length > 0) {
261
- if (afterUp.includes('\x1b[2K')) {
262
- afterUp = afterUp.slice(afterUp.lastIndexOf('\x1b[2K') + 4);
263
- resolvedLines[resolvedLines.length - 1] = afterUp;
264
- } else if (afterUp.includes('\r')) {
265
- const parts = afterUp.split('\r');
266
- resolvedLines[resolvedLines.length - 1] = parts[parts.length - 1];
267
- } else {
268
- resolvedLines[resolvedLines.length - 1] = afterUp;
269
- }
270
- line = beforeUp;
271
- } else {
272
- line = beforeUp + afterUp;
273
- }
274
- }
275
-
276
- if (line.includes('\x1b[2K')) {
277
- const idx = line.lastIndexOf('\x1b[2K');
278
- line = line.slice(idx + 4);
279
- }
280
-
281
- if (line.includes('\r')) {
282
- const parts = line.split('\r');
283
- line = parts[parts.length - 1];
284
- }
285
-
286
- line = line.replace(/\x1b\[[0]?K/g, '');
287
- line = line.replace(/\x1b\[(?:1)?G/g, '');
288
- resolvedLines.push(line);
289
- }
290
-
291
- return resolvedLines.join('\n');
292
- }
293
-
294
- function ansiToHtml(str) {
295
- if (!str) return '';
296
- const resolved = resolveAnsiControlCodes(String(str));
297
- if (!resolved.includes('\x1b[')) {
298
- return escapeHtml(resolved);
299
- }
300
-
301
- // Strip non-color cursor control sequences without stripping lowercase 'm' SGR codes
302
- const cleaned = resolved.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g, '');
303
-
304
- const tokenRegex = /\x1b\[([0-9;]*)m/g;
305
- let result = '';
306
- let lastIdx = 0;
307
- let match;
308
-
309
- const state = {
310
- bold: false,
311
- dim: false,
312
- italic: false,
313
- underline: false,
314
- fgClass: null,
315
- bgClass: null,
316
- fgColor: null,
317
- bgColor: null
318
- };
319
-
320
- const resetState = () => {
321
- state.bold = false;
322
- state.dim = false;
323
- state.italic = false;
324
- state.underline = false;
325
- state.fgClass = null;
326
- state.bgClass = null;
327
- state.fgColor = null;
328
- state.bgColor = null;
329
- };
330
-
331
- const renderChunk = (rawText) => {
332
- if (!rawText) return '';
333
- const escaped = escapeHtml(rawText);
334
- const classes = [];
335
- if (state.bold) classes.push('cl-ansi-bold');
336
- if (state.dim) classes.push('cl-ansi-dim');
337
- if (state.italic) classes.push('cl-ansi-italic');
338
- if (state.underline) classes.push('cl-ansi-underline');
339
- if (state.fgClass) classes.push(state.fgClass);
340
- if (state.bgClass) classes.push(state.bgClass);
341
-
342
- const styles = [];
343
- if (state.fgColor) styles.push(`color:${state.fgColor}`);
344
- if (state.bgColor) styles.push(`background-color:${state.bgColor}`);
345
-
346
- if (classes.length === 0 && styles.length === 0) {
347
- return escaped;
348
- }
349
- const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
350
- const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
351
- return `<span${classAttr}${styleAttr}>${escaped}</span>`;
352
- };
353
-
354
- while ((match = tokenRegex.exec(cleaned)) !== null) {
355
- const rawText = cleaned.slice(lastIdx, match.index);
356
- if (rawText) result += renderChunk(rawText);
357
- lastIdx = tokenRegex.lastIndex;
358
-
359
- const codes = match[1] ? match[1].split(';').map(Number) : [0];
360
- for (let i = 0; i < codes.length; i++) {
361
- const code = codes[i];
362
- if (code === 0 || Number.isNaN(code)) {
363
- resetState();
364
- } else if (code === 1) {
365
- state.bold = true;
366
- } else if (code === 2) {
367
- state.dim = true;
368
- } else if (code === 3) {
369
- state.italic = true;
370
- } else if (code === 4) {
371
- state.underline = true;
372
- } else if (code === 22) {
373
- state.bold = false;
374
- state.dim = false;
375
- } else if (code === 23) {
376
- state.italic = false;
377
- } else if (code === 24) {
378
- state.underline = false;
379
- } else if (code === 39) {
380
- state.fgClass = null;
381
- state.fgColor = null;
382
- } else if (code === 49) {
383
- state.bgClass = null;
384
- state.bgColor = null;
385
- } else if ((code === 38 || code === 48) && codes[i + 1] === 5 && i + 2 < codes.length) {
386
- const color = ansi256ToColor(codes[i + 2]);
387
- if (color) {
388
- if (code === 38) {
389
- state.fgClass = null;
390
- state.fgColor = color;
391
- } else {
392
- state.bgClass = null;
393
- state.bgColor = color;
394
- }
395
- }
396
- i += 2;
397
- } else if ((code === 38 || code === 48) && codes[i + 1] === 2 && i + 4 < codes.length) {
398
- const r = Math.max(0, Math.min(255, Number(codes[i + 2]) || 0));
399
- const g = Math.max(0, Math.min(255, Number(codes[i + 3]) || 0));
400
- const b = Math.max(0, Math.min(255, Number(codes[i + 4]) || 0));
401
- const color = `rgb(${r}, ${g}, ${b})`;
402
- if (code === 38) {
403
- state.fgClass = null;
404
- state.fgColor = color;
405
- } else {
406
- state.bgClass = null;
407
- state.bgColor = color;
408
- }
409
- i += 4;
410
- } else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
411
- state.fgClass = ANSI_CODE_MAP[code] || null;
412
- state.fgColor = null;
413
- } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
414
- state.bgClass = ANSI_CODE_MAP[code] || null;
415
- state.bgColor = null;
416
- }
417
- }
418
- }
419
-
420
- const remaining = cleaned.slice(lastIdx);
421
- if (remaining) result += renderChunk(remaining);
422
- return result;
423
- }
424
-
425
- const parseAnsiToHtml = ansiToHtml;
426
-
427
- const MAX_SCROLLBACK = 2000;
428
- const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
429
-
430
- function sanitizeLogType(type) {
431
- const t = String(type || 'stdout').trim();
432
- return VALID_LOG_TYPES.has(t) ? t : 'stdout';
433
- }
434
-
435
- class PTYTerminalEngine {
436
- constructor(container, options = {}) {
437
- if (
438
- container &&
439
- typeof container === 'object' &&
440
- typeof container.querySelector !== 'function' &&
441
- typeof container.appendChild !== 'function' &&
442
- arguments.length === 1
443
- ) {
444
- options = container;
445
- container = options.container || null;
446
- }
447
- this.container = container || null;
448
- this.options = options || {};
449
- this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
450
- ? this.options.maxScrollback
451
- : MAX_SCROLLBACK;
452
- this.maxHistory = typeof this.options.maxHistory === 'number' && this.options.maxHistory > 0
453
- ? this.options.maxHistory
454
- : 1000;
455
- this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
456
- this.cwd = this.options.cwd || '/workspace';
457
- this.replMode = Boolean(this.options.replMode);
458
- this.promptOverride = this.options.prompt || null;
459
- this.history = Array.isArray(this.options.history) ? this.options.history : [];
460
- this.historyIdx = -1;
461
- this.savedBuffer = '';
462
- this.buffer = '';
463
- this.cursor = 0;
464
- this.searchMode = false;
465
- this.searchQuery = '';
466
- this.searchMatchIdx = -1;
467
- this._readLineQueue = [];
468
- this.isBusy = false;
469
- this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
470
- this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
471
- this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
472
- this.onInterrupt = typeof this.options.onInterrupt === 'function' ? this.options.onInterrupt : null;
473
-
474
- // Stream & active line buffering state
475
- this._activeLineCommitted = true;
476
- this._cursorCol = 0;
477
- this._pendingEscape = '';
478
- this._targetLineIdx = -1;
479
- this._needsRewrite = false;
480
- this._activeLineEl = null;
481
-
482
- this._mounted = false;
483
- this._listeners = [];
484
-
485
- if (this.container) {
486
- this.mount(this.container);
487
- }
488
- }
489
-
490
- getPrompt() {
491
- if (this.promptOverride) return this.promptOverride;
492
- if (this.replMode) return '> ';
493
- const cwd = this.cwd || '/workspace';
494
- return `codelab:${cwd}$ `;
495
- }
496
-
497
- setPrompt(p) {
498
- this.promptOverride = p;
499
- this.updateActiveLine();
500
- }
501
-
502
- setCwd(cwd) {
503
- this.cwd = cwd;
504
- this.updateActiveLine();
505
- }
506
-
507
- setReplMode(enabled) {
508
- this.replMode = Boolean(enabled);
509
- this.updateActiveLine();
510
- }
511
-
512
- writeStreamChunk(data, type = 'stdout') {
513
- let str = String(data != null ? data : '');
514
- if (!str) return;
515
-
516
- if (this._pendingEscape) {
517
- str = this._pendingEscape + str;
518
- this._pendingEscape = '';
519
- }
520
-
521
- let modified = false;
522
- let i = 0;
523
-
524
- while (i < str.length) {
525
- if (str[i] === '\x1b') {
526
- const rest = str.slice(i);
527
- if (/^\x1b(?:\[[0-9;?]*)?$/.test(rest)) {
528
- this._pendingEscape = rest;
529
- break;
530
- }
531
-
532
- const csiMatch = /^\x1b\[([0-9;?]*)([A-Za-z])/.exec(rest);
533
- if (csiMatch) {
534
- const params = csiMatch[1];
535
- const cmd = csiMatch[2];
536
- const seq = csiMatch[0];
537
- i += seq.length;
538
-
539
- if (cmd === 'K') {
540
- const cur = this._getActiveLine(type);
541
- if (params === '2') {
542
- cur.text = '';
543
- this._cursorCol = 0;
544
- this._needsRewrite = false;
545
- } else {
546
- cur.text = cur.text.slice(0, this._cursorCol);
547
- this._needsRewrite = false;
548
- }
549
- modified = true;
550
- } else if (cmd === 'A') {
551
- const count = parseInt(params, 10) || 1;
552
- if (this.logs.length > 0) {
553
- const baseIdx = this._activeLineCommitted ? this.logs.length : this.logs.length - 1;
554
- this._targetLineIdx = Math.max(0, baseIdx - count);
555
- this._activeLineCommitted = false;
556
- this._cursorCol = 0;
557
- this._needsRewrite = false;
558
- const targetLine = this.logs[this._targetLineIdx];
559
- if (targetLine) targetLine.text = '';
560
- this._activeLineEl = null;
561
- }
562
- } else if (cmd === 'G') {
563
- this._cursorCol = 0;
564
- this._needsRewrite = true;
565
- } else if (cmd === 'J' && params === '2') {
566
- this.clear();
567
- } else if (cmd === 'm') {
568
- const cur = this._getActiveLine(type);
569
- cur.text += seq;
570
- modified = true;
571
- }
572
- continue;
573
- }
574
- }
575
-
576
- const ch = str[i];
577
- if (ch === '\r') {
578
- this._cursorCol = 0;
579
- this._needsRewrite = true;
580
- i++;
581
- } else if (ch === '\n') {
582
- const cur = this._getActiveLine(type);
583
- cur.text += '\n';
584
- this._activeLineCommitted = true;
585
- this._cursorCol = 0;
586
- this._targetLineIdx = -1;
587
- this._needsRewrite = false;
588
- this._activeLineEl = null;
589
- modified = true;
590
- i++;
591
- } else {
592
- const cur = this._getActiveLine(type);
593
- if (this._needsRewrite && this._cursorCol === 0 && cur.text.length > 0 && !cur.text.endsWith('\n')) {
594
- cur.text = ch;
595
- this._needsRewrite = false;
596
- } else {
597
- cur.text += ch;
598
- }
599
- this._cursorCol++;
600
- modified = true;
601
- i++;
602
- }
603
- }
604
-
605
- if (modified) {
606
- this._updateActiveDomLine();
607
- }
608
- this._scrollToBottom();
609
- }
610
-
611
- write(data, type = 'stdout') {
612
- this.writeStreamChunk(data, type);
613
- }
614
-
615
- writeln(data, type = 'stdout') {
616
- this.writeStreamChunk(String(data) + '\n', type);
617
- }
618
-
619
- isCommandRunning() {
620
- return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
621
- }
622
-
623
- _pushLog(entry) {
624
- const normalized = {
625
- type: sanitizeLogType(entry && entry.type),
626
- text: String(entry && entry.text != null ? entry.text : '')
627
- };
628
- this.logs.push(normalized);
629
- if (this.logs.length > this.maxScrollback) {
630
- const excess = this.logs.length - this.maxScrollback;
631
- this.logs.splice(0, excess);
632
- if (this._targetLineIdx >= 0) {
633
- this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
634
- }
635
- if (this.container && typeof this.container.querySelector === 'function') {
636
- const logEl = this.container.querySelector('#cl-terminal-log');
637
- if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
638
- while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
639
- logEl.removeChild(logEl.firstChild);
640
- }
641
- }
642
- }
643
- }
644
- return normalized;
645
- }
646
-
647
- _getActiveLine(type) {
648
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
649
- return this.logs[this._targetLineIdx];
650
- }
651
- if (this._activeLineCommitted || this.logs.length === 0) {
652
- const newLine = this._pushLog({ text: '', type });
653
- this._activeLineCommitted = false;
654
- this._cursorCol = 0;
655
- this._targetLineIdx = this.logs.length - 1;
656
- this._needsRewrite = false;
657
- this._appendDomLine(newLine);
658
- return newLine;
659
- }
660
- this._targetLineIdx = this.logs.length - 1;
661
- return this.logs[this.logs.length - 1];
662
- }
663
-
664
- _appendDomLine(line) {
665
- if (!this.container || typeof document === 'undefined') return;
666
- const logEl = this.container.querySelector('#cl-terminal-log');
667
- if (!logEl) return;
668
- const lineEl = document.createElement('div');
669
- lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
670
- lineEl.innerHTML = ansiToHtml(line.text);
671
- logEl.appendChild(lineEl);
672
- this._activeLineEl = lineEl;
673
- }
674
-
675
- _updateActiveDomLine() {
676
- if (!this.container || typeof document === 'undefined') return;
677
- const line = this._getActiveLineSync();
678
- if (!line) return;
679
- let lineEl = this._activeLineEl;
680
- if (!lineEl || !lineEl.parentNode) {
681
- const logEl = this.container.querySelector('#cl-terminal-log');
682
- if (logEl) {
683
- if (this._targetLineIdx >= 0 && this._targetLineIdx < logEl.children.length) {
684
- lineEl = logEl.children[this._targetLineIdx];
685
- } else {
686
- lineEl = logEl.children[logEl.children.length - 1];
687
- }
688
- this._activeLineEl = lineEl;
689
- }
690
- }
691
- if (lineEl) {
692
- lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
693
- lineEl.innerHTML = ansiToHtml(line.text);
694
- }
695
- }
696
-
697
- _getActiveLineSync() {
698
- if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
699
- return this.logs[this._targetLineIdx];
700
- }
701
- return this.logs[this.logs.length - 1] || null;
702
- }
703
-
704
- _scrollToBottom() {
705
- if (!this.container) return;
706
- const surface = this.container.querySelector('#cl-terminal-surface') || this.container;
707
- if (surface && typeof surface.scrollTop === 'number' && typeof surface.scrollHeight === 'number') {
708
- surface.scrollTop = surface.scrollHeight;
709
- }
710
- }
711
-
712
- clear() {
713
- this.logs.length = 0;
714
- this._activeLineCommitted = true;
715
- this._cursorCol = 0;
716
- this._targetLineIdx = -1;
717
- this._needsRewrite = false;
718
- this._activeLineEl = null;
719
- if (this.container && typeof this.container.querySelector === 'function') {
720
- const logEl = this.container.querySelector('#cl-terminal-log');
721
- if (logEl) {
722
- logEl.innerHTML = '';
723
- }
724
- }
725
- }
726
-
727
- getHistory() {
728
- return [...this.history];
729
- }
730
-
731
- _activateNextReadLine() {
732
- if (!this._readLineQueue || this._readLineQueue.length === 0) return;
733
- const head = this._readLineQueue[0];
734
- if (head && typeof head === 'object' && !head._activated) {
735
- head._activated = true;
736
- head.prevPrompt = this.promptOverride;
737
- if (head.promptText) {
738
- this.promptOverride = head.promptText;
739
- }
740
- }
741
- }
742
-
743
- _drainReadLineQueue(result = null) {
744
- if (!Array.isArray(this._readLineQueue) || this._readLineQueue.length === 0) return;
745
- const queued = this._readLineQueue.splice(0, this._readLineQueue.length);
746
- let restoredPrompt = undefined;
747
- for (const entry of queued) {
748
- if (entry && typeof entry === 'object' && entry._activated && restoredPrompt === undefined) {
749
- restoredPrompt = entry.prevPrompt;
750
- }
751
- if (entry && typeof entry.cleanup === 'function') {
752
- entry.cleanup();
753
- }
754
- }
755
- if (restoredPrompt !== undefined) {
756
- this.promptOverride = restoredPrompt;
757
- }
758
- for (const entry of queued) {
759
- if (typeof entry === 'function') {
760
- try { entry(result); } catch (err) { _terminalLogger.debug('readLine callback threw during drain.', err); }
761
- } else if (entry && typeof entry.resolve === 'function') {
762
- try { entry.resolve(result); } catch (err) { _terminalLogger.debug('readLine resolve threw during drain.', err); }
763
- }
764
- }
765
- }
766
-
767
- readLine(promptText = '', options = {}) {
768
- if (options && options.signal && options.signal.aborted) {
769
- return Promise.resolve(null);
770
- }
771
- return new Promise((resolve) => {
772
- const item = {
773
- promptText: String(promptText || ''),
774
- prevPrompt: null,
775
- _activated: false,
776
- cleanup: null,
777
- resolve
778
- };
779
- if (options && options.signal && typeof options.signal.addEventListener === 'function') {
780
- const onAbort = () => {
781
- const idx = this._readLineQueue.indexOf(item);
782
- if (idx !== -1) {
783
- this._readLineQueue.splice(idx, 1);
784
- if (item._activated) {
785
- this.promptOverride = item.prevPrompt;
786
- this._activateNextReadLine();
787
- }
788
- this.updateActiveLine();
789
- resolve(null);
790
- }
791
- };
792
- options.signal.addEventListener('abort', onAbort, { once: true });
793
- item.cleanup = () => {
794
- try { options.signal.removeEventListener('abort', onAbort); } catch (err) { _terminalLogger.debug('readLine abort listener cleanup failed.', err); }
795
- };
796
- }
797
- this._readLineQueue.push(item);
798
- this._activateNextReadLine();
799
- this.updateActiveLine();
800
- });
801
- }
802
-
803
- focus() {
804
- if (!this.container || typeof this.container.querySelector !== 'function') return;
805
- const input = this.container.querySelector('#cl-repl-input');
806
- if (input && typeof input.focus === 'function') {
807
- try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
808
- }
809
- }
810
-
811
- mount(container) {
812
- if (typeof container === 'string' && typeof document !== 'undefined') {
813
- container = document.querySelector(container);
814
- }
815
- this.container = container || null;
816
- if (!this.container || typeof this.container.querySelector !== 'function') {
817
- this._mounted = false;
818
- return;
819
- }
820
- this._mounted = true;
821
- this.render();
822
- }
823
-
824
- _cleanupListeners() {
825
- if (!Array.isArray(this._listeners)) {
826
- this._listeners = [];
827
- return;
828
- }
829
- for (const entry of this._listeners) {
830
- if (typeof entry === 'function') {
831
- try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
832
- } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
833
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
834
- }
835
- }
836
- this._listeners = [];
837
- }
838
-
839
- destroy() {
840
- this._drainReadLineQueue(null);
841
- this._cleanupListeners();
842
- this._mounted = false;
843
- }
844
-
845
- _addListener(target, type, handler) {
846
- if (target && typeof target.addEventListener === 'function') {
847
- target.addEventListener(type, handler);
848
- this._listeners.push({ target, type, handler });
849
- }
850
- }
851
-
852
- _bindEvents() {
853
- this._cleanupListeners();
854
- if (!this.container || typeof this.container.querySelector !== 'function') return;
855
- const termSurface = this.container.querySelector('#cl-terminal-surface') || this.container;
856
- const input = this.container.querySelector('#cl-repl-input');
857
- const form = this.container.querySelector('#cl-repl-form');
858
-
859
- if (termSurface) {
860
- this._addListener(termSurface, 'click', (e) => {
861
- if (e && e.target === input) return;
862
- const hasSelection = typeof window !== 'undefined' && window.getSelection && String(window.getSelection());
863
- if (!hasSelection) this.focus();
864
- });
865
- }
866
-
867
- if (input) {
868
- this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
869
- this._addListener(input, 'input', () => {
870
- if (this.isCommandRunning()) {
871
- input.value = '';
872
- return;
873
- }
874
- if (input.value !== this.buffer) {
875
- this.buffer = input.value;
876
- this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
877
- this.updateActiveLine();
878
- }
879
- });
880
- }
881
-
882
- if (form) {
883
- this._addListener(form, 'submit', (e) => {
884
- if (e && typeof e.preventDefault === 'function') e.preventDefault();
885
- this.submitLine();
886
- });
887
- }
888
- }
889
-
890
- _findReverseSearchMatch(query, startIdx) {
891
- if (!query || !this.history.length) return -1;
892
- const from = typeof startIdx === 'number' ? Math.min(startIdx, this.history.length - 1) : this.history.length - 1;
893
- for (let i = from; i >= 0; i--) {
894
- if (this.history[i] && this.history[i].includes(query)) {
895
- return i;
896
- }
897
- }
898
- return -1;
899
- }
900
-
901
- handleKeyDown(e) {
902
- if (!e) return;
903
- if (this.onKey) {
904
- try {
905
- const res = this.onKey(e);
906
- if (res === false) return;
907
- } catch (err) {
908
- _terminalLogger.warn('Terminal onKey callback threw.', err);
909
- }
910
- }
911
-
912
- const key = e.key;
913
- const isCtrl = Boolean(e.ctrlKey || e.metaKey);
914
-
915
- if (isCtrl && (key === 'l' || key === 'L')) {
916
- if (e.preventDefault) e.preventDefault();
917
- this.clear();
918
- return;
919
- }
920
-
921
- if (isCtrl && (key === 'c' || key === 'C')) {
922
- if (e.preventDefault) e.preventDefault();
923
- const wasBusy = this.isBusy || (this._readLineQueue && this._readLineQueue.length > 0);
924
- this.isBusy = false;
925
- this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
926
- this.buffer = '';
927
- this.cursor = 0;
928
- this.historyIdx = -1;
929
- this._drainReadLineQueue(null);
930
- if (this.replMode) {
931
- this.replMode = false;
932
- }
933
- if (this.onInterrupt) {
934
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
935
- }
936
- this.render();
937
- return;
938
- }
939
-
940
- if (this.isCommandRunning()) {
941
- if (e.preventDefault) e.preventDefault();
942
- return;
943
- }
944
-
945
- if (isCtrl && (key === 'r' || key === 'R')) {
946
- if (e.preventDefault) e.preventDefault();
947
- if (!this.searchMode) {
948
- this.searchMode = true;
949
- this.searchQuery = '';
950
- this.searchMatchIdx = -1;
951
- } else if (this.searchQuery) {
952
- const nextStart = this.searchMatchIdx > 0 ? this.searchMatchIdx - 1 : this.history.length - 1;
953
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, nextStart);
954
- if (matchIdx !== -1) {
955
- this.searchMatchIdx = matchIdx;
956
- this.buffer = this.history[matchIdx];
957
- this.cursor = this.buffer.length;
958
- }
959
- }
960
- this.updateActiveLine();
961
- return;
962
- }
963
-
964
- if (this.searchMode) {
965
- if (key === 'Escape' || (isCtrl && (key === 'g' || key === 'G'))) {
966
- if (e.preventDefault) e.preventDefault();
967
- this.searchMode = false;
968
- this.searchQuery = '';
969
- this.searchMatchIdx = -1;
970
- this.updateActiveLine();
971
- return;
972
- }
973
- if (key === 'Backspace') {
974
- if (e.preventDefault) e.preventDefault();
975
- this.searchQuery = this.searchQuery.slice(0, -1);
976
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
977
- this.searchMatchIdx = matchIdx;
978
- if (matchIdx !== -1) {
979
- this.buffer = this.history[matchIdx];
980
- this.cursor = this.buffer.length;
981
- }
982
- this.updateActiveLine();
983
- return;
984
- }
985
- if (key === 'Enter') {
986
- if (e.preventDefault) e.preventDefault();
987
- this.searchMode = false;
988
- this.searchQuery = '';
989
- this.searchMatchIdx = -1;
990
- this.submitLine();
991
- return;
992
- }
993
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
994
- if (e.preventDefault) e.preventDefault();
995
- this.searchQuery += key;
996
- const matchIdx = this._findReverseSearchMatch(this.searchQuery, this.history.length - 1);
997
- this.searchMatchIdx = matchIdx;
998
- if (matchIdx !== -1) {
999
- this.buffer = this.history[matchIdx];
1000
- this.cursor = this.buffer.length;
1001
- }
1002
- this.updateActiveLine();
1003
- return;
1004
- }
1005
- this.searchMode = false;
1006
- this.searchQuery = '';
1007
- this.searchMatchIdx = -1;
1008
- }
1009
-
1010
- if (key === 'ArrowLeft') {
1011
- if (e.preventDefault) e.preventDefault();
1012
- if (this.cursor > 0) {
1013
- this.cursor--;
1014
- this.updateActiveLine();
1015
- }
1016
- return;
1017
- }
1018
-
1019
- if (key === 'ArrowRight') {
1020
- if (e.preventDefault) e.preventDefault();
1021
- if (this.cursor < this.buffer.length) {
1022
- this.cursor++;
1023
- this.updateActiveLine();
1024
- }
1025
- return;
1026
- }
1027
-
1028
- if (key === 'Home' || (isCtrl && (key === 'a' || key === 'A'))) {
1029
- if (e.preventDefault) e.preventDefault();
1030
- this.cursor = 0;
1031
- this.updateActiveLine();
1032
- return;
1033
- }
1034
-
1035
- if (key === 'End' || (isCtrl && (key === 'e' || key === 'E'))) {
1036
- if (e.preventDefault) e.preventDefault();
1037
- this.cursor = this.buffer.length;
1038
- this.updateActiveLine();
1039
- return;
1040
- }
1041
-
1042
- if (isCtrl && (key === 'u' || key === 'U')) {
1043
- if (e.preventDefault) e.preventDefault();
1044
- this.buffer = this.buffer.slice(this.cursor);
1045
- this.cursor = 0;
1046
- this.updateActiveLine();
1047
- return;
1048
- }
1049
-
1050
- if (isCtrl && (key === 'k' || key === 'K')) {
1051
- if (e.preventDefault) e.preventDefault();
1052
- this.buffer = this.buffer.slice(0, this.cursor);
1053
- this.updateActiveLine();
1054
- return;
1055
- }
1056
-
1057
- if (key === 'Backspace') {
1058
- if (e.preventDefault) e.preventDefault();
1059
- if (this.cursor > 0) {
1060
- this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
1061
- this.cursor--;
1062
- this.updateActiveLine();
1063
- }
1064
- return;
1065
- }
1066
-
1067
- if (key === 'Delete') {
1068
- if (e.preventDefault) e.preventDefault();
1069
- if (this.cursor < this.buffer.length) {
1070
- this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
1071
- this.updateActiveLine();
1072
- }
1073
- return;
1074
- }
1075
-
1076
- if (isCtrl && (key === 'd' || key === 'D')) {
1077
- if (this.buffer === '') {
1078
- if (e.preventDefault) e.preventDefault();
1079
- if (this.replMode) {
1080
- this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
1081
- this.replMode = false;
1082
- this.render();
1083
- return;
1084
- }
1085
- }
1086
- }
1087
-
1088
- if (key === 'ArrowUp') {
1089
- if (e.preventDefault) e.preventDefault();
1090
- if (!this.history.length) return;
1091
- if (this.historyIdx === -1) {
1092
- this.savedBuffer = this.buffer;
1093
- this.historyIdx = this.history.length - 1;
1094
- } else if (this.historyIdx > 0) {
1095
- this.historyIdx--;
1096
- }
1097
- this.buffer = this.history[this.historyIdx] || '';
1098
- this.cursor = this.buffer.length;
1099
- this.updateActiveLine();
1100
- return;
1101
- }
1102
-
1103
- if (key === 'ArrowDown') {
1104
- if (e.preventDefault) e.preventDefault();
1105
- if (this.historyIdx !== -1) {
1106
- if (this.historyIdx < this.history.length - 1) {
1107
- this.historyIdx++;
1108
- this.buffer = this.history[this.historyIdx] || '';
1109
- } else {
1110
- this.historyIdx = -1;
1111
- this.buffer = this.savedBuffer || '';
1112
- }
1113
- this.cursor = this.buffer.length;
1114
- this.updateActiveLine();
1115
- }
1116
- return;
1117
- }
1118
-
1119
- if (key === 'Tab') {
1120
- if (e.preventDefault) e.preventDefault();
1121
- this.autoComplete();
1122
- return;
1123
- }
1124
-
1125
- if (key === 'Enter') {
1126
- if (e.preventDefault) e.preventDefault();
1127
- this.submitLine();
1128
- return;
1129
- }
1130
-
1131
- // Printable character
1132
- if (key && key.length === 1 && !isCtrl && !e.altKey) {
1133
- if (e.preventDefault) e.preventDefault();
1134
- this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1135
- this.cursor++;
1136
- this.updateActiveLine();
1137
- }
1138
- }
1139
-
1140
- autoComplete() {
1141
- if (!this.getCompletions) return;
1142
- const res = this.getCompletions(this.buffer, this.cursor);
1143
- if (!res || !Array.isArray(res.matches) || res.matches.length === 0) return;
1144
-
1145
- const matches = res.matches;
1146
- if (matches.length === 1) {
1147
- const match = matches[0];
1148
- const isDir = match.endsWith('/');
1149
- const appendChar = isDir ? '' : ' ';
1150
- const before = this.buffer.slice(0, res.tokenStart);
1151
- const after = this.buffer.slice(this.cursor);
1152
- this.buffer = before + match + appendChar + after;
1153
- this.cursor = before.length + match.length + appendChar.length;
1154
- this.updateActiveLine();
1155
- } else {
1156
- // Find longest common prefix
1157
- let lcp = matches[0];
1158
- for (let i = 1; i < matches.length; i++) {
1159
- let j = 0;
1160
- while (j < lcp.length && j < matches[i].length && lcp[j] === matches[i][j]) {
1161
- j++;
1162
- }
1163
- lcp = lcp.slice(0, j);
1164
- }
1165
-
1166
- if (lcp.length > res.token.length) {
1167
- const before = this.buffer.slice(0, res.tokenStart);
1168
- const after = this.buffer.slice(this.cursor);
1169
- this.buffer = before + lcp + after;
1170
- this.cursor = before.length + lcp.length;
1171
- }
1172
-
1173
- // Print candidate matches
1174
- this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1175
- this._pushLog({ type: 'stdout', text: matches.join(' ') });
1176
- this.render();
1177
- }
1178
- }
1179
-
1180
- submitLine() {
1181
- if (this._readLineQueue && this._readLineQueue.length > 0) {
1182
- const line = this.buffer;
1183
- this.buffer = '';
1184
- this.cursor = 0;
1185
- this.historyIdx = -1;
1186
- this.searchMode = false;
1187
- this.searchQuery = '';
1188
- this.searchMatchIdx = -1;
1189
-
1190
- const entry = this._readLineQueue.shift();
1191
- if (entry && typeof entry.cleanup === 'function') {
1192
- entry.cleanup();
1193
- }
1194
- if (typeof entry === 'function') {
1195
- this.updateActiveLine();
1196
- entry(line);
1197
- } else if (entry && typeof entry.resolve === 'function') {
1198
- this.promptOverride = entry.prevPrompt;
1199
- this._activateNextReadLine();
1200
- this.updateActiveLine();
1201
- entry.resolve(line);
1202
- }
1203
- return;
1204
- }
1205
-
1206
- if (this.isBusy) {
1207
- return;
1208
- }
1209
-
1210
- const line = this.buffer;
1211
- const promptSnap = this.getPrompt();
1212
- this.buffer = '';
1213
- this.cursor = 0;
1214
- this.historyIdx = -1;
1215
- this.searchMode = false;
1216
- this.searchQuery = '';
1217
- this.searchMatchIdx = -1;
1218
-
1219
- const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1220
- this._activeLineCommitted = true;
1221
- this._cursorCol = 0;
1222
- this._targetLineIdx = -1;
1223
- this._needsRewrite = false;
1224
- this._appendDomLine(echoed);
1225
- this._activeLineEl = null;
1226
-
1227
- if (line.trim()) {
1228
- if (this.history[this.history.length - 1] !== line.trim()) {
1229
- this.history.push(line.trim());
1230
- const maxHist = typeof this.maxHistory === 'number' && this.maxHistory > 0 ? this.maxHistory : 1000;
1231
- if (this.history.length > maxHist) {
1232
- this.history.splice(0, this.history.length - maxHist);
1233
- }
1234
- }
1235
- }
1236
-
1237
- if (!this.onCommand) {
1238
- this.updateActiveLine();
1239
- return;
1240
- }
1241
-
1242
- this.isBusy = true;
1243
- this.updateActiveLine();
1244
-
1245
- let cmdResult;
1246
- try {
1247
- cmdResult = this.onCommand(line);
1248
- } catch (err) {
1249
- this.isBusy = false;
1250
- this.updateActiveLine();
1251
- throw err;
1252
- }
1253
-
1254
- if (cmdResult && typeof cmdResult.then === 'function') {
1255
- Promise.resolve(cmdResult)
1256
- .catch((err) => {
1257
- _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1258
- })
1259
- .finally(() => {
1260
- this.isBusy = false;
1261
- this.updateActiveLine();
1262
- });
1263
- } else {
1264
- this.isBusy = false;
1265
- this.updateActiveLine();
1266
- }
1267
- }
1268
-
1269
- updateActiveLine() {
1270
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1271
- const input = this.container.querySelector('#cl-repl-input');
1272
- if (input && input.value !== this.buffer) {
1273
- input.value = this.buffer;
1274
- }
1275
- const lineEl = this.container.querySelector('#cl-pty-active-line');
1276
- if (!lineEl) return;
1277
-
1278
- if (this.isCommandRunning()) {
1279
- if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1280
- if (lineEl.style) lineEl.style.display = 'none';
1281
- lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
1282
- return;
1283
- }
1284
-
1285
- if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1286
- if (lineEl.style) lineEl.style.display = '';
1287
-
1288
- const prompt = this.searchMode
1289
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1290
- : this.getPrompt();
1291
- const before = this.buffer.slice(0, this.cursor);
1292
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1293
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1294
-
1295
- 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>`;
1296
- }
1297
-
1298
- render() {
1299
- if (!this.container || typeof this.container.querySelector !== 'function') return;
1300
- const prevInput = this.container.querySelector('#cl-repl-input');
1301
- const hadFocus = Boolean(
1302
- prevInput &&
1303
- typeof document !== 'undefined' &&
1304
- document.activeElement === prevInput
1305
- );
1306
-
1307
- const logsHtml = this.logs
1308
- .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1309
- .join('');
1310
-
1311
- const busy = this.isCommandRunning();
1312
- const prompt = busy
1313
- ? ''
1314
- : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1315
- const before = busy ? '' : this.buffer.slice(0, this.cursor);
1316
- const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1317
- const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1318
- const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1319
- const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1320
-
1321
- this.container.innerHTML = `
22
+ (function(g,b){const m=b();g&&(g.CodeLabTerminal=m,g.PTYTerminalEngine=m.PTYTerminalEngine,g.createPTYTerminalEngine=m.createPTYTerminalEngine,g.createTerminal=m.createTerminal,g.ansiToHtml=m.ansiToHtml,g.parseAnsiToHtml=m.parseAnsiToHtml),typeof module<"u"&&module.exports?module.exports=m:typeof define=="function"&&define.amd&&define([],function(){return m})})(typeof globalThis<"u"?globalThis:typeof window<"u"?window:this,function(){"use strict";const g=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},b=g&&g.CodeLabLogger&&typeof g.CodeLabLogger.createLogger=="function"?g.CodeLabLogger.createLogger():{debug(){},info(...u){typeof console<"u"&&console.info&&console.info("[code-lab]",...u)},warn(...u){typeof console<"u"&&console.warn&&console.warn("[code-lab]",...u)},error(...u){typeof console<"u"&&console.error&&console.error("[code-lab]",...u)}},m={1:"cl-ansi-bold",2:"cl-ansi-dim",3:"cl-ansi-italic",4:"cl-ansi-underline",7:"cl-ansi-inverse",9:"cl-ansi-strike",30:"cl-ansi-black",31:"cl-ansi-red",32:"cl-ansi-green",33:"cl-ansi-yellow",34:"cl-ansi-blue",35:"cl-ansi-magenta",36:"cl-ansi-cyan",37:"cl-ansi-white",90:"cl-ansi-gray",91:"cl-ansi-bright-red",92:"cl-ansi-bright-green",93:"cl-ansi-bright-yellow",94:"cl-ansi-bright-blue",95:"cl-ansi-bright-magenta",96:"cl-ansi-bright-cyan",97:"cl-ansi-bright-white",40:"cl-ansi-bg-black",41:"cl-ansi-bg-red",42:"cl-ansi-bg-green",43:"cl-ansi-bg-yellow",44:"cl-ansi-bg-blue",45:"cl-ansi-bg-magenta",46:"cl-ansi-bg-cyan",47:"cl-ansi-bg-white",100:"cl-ansi-bg-bright-black",101:"cl-ansi-bg-bright-red",102:"cl-ansi-bg-bright-green",103:"cl-ansi-bg-bright-yellow",104:"cl-ansi-bg-bright-blue",105:"cl-ansi-bg-bright-magenta",106:"cl-ansi-bg-bright-cyan",107:"cl-ansi-bg-bright-white"},S=["#000000","#cd3131","#0dbc79","#e5e510","#2472c8","#bc3fbc","#11a8cd","#e5e5e5","#666666","#f14c4c","#23d18b","#f5f543","#3b8eea","#d670d6","#29b8db","#ffffff"];function I(u){const e=Number(u);if(!Number.isFinite(e)||e<0||e>255)return null;if(e<16)return S[e];if(e<232){const n=e-16,i=Math.floor(n/36),l=Math.floor(n%36/6),r=n%6,s=f=>f===0?0:55+f*40;return`rgb(${s(i)}, ${s(l)}, ${s(r)})`}const t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}function y(u){return u==null?"":String(u).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function C(u){if(!u)return"";const e=String(u);if(!e.includes("\x1B")&&!e.includes("\r"))return e;let t=e;t=t.replace(/\x1b\]8;[^;]*;[^\x07\x1b]*(?:\x07|\x1b\\)([\s\S]*?)\x1b\]8;;(?:\x07|\x1b\\)/g,"$1"),t=t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"");const n=t.lastIndexOf("\x1B[2J"),i=t.lastIndexOf("\x1B[3J"),l=t.lastIndexOf("\x1Bc"),r=Math.max(n,i,l);if(r!==-1){const p=r===l?2:4;t=t.slice(r+p),t=t.replace(/^(?:\x1b\[[23]J|\x1b\[(?:\d+;\d+)?H)+/,"")}t=t.replace(/\r\n/g,`
23
+ `);const s=t.split(`
24
+ `),f=[];for(let p=0;p<s.length;p++){let c=s[p];for(;/\x1b\[(?:1)?A/.test(c);){const a=/\x1b\[(?:1)?A/.exec(c),d=c.slice(0,a.index);let h=c.slice(a.index+a[0].length);if(f.length>0){if(h.includes("\x1B[2K"))h=h.slice(h.lastIndexOf("\x1B[2K")+4),f[f.length-1]=h;else if(h.includes("\r")){const o=h.split("\r");f[f.length-1]=o[o.length-1]}else f[f.length-1]=h;c=d}else c=d+h}if(c.includes("\x1B[2K")){const a=c.lastIndexOf("\x1B[2K");c=c.slice(a+4)}if(c.includes("\r")){const a=c.split("\r");c=a[a.length-1]}c=c.replace(/\x1b\[[0]?K/g,""),c=c.replace(/\x1b\[(?:1)?G/g,""),f.push(c)}return f.join(`
25
+ `)}function _(u){if(!u)return"";const e=C(String(u));if(!e.includes("\x1B["))return y(e);const t=e.replace(/\x1b\[[0-9;?]*(?!m)[A-Za-z]/g,""),n=/\x1b\[([0-9;]*)m/g;let i="",l=0,r;const s={bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1,strike:!1,fgClass:null,bgClass:null,fgColor:null,bgColor:null},f=()=>{s.bold=!1,s.dim=!1,s.italic=!1,s.underline=!1,s.inverse=!1,s.strike=!1,s.fgClass=null,s.bgClass=null,s.fgColor=null,s.bgColor=null},p=a=>{if(!a)return"";const d=y(a),h=[];s.bold&&h.push("cl-ansi-bold"),s.dim&&h.push("cl-ansi-dim"),s.italic&&h.push("cl-ansi-italic"),s.underline&&h.push("cl-ansi-underline"),s.inverse&&h.push("cl-ansi-inverse"),s.strike&&h.push("cl-ansi-strike"),s.fgClass&&h.push(s.fgClass),s.bgClass&&h.push(s.bgClass);const o=[];if(s.fgColor&&o.push(`color:${s.fgColor}`),s.bgColor&&o.push(`background-color:${s.bgColor}`),s.inverse&&!s.fgClass&&!s.bgClass&&o.push("filter:invert(1)"),s.strike&&o.push("text-decoration:line-through"),h.length===0&&o.length===0)return d;const v=h.length>0?` class="${h.join(" ")}"`:"",x=o.length>0?` style="${o.join(";")}"`:"";return`<span${v}${x}>${d}</span>`};for(;(r=n.exec(t))!==null;){const a=t.slice(l,r.index);a&&(i+=p(a)),l=n.lastIndex;const d=r[1]?r[1].split(";").map(Number):[0];for(let h=0;h<d.length;h++){const o=d[h];if(o===0||Number.isNaN(o))f();else if(o===1)s.bold=!0;else if(o===2)s.dim=!0;else if(o===3)s.italic=!0;else if(o===4)s.underline=!0;else if(o===7)s.inverse=!0;else if(o===9)s.strike=!0;else if(o===22)s.bold=!1,s.dim=!1;else if(o===23)s.italic=!1;else if(o===24)s.underline=!1;else if(o===27)s.inverse=!1;else if(o===29)s.strike=!1;else if(o===39)s.fgClass=null,s.fgColor=null;else if(o===49)s.bgClass=null,s.bgColor=null;else if((o===38||o===48)&&d[h+1]===5&&h+2<d.length){const v=I(d[h+2]);v&&(o===38?(s.fgClass=null,s.fgColor=v):(s.bgClass=null,s.bgColor=v)),h+=2}else if((o===38||o===48)&&d[h+1]===2&&h+4<d.length){const v=Math.max(0,Math.min(255,Number(d[h+2])||0)),x=Math.max(0,Math.min(255,Number(d[h+3])||0)),E=Math.max(0,Math.min(255,Number(d[h+4])||0)),D=`rgb(${v}, ${x}, ${E})`;o===38?(s.fgClass=null,s.fgColor=D):(s.bgClass=null,s.bgColor=D),h+=4}else o>=30&&o<=37||o>=90&&o<=97?(s.fgClass=m[o]||null,s.fgColor=null):(o>=40&&o<=47||o>=100&&o<=107)&&(s.bgClass=m[o]||null,s.bgColor=null)}}const c=t.slice(l);return c&&(i+=p(c)),i}const M=_,T=2e3,k=new Set(["stdout","stderr","system","info","warn","error","success"]);function L(u){const e=String(u||"stdout").trim();return k.has(e)?e:"stdout"}class w{constructor(e,t={}){e&&typeof e=="object"&&typeof e.querySelector!="function"&&typeof e.appendChild!="function"&&arguments.length===1&&(t=e,e=t.container||null),this.container=e||null,this.options=t||{},this.maxScrollback=typeof this.options.maxScrollback=="number"&&this.options.maxScrollback>0?this.options.maxScrollback:T,this.maxHistory=typeof this.options.maxHistory=="number"&&this.options.maxHistory>0?this.options.maxHistory:1e3,this.logs=Array.isArray(this.options.logs)?this.options.logs:[],this.cwd=this.options.cwd||"/workspace",this.replMode=!!this.options.replMode,this.promptOverride=this.options.prompt||null,this.history=Array.isArray(this.options.history)?this.options.history:[],this.historyIdx=-1,this.savedBuffer="",this.buffer="",this.cursor=0,this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1,this._readLineQueue=[],this.isBusy=!1,this.onCommand=typeof this.options.onCommand=="function"?this.options.onCommand:null,this.getCompletions=typeof this.options.getCompletions=="function"?this.options.getCompletions:null,this.onKey=typeof this.options.onKey=="function"?this.options.onKey:null,this.onInterrupt=typeof this.options.onInterrupt=="function"?this.options.onInterrupt:null,this._activeLineCommitted=!0,this._cursorCol=0,this._pendingEscape="",this._targetLineIdx=-1,this._needsRewrite=!1,this._activeLineEl=null,this._mounted=!1,this._listeners=[],this.container&&this.mount(this.container)}getPrompt(){return this.promptOverride?this.promptOverride:this.replMode?"> ":`codelab:${this.cwd||"/workspace"}$ `}setPrompt(e){this.promptOverride=e,this.updateActiveLine()}setCwd(e){this.cwd=e,this.updateActiveLine()}setReplMode(e){this.replMode=!!e,this.updateActiveLine()}writeStreamChunk(e,t="stdout"){let n=String(e??"");if(!n)return;this._pendingEscape&&(n=this._pendingEscape+n,this._pendingEscape="");let i=!1,l=0;for(;l<n.length;){if(n[l]==="\x1B"){const s=n.slice(l);if(s==="\x1B"||/^\x1b\[[0-9;?]*$/.test(s)||/^\x1b\][^\x07]*(?:\x1b)?$/.test(s)){this._pendingEscape=s;break}if(s.startsWith("\x1Bc")){l+=2,this.clear(),i=!1;continue}const f=/^\x1b\]([^\x07\x1b]*)(?:\x07|\x1b\\)/.exec(s);if(f){l+=f[0].length;continue}const p=/^\x1b\[([0-9;?]*)([A-Za-z])/.exec(s);if(p){const c=p[1],a=p[2],d=p[0];if(l+=d.length,a==="K"){const h=this._getActiveLine(t);c==="2"?(h.text="",this._cursorCol=0,this._needsRewrite=!1):(h.text=h.text.slice(0,this._cursorCol),this._needsRewrite=!1),i=!0}else if(a==="A"){const h=parseInt(c,10)||1;if(this.logs.length>0){const o=this._activeLineCommitted?this.logs.length:this.logs.length-1;this._targetLineIdx=Math.max(0,o-h),this._activeLineCommitted=!1,this._cursorCol=0,this._needsRewrite=!1;const v=this.logs[this._targetLineIdx];v&&(v.text=""),this._activeLineEl=null}}else if(a==="G"||a==="H"||a==="f")this._cursorCol=0,a==="G"&&(this._needsRewrite=!0);else if(a==="J"&&(c==="2"||c==="3"))this.clear(),i=!1;else if(a==="m"){const h=this._getActiveLine(t);h.text+=d,i=!0}continue}}const r=n[l];if(r==="\r")this._cursorCol=0,this._needsRewrite=!0,l++;else if(r===`
26
+ `){const s=this._getActiveLine(t);s.text+=`
27
+ `,this._activeLineCommitted=!0,this._cursorCol=0,this._targetLineIdx=-1,this._needsRewrite=!1,this._activeLineEl=null,i=!0,l++}else{const s=this._getActiveLine(t);this._needsRewrite&&this._cursorCol===0&&s.text.length>0&&!s.text.endsWith(`
28
+ `)?(s.text=r,this._needsRewrite=!1):s.text+=r,this._cursorCol++,i=!0,l++}}i&&this._updateActiveDomLine(),this._scrollToBottom()}write(e,t="stdout"){this.writeStreamChunk(e,t)}writeln(e,t="stdout"){this.writeStreamChunk(String(e)+`
29
+ `,t)}isCommandRunning(){return!!(this.isBusy&&(!this._readLineQueue||this._readLineQueue.length===0))}_pushLog(e){const t={type:L(e&&e.type),text:String(e&&e.text!=null?e.text:"")};if(this.logs.push(t),this.logs.length>this.maxScrollback){const n=this.logs.length-this.maxScrollback;if(this.logs.splice(0,n),this._targetLineIdx>=0&&(this._targetLineIdx=Math.max(0,this._targetLineIdx-n)),this.container&&typeof this.container.querySelector=="function"){const i=this.container.querySelector("#cl-terminal-log");if(i&&i.children&&i.children.length>this.maxScrollback)for(;i.children.length>this.maxScrollback&&typeof i.removeChild=="function"&&i.firstChild;)i.removeChild(i.firstChild)}}return t}_getActiveLine(e){if(this._targetLineIdx>=0&&this._targetLineIdx<this.logs.length)return this.logs[this._targetLineIdx];if(this._activeLineCommitted||this.logs.length===0){const t=this._pushLog({text:"",type:e});return this._activeLineCommitted=!1,this._cursorCol=0,this._targetLineIdx=this.logs.length-1,this._needsRewrite=!1,this._appendDomLine(t),t}return this._targetLineIdx=this.logs.length-1,this.logs[this.logs.length-1]}_appendDomLine(e){if(!this.container||typeof document>"u")return;const t=this.container.querySelector("#cl-terminal-log");if(!t)return;const n=document.createElement("div");n.className="codelab-log-line "+L(e.type),n.innerHTML=_(e.text),t.appendChild(n),this._activeLineEl=n}_updateActiveDomLine(){if(!this.container||typeof document>"u")return;const e=this._getActiveLineSync();if(!e)return;let t=this._activeLineEl;if(!t||!t.parentNode){const n=this.container.querySelector("#cl-terminal-log");n&&(this._targetLineIdx>=0&&this._targetLineIdx<n.children.length?t=n.children[this._targetLineIdx]:t=n.children[n.children.length-1],this._activeLineEl=t)}t&&(t.className="codelab-log-line "+L(e.type),t.innerHTML=_(e.text))}_getActiveLineSync(){return this._targetLineIdx>=0&&this._targetLineIdx<this.logs.length?this.logs[this._targetLineIdx]:this.logs[this.logs.length-1]||null}_scrollToBottom(){if(!this.container)return;const e=this.container.querySelector("#cl-terminal-surface")||this.container;e&&typeof e.scrollTop=="number"&&typeof e.scrollHeight=="number"&&(e.scrollTop=e.scrollHeight)}clear(){if(this.logs.length=0,this._activeLineCommitted=!0,this._cursorCol=0,this._targetLineIdx=-1,this._needsRewrite=!1,this._activeLineEl=null,this.container&&typeof this.container.querySelector=="function"){const e=this.container.querySelector("#cl-terminal-log");e&&(e.innerHTML="")}}getHistory(){return[...this.history]}_activateNextReadLine(){if(!this._readLineQueue||this._readLineQueue.length===0)return;const e=this._readLineQueue[0];e&&typeof e=="object"&&!e._activated&&(e._activated=!0,e.prevPrompt=this.promptOverride,e.promptText&&(this.promptOverride=e.promptText))}_drainReadLineQueue(e=null){if(!Array.isArray(this._readLineQueue)||this._readLineQueue.length===0)return;const t=this._readLineQueue.splice(0,this._readLineQueue.length);let n;for(const i of t)i&&typeof i=="object"&&i._activated&&n===void 0&&(n=i.prevPrompt),i&&typeof i.cleanup=="function"&&i.cleanup();n!==void 0&&(this.promptOverride=n);for(const i of t)if(typeof i=="function")try{i(e)}catch(l){b.debug("readLine callback threw during drain.",l)}else if(i&&typeof i.resolve=="function")try{i.resolve(e)}catch(l){b.debug("readLine resolve threw during drain.",l)}}readLine(e="",t={}){return t&&t.signal&&t.signal.aborted?Promise.resolve(null):new Promise(n=>{const i={promptText:String(e||""),prevPrompt:null,_activated:!1,cleanup:null,resolve:n};if(t&&t.signal&&typeof t.signal.addEventListener=="function"){const l=()=>{const r=this._readLineQueue.indexOf(i);r!==-1&&(this._readLineQueue.splice(r,1),i._activated&&(this.promptOverride=i.prevPrompt,this._activateNextReadLine()),this.updateActiveLine(),n(null))};t.signal.addEventListener("abort",l,{once:!0}),i.cleanup=()=>{try{t.signal.removeEventListener("abort",l)}catch(r){b.debug("readLine abort listener cleanup failed.",r)}}}this._readLineQueue.push(i),this._activateNextReadLine(),this.updateActiveLine()})}focus(){if(!this.container||typeof this.container.querySelector!="function")return;const e=this.container.querySelector("#cl-repl-input");if(e&&typeof e.focus=="function")try{e.focus()}catch(t){b.debug("Terminal input focus skipped.",t)}}mount(e){if(typeof e=="string"&&typeof document<"u"&&(e=document.querySelector(e)),this.container=e||null,!this.container||typeof this.container.querySelector!="function"){this._mounted=!1;return}this._mounted=!0,this.render()}_cleanupListeners(){if(!Array.isArray(this._listeners)){this._listeners=[];return}for(const e of this._listeners)if(typeof e=="function")try{e()}catch(t){b.debug("Terminal listener cleanup callback failed.",t)}else if(e&&e.target&&typeof e.target.removeEventListener=="function")try{e.target.removeEventListener(e.type,e.handler)}catch(t){b.debug("Terminal removeEventListener failed.",t)}this._listeners=[]}destroy(){this._drainReadLineQueue(null),this._cleanupListeners(),this._mounted=!1}_addListener(e,t,n){e&&typeof e.addEventListener=="function"&&(e.addEventListener(t,n),this._listeners.push({target:e,type:t,handler:n}))}_bindEvents(){if(this._cleanupListeners(),!this.container||typeof this.container.querySelector!="function")return;const e=this.container.querySelector("#cl-terminal-surface")||this.container,t=this.container.querySelector("#cl-repl-input"),n=this.container.querySelector("#cl-repl-form");e&&this._addListener(e,"click",i=>{if(i&&i.target===t)return;typeof window<"u"&&window.getSelection&&String(window.getSelection())||this.focus()}),t&&(this._addListener(t,"keydown",i=>this.handleKeyDown(i)),this._addListener(t,"paste",i=>{const l=i&&i.clipboardData&&typeof i.clipboardData.getData=="function"?i.clipboardData.getData("text/plain"):"";l&&(i.preventDefault&&i.preventDefault(),this.pasteText(l))}),this._addListener(t,"input",()=>{if(this.isCommandRunning()){t.value="";return}t.value!==this.buffer&&(this.buffer=t.value,this.cursor=typeof t.selectionStart=="number"?t.selectionStart:this.buffer.length,this.updateActiveLine())})),n&&this._addListener(n,"submit",i=>{i&&typeof i.preventDefault=="function"&&i.preventDefault(),this.submitLine()})}_findReverseSearchMatch(e,t){if(!e||!this.history.length)return-1;const n=typeof t=="number"?Math.min(t,this.history.length-1):this.history.length-1;for(let i=n;i>=0;i--)if(this.history[i]&&this.history[i].includes(e))return i;return-1}handleKeyDown(e){if(!e)return;if(this.onKey)try{if(this.onKey(e)===!1)return}catch(r){b.warn("Terminal onKey callback threw.",r)}const t=e.key,n=!!(e.ctrlKey&&!e.metaKey),i=!!(e.metaKey&&!e.ctrlKey),l=!!(e.ctrlKey||e.metaKey);if(l&&(t==="l"||t==="L")||i&&(t==="k"||t==="K")){e.preventDefault&&e.preventDefault(),this.clear();return}if(!(i&&(t==="c"||t==="C"))&&!(i&&(t==="v"||t==="V"))){if(n&&(t==="c"||t==="C")){if(e.shiftKey||!this.isBusy&&typeof window<"u"&&typeof window.getSelection=="function"&&String(window.getSelection()).length>0)return;e.preventDefault&&e.preventDefault();const s=this.isBusy||this._readLineQueue&&this._readLineQueue.length>0;this.isBusy=!1;const f=this._pushLog({type:"system",text:s?"^C":`${this.getPrompt()}${this.buffer}^C`});if(this._appendDomLine(f),this._activeLineCommitted=!0,this._activeLineEl=null,this.buffer="",this.cursor=0,this.historyIdx=-1,this._drainReadLineQueue(null),this.replMode&&(this.replMode=!1),this.onInterrupt)try{this.onInterrupt()}catch(p){b.warn("Terminal onInterrupt callback threw.",p)}this.updateActiveLine(),this._scrollToBottom();return}if(this.isCommandRunning()){e.preventDefault&&e.preventDefault();return}if(l&&(t==="r"||t==="R")){if(e.preventDefault&&e.preventDefault(),!this.searchMode)this.searchMode=!0,this.searchQuery="",this.searchMatchIdx=-1;else if(this.searchQuery){const r=this.searchMatchIdx>0?this.searchMatchIdx-1:this.history.length-1,s=this._findReverseSearchMatch(this.searchQuery,r);s!==-1&&(this.searchMatchIdx=s,this.buffer=this.history[s],this.cursor=this.buffer.length)}this.updateActiveLine();return}if(this.searchMode){if(t==="Escape"||l&&(t==="g"||t==="G")){e.preventDefault&&e.preventDefault(),this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1,this.updateActiveLine();return}if(t==="Backspace"){e.preventDefault&&e.preventDefault(),this.searchQuery=this.searchQuery.slice(0,-1);const r=this._findReverseSearchMatch(this.searchQuery,this.history.length-1);this.searchMatchIdx=r,r!==-1&&(this.buffer=this.history[r],this.cursor=this.buffer.length),this.updateActiveLine();return}if(t==="Enter"){e.preventDefault&&e.preventDefault(),this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1,this.submitLine();return}if(t&&t.length===1&&!l&&!e.altKey){e.preventDefault&&e.preventDefault(),this.searchQuery+=t;const r=this._findReverseSearchMatch(this.searchQuery,this.history.length-1);this.searchMatchIdx=r,r!==-1&&(this.buffer=this.history[r],this.cursor=this.buffer.length),this.updateActiveLine();return}this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1}if(e.altKey&&(t==="b"||t==="B"||t==="ArrowLeft")||n&&t==="ArrowLeft"){e.preventDefault&&e.preventDefault();let r=this.cursor;for(;r>0&&/\s/.test(this.buffer[r-1]);)r--;for(;r>0&&!/\s/.test(this.buffer[r-1]);)r--;this.cursor=r,this.updateActiveLine();return}if(e.altKey&&(t==="f"||t==="F"||t==="ArrowRight")||n&&t==="ArrowRight"){e.preventDefault&&e.preventDefault();let r=this.cursor;for(;r<this.buffer.length&&/\s/.test(this.buffer[r]);)r++;for(;r<this.buffer.length&&!/\s/.test(this.buffer[r]);)r++;this.cursor=r,this.updateActiveLine();return}if(n&&(t==="w"||t==="W")||e.altKey&&t==="Backspace"){e.preventDefault&&e.preventDefault();let r=this.cursor;for(;r>0&&/\s/.test(this.buffer[r-1]);)r--;for(;r>0&&!/\s/.test(this.buffer[r-1]);)r--;this.buffer=this.buffer.slice(0,r)+this.buffer.slice(this.cursor),this.cursor=r,this.updateActiveLine();return}if(t==="ArrowLeft"){e.preventDefault&&e.preventDefault(),this.cursor>0&&(this.cursor--,this.updateActiveLine());return}if(t==="ArrowRight"){e.preventDefault&&e.preventDefault(),this.cursor<this.buffer.length&&(this.cursor++,this.updateActiveLine());return}if(t==="Home"||l&&(t==="a"||t==="A")){e.preventDefault&&e.preventDefault(),this.cursor=0,this.updateActiveLine();return}if(t==="End"||l&&(t==="e"||t==="E")){e.preventDefault&&e.preventDefault(),this.cursor=this.buffer.length,this.updateActiveLine();return}if(l&&(t==="u"||t==="U")){e.preventDefault&&e.preventDefault(),this.buffer=this.buffer.slice(this.cursor),this.cursor=0,this.updateActiveLine();return}if(l&&(t==="k"||t==="K")){e.preventDefault&&e.preventDefault(),this.buffer=this.buffer.slice(0,this.cursor),this.updateActiveLine();return}if(t==="Backspace"){e.preventDefault&&e.preventDefault(),this.cursor>0&&(this.buffer=this.buffer.slice(0,this.cursor-1)+this.buffer.slice(this.cursor),this.cursor--,this.updateActiveLine());return}if(t==="Delete"){e.preventDefault&&e.preventDefault(),this.cursor<this.buffer.length&&(this.buffer=this.buffer.slice(0,this.cursor)+this.buffer.slice(this.cursor+1),this.updateActiveLine());return}if(l&&(t==="d"||t==="D")&&this.buffer===""){if(e.preventDefault&&e.preventDefault(),this._readLineQueue&&this._readLineQueue.length>0){this._drainReadLineQueue(null),this.updateActiveLine();return}if(this.replMode){this._pushLog({type:"system",text:`${this.getPrompt()}.exit`}),this.replMode=!1,this.render();return}}if(t==="ArrowUp"){if(e.preventDefault&&e.preventDefault(),!this.history.length)return;this.historyIdx===-1?(this.savedBuffer=this.buffer,this.historyIdx=this.history.length-1):this.historyIdx>0&&this.historyIdx--,this.buffer=this.history[this.historyIdx]||"",this.cursor=this.buffer.length,this.updateActiveLine();return}if(t==="ArrowDown"){e.preventDefault&&e.preventDefault(),this.historyIdx!==-1&&(this.historyIdx<this.history.length-1?(this.historyIdx++,this.buffer=this.history[this.historyIdx]||""):(this.historyIdx=-1,this.buffer=this.savedBuffer||""),this.cursor=this.buffer.length,this.updateActiveLine());return}if(t==="Tab"){e.preventDefault&&e.preventDefault(),this.autoComplete();return}if(t==="Enter"){e.preventDefault&&e.preventDefault(),this.submitLine();return}t&&t.length===1&&!l&&!e.altKey&&(e.preventDefault&&e.preventDefault(),this.buffer=this.buffer.slice(0,this.cursor)+t+this.buffer.slice(this.cursor),this.cursor++,this.updateActiveLine())}}async pasteText(e){if(!e||this.isCommandRunning())return;const t=String(e).replace(/\r\n/g,`
30
+ `).replace(/\r/g,`
31
+ `);if(!t.includes(`
32
+ `)){this.buffer=this.buffer.slice(0,this.cursor)+t+this.buffer.slice(this.cursor),this.cursor+=t.length,this.updateActiveLine();return}const n=t.split(`
33
+ `);for(let i=0;i<n.length;i++){const l=n[i];if(i<n.length-1)for(this.buffer=this.buffer.slice(0,this.cursor)+l+this.buffer.slice(this.cursor),this.cursor=this.buffer.length,this.submitLine();this.isCommandRunning();)await new Promise(r=>setTimeout(r,10));else l.length>0&&(this.buffer=l,this.cursor=l.length,this.updateActiveLine())}}autoComplete(){if(!this.getCompletions)return;const e=this.getCompletions(this.buffer,this.cursor);if(!e||!Array.isArray(e.matches)||e.matches.length===0)return;const t=e.matches;if(t.length===1){const n=t[0],l=n.endsWith("/")?"":" ",r=this.buffer.slice(0,e.tokenStart),s=this.buffer.slice(this.cursor);this.buffer=r+n+l+s,this.cursor=r.length+n.length+l.length,this.updateActiveLine()}else{let n=t[0];for(let i=1;i<t.length;i++){let l=0;for(;l<n.length&&l<t[i].length&&n[l]===t[i][l];)l++;n=n.slice(0,l)}if(n.length>e.token.length){const i=this.buffer.slice(0,e.tokenStart),l=this.buffer.slice(this.cursor);this.buffer=i+n+l,this.cursor=i.length+n.length}this._pushLog({type:"system",text:`${this.getPrompt()}${this.buffer}`}),this._pushLog({type:"stdout",text:t.join(" ")}),this.render()}}submitLine(){if(this._readLineQueue&&this._readLineQueue.length>0){const l=this.buffer;this.buffer="",this.cursor=0,this.historyIdx=-1,this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1;const r=this._readLineQueue.shift();r&&typeof r.cleanup=="function"&&r.cleanup(),typeof r=="function"?(this.updateActiveLine(),r(l)):r&&typeof r.resolve=="function"&&(this.promptOverride=r.prevPrompt,this._activateNextReadLine(),this.updateActiveLine(),r.resolve(l));return}if(this.isBusy)return;const e=this.buffer,t=this.getPrompt();this.buffer="",this.cursor=0,this.historyIdx=-1,this.searchMode=!1,this.searchQuery="",this.searchMatchIdx=-1;const n=this._pushLog({type:"system",text:`${t}${e}`});if(this._activeLineCommitted=!0,this._cursorCol=0,this._targetLineIdx=-1,this._needsRewrite=!1,this._appendDomLine(n),this._activeLineEl=null,e.trim()&&this.history[this.history.length-1]!==e.trim()){this.history.push(e.trim());const l=typeof this.maxHistory=="number"&&this.maxHistory>0?this.maxHistory:1e3;this.history.length>l&&this.history.splice(0,this.history.length-l)}if(!this.onCommand){this.updateActiveLine();return}this.isBusy=!0,this.updateActiveLine();let i;try{i=this.onCommand(e)}catch(l){throw this.isBusy=!1,this.updateActiveLine(),l}i&&typeof i.then=="function"?Promise.resolve(i).catch(l=>{b.debug("Terminal onCommand promise rejected.",l)}).finally(()=>{this.isBusy=!1,this.updateActiveLine()}):(this.isBusy=!1,this.updateActiveLine())}updateActiveLine(){if(!this.container||typeof this.container.querySelector!="function")return;const e=this.container.querySelector("#cl-repl-input");e&&e.value!==this.buffer&&(e.value=this.buffer);const t=this.container.querySelector("#cl-pty-active-line");if(!t)return;if(this.isCommandRunning()){typeof t.setAttribute=="function"&&t.setAttribute("data-busy","true"),t.style&&(t.style.display="none"),t.innerHTML='<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>';return}typeof t.removeAttribute=="function"&&t.removeAttribute("data-busy"),t.style&&(t.style.display="");const n=this.searchMode?`(reverse-i-search)\`${this.searchQuery}\`: `:this.getPrompt(),i=this.buffer.slice(0,this.cursor),l=this.cursor<this.buffer.length?this.buffer[this.cursor]:" ",r=this.cursor<this.buffer.length?this.buffer.slice(this.cursor+1):"";t.innerHTML=`<span class="codelab-pty__prompt">${y(n)}</span><span class="codelab-pty__before">${y(i)}</span><span class="codelab-pty__cursor blink">${y(l)}</span><span class="codelab-pty__after">${y(r)}</span>`}render(){if(!this.container||typeof this.container.querySelector!="function")return;const e=this.container.querySelector("#cl-repl-input"),t=!!(e&&typeof document<"u"&&document.activeElement===e),n=this.logs.map(a=>`<div class="codelab-log-line ${L(a.type)}">${_(a.text)}</div>`).join(""),i=this.isCommandRunning(),l=i?"":this.searchMode?`(reverse-i-search)\`${this.searchQuery}\`: `:this.getPrompt(),r=i?"":this.buffer.slice(0,this.cursor),s=i?"":this.cursor<this.buffer.length?this.buffer[this.cursor]:" ",f=i?"":this.cursor<this.buffer.length?this.buffer.slice(this.cursor+1):"",p=i?' data-busy="true" style="display:none;"':"",c=i?"codelab-pty__cursor":"codelab-pty__cursor blink";if(this.container.innerHTML=`
1322
34
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1323
- <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1324
- <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1325
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
35
+ <div class="codelab-terminal__log" id="cl-terminal-log">${n}</div>
36
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${p}>
37
+ <span class="codelab-pty__prompt">${y(l)}</span><span class="codelab-pty__before">${y(r)}</span><span class="${c}">${y(s)}</span><span class="codelab-pty__after">${y(f)}</span>
1326
38
  </div>
1327
39
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1328
- <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
40
+ <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${y(this.buffer)}">
1329
41
  </form>
1330
42
  </div>
1331
- `;
1332
-
1333
- this._scrollToBottom();
1334
-
1335
- this._bindEvents();
1336
-
1337
- if (hadFocus) {
1338
- const nextInput = this.container.querySelector('#cl-repl-input');
1339
- if (nextInput && typeof nextInput.focus === 'function') {
1340
- try {
1341
- nextInput.focus();
1342
- if (typeof nextInput.setSelectionRange === 'function') {
1343
- nextInput.setSelectionRange(this.cursor, this.cursor);
1344
- }
1345
- } catch (err) {
1346
- _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
1347
- }
1348
- }
1349
- }
1350
- }
1351
- }
1352
-
1353
- function createTerminal(container, options = {}) {
1354
- return new PTYTerminalEngine(container, options);
1355
- }
1356
-
1357
- const createPTYTerminalEngine = createTerminal;
1358
-
1359
- return {
1360
- PTYTerminalEngine,
1361
- createPTYTerminalEngine,
1362
- createTerminal,
1363
- ansiToHtml,
1364
- parseAnsiToHtml,
1365
- escapeHtml,
1366
- ANSI_CODE_MAP,
1367
- resolveAnsiControlCodes
1368
- };
1369
- });
1370
-
43
+ `,this._scrollToBottom(),this._bindEvents(),t){const a=this.container.querySelector("#cl-repl-input");if(a&&typeof a.focus=="function")try{a.focus(),typeof a.setSelectionRange=="function"&&a.setSelectionRange(this.cursor,this.cursor)}catch(d){b.debug("Terminal focus/selection restore skipped.",d)}}}}function A(u,e={}){return new w(u,e)}return{PTYTerminalEngine:w,createPTYTerminalEngine:A,createTerminal:A,ansiToHtml:_,parseAnsiToHtml:M,escapeHtml:y,ANSI_CODE_MAP:m,resolveAnsiControlCodes:C}});
1371
44
 
1372
45
  })();
1373
46