@innovatorved/code-lab 0.2.0 → 0.3.1

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 (66) hide show
  1. package/ARCHITECTURE.md +11 -6
  2. package/CHANGELOG.md +40 -0
  3. package/README.md +18 -8
  4. package/dist/code-lab.css +198 -0
  5. package/dist/code-lab.d.ts +27 -9
  6. package/dist/code-lab.esm.js +8516 -84
  7. package/dist/code-lab.js +8514 -82
  8. package/dist/extensions/cpp.d.ts +40 -6
  9. package/dist/extensions/cpp.esm.js +1027 -7
  10. package/dist/extensions/cpp.js +1027 -7
  11. package/dist/extensions/guided-lab.esm.js +40 -2
  12. package/dist/extensions/guided-lab.js +40 -2
  13. package/dist/extensions/python.d.ts +92 -0
  14. package/dist/extensions/python.esm.js +5476 -0
  15. package/dist/extensions/python.js +5495 -0
  16. package/dist/index.d.ts +7 -4
  17. package/dist/preview-sw.js +1 -1
  18. package/dist/runtime/index.d.ts +4 -0
  19. package/dist/runtime/test-harness.d.ts +24 -0
  20. package/dist/runtime.esm.js +36 -4
  21. package/dist/runtime.js +36 -4
  22. package/dist/schemas.d.ts +137 -24
  23. package/dist/schemas.esm.js +44 -2
  24. package/dist/schemas.js +44 -2
  25. package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
  26. package/dist/shell/index.d.ts +4 -0
  27. package/dist/shell.esm.js +113 -1
  28. package/dist/shell.js +113 -1
  29. package/dist/terminal.esm.js +1 -1
  30. package/dist/terminal.js +1 -1
  31. package/dist/workbench/command-palette.d.ts +10 -0
  32. package/dist/workbench/diff-editor.d.ts +26 -0
  33. package/dist/workbench/drawer.d.ts +18 -0
  34. package/dist/workbench/editor.d.ts +11 -0
  35. package/dist/workbench/file-tree.d.ts +11 -0
  36. package/dist/workbench/guided-pane.d.ts +11 -0
  37. package/dist/workbench/icons.d.ts +5 -0
  38. package/dist/workbench/index.d.ts +39 -0
  39. package/dist/workbench/share.d.ts +21 -0
  40. package/dist/workbench/styles.d.ts +4 -0
  41. package/dist/workbench/toolbar.d.ts +17 -0
  42. package/dist/workbench.d.ts +6 -1
  43. package/package.json +8 -2
  44. package/src/code-lab.css +198 -0
  45. package/src/extensions/cpp.ts +966 -5
  46. package/src/extensions/python.ts +1293 -0
  47. package/src/index.ts +35 -3
  48. package/src/runtime/index.ts +5 -0
  49. package/src/runtime/test-harness.ts +57 -0
  50. package/src/runtime.ts +35 -3
  51. package/src/schemas.ts +47 -2
  52. package/src/shell/coreutils/compilers-cli.ts +103 -0
  53. package/src/shell/index.ts +5 -0
  54. package/src/shell.ts +112 -0
  55. package/src/workbench/command-palette.ts +140 -0
  56. package/src/workbench/diff-editor.ts +216 -0
  57. package/src/workbench/drawer.ts +144 -0
  58. package/src/workbench/editor.ts +49 -0
  59. package/src/workbench/file-tree.ts +51 -0
  60. package/src/workbench/guided-pane.ts +33 -0
  61. package/src/workbench/icons.ts +48 -0
  62. package/src/workbench/index.ts +38 -0
  63. package/src/workbench/share.ts +99 -0
  64. package/src/workbench/styles.ts +200 -0
  65. package/src/workbench/toolbar.ts +171 -0
  66. package/src/workbench.ts +744 -69
package/src/workbench.ts CHANGED
@@ -57,7 +57,7 @@
57
57
 
58
58
  // The bundler rewrites this literal from package.json at build time. Keeping
59
59
  // the fallback in sync lets tests require src/workbench.js directly.
60
- const CODELAB_VERSION = '0.2.0';
60
+ const CODELAB_VERSION = '0.3.1';
61
61
 
62
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
63
63
  const NODE_AMBIENT_DTS = `
@@ -1135,8 +1135,8 @@ int main() {
1135
1135
  `
1136
1136
  };
1137
1137
 
