@innovatorved/code-lab 0.3.0 → 0.3.2

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 (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
package/src/terminal.ts CHANGED
@@ -303,6 +303,14 @@
303
303
 
304
304
  const parseAnsiToHtml = ansiToHtml;
305
305
 
306
+ const MAX_SCROLLBACK = 2000;
307
+ const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
308
+
309
+ function sanitizeLogType(type) {
310
+ const t = String(type || 'stdout').trim();
311
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
312
+ }
313
+
306
314
  class PTYTerminalEngine {
307
315
  constructor(container, options = {}) {
308
316
  if (
@@ -317,6 +325,9 @@
317
325
  }
318
326
  this.container = container || null;
319
327
  this.options = options || {};
328
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
329
+ ? this.options.maxScrollback
330
+ : MAX_SCROLLBACK;
320
331
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
321
332
  this.cwd = this.options.cwd || '/workspace';
322
333
  this.replMode = Boolean(this.options.replMode);
@@ -330,6 +341,7 @@
330
341
  this.searchQuery = '';
331
342
  this.searchMatchIdx = -1;
332
343
  this._readLineQueue = [];
344
+ this.isBusy = false;
333
345
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
334
346
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
335
347
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -480,13 +492,40 @@
480
492
  this.writeStreamChunk(String(data) + '\n', type);
481
493
  }
482
494
 
495
+ isCommandRunning() {
496
+ return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
497
+ }
498
+
499
+ _pushLog(entry) {
500
+ const normalized = {
501
+ type: sanitizeLogType(entry && entry.type),
502
+ text: String(entry && entry.text != null ? entry.text : '')
503
+ };
504
+ this.logs.push(normalized);
505
+ if (this.logs.length > this.maxScrollback) {
506
+ const excess = this.logs.length - this.maxScrollback;
507
+ this.logs.splice(0, excess);
508
+ if (this._targetLineIdx >= 0) {
509
+ this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
510
+ }
511
+ if (this.container && typeof this.container.querySelector === 'function') {
512
+ const logEl = this.container.querySelector('#cl-terminal-log');
513
+ if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
514
+ while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
515
+ logEl.removeChild(logEl.firstChild);
516
+ }
517
+ }
518
+ }
519
+ }
520
+ return normalized;
521
+ }
522
+
483
523
  _getActiveLine(type) {
484
524
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
485
525
  return this.logs[this._targetLineIdx];
486
526
  }
487
527
  if (this._activeLineCommitted || this.logs.length === 0) {
488
- const newLine = { text: '', type };
489
- this.logs.push(newLine);
528
+ const newLine = this._pushLog({ text: '', type });
490
529
  this._activeLineCommitted = false;
491
530
  this._cursorCol = 0;
492
531
  this._targetLineIdx = this.logs.length - 1;
@@ -503,7 +542,7 @@
503
542
  const logEl = this.container.querySelector('#cl-terminal-log');
504
543
  if (!logEl) return;
505
544
  const lineEl = document.createElement('div');
506
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
545
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
507
546
  lineEl.innerHTML = ansiToHtml(line.text);
508
547
  logEl.appendChild(lineEl);
509
548
  this._activeLineEl = lineEl;
@@ -526,7 +565,7 @@
526
565
  }
527
566
  }
528
567
  if (lineEl) {
529
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
568
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
530
569
  lineEl.innerHTML = ansiToHtml(line.text);
531
570
  }
532
571
  }
@@ -565,17 +604,29 @@
565
604
  return [...this.history];
566
605
  }
567
606
 
