@innovatorved/code-lab 0.1.12 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/ARCHITECTURE.md +8 -8
  2. package/CHANGELOG.md +107 -0
  3. package/README.md +48 -8
  4. package/dist/code-lab.css +165 -0
  5. package/dist/code-lab.d.ts +19 -7
  6. package/dist/code-lab.esm.js +29988 -17401
  7. package/dist/code-lab.js +22940 -10357
  8. package/dist/extensions/cpp.d.ts +119 -0
  9. package/dist/extensions/cpp.esm.js +5193 -0
  10. package/dist/extensions/cpp.js +5212 -0
  11. package/dist/extensions/guided-lab.esm.js +48 -6
  12. package/dist/extensions/guided-lab.js +49 -6
  13. package/dist/extensions/javascript.d.ts +24 -0
  14. package/dist/extensions/javascript.esm.js +36 -0
  15. package/dist/extensions/javascript.js +59 -0
  16. package/dist/extensions/typescript.d.ts +36 -0
  17. package/dist/extensions/typescript.esm.js +55 -0
  18. package/dist/extensions/typescript.js +78 -0
  19. package/dist/index.d.ts +5 -2
  20. package/dist/preview-sw.js +1 -1
  21. package/dist/runtime.d.ts +7 -0
  22. package/dist/runtime.esm.js +4001 -2563
  23. package/dist/runtime.js +3993 -2563
  24. package/dist/schemas.d.ts +122 -23
  25. package/dist/schemas.esm.js +43 -6
  26. package/dist/schemas.js +43 -6
  27. package/dist/shell.esm.js +982 -4
  28. package/dist/shell.js +982 -4
  29. package/dist/terminal.esm.js +1 -1
  30. package/dist/terminal.js +1 -1
  31. package/package.json +27 -3
  32. package/src/code-lab.css +165 -0
  33. package/src/extensions/cpp.ts +1081 -0
  34. package/src/extensions/guided-lab.ts +10 -0
  35. package/src/extensions/javascript.ts +54 -0
  36. package/src/extensions/typescript.ts +85 -0
  37. package/src/index.ts +33 -2
  38. package/src/runtime.ts +3995 -2562
  39. package/src/schemas.ts +49 -7
  40. package/src/shell.ts +981 -3
  41. package/src/workbench.ts +535 -66
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.1.12';
60
+ const CODELAB_VERSION = '0.2.0';
61
61
 