1138
- // Helper to convert JS file set to TS or C++ file set if explicit language files aren't provided
1139
- function mapFilesToLanguage(filesObj, lang, explicitTsFiles, explicitCppFiles) {
1138
+ // Helper to convert JS file set to TS, C++, or Python file set if explicit language files aren't provided
1139
+ function mapFilesToLanguage(filesObj, lang, explicitTsFiles, explicitCppFiles, explicitPyFiles) {
1140
1140
  if (lang === 'ts' && explicitTsFiles && Object.keys(explicitTsFiles).length > 0) {
1141
1141
  return { ...explicitTsFiles };
1142
1142
  }
@@ -1159,6 +1159,25 @@ int main() {
1159
1159
  }
1160
1160
  return outCpp;
1161
1161
  }
1162
+ if (lang === 'py') {
1163
+ if (explicitPyFiles && Object.keys(explicitPyFiles).length > 0) {
1164
+ return { ...explicitPyFiles };
1165
+ }
1166
+ const existingPy = {};
1167
+ for (const [name, content] of Object.entries(filesObj || {})) {
1168
+ if (/\.(py|md)$/i.test(name)) {
1169
+ existingPy[name] = content;
1170
+ }
1171
+ }
1172
+ if (Object.keys(existingPy).some(f => /\.py$/i.test(f))) {
1173
+ return existingPy;
1174
+ }
1175
+ const outPy = { ...DEFAULT_STANDALONE_PYTHON_FILES };
1176
+ if (filesObj && filesObj['README.md']) {
1177
+ outPy['README.md'] = filesObj['README.md'];
1178
+ }
1179
+ return outPy;
1180
+ }
1162
1181
  const out = {};
1163
1182
  for (const [name, content] of Object.entries(filesObj || {})) {
1164
1183
  if (lang === 'ts' && name.endsWith('.js')) {
@@ -1173,6 +1192,11 @@ int main() {
1173
1192
  return out;
1174
1193
  }
1175
1194
 
1195
+ const DEFAULT_STANDALONE_PYTHON_FILES = {
1196
+ 'main.py': `"""\\nStandalone Python 3.12 Sandbox with CPython WebAssembly.\\n"""\\nfrom codelab_test import describe, it, assert_equal\\n\\ndef solve(x):\\n return x\\n\\nif __name__ == '__main__':\\n print("Hello from Python 3.12 in CodeLab!")\\n print("Output:", solve({"status": "ok"}))\\n`,
1197
+ 'test.py': `from codelab_test import describe, it, assert_equal\\nfrom main import solve\\n\\nwith describe("Python Sandbox Test Suite"):\\n with it("returns input value"):\\n assert_equal(solve(42), 42)\\n`
1198
+ };
1199
+
1176
1200
  const DEFAULT_STANDALONE_FILES = {
1177
1201
  'index.js': `'use strict';\n\nfunction solve(input) {\n return input;\n}\n\nmodule.exports = { solve };\n`,
1178
1202
  'demo.js': `'use strict';\nconst { solve } = require('./index.js');\n\nconsole.log('Demo output:', solve({ status: 'ok', timestamp: Date.now() }));\n`,
@@ -1215,7 +1239,12 @@ int main() {
1215
1239
  tablet: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>',
1216
1240
  smartphone: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2" width="10" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>',
1217
1241
  externalLink: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',
1218
- x: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
1242
+ x: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
1243
+ warning: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
1244
+ clock: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
1245
+ memory: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 19v2"/><path d="M10 19v2"/><path d="M14 19v2"/><path d="M18 19v2"/><path d="M6 3v2"/><path d="M10 3v2"/><path d="M14 3v2"/><path d="M18 3v2"/><rect x="2" y="5" width="20" height="14" rx="2"/></svg>',
1246
+ keyboard: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M6 8h.01"/><path d="M10 8h.01"/><path d="M14 8h.01"/><path d="M18 8h.01"/><path d="M6 12h.01"/><path d="M10 12h.01"/><path d="M14 12h.01"/><path d="M18 12h.01"/><path d="M7 16h10"/></svg>',
1247
+ share: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>'
1219
1248
  };
1220
1249
 
1221
1250
  let _workbenchInstanceCounter = 0;
@@ -1392,7 +1421,9 @@ int main() {
1392
1421
  ...(options.tsStarterFiles ? { tsStarterFiles: options.tsStarterFiles } : {}),
1393
1422
  ...((options.tsSolutionFiles || options.tsFiles) ? { tsSolutionFiles: options.tsSolutionFiles || options.tsFiles } : {}),
1394
1423
  ...(options.cppStarterFiles ? { cppStarterFiles: options.cppStarterFiles } : {}),
1395
- ...((options.cppSolutionFiles || options.cppFiles) ? { cppSolutionFiles: options.cppSolutionFiles || options.cppFiles } : {})
1424
+ ...((options.cppSolutionFiles || options.cppFiles) ? { cppSolutionFiles: options.cppSolutionFiles || options.cppFiles } : {}),
1425
+ ...(options.pyStarterFiles ? { pyStarterFiles: options.pyStarterFiles } : {}),
1426
+ ...((options.pySolutionFiles || options.pyFiles) ? { pySolutionFiles: options.pySolutionFiles || options.pyFiles } : {})
1396
1427
  };
1397
1428
  this.steps = options.steps || this.guidedConfig?.steps || [];
1398
1429
  this.hasGuidedLab = Boolean(
@@ -1403,7 +1434,7 @@ int main() {
1403
1434
  this.enabledLanguages = new Set(['js']);
1404
1435
  if (Array.isArray(options.languages)) {
1405
1436
  for (const l of options.languages) {
1406
- if (l === 'js' || l === 'ts' || l === 'cpp') this.enabledLanguages.add(l);
1437
+ if (l === 'js' || l === 'ts' || l === 'cpp' || l === 'py') this.enabledLanguages.add(l);
1407
1438
  }
1408
1439
  }
1409
1440
  if (
@@ -1425,6 +1456,15 @@ int main() {
1425
1456
  ) {
1426
1457
  this.enabledLanguages.add('cpp');
1427
1458
  }
1459
+ if (
1460
+ this.guidedConfig.pyStarterFiles ||
1461
+ this.guidedConfig.pySolutionFiles ||
1462
+ this.guidedConfig.pyFiles ||
1463
+ options.lang === 'py' ||
1464
+ options.language === 'py'
1465
+ ) {
1466
+ this.enabledLanguages.add('py');
1467
+ }
1428
1468
  this.hasMultipleLanguages = Boolean(
1429
1469
  options.hasMultipleLanguages ||
1430
1470
  options.languages ||
@@ -1435,8 +1475,13 @@ int main() {
1435
1475
  this.guidedConfig.cppStarterFiles ||
1436
1476
  this.guidedConfig.cppSolutionFiles ||
1437
1477
  this.guidedConfig.cppFiles ||
1478
+ this.guidedConfig.pyStarterFiles ||
1479
+ this.guidedConfig.pySolutionFiles ||
1480
+ this.guidedConfig.pyFiles ||
1438
1481
  (this.hasGuidedLab && (options.lang || options.language))
1439
1482
  );
1483
+ this.showWebPreviewOption = Boolean(options.showWebPreview);
1484
+ this._diffManager = null;
1440
1485
 
1441
1486
  // Load saved user state from localStorage (with in-memory fallback)
1442
1487
  this.savedState = this._loadState();
@@ -1463,7 +1508,12 @@ int main() {
1463
1508
  this.renamingItem = null;
1464
1509
  this._draggedFile = null;
1465
1510
  this.guideTab = 'steps'; // 'steps' | 'readme'
1466
- this.drawerTab = 'tests'; // 'tests' | 'terminal' | 'ports' | 'preview' | 'network' | 'inspector'
1511
+ this.drawerTab = (this.hasGuidedLab && this.mode === 'guided') ? 'tests' : 'terminal';
1512
+ this.testSuiteVisible = Boolean(this.hasGuidedLab && this.mode === 'guided');
1513
+ this.lastDurationMs = null;
1514
+ this.lastPeakMemoryBytes = null;
1515
+ this.customStdin = (options && options.stdin) || '';
1516
+ this._eventsBound = false;
1467
1517
  // ── Web Preview (M3) state ──
1468
1518
  this.previewState = {
1469
1519
  port: null,
@@ -1601,6 +1651,7 @@ int main() {
1601
1651
  this._renderShell();
1602
1652
  this._bindEvents();
1603
1653
  this._initEditor();
1654
+ this._checkUrlSnapshot();
1604
1655
 
1605
1656
  const initialPlugins = [
1606
1657
  ...(Array.isArray(options.extensions) ? options.extensions : []),
@@ -2032,9 +2083,12 @@ int main() {
2032
2083
  }
2033
2084
  }
2034
2085
  if (durEl) {
2035
- if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
2086
+ const ms = (typeof this.lastDurationMs === 'number' && !Number.isNaN(this.lastDurationMs))
2087
+ ? this.lastDurationMs
2088
+ : this.lastRunDurationMs;
2089
+ if (typeof ms === 'number' && !Number.isNaN(ms)) {
2036
2090
  durEl.style.display = 'inline-flex';
2037
- durEl.textContent = `⚡ ${this.lastRunDurationMs.toFixed(1)}ms`;
2091
+ durEl.textContent = `⚡ ${ms.toFixed(1)}ms`;
2038
2092
  } else {
2039
2093
  durEl.style.display = 'none';
2040
2094
  }
@@ -2045,10 +2099,13 @@ int main() {
2045
2099
  if (langEl) {
2046
2100
  langEl.textContent = this.lang === 'cpp'
2047
2101
  ? 'C++20 (Clang/WASI)'
2048
- : this.lang === 'ts'
2049
- ? 'TypeScript 5.x'
2050
- : 'JavaScript (CJS/ESM)';
2102
+ : this.lang === 'py'
2103
+ ? 'Python 3.12 (CPython WASI)'
2104
+ : this.lang === 'ts'
2105
+ ? 'TypeScript 5.x'
2106
+ : 'JavaScript (CJS/ESM)';
2051
2107
  }
2108
+ this._updateTelemetryHud();
2052
2109
  }
2053
2110
 
2054
2111
  _getBaseFilesForModeAndLang(mode, lang) {
@@ -2057,19 +2114,21 @@ int main() {
2057
2114
  ...this.referenceFiles,
2058
2115
  ...(this.guidedConfig?.starterFiles || {})
2059
2116
  };
2060
- if (mode === 'guided' && (this.guidedConfig?.starterFiles || this.guidedConfig?.tsStarterFiles || this.guidedConfig?.cppStarterFiles)) {
2117
+ if (mode === 'guided' && (this.guidedConfig?.starterFiles || this.guidedConfig?.tsStarterFiles || this.guidedConfig?.cppStarterFiles || this.guidedConfig?.pyStarterFiles)) {
2061
2118
  return mapFilesToLanguage(
2062
2119
  baseJsStarter,
2063
2120
  lang,
2064
2121
  this.guidedConfig?.tsStarterFiles,
2065
- this.guidedConfig?.cppStarterFiles
2122
+ this.guidedConfig?.cppStarterFiles,
2123
+ this.guidedConfig?.pyStarterFiles
2066
2124
  );
2067
2125
  }
2068
2126
  return mapFilesToLanguage(
2069
2127
  baseJsSolution,
2070
2128
  lang,
2071
2129
  this.guidedConfig?.tsSolutionFiles,
2072
- this.guidedConfig?.cppSolutionFiles
2130
+ this.guidedConfig?.cppSolutionFiles,
2131
+ this.guidedConfig?.pySolutionFiles
2073
2132
  );
2074
2133
  }
2075
2134
 
@@ -2093,6 +2152,20 @@ int main() {
2093
2152
 
2094
2153
  _pickDefaultFile() {
2095
2154
  const names = Object.keys(this.files);
2155
+ if (this.lang === 'py') {
2156
+ if (this.guidedConfig?.mainFile) {
2157
+ const pyMain = this.guidedConfig.mainFile.replace(/\.(js|ts|cpp)$/, '.py');
2158
+ if (this.files[pyMain]) return pyMain;
2159
+ }
2160
+ if (this.files['main.py']) return 'main.py';
2161
+ if (this.files['solution.py']) return 'solution.py';
2162
+ if (this.files['app.py']) return 'app.py';
2163
+ const pyImpl = names.find(f =>
2164
+ /\.py$/i.test(f) &&
2165
+ !/(^|\/)(demo|test.*|.*_test)\.py$/i.test(f)
2166
+ );
2167
+ return pyImpl || names.find(f => !f.endsWith('.md')) || names[0] || '';
2168
+ }
2096
2169
  if (this.lang === 'cpp') {
2097
2170
  if (this.guidedConfig?.mainFile) {
2098
2171
  const cppMain = this.guidedConfig.mainFile.replace(/\.(js|ts)$/, '.hpp');
@@ -2124,6 +2197,29 @@ int main() {
2124
2197
 
2125
2198
  _findEntryFile(kind) {
2126
2199
  const names = Object.keys(this.files);
2200
+ if (this.lang === 'py') {
2201
+ if (kind === 'test') {
2202
+ if (this.explicitTestEntry) {
2203
+ const pyTest = this.explicitTestEntry.replace(/\.(js|ts|cpp)$/, '.py');
2204
+ if (this.files[pyTest]) return pyTest;
2205
+ if (this.files[this.explicitTestEntry]) return this.explicitTestEntry;
2206
+ }
2207
+ if (this.files['test.py']) return 'test.py';
2208
+ if (this.files['test_main.py']) return 'test_main.py';
2209
+ return names.find(f => /(^|\/)(test.*|.*_test)\.py$/i.test(f)) || null;
2210
+ }
2211
+ if (this.explicitEntry) {
2212
+ const pyEntry = this.explicitEntry.replace(/\.(js|ts|cpp)$/, '.py');
2213
+ if (this.files[pyEntry]) return pyEntry;
2214
+ if (this.files[this.explicitEntry]) return this.explicitEntry;
2215
+ }
2216
+ if (this.files['main.py']) return 'main.py';
2217
+ if (this.files['demo.py']) return 'demo.py';
2218
+ if (this.files['app.py']) return 'app.py';
2219
+ return names.find(f => /(^|\/)(main|demo|app)\.py$/i.test(f)) ||
2220
+ names.find(f => /\.py$/i.test(f) && !/(^|\/)(test.*|.*_test)\.py$/i.test(f)) ||
2221
+ null;
2222
+ }
2127
2223
  if (this.lang === 'cpp') {
2128
2224
  if (kind === 'test') {
2129
2225
  if (this.explicitTestEntry) {
@@ -2155,16 +2251,16 @@ int main() {
2155
2251
  if (this.files[candidate]) return candidate;
2156
2252
  if (this.files[this.explicitEntry]) return this.explicitEntry;
2157
2253
  }
2158
- const pattern = kind === 'test' ? /(^|\/)test\.(js|ts|cpp|cc|cxx)$/i : /(^|\/)(demo|main)\.(js|ts|cpp|cc|cxx)$/i;
2254
+ const pattern = kind === 'test' ? /(^|\/)test\.(js|ts|cpp|cc|cxx|py)$/i : /(^|\/)(demo|main)\.(js|ts|cpp|cc|cxx|py)$/i;
2159
2255
  const found = names.find(f => pattern.test(f));
2160
2256
  if (found) return found;
2161
2257
  if (kind === 'demo') {
2162
- const isConfigOrTest = f => /(^|\/)(test|.*\.(?:test|spec|config|d))\.(js|ts|mjs|cjs|cpp|cc|cxx)$/i.test(f) || /(^|\/)\.[^/]+$/i.test(f);
2258
+ const isConfigOrTest = f => /(^|\/)(test|.*\.(?:test|spec|config|d))\.(js|ts|mjs|cjs|cpp|cc|cxx|py)$/i.test(f) || /(^|\/)\.[^/]+$/i.test(f);
2163
2259
  const hasHtmlEntry = Boolean(this.files['index.html'] || this.files['public/index.html']);
2164
2260
  if (hasHtmlEntry) {
2165
2261
  return names.find(f => /(^|\/)(server|app|demo)\.(js|ts)$/i.test(f) && !/^src\//i.test(f)) || null;
2166
2262
  }
2167
- return names.find(f => /\.(js|ts|cpp|cc|cxx)$/i.test(f) && !isConfigOrTest(f)) || null;
2263
+ return names.find(f => /\.(js|ts|cpp|cc|cxx|py)$/i.test(f) && !isConfigOrTest(f)) || null;
2168
2264
  }
2169
2265
  return null;
2170
2266
  }
@@ -2186,11 +2282,19 @@ int main() {
2186
2282
  ? 'Send Ctrl+C — interrupt the running command'
2187
2283
  : 'Send Ctrl+C (clears the current input line)';
2188
2284
  }
2189
- this.container.querySelectorAll('[data-cl-action="run-demo"], [data-cl-action="run-tests"], [data-cl-action="verify-step"]').forEach(btn => {
2285
+ this.container.querySelectorAll('[data-cl-action="run-code"], [data-cl-action="run-entry"], [data-cl-action="run-active-file"], [data-cl-action="run-demo"], [data-cl-action="run-tests"], [data-cl-action="verify-step"]').forEach(btn => {
2190
2286
  btn.disabled = this.isRunning;
2191
2287
  });
2192
2288
  }
2193
2289
 
2290
+ _hasWebContent() {
2291
+ if (this.showWebPreviewOption === true) return true;
2292
+ if (!this.files) return false;
2293
+ if (this.files['index.html'] || this.files['src/index.html'] || this.files['public/index.html']) return true;
2294
+ if (this.portTable && typeof this.portTable.listServers === 'function' && this.portTable.listServers().length > 0) return true;
2295
+ return false;
2296
+ }
2297
+
2194
2298
  _renderLanguageSwitcherHtml() {
2195
2299
  const hasMulti = Boolean(
2196
2300
  this.hasMultipleLanguages ||
@@ -2203,11 +2307,13 @@ int main() {
2203
2307
  !this.enabledLanguages.has('cpp')
2204
2308
  );
2205
2309
  const showCpp = Boolean(this.enabledLanguages && this.enabledLanguages.has('cpp'));
2310
+ const showPy = Boolean(this.enabledLanguages && this.enabledLanguages.has('py'));
2206
2311
  return `
2207
2312
  <div class="codelab-lang-switch" role="group" aria-label="Language Selector">
2208
2313
  <button type="button" class="codelab-lang-btn ${this.lang === 'js' ? 'active' : ''}" data-cl-lang="js" data-lang="js" aria-pressed="${this.lang === 'js'}">JS</button>
2209
2314
  ${showTs ? `<button type="button" class="codelab-lang-btn ${this.lang === 'ts' ? 'active' : ''}" data-cl-lang="ts" data-lang="ts" aria-pressed="${this.lang === 'ts'}">TS</button>` : ''}
2210
2315
  ${showCpp ? `<button type="button" class="codelab-lang-btn ${this.lang === 'cpp' ? 'active' : ''}" data-cl-lang="cpp" data-lang="cpp" aria-pressed="${this.lang === 'cpp'}">C++</button>` : ''}
2316
+ ${showPy ? `<button type="button" class="codelab-lang-btn ${this.lang === 'py' ? 'active' : ''}" data-cl-lang="py" data-lang="py" aria-pressed="${this.lang === 'py'}">PY</button>` : ''}
2211
2317
  </div>
2212
2318
  `;
2213
2319
  }
@@ -2229,6 +2335,75 @@ int main() {
2229
2335
  }
2230
2336
  }
2231
2337
 
2338
+ _refreshToolbarAndTabs() {
2339
+ if (!this.container) return;
2340
+ this._refreshLanguageSwitcher();
2341
+ const topbar = this.container.querySelector('.codelab-topbar');
2342
+ if (topbar) {
2343
+ const previewBtn = topbar.querySelector('#cl-preview-app-btn');
2344
+ const hasWeb = this._hasWebContent();
2345
+ if (hasWeb) {
2346
+ if (!previewBtn) {
2347
+ const stopBtn = topbar.querySelector('#cl-stop-btn');
2348
+ if (stopBtn && stopBtn.parentElement) {
2349
+ const globeHtml = `<button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run &amp; Preview in Browser" aria-label="Run and Preview in Browser">${CL_ICONS.globe}</button>`;
2350
+ stopBtn.insertAdjacentHTML('afterend', globeHtml);
2351
+ }
2352
+ } else {
2353
+ previewBtn.style.display = 'inline-flex';
2354
+ }
2355
+ } else if (previewBtn) {
2356
+ previewBtn.style.display = 'none';
2357
+ }
2358
+ }
2359
+ this._refreshDrawerTabs();
2360
+ }
2361
+
2362
+ _refreshDrawerTabs() {
2363
+ if (!this.container) return;
2364
+ const drawerTabs = this.container.querySelector('.codelab-drawer__tabs');
2365
+ if (!drawerTabs) return;
2366
+
2367
+ const isGuided = Boolean(this.hasGuidedLab && this.mode === 'guided');
2368
+ const showTests = isGuided || this.testSuiteVisible || this.drawerTab === 'tests';
2369
+ const hasWeb = this._hasWebContent();
2370
+ const problemsCount = this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function'
2371
+ ? this._diagnosticsStore.getAll().length
2372
+ : 0;
2373
+
2374
+ let probTab = drawerTabs.querySelector('[data-cl-drawertab="problems"]');
2375
+ if (!probTab) {
2376
+ const termTab = drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
2377
+ if (termTab) {
2378
+ termTab.insertAdjacentHTML('afterend', `
2379
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'problems'}" class="codelab-drawer__tab ${this.drawerTab === 'problems' ? 'active' : ''}" data-cl-drawertab="problems" title="Compiler &amp; Runtime Problems">
2380
+ ${CL_ICONS.warning}
2381
+ <span>Problems</span>
2382
+ <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>
2383
+ </button>
2384
+ `);
2385
+ }
2386
+ } else {
2387
+ const countSpan = probTab.querySelector('#cl-problems-count');
2388
+ if (countSpan) countSpan.textContent = String(problemsCount);
2389
+ }
2390
+
2391
+
2392
+ let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
2393
+ if (!stdinTab) {
2394
+ const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
2395
+ if (afterTab) {
2396
+ afterTab.insertAdjacentHTML('afterend', `
2397
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'stdin'}" class="codelab-drawer__tab ${this.drawerTab === 'stdin' ? 'active' : ''}" data-cl-drawertab="stdin" title="Standard Input">
2398
+ ${CL_ICONS.keyboard}
2399
+ <span>Stdin</span>
2400
+ </button>
2401
+ `);
2402
+ }
2403
+ }
2404
+
2405
+ }
2406
+
2232
2407
  // ── Render Workbench DOM ───────────────────────────────────────────────
2233
2408
  _renderShell() {
2234
2409
  if (this.themeOption !== 'auto') {
@@ -2270,6 +2445,12 @@ int main() {
2270
2445
  </div>
2271
2446
  ` : ''}
2272
2447
  ${this._renderLanguageSwitcherHtml()}
2448
+ <span class="codelab-toolbar__sep" aria-hidden="true"></span>
2449
+ <button type="button" class="codelab-cmd-trigger" data-cl-action="command-palette" title="Open Command Palette (⌘K / ⇧⌘P)">
2450
+ ${CL_ICONS.search}
2451
+ <span>Command Palette</span>
2452
+ <kbd style="opacity:0.7">⇧⌘P</kbd>
2453
+ </button>
2273
2454
  </div>
2274
2455
 
2275
2456
  <div class="codelab-topbar__right">
@@ -2277,18 +2458,50 @@ int main() {
2277
2458
  ${CL_ICONS.stop}
2278
2459
  <span>Stop</span>
2279
2460
  </button>
2280
- <button type="button" class="codelab-btn codelab-btn--run" data-cl-action="run-demo" title="Run demo.js (⌘+Shift+Enter)">
2281
- ${CL_ICONS.play}
2282
- <span>Run Demo</span>
2283
- <span class="codelab-btn__kbd">⇧⌘↵</span>
2284
- </button>
2285
- <button type="button" class="codelab-btn codelab-btn--test" id="cl-primary-exec-btn" data-cl-action="${(this.hasGuidedLab && this.mode === 'guided') ? 'verify-step' : 'run-tests'}" title="${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Current Step (⌘+Enter)' : 'Run Test Suite (⌘+Enter)'}">
2286
- ${CL_ICONS.check}
2287
- <span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
2288
- <span class="codelab-btn__kbd">⌘↵</span>
2461
+ ${(this.hasGuidedLab && this.mode === 'guided') ? `
2462
+ <button type="button" class="codelab-btn codelab-btn--run" data-cl-action="run-demo" title="Run demo.js (⌘+Shift+Enter)">
2463
+ ${CL_ICONS.play}
2464
+ <span>Run Demo</span>
2465
+ <span class="codelab-btn__kbd">⇧⌘↵</span>
2466
+ </button>
2467
+ <button type="button" class="codelab-btn codelab-btn--test" id="cl-primary-exec-btn" data-cl-action="verify-step" title="Verify Current Step (⌘+Enter)">
2468
+ ${CL_ICONS.check}
2469
+ <span>Verify Step</span>
2470
+ <span class="codelab-btn__kbd">⌘↵</span>
2471
+ </button>
2472
+ ` : `
2473
+ <div class="codelab-btn-split">
2474
+ <button type="button" class="codelab-btn codelab-btn--run codelab-btn-split__main" id="cl-primary-exec-btn" data-cl-action="run-code" title="Run Code (⌘↵)">
2475
+ ${CL_ICONS.play}
2476
+ <span>Run Code</span>
2477
+ <span class="codelab-btn__kbd">⌘↵</span>
2478
+ </button>
2479
+ <button type="button" class="codelab-btn codelab-btn--run codelab-btn-split__trigger" id="cl-split-run-trigger" title="More Execution Options" aria-haspopup="true">
2480
+ ${CL_ICONS.chevronDown}
2481
+ </button>
2482
+ <div class="codelab-split-menu" id="cl-split-run-menu">
2483
+ <button type="button" class="codelab-split-menu__item" data-cl-action="run-demo">
2484
+ <span>▶ Run Entry / Demo</span> <kbd style="opacity:0.6">⌘↵</kbd>
2485
+ </button>
2486
+ <button type="button" class="codelab-split-menu__item" data-cl-action="run-active-file">
2487
+ <span>▶ Run Active File (${escapeHtml(this.activeFile || 'active')})</span> <kbd style="opacity:0.6">⇧⌘↵</kbd>
2488
+ </button>
2489
+ ${this._findEntryFile('test') ? `
2490
+ <button type="button" class="codelab-split-menu__item" data-cl-action="run-tests">
2491
+ <span>✓ Run Test Suite</span>
2492
+ </button>
2493
+ ` : ''}
2494
+ <button type="button" class="codelab-split-menu__item" data-cl-action="open-stdin">
2495
+ <span>⌨ Configure Stdin / Input...</span>
2496
+ </button>
2497
+ </div>
2498
+ </div>
2499
+ `}
2500
+ <button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run &amp; Preview in Browser" aria-label="Run and Preview in Browser" style="display: ${this._hasWebContent() ? 'inline-flex' : 'none'}">
2501
+ ${CL_ICONS.globe}
2289
2502
  </button>
2290
- <button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run &amp; Preview in Browser (built-in dev server)" aria-label="Run and Preview in Browser">
2291
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
2503
+ <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="share-snapshot" title="Share Snapshot Link (#codelab=...)" aria-label="Share Snapshot Link">
2504
+ ${CL_ICONS.share}
2292
2505
  </button>
2293
2506
  <span class="codelab-toolbar__sep" aria-hidden="true"></span>
2294
2507
  ${this.hasGuidedLab ? `
@@ -2386,14 +2599,23 @@ int main() {
2386
2599
  <div class="codelab-drawer codelab-bottom" id="cl-drawer">
2387
2600
  <div class="codelab-drawer__bar">
2388
2601
  <div class="codelab-drawer__tabs" role="tablist" aria-label="Execution Output Panels">
2602
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'terminal'}" class="codelab-drawer__tab ${this.drawerTab === 'terminal' ? 'active' : ''}" data-cl-drawertab="terminal">
2603
+ ${CL_ICONS.terminal}
2604
+ <span>Terminal &amp; REPL</span>
2605
+ </button>
2606
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'problems'}" class="codelab-drawer__tab ${this.drawerTab === 'problems' ? 'active' : ''}" data-cl-drawertab="problems" title="Compiler &amp; Runtime Problems">
2607
+ ${CL_ICONS.warning}
2608
+ <span>Problems</span>
2609
+ <span class="codelab-badge" id="cl-problems-count" style="margin-left:4px;font-size:10px;padding:1px 5px;border-radius:10px;background:rgba(255,255,255,0.1);color:#fff;">${this._diagnosticsStore ? this._diagnosticsStore.getAll().length : 0}</span>
2610
+ </button>
2389
2611
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'tests'}" class="codelab-drawer__tab ${this.drawerTab === 'tests' ? 'active' : ''}" data-cl-drawertab="tests">
2390
2612
  ${CL_ICONS.check}
2391
2613
  <span>Test Suite</span>
2392
2614
  <span class="codelab-drawer__pill" id="cl-test-pill">Ready</span>
2393
2615
  </button>
2394
- <button type="button" role="tab" aria-selected="${this.drawerTab === 'terminal'}" class="codelab-drawer__tab ${this.drawerTab === 'terminal' ? 'active' : ''}" data-cl-drawertab="terminal">
2395
- ${CL_ICONS.terminal}
2396
- <span>Terminal &amp; REPL</span>
2616
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'stdin'}" class="codelab-drawer__tab ${this.drawerTab === 'stdin' ? 'active' : ''}" data-cl-drawertab="stdin" title="Standard Input">
2617
+ ${CL_ICONS.keyboard}
2618
+ <span>Stdin</span>
2397
2619
  </button>
2398
2620
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'ports'}" class="codelab-drawer__tab ${this.drawerTab === 'ports' ? 'active' : ''}" data-cl-drawertab="ports">
2399
2621
  ${CL_ICONS.radio}
@@ -2401,7 +2623,7 @@ int main() {
2401
2623
  <span class="codelab-drawer__pill" id="cl-ports-pill">${this.portTable && typeof this.portTable.listServers === 'function' ? this.portTable.listServers().length : 0} open</span>
2402
2624
  </button>
2403
2625
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'preview'}" class="codelab-drawer__tab ${this.drawerTab === 'preview' ? 'active' : ''}" data-cl-drawertab="preview" title="In-browser Web Preview">
2404
- ${CL_ICONS.externalLink || CL_ICONS.radio || ''}
2626
+ ${CL_ICONS.globe}
2405
2627
  <span>Web Preview</span>
2406
2628
  </button>
2407
2629
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'network'}" class="codelab-drawer__tab ${this.drawerTab === 'network' ? 'active' : ''}" data-cl-drawertab="network">
@@ -2415,6 +2637,7 @@ int main() {
2415
2637
  <span class="codelab-drawer__pill" id="cl-vfs-pill">0 files</span>
2416
2638
  </button>
2417
2639
  </div>
2640
+ <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
2418
2641
  <div style="display:flex;align-items:center;gap:6px;">
2419
2642
  <button type="button" class="codelab-btn codelab-btn--icon codelab-btn--ctrl-c" id="cl-ctrl-c-btn" data-cl-action="interrupt" title="Send Ctrl+C — interrupt a running command" aria-label="Send Ctrl+C interrupt" style="padding:2px 8px;font-size:11px;font-family:var(--cl-font-mono);">Ctrl+C</button>
2420
2643
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="clear-terminal" title="Clear Output" style="padding:2px 6px;font-size:11px;">Clear</button>
@@ -2443,7 +2666,7 @@ int main() {
2443
2666
  <span class="codelab-statusbar__sep">·</span>
2444
2667
  <span class="codelab-statusbar__item">UTF-8</span>
2445
2668
  <span class="codelab-statusbar__sep">·</span>
2446
- <span class="codelab-statusbar__item" id="cl-status-lang">${this.lang === 'cpp' ? 'C++20 (Clang/WASI)' : this.lang === 'ts' ? 'TypeScript 5.x' : 'JavaScript (CJS/ESM)'}</span>
2669
+ <span class="codelab-statusbar__item" id="cl-status-lang">${this.lang === 'cpp' ? 'C++20 (Clang/WASI)' : this.lang === 'py' ? 'Python 3.12 (CPython WASI)' : this.lang === 'ts' ? 'TypeScript 5.x' : 'JavaScript (CJS/ESM)'}</span>
2447
2670
  </div>
2448
2671
  </footer>
2449
2672
 
@@ -3452,6 +3675,15 @@ int main() {
3452
3675
  });
3453
3676
 
3454
3677
  // Update pills
3678
+ const problemsCountEl = this.container.querySelector('#cl-problems-count');
3679
+ if (problemsCountEl) {
3680
+ const count = this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function'
3681
+ ? this._diagnosticsStore.getAll().length
3682
+ : 0;
3683
+ problemsCountEl.textContent = String(count);
3684
+ }
3685
+ this._updateTelemetryHud();
3686
+
3455
3687
  if (testPill) {
3456
3688
  if (!this.lastTestResults.length) {
3457
3689
  testPill.textContent = 'Ready';
@@ -3479,6 +3711,61 @@ int main() {
3479
3711
  vfsPill.textContent = httpCount > 0 ? `${diskCount} files · ${httpCount} reqs` : `${diskCount} files`;
3480
3712
  }
3481
3713
 
3714
+ if (this.drawerTab === 'problems') {
3715
+ const store = this._diagnosticsStore;
3716
+ const problems = store && typeof store.getAll === 'function' ? store.getAll() : [];
3717
+ if (!problems.length) {
3718
+ bodyEl.innerHTML = `
3719
+ <div style="color:var(--cl-fg-muted);padding:16px;text-align:center;">
3720
+ ${CL_ICONS.check} No problems detected in workspace.
3721
+ </div>
3722
+ `;
3723
+ return;
3724
+ }
3725
+ bodyEl.innerHTML = `
3726
+ <div class="codelab-problems-list">
3727
+ ${problems.map(p => {
3728
+ const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
3729
+ const cls = p.severity === 'error' ? 'codelab-problem-item--error' : (p.severity === 'warning' ? 'codelab-problem-item--warning' : 'codelab-problem-item--info');
3730
+ return `
3731
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${p.col || 1}" role="button" tabindex="0">
3732
+ <span class="codelab-problem-item__icon">${icon}</span>
3733
+ <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
3734
+ <span class="codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${p.col || 1}</span>
3735
+ </div>
3736
+ `;
3737
+ }).join('')}
3738
+ </div>
3739
+ `;
3740
+ return;
3741
+ }
3742
+
3743
+ if (this.drawerTab === 'stdin') {
3744
+ bodyEl.innerHTML = `
3745
+ <div class="codelab-stdin-panel" style="padding:10px;height:100%;display:flex;flex-direction:column;box-sizing:border-box;">
3746
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;font-size:12px;color:var(--cl-fg-muted);">
3747
+ <span>Standard Input (std::cin / sys.stdin / process.stdin)</span>
3748
+ <button type="button" class="codelab-btn codelab-btn--sm" id="cl-stdin-clear-btn" style="padding:2px 8px;font-size:11px;">Clear</button>
3749
+ </div>
3750
+ <textarea id="cl-stdin-textarea" class="codelab-stdin-textarea" style="flex:1;width:100%;background:var(--cl-bg-input, #1e1e1e);color:var(--cl-fg, #d4d4d4);border:1px solid var(--cl-border, #333);border-radius:4px;padding:8px;font-family:var(--cl-font-mono, monospace);font-size:12px;resize:none;outline:none;box-sizing:border-box;" placeholder="Enter or paste custom stdin here (used by std::cin, sys.stdin, fs.readFileSync(0))...">${escapeHtml(this.customStdin || '')}</textarea>
3751
+ </div>
3752
+ `;
3753
+ const ta = bodyEl.querySelector('#cl-stdin-textarea');
3754
+ if (ta) {
3755
+ ta.addEventListener('input', () => {
3756
+ this.customStdin = ta.value;
3757
+ });
3758
+ }
3759
+ const clearBtn = bodyEl.querySelector('#cl-stdin-clear-btn');
3760
+ if (clearBtn && ta) {
3761
+ clearBtn.addEventListener('click', () => {
3762
+ this.customStdin = '';
3763
+ ta.value = '';
3764
+ });
3765
+ }
3766
+ return;
3767
+ }
3768
+
3482
3769
  if (this.drawerTab === 'tests') {
3483
3770
  if (!this.lastTestResults.length) {
3484
3771
  bodyEl.innerHTML = `
@@ -3837,6 +4124,33 @@ int main() {
3837
4124
  }
3838
4125
  }
3839
4126
 
4127
+ _updateTelemetryHud() {
4128
+ const hud = this.container ? this.container.querySelector('#cl-telemetry-hud') : null;
4129
+ if (!hud) return;
4130
+ if (this.lastDurationMs === null && this.lastPeakMemoryBytes === null) {
4131
+ hud.style.display = 'none';
4132
+ return;
4133
+ }
4134
+ hud.style.display = 'inline-flex';
4135
+ let timeStr = '';
4136
+ if (this.lastDurationMs !== null) {
4137
+ timeStr = this.lastDurationMs < 1000
4138
+ ? `${this.lastDurationMs.toFixed(1)} ms`
4139
+ : `${(this.lastDurationMs / 1000).toFixed(2)} s`;
4140
+ }
4141
+ let memStr = '';
4142
+ if (this.lastPeakMemoryBytes !== null && this.lastPeakMemoryBytes > 0) {
4143
+ const mb = this.lastPeakMemoryBytes / (1024 * 1024);
4144
+ const suffix = this.lang === 'cpp' ? 'Wasm' : this.lang === 'py' ? 'Heap' : 'Mem';
4145
+ memStr = `${mb < 0.1 ? (this.lastPeakMemoryBytes / 1024).toFixed(1) + ' KB' : mb.toFixed(1) + ' MB'} ${suffix}`;
4146
+ }
4147
+ hud.innerHTML = `
4148
+ ${timeStr ? `<span class="codelab-hud-pill__metric">${CL_ICONS.clock} <span>${timeStr}</span></span>` : ''}
4149
+ ${timeStr && memStr ? `<span style="opacity:0.4;">·</span>` : ''}
4150
+ ${memStr ? `<span class="codelab-hud-pill__metric">${CL_ICONS.memory} <span>${memStr}</span></span>` : ''}
4151
+ `;
4152
+ }
4153
+
3840
4154
  _handleInterrupt() {
3841
4155
  const isCommandRunning = Boolean(this.isRunning || this._activeCommandAbortController);
3842
4156
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
@@ -5932,13 +6246,19 @@ int main() {
5932
6246
  let model = typeof this.monaco.editor.getModel === 'function' ? this.monaco.editor.getModel(uri) : null;
5933
6247
  const lang = /\.(cpp|cc|cxx|hpp|h)$/i.test(filename)
5934
6248
  ? 'cpp'
5935
- : filename.endsWith('.ts')
5936
- ? 'typescript'
5937
- : filename.endsWith('.json')
5938
- ? 'json'
5939
- : filename.endsWith('.md')
5940
- ? 'markdown'
5941
- : 'javascript';
6249
+ : /\.py$/i.test(filename)
6250
+ ? 'python'
6251
+ : filename.endsWith('.ts')
6252
+ ? 'typescript'
6253
+ : filename.endsWith('.json')
6254
+ ? 'json'
6255
+ : filename.endsWith('.html')
6256
+ ? 'html'
6257
+ : filename.endsWith('.css')
6258
+ ? 'css'
6259
+ : filename.endsWith('.md')
6260
+ ? 'markdown'
6261
+ : 'javascript';
5942
6262
  if (!model) {
5943
6263
  model = this.monaco.editor.createModel(this.files[filename] || '', lang, uri);
5944
6264
  if (model && typeof model.onDidChangeContent === 'function') {
@@ -5947,6 +6267,12 @@ int main() {
5947
6267
  this.files[filename] = val;
5948
6268
  this._saveState();
5949
6269
  this._notifyCodeChange(filename, val);
6270
+ if (this.lang === 'py' && typeof this._pyLintHandler === 'function') {
6271
+ this._pyLintHandler(filename, val);
6272
+ }
6273
+ if (this.lang === 'cpp' && typeof this._cppLintHandler === 'function') {
6274
+ this._cppLintHandler(filename, val);
6275
+ }
5950
6276
  });
5951
6277
  }
5952
6278
  } else if (model.getValue() !== (this.files[filename] || '')) {
@@ -6049,6 +6375,9 @@ int main() {
6049
6375
 
6050
6376
  // ── Event Delegation & Interactive Splitters ───────────────────────────
6051
6377
  _bindEvents() {
6378
+ if (this._eventsBound) return;
6379
+ this._eventsBound = true;
6380
+
6052
6381
  this._bindSplitters();
6053
6382
 
6054
6383
  this._escHandler = e => {
@@ -6117,6 +6446,16 @@ int main() {
6117
6446
  this.openCommandPalette('commands');
6118
6447
  return;
6119
6448
  }
6449
+ if ((e.metaKey || e.ctrlKey) && keyLower === 'k') {
6450
+ e.preventDefault();
6451
+ this.openCommandPalette('commands');
6452
+ return;
6453
+ }
6454
+ if (e.altKey && e.shiftKey && keyLower === 'f') {
6455
+ e.preventDefault();
6456
+ this.formatActiveDocument();
6457
+ return;
6458
+ }
6120
6459
  if ((e.metaKey || e.ctrlKey) && !e.shiftKey && keyLower === 'p') {
6121
6460
  e.preventDefault();
6122
6461
  this.openCommandPalette('files');
@@ -6133,11 +6472,15 @@ int main() {
6133
6472
  if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
6134
6473
  e.preventDefault();
6135
6474
  if (e.shiftKey) {
6136
- this.runDemo();
6475
+ if (this.mode === 'guided') {
6476
+ this.runDemo();
6477
+ } else {
6478
+ this.runActiveFile();
6479
+ }
6137
6480
  } else if (this.mode === 'guided') {
6138
6481
  this.verifyCurrentStep();
6139
6482
  } else {
6140
- this.runTests();
6483
+ this.runCode();
6141
6484
  }
6142
6485
  }
6143
6486
  });
@@ -6414,6 +6757,36 @@ int main() {
6414
6757
  return;
6415
6758
  }
6416
6759
 
6760
+ const splitTrigger = e.target.closest('#cl-split-run-trigger');
6761
+ if (splitTrigger) {
6762
+ e.stopPropagation();
6763
+ const menu = this.container.querySelector('#cl-split-run-menu');
6764
+ if (menu) menu.classList.toggle('active');
6765
+ return;
6766
+ }
6767
+
6768
+ const splitMenu = this.container.querySelector('#cl-split-run-menu');
6769
+ if (splitMenu && splitMenu.classList.contains('active') && !e.target.closest('.codelab-btn-split')) {
6770
+ splitMenu.classList.remove('active');
6771
+ }
6772
+
6773
+ const problemItem = e.target.closest('[data-cl-problem-file]');
6774
+ if (problemItem) {
6775
+ e.stopPropagation();
6776
+ const pFile = problemItem.dataset.clProblemFile;
6777
+ const pLine = Number(problemItem.dataset.clProblemLine || 1);
6778
+ const pCol = Number(problemItem.dataset.clProblemCol || 1);
6779
+ if (pFile) {
6780
+ this.openFile(pFile);
6781
+ if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
6782
+ this.editor.revealLineInCenter(pLine);
6783
+ this.editor.setPosition({ lineNumber: pLine, column: pCol });
6784
+ this.editor.focus();
6785
+ }
6786
+ }
6787
+ return;
6788
+ }
6789
+
6417
6790
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
6418
6791
  if (drawerTabBtn) {
6419
6792
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -6422,8 +6795,16 @@ int main() {
6422
6795
 
6423
6796
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
6424
6797
  if (actionBtn) {
6798
+ if (splitMenu && splitMenu.classList.contains('active')) {
6799
+ splitMenu.classList.remove('active');
6800
+ }
6425
6801
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
6426
- if (action === 'run-demo') this.runDemo();
6802
+ if (action === 'run-code') this.runCode();
6803
+ else if (action === 'run-entry') this.runEntry();
6804
+ else if (action === 'run-active-file') this.runActiveFile();
6805
+ else if (action === 'open-stdin') this.switchDrawerTab('stdin');
6806
+ else if (action === 'share-snapshot') this.shareSnapshot();
6807
+ else if (action === 'run-demo') this.runDemo();
6427
6808
  else if (action === 'run-tests') this.runTests();
6428
6809
  else if (action === 'stop-run') this.stopExecution();
6429
6810
  else if (action === 'interrupt') this._handleInterrupt();
@@ -6711,9 +7092,15 @@ int main() {
6711
7092
  // ── VS Code Command Palette & Quick Open ────────────────────────────────
6712
7093
  _getPaletteCommands() {
6713
7094
  return [
7095
+ { id: 'run-code', label: 'CodeLab: Run Code (Entry or Active File)', shortcut: '⌘↵', action: () => this.runCode() },
7096
+ { id: 'run-active', label: 'CodeLab: Run Active File', shortcut: '⇧⌘↵', action: () => this.runActiveFile() },
6714
7097
  { id: 'run-demo', label: 'CodeLab: Run Demo Script', shortcut: '⇧⌘↵', action: () => this.runDemo() },
6715
7098
  { id: 'run-tests', label: 'CodeLab: Run Unit Tests', shortcut: '⌘↵', action: () => this.runTests() },
6716
7099
  { id: 'verify-step', label: 'CodeLab: Verify Current Guided Step', shortcut: '⌘↵', action: () => this.verifyCurrentStep() },
7100
+ { id: 'format-document', label: 'Editor: Format Document', shortcut: '⇧⌥F', action: () => this.formatActiveDocument() },
7101
+ { id: 'share-snapshot', label: 'CodeLab: Share Snapshot Link (#codelab=...)', action: () => this.shareSnapshot() },
7102
+ { id: 'open-stdin', label: 'View: Open Stdin / Custom Input Panel', action: () => this.switchDrawerTab('stdin') },
7103
+ { id: 'view-problems-tab', label: 'View: Focus Problems Drawer Tab', action: () => this.switchDrawerTab('problems') },
6717
7104
  { id: 'compare-solution', label: 'CodeLab: Compare Active File with Reference Solution (Diff)', action: () => this.showDiffModal(this.activeFile || this._pickDefaultFile(), 'solution') },
6718
7105
  { id: 'compare-starter', label: 'CodeLab: Compare Active File with Starter Template (Diff)', action: () => this.showDiffModal(this.activeFile || this._pickDefaultFile(), 'starter') },
6719
7106
  { id: 'apply-solution', label: 'CodeLab: Apply Reference Solution to Active File', action: () => this.applyReferenceSolution() },
@@ -6724,9 +7111,10 @@ int main() {
6724
7111
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
6725
7112
  { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
6726
7113
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
6727
- { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript / C++', action: () => {
7114
+ { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript / C++ / Python', action: () => {
6728
7115
  const order = ['js', 'ts'];
6729
7116
  if (this.enabledLanguages && this.enabledLanguages.has('cpp')) order.push('cpp');
7117
+ if (this.enabledLanguages && this.enabledLanguages.has('py')) order.push('py');
6730
7118
  const next = order[(order.indexOf(this.lang) + 1) % order.length] || 'js';
6731
7119
  this.setLanguage(next);
6732
7120
  } },
@@ -6922,6 +7310,31 @@ int main() {
6922
7310
  }
6923
7311
 
6924
7312
  showDiffModal(targetFile = null, compareTarget = 'solution') {
7313
+ const file = targetFile || this.activeFile || this._pickDefaultFile();
7314
+ if (!this._diffManager) {
7315
+ let DiffManagerCls = (root && root.CodeLabWorkbenchComponents && root.CodeLabWorkbenchComponents.CodeLabDiffEditorManager) ||
7316
+ (typeof globalThis !== 'undefined' && globalThis.CodeLabWorkbenchComponents && globalThis.CodeLabWorkbenchComponents.CodeLabDiffEditorManager) ||
7317
+ null;
7318
+ if (!DiffManagerCls && typeof require === 'function') {
7319
+ try {
7320
+ const mod = require('./workbench/diff-editor');
7321
+ DiffManagerCls = mod.CodeLabDiffEditorManager;
7322
+ } catch (err) {
7323
+ void err;
7324
+ }
7325
+ }
7326
+ if (DiffManagerCls) {
7327
+ this._diffManager = new DiffManagerCls(this);
7328
+ }
7329
+ }
7330
+ if (this._diffManager && typeof window !== 'undefined' && window.monaco && window.monaco.editor && typeof window.monaco.editor.createDiffEditor === 'function') {
7331
+ const ok = this._diffManager.openInlineDiff(file, compareTarget);
7332
+ if (ok) return;
7333
+ }
7334
+ this.showDiffModalFallback(file, compareTarget);
7335
+ }
7336
+
7337
+ showDiffModalFallback(targetFile = null, compareTarget = 'solution') {
6925
7338
  const slot = this.container.querySelector('#cl-modal-slot');
6926
7339
  if (!slot) return;
6927
7340
 
@@ -7307,7 +7720,7 @@ int main() {
7307
7720
  }
7308
7721
 
7309
7722
  setLanguage(newLang) {
7310
- if (newLang !== 'js' && newLang !== 'ts' && newLang !== 'cpp') return;
7723
+ if (newLang !== 'js' && newLang !== 'ts' && newLang !== 'cpp' && newLang !== 'py') return;
7311
7724
  if (this.lang === newLang) return;
7312
7725
  this.lang = newLang;
7313
7726
  if (this.enabledLanguages instanceof Set) {
@@ -7318,7 +7731,11 @@ int main() {
7318
7731
  this.activeFile = this._pickDefaultFile();
7319
7732
  this._saveState();
7320
7733
 
7321
- this._refreshLanguageSwitcher();
7734
+ if (typeof this._refreshToolbarAndTabs === 'function') {
7735
+ this._refreshToolbarAndTabs();
7736
+ } else {
7737
+ this._refreshLanguageSwitcher();
7738
+ }
7322
7739
  this.container.querySelectorAll('[data-cl-lang]').forEach(btn => {
7323
7740
  const isActive = btn.dataset.clLang === this.lang;
7324
7741
  btn.classList.toggle('active', isActive);
@@ -7328,6 +7745,7 @@ int main() {
7328
7745
  this._syncAllModels();
7329
7746
  this._syncActiveFileToView();
7330
7747
  this._renderGuidePane();
7748
+ this._updateStatusBar();
7331
7749
  }
7332
7750
 
7333
7751
  switchLang(newLang) {
@@ -7357,7 +7775,7 @@ int main() {
7357
7775
  if (mode === 'guided' || mode === 'sandbox') {
7358
7776
  this.setMode(mode);
7359
7777
  }
7360
- if (lang === 'js' || lang === 'ts' || lang === 'cpp') {
7778
+ if (lang === 'js' || lang === 'ts' || lang === 'cpp' || lang === 'py') {
7361
7779
  this.setLanguage(lang);
7362
7780
  }
7363
7781
  if (typeof stepIndex === 'number' && !Number.isNaN(stepIndex)) {
@@ -7612,6 +8030,7 @@ int main() {
7612
8030
  const payload = {
7613
8031
  ...execOptions,
7614
8032
  instanceId: this.instanceId,
8033
+ stdin: execOptions.stdin !== undefined ? execOptions.stdin : (this.customStdin || ''),
7615
8034
  cppCompiler: execOptions.cppCompiler || this.cppCompiler,
7616
8035
  onStdout: execOptions.onStdout || ((chunk) => this._appendTerminalStream('stdout', chunk)),
7617
8036
  onStderr: execOptions.onStderr || ((chunk) => this._appendTerminalStream('stderr', chunk)),
@@ -7619,7 +8038,8 @@ int main() {
7619
8038
  };
7620
8039
  try {
7621
8040
  const isCppEntry = Boolean(payload && typeof payload.entry === 'string' && /\.(cpp|cc|cxx|wasm)$/i.test(payload.entry));
7622
- if (!isCppEntry && typeof root.CodeLabRuntime?.preloadNpmPackages === 'function' && payload && payload.files) {
8041
+ const isPyEntry = Boolean(payload && typeof payload.entry === 'string' && /\.py$/i.test(payload.entry));
8042
+ if (!isCppEntry && !isPyEntry && typeof root.CodeLabRuntime?.preloadNpmPackages === 'function' && payload && payload.files) {
7623
8043
  const rawDetected = this._detectPackages();
7624
8044
  const detectedList = Array.isArray(rawDetected)
7625
8045
  ? rawDetected
@@ -7636,9 +8056,22 @@ int main() {
7636
8056
  payload.packages = Object.assign({}, preloaded, payload.packages || {});
7637
8057
  }
7638
8058
  }
7639
- this._setRuntimeStatus('running', isCppEntry ? `Compiling & Running ${payload.entry}...` : `Running ${payload.entry || payload.mode || 'script'}...`);
8059
+ this._setRuntimeStatus('running', isCppEntry ? `Compiling & Running ${payload.entry}...` : isPyEntry ? `Running Python 3.12: ${payload.entry}...` : `Running ${payload.entry || payload.mode || 'script'}...`);
7640
8060
  let res;
7641
- if (isCppEntry && typeof root.CodeLabRuntime?.executeInVirtualRuntime === 'function') {
8061
+ const pyRunner = this.pythonCompiler || (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) || (typeof root !== 'undefined' && root.__codelabPythonCompiler);
8062
+ if ((isPyEntry || this.lang === 'py') && pyRunner) {
8063
+ res = await pyRunner(payload);
8064
+ } else if (isPyEntry || this.lang === 'py') {
8065
+ this._setRuntimeStatus('error', 'Python 3.12 extension not loaded');
8066
+ return {
8067
+ ok: false,
8068
+ exitCode: 1,
8069
+ stdout: '',
8070
+ stderr: 'Python WebAssembly toolchain is not registered. Enable pythonExtension from "@innovatorved/code-lab/extensions/python" to run Python files.\n',
8071
+ durationMs: 0,
8072
+ peakMemoryBytes: 0
8073
+ };
8074
+ } else if (isCppEntry && typeof root.CodeLabRuntime?.executeInVirtualRuntime === 'function') {
7642
8075
  res = await root.CodeLabRuntime.executeInVirtualRuntime(payload);
7643
8076
  } else if (typeof root.CodeLabRuntime?.executeInWorker === 'function') {
7644
8077
  res = await root.CodeLabRuntime.executeInWorker(payload);
@@ -7649,6 +8082,9 @@ int main() {
7649
8082
  }
7650
8083
  const elapsed = Math.round((typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0);
7651
8084
  this.lastRunDurationMs = res && typeof res.durationMs === 'number' ? res.durationMs : elapsed;
8085
+ this.lastDurationMs = this.lastRunDurationMs;
8086
+ this.lastPeakMemoryBytes = res && typeof res.peakMemoryBytes === 'number' ? res.peakMemoryBytes : null;
8087
+ this._updateTelemetryHud();
7652
8088
  this._setRuntimeStatus('idle', 'Ready · Node v22 VFS');
7653
8089
  return res;
7654
8090
  } catch (err) {
@@ -7661,14 +8097,36 @@ int main() {
7661
8097
  }
7662
8098
  }
7663
8099
 
7664
- async runDemo() {
7665
- if (this.isRunning) return;
7666
- const entry = this._findEntryFile('demo');
8100
+ async runCode() {
8101
+ const entry = this._findEntryFile('demo') || this.activeFile || this._pickDefaultFile();
7667
8102
  if (!entry) {
7668
- if ((this.files['index.html'] || this.files['public/index.html']) && typeof this.previewApp === 'function') {
7669
- return this.previewApp();
7670
- }
7671
- this.terminalLogs.push({ type: 'stderr', text: 'No demo.js / demo.ts file found in this workspace.' });
8103
+ this.terminalLogs.push({ type: 'stderr', text: 'No entry file or active file to run.' });
8104
+ this.drawerTab = 'terminal';
8105
+ this._renderDrawerBody();
8106
+ return;
8107
+ }
8108
+ return this._executeEntryFile(entry);
8109
+ }
8110
+
8111
+ async runEntry() {
8112
+ return this.runCode();
8113
+ }
8114
+
8115
+ async runActiveFile() {
8116
+ const file = this.activeFile || this._pickDefaultFile();
8117
+ if (!file) {
8118
+ this.terminalLogs.push({ type: 'stderr', text: 'No active file to run.' });
8119
+ this.drawerTab = 'terminal';
8120
+ this._renderDrawerBody();
8121
+ return;
8122
+ }
8123
+ return this._executeEntryFile(file);
8124
+ }
8125
+
8126
+ async _executeEntryFile(entry) {
8127
+ if (this.isRunning) return;
8128
+ if (!entry || this.files[entry] === undefined) {
8129
+ this.terminalLogs.push({ type: 'stderr', text: `File not found: ${entry || 'entry'}` });
7672
8130
  this.drawerTab = 'terminal';
7673
8131
  this._renderDrawerBody();
7674
8132
  return;
@@ -7677,11 +8135,14 @@ int main() {
7677
8135
  this.isRunning = true;
7678
8136
  this._updateRunStateUI();
7679
8137
  this.drawerTab = 'terminal';
7680
- const isCppDemo = /\.(cpp|cc|cxx)$/i.test(entry);
7681
- this.terminalLogs.push({
7682
- type: 'system',
7683
- text: isCppDemo ? `\n$ g++ -std=c++20 ${entry} -o a.out && ./a.out` : `\n$ node ${entry}`
7684
- });
8138
+ const isCpp = /\.(cpp|cc|cxx)$/i.test(entry);
8139
+ const isPy = /\.py$/i.test(entry);
8140
+ const cmdText = isCpp
8141
+ ? `\n$ g++ -std=c++20 ${entry} -o a.out && ./a.out`
8142
+ : isPy
8143
+ ? `\n$ python3 ${entry}`
8144
+ : `\n$ node ${entry}`;
8145
+ this.terminalLogs.push({ type: 'system', text: cmdText });
7685
8146
  this._renderDrawerBody();
7686
8147
 
7687
8148
  let abortCtrl = new AbortController();
@@ -7695,6 +8156,7 @@ int main() {
7695
8156
  files: { ...this.files },
7696
8157
  entry,
7697
8158
  mode: 'run',
8159
+ stdin: this.customStdin || '',
7698
8160
  signal: abortCtrl.signal,
7699
8161
  onStdout: (c) => {
7700
8162
  streamedStdout = true;
@@ -7721,6 +8183,9 @@ int main() {
7721
8183
  if (!aborted) {
7722
8184
  this.lastFsSnapshot = res.fsSnapshot || [];
7723
8185
  this.lastHttpTrace = res.httpTrace || [];
8186
+ if (res.durationMs !== undefined) this.lastDurationMs = res.durationMs;
8187
+ if (res.peakMemoryBytes !== undefined) this.lastPeakMemoryBytes = res.peakMemoryBytes;
8188
+ this._updateTelemetryHud();
7724
8189
  }
7725
8190
 
7726
8191
  if (this.onRun) {
@@ -7744,23 +8209,199 @@ int main() {
7744
8209
  return lastRes;
7745
8210
  }
7746
8211
 
8212
+ async runDemo() {
8213
+ if (this.isRunning) return;
8214
+ const entry = this._findEntryFile('demo') || this._findEntryFile('entry') || this.activeFile;
8215
+ if (!entry) {
8216
+ if ((this.files['index.html'] || this.files['public/index.html']) && typeof this.previewApp === 'function') {
8217
+ return this.previewApp();
8218
+ }
8219
+ this.terminalLogs.push({ type: 'stderr', text: 'No entry or demo file found in this workspace.' });
8220
+ this.drawerTab = 'terminal';
8221
+ this._renderDrawerBody();
8222
+ return;
8223
+ }
8224
+ return this._executeEntryFile(entry);
8225
+ }
8226
+
8227
+ async formatActiveDocument() {
8228
+ if (!this.activeFile) return;
8229
+ const file = this.activeFile;
8230
+ const code = this.files[file] || '';
8231
+ if (!code) return;
8232
+
8233
+ if (file.endsWith('.js') || file.endsWith('.ts') || file.endsWith('.jsx') || file.endsWith('.tsx')) {
8234
+ if (this.editor && typeof this.editor.getAction === 'function') {
8235
+ const action = this.editor.getAction('editor.action.formatDocument');
8236
+ if (action && typeof action.run === 'function') {
8237
+ await action.run();
8238
+ const newCode = this.editor.getValue();
8239
+ this.files[file] = newCode;
8240
+ this._saveState();
8241
+ this._notifyCodeChange(file, newCode);
8242
+ return;
8243
+ }
8244
+ }
8245
+ } else if (file.endsWith('.cpp') || file.endsWith('.hpp') || file.endsWith('.cc') || file.endsWith('.h')) {
8246
+ let formatter = (root && root.CodeLabWorkbenchComponents && root.CodeLabWorkbenchComponents.formatCppSource) ||
8247
+ (typeof globalThis !== 'undefined' && globalThis.CodeLabWorkbenchComponents && globalThis.CodeLabWorkbenchComponents.formatCppSource) ||
8248
+ null;
8249
+ if (!formatter && typeof require === 'function') {
8250
+ try {
8251
+ const mod = require('./workbench/editor');
8252
+ formatter = mod.formatCppSource;
8253
+ } catch (err) {
8254
+ void err;
8255
+ }
8256
+ }
8257
+ if (formatter) {
8258
+ const formatted = formatter(code);
8259
+ if (formatted !== code) {
8260
+ this.files[file] = formatted;
8261
+ if (this.editor && this.editor.getModel()) {
8262
+ this.editor.setValue(formatted);
8263
+ }
8264
+ this._saveState();
8265
+ this._notifyCodeChange(file, formatted);
8266
+ }
8267
+ }
8268
+ } else if (file.endsWith('.py')) {
8269
+ let formatter = (root && root.CodeLabPython && root.CodeLabPython.formatPythonSource) ||
8270
+ (typeof globalThis !== 'undefined' && globalThis.CodeLabPython && globalThis.CodeLabPython.formatPythonSource) ||
8271
+ null;
8272
+ if (!formatter && typeof require === 'function') {
8273
+ try {
8274
+ const mod = require('./extensions/python');
8275
+ formatter = mod.formatPythonSource;
8276
+ } catch (err) {
8277
+ void err;
8278
+ }
8279
+ }
8280
+ if (formatter) {
8281
+ const formatted = formatter(code);
8282
+ if (formatted !== code) {
8283
+ this.files[file] = formatted;
8284
+ if (this.editor && this.editor.getModel()) {
8285
+ this.editor.setValue(formatted);
8286
+ }
8287
+ this._saveState();
8288
+ this._notifyCodeChange(file, formatted);
8289
+ }
8290
+ }
8291
+ }
8292
+ }
8293
+
8294
+ async shareSnapshot() {
8295
+ let compressor = (root && root.CodeLabWorkbenchComponents && root.CodeLabWorkbenchComponents.compressWorkspaceSnapshot) ||
8296
+ (typeof globalThis !== 'undefined' && globalThis.CodeLabWorkbenchComponents && globalThis.CodeLabWorkbenchComponents.compressWorkspaceSnapshot) ||
8297
+ null;
8298
+ if (!compressor && typeof require === 'function') {
8299
+ try {
8300
+ const mod = require('./workbench/share');
8301
+ compressor = mod.compressWorkspaceSnapshot;
8302
+ } catch (err) {
8303
+ void err;
8304
+ }
8305
+ }
8306
+ if (!compressor) {
8307
+ this._showToast('Snapshot compression not available', 'error');
8308
+ return;
8309
+ }
8310
+ try {
8311
+ const payload = {
8312
+ lang: this.lang,
8313
+ activeFile: this.activeFile,
8314
+ files: { ...this.files },
8315
+ stdin: this.customStdin || ''
8316
+ };
8317
+ const token = await compressor(payload);
8318
+ if (typeof window !== 'undefined' && window.location) {
8319
+ const newUrl = `${window.location.origin}${window.location.pathname}#codelab=${token}`;
8320
+ if (window.history && typeof window.history.replaceState === 'function') {
8321
+ window.history.replaceState(null, '', newUrl);
8322
+ } else {
8323
+ window.location.hash = `codelab=${token}`;
8324
+ }
8325
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
8326
+ await navigator.clipboard.writeText(newUrl);
8327
+ this._showToast('Snapshot link copied to clipboard! (#codelab=...)', 'success');
8328
+ } else {
8329
+ this._showToast('Snapshot link generated in URL hash (#codelab=...)', 'success');
8330
+ }
8331
+ }
8332
+ } catch (err) {
8333
+ this.logger.error('Failed to create snapshot.', err);
8334
+ this._showToast('Failed to create snapshot', 'error');
8335
+ }
8336
+ }
8337
+
8338
+ async _checkUrlSnapshot() {
8339
+ if (typeof window === 'undefined' || !window.location || !window.location.hash) return;
8340
+ const hash = window.location.hash;
8341
+ const match = hash.match(/#(?:codelab|snapshot)=([A-Za-z0-9_-]+)/);
8342
+ if (!match) return;
8343
+ const token = match[1];
8344
+ let decompressor = (root && root.CodeLabWorkbenchComponents && root.CodeLabWorkbenchComponents.decompressWorkspaceSnapshot) ||
8345
+ (typeof globalThis !== 'undefined' && globalThis.CodeLabWorkbenchComponents && globalThis.CodeLabWorkbenchComponents.decompressWorkspaceSnapshot) ||
8346
+ null;
8347
+ if (!decompressor && typeof require === 'function') {
8348
+ try {
8349
+ const mod = require('./workbench/share');
8350
+ decompressor = mod.decompressWorkspaceSnapshot;
8351
+ } catch (err) {
8352
+ void err;
8353
+ }
8354
+ }
8355
+ if (!decompressor) return;
8356
+ try {
8357
+ const snapshot = await decompressor(token);
8358
+ if (snapshot && snapshot.files && typeof snapshot.files === 'object') {
8359
+ this.files = { ...snapshot.files };
8360
+ if (snapshot.lang && (snapshot.lang === 'js' || snapshot.lang === 'ts' || snapshot.lang === 'cpp' || snapshot.lang === 'py')) {
8361
+ this.lang = snapshot.lang;
8362
+ }
8363
+ if (snapshot.stdin) {
8364
+ this.customStdin = snapshot.stdin;
8365
+ }
8366
+ if (snapshot.activeFile && this.files[snapshot.activeFile]) {
8367
+ this.activeFile = snapshot.activeFile;
8368
+ }
8369
+ this.openTabs = Object.keys(this.files);
8370
+ this._renderFileLists();
8371
+ this._renderBreadcrumbs();
8372
+ this._syncAllModels();
8373
+ if (this.activeFile) this.openFile(this.activeFile);
8374
+ this._showToast('Restored workspace from snapshot URL', 'success');
8375
+ }
8376
+ } catch (err) {
8377
+ this.logger.warn('Failed to decompress URL snapshot.', err);
8378
+ }
8379
+ }
8380
+
7747
8381
  async runTests(filterTestNames = null) {
7748
8382
  if (this.isRunning) return;
7749
8383
  const entry = this._findEntryFile('test');
7750
8384
  if (!entry) {
7751
- this.terminalLogs.push({ type: 'stderr', text: 'No test.js / test.ts file found in this workspace.' });
8385
+ this.terminalLogs.push({ type: 'stderr', text: 'No test file (test.js, test.ts, test.cpp, test.py) found in this workspace.' });
7752
8386
  this.drawerTab = 'terminal';
7753
8387
  this._renderDrawerBody();
7754
8388
  return;
7755
8389
  }
7756
8390
 
7757
8391
  this.isRunning = true;
7758
- this._updateRunStateUI();
8392
+ this.testSuiteVisible = true;
7759
8393
  this.drawerTab = 'tests';
8394
+ this._refreshDrawerTabs();
8395
+ this._updateRunStateUI();
7760
8396
  const isCppTest = /\.(cpp|cc|cxx)$/i.test(entry);
8397
+ const isPyTest = /\.py$/i.test(entry);
7761
8398
  this.terminalLogs.push({
7762
8399
  type: 'system',
7763
- text: isCppTest ? `\n$ g++ -std=c++20 ${entry} -o a.out && ./a.out` : `\n$ node ${entry}`
8400
+ text: isCppTest
8401
+ ? `\n$ g++ -std=c++20 ${entry} -o a.out && ./a.out`
8402
+ : isPyTest
8403
+ ? `\n$ pytest ${entry}`
8404
+ : `\n$ node ${entry}`
7764
8405
  });
7765
8406
 
7766
8407
  let abortCtrl = new AbortController();
@@ -7774,6 +8415,7 @@ int main() {
7774
8415
  files: { ...this.files },
7775
8416
  entry,
7776
8417
  mode: 'test',
8418
+ stdin: this.customStdin || '',
7777
8419
  testFilter: filterTestNames,
7778
8420
  signal: abortCtrl.signal,
7779
8421
  onStdout: (c) => {
@@ -7793,6 +8435,9 @@ int main() {
7793
8435
  this.lastTestResults = res.testResults || [];
7794
8436
  this.lastFsSnapshot = res.fsSnapshot || [];
7795
8437
  this.lastHttpTrace = res.httpTrace || [];
8438
+ if (res.durationMs !== undefined) this.lastDurationMs = res.durationMs;
8439
+ if (res.peakMemoryBytes !== undefined) this.lastPeakMemoryBytes = res.peakMemoryBytes;
8440
+ this._updateTelemetryHud();
7796
8441
  }
7797
8442
 
7798
8443
  if (!aborted && !streamedStdout && res.stdout) {
@@ -8352,6 +8997,7 @@ int main() {
8352
8997
  }
8353
8998
 
8354
8999
  showProblemsModal() {
9000
+ this.switchDrawerTab('problems');
8355
9001
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
8356
9002
  if (!slot) return;
8357
9003
  const items = this.getDiagnostics();
@@ -8750,7 +9396,11 @@ int main() {
8750
9396
  if (this.enabledLanguages instanceof Set && this.enabledLanguages.size > 1) {
8751
9397
  this.hasMultipleLanguages = true;
8752
9398
  }
8753
- this._refreshLanguageSwitcher();
9399
+ if (typeof this._refreshToolbarAndTabs === 'function') {
9400
+ this._refreshToolbarAndTabs();
9401
+ } else {
9402
+ this._refreshLanguageSwitcher();
9403
+ }
8754
9404
  return this;
8755
9405
  }
8756
9406
 
@@ -8885,8 +9535,13 @@ int main() {
8885
9535
  openCommandPalette(mode) { if (this._instance) this._instance.openCommandPalette(mode); }
8886
9536
  showDiffModal(file, target) { if (this._instance) this._instance.showDiffModal(file, target); }
8887
9537
  cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
9538
+ runCode() { return this._instance ? this._instance.runCode() : Promise.resolve(); }
9539
+ runEntry() { return this._instance ? this._instance.runEntry() : Promise.resolve(); }
9540
+ runActiveFile() { return this._instance ? this._instance.runActiveFile() : Promise.resolve(); }
8888
9541
  runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
8889
9542
  runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
9543
+ formatActiveDocument() { return this._instance ? this._instance.formatActiveDocument() : Promise.resolve(); }
9544
+ shareSnapshot() { return this._instance ? this._instance.shareSnapshot() : Promise.resolve(); }
8890
9545
  previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
8891
9546
  stopExecution() { if (this._instance) this._instance.stopExecution(); }
8892
9547
  reset() { if (this._instance) this._instance.reset(); }
@@ -8981,7 +9636,8 @@ int main() {
8981
9636
  guidedLab: null,
8982
9637
  javascript: null,
8983
9638
  typescript: null,
8984
- cpp: null
9639
+ cpp: null,
9640
+ python: null
8985
9641
  },
8986
9642
  parseGitHubRepoUrl,
8987
9643
  cloneRepo: cloneGitHubRepository,
@@ -9008,3 +9664,22 @@ int main() {
9008
9664
  module.exports = CodeLabSDK;
9009
9665
  }
9010
9666
  })(typeof window !== 'undefined' ? window : globalThis);
9667
+
9668
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
9669
+ const _hostWorkbench: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabWorkbench : undefined)
9670
+ || (typeof window !== 'undefined' ? (window as any).CodeLabWorkbench : undefined)
9671
+ || (typeof module !== 'undefined' && module.exports && (module.exports.CodeLabWorkbench || module.exports) ? (module.exports.CodeLabWorkbench || module.exports) : undefined);
9672
+
9673
+ const _hostElement: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabElement : undefined)
9674
+ || (typeof window !== 'undefined' ? (window as any).CodeLabElement : undefined)
9675
+ || (typeof module !== 'undefined' && module.exports ? module.exports.CodeLabElement : undefined);
9676
+
9677
+ const _hostSDK: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLab : undefined)
9678
+ || (typeof window !== 'undefined' ? (window as any).CodeLab : undefined)
9679
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
9680
+
9681
+ export const CodeLabWorkbench: any = _hostWorkbench;
9682
+ export const Workbench: any = _hostWorkbench;
9683
+ export const CodeLabElement: any = _hostElement;
9684
+ export const CodeLab: any = _hostSDK;
9685
+ export default _hostSDK;