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