62
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
63
63
  const NODE_AMBIENT_DTS = `
@@ -1096,11 +1096,69 @@ declare module 'bun:sqlite' {
1096
1096
  return monacoPromise;
1097
1097
  }
1098
1098
 
1099
- // Helper to convert JS file set to TS file set if explicit TS files aren't provided
1100
- function mapFilesToLanguage(filesObj, lang, explicitTsFiles) {
1099
+ const DEFAULT_STANDALONE_CPP_FILES = {
1100
+ 'solution.hpp': `#pragma once
1101
+ #include <bits/stdc++.h>
1102
+ #include <codelab/dsa.hpp>
1103
+ using namespace std;
1104
+
1105
+ vector<int> twoSum(const vector<int>& nums, int target) {
1106
+ unordered_map<int, int> seen;
1107
+ for (int i = 0; i < (int)nums.size(); ++i) {
1108
+ int complement = target - nums[i];
1109
+ if (seen.count(complement)) return {seen[complement], i};
1110
+ seen[nums[i]] = i;
1111
+ }
1112
+ return {};
1113
+ }
1114
+ `,
1115
+ 'main.cpp': `#include "solution.hpp"
1116
+
1117
+ int main() {
1118
+ vector<int> nums = {2, 7, 11, 15};
1119
+ codelab::dbg(twoSum(nums, 9));
1120
+ return 0;
1121
+ }
1122
+ `,
1123
+ 'test.cpp': `#include <codelab/test.hpp>
1124
+ #include "solution.hpp"
1125
+
1126
+ int main() {
1127
+ DESCRIBE("Standalone C++ Sandbox", [] {
1128
+ TEST("twoSum finds target pair indices", [] {
1129
+ ASSERT_EQ(twoSum({2, 7, 11, 15}, 9), (vector<int>{0, 1}));
1130
+ ASSERT_EQ(twoSum({3, 2, 4}, 6), (vector<int>{1, 2}));
1131
+ });
1132
+ });
1133
+ return codelab::test::exit_code();
1134
+ }
1135
+ `
1136
+ };
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) {
1101
1140
  if (lang === 'ts' && explicitTsFiles && Object.keys(explicitTsFiles).length > 0) {
1102
1141
  return { ...explicitTsFiles };
1103
1142
  }
1143
+ if (lang === 'cpp') {
1144
+ if (explicitCppFiles && Object.keys(explicitCppFiles).length > 0) {
1145
+ return { ...explicitCppFiles };
1146
+ }
1147
+ const existingCpp = {};
1148
+ for (const [name, content] of Object.entries(filesObj || {})) {
1149
+ if (/\.(cpp|cc|cxx|h|hpp|md)$/i.test(name)) {
1150
+ existingCpp[name] = content;
1151
+ }
1152
+ }
1153
+ if (Object.keys(existingCpp).some(f => /\.(cpp|cc|cxx)$/i.test(f))) {
1154
+ return existingCpp;
1155
+ }
1156
+ const outCpp = { ...DEFAULT_STANDALONE_CPP_FILES };
1157
+ if (filesObj && filesObj['README.md']) {
1158
+ outCpp['README.md'] = filesObj['README.md'];
1159
+ }
1160
+ return outCpp;
1161
+ }
1104
1162
  const out = {};
1105
1163
  for (const [name, content] of Object.entries(filesObj || {})) {
1106
1164
  if (lang === 'ts' && name.endsWith('.js')) {
@@ -1332,7 +1390,9 @@ declare module 'bun:sqlite' {
1332
1390
  ...(options.guided || {}),
1333
1391
  ...(options.starterFiles ? { starterFiles: options.starterFiles } : {}),
1334
1392
  ...(options.tsStarterFiles ? { tsStarterFiles: options.tsStarterFiles } : {}),
1335
- ...((options.tsSolutionFiles || options.tsFiles) ? { tsSolutionFiles: options.tsSolutionFiles || options.tsFiles } : {})
1393
+ ...((options.tsSolutionFiles || options.tsFiles) ? { tsSolutionFiles: options.tsSolutionFiles || options.tsFiles } : {}),
1394
+ ...(options.cppStarterFiles ? { cppStarterFiles: options.cppStarterFiles } : {}),
1395
+ ...((options.cppSolutionFiles || options.cppFiles) ? { cppSolutionFiles: options.cppSolutionFiles || options.cppFiles } : {})
1336
1396
  };
1337
1397
  this.steps = options.steps || this.guidedConfig?.steps || [];
1338
1398
  this.hasGuidedLab = Boolean(
@@ -1340,12 +1400,41 @@ declare module 'bun:sqlite' {
1340
1400
  options.guidedLab ||
1341
1401
  (this.steps && this.steps.length > 0)
1342
1402
  );
1403
+ this.enabledLanguages = new Set(['js']);
1404
+ if (Array.isArray(options.languages)) {
1405
+ for (const l of options.languages) {
1406
+ if (l === 'js' || l === 'ts' || l === 'cpp') this.enabledLanguages.add(l);
1407
+ }
1408
+ }
1409
+ if (
1410
+ options.hasMultipleLanguages ||
1411
+ this.guidedConfig.tsStarterFiles ||
1412
+ this.guidedConfig.tsSolutionFiles ||
1413
+ this.guidedConfig.tsFiles ||
1414
+ options.lang === 'ts' ||
1415
+ options.language === 'ts'
1416
+ ) {
1417
+ this.enabledLanguages.add('ts');
1418
+ }
1419
+ if (
1420
+ this.guidedConfig.cppStarterFiles ||
1421
+ this.guidedConfig.cppSolutionFiles ||
1422
+ this.guidedConfig.cppFiles ||
1423
+ options.lang === 'cpp' ||
1424
+ options.language === 'cpp'
1425
+ ) {
1426
+ this.enabledLanguages.add('cpp');
1427
+ }
1343
1428
  this.hasMultipleLanguages = Boolean(
1344
1429
  options.hasMultipleLanguages ||
1345
1430
  options.languages ||
1431
+ this.enabledLanguages.size > 1 ||
1346
1432
  this.guidedConfig.tsStarterFiles ||
1347
1433
  this.guidedConfig.tsSolutionFiles ||
1348
1434
  this.guidedConfig.tsFiles ||
1435
+ this.guidedConfig.cppStarterFiles ||
1436
+ this.guidedConfig.cppSolutionFiles ||
1437
+ this.guidedConfig.cppFiles ||
1349
1438
  (this.hasGuidedLab && (options.lang || options.language))
1350
1439
  );
1351
1440
 
@@ -1513,10 +1602,12 @@ declare module 'bun:sqlite' {
1513
1602
  this._bindEvents();
1514
1603
  this._initEditor();
1515
1604
 
1516
- if (Array.isArray(options.plugins)) {
1517
- for (const plugin of options.plugins) {
1518
- this.use(plugin);
1519
- }
1605
+ const initialPlugins = [
1606
+ ...(Array.isArray(options.extensions) ? options.extensions : []),
1607
+ ...(Array.isArray(options.plugins) ? options.plugins : [])
1608
+ ];
1609
+ for (const plugin of initialPlugins) {
1610
+ this.use(plugin);
1520
1611
  }
1521
1612
 
1522
1613
  if (options.repo && typeof options.repo === 'string') {
@@ -1581,6 +1672,7 @@ declare module 'bun:sqlite' {
1581
1672
  this.logger.debug('Could not parse portTable dispatch URL.', err);
1582
1673
  }
1583
1674
  const method = String((init && init.method) || 'GET').toUpperCase();
1675
+ const fromPort = (init && init._fromPort) ? Number(init._fromPort) : null;
1584
1676
  try {
1585
1677
  const res = await origDispatch(url, init);
1586
1678
  const durationMs = Math.max(0.1, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0);
@@ -1606,8 +1698,9 @@ declare module 'bun:sqlite' {
1606
1698
  try {
1607
1699
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
1608
1700
  } catch (err) {
1609
- void err;
1701
+ this.logger.debug('Response body is not JSON.', err);
1610
1702
  }
1703
+ const chaosEffect = (res && res._chaosEffect) || responseHeaders['x-codelab-chaos'] || null;
1611
1704
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
1612
1705
  this.lastHttpTrace.push({
1613
1706
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -1616,6 +1709,8 @@ declare module 'bun:sqlite' {
1616
1709
  url: reqPath,
1617
1710
  fullUrl,
1618
1711
  port: parsedPort,
1712
+ fromPort,
1713
+ chaosEffect,
1619
1714
  status: (res && res.status) || 200,
1620
1715
  statusText: (res && res.statusText) || 'OK',
1621
1716
  durationMs,
@@ -1626,8 +1721,34 @@ declare module 'bun:sqlite' {
1626
1721
  responseBody: bodyText,
1627
1722
  formattedBody
1628
1723
  });
1724
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
1725
+ if (netPill) netPill.textContent = `${this.lastHttpTrace.length} reqs`;
1629
1726
  return res;
1630
1727
  } catch (err) {
1728
+ const durationMs = Math.max(0.1, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0);
1729
+ if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
1730
+ const errMsg = String((err && err.message) || err);
1731
+ this.lastHttpTrace.push({
1732
+ id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
1733
+ timestamp: new Date().toLocaleTimeString(),
1734
+ method,
1735
+ url: reqPath,
1736
+ fullUrl,
1737
+ port: parsedPort,
1738
+ fromPort,
1739
+ chaosEffect: (err && err.chaosEffect) || (err && err.code) || 'ERROR',
1740
+ status: 0,
1741
+ statusText: (err && (err.chaosEffect || err.code)) || 'ERROR',
1742
+ durationMs,
1743
+ size: 0,
1744
+ requestHeaders: (init && init.headers) || {},
1745
+ requestBody: (init && init.body) || '',
1746
+ responseHeaders: {},
1747
+ responseBody: errMsg,
1748
+ formattedBody: errMsg
1749
+ });
1750
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
1751
+ if (netPill) netPill.textContent = `${this.lastHttpTrace.length} reqs`;
1631
1752
  throw err;
1632
1753
  }
1633
1754
  };
@@ -1922,7 +2043,11 @@ declare module 'bun:sqlite' {
1922
2043
  curEl.textContent = `Ln ${this.cursorPos.lineNumber || 1}, Col ${this.cursorPos.column || 1}`;
1923
2044
  }
1924
2045
  if (langEl) {
1925
- langEl.textContent = this.lang === 'ts' ? 'TypeScript 5.x' : 'JavaScript (CJS/ESM)';
2046
+ langEl.textContent = this.lang === 'cpp'
2047
+ ? 'C++20 (Clang/WASI)'
2048
+ : this.lang === 'ts'
2049
+ ? 'TypeScript 5.x'
2050
+ : 'JavaScript (CJS/ESM)';
1926
2051
  }
1927
2052
  }
1928
2053
 
@@ -1932,10 +2057,20 @@ declare module 'bun:sqlite' {
1932
2057
  ...this.referenceFiles,
1933
2058
  ...(this.guidedConfig?.starterFiles || {})
1934
2059
  };
1935
- if (mode === 'guided' && this.guidedConfig?.starterFiles) {
1936
- return mapFilesToLanguage(baseJsStarter, lang, this.guidedConfig?.tsStarterFiles);
2060
+ if (mode === 'guided' && (this.guidedConfig?.starterFiles || this.guidedConfig?.tsStarterFiles || this.guidedConfig?.cppStarterFiles)) {
2061
+ return mapFilesToLanguage(
2062
+ baseJsStarter,
2063
+ lang,
2064
+ this.guidedConfig?.tsStarterFiles,
2065
+ this.guidedConfig?.cppStarterFiles
2066
+ );
1937
2067
  }
1938
- return mapFilesToLanguage(baseJsSolution, lang, this.guidedConfig?.tsSolutionFiles);
2068
+ return mapFilesToLanguage(
2069
+ baseJsSolution,
2070
+ lang,
2071
+ this.guidedConfig?.tsSolutionFiles,
2072
+ this.guidedConfig?.cppSolutionFiles
2073
+ );
1939
2074
  }
1940
2075
 
1941
2076
  _isUserCreatedFile(filename) {
@@ -1958,6 +2093,21 @@ declare module 'bun:sqlite' {
1958
2093
 
1959
2094
  _pickDefaultFile() {
1960
2095
  const names = Object.keys(this.files);
2096
+ if (this.lang === 'cpp') {
2097
+ if (this.guidedConfig?.mainFile) {
2098
+ const cppMain = this.guidedConfig.mainFile.replace(/\.(js|ts)$/, '.hpp');
2099
+ if (this.files[cppMain]) return cppMain;
2100
+ const cppMainSrc = this.guidedConfig.mainFile.replace(/\.(js|ts)$/, '.cpp');
2101
+ if (this.files[cppMainSrc]) return cppMainSrc;
2102
+ }
2103
+ if (this.files['solution.hpp']) return 'solution.hpp';
2104
+ if (this.files['main.cpp']) return 'main.cpp';
2105
+ const cppImpl = names.find(f =>
2106
+ /\.(cpp|cc|cxx|hpp|h)$/i.test(f) &&
2107
+ !/(^|\/)(demo|test)\.(cpp|cc|cxx)$/i.test(f)
2108
+ );
2109
+ return cppImpl || names.find(f => !f.endsWith('.md')) || names[0] || '';
2110
+ }
1961
2111
  const ext = this.lang === 'ts' ? '.ts' : '.js';
1962
2112
  if (this.guidedConfig?.mainFile) {
1963
2113
  const mainCandidate = this.lang === 'ts'
@@ -1974,6 +2124,27 @@ declare module 'bun:sqlite' {
1974
2124
 
1975
2125
  _findEntryFile(kind) {
1976
2126
  const names = Object.keys(this.files);
2127
+ if (this.lang === 'cpp') {
2128
+ if (kind === 'test') {
2129
+ if (this.explicitTestEntry) {
2130
+ const cppTest = this.explicitTestEntry.replace(/\.(js|ts)$/, '.cpp');
2131
+ if (this.files[cppTest]) return cppTest;
2132
+ if (this.files[this.explicitTestEntry]) return this.explicitTestEntry;
2133
+ }
2134
+ if (this.files['test.cpp']) return 'test.cpp';
2135
+ return names.find(f => /(^|\/)test\.(cpp|cc|cxx)$/i.test(f)) || null;
2136
+ }
2137
+ if (this.explicitEntry) {
2138
+ const cppEntry = this.explicitEntry.replace(/\.(js|ts)$/, '.cpp');
2139
+ if (this.files[cppEntry]) return cppEntry;
2140
+ if (this.files[this.explicitEntry]) return this.explicitEntry;
2141
+ }
2142
+ if (this.files['main.cpp']) return 'main.cpp';
2143
+ if (this.files['demo.cpp']) return 'demo.cpp';
2144
+ return names.find(f => /(^|\/)(main|demo)\.(cpp|cc|cxx)$/i.test(f)) ||
2145
+ names.find(f => /\.(cpp|cc|cxx)$/i.test(f) && !/(^|\/)test\.(cpp|cc|cxx)$/i.test(f)) ||
2146
+ null;
2147
+ }
1977
2148
  if (kind === 'test' && this.explicitTestEntry) {
1978
2149
  const candidate = this.lang === 'ts' ? this.explicitTestEntry.replace(/\.js$/, '.ts') : this.explicitTestEntry;
1979
2150
  if (this.files[candidate]) return candidate;
@@ -1984,16 +2155,16 @@ declare module 'bun:sqlite' {
1984
2155
  if (this.files[candidate]) return candidate;
1985
2156
  if (this.files[this.explicitEntry]) return this.explicitEntry;
1986
2157
  }
1987
- const pattern = kind === 'test' ? /(^|\/)test\.(js|ts)$/i : /(^|\/)demo\.(js|ts)$/i;
2158
+ const pattern = kind === 'test' ? /(^|\/)test\.(js|ts|cpp|cc|cxx)$/i : /(^|\/)(demo|main)\.(js|ts|cpp|cc|cxx)$/i;
1988
2159
  const found = names.find(f => pattern.test(f));
1989
2160
  if (found) return found;
1990
2161
  if (kind === 'demo') {
1991
- const isConfigOrTest = f => /(^|\/)(test|.*\.(?:test|spec|config|d))\.(js|ts|mjs|cjs)$/i.test(f) || /(^|\/)\.[^/]+$/i.test(f);
2162
+ const isConfigOrTest = f => /(^|\/)(test|.*\.(?:test|spec|config|d))\.(js|ts|mjs|cjs|cpp|cc|cxx)$/i.test(f) || /(^|\/)\.[^/]+$/i.test(f);
1992
2163
  const hasHtmlEntry = Boolean(this.files['index.html'] || this.files['public/index.html']);
1993
2164
  if (hasHtmlEntry) {
1994
2165
  return names.find(f => /(^|\/)(server|app|demo)\.(js|ts)$/i.test(f) && !/^src\//i.test(f)) || null;
1995
2166
  }
1996
- return names.find(f => /\.(js|ts)$/i.test(f) && !isConfigOrTest(f)) || null;
2167
+ return names.find(f => /\.(js|ts|cpp|cc|cxx)$/i.test(f) && !isConfigOrTest(f)) || null;
1997
2168
  }
1998
2169
  return null;
1999
2170
  }
@@ -2020,6 +2191,44 @@ declare module 'bun:sqlite' {
2020
2191
  });
2021
2192
  }
2022
2193
 
2194
+ _renderLanguageSwitcherHtml() {
2195
+ const hasMulti = Boolean(
2196
+ this.hasMultipleLanguages ||
2197
+ (this.enabledLanguages && this.enabledLanguages.size > 1)
2198
+ );
2199
+ if (!hasMulti) return '';
2200
+ const showTs = Boolean(
2201
+ !this.enabledLanguages ||
2202
+ this.enabledLanguages.has('ts') ||
2203
+ !this.enabledLanguages.has('cpp')
2204
+ );
2205
+ const showCpp = Boolean(this.enabledLanguages && this.enabledLanguages.has('cpp'));
2206
+ return `
2207
+ <div class="codelab-lang-switch" role="group" aria-label="Language Selector">
2208
+ <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
+ ${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
+ ${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>` : ''}
2211
+ </div>
2212
+ `;
2213
+ }
2214
+
2215
+ _refreshLanguageSwitcher() {
2216
+ if (!this.container) return;
2217
+ const topLeft = this.container.querySelector('.codelab-topbar__left');
2218
+ if (!topLeft) return;
2219
+ const existing = topLeft.querySelector('.codelab-lang-switch');
2220
+ const htmlStr = this._renderLanguageSwitcherHtml().trim();
2221
+ if (existing) {
2222
+ if (htmlStr) {
2223
+ existing.outerHTML = htmlStr;
2224
+ } else {
2225
+ existing.remove();
2226
+ }
2227
+ } else if (htmlStr) {
2228
+ topLeft.insertAdjacentHTML('beforeend', htmlStr);
2229
+ }
2230
+ }
2231
+
2023
2232
  // ── Render Workbench DOM ───────────────────────────────────────────────
2024
2233
  _renderShell() {
2025
2234
  if (this.themeOption !== 'auto') {
@@ -2060,12 +2269,7 @@ declare module 'bun:sqlite' {
2060
2269
  </button>
2061
2270
  </div>
2062
2271
  ` : ''}
2063
- ${this.hasMultipleLanguages ? `
2064
- <div class="codelab-lang-switch" role="group" aria-label="Language Selector">
2065
- <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>
2066
- <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>
2067
- </div>
2068
- ` : ''}
2272
+ ${this._renderLanguageSwitcherHtml()}
2069
2273
  </div>
2070
2274
 
2071
2275
  <div class="codelab-topbar__right">
@@ -2239,7 +2443,7 @@ declare module 'bun:sqlite' {
2239
2443
  <span class="codelab-statusbar__sep">·</span>
2240
2444
  <span class="codelab-statusbar__item">UTF-8</span>
2241
2445
  <span class="codelab-statusbar__sep">·</span>
2242
- <span class="codelab-statusbar__item" id="cl-status-lang">${this.lang === 'ts' ? 'TypeScript 5.x' : 'JavaScript (CJS/ESM)'}</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>
2243
2447
  </div>
2244
2448
  </footer>
2245
2449
 
@@ -2260,13 +2464,30 @@ declare module 'bun:sqlite' {
2260
2464
  this._updateRunStateUI();
2261
2465
  }
2262
2466
 
2467
+ _resolveStepTargetFile(rawTarget) {
2468
+ if (!rawTarget) return '';
2469
+ if (this.lang === 'cpp') {
2470
+ const asHpp = rawTarget.replace(/\.(js|ts)$/, '.hpp');
2471
+ if (this.files && this.files[asHpp] !== undefined) return asHpp;
2472
+ const asCpp = rawTarget.replace(/\.(js|ts)$/, '.cpp');
2473
+ if (this.files && this.files[asCpp] !== undefined) return asCpp;
2474
+ if (this.files && this.files['solution.hpp'] !== undefined) return 'solution.hpp';
2475
+ if (this.files && this.files['main.cpp'] !== undefined) return 'main.cpp';
2476
+ return asCpp;
2477
+ }
2478
+ if (this.lang === 'ts') {
2479
+ return rawTarget.replace(/\.js$/, '.ts');
2480
+ }
2481
+ return rawTarget;
2482
+ }
2483
+
2263
2484
  _detectActiveSymbol(filePath) {
2264
2485
  if (!filePath || !this.files || typeof this.files[filePath] !== 'string') return '';
2265
2486
  if (this.mode === 'guided' && this.steps && this.steps.length > 0) {
2266
2487
  const step = this.steps[this.activeStepIndex];
2267
2488
  if (step) {
2268
2489
  const rawTarget = step.targetFile || '';
2269
- const stepTarget = this.lang === 'ts' && rawTarget ? rawTarget.replace(/\.js$/, '.ts') : rawTarget;
2490
+ const stepTarget = rawTarget ? this._resolveStepTargetFile(rawTarget) : '';
2270
2491
  if ((!stepTarget || stepTarget === filePath) && (step.targetSymbol || step.symbol)) {
2271
2492
  return String(step.targetSymbol || step.symbol);
2272
2493
  }
@@ -2469,7 +2690,7 @@ declare module 'bun:sqlite' {
2469
2690
 
2470
2691
  const step = this.steps[this.activeStepIndex] || this.steps[0];
2471
2692
  const isStepPassed = this.completedSteps.has(step.id);
2472
- const targetFile = this.lang === 'ts' && step.targetFile ? step.targetFile.replace(/\.js$/, '.ts') : (step.targetFile || this._pickDefaultFile());
2693
+ const targetFile = step.targetFile ? this._resolveStepTargetFile(step.targetFile) : this._pickDefaultFile();
2473
2694
  const progressPct = Math.round((this.completedSteps.size / Math.max(1, this.steps.length)) * 100);
2474
2695
 
2475
2696
  // Match step test results
@@ -2696,8 +2917,8 @@ declare module 'bun:sqlite' {
2696
2917
  const sortedFiles = Array.from(node.files.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2697
2918
  for (const [baseName, fullPath] of sortedFiles) {
2698
2919
  const isActive = fullPath === this.activeFile;
2699
- const badge = fullPath.endsWith('.md') ? 'DOC' : fullPath.endsWith('.json') ? 'PKG' : /(^|\/)test\./i.test(fullPath) ? 'TEST' : /(^|\/)demo\./i.test(fullPath) ? 'DEMO' : 'SRC';
2700
- const ext = fullPath.endsWith('.ts') ? 'ts' : fullPath.endsWith('.js') ? 'js' : fullPath.endsWith('.json') ? 'json' : fullPath.endsWith('.md') ? 'md' : 'txt';
2920
+ const badge = fullPath.endsWith('.md') ? 'DOC' : fullPath.endsWith('.json') ? 'PKG' : /(^|\/)test\./i.test(fullPath) ? 'TEST' : /(^|\/)(demo|main)\./i.test(fullPath) ? 'DEMO' : /\.(hpp|h)$/i.test(fullPath) ? 'HDR' : 'SRC';
2921
+ const ext = /\.(cpp|cc|cxx|hpp|h)$/i.test(fullPath) ? 'cpp' : fullPath.endsWith('.ts') ? 'ts' : fullPath.endsWith('.js') ? 'js' : fullPath.endsWith('.json') ? 'json' : fullPath.endsWith('.md') ? 'md' : 'txt';
2701
2922
  const fileIcon = ext === 'json' ? CL_ICONS.database : ext === 'md' ? CL_ICONS.book : CL_ICONS.file;
2702
2923
  const indent = depth * 14 + 10;
2703
2924
  treeHtml += `
@@ -2821,10 +3042,10 @@ declare module 'bun:sqlite' {
2821
3042
  const openTabs = Array.isArray(this.openTabs) ? this.openTabs : [];
2822
3043
  const tabsHtml = openTabs.map(f => {
2823
3044
  const isActive = f === this.activeFile;
2824
- const ext = f.endsWith('.ts') ? 'ts' : f.endsWith('.js') ? 'js' : f.endsWith('.json') ? 'json' : f.endsWith('.md') ? 'md' : 'txt';
3045
+ const ext = /\.(cpp|cc|cxx|hpp|h)$/i.test(f) ? 'cpp' : f.endsWith('.ts') ? 'ts' : f.endsWith('.js') ? 'js' : f.endsWith('.json') ? 'json' : f.endsWith('.md') ? 'md' : 'txt';
2825
3046
  return `
2826
3047
  <div role="tab" tabindex="0" aria-selected="${isActive}" class="codelab-tab ${isActive ? 'active' : ''}" data-cl-file="${escapeHtml(f)}" data-tab-file="${escapeHtml(f)}">
2827
- <span class="codelab-tab__ext codelab-tab__ext--${ext}">${ext.toUpperCase()}</span>
3048
+ <span class="codelab-tab__ext codelab-tab__ext--${ext}">${ext === 'cpp' ? 'C++' : ext.toUpperCase()}</span>
2828
3049
  <span class="codelab-tab__label">${escapeHtml(f)}</span>
2829
3050
  <button type="button" class="codelab-tab__close" data-action="close-tab" data-cl-file="${escapeHtml(f)}" title="Close ${escapeHtml(f)}" aria-label="Close ${escapeHtml(f)}">×</button>
2830
3051
  </div>
@@ -3079,7 +3300,7 @@ declare module 'bun:sqlite' {
3079
3300
  createFile(rawName, initialContent = null) {
3080
3301
  let clean = String(rawName).trim().replace(/^\/+/, '');
3081
3302
  if (!clean) return;
3082
- if (!/\.(js|ts|json|md|txt)$/i.test(clean) && !clean.includes('.')) {
3303
+ if (!/\.(js|ts|cpp|cc|cxx|hpp|h|json|md|txt)$/i.test(clean) && !clean.includes('.')) {
3083
3304
  clean += `.${this.lang}`;
3084
3305
  }
3085
3306
  if (this.files[clean] !== undefined) {
@@ -3097,7 +3318,11 @@ declare module 'bun:sqlite' {
3097
3318
  } else {
3098
3319
  this.files[clean] = clean.endsWith('.json')
3099
3320
  ? '{\n "name": "' + this.labId + '",\n "dependencies": {}\n}\n'
3100
- : `'use strict';\n\n// ${clean}\n`;
3321
+ : /\.(hpp|h)$/i.test(clean)
3322
+ ? `#pragma once\n#include <bits/stdc++.h>\n\n// ${clean}\n`
3323
+ : /\.(cpp|cc|cxx)$/i.test(clean)
3324
+ ? `#include <bits/stdc++.h>\nusing namespace std;\n\n// ${clean}\nint main() {\n return 0;\n}\n`
3325
+ : `'use strict';\n\n// ${clean}\n`;
3101
3326
  }
3102
3327
  this._saveState();
3103
3328
  this._getOrCreateModel(clean);
@@ -3725,10 +3950,10 @@ declare module 'bun:sqlite' {
3725
3950
 
3726
3951
  if (isFirstToken) {
3727
3952
  const commands = [
3728
- 'cat', 'cd', 'clear', 'cp', 'curl', 'echo', 'env', 'export', 'find',
3729
- 'grep', 'head', 'help', 'history', 'jobs', 'kill', 'ls', 'mkdir', 'mv',
3730
- 'node', 'npm', 'npx', 'ps', 'pwd', 'rm', 'sed', 'sort', 'tail', 'touch',
3731
- 'uniq', 'unset', 'wc', 'which', 'bun'
3953
+ 'ab', 'bun', 'cat', 'cd', 'chaos', 'clear', 'cp', 'curl', 'echo', 'env',
3954
+ 'export', 'find', 'grep', 'head', 'help', 'hey', 'history', 'jobs', 'kill',
3955
+ 'ls', 'mkdir', 'mv', 'node', 'npm', 'npx', 'ps', 'pwd', 'redis-cli', 'rm',
3956
+ 'sed', 'sort', 'sqlite3', 'tail', 'touch', 'uniq', 'unset', 'wc', 'which', 'wrk'
3732
3957
  ];
3733
3958
  return commands.filter(c => c.startsWith(token));
3734
3959
  } else {
@@ -3789,25 +4014,53 @@ declare module 'bun:sqlite' {
3789
4014
  <th>Host / URL</th>
3790
4015
  <th>Protocol</th>
3791
4016
  <th>Process / Service</th>
3792
- <th>Status</th>
3793
- <th style="text-align:right;">Actions</th>
4017
+ <th>Status &amp; Chaos</th>
4018
+ <th style="text-align:right;">Chaos Injection &amp; Actions</th>
3794
4019
  </tr>
3795
4020
  </thead>
3796
4021
  <tbody>
3797
- ${servers.map(s => `
4022
+ ${servers.map(s => {
4023
+ const rule = (this.portTable && typeof this.portTable.getChaosRule === 'function')
4024
+ ? this.portTable.getChaosRule(s.port)
4025
+ : null;
4026
+ const isCrashed = Boolean(rule && rule.crashed);
4027
+ const hasLat = Boolean(rule && rule.latencyMs > 0);
4028
+ const hasErr = Boolean(rule && rule.errorRate > 0);
4029
+ const hasDrop = Boolean(rule && rule.dropRate > 0);
4030
+ const hasAnyChaos = isCrashed || hasLat || hasErr || hasDrop || Boolean(rule && rule.partitionFromPorts && rule.partitionFromPorts.length);
4031
+ const chaosPills = [];
4032
+ if (isCrashed) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">CRASHED</span>`);
4033
+ if (hasLat) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--warn">+${rule.latencyMs}ms</span>`);
4034
+ if (hasErr) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.errorRate * 100)}% HTTP ${rule.errorStatus || 503}</span>`);
4035
+ if (hasDrop) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.dropRate * 100)}% DROP</span>`);
4036
+ return `
3798
4037
  <tr>
3799
4038
  <td><span class="codelab-port-tag">${s.port}</span></td>
3800
4039
  <td><a href="http://127.0.0.1:${s.port}/" target="_blank" class="codelab-port-link">http://127.0.0.1:${s.port}/</a></td>
3801
4040
  <td><span class="codelab-badge">${escapeHtml(s.protocol || 'HTTP/1.1')}</span></td>
3802
4041
  <td><code>${escapeHtml(s.service || (s.pid ? `PID ${s.pid}` : 'node'))}</code></td>
3803
- <td><span class="codelab-port-status codelab-port-status--listening"><span class="codelab-port-status-dot"></span>LISTENING</span></td>
4042
+ <td>
4043
+ <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
4044
+ <span class="codelab-port-status ${isCrashed ? 'codelab-port-status--crashed' : 'codelab-port-status--listening'}">
4045
+ <span class="codelab-port-status-dot"></span>${isCrashed ? 'CRASHED' : 'LISTENING'}
4046
+ </span>
4047
+ ${chaosPills.join('')}
4048
+ </div>
4049
+ </td>
3804
4050
  <td style="text-align:right;white-space:nowrap;">
4051
+ <span class="codelab-chaos-btn-group" title="Inject network faults on port :${s.port}">
4052
+ <button type="button" class="codelab-btn codelab-btn--sm ${hasLat ? 'codelab-btn--chaos-active' : ''}" data-cl-action="chaos-latency" data-port="${s.port}" title="Toggle +200ms network latency on :${s.port}">+200ms</button>
4053
+ <button type="button" class="codelab-btn codelab-btn--sm ${hasErr ? 'codelab-btn--chaos-active' : ''}" data-cl-action="chaos-error" data-port="${s.port}" title="Toggle 25% HTTP 503 error rate on :${s.port}">25% 503</button>
4054
+ <button type="button" class="codelab-btn codelab-btn--sm ${isCrashed ? 'codelab-btn--danger' : ''}" data-cl-action="chaos-crash" data-port="${s.port}" title="Simulate node crash (ECONNREFUSED) on :${s.port}">${isCrashed ? 'Recover' : 'Crash'}</button>
4055
+ ${hasAnyChaos ? `<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="chaos-heal" data-port="${s.port}" title="Heal all chaos rules on :${s.port}">Heal</button>` : ''}
4056
+ </span>
3805
4057
  <button type="button" class="codelab-btn codelab-btn--sm codelab-btn--primary" data-cl-action="open-web-preview" data-port="${s.port}" data-cl-port="${s.port}">Preview</button>
3806
4058
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="open-port-client" data-port="${s.port}" data-cl-port="${s.port}">Open in Client</button>
3807
4059
  <button type="button" class="codelab-btn codelab-btn--sm codelab-btn--danger" data-cl-action="stop-port" data-port="${s.port}" data-cl-port="${s.port}">Stop</button>
3808
4060
  </td>
3809
4061
  </tr>
3810
- `).join('')}
4062
+ `;
4063
+ }).join('')}
3811
4064
  </tbody>
3812
4065
  </table>
3813
4066
  </div>
@@ -3860,7 +4113,7 @@ declare module 'bun:sqlite' {
3860
4113
  <div class="codelab-ports-panel">
3861
4114
  <div class="codelab-panel-section">
3862
4115
  <div class="codelab-section-title">
3863
- <span>${CL_ICONS.radio || ''} Active Port Listeners</span>
4116
+ <span>${CL_ICONS.radio || ''} Active Port Listeners &amp; Chaos Controls</span>
3864
4117
  <span class="codelab-badge">${servers.length} listening</span>
3865
4118
  </div>
3866
4119
  ${serversHtml}
@@ -3945,6 +4198,85 @@ declare module 'bun:sqlite' {
3945
4198
  const traces = Array.isArray(this.lastHttpTrace) ? this.lastHttpTrace : [];
3946
4199
  const filter = this.networkFilter;
3947
4200
 
4201
+ // Compute SLO & Latency Percentiles across all captured traces
4202
+ const totalReqs = traces.length;
4203
+ let count2xx = 0;
4204
+ let count429 = 0;
4205
+ let count5xxOrErr = 0;
4206
+ const sortedDurations = traces.map(t => Number(t.durationMs || 0)).sort((a, b) => a - b);
4207
+ for (const t of traces) {
4208
+ const st = Number(t.status || 0);
4209
+ if (st >= 200 && st < 300) count2xx++;
4210
+ else if (st === 429) count429++;
4211
+ else if (st >= 500 || st === 0) count5xxOrErr++;
4212
+ }
4213
+ const pctLat = (p) => {
4214
+ if (!sortedDurations.length) return '0.0';
4215
+ const idx = Math.min(sortedDurations.length - 1, Math.floor((p / 100) * sortedDurations.length));
4216
+ return sortedDurations[idx].toFixed(1);
4217
+ };
4218
+ const okPct = totalReqs > 0 ? ((count2xx / totalReqs) * 100).toFixed(1) : '100.0';
4219
+ const p50Ms = pctLat(50);
4220
+ const p95Ms = pctLat(95);
4221
+ const p99Ms = pctLat(99);
4222
+
4223
+ // Build Live Service Topology & Chaos Map
4224
+ const servers = (this.portTable && typeof this.portTable.listServers === 'function')
4225
+ ? this.portTable.listServers()
4226
+ : [];
4227
+ const edgeMap = new Map();
4228
+ for (const t of traces) {
4229
+ const src = t.fromPort ? `:${t.fromPort}` : 'Client';
4230
+ const dst = `:${t.port || 3000}`;
4231
+ const key = `${src}→${dst}`;
4232
+ const cur = edgeMap.get(key) || { src, dst, targetPort: Number(t.port || 3000), count: 0, errCount: 0, totalMs: 0 };
4233
+ cur.count++;
4234
+ if (Number(t.status || 0) >= 500 || Number(t.status || 0) === 0) cur.errCount++;
4235
+ cur.totalMs += Number(t.durationMs || 0);
4236
+ edgeMap.set(key, cur);
4237
+ }
4238
+
4239
+ let topologyHtml = '';
4240
+ if (servers.length > 0 || edgeMap.size > 0) {
4241
+ const edgePills = Array.from(edgeMap.values()).map(e => {
4242
+ const avg = (e.totalMs / Math.max(1, e.count)).toFixed(1);
4243
+ const hasErrors = e.errCount > 0;
4244
+ return `
4245
+ <span class="codelab-topo-edge ${hasErrors ? 'codelab-topo-edge--err' : ''}">
4246
+ <strong>${escapeHtml(e.src)}</strong>
4247
+ <span class="codelab-topo-arrow">──(${e.count} req · ${avg}ms${hasErrors ? ` · ${e.errCount} err` : ''})──▶</span>
4248
+ <strong>${escapeHtml(e.dst)}</strong>
4249
+ </span>
4250
+ `;
4251
+ }).join('');
4252
+
4253
+ const nodePills = servers.map(s => {
4254
+ const rule = (this.portTable && typeof this.portTable.getChaosRule === 'function')
4255
+ ? this.portTable.getChaosRule(s.port)
4256
+ : null;
4257
+ const isCrashed = Boolean(rule && rule.crashed);
4258
+ const hasLat = Boolean(rule && rule.latencyMs > 0);
4259
+ const hasErr = Boolean(rule && rule.errorRate > 0);
4260
+ return `
4261
+ <span class="codelab-topo-node ${isCrashed ? 'is-crashed' : (hasLat || hasErr ? 'is-degraded' : 'is-healthy')}">
4262
+ <span class="codelab-port-status-dot"></span>
4263
+ <code>:${s.port}</code>
4264
+ <span>${escapeHtml(s.service || 'node')}</span>
4265
+ ${isCrashed ? '<span class="codelab-chaos-badge codelab-chaos-badge--danger">CRASHED</span>' : ''}
4266
+ ${hasLat ? `<span class="codelab-chaos-badge codelab-chaos-badge--warn">+${rule.latencyMs}ms</span>` : ''}
4267
+ ${hasErr ? `<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.errorRate * 100)}% ${rule.errorStatus || 503}</span>` : ''}
4268
+ </span>
4269
+ `;
4270
+ }).join('');
4271
+
4272
+ topologyHtml = `
4273
+ <div class="codelab-topo-bar">
4274
+ <div class="codelab-topo-nodes">${nodePills || '<span style="font-size:11px;color:var(--cl-fg-muted);">No listening servers</span>'}</div>
4275
+ ${edgePills ? `<div class="codelab-topo-edges">${edgePills}</div>` : ''}
4276
+ </div>
4277
+ `;
4278
+ }
4279
+
3948
4280
  const filtered = traces.filter(t => {
3949
4281
  if (filter.method && filter.method !== 'ALL' && (t.method || 'GET').toUpperCase() !== filter.method) return false;
3950
4282
  if (filter.status && filter.status !== 'ALL') {
@@ -3952,7 +4284,7 @@ declare module 'bun:sqlite' {
3952
4284
  if (filter.status === '2xx' && (s < 200 || s >= 300)) return false;
3953
4285
  if (filter.status === '3xx' && (s < 300 || s >= 400)) return false;
3954
4286
  if (filter.status === '4xx' && (s < 400 || s >= 500)) return false;
3955
- if (filter.status === '5xx' && (s < 500 || s >= 600)) return false;
4287
+ if (filter.status === '5xx' && (s < 500 && s !== 0)) return false;
3956
4288
  }
3957
4289
  if (filter.search) {
3958
4290
  const query = filter.search.toLowerCase();
@@ -3971,23 +4303,26 @@ declare module 'bun:sqlite' {
3971
4303
  rowsHtml = `
3972
4304
  <tr>
3973
4305
  <td colspan="7" style="text-align:center;padding:32px;color:var(--cl-fg-muted);">
3974
- ${traces.length === 0 ? 'No network requests recorded yet. Run a demo, tests, or send an HTTP request to inspect traffic.' : 'No network requests match the active filters.'}
4306
+ ${traces.length === 0 ? 'No network requests recorded yet. Run a demo, click "⚡ Load Test", or run `hey -n 50 http://localhost:3000` in the terminal.' : 'No network requests match the active filters.'}
3975
4307
  </td>
3976
4308
  </tr>
3977
4309
  `;
3978
4310
  } else {
3979
4311
  const maxDuration = Math.max(1, ...filtered.map(t => t.durationMs || 1));
3980
4312
  rowsHtml = filtered.map(t => {
3981
- const status = Number(t.status || 200);
3982
- const statusClass = status < 300 ? 'status-2xx' : (status < 400 ? 'status-3xx' : (status < 500 ? 'status-4xx' : 'status-5xx'));
4313
+ const status = Number(t.status || 0);
4314
+ const statusLabel = status === 0 ? (t.statusText || 'ERR') : String(status);
4315
+ const statusClass = status === 0 ? 'status-5xx' : (status < 300 ? 'status-2xx' : (status < 400 ? 'status-3xx' : (status < 500 ? 'status-4xx' : 'status-5xx')));
3983
4316
  const widthPct = Math.min(100, Math.max(8, Math.round(((t.durationMs || 1) / maxDuration) * 100)));
3984
4317
  const isSelected = selectedTrace && String(selectedTrace.id) === String(t.id);
4318
+ const hopLabel = t.fromPort ? `:${t.fromPort}→:${t.port || 3000}` : `:${t.port || 3000}`;
4319
+ const chaosChip = t.chaosEffect ? `<span class="codelab-chaos-badge codelab-chaos-badge--warn" style="margin-left:4px;">${escapeHtml(String(t.chaosEffect))}</span>` : '';
3985
4320
  return `
3986
4321
  <tr class="codelab-net-row ${isSelected ? 'selected' : ''}" data-cl-action="select-net-trace" data-trace-id="${escapeHtml(t.id || '')}" data-cl-trace-id="${escapeHtml(t.id || '')}">
3987
- <td><span class="codelab-status-badge ${statusClass}">${status}</span></td>
4322
+ <td><span class="codelab-status-badge ${statusClass}">${escapeHtml(statusLabel)}</span>${chaosChip}</td>
3988
4323
  <td><span class="codelab-method-badge codelab-method-${(t.method || 'GET').toLowerCase()}">${escapeHtml(t.method || 'GET')}</span></td>
3989
4324
  <td class="codelab-net-path" title="${escapeHtml(t.url || '/')}">${escapeHtml(t.url || '/')}</td>
3990
- <td><code>${t.port || 3000}</code></td>
4325
+ <td><code>${escapeHtml(hopLabel)}</code></td>
3991
4326
  <td style="white-space:nowrap;font-family:var(--cl-font-mono);font-size:11.5px;">${(t.durationMs || 0).toFixed(1)} ms</td>
3992
4327
  <td style="white-space:nowrap;font-family:var(--cl-font-mono);font-size:11.5px;">${t.size != null ? t.size : 0} B</td>
3993
4328
  <td class="codelab-waterfall-cell">
@@ -4021,6 +4356,8 @@ declare module 'bun:sqlite' {
4021
4356
  <div class="codelab-net-detail__section">
4022
4357
  <div class="codelab-detail-label">General</div>
4023
4358
  <div class="codelab-detail-kv"><strong>URL:</strong> 127.0.0.1:${selectedTrace.port}${escapeHtml(selectedTrace.url || '/')}</div>
4359
+ ${selectedTrace.fromPort ? `<div class="codelab-detail-kv"><strong>Caller Port:</strong> :${selectedTrace.fromPort}</div>` : ''}
4360
+ ${selectedTrace.chaosEffect ? `<div class="codelab-detail-kv"><strong>Chaos Fault:</strong> ${escapeHtml(String(selectedTrace.chaosEffect))}</div>` : ''}
4024
4361
  <div class="codelab-detail-kv"><strong>Status:</strong> ${selectedTrace.status} ${escapeHtml(selectedTrace.statusText || '')}</div>
4025
4362
  <div class="codelab-detail-kv"><strong>Duration:</strong> ${(selectedTrace.durationMs || 0).toFixed(2)} ms</div>
4026
4363
  <div class="codelab-detail-kv"><strong>Size:</strong> ${selectedTrace.size || 0} bytes</div>
@@ -4050,8 +4387,42 @@ declare module 'bun:sqlite' {
4050
4387
 
4051
4388
  bodyEl.innerHTML = `
4052
4389
  <div class="codelab-network-panel ${selectedTrace ? 'has-detail' : ''}">
4390
+ <div class="codelab-slo-bar" role="region" aria-label="SLO and Latency Telemetry">
4391
+ <div class="codelab-slo-metric">
4392
+ <span class="codelab-slo-label">Requests</span>
4393
+ <span class="codelab-slo-val">${totalReqs}</span>
4394
+ </div>
4395
+ <div class="codelab-slo-metric">
4396
+ <span class="codelab-slo-label">2xx SLO</span>
4397
+ <span class="codelab-slo-val ${Number(okPct) < 95 && totalReqs > 0 ? 'is-warn' : 'is-ok'}">${okPct}%</span>
4398
+ </div>
4399
+ <div class="codelab-slo-metric">
4400
+ <span class="codelab-slo-label">429 Throttled</span>
4401
+ <span class="codelab-slo-val ${count429 > 0 ? 'is-warn' : ''}">${count429}</span>
4402
+ </div>
4403
+ <div class="codelab-slo-metric">
4404
+ <span class="codelab-slo-label">5xx / Faults</span>
4405
+ <span class="codelab-slo-val ${count5xxOrErr > 0 ? 'is-err' : ''}">${count5xxOrErr}</span>
4406
+ </div>
4407
+ <div class="codelab-slo-metric">
4408
+ <span class="codelab-slo-label">p50</span>
4409
+ <span class="codelab-slo-val">${p50Ms} ms</span>
4410
+ </div>
4411
+ <div class="codelab-slo-metric">
4412
+ <span class="codelab-slo-label">p95</span>
4413
+ <span class="codelab-slo-val">${p95Ms} ms</span>
4414
+ </div>
4415
+ <div class="codelab-slo-metric">
4416
+ <span class="codelab-slo-label">p99</span>
4417
+ <span class="codelab-slo-val">${p99Ms} ms</span>
4418
+ </div>
4419
+ <div style="margin-left:auto;display:flex;align-items:center;gap:6px;">
4420
+ <button type="button" class="codelab-btn codelab-btn--sm codelab-btn--primary" data-cl-action="run-quick-loadtest" title="Run 50 concurrent requests (hey -n 50 -c 10) against active server">⚡ Load Test (50 reqs)</button>
4421
+ </div>
4422
+ </div>
4423
+ ${topologyHtml}
4053
4424
  <div class="codelab-net-toolbar">
4054
- <input type="text" class="codelab-input" id="cl-net-search" placeholder="Filter URL or method..." value="${escapeHtml(filter.search)}" aria-label="Filter network traces">
4425
+ <input type="text" class="codelab-input" id="cl-net-search" placeholder="Filter URL, port, or method..." value="${escapeHtml(filter.search)}" aria-label="Filter network traces">
4055
4426
  <select class="codelab-select" id="cl-net-method" aria-label="Filter by method">
4056
4427
  <option value="ALL" ${filter.method === 'ALL' ? 'selected' : ''}>All Methods</option>
4057
4428
  <option value="GET" ${filter.method === 'GET' ? 'selected' : ''}>GET</option>
@@ -4065,7 +4436,7 @@ declare module 'bun:sqlite' {
4065
4436
  <option value="2xx" ${filter.status === '2xx' ? 'selected' : ''}>2xx Success</option>
4066
4437
  <option value="3xx" ${filter.status === '3xx' ? 'selected' : ''}>3xx Redirect</option>
4067
4438
  <option value="4xx" ${filter.status === '4xx' ? 'selected' : ''}>4xx Client Error</option>
4068
- <option value="5xx" ${filter.status === '5xx' ? 'selected' : ''}>5xx Server Error</option>
4439
+ <option value="5xx" ${filter.status === '5xx' ? 'selected' : ''}>5xx / Network Fault</option>
4069
4440
  </select>
4070
4441
  <button type="button" class="codelab-btn" data-cl-action="clear-net-traces">Clear</button>
4071
4442
  <span style="margin-left:auto;font-size:11.5px;color:var(--cl-fg-muted);">${filtered.length} of ${traces.length} requests</span>
@@ -4075,10 +4446,10 @@ declare module 'bun:sqlite' {
4075
4446
  <table class="codelab-net-table">
4076
4447
  <thead>
4077
4448
  <tr>
4078
- <th style="width:55px;">Status</th>
4449
+ <th style="width:85px;">Status</th>
4079
4450
  <th style="width:65px;">Method</th>
4080
4451
  <th>Path</th>
4081
- <th style="width:60px;">Port</th>
4452
+ <th style="width:95px;">Route</th>
4082
4453
  <th style="width:75px;">Time</th>
4083
4454
  <th style="width:70px;">Size</th>
4084
4455
  <th style="width:140px;">Waterfall</th>
@@ -4276,6 +4647,9 @@ declare module 'bun:sqlite' {
4276
4647
  if (this.drawerTab === 'ports') this._renderDrawerBody();
4277
4648
  this._dismissPortToast(port);
4278
4649
  }));
4650
+ this._portListenerUnsubs.push(this.portTable.on('chaos', () => {
4651
+ if (this.drawerTab === 'ports' || this.drawerTab === 'network') this._renderDrawerBody();
4652
+ }));
4279
4653
  } catch (err) {
4280
4654
  this.logger.warn('Failed to attach portTable event listeners.', err);
4281
4655
  }
@@ -5556,7 +5930,15 @@ declare module 'bun:sqlite' {
5556
5930
  const rawUri = `file:///${this.labId}/${filename}`;
5557
5931
  const uri = uriParser ? uriParser.parse(rawUri) : { toString: () => rawUri };
5558
5932
  let model = typeof this.monaco.editor.getModel === 'function' ? this.monaco.editor.getModel(uri) : null;
5559
- const lang = filename.endsWith('.ts') ? 'typescript' : filename.endsWith('.json') ? 'json' : filename.endsWith('.md') ? 'markdown' : 'javascript';
5933
+ const lang = /\.(cpp|cc|cxx|hpp|h)$/i.test(filename)
5934
+ ? 'cpp'
5935
+ : filename.endsWith('.ts')
5936
+ ? 'typescript'
5937
+ : filename.endsWith('.json')
5938
+ ? 'json'
5939
+ : filename.endsWith('.md')
5940
+ ? 'markdown'
5941
+ : 'javascript';
5560
5942
  if (!model) {
5561
5943
  model = this.monaco.editor.createModel(this.files[filename] || '', lang, uri);
5562
5944
  if (model && typeof model.onDidChangeContent === 'function') {
@@ -6218,6 +6600,43 @@ declare module 'bun:sqlite' {
6218
6600
  this.networkFilter.selectedTraceId = null;
6219
6601
  }
6220
6602
  this._renderDrawerBody();
6603
+ } else if (action === 'chaos-latency' || action === 'chaos-error' || action === 'chaos-crash' || action === 'chaos-heal') {
6604
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
6605
+ if (port && this.portTable && typeof this.portTable.setChaosRule === 'function') {
6606
+ const cur = (typeof this.portTable.getChaosRule === 'function' ? this.portTable.getChaosRule(port) : null) || {};
6607
+ if (action === 'chaos-latency') {
6608
+ const nextLat = cur.latencyMs > 0 ? 0 : 200;
6609
+ this.portTable.setChaosRule(port, { latencyMs: nextLat, jitterMs: nextLat ? 40 : 0 });
6610
+ this._showToast(nextLat ? `Injected +200ms latency (±40ms jitter) on :${port}` : `Removed latency injection on :${port}`, 'info');
6611
+ } else if (action === 'chaos-error') {
6612
+ const nextErr = cur.errorRate > 0 ? 0 : 0.25;
6613
+ this.portTable.setChaosRule(port, { errorRate: nextErr, errorStatus: 503 });
6614
+ this._showToast(nextErr ? `Injected 25% HTTP 503 error rate on :${port}` : `Removed HTTP 503 fault injection on :${port}`, nextErr ? 'error' : 'info');
6615
+ } else if (action === 'chaos-crash') {
6616
+ const nextCrash = !cur.crashed;
6617
+ this.portTable.setChaosRule(port, { crashed: nextCrash });
6618
+ this._showToast(nextCrash ? `Port :${port} marked CRASHED (ECONNREFUSED)` : `Port :${port} recovered`, nextCrash ? 'error' : 'info');
6619
+ } else if (action === 'chaos-heal') {
6620
+ this.portTable.clearChaosRules(port);
6621
+ this._showToast(`Port :${port} healed (all fault rules cleared)`, 'info');
6622
+ }
6623
+ this._renderDrawerBody();
6624
+ }
6625
+ } else if (action === 'run-quick-loadtest') {
6626
+ const targetPort = this._firstListeningPort() || 3000;
6627
+ const targetUrl = `http://127.0.0.1:${targetPort}/`;
6628
+ if (this.shell && typeof this.shell.execute === 'function') {
6629
+ this._showToast(`Running load test: hey -n 50 -c 10 ${targetUrl}`, 'info');
6630
+ this.shell.execute(`hey -n 50 -c 10 ${targetUrl}`, {}).then((res) => {
6631
+ if (res && res.stdout) {
6632
+ this.terminalLogs.push({ type: 'system', text: `\n$ hey -n 50 -c 10 ${targetUrl}` });
6633
+ this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
6634
+ }
6635
+ this._renderDrawerBody();
6636
+ }).catch((err) => {
6637
+ this.logger.debug('Quick load test failed.', err);
6638
+ });
6639
+ }
6221
6640
  }
6222
6641
  return;
6223
6642
  }
@@ -6305,7 +6724,12 @@ declare module 'bun:sqlite' {
6305
6724
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
6306
6725
  { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
6307
6726
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
6308
- { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
6727
+ { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript / C++', action: () => {
6728
+ const order = ['js', 'ts'];
6729
+ if (this.enabledLanguages && this.enabledLanguages.has('cpp')) order.push('cpp');
6730
+ const next = order[(order.indexOf(this.lang) + 1) % order.length] || 'js';
6731
+ this.setLanguage(next);
6732
+ } },
6309
6733
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
6310
6734
  { id: 'toggle-guide', label: 'View: Toggle Guide Sidebar', action: () => this.toggleGuide() },
6311
6735
  { id: 'toggle-drawer', label: 'View: Toggle Bottom Drawer (Tests / Terminal / VFS)', action: () => {
@@ -6770,7 +7194,7 @@ declare module 'bun:sqlite' {
6770
7194
  const step = this.steps[idx];
6771
7195
  if (step) {
6772
7196
  const rawTarget = step.targetFile || this._pickDefaultFile();
6773
- const targetFile = this.lang === 'ts' && rawTarget ? rawTarget.replace(/\.js$/, '.ts') : rawTarget;
7197
+ const targetFile = rawTarget ? this._resolveStepTargetFile(rawTarget) : this._pickDefaultFile();
6774
7198
  this.openFile(targetFile, step.targetSymbol || `TODO (Step ${idx + 1})`);
6775
7199
  }
6776
7200
  }
@@ -6874,15 +7298,27 @@ declare module 'bun:sqlite' {
6874
7298
  }
6875
7299
  }
6876
7300
 
7301
+ get language() {
7302
+ return this.lang;
7303
+ }
7304
+
7305
+ set language(newLang) {
7306
+ this.setLanguage(newLang);
7307
+ }
7308
+
6877
7309
  setLanguage(newLang) {
6878
- if (newLang !== 'js' && newLang !== 'ts') return;
7310
+ if (newLang !== 'js' && newLang !== 'ts' && newLang !== 'cpp') return;
6879
7311
  if (this.lang === newLang) return;
6880
7312
  this.lang = newLang;
7313
+ if (this.enabledLanguages instanceof Set) {
7314
+ this.enabledLanguages.add(newLang);
7315
+ }
6881
7316
  this.files = this._computeInitialFiles();
6882
7317
  this.openTabs = this._orderedFileNames();
6883
7318
  this.activeFile = this._pickDefaultFile();
6884
7319
  this._saveState();
6885
7320
 
7321
+ this._refreshLanguageSwitcher();
6886
7322
  this.container.querySelectorAll('[data-cl-lang]').forEach(btn => {
6887
7323
  const isActive = btn.dataset.clLang === this.lang;
6888
7324
  btn.classList.toggle('active', isActive);
@@ -6894,6 +7330,14 @@ declare module 'bun:sqlite' {
6894
7330
  this._renderGuidePane();
6895
7331
  }
6896
7332
 
7333
+ switchLang(newLang) {
7334
+ return this.setLanguage(newLang);
7335
+ }
7336
+
7337
+ switchMode(newMode) {
7338
+ return this.setMode(newMode);
7339
+ }
7340
+
6897
7341
  configure({ mode, lang, stepIndex, onClose } = {}) {
6898
7342
  if (typeof onClose === 'function') {
6899
7343
  this.onClose = onClose;
@@ -6913,7 +7357,7 @@ declare module 'bun:sqlite' {
6913
7357
  if (mode === 'guided' || mode === 'sandbox') {
6914
7358
  this.setMode(mode);
6915
7359
  }
6916
- if (lang === 'js' || lang === 'ts') {
7360
+ if (lang === 'js' || lang === 'ts' || lang === 'cpp') {
6917
7361
  this.setLanguage(lang);
6918
7362
  }
6919
7363
  if (typeof stepIndex === 'number' && !Number.isNaN(stepIndex)) {
@@ -7168,12 +7612,14 @@ declare module 'bun:sqlite' {
7168
7612
  const payload = {
7169
7613
  ...execOptions,
7170
7614
  instanceId: this.instanceId,
7615
+ cppCompiler: execOptions.cppCompiler || this.cppCompiler,
7171
7616
  onStdout: execOptions.onStdout || ((chunk) => this._appendTerminalStream('stdout', chunk)),
7172
7617
  onStderr: execOptions.onStderr || ((chunk) => this._appendTerminalStream('stderr', chunk)),
7173
7618
  signal: execOptions.signal || this._activeCommandAbortController?.signal
7174
7619
  };
7175
7620
  try {
7176
- if (typeof root.CodeLabRuntime?.preloadNpmPackages === 'function' && payload && payload.files) {
7621
+ 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) {
7177
7623
  const rawDetected = this._detectPackages();
7178
7624
  const detectedList = Array.isArray(rawDetected)
7179
7625
  ? rawDetected
@@ -7190,9 +7636,11 @@ declare module 'bun:sqlite' {
7190
7636
  payload.packages = Object.assign({}, preloaded, payload.packages || {});
7191
7637
  }
7192
7638
  }
7193
- this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
7639
+ this._setRuntimeStatus('running', isCppEntry ? `Compiling & Running ${payload.entry}...` : `Running ${payload.entry || payload.mode || 'script'}...`);
7194
7640
  let res;
7195
- if (typeof root.CodeLabRuntime?.executeInWorker === 'function') {
7641
+ if (isCppEntry && typeof root.CodeLabRuntime?.executeInVirtualRuntime === 'function') {
7642
+ res = await root.CodeLabRuntime.executeInVirtualRuntime(payload);
7643
+ } else if (typeof root.CodeLabRuntime?.executeInWorker === 'function') {
7196
7644
  res = await root.CodeLabRuntime.executeInWorker(payload);
7197
7645
  } else if (typeof root.CodeLabRuntime?.executeInVirtualRuntime === 'function') {
7198
7646
  res = await root.CodeLabRuntime.executeInVirtualRuntime(payload);
@@ -7229,13 +7677,18 @@ declare module 'bun:sqlite' {
7229
7677
  this.isRunning = true;
7230
7678
  this._updateRunStateUI();
7231
7679
  this.drawerTab = 'terminal';
7232
- this.terminalLogs.push({ type: 'system', text: `\n$ node ${entry}` });
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
+ });
7233
7685
  this._renderDrawerBody();
7234
7686
 
7235
- const abortCtrl = new AbortController();
7687
+ let abortCtrl = new AbortController();
7236
7688
  this._activeCommandAbortController = abortCtrl;
7237
7689
  let streamedStdout = false;
7238
7690
  let streamedStderr = false;
7691
+ let lastRes = null;
7239
7692
 
7240
7693
  try {
7241
7694
  const res = await this._executeRuntime({
@@ -7252,6 +7705,7 @@ declare module 'bun:sqlite' {
7252
7705
  this._appendTerminalStream('stderr', c);
7253
7706
  }
7254
7707
  });
7708
+ lastRes = res;
7255
7709
  this._flushTerminalStream();
7256
7710
  const aborted = this._isAbortResult(res, abortCtrl.signal);
7257
7711
 
@@ -7287,6 +7741,7 @@ declare module 'bun:sqlite' {
7287
7741
  }
7288
7742
 
7289
7743
  this._renderDrawerBody();
7744
+ return lastRes;
7290
7745
  }
7291
7746
 
7292
7747
  async runTests(filterTestNames = null) {
@@ -7302,12 +7757,17 @@ declare module 'bun:sqlite' {
7302
7757
  this.isRunning = true;
7303
7758
  this._updateRunStateUI();
7304
7759
  this.drawerTab = 'tests';
7305
- this.terminalLogs.push({ type: 'system', text: `\n$ node ${entry}` });
7760
+ const isCppTest = /\.(cpp|cc|cxx)$/i.test(entry);
7761
+ this.terminalLogs.push({
7762
+ type: 'system',
7763
+ text: isCppTest ? `\n$ g++ -std=c++20 ${entry} -o a.out && ./a.out` : `\n$ node ${entry}`
7764
+ });
7306
7765
 
7307
- const abortCtrl = new AbortController();
7766
+ let abortCtrl = new AbortController();
7308
7767
  this._activeCommandAbortController = abortCtrl;
7309
7768
  let streamedStdout = false;
7310
7769
  let streamedStderr = false;
7770
+ let lastRes = null;
7311
7771
 
7312
7772
  try {
7313
7773
  const res = await this._executeRuntime({
@@ -7325,6 +7785,7 @@ declare module 'bun:sqlite' {
7325
7785
  this._appendTerminalStream('stderr', c);
7326
7786
  }
7327
7787
  });
7788
+ lastRes = res;
7328
7789
  this._flushTerminalStream();
7329
7790
  const aborted = this._isAbortResult(res, abortCtrl.signal);
7330
7791
 
@@ -7405,6 +7866,7 @@ declare module 'bun:sqlite' {
7405
7866
  this._renderStepPills();
7406
7867
  this._renderGuidePane();
7407
7868
  this._renderDrawerBody();
7869
+ return lastRes;
7408
7870
  }
7409
7871
 
7410
7872
  async verifyCurrentStep() {
@@ -7735,7 +8197,7 @@ declare module 'bun:sqlite' {
7735
8197
  if (data.mode === 'guided' || data.mode === 'sandbox') {
7736
8198
  this.mode = data.mode;
7737
8199
  }
7738
- if (data.language === 'js' || data.language === 'ts') {
8200
+ if (data.language === 'js' || data.language === 'ts' || data.language === 'cpp') {
7739
8201
  this.lang = data.language;
7740
8202
  }
7741
8203
  if (data.files && typeof data.files === 'object') {
@@ -8285,6 +8747,10 @@ declare module 'bun:sqlite' {
8285
8747
  } else if (typeof plugin === 'object' && typeof plugin.install === 'function') {
8286
8748
  plugin.install(this, pluginOptions);
8287
8749
  }
8750
+ if (this.enabledLanguages instanceof Set && this.enabledLanguages.size > 1) {
8751
+ this.hasMultipleLanguages = true;
8752
+ }
8753
+ this._refreshLanguageSwitcher();
8288
8754
  return this;
8289
8755
  }
8290
8756
 
@@ -8347,7 +8813,7 @@ declare module 'bun:sqlite' {
8347
8813
  if (rootEl) rootEl.setAttribute('data-cl-theme', this._instance._resolvedTheme());
8348
8814
  } else if (name === 'mode' && (newVal === 'guided' || newVal === 'sandbox')) {
8349
8815
  this._instance.switchMode(newVal);
8350
- } else if ((name === 'language' || name === 'lang') && (newVal === 'js' || newVal === 'ts')) {
8816
+ } else if ((name === 'language' || name === 'lang') && (newVal === 'js' || newVal === 'ts' || newVal === 'cpp')) {
8351
8817
  this._instance.switchLang(newVal);
8352
8818
  } else if (name === 'title' && newVal) {
8353
8819
  this._instance.title = newVal;
@@ -8512,7 +8978,10 @@ declare module 'bun:sqlite' {
8512
8978
  renderMarkdown: renderSimpleMarkdown,
8513
8979
  renderSimpleMarkdown: renderSimpleMarkdown,
8514
8980
  extensions: {
8515
- guidedLab: null
8981
+ guidedLab: null,
8982
+ javascript: null,
8983
+ typescript: null,
8984
+ cpp: null
8516
8985
  },
8517
8986
  parseGitHubRepoUrl,
8518
8987
  cloneRepo: cloneGitHubRepository,