568
- readLine(promptText = '') {
569
- const prevPrompt = this.promptOverride;
570
- if (promptText) {
571
- this.setPrompt(promptText);
607
+ _activateNextReadLine() {
608
+ if (!this._readLineQueue || this._readLineQueue.length === 0) return;
609
+ const head = this._readLineQueue[0];
610
+ if (head && typeof head === 'object' && !head._activated) {
611
+ head._activated = true;
612
+ head.prevPrompt = this.promptOverride;
613
+ if (head.promptText) {
614
+ this.promptOverride = head.promptText;
615
+ }
572
616
  }
617
+ }
618
+
619
+ readLine(promptText = '') {
573
620
  return new Promise((resolve) => {
574
- this._readLineQueue.push((line) => {
575
- this.promptOverride = prevPrompt;
576
- this.updateActiveLine();
577
- resolve(line);
578
- });
621
+ const item = {
622
+ promptText: String(promptText || ''),
623
+ prevPrompt: null,
624
+ _activated: false,
625
+ resolve
626
+ };
627
+ this._readLineQueue.push(item);
628
+ this._activateNextReadLine();
629
+ this.updateActiveLine();
579
630
  });
580
631
  }
581
632
 
@@ -645,6 +696,10 @@
645
696
  if (input) {
646
697
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
647
698
  this._addListener(input, 'input', () => {
699
+ if (this.isCommandRunning()) {
700
+ input.value = '';
701
+ return;
702
+ }
648
703
  if (input.value !== this.buffer) {
649
704
  this.buffer = input.value;
650
705
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -686,6 +741,35 @@
686
741
  const key = e.key;
687
742
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
688
743
 
744
+ if (isCtrl && (key === 'l' || key === 'L')) {
745
+ if (e.preventDefault) e.preventDefault();
746
+ this.clear();
747
+ return;
748
+ }
749
+
750
+ if (isCtrl && (key === 'c' || key === 'C')) {
751
+ if (e.preventDefault) e.preventDefault();
752
+ const wasBusy = this.isBusy;
753
+ this.isBusy = false;
754
+ this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
755
+ this.buffer = '';
756
+ this.cursor = 0;
757
+ this.historyIdx = -1;
758
+ if (this.replMode) {
759
+ this.replMode = false;
760
+ }
761
+ if (this.onInterrupt) {
762
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
763
+ }
764
+ this.render();
765
+ return;
766
+ }
767
+
768
+ if (this.isCommandRunning()) {
769
+ if (e.preventDefault) e.preventDefault();
770
+ return;
771
+ }
772
+
689
773
  if (isCtrl && (key === 'r' || key === 'R')) {
690
774
  if (e.preventDefault) e.preventDefault();
691
775
  if (!this.searchMode) {
@@ -817,33 +901,11 @@
817
901
  return;
818
902
  }
819
903
 
820
- if (isCtrl && (key === 'l' || key === 'L')) {
821
- if (e.preventDefault) e.preventDefault();
822
- this.clear();
823
- return;
824
- }
825
-
826
- if (isCtrl && (key === 'c' || key === 'C')) {
827
- if (e.preventDefault) e.preventDefault();
828
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
829
- this.buffer = '';
830
- this.cursor = 0;
831
- this.historyIdx = -1;
832
- if (this.replMode) {
833
- this.replMode = false;
834
- }
835
- if (this.onInterrupt) {
836
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
837
- }
838
- this.render();
839
- return;
840
- }
841
-
842
904
  if (isCtrl && (key === 'd' || key === 'D')) {
843
905
  if (this.buffer === '') {
844
906
  if (e.preventDefault) e.preventDefault();
845
907
  if (this.replMode) {
846
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
908
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
847
909
  this.replMode = false;
848
910
  this.render();
849
911
  return;
@@ -937,14 +999,41 @@
937
999
  }
938
1000
 
939
1001
  // Print candidate matches
940
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
941
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
1002
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1003
+ this._pushLog({ type: 'stdout', text: matches.join(' ') });
942
1004
  this.render();
943
1005
  }
944
1006
  }
945
1007
 
946
1008
  submitLine() {
1009
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
1010
+ const line = this.buffer;
1011
+ this.buffer = '';
1012
+ this.cursor = 0;
1013
+ this.historyIdx = -1;
1014
+ this.searchMode = false;
1015
+ this.searchQuery = '';
1016
+ this.searchMatchIdx = -1;
1017
+
1018
+ const entry = this._readLineQueue.shift();
1019
+ if (typeof entry === 'function') {
1020
+ this.updateActiveLine();
1021
+ entry(line);
1022
+ } else if (entry && typeof entry.resolve === 'function') {
1023
+ this.promptOverride = entry.prevPrompt;
1024
+ this._activateNextReadLine();
1025
+ this.updateActiveLine();
1026
+ entry.resolve(line);
1027
+ }
1028
+ return;
1029
+ }
1030
+
1031
+ if (this.isBusy) {
1032
+ return;
1033
+ }
1034
+
947
1035
  const line = this.buffer;
1036
+ const promptSnap = this.getPrompt();
948
1037
  this.buffer = '';
949
1038
  this.cursor = 0;
950
1039
  this.historyIdx = -1;
@@ -952,22 +1041,49 @@
952
1041
  this.searchQuery = '';
953
1042
  this.searchMatchIdx = -1;
954
1043
 
1044
+ const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1045
+ this._activeLineCommitted = true;
1046
+ this._cursorCol = 0;
1047
+ this._targetLineIdx = -1;
1048
+ this._needsRewrite = false;
1049
+ this._appendDomLine(echoed);
1050
+ this._activeLineEl = null;
1051
+
955
1052
  if (line.trim()) {
956
1053
  if (this.history[this.history.length - 1] !== line.trim()) {
957
1054
  this.history.push(line.trim());
958
1055
  }
959
1056
  }
960
1057
 
961
- if (this._readLineQueue && this._readLineQueue.length > 0) {
962
- const resolver = this._readLineQueue.shift();
1058
+ if (!this.onCommand) {
963
1059
  this.updateActiveLine();
964
- resolver(line);
965
1060
  return;
966
1061
  }
967
1062
 
1063
+ this.isBusy = true;
968
1064
  this.updateActiveLine();
969
- if (this.onCommand) {
970
- this.onCommand(line);
1065
+
1066
+ let cmdResult;
1067
+ try {
1068
+ cmdResult = this.onCommand(line);
1069
+ } catch (err) {
1070
+ this.isBusy = false;
1071
+ this.updateActiveLine();
1072
+ throw err;
1073
+ }
1074
+
1075
+ if (cmdResult && typeof cmdResult.then === 'function') {
1076
+ Promise.resolve(cmdResult)
1077
+ .catch((err) => {
1078
+ _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1079
+ })
1080
+ .finally(() => {
1081
+ this.isBusy = false;
1082
+ this.updateActiveLine();
1083
+ });
1084
+ } else {
1085
+ this.isBusy = false;
1086
+ this.updateActiveLine();
971
1087
  }
972
1088
  }
973
1089
 
@@ -980,6 +1096,16 @@
980
1096
  const lineEl = this.container.querySelector('#cl-pty-active-line');
981
1097
  if (!lineEl) return;
982
1098
 
1099
+ if (this.isCommandRunning()) {
1100
+ if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1101
+ if (lineEl.style) lineEl.style.display = 'none';
1102
+ 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>`;
1103
+ return;
1104
+ }
1105
+
1106
+ if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1107
+ if (lineEl.style) lineEl.style.display = '';
1108
+
983
1109
  const prompt = this.searchMode
984
1110
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
985
1111
  : this.getPrompt();
@@ -1000,21 +1126,24 @@
1000
1126
  );
1001
1127
 
1002
1128
  const logsHtml = this.logs
1003
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
1129
+ .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1004
1130
  .join('');
1005
1131
 
1006
- const prompt = this.searchMode
1007
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1008
- : this.getPrompt();
1009
- const before = this.buffer.slice(0, this.cursor);
1010
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1011
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1132
+ const busy = this.isCommandRunning();
1133
+ const prompt = busy
1134
+ ? ''
1135
+ : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1136
+ const before = busy ? '' : this.buffer.slice(0, this.cursor);
1137
+ const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1138
+ const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1139
+ const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1140
+ const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1012
1141
 
1013
1142
  this.container.innerHTML = `
1014
1143
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1015
1144
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1016
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
1017
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1145
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1146
+ <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>
1018
1147
  </div>
1019
1148
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1020
1149
  <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
@@ -4,6 +4,15 @@
4
4
 
5
5
  import { CL_ICONS } from './icons';
6
6
 
7
+ function escapeHtml(str: unknown): string {
8
+ return String(str ?? '')
9
+ .replace(/&/g, '&amp;')
10
+ .replace(/</g, '&lt;')
11
+ .replace(/>/g, '&gt;')
12
+ .replace(/"/g, '&quot;')
13
+ .replace(/'/g, '&#39;');
14
+ }
15
+
7
16
  export interface DiffComputeResult {
8
17
  hunks: Array<{ type: 'context' | 'add' | 'del'; text: string; oldLine: number | null; newLine: number | null }>;
9
18
  added: number;
@@ -115,11 +124,25 @@ export class CodeLabDiffEditorManager {
115
124
  if (editorHost) editorHost.style.display = 'none';
116
125
  if (fallbackTextarea) fallbackTextarea.style.display = 'none';
117
126
 
127
+ if (this.diffEditor) {
128
+ this.diffEditor.dispose();
129
+ this.diffEditor = null;
130
+ }
131
+ if (this.originalModel) {
132
+ this.originalModel.dispose();
133
+ this.originalModel = null;
134
+ }
135
+ if (this.modifiedModel) {
136
+ this.modifiedModel.dispose();
137
+ this.modifiedModel = null;
138
+ }
139
+
140
+ const safeFile = escapeHtml(file);
118
141
  diffContainer.innerHTML = `
119
142
  <div class="codelab-diff-toolbar">
120
143
  <span style="font-weight:600;display:inline-flex;align-items:center;gap:6px;">
121
144
  ${CL_ICONS.diff}
122
- <span>Diff: <code>${file}</code> (${isStarter ? 'Current vs Starter' : 'Current vs Solution'})</span>
145
+ <span>Diff: <code>${safeFile}</code> (${isStarter ? 'Current vs Starter' : 'Current vs Solution'})</span>
123
146
  </span>
124
147
  <div class="codelab-segmented" style="margin-left:16px;">
125
148
  <button type="button" class="codelab-segmented__btn ${target === 'starter' ? 'active' : ''}" id="cl-diff-toggle-starter">Starter</button>
@@ -135,16 +158,14 @@ export class CodeLabDiffEditorManager {
135
158
  `;
136
159
 
137
160
  const slot = diffContainer.querySelector('#cl-diff-editor-slot');
138
- if (!this.diffEditor) {
139
- this.diffEditor = monaco.editor.createDiffEditor(slot, {
140
- readOnly: false,
141
- originalEditable: false,
142
- theme: this.workbench.theme === 'light' ? 'vs' : 'vs-dark',
143
- renderSideBySide: true,
144
- automaticLayout: true,
145
- minimap: { enabled: false }
146
- });
147
- }
161
+ this.diffEditor = monaco.editor.createDiffEditor(slot, {
162
+ readOnly: false,
163
+ originalEditable: false,
164
+ theme: this.workbench.theme === 'light' ? 'vs' : 'vs-dark',
165
+ renderSideBySide: true,
166
+ automaticLayout: true,
167
+ minimap: { enabled: false }
168
+ });
148
169
 
149
170
  const lang = file.endsWith('.ts') ? 'typescript' : file.endsWith('.cpp') ? 'cpp' : file.endsWith('.py') ? 'python' : 'javascript';
150
171
  this.originalModel = monaco.editor.createModel(refCode, lang);
@@ -172,13 +193,20 @@ export class CodeLabDiffEditorManager {
172
193
  this.openInlineDiff(file, 'solution');
173
194
  });
174
195
  diffContainer.querySelector('#cl-diff-revert-btn')?.addEventListener('click', () => {
175
- const starterCode = (this.workbench.starterFiles && this.workbench.starterFiles[file]) || '';
196
+ const starterMap = this.workbench.starterFiles || (typeof this.workbench._getBaseFilesForModeAndLang === 'function' ? this.workbench._getBaseFilesForModeAndLang('guided', this.workbench.lang) : {});
197
+ const starterCode = (starterMap && starterMap[file]) || '';
176
198
  this.workbench.files[file] = starterCode;
177
199
  this.closeInlineDiff();
178
200
  this.workbench.openFile(file);
179
201
  });
180
202
  diffContainer.querySelector('#cl-diff-apply-btn')?.addEventListener('click', () => {
181
- const solutionCode = (this.workbench.solutionFiles && this.workbench.solutionFiles[file]) || '';
203
+ if (typeof this.workbench.applyReferenceSolution === 'function') {
204
+ this.closeInlineDiff();
205
+ this.workbench.applyReferenceSolution();
206
+ return;
207
+ }
208
+ const solutionMap = this.workbench.solutionFiles || (typeof this.workbench._getBaseFilesForModeAndLang === 'function' ? this.workbench._getBaseFilesForModeAndLang('sandbox', this.workbench.lang) : {});
209
+ const solutionCode = (solutionMap && solutionMap[file]) || '';
182
210
  this.workbench.files[file] = solutionCode;
183
211
  this.closeInlineDiff();
184
212
  this.workbench.openFile(file);
@@ -4,6 +4,15 @@
4
4
 
5
5
  import { CL_ICONS } from './icons';
6
6
 
7
+ function escapeHtml(str: unknown): string {
8
+ return String(str ?? '')
9
+ .replace(/&/g, '&amp;')
10
+ .replace(/</g, '&lt;')
11
+ .replace(/>/g, '&gt;')
12
+ .replace(/"/g, '&quot;')
13
+ .replace(/'/g, '&#39;');
14
+ }
15
+
7
16
  export interface DrawerTabOptions {
8
17
  workbench: any;
9
18
  drawerTab: string;
@@ -58,12 +67,10 @@ export function renderDrawerTabsHtml(opts: DrawerTabOptions): string {
58
67
  <span class="codelab-badge ${problemsCount > 0 ? 'codelab-badge--warn' : ''}" id="cl-problems-count" style="margin-left:4px;font-size:10px;padding:1px 5px;border-radius:10px;background:${problemsCount > 0 ? '#cca700' : 'rgba(255,255,255,0.1)'};color:#fff;">${problemsCount}</span>
59
68
  </button>
60
69
 
61
- ${showTests ? `
62
70
  <button type="button" role="tab" aria-selected="${drawerTab === 'tests'}" class="codelab-drawer__tab ${drawerTab === 'tests' ? 'active' : ''}" data-cl-drawertab="tests">
63
71
  ${CL_ICONS.check}
64
72
  <span>Test Suite</span>
65
73
  </button>
66
- ` : ''}
67
74
 
68
75
  <button type="button" role="tab" aria-selected="${drawerTab === 'stdin'}" class="codelab-drawer__tab ${drawerTab === 'stdin' ? 'active' : ''}" data-cl-drawertab="stdin" title="Standard Input / Competitive Programming Custom Input">
69
76
  ${CL_ICONS.keyboard}
@@ -75,12 +82,10 @@ export function renderDrawerTabsHtml(opts: DrawerTabOptions): string {
75
82
  <span>Ports</span>
76
83
  </button>
77
84
 
78
- ${hasWebContent ? `
79
85
  <button type="button" role="tab" aria-selected="${drawerTab === 'preview'}" class="codelab-drawer__tab ${drawerTab === 'preview' ? 'active' : ''}" data-cl-drawertab="preview" title="In-browser Web Preview">
80
86
  ${CL_ICONS.externalLink || CL_ICONS.globe}
81
87
  <span>Web Preview</span>
82
88
  </button>
83
- ` : ''}
84
89
 
85
90
  <button type="button" role="tab" aria-selected="${drawerTab === 'network'}" class="codelab-drawer__tab ${drawerTab === 'network' ? 'active' : ''}" data-cl-drawertab="network">
86
91
  ${CL_ICONS.activity}
@@ -122,11 +127,15 @@ export function renderProblemsPanelHtml(workbench: any): string {
122
127
  ${items.map((item: any) => {
123
128
  const icon = item.severity === 'error' ? '✗' : (item.severity === 'warning' ? '⚠' : 'ℹ');
124
129
  const cls = item.severity === 'error' ? 'codelab-problem-item--error' : (item.severity === 'warning' ? 'codelab-problem-item--warning' : 'codelab-problem-item--info');
130
+ const safeFile = escapeHtml(item.file);
131
+ const safeMsg = escapeHtml(item.message);
132
+ const safeLine = Number(item.line) || 1;
133
+ const safeCol = Number(item.col) || 1;
125
134
  return `
126
- <div class="codelab-problem-item ${cls}" data-cl-problem-file="${item.file}" data-cl-problem-line="${item.line}" data-cl-problem-col="${item.col || 1}">
135
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${safeFile}" data-cl-problem-line="${safeLine}" data-cl-problem-col="${safeCol}">
127
136
  <span style="font-weight:bold;">${icon}</span>
128
- <span>${item.message}</span>
129
- <span class="codelab-problem-item__location">${item.file}:${item.line}:${item.col || 1}</span>
137
+ <span>${safeMsg}</span>
138
+ <span class="codelab-problem-item__location">${safeFile}:${safeLine}:${safeCol}</span>
130
139
  </div>
131
140
  `;
132
141
  }).join('')}
@@ -135,7 +144,7 @@ export function renderProblemsPanelHtml(workbench: any): string {
135
144
  }
136
145
 
137
146
  export function renderStdinPanelHtml(workbench: any): string {
138
- const val = workbench.customStdin || '';
147
+ const val = escapeHtml(workbench.customStdin || '');
139
148
  return `
140
149
  <div class="codelab-stdin-panel">
141
150
  <div class="codelab-stdin-panel__header">
@@ -4,6 +4,15 @@
4
4
 
5
5
  import { CL_ICONS } from './icons';
6
6
 
7
+ function escapeHtml(str: unknown): string {
8
+ return String(str ?? '')
9
+ .replace(/&/g, '&amp;')
10
+ .replace(/</g, '&lt;')
11
+ .replace(/>/g, '&gt;')
12
+ .replace(/"/g, '&quot;')
13
+ .replace(/'/g, '&#39;');
14
+ }
15
+
7
16
  export interface GuidedStepData {
8
17
  id: string;
9
18
  title: string;
@@ -21,10 +30,11 @@ export function renderStepPillsHtml(steps: GuidedStepData[], activeIndex: number
21
30
  const isPassed = completedStepIds.has(step.id);
22
31
  const isActive = idx === activeIndex;
23
32
  const cls = `codelab-step-pill ${isActive ? 'active' : ''} ${isPassed ? 'passed' : ''}`;
33
+ const safeTitle = escapeHtml(step.title);
24
34
  return `
25
- <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${step.title}">
35
+ <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${safeTitle}">
26
36
  <span class="codelab-step-pill__num">${isPassed ? CL_ICONS.check : idx + 1}</span>
27
- <span class="codelab-step-pill__label">${step.title}</span>
37
+ <span class="codelab-step-pill__label">${safeTitle}</span>
28
38
  </button>
29
39
  `;
30
40
  }).join('')}
@@ -61,6 +61,8 @@ export async function compressWorkspaceSnapshot(payload: WorkspaceSharePayload):
61
61
  return bufferToBase64Url(rawBytes);
62
62
  }
63
63
 
64
+ const MAX_DECOMPRESSED_SNAPSHOT_BYTES = 5 * 1024 * 1024; // 5 MB
65
+
64
66
  /**
65
67
  * Decompresses a Base64url string into workspace snapshot payload.
66
68
  */
@@ -68,28 +70,55 @@ export async function decompressWorkspaceSnapshot(encoded: string): Promise<Work
68
70
  if (!encoded || typeof encoded !== 'string') return null;
69
71
  try {
70
72
  const bytes = base64UrlToBuffer(encoded);
73
+ if (bytes.byteLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
74
+ throw new Error('Snapshot payload exceeds maximum allowed size');
75
+ }
71
76
 
72
77
  if (typeof DecompressionStream !== 'undefined') {
73
78
  try {
74
79
  const ds = new DecompressionStream('deflate-raw');
75
80
  const writer = ds.writable.getWriter();
76
- writer.write(bytes as any);
77
- writer.close();
81
+ const writeInput = new Uint8Array(bytes.byteLength);
82
+ writeInput.set(bytes);
83
+ writer.write(writeInput).catch(() => {});
84
+ writer.close().catch(() => {});
78
85
 
79
- const response = new Response(ds.readable);
80
- const decompressed = await response.arrayBuffer();
86
+ const reader = ds.readable.getReader();
87
+ const chunks: Uint8Array[] = [];
88
+ let totalLength = 0;
89
+ while (true) {
90
+ const step = await reader.read();
91
+ if (step.done) break;
92
+ const chunk = step.value;
93
+ if (chunk) {
94
+ totalLength += chunk.byteLength;
95
+ if (totalLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
96
+ await reader.cancel().catch(() => {});
97
+ throw new Error('Decompressed snapshot exceeds 5 MB safety limit');
98
+ }
99
+ chunks.push(chunk);
100
+ }
101
+ }
102
+ const decompressed = new Uint8Array(totalLength);
103
+ let offset = 0;
104
+ for (const chunk of chunks) {
105
+ decompressed.set(chunk, offset);
106
+ offset += chunk.byteLength;
107
+ }
81
108
  const text = new TextDecoder().decode(decompressed);
82
- return JSON.parse(text);
109
+ return JSON.parse(text) as WorkspaceSharePayload;
83
110
  } catch (err) {
111
+ if (err instanceof Error && err.message.includes('safety limit')) {
112
+ throw err;
113
+ }
84
114
  // Fallback for uncompressed raw JSON payload
85
- void err;
86
115
  const rawText = new TextDecoder().decode(bytes);
87
- return JSON.parse(rawText);
116
+ return JSON.parse(rawText) as WorkspaceSharePayload;
88
117
  }
89
118
  }
90
119
 
91
120
  const rawText = new TextDecoder().decode(bytes);
92
- return JSON.parse(rawText);
121
+ return JSON.parse(rawText) as WorkspaceSharePayload;
93
122
  } catch (err) {
94
123
  if (typeof console !== 'undefined' && console.warn) {
95
124
  console.warn('[CodeLab Share Snapshot Restore Error]:', err);
@@ -35,7 +35,8 @@ export const WORKBENCH_STYLES = `
35
35
  padding: 4px 0;
36
36
  display: none;
37
37
  }
38
- .codelab-split-menu.open {
38
+ .codelab-split-menu.open,
39
+ .codelab-split-menu.active {
39
40
  display: block;
40
41
  }
41
42
  .codelab-split-menu__item {