@innovatorved/code-lab 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -162,7 +162,12 @@ var CodeLabCsp = (() => {
162
162
  directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
163
163
  directive("frame-src", withData("frameSrc")),
164
164
  directive("form-action", [self]),
165
- directive("frame-ancestors", [options.frameAncestors || "'self'"])
165
+ directive("frame-ancestors", (() => {
166
+ const rawFa = typeof options.frameAncestors === "string" ? options.frameAncestors.trim() : "";
167
+ if (!rawFa) return ["'self'"];
168
+ const tokens = cleanSources(rawFa.split(/\s+/));
169
+ return tokens.length > 0 ? tokens : ["'self'"];
170
+ })())
166
171
  ].join("; ");
167
172
  }
168
173
  function describePreviewNetwork(config) {
@@ -200,15 +205,6 @@ var CodeLabCsp = (() => {
200
205
  };
201
206
  }
202
207
  function shim(name) {
203
- var blocked = false;
204
- try {
205
- var existing = window[name];
206
- if (existing) { existing.getItem('__codelab_probe__'); return; }
207
- } catch (err) {
208
- // Expected on an opaque origin: the accessor itself throws.
209
- blocked = Boolean(err);
210
- }
211
- void blocked;
212
208
  try {
213
209
  Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
214
210
  } catch (err) {
@@ -368,6 +364,7 @@ var CodeLabCsp = (() => {
368
364
  }
369
365
 
370
366
  window.addEventListener('message', function (event) {
367
+ if (event && event.source && event.source !== window.parent) return;
371
368
  var data = event && event.data;
372
369
  if (!data || typeof data !== 'object') return;
373
370
  if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
@@ -771,6 +768,13 @@ var CodeLabZip = (() => {
771
768
  }
772
769
  return (crc ^ 4294967295) >>> 0;
773
770
  }
771
+ var DANGEROUS_PATH_SEGMENTS = /* @__PURE__ */ new Set([
772
+ "__proto__",
773
+ "constructor",
774
+ "prototype"
775
+ ]);
776
+ var MAX_ZIP_ENTRIES = 1e4;
777
+ var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
774
778
  function sanitizeZipPath(rawPath) {
775
779
  const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
776
780
  const parts = normalized.split("/");
@@ -778,6 +782,9 @@ var CodeLabZip = (() => {
778
782
  for (const part of parts) {
779
783
  const trimmed = part.trim();
780
784
  if (!trimmed || trimmed === ".") continue;
785
+ if (DANGEROUS_PATH_SEGMENTS.has(trimmed)) {
786
+ return "";
787
+ }
781
788
  if (trimmed === "..") {
782
789
  if (safeParts.length > 0) {
783
790
  safeParts.pop();
@@ -804,7 +811,7 @@ var CodeLabZip = (() => {
804
811
  function readUInt32LE(buf, offset) {
805
812
  return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
806
813
  }
807
- async function createZip(files) {
814
+ function createZip(files) {
808
815
  const entries = [];
809
816
  let localSectionSize = 0;
810
817
  let centralDirSize = 0;
@@ -879,7 +886,7 @@ var CodeLabZip = (() => {
879
886
  writeUInt16LE(out, cursor + 20, 0);
880
887
  return out;
881
888
  }
882
- async function extractZip(data) {
889
+ function extractZip(data) {
883
890
  const bytes = toUint8Array(data);
884
891
  if (bytes.length < 22) {
885
892
  throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
@@ -896,13 +903,17 @@ var CodeLabZip = (() => {
896
903
  throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
897
904
  }
898
905
  const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
906
+ if (totalEntries > MAX_ZIP_ENTRIES) {
907
+ throw new Error(`ZIP archive exceeds maximum allowed entry count (${MAX_ZIP_ENTRIES})`);
908
+ }
899
909
  const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
900
910
  const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
901
911
  if (centralDirOffset + centralDirSize > bytes.length) {
902
912
  throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
903
913
  }
904
- const result = {};
914
+ const result = /* @__PURE__ */ Object.create(null);
905
915
  let cdCursor = centralDirOffset;
916
+ let totalExtractedBytes = 0;
906
917
  for (let i = 0; i < totalEntries; i++) {
907
918
  if (cdCursor + 46 > bytes.length) {
908
919
  throw new Error("Corrupted ZIP archive: truncated Central Directory header");
@@ -942,6 +953,10 @@ var CodeLabZip = (() => {
942
953
  if (dataEnd > bytes.length) {
943
954
  throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
944
955
  }
956
+ totalExtractedBytes += compressedSize;
957
+ if (totalExtractedBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
958
+ throw new Error(`ZIP archive exceeds maximum uncompressed size limit (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes)`);
959
+ }
945
960
  const rawFileBytes = bytes.subarray(dataStart, dataEnd);
946
961
  if (compressionMethod !== 0) {
947
962
  throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
@@ -954,7 +969,7 @@ var CodeLabZip = (() => {
954
969
  }
955
970
  result[safeName] = textDecoder.decode(rawFileBytes);
956
971
  }
957
- return result;
972
+ return { ...result };
958
973
  }
959
974
  var zip_default = {
960
975
  createZip,
@@ -1332,8 +1347,14 @@ var CodeLabSearch = (() => {
1332
1347
  }
1333
1348
  function matchesGlob(filePath, pattern) {
1334
1349
  if (!pattern || pattern === "*" || pattern === "**") return true;
1350
+ if (pattern.includes(",")) {
1351
+ const subPatterns = pattern.split(",").map((s) => s.trim()).filter(Boolean);
1352
+ if (subPatterns.length > 1) {
1353
+ return subPatterns.some((sub) => matchesGlob(filePath, sub));
1354
+ }
1355
+ }
1335
1356
  const normPath = normalizeSearchPath(filePath);
1336
- const normPattern = normalizeSearchPath(pattern);
1357
+ const normPattern = normalizeSearchPath(pattern.trim());
1337
1358
  if (normPattern === normPath) return true;
1338
1359
  if (!normPattern.includes("*") && !normPattern.includes("?")) {
1339
1360
  return normPath.includes(normPattern) || normPath.endsWith(normPattern);
@@ -1344,10 +1365,12 @@ var CodeLabSearch = (() => {
1344
1365
  const c = normPattern[i];
1345
1366
  if (c === "*") {
1346
1367
  if (normPattern[i + 1] === "*") {
1347
- regexStr += ".*";
1348
1368
  i += 2;
1349
1369
  if (normPattern[i] === "/") {
1370
+ regexStr += "(?:.*/)?";
1350
1371
  i++;
1372
+ } else {
1373
+ regexStr += ".*";
1351
1374
  }
1352
1375
  continue;
1353
1376
  } else {
@@ -1371,7 +1394,12 @@ var CodeLabSearch = (() => {
1371
1394
  regexStr += "$";
1372
1395
  try {
1373
1396
  const re = new RegExp(regexStr);
1374
- return re.test(normPath);
1397
+ if (re.test(normPath)) return true;
1398
+ if (!normPattern.includes("/")) {
1399
+ const baseName = normPath.split("/").pop() || normPath;
1400
+ if (re.test(baseName)) return true;
1401
+ }
1402
+ return false;
1375
1403
  } catch (err) {
1376
1404
  return normPath.includes(normPattern.replace(/[*?]/g, ""));
1377
1405
  }
@@ -1484,7 +1512,7 @@ var CodeLabSearch = (() => {
1484
1512
  }
1485
1513
  function replaceInFiles(files, arg2, arg3, arg4) {
1486
1514
  let query = "";
1487
- const replacement = typeof arg3 === "string" ? arg3 : "";
1515
+ let replacement = typeof arg3 === "string" ? arg3 : "";
1488
1516
  let opts = {};
1489
1517
  let targetFiles = void 0;
1490
1518
  if (typeof arg2 === "string") {
@@ -1498,6 +1526,9 @@ var CodeLabSearch = (() => {
1498
1526
  } else if (arg2 && typeof arg2 === "object") {
1499
1527
  opts = arg2;
1500
1528
  query = opts.query || "";
1529
+ if (typeof arg3 !== "string" && typeof opts.replacement === "string") {
1530
+ replacement = opts.replacement;
1531
+ }
1501
1532
  if (Array.isArray(arg4)) {
1502
1533
  targetFiles = arg4;
1503
1534
  } else {
@@ -1505,10 +1536,13 @@ var CodeLabSearch = (() => {
1505
1536
  }
1506
1537
  }
1507
1538
  if (!query) {
1539
+ const copy = { ...files };
1508
1540
  return {
1509
- updatedFiles: { ...files },
1541
+ updatedFiles: copy,
1542
+ files: copy,
1510
1543
  replacedCount: 0,
1511
- filesAffected: []
1544
+ filesAffected: [],
1545
+ filesModified: 0
1512
1546
  };
1513
1547
  }
1514
1548
  const isCaseSensitive = Boolean(opts.caseSensitive);
@@ -1524,10 +1558,13 @@ var CodeLabSearch = (() => {
1524
1558
  try {
1525
1559
  regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1526
1560
  } catch (err) {
1561
+ const copy = { ...files };
1527
1562
  return {
1528
- updatedFiles: { ...files },
1563
+ updatedFiles: copy,
1564
+ files: copy,
1529
1565
  replacedCount: 0,
1530
- filesAffected: []
1566
+ filesAffected: [],
1567
+ filesModified: 0
1531
1568
  };
1532
1569
  }
1533
1570
  const updatedFiles = { ...files };
@@ -1537,35 +1574,47 @@ var CodeLabSearch = (() => {
1537
1574
  if (targetFiles && !targetFiles.includes(filePath)) continue;
1538
1575
  if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1539
1576
  if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1540
- regex.lastIndex = 0;
1577
+ const lines = content.split("\n");
1541
1578
  let countInFile = 0;
1542
- let m;
1543
- while ((m = regex.exec(content)) !== null) {
1544
- countInFile++;
1545
- if (m[0].length === 0) {
1546
- regex.lastIndex++;
1547
- if (regex.lastIndex > content.length) {
1548
- break;
1579
+ const newLines = [];
1580
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
1581
+ const lineText = lines[lineIdx];
1582
+ regex.lastIndex = 0;
1583
+ let lineMatches = 0;
1584
+ let m;
1585
+ while ((m = regex.exec(lineText)) !== null) {
1586
+ lineMatches++;
1587
+ if (m[0].length === 0) {
1588
+ regex.lastIndex++;
1589
+ if (regex.lastIndex > lineText.length) {
1590
+ break;
1591
+ }
1549
1592
  }
1550
1593
  }
1551
- }
1552
- if (countInFile > 0) {
1553
- regex.lastIndex = 0;
1554
- let newContent;
1555
- if (isRegex) {
1556
- newContent = content.replace(regex, replacement);
1594
+ if (lineMatches > 0) {
1595
+ countInFile += lineMatches;
1596
+ regex.lastIndex = 0;
1597
+ if (isRegex) {
1598
+ newLines.push(lineText.replace(regex, replacement));
1599
+ } else {
1600
+ newLines.push(lineText.replace(regex, () => replacement));
1601
+ }
1557
1602
  } else {
1558
- newContent = content.replace(regex, () => replacement);
1603
+ newLines.push(lineText);
1559
1604
  }
1560
- updatedFiles[filePath] = newContent;
1605
+ }
1606
+ if (countInFile > 0) {
1607
+ updatedFiles[filePath] = newLines.join("\n");
1561
1608
  filesAffected.push(filePath);
1562
1609
  replacedCount += countInFile;
1563
1610
  }
1564
1611
  }
1565
1612
  return {
1566
1613
  updatedFiles,
1614
+ files: updatedFiles,
1567
1615
  replacedCount,
1568
- filesAffected
1616
+ filesAffected,
1617
+ filesModified: filesAffected.length
1569
1618
  };
1570
1619
  }
1571
1620
  return __toCommonJS(search_exports);
@@ -1600,9 +1649,11 @@ var CodeLabDiagnostics = (() => {
1600
1649
  var DiagnosticsStore = class {
1601
1650
  items = /* @__PURE__ */ new Map();
1602
1651
  listeners = /* @__PURE__ */ new Set();
1603
- add(item) {
1604
- if (!item || typeof item.id !== "string" || !item.id) return;
1605
- const normalized = {
1652
+ batchDepth = 0;
1653
+ batchDirty = false;
1654
+ normalizeItem(item) {
1655
+ if (!item || typeof item.id !== "string" || !item.id) return null;
1656
+ return {
1606
1657
  ...item,
1607
1658
  file: String(item.file || ""),
1608
1659
  line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
@@ -1610,9 +1661,39 @@ var CodeLabDiagnostics = (() => {
1610
1661
  message: String(item.message || ""),
1611
1662
  severity: item.severity || "error"
1612
1663
  };
1664
+ }
1665
+ add(item) {
1666
+ const normalized = this.normalizeItem(item);
1667
+ if (!normalized) return;
1613
1668
  this.items.set(normalized.id, normalized);
1614
1669
  this.notify();
1615
1670
  }
1671
+ setMany(items, clearSource) {
1672
+ this.batch(() => {
1673
+ if (clearSource !== void 0) {
1674
+ this.clear(clearSource);
1675
+ }
1676
+ for (const item of items) {
1677
+ const normalized = this.normalizeItem(item);
1678
+ if (normalized) {
1679
+ this.items.set(normalized.id, normalized);
1680
+ this.batchDirty = true;
1681
+ }
1682
+ }
1683
+ });
1684
+ }
1685
+ batch(fn) {
1686
+ this.batchDepth++;
1687
+ try {
1688
+ fn();
1689
+ } finally {
1690
+ this.batchDepth--;
1691
+ if (this.batchDepth === 0 && this.batchDirty) {
1692
+ this.batchDirty = false;
1693
+ this.notify();
1694
+ }
1695
+ }
1696
+ }
1616
1697
  remove(id) {
1617
1698
  if (this.items.delete(id)) {
1618
1699
  this.notify();
@@ -1654,6 +1735,10 @@ var CodeLabDiagnostics = (() => {
1654
1735
  };
1655
1736
  }
1656
1737
  notify() {
1738
+ if (this.batchDepth > 0) {
1739
+ this.batchDirty = true;
1740
+ return;
1741
+ }
1657
1742
  if (this.listeners.size === 0) return;
1658
1743
  const snapshot = this.getAll();
1659
1744
  for (const listener of this.listeners) {
@@ -1737,10 +1822,28 @@ var CodeLabScm = (() => {
1737
1822
  ]
1738
1823
  };
1739
1824
  }
1740
- function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1741
- const state = gitState || createGitState({});
1742
- const headFiles = state.headFiles || {};
1743
- const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1825
+ function computeGitStatus(arg1, arg2 = "/workspace", gitState) {
1826
+ let vfsFiles;
1827
+ let state;
1828
+ if (arg1 && typeof arg1 === "object" && ("headFiles" in arg1 || "headSnapshot" in arg1 || "staged" in arg1 || "commits" in arg1)) {
1829
+ state = arg1;
1830
+ vfsFiles = arg2 && typeof arg2 === "object" ? arg2 : {};
1831
+ } else {
1832
+ vfsFiles = arg1 && typeof arg1 === "object" ? arg1 : {};
1833
+ state = gitState || createGitState({});
1834
+ }
1835
+ const headFiles = state.headFiles || state.headSnapshot || {};
1836
+ const currentStaged = /* @__PURE__ */ new Map();
1837
+ if (state.staged instanceof Map) {
1838
+ for (const [k, v] of state.staged.entries()) {
1839
+ currentStaged.set(k, v);
1840
+ }
1841
+ } else if (state.staged instanceof Set) {
1842
+ for (const k of state.staged.values()) {
1843
+ const existsInVfs = Object.prototype.hasOwnProperty.call(vfsFiles, k);
1844
+ currentStaged.set(k, existsInVfs ? vfsFiles[k] : null);
1845
+ }
1846
+ }
1744
1847
  const untracked = [];
1745
1848
  const modified = [];
1746
1849
  const deleted = [];
@@ -1748,12 +1851,14 @@ var CodeLabScm = (() => {
1748
1851
  for (const [filePath, stagedContent] of currentStaged.entries()) {
1749
1852
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1750
1853
  if (stagedContent === null) {
1751
- staged.push({
1752
- path: filePath,
1753
- status: "deleted",
1754
- staged: true,
1755
- oldContent: headFiles[filePath]
1756
- });
1854
+ if (inHead) {
1855
+ staged.push({
1856
+ path: filePath,
1857
+ status: "deleted",
1858
+ staged: true,
1859
+ oldContent: headFiles[filePath]
1860
+ });
1861
+ }
1757
1862
  } else {
1758
1863
  staged.push({
1759
1864
  path: filePath,
@@ -1806,6 +1911,36 @@ var CodeLabScm = (() => {
1806
1911
  }
1807
1912
  }
1808
1913
  const unstaged = [...modified, ...deleted];
1914
+ const entries = [
1915
+ ...staged.map((s) => ({
1916
+ path: s.path,
1917
+ status: s.status,
1918
+ staged: true,
1919
+ index: s.status === "added" ? "A" : s.status === "deleted" ? "D" : "M",
1920
+ worktree: " "
1921
+ })),
1922
+ ...modified.map((m) => ({
1923
+ path: m.path,
1924
+ status: m.status,
1925
+ staged: false,
1926
+ index: " ",
1927
+ worktree: "M"
1928
+ })),
1929
+ ...deleted.map((d) => ({
1930
+ path: d.path,
1931
+ status: d.status,
1932
+ staged: false,
1933
+ index: " ",
1934
+ worktree: "D"
1935
+ })),
1936
+ ...untracked.map((u) => ({
1937
+ path: u.path,
1938
+ status: u.status,
1939
+ staged: false,
1940
+ index: "?",
1941
+ worktree: "?"
1942
+ }))
1943
+ ];
1809
1944
  const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1810
1945
  return {
1811
1946
  branch: state.branch || "main",
@@ -1815,6 +1950,7 @@ var CodeLabScm = (() => {
1815
1950
  deleted,
1816
1951
  staged,
1817
1952
  unstaged,
1953
+ entries,
1818
1954
  hasChanges: !isClean,
1819
1955
  isClean
1820
1956
  };
@@ -1824,11 +1960,20 @@ var CodeLabScm = (() => {
1824
1960
  if (!(gitState.staged instanceof Map)) {
1825
1961
  gitState.staged = /* @__PURE__ */ new Map();
1826
1962
  }
1827
- gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1963
+ const normalizedContent = currentContent === void 0 ? null : currentContent;
1964
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
1965
+ if (normalizedContent === null && !Object.prototype.hasOwnProperty.call(headFiles, relativePath) && !gitState.staged.has(relativePath)) {
1966
+ return;
1967
+ }
1968
+ gitState.staged.set(relativePath, normalizedContent);
1828
1969
  }
1829
1970
  function unstageFile(gitState, relativePath) {
1830
- if (!gitState || !(gitState.staged instanceof Map)) return;
1831
- gitState.staged.delete(relativePath);
1971
+ if (!gitState) return;
1972
+ if (gitState.staged instanceof Map) {
1973
+ gitState.staged.delete(relativePath);
1974
+ } else if (gitState.staged instanceof Set) {
1975
+ gitState.staged.delete(relativePath);
1976
+ }
1832
1977
  }
1833
1978
  function commitChanges(gitState, message) {
1834
1979
  const trimmed = typeof message === "string" ? message.trim() : "";
@@ -1838,8 +1983,10 @@ var CodeLabScm = (() => {
1838
1983
  if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1839
1984
  throw new Error("Nothing to commit (staging area is empty)");
1840
1985
  }
1841
- const newHeadFiles = { ...gitState.headFiles || {} };
1986
+ const newHeadFiles = { ...gitState.headFiles || gitState.headSnapshot || {} };
1987
+ const diffSummaryParts = [];
1842
1988
  for (const [filePath, content] of gitState.staged.entries()) {
1989
+ diffSummaryParts.push(`${filePath}:${content === null ? "<DEL>" : content}`);
1843
1990
  if (content === null) {
1844
1991
  delete newHeadFiles[filePath];
1845
1992
  } else {
@@ -1847,19 +1994,22 @@ var CodeLabScm = (() => {
1847
1994
  }
1848
1995
  }
1849
1996
  const timestamp = Date.now();
1850
- const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1997
+ const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
1998
+ const hash = computeShortCommitHash(
1999
+ `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join("|")}`
2000
+ );
1851
2001
  const commit = {
1852
2002
  hash,
1853
2003
  message: trimmed,
1854
2004
  timestamp,
1855
- files: newHeadFiles
2005
+ files: { ...newHeadFiles }
1856
2006
  };
1857
2007
  if (!Array.isArray(gitState.commits)) {
1858
2008
  gitState.commits = [];
1859
2009
  }
1860
2010
  gitState.commits.push(commit);
1861
2011
  gitState.headCommit = hash;
1862
- gitState.headFiles = newHeadFiles;
2012
+ gitState.headFiles = { ...newHeadFiles };
1863
2013
  gitState.staged.clear();
1864
2014
  return hash;
1865
2015
  }
@@ -2003,7 +2153,8 @@ var CodeLabWorkbenchComponents = (() => {
2003
2153
  padding: 4px 0;
2004
2154
  display: none;
2005
2155
  }
2006
- .codelab-split-menu.open {
2156
+ .codelab-split-menu.open,
2157
+ .codelab-split-menu.active {
2007
2158
  display: block;
2008
2159
  }
2009
2160
  .codelab-split-menu__item {
@@ -2173,6 +2324,9 @@ var CodeLabWorkbenchComponents = (() => {
2173
2324
  renderLanguageSwitcherHtml: () => renderLanguageSwitcherHtml,
2174
2325
  renderToolbarHtml: () => renderToolbarHtml
2175
2326
  });
2327
+ function escapeHtml(str) {
2328
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2329
+ }
2176
2330
  function renderLanguageSwitcherHtml(workbench) {
2177
2331
  const enabled = workbench.enabledLanguages || /* @__PURE__ */ new Set(["js"]);
2178
2332
  const showTs = enabled.has("ts");
@@ -2194,7 +2348,9 @@ var CodeLabWorkbenchComponents = (() => {
2194
2348
  function renderToolbarHtml(opts) {
2195
2349
  const { workbench, title, backLabel, hasGuidedLab, mode, activeFile, hasWebContent, activeServerCount } = opts;
2196
2350
  const isGuided = Boolean(hasGuidedLab && mode === "guided");
2197
- const brandLabel = title || "code-lab";
2351
+ const brandLabel = escapeHtml(title || "code-lab");
2352
+ const safeBackLabel = escapeHtml(backLabel);
2353
+ const safeActiveFile = escapeHtml(activeFile || "active");
2198
2354
  const testFileExists = Boolean(
2199
2355
  workbench._findEntryFile && workbench._findEntryFile("test") !== null
2200
2356
  );
@@ -2202,9 +2358,9 @@ var CodeLabWorkbenchComponents = (() => {
2202
2358
  <div class="codelab-topbar codelab-toolbar">
2203
2359
  <div class="codelab-topbar__left">
2204
2360
  ${workbench.onClose ? `
2205
- <button type="button" class="codelab-btn codelab-btn--back" data-cl-action="close-lab" title="${backLabel}">
2361
+ <button type="button" class="codelab-btn codelab-btn--back" data-cl-action="close-lab" title="${safeBackLabel}">
2206
2362
  ${CL_ICONS.arrowLeft}
2207
- <span>${backLabel}</span>
2363
+ <span>${safeBackLabel}</span>
2208
2364
  </button>
2209
2365
  ` : ""}
2210
2366
  <span class="codelab-brand ${workbench.onClose ? "codelab-brand--with-back" : ""}" title="${brandLabel}">
@@ -2268,7 +2424,7 @@ var CodeLabWorkbenchComponents = (() => {
2268
2424
  <span>\u25B6 Run Entry / Demo</span> <kbd style="opacity:0.6">\u2318\u21B5</kbd>
2269
2425
  </button>
2270
2426
  <button type="button" class="codelab-split-menu__item" data-cl-action="run-active-file">
2271
- <span>\u25B6 Run Active File (${activeFile || "active"})</span> <kbd style="opacity:0.6">\u21E7\u2318\u21B5</kbd>
2427
+ <span>\u25B6 Run Active File (${safeActiveFile})</span> <kbd style="opacity:0.6">\u21E7\u2318\u21B5</kbd>
2272
2428
  </button>
2273
2429
  ${testFileExists ? `
2274
2430
  <button type="button" class="codelab-split-menu__item" data-cl-action="run-tests">
@@ -2328,6 +2484,9 @@ var CodeLabWorkbenchComponents = (() => {
2328
2484
  renderProblemsPanelHtml: () => renderProblemsPanelHtml,
2329
2485
  renderStdinPanelHtml: () => renderStdinPanelHtml
2330
2486
  });
2487
+ function escapeHtml2(str) {
2488
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2489
+ }
2331
2490
  function formatTelemetryHud(durationMs, memoryBytes, lang) {
2332
2491
  if (durationMs === null && memoryBytes === null) return "";
2333
2492
  const timeStr = durationMs !== null ? durationMs < 1e3 ? `${durationMs.toFixed(1)} ms` : `${(durationMs / 1e3).toFixed(2)} s` : "";
@@ -2363,12 +2522,10 @@ var CodeLabWorkbenchComponents = (() => {
2363
2522
  <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>
2364
2523
  </button>
2365
2524
 
2366
- ${showTests ? `
2367
2525
  <button type="button" role="tab" aria-selected="${drawerTab === "tests"}" class="codelab-drawer__tab ${drawerTab === "tests" ? "active" : ""}" data-cl-drawertab="tests">
2368
2526
  ${CL_ICONS.check}
2369
2527
  <span>Test Suite</span>
2370
2528
  </button>
2371
- ` : ""}
2372
2529
 
2373
2530
  <button type="button" role="tab" aria-selected="${drawerTab === "stdin"}" class="codelab-drawer__tab ${drawerTab === "stdin" ? "active" : ""}" data-cl-drawertab="stdin" title="Standard Input / Competitive Programming Custom Input">
2374
2531
  ${CL_ICONS.keyboard}
@@ -2380,12 +2537,10 @@ var CodeLabWorkbenchComponents = (() => {
2380
2537
  <span>Ports</span>
2381
2538
  </button>
2382
2539
 
2383
- ${hasWebContent ? `
2384
2540
  <button type="button" role="tab" aria-selected="${drawerTab === "preview"}" class="codelab-drawer__tab ${drawerTab === "preview" ? "active" : ""}" data-cl-drawertab="preview" title="In-browser Web Preview">
2385
2541
  ${CL_ICONS.externalLink || CL_ICONS.globe}
2386
2542
  <span>Web Preview</span>
2387
2543
  </button>
2388
- ` : ""}
2389
2544
 
2390
2545
  <button type="button" role="tab" aria-selected="${drawerTab === "network"}" class="codelab-drawer__tab ${drawerTab === "network" ? "active" : ""}" data-cl-drawertab="network">
2391
2546
  ${CL_ICONS.activity}
@@ -2424,11 +2579,15 @@ var CodeLabWorkbenchComponents = (() => {
2424
2579
  ${items.map((item) => {
2425
2580
  const icon = item.severity === "error" ? "\u2717" : item.severity === "warning" ? "\u26A0" : "\u2139";
2426
2581
  const cls = item.severity === "error" ? "codelab-problem-item--error" : item.severity === "warning" ? "codelab-problem-item--warning" : "codelab-problem-item--info";
2582
+ const safeFile = escapeHtml2(item.file);
2583
+ const safeMsg = escapeHtml2(item.message);
2584
+ const safeLine = Number(item.line) || 1;
2585
+ const safeCol = Number(item.col) || 1;
2427
2586
  return `
2428
- <div class="codelab-problem-item ${cls}" data-cl-problem-file="${item.file}" data-cl-problem-line="${item.line}" data-cl-problem-col="${item.col || 1}">
2587
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${safeFile}" data-cl-problem-line="${safeLine}" data-cl-problem-col="${safeCol}">
2429
2588
  <span style="font-weight:bold;">${icon}</span>
2430
- <span>${item.message}</span>
2431
- <span class="codelab-problem-item__location">${item.file}:${item.line}:${item.col || 1}</span>
2589
+ <span>${safeMsg}</span>
2590
+ <span class="codelab-problem-item__location">${safeFile}:${safeLine}:${safeCol}</span>
2432
2591
  </div>
2433
2592
  `;
2434
2593
  }).join("")}
@@ -2436,7 +2595,7 @@ var CodeLabWorkbenchComponents = (() => {
2436
2595
  `;
2437
2596
  }
2438
2597
  function renderStdinPanelHtml(workbench) {
2439
- const val = workbench.customStdin || "";
2598
+ const val = escapeHtml2(workbench.customStdin || "");
2440
2599
  return `
2441
2600
  <div class="codelab-stdin-panel">
2442
2601
  <div class="codelab-stdin-panel__header">
@@ -2454,6 +2613,9 @@ var CodeLabWorkbenchComponents = (() => {
2454
2613
  CodeLabDiffEditorManager: () => CodeLabDiffEditorManager,
2455
2614
  computeSimpleDiff: () => computeSimpleDiff
2456
2615
  });
2616
+ function escapeHtml3(str) {
2617
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2618
+ }
2457
2619
  function computeSimpleDiff(oldText, newText) {
2458
2620
  const oldLines = String(oldText || "").split("\n");
2459
2621
  const newLines = String(newText || "").split("\n");
@@ -2539,11 +2701,24 @@ var CodeLabWorkbenchComponents = (() => {
2539
2701
  diffContainer.style.display = "flex";
2540
2702
  if (editorHost) editorHost.style.display = "none";
2541
2703
  if (fallbackTextarea) fallbackTextarea.style.display = "none";
2704
+ if (this.diffEditor) {
2705
+ this.diffEditor.dispose();
2706
+ this.diffEditor = null;
2707
+ }
2708
+ if (this.originalModel) {
2709
+ this.originalModel.dispose();
2710
+ this.originalModel = null;
2711
+ }
2712
+ if (this.modifiedModel) {
2713
+ this.modifiedModel.dispose();
2714
+ this.modifiedModel = null;
2715
+ }
2716
+ const safeFile = escapeHtml3(file);
2542
2717
  diffContainer.innerHTML = `
2543
2718
  <div class="codelab-diff-toolbar">
2544
2719
  <span style="font-weight:600;display:inline-flex;align-items:center;gap:6px;">
2545
2720
  ${CL_ICONS.diff}
2546
- <span>Diff: <code>${file}</code> (${isStarter ? "Current vs Starter" : "Current vs Solution"})</span>
2721
+ <span>Diff: <code>${safeFile}</code> (${isStarter ? "Current vs Starter" : "Current vs Solution"})</span>
2547
2722
  </span>
2548
2723
  <div class="codelab-segmented" style="margin-left:16px;">
2549
2724
  <button type="button" class="codelab-segmented__btn ${target === "starter" ? "active" : ""}" id="cl-diff-toggle-starter">Starter</button>
@@ -2558,16 +2733,14 @@ var CodeLabWorkbenchComponents = (() => {
2558
2733
  <div class="codelab-diff-host" id="cl-diff-editor-slot"></div>
2559
2734
  `;
2560
2735
  const slot = diffContainer.querySelector("#cl-diff-editor-slot");
2561
- if (!this.diffEditor) {
2562
- this.diffEditor = monaco.editor.createDiffEditor(slot, {
2563
- readOnly: false,
2564
- originalEditable: false,
2565
- theme: this.workbench.theme === "light" ? "vs" : "vs-dark",
2566
- renderSideBySide: true,
2567
- automaticLayout: true,
2568
- minimap: { enabled: false }
2569
- });
2570
- }
2736
+ this.diffEditor = monaco.editor.createDiffEditor(slot, {
2737
+ readOnly: false,
2738
+ originalEditable: false,
2739
+ theme: this.workbench.theme === "light" ? "vs" : "vs-dark",
2740
+ renderSideBySide: true,
2741
+ automaticLayout: true,
2742
+ minimap: { enabled: false }
2743
+ });
2571
2744
  const lang = file.endsWith(".ts") ? "typescript" : file.endsWith(".cpp") ? "cpp" : file.endsWith(".py") ? "python" : "javascript";
2572
2745
  this.originalModel = monaco.editor.createModel(refCode, lang);
2573
2746
  this.modifiedModel = monaco.editor.createModel(currentCode, lang);
@@ -2589,13 +2762,20 @@ var CodeLabWorkbenchComponents = (() => {
2589
2762
  this.openInlineDiff(file, "solution");
2590
2763
  });
2591
2764
  diffContainer.querySelector("#cl-diff-revert-btn")?.addEventListener("click", () => {
2592
- const starterCode = this.workbench.starterFiles && this.workbench.starterFiles[file] || "";
2765
+ const starterMap = this.workbench.starterFiles || (typeof this.workbench._getBaseFilesForModeAndLang === "function" ? this.workbench._getBaseFilesForModeAndLang("guided", this.workbench.lang) : {});
2766
+ const starterCode = starterMap && starterMap[file] || "";
2593
2767
  this.workbench.files[file] = starterCode;
2594
2768
  this.closeInlineDiff();
2595
2769
  this.workbench.openFile(file);
2596
2770
  });
2597
2771
  diffContainer.querySelector("#cl-diff-apply-btn")?.addEventListener("click", () => {
2598
- const solutionCode = this.workbench.solutionFiles && this.workbench.solutionFiles[file] || "";
2772
+ if (typeof this.workbench.applyReferenceSolution === "function") {
2773
+ this.closeInlineDiff();
2774
+ this.workbench.applyReferenceSolution();
2775
+ return;
2776
+ }
2777
+ const solutionMap = this.workbench.solutionFiles || (typeof this.workbench._getBaseFilesForModeAndLang === "function" ? this.workbench._getBaseFilesForModeAndLang("sandbox", this.workbench.lang) : {});
2778
+ const solutionCode = solutionMap && solutionMap[file] || "";
2599
2779
  this.workbench.files[file] = solutionCode;
2600
2780
  this.closeInlineDiff();
2601
2781
  this.workbench.openFile(file);
@@ -2810,21 +2990,53 @@ var CodeLabWorkbenchComponents = (() => {
2810
2990
  }
2811
2991
  return bufferToBase64Url(rawBytes);
2812
2992
  }
2993
+ var MAX_DECOMPRESSED_SNAPSHOT_BYTES = 5 * 1024 * 1024;
2813
2994
  async function decompressWorkspaceSnapshot(encoded) {
2814
2995
  if (!encoded || typeof encoded !== "string") return null;
2815
2996
  try {
2816
2997
  const bytes = base64UrlToBuffer(encoded);
2998
+ if (bytes.byteLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
2999
+ throw new Error("Snapshot payload exceeds maximum allowed size");
3000
+ }
2817
3001
  if (typeof DecompressionStream !== "undefined") {
2818
3002
  try {
2819
3003
  const ds = new DecompressionStream("deflate-raw");
2820
3004
  const writer = ds.writable.getWriter();
2821
- writer.write(bytes);
2822
- writer.close();
2823
- const response = new Response(ds.readable);
2824
- const decompressed = await response.arrayBuffer();
3005
+ const writeInput = new Uint8Array(bytes.byteLength);
3006
+ writeInput.set(bytes);
3007
+ writer.write(writeInput).catch(() => {
3008
+ });
3009
+ writer.close().catch(() => {
3010
+ });
3011
+ const reader = ds.readable.getReader();
3012
+ const chunks = [];
3013
+ let totalLength = 0;
3014
+ while (true) {
3015
+ const step = await reader.read();
3016
+ if (step.done) break;
3017
+ const chunk = step.value;
3018
+ if (chunk) {
3019
+ totalLength += chunk.byteLength;
3020
+ if (totalLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
3021
+ await reader.cancel().catch(() => {
3022
+ });
3023
+ throw new Error("Decompressed snapshot exceeds 5 MB safety limit");
3024
+ }
3025
+ chunks.push(chunk);
3026
+ }
3027
+ }
3028
+ const decompressed = new Uint8Array(totalLength);
3029
+ let offset = 0;
3030
+ for (const chunk of chunks) {
3031
+ decompressed.set(chunk, offset);
3032
+ offset += chunk.byteLength;
3033
+ }
2825
3034
  const text = new TextDecoder().decode(decompressed);
2826
3035
  return JSON.parse(text);
2827
3036
  } catch (err) {
3037
+ if (err instanceof Error && err.message.includes("safety limit")) {
3038
+ throw err;
3039
+ }
2828
3040
  const rawText2 = new TextDecoder().decode(bytes);
2829
3041
  return JSON.parse(rawText2);
2830
3042
  }
@@ -2918,6 +3130,9 @@ var CodeLabWorkbenchComponents = (() => {
2918
3130
  __export(guided_pane_exports, {
2919
3131
  renderStepPillsHtml: () => renderStepPillsHtml
2920
3132
  });
3133
+ function escapeHtml4(str) {
3134
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
3135
+ }
2921
3136
  function renderStepPillsHtml(steps, activeIndex, completedStepIds) {
2922
3137
  if (!steps || steps.length === 0) return "";
2923
3138
  return `
@@ -2926,10 +3141,11 @@ var CodeLabWorkbenchComponents = (() => {
2926
3141
  const isPassed = completedStepIds.has(step.id);
2927
3142
  const isActive = idx === activeIndex;
2928
3143
  const cls = `codelab-step-pill ${isActive ? "active" : ""} ${isPassed ? "passed" : ""}`;
3144
+ const safeTitle = escapeHtml4(step.title);
2929
3145
  return `
2930
- <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${step.title}">
3146
+ <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${safeTitle}">
2931
3147
  <span class="codelab-step-pill__num">${isPassed ? CL_ICONS.check : idx + 1}</span>
2932
- <span class="codelab-step-pill__label">${step.title}</span>
3148
+ <span class="codelab-step-pill__label">${safeTitle}</span>
2933
3149
  </button>
2934
3150
  `;
2935
3151
  }).join("")}
@@ -3979,22 +4195,40 @@ function __initVirtualRuntime(rootScope) {
3979
4195
  // =========================================================================
3980
4196
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
3981
4197
  // =========================================================================
3982
- function createVirtualFs(initialFiles = {}) {
4198
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
3983
4199
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
3984
4200
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
3985
4201
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
4202
+ const MAX_DELETED_CACHE_ENTRIES = 50;
4203
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
4204
+ const customCwdGetter = typeof vfsOptions === 'function'
4205
+ ? vfsOptions
4206
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
3986
4207
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
3987
4208
  let nextFd = 10;
3988
4209
  let nextIno = 100;
3989
4210
  let mkdtempCounter = 1;
3990
4211
 
4212
+ function recordDeletedForInspector(p, data, mtimeMs) {
4213
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
4214
+ if (deletedInspectorCache.has(p)) {
4215
+ deletedInspectorCache.delete(p);
4216
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
4217
+ const oldestKey = deletedInspectorCache.keys().next().value;
4218
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
4219
+ }
4220
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
4221
+ }
4222
+
3991
4223
  function normPath(p) {
3992
4224
  if (typeof p !== 'string' || !p) {
3993
4225
  const err = new TypeError('path must be a non-empty string');
3994
4226
  err.code = 'ERR_INVALID_ARG_TYPE';
3995
4227
  throw err;
3996
4228
  }
3997
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
4229
+ const baseCwd = typeof customCwdGetter === 'function'
4230
+ ? customCwdGetter()
4231
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
3998
4232
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
3999
4233
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
4000
4234
  }
@@ -4045,9 +4279,13 @@ function __initVirtualRuntime(rootScope) {
4045
4279
  for (const [relPath, content] of Object.entries(initialFiles)) {
4046
4280
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
4047
4281
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
4048
- const fullPath = isSystemPath
4282
+ let fullPath = isSystemPath
4049
4283
  ? normPath(relPath)
4050
4284
  : normPath(`/workspace/${cleanRel}`);
4285
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
4286
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
4287
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
4288
+ }
4051
4289
  ensureParentDirs(fullPath);
4052
4290
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
4053
4291
  files.set(fullPath, {
@@ -4227,13 +4465,6 @@ function __initVirtualRuntime(rootScope) {
4227
4465
  fsyncSync(fd) {
4228
4466
  const entry = fdTable.get(fd);
4229
4467
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
4230
- if (!entry.isDirectory && entry.inode) {
4231
- deletedInspectorCache.set(entry.path, {
4232
- data: entry.inode.data.slice(),
4233
- mtimeMs: entry.inode.mtimeMs,
4234
- deletedAtMs: null
4235
- });
4236
- }
4237
4468
  },
4238
4469
 
4239
4470
  fdatasyncSync(fd) {
@@ -4274,12 +4505,6 @@ function __initVirtualRuntime(rootScope) {
4274
4505
  inode.mtimeMs = Date.now();
4275
4506
  entry.pos = writePos + chunk.byteLength;
4276
4507
 
4277
- deletedInspectorCache.set(entry.path, {
4278
- data: inode.data.slice(),
4279
- mtimeMs: inode.mtimeMs,
4280
- deletedAtMs: null
4281
- });
4282
-
4283
4508
  return chunk.byteLength;
4284
4509
  },
4285
4510
 
@@ -4331,7 +4556,7 @@ function __initVirtualRuntime(rootScope) {
4331
4556
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
4332
4557
  }
4333
4558
  }
4334
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4559
+ deletedInspectorCache.delete(np);
4335
4560
  },
4336
4561
 
4337
4562
  chmodSync(p, mode) {
@@ -4360,7 +4585,7 @@ function __initVirtualRuntime(rootScope) {
4360
4585
  combined.set(chunk, inode.data.byteLength);
4361
4586
  inode.data = combined;
4362
4587
  inode.mtimeMs = Date.now();
4363
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4588
+ deletedInspectorCache.delete(np);
4364
4589
  },
4365
4590
 
4366
4591
  truncateSync(p, len = 0) {
@@ -4376,7 +4601,6 @@ function __initVirtualRuntime(rootScope) {
4376
4601
  inode.data = grown;
4377
4602
  }
4378
4603
  inode.mtimeMs = Date.now();
4379
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4380
4604
  },
4381
4605
 
4382
4606
  renameSync(oldP, newP) {
@@ -4437,16 +4661,14 @@ function __initVirtualRuntime(rootScope) {
4437
4661
  if (fdEntry.path === src) fdEntry.path = dst;
4438
4662
  }
4439
4663
  deletedInspectorCache.delete(src);
4440
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4664
+ deletedInspectorCache.delete(dst);
4441
4665
  },
4442
4666
 
4443
4667
  unlinkSync(p) {
4444
4668
  const np = normPath(p);
4445
4669
  const inode = files.get(np);
4446
4670
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
4447
- if (inode.data.byteLength > 0) {
4448
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4449
- }
4671
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
4450
4672
  files.delete(np);
4451
4673
  },
4452
4674
 
@@ -4463,9 +4685,7 @@ function __initVirtualRuntime(rootScope) {
4463
4685
  for (const [fPath, inode] of Array.from(files.entries())) {
4464
4686
  if (fPath.startsWith(prefix)) {
4465
4687
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
4466
- if (inode.data.byteLength > 0) {
4467
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4468
- }
4688
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
4469
4689
  files.delete(fPath);
4470
4690
  }
4471
4691
  }
@@ -6039,6 +6259,7 @@ function __initVirtualRuntime(rootScope) {
6039
6259
  responseHeaders: {},
6040
6260
  _t0: performance.now()
6041
6261
  };
6262
+ if (httpTrace.length >= 500) httpTrace.shift();
6042
6263
  httpTrace.push(traceEntry);
6043
6264
  this._traceEntry = traceEntry;
6044
6265
 
@@ -7030,6 +7251,7 @@ function __initVirtualRuntime(rootScope) {
7030
7251
  this._peer = serverSocket;
7031
7252
  this.connecting = false;
7032
7253
 
7254
+ if (sharedTrace.length >= 500) sharedTrace.shift();
7033
7255
  sharedTrace.push({
7034
7256
  protocol: 'TCP',
7035
7257
  event: 'connect',
@@ -9322,7 +9544,10 @@ function __initVirtualRuntime(rootScope) {
9322
9544
  const activePortTable = optPortTable || portTable || _defaultPortTable;
9323
9545
  resourceTracker.pid = pid;
9324
9546
 
9325
- const vfs = optVfs || createVirtualFs(files);
9547
+ let currentCwd = '/workspace';
9548
+ _activeCwdGetter = () => currentCwd;
9549
+
9550
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
9326
9551
  if (optVfs && files && typeof files === 'object') {
9327
9552
  for (const [fPath, content] of Object.entries(files)) {
9328
9553
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -9716,8 +9941,6 @@ function __initVirtualRuntime(rootScope) {
9716
9941
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
9717
9942
 
9718
9943
  let syncExecDepth = 0;
9719
- let currentCwd = '/workspace';
9720
- _activeCwdGetter = () => currentCwd;
9721
9944
 
9722
9945
  const sandboxProcess = Object.assign(new EventEmitter(), {
9723
9946
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
@@ -15626,6 +15849,13 @@ if (typeof module !== 'undefined' && module.exports) {
15626
15849
  return out;
15627
15850
  }
15628
15851
 
15852
+ function quoteShellArg(arg) {
15853
+ const s = String(arg ?? '');
15854
+ if (s.length === 0) return "''";
15855
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
15856
+ return "'" + s.replace(/'/g, "'\\''") + "'";
15857
+ }
15858
+
15629
15859
  async function runPackageScript(scriptName, scriptArgs, ctx) {
15630
15860
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
15631
15861
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -15633,7 +15863,7 @@ if (typeof module !== 'undefined' && module.exports) {
15633
15863
  }
15634
15864
  let cmd = pkgData.scripts[scriptName];
15635
15865
  if (scriptArgs && scriptArgs.length > 0) {
15636
- cmd += ' ' + scriptArgs.join(' ');
15866
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
15637
15867
  }
15638
15868
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
15639
15869
  if (fallback) return fallback;
@@ -15886,6 +16116,11 @@ if (typeof module !== 'undefined' && module.exports) {
15886
16116
  const isFile = (p) => exists(p) && !isDir(p);
15887
16117
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
15888
16118
 
16119
+ const isWithinRoot = (p) => {
16120
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
16121
+ return p === rootDir || p.startsWith(rootPrefix);
16122
+ };
16123
+
15889
16124
  const resolveLocalTarget = (baseDir, rawSpec) => {
15890
16125
  if (!rawSpec || typeof rawSpec !== 'string') return null;
15891
16126
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -15893,6 +16128,7 @@ if (typeof module !== 'undefined' && module.exports) {
15893
16128
  const candidateBase = clean.startsWith('/')
15894
16129
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
15895
16130
  : PosixPath.join(baseDir, clean);
16131
+ if (!isWithinRoot(candidateBase)) return null;
15896
16132
  if (isFile(candidateBase)) return candidateBase;
15897
16133
  const cands = [
15898
16134
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -15901,7 +16137,7 @@ if (typeof module !== 'undefined' && module.exports) {
15901
16137
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
15902
16138
  ];
15903
16139
  for (const c of cands) {
15904
- if (isFile(c)) return c;
16140
+ if (isWithinRoot(c) && isFile(c)) return c;
15905
16141
  }
15906
16142
  return null;
15907
16143
  };
@@ -16030,7 +16266,7 @@ if (typeof module !== 'undefined' && module.exports) {
16030
16266
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
16031
16267
  needsTailwindBrowser = true;
16032
16268
  }
16033
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
16269
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
16034
16270
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
16035
16271
  });
16036
16272
 
@@ -16042,7 +16278,7 @@ if (typeof module !== 'undefined' && module.exports) {
16042
16278
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
16043
16279
  const rawScript = readText(scriptTarget);
16044
16280
  if (rawScript === null) return fullTag;
16045
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
16281
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
16046
16282
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
16047
16283
  const typeAttr = isMod ? ' type="module"' : '';
16048
16284
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -16065,6 +16301,12 @@ if (typeof module !== 'undefined' && module.exports) {
16065
16301
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
16066
16302
  const rel = pathname.replace(/^\/+/, '');
16067
16303
  let target = PosixPath.join(rootDir, rel);
16304
+ if (!isWithinRoot(target)) {
16305
+ return new Response(
16306
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
16307
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
16308
+ );
16309
+ }
16068
16310
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
16069
16311
 
16070
16312
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -16089,8 +16331,13 @@ if (typeof module !== 'undefined' && module.exports) {
16089
16331
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
16090
16332
  }
16091
16333
  if (!exists(target)) {
16334
+ const safePath = String(pathname)
16335
+ .replace(/&/g, '&amp;')
16336
+ .replace(/</g, '&lt;')
16337
+ .replace(/>/g, '&gt;')
16338
+ .replace(/"/g, '&quot;');
16092
16339
  return new Response(
16093
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
16340
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
16094
16341
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
16095
16342
  );
16096
16343
  }
@@ -18241,13 +18488,17 @@ if (typeof module !== 'undefined' && module.exports) {
18241
18488
 
18242
18489
  const count = Math.max(1, result.filesWritten);
18243
18490
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
18491
+ if (!enumeratedEmitted) {
18492
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
18493
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
18494
+ }
18244
18495
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
18245
18496
  const stdout =
18246
18497
  `Cloning into '${dirDisplayName}'...\n` +
18247
18498
  `remote: Enumerating objects: ${count}, done.\n` +
18248
18499
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
18249
18500
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
18250
- return { code: 0, stdout, stderr: '' };
18501
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
18251
18502
  } catch (err) {
18252
18503
  if (ctx.signal && ctx.signal.aborted) {
18253
18504
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -19310,7 +19561,8 @@ if (typeof module !== 'undefined' && module.exports) {
19310
19561
  if (ctx.vfs.existsSync(binPath)) {
19311
19562
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
19312
19563
  }
19313
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
19564
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
19565
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
19314
19566
  },
19315
19567
 
19316
19568
  async bunx(args, ctx) {
@@ -19381,7 +19633,8 @@ if (typeof module !== 'undefined' && module.exports) {
19381
19633
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
19382
19634
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
19383
19635
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
19384
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
19636
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
19637
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
19385
19638
  }
19386
19639
 
19387
19640
  if (sub === 'dlx') {
@@ -20564,18 +20817,27 @@ if (typeof module !== 'undefined' && module.exports) {
20564
20817
  if (item.background) {
20565
20818
  const pid = this.nextPid++;
20566
20819
  const jobId = this.nextJobId++;
20820
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20567
20821
  const job = {
20568
20822
  id: jobId,
20569
20823
  pid,
20570
20824
  command: trimmed,
20571
20825
  status: 'Running',
20572
- startTime: Date.now()
20826
+ startTime: Date.now(),
20827
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20573
20828
  };
20574
20829
  this.jobs.set(jobId, job);
20575
20830
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20576
20831
 
20577
- // Run in background promise
20578
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
20832
+ // Run in background promise with its own independent AbortSignal
20833
+ this._executeAstNode(item.node, {
20834
+ ...execOptions,
20835
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
20836
+ env: Object.assign({}, this.env, currentEnv),
20837
+ cwd: this.cwd,
20838
+ pid,
20839
+ isBackground: true
20840
+ })
20579
20841
  .then(res => {
20580
20842
  if (job.status !== 'Terminated') {
20581
20843
  job.status = 'Done';
@@ -20729,17 +20991,24 @@ if (typeof module !== 'undefined' && module.exports) {
20729
20991
  if (item.background) {
20730
20992
  const pid = this.nextPid++;
20731
20993
  const jobId = this.nextJobId++;
20994
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20732
20995
  const job = {
20733
20996
  id: jobId,
20734
20997
  pid,
20735
20998
  command: 'background',
20736
20999
  status: 'Running',
20737
- startTime: Date.now()
21000
+ startTime: Date.now(),
21001
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20738
21002
  };
20739
21003
  this.jobs.set(jobId, job);
20740
21004
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20741
21005
 
20742
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
21006
+ this._executeAstNode(item.node, {
21007
+ ...context,
21008
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
21009
+ pid,
21010
+ isBackground: true
21011
+ })
20743
21012
  .then(res => {
20744
21013
  if (job.status !== 'Terminated') {
20745
21014
  job.status = 'Done';
@@ -20855,7 +21124,11 @@ if (typeof module !== 'undefined' && module.exports) {
20855
21124
  wordItems.push(...(innerCtx.positionalArgs || []));
20856
21125
  }
20857
21126
 
21127
+ let loopIter = 0;
20858
21128
  for (const val of wordItems) {
21129
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21130
+ await new Promise((r) => setTimeout(r, 0));
21131
+ }
20859
21132
  if (innerCtx.signal && innerCtx.signal.aborted) {
20860
21133
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20861
21134
  }
@@ -20900,7 +21173,11 @@ if (typeof module !== 'undefined' && module.exports) {
20900
21173
  let combinedStderr = '';
20901
21174
  let lastCode = 0;
20902
21175
 
21176
+ let loopIter = 0;
20903
21177
  while (true) {
21178
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21179
+ await new Promise((r) => setTimeout(r, 0));
21180
+ }
20904
21181
  if (innerCtx.signal && innerCtx.signal.aborted) {
20905
21182
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20906
21183
  }
@@ -21367,7 +21644,9 @@ if (typeof module !== 'undefined' && module.exports) {
21367
21644
 
21368
21645
  // Route any remaining unstreamed output
21369
21646
  if (res.stdout) {
21370
- if (streamedStdoutBytes > 0) {
21647
+ if (res.alreadyStreamed) {
21648
+ stdoutOut = res.stdout;
21649
+ } else if (streamedStdoutBytes > 0) {
21371
21650
  if (res.stdout.length > streamedStdoutBytes) {
21372
21651
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
21373
21652
  }
@@ -21726,6 +22005,14 @@ if (typeof module !== 'undefined' && module.exports) {
21726
22005
 
21727
22006
  const parseAnsiToHtml = ansiToHtml;
21728
22007
 
22008
+ const MAX_SCROLLBACK = 2000;
22009
+ const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
22010
+
22011
+ function sanitizeLogType(type) {
22012
+ const t = String(type || 'stdout').trim();
22013
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
22014
+ }
22015
+
21729
22016
  class PTYTerminalEngine {
21730
22017
  constructor(container, options = {}) {
21731
22018
  if (
@@ -21740,6 +22027,9 @@ if (typeof module !== 'undefined' && module.exports) {
21740
22027
  }
21741
22028
  this.container = container || null;
21742
22029
  this.options = options || {};
22030
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
22031
+ ? this.options.maxScrollback
22032
+ : MAX_SCROLLBACK;
21743
22033
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
21744
22034
  this.cwd = this.options.cwd || '/workspace';
21745
22035
  this.replMode = Boolean(this.options.replMode);
@@ -21753,6 +22043,7 @@ if (typeof module !== 'undefined' && module.exports) {
21753
22043
  this.searchQuery = '';
21754
22044
  this.searchMatchIdx = -1;
21755
22045
  this._readLineQueue = [];
22046
+ this.isBusy = false;
21756
22047
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
21757
22048
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
21758
22049
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -21903,13 +22194,40 @@ if (typeof module !== 'undefined' && module.exports) {
21903
22194
  this.writeStreamChunk(String(data) + '\n', type);
21904
22195
  }
21905
22196
 
22197
+ isCommandRunning() {
22198
+ return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
22199
+ }
22200
+
22201
+ _pushLog(entry) {
22202
+ const normalized = {
22203
+ type: sanitizeLogType(entry && entry.type),
22204
+ text: String(entry && entry.text != null ? entry.text : '')
22205
+ };
22206
+ this.logs.push(normalized);
22207
+ if (this.logs.length > this.maxScrollback) {
22208
+ const excess = this.logs.length - this.maxScrollback;
22209
+ this.logs.splice(0, excess);
22210
+ if (this._targetLineIdx >= 0) {
22211
+ this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
22212
+ }
22213
+ if (this.container && typeof this.container.querySelector === 'function') {
22214
+ const logEl = this.container.querySelector('#cl-terminal-log');
22215
+ if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
22216
+ while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
22217
+ logEl.removeChild(logEl.firstChild);
22218
+ }
22219
+ }
22220
+ }
22221
+ }
22222
+ return normalized;
22223
+ }
22224
+
21906
22225
  _getActiveLine(type) {
21907
22226
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
21908
22227
  return this.logs[this._targetLineIdx];
21909
22228
  }
21910
22229
  if (this._activeLineCommitted || this.logs.length === 0) {
21911
- const newLine = { text: '', type };
21912
- this.logs.push(newLine);
22230
+ const newLine = this._pushLog({ text: '', type });
21913
22231
  this._activeLineCommitted = false;
21914
22232
  this._cursorCol = 0;
21915
22233
  this._targetLineIdx = this.logs.length - 1;
@@ -21926,7 +22244,7 @@ if (typeof module !== 'undefined' && module.exports) {
21926
22244
  const logEl = this.container.querySelector('#cl-terminal-log');
21927
22245
  if (!logEl) return;
21928
22246
  const lineEl = document.createElement('div');
21929
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22247
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21930
22248
  lineEl.innerHTML = ansiToHtml(line.text);
21931
22249
  logEl.appendChild(lineEl);
21932
22250
  this._activeLineEl = lineEl;
@@ -21949,7 +22267,7 @@ if (typeof module !== 'undefined' && module.exports) {
21949
22267
  }
21950
22268
  }
21951
22269
  if (lineEl) {
21952
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22270
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21953
22271
  lineEl.innerHTML = ansiToHtml(line.text);
21954
22272
  }
21955
22273
  }
@@ -21988,17 +22306,29 @@ if (typeof module !== 'undefined' && module.exports) {
21988
22306
  return [...this.history];
21989
22307
  }
21990
22308
 
21991
- readLine(promptText = '') {
21992
- const prevPrompt = this.promptOverride;
21993
- if (promptText) {
21994
- this.setPrompt(promptText);
22309
+ _activateNextReadLine() {
22310
+ if (!this._readLineQueue || this._readLineQueue.length === 0) return;
22311
+ const head = this._readLineQueue[0];
22312
+ if (head && typeof head === 'object' && !head._activated) {
22313
+ head._activated = true;
22314
+ head.prevPrompt = this.promptOverride;
22315
+ if (head.promptText) {
22316
+ this.promptOverride = head.promptText;
22317
+ }
21995
22318
  }
22319
+ }
22320
+
22321
+ readLine(promptText = '') {
21996
22322
  return new Promise((resolve) => {
21997
- this._readLineQueue.push((line) => {
21998
- this.promptOverride = prevPrompt;
21999
- this.updateActiveLine();
22000
- resolve(line);
22001
- });
22323
+ const item = {
22324
+ promptText: String(promptText || ''),
22325
+ prevPrompt: null,
22326
+ _activated: false,
22327
+ resolve
22328
+ };
22329
+ this._readLineQueue.push(item);
22330
+ this._activateNextReadLine();
22331
+ this.updateActiveLine();
22002
22332
  });
22003
22333
  }
22004
22334
 
@@ -22068,6 +22398,10 @@ if (typeof module !== 'undefined' && module.exports) {
22068
22398
  if (input) {
22069
22399
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
22070
22400
  this._addListener(input, 'input', () => {
22401
+ if (this.isCommandRunning()) {
22402
+ input.value = '';
22403
+ return;
22404
+ }
22071
22405
  if (input.value !== this.buffer) {
22072
22406
  this.buffer = input.value;
22073
22407
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -22109,6 +22443,35 @@ if (typeof module !== 'undefined' && module.exports) {
22109
22443
  const key = e.key;
22110
22444
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
22111
22445
 
22446
+ if (isCtrl && (key === 'l' || key === 'L')) {
22447
+ if (e.preventDefault) e.preventDefault();
22448
+ this.clear();
22449
+ return;
22450
+ }
22451
+
22452
+ if (isCtrl && (key === 'c' || key === 'C')) {
22453
+ if (e.preventDefault) e.preventDefault();
22454
+ const wasBusy = this.isBusy;
22455
+ this.isBusy = false;
22456
+ this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
22457
+ this.buffer = '';
22458
+ this.cursor = 0;
22459
+ this.historyIdx = -1;
22460
+ if (this.replMode) {
22461
+ this.replMode = false;
22462
+ }
22463
+ if (this.onInterrupt) {
22464
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
22465
+ }
22466
+ this.render();
22467
+ return;
22468
+ }
22469
+
22470
+ if (this.isCommandRunning()) {
22471
+ if (e.preventDefault) e.preventDefault();
22472
+ return;
22473
+ }
22474
+
22112
22475
  if (isCtrl && (key === 'r' || key === 'R')) {
22113
22476
  if (e.preventDefault) e.preventDefault();
22114
22477
  if (!this.searchMode) {
@@ -22240,33 +22603,11 @@ if (typeof module !== 'undefined' && module.exports) {
22240
22603
  return;
22241
22604
  }
22242
22605
 
22243
- if (isCtrl && (key === 'l' || key === 'L')) {
22244
- if (e.preventDefault) e.preventDefault();
22245
- this.clear();
22246
- return;
22247
- }
22248
-
22249
- if (isCtrl && (key === 'c' || key === 'C')) {
22250
- if (e.preventDefault) e.preventDefault();
22251
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
22252
- this.buffer = '';
22253
- this.cursor = 0;
22254
- this.historyIdx = -1;
22255
- if (this.replMode) {
22256
- this.replMode = false;
22257
- }
22258
- if (this.onInterrupt) {
22259
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
22260
- }
22261
- this.render();
22262
- return;
22263
- }
22264
-
22265
22606
  if (isCtrl && (key === 'd' || key === 'D')) {
22266
22607
  if (this.buffer === '') {
22267
22608
  if (e.preventDefault) e.preventDefault();
22268
22609
  if (this.replMode) {
22269
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
22610
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
22270
22611
  this.replMode = false;
22271
22612
  this.render();
22272
22613
  return;
@@ -22360,14 +22701,41 @@ if (typeof module !== 'undefined' && module.exports) {
22360
22701
  }
22361
22702
 
22362
22703
  // Print candidate matches
22363
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
22364
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
22704
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
22705
+ this._pushLog({ type: 'stdout', text: matches.join(' ') });
22365
22706
  this.render();
22366
22707
  }
22367
22708
  }
22368
22709
 
22369
22710
  submitLine() {
22711
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
22712
+ const line = this.buffer;
22713
+ this.buffer = '';
22714
+ this.cursor = 0;
22715
+ this.historyIdx = -1;
22716
+ this.searchMode = false;
22717
+ this.searchQuery = '';
22718
+ this.searchMatchIdx = -1;
22719
+
22720
+ const entry = this._readLineQueue.shift();
22721
+ if (typeof entry === 'function') {
22722
+ this.updateActiveLine();
22723
+ entry(line);
22724
+ } else if (entry && typeof entry.resolve === 'function') {
22725
+ this.promptOverride = entry.prevPrompt;
22726
+ this._activateNextReadLine();
22727
+ this.updateActiveLine();
22728
+ entry.resolve(line);
22729
+ }
22730
+ return;
22731
+ }
22732
+
22733
+ if (this.isBusy) {
22734
+ return;
22735
+ }
22736
+
22370
22737
  const line = this.buffer;
22738
+ const promptSnap = this.getPrompt();
22371
22739
  this.buffer = '';
22372
22740
  this.cursor = 0;
22373
22741
  this.historyIdx = -1;
@@ -22375,22 +22743,49 @@ if (typeof module !== 'undefined' && module.exports) {
22375
22743
  this.searchQuery = '';
22376
22744
  this.searchMatchIdx = -1;
22377
22745
 
22746
+ const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
22747
+ this._activeLineCommitted = true;
22748
+ this._cursorCol = 0;
22749
+ this._targetLineIdx = -1;
22750
+ this._needsRewrite = false;
22751
+ this._appendDomLine(echoed);
22752
+ this._activeLineEl = null;
22753
+
22378
22754
  if (line.trim()) {
22379
22755
  if (this.history[this.history.length - 1] !== line.trim()) {
22380
22756
  this.history.push(line.trim());
22381
22757
  }
22382
22758
  }
22383
22759
 
22384
- if (this._readLineQueue && this._readLineQueue.length > 0) {
22385
- const resolver = this._readLineQueue.shift();
22760
+ if (!this.onCommand) {
22386
22761
  this.updateActiveLine();
22387
- resolver(line);
22388
22762
  return;
22389
22763
  }
22390
22764
 
22765
+ this.isBusy = true;
22391
22766
  this.updateActiveLine();
22392
- if (this.onCommand) {
22393
- this.onCommand(line);
22767
+
22768
+ let cmdResult;
22769
+ try {
22770
+ cmdResult = this.onCommand(line);
22771
+ } catch (err) {
22772
+ this.isBusy = false;
22773
+ this.updateActiveLine();
22774
+ throw err;
22775
+ }
22776
+
22777
+ if (cmdResult && typeof cmdResult.then === 'function') {
22778
+ Promise.resolve(cmdResult)
22779
+ .catch((err) => {
22780
+ _terminalLogger.debug('Terminal onCommand promise rejected.', err);
22781
+ })
22782
+ .finally(() => {
22783
+ this.isBusy = false;
22784
+ this.updateActiveLine();
22785
+ });
22786
+ } else {
22787
+ this.isBusy = false;
22788
+ this.updateActiveLine();
22394
22789
  }
22395
22790
  }
22396
22791
 
@@ -22403,6 +22798,16 @@ if (typeof module !== 'undefined' && module.exports) {
22403
22798
  const lineEl = this.container.querySelector('#cl-pty-active-line');
22404
22799
  if (!lineEl) return;
22405
22800
 
22801
+ if (this.isCommandRunning()) {
22802
+ if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
22803
+ if (lineEl.style) lineEl.style.display = 'none';
22804
+ lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
22805
+ return;
22806
+ }
22807
+
22808
+ if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
22809
+ if (lineEl.style) lineEl.style.display = '';
22810
+
22406
22811
  const prompt = this.searchMode
22407
22812
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
22408
22813
  : this.getPrompt();
@@ -22423,21 +22828,24 @@ if (typeof module !== 'undefined' && module.exports) {
22423
22828
  );
22424
22829
 
22425
22830
  const logsHtml = this.logs
22426
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
22831
+ .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
22427
22832
  .join('');
22428
22833
 
22429
- const prompt = this.searchMode
22430
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
22431
- : this.getPrompt();
22432
- const before = this.buffer.slice(0, this.cursor);
22433
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
22434
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
22834
+ const busy = this.isCommandRunning();
22835
+ const prompt = busy
22836
+ ? ''
22837
+ : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
22838
+ const before = busy ? '' : this.buffer.slice(0, this.cursor);
22839
+ const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
22840
+ const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
22841
+ const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
22842
+ const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
22435
22843
 
22436
22844
  this.container.innerHTML = `
22437
22845
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
22438
22846
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
22439
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
22440
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
22847
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
22848
+ <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
22441
22849
  </div>
22442
22850
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
22443
22851
  <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
@@ -22547,7 +22955,7 @@ if (typeof module !== 'undefined' && module.exports) {
22547
22955
 
22548
22956
  // The bundler rewrites this literal from package.json at build time. Keeping
22549
22957
  // the fallback in sync lets tests require src/workbench.js directly.
22550
- const CODELAB_VERSION = '0.3.0';
22958
+ const CODELAB_VERSION = '0.3.2';
22551
22959
 
22552
22960
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
22553
22961
  const NODE_AMBIENT_DTS = `
@@ -23122,11 +23530,16 @@ declare module 'bun:sqlite' {
23122
23530
  if (!str) return '';
23123
23531
  let text = String(str);
23124
23532
 
23125
- // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
23126
- text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
23533
+ // Markdown Links: [label](url "title") or [label](url) — stash anchors before emphasis regexes
23534
+ // so underscores/asterisks inside URLs or titles are not mangled, and use non-nested quantifiers.
23535
+ const inlineLinks = [];
23536
+ text = text.replace(/\[([^\]]+)\]\(([^\s()]+(?:\([^\s()]*\)[^\s()]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
23127
23537
  const cleanUrl = sanitizeUrl(url);
23128
23538
  const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
23129
- return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
23539
+ const formattedLabel = renderInlineFormatting(label);
23540
+ const idx = inlineLinks.length;
23541
+ inlineLinks.push(String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${raw(formattedLabel)}</a>`));
23542
+ return `\x00CLLINK${idx}\x00`;
23130
23543
  });
23131
23544
 
23132
23545
  // Strikethrough: ~~del~~
@@ -23144,6 +23557,10 @@ declare module 'bun:sqlite' {
23144
23557
  text = text.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
23145
23558
  text = text.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');
23146
23559
 
23560
+ if (inlineLinks.length > 0) {
23561
+ text = text.replace(/\x00CLLINK(\d+)\x00/g, (_, i) => inlineLinks[Number(i)] || '');
23562
+ }
23563
+
23147
23564
  return text;
23148
23565
  }
23149
23566
 
@@ -23331,7 +23748,7 @@ declare module 'bun:sqlite' {
23331
23748
  const lang = (info || '').trim().split(/\s+/)[0] || '';
23332
23749
  const idx = codeBlocks.length;
23333
23750
  codeBlocks.push(renderCodeBlock(code || '', lang));
23334
- return `\n\n\x00CODEBLOCK_${idx}\x00\n\n`;
23751
+ return `\n\n\x00CLCODEBLOCK${idx}\x00\n\n`;
23335
23752
  });
23336
23753
 
23337
23754
  // Phase 2: Inline Code Span Extraction
@@ -23343,7 +23760,7 @@ declare module 'bun:sqlite' {
23343
23760
  }
23344
23761
  const idx = inlineCodes.length;
23345
23762
  inlineCodes.push(`<code class="codelab-inline-code">${escapeHtml(clean)}</code>`);
23346
- return `\x00INLINECODE_${idx}\x00`;
23763
+ return `\x00CLINLINECODE${idx}\x00`;
23347
23764
  });
23348
23765
 
23349
23766
  // Phase 2b: Autolinks are the only inline construct that uses angle
@@ -23356,7 +23773,7 @@ declare module 'bun:sqlite' {
23356
23773
  autolinks.push(
23357
23774
  `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
23358
23775
  );
23359
- return `\x00AUTOLINK_${idx}\x00`;
23776
+ return `\x00CLAUTOLINK${idx}\x00`;
23360
23777
  });
23361
23778
 
23362
23779
  // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
@@ -23391,7 +23808,7 @@ declare module 'bun:sqlite' {
23391
23808
  }
23392
23809
  const idx = calloutBlocks.length;
23393
23810
  calloutBlocks.push(blockHtml);
23394
- return `\n\n\x00CALLOUT_${idx}\x00\n\n`;
23811
+ return `\n\n\x00CLCALLOUT${idx}\x00\n\n`;
23395
23812
  });
23396
23813
 
23397
23814
  // Phase 4: GFM Tables with Column Alignments
@@ -23401,7 +23818,7 @@ declare module 'bun:sqlite' {
23401
23818
  if (rendered === tableText) return match;
23402
23819
  const idx = tableBlocks.length;
23403
23820
  tableBlocks.push(rendered);
23404
- return `\n\n\x00TABLE_${idx}\x00\n\n`;
23821
+ return `\n\n\x00CLTABLE${idx}\x00\n\n`;
23405
23822
  });
23406
23823
 
23407
23824
  // Phase 5: Task Lists & Nested Lists
@@ -23410,7 +23827,7 @@ declare module 'bun:sqlite' {
23410
23827
  text = text.replace(/(?:^[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*(?:\n[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*|\n[ ]{2,}[^\n]*)*)+/gm, (match) => {
23411
23828
  const idx = listBlocks.length;
23412
23829
  listBlocks.push(renderListBlock(match, taskCounter));
23413
- return `\n\n\x00LIST_${idx}\x00\n\n`;
23830
+ return `\n\n\x00CLLIST${idx}\x00\n\n`;
23414
23831
  });
23415
23832
 
23416
23833
  // Phase 6: Headings, Horizontal Rules, Paragraphs & Inline Spans
@@ -23432,18 +23849,18 @@ declare module 'bun:sqlite' {
23432
23849
  const trimmed = p.trim();
23433
23850
  if (!trimmed) return '';
23434
23851
  if (/^<(h[1-6]|hr|pre|div|blockquote|table|ul|ol)/i.test(trimmed)) return trimmed;
23435
- if (/^\x00(CODEBLOCK|CALLOUT|TABLE|LIST)_\d+\x00$/.test(trimmed)) return trimmed;
23852
+ if (/^\x00CL(CODEBLOCK|CALLOUT|TABLE|LIST)\d+\x00$/.test(trimmed)) return trimmed;
23436
23853
  return `<p>${renderInlineFormatting(trimmed).replace(/\n/g, '<br>')}</p>`;
23437
23854
  }).filter(Boolean).join('\n');
23438
23855
 
23439
23856
  // Phase 7: Placeholder Restoration (Reverse order)
23440
23857
  let finalHtml = paras
23441
- .replace(/\x00LIST_(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
23442
- .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
23443
- .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
23444
- .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
23445
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
23446
- .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
23858
+ .replace(/\x00CLLIST(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
23859
+ .replace(/\x00CLTABLE(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
23860
+ .replace(/\x00CLCALLOUT(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
23861
+ .replace(/\x00CLCODEBLOCK(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
23862
+ .replace(/\x00CLINLINECODE(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
23863
+ .replace(/\x00CLAUTOLINK(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
23447
23864
 
23448
23865
  return finalHtml;
23449
23866
  }
@@ -24446,9 +24863,18 @@ int main() {
24446
24863
  if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
24447
24864
  try {
24448
24865
  if (!this._idbStorage) {
24449
- this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
24450
- }
24451
- if (this._idbStorage && typeof this._idbStorage.save === 'function') {
24866
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
24867
+ }
24868
+ if (this._idbStorage && typeof this._idbStorage.saveProject === 'function') {
24869
+ Promise.resolve(this._idbStorage.saveProject({
24870
+ id: this.labId,
24871
+ name: this.title || this.labId,
24872
+ files: { ...(this.files || {}) },
24873
+ updatedAt: Date.now()
24874
+ })).catch((err) => {
24875
+ this.logger.debug('Async WorkspaceStorage saveProject skipped.', err);
24876
+ });
24877
+ } else if (this._idbStorage && typeof this._idbStorage.save === 'function') {
24452
24878
  Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
24453
24879
  this.logger.debug('Async WorkspaceStorage save skipped.', err);
24454
24880
  });
@@ -24775,6 +25201,7 @@ int main() {
24775
25201
  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 => {
24776
25202
  btn.disabled = this.isRunning;
24777
25203
  });
25204
+ this._updatePtyActiveLine();
24778
25205
  }
24779
25206
 
24780
25207
  _hasWebContent() {
@@ -24878,13 +25305,10 @@ int main() {
24878
25305
  if (countSpan) countSpan.textContent = String(problemsCount);
24879
25306
  }
24880
25307
 
24881
- let testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
24882
- if (testTab) {
24883
- testTab.style.display = showTests ? 'inline-flex' : 'none';
24884
- }
24885
25308
 
24886
25309
  let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
24887
25310
  if (!stdinTab) {
25311
+ const testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
24888
25312
  const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
24889
25313
  if (afterTab) {
24890
25314
  afterTab.insertAdjacentHTML('afterend', `
@@ -24896,10 +25320,6 @@ int main() {
24896
25320
  }
24897
25321
  }
24898
25322
 
24899
- let previewTab = drawerTabs.querySelector('[data-cl-drawertab="preview"]');
24900
- if (previewTab) {
24901
- previewTab.style.display = hasWeb ? 'inline-flex' : 'none';
24902
- }
24903
25323
  }
24904
25324
 
24905
25325
  // ── Render Workbench DOM ───────────────────────────────────────────────
@@ -25106,13 +25526,11 @@ int main() {
25106
25526
  <span>Problems</span>
25107
25527
  <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>
25108
25528
  </button>
25109
- ${((this.hasGuidedLab && this.mode === 'guided') || this.testSuiteVisible || this.drawerTab === 'tests') ? `
25110
25529
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'tests'}" class="codelab-drawer__tab ${this.drawerTab === 'tests' ? 'active' : ''}" data-cl-drawertab="tests">
25111
25530
  ${CL_ICONS.check}
25112
25531
  <span>Test Suite</span>
25113
25532
  <span class="codelab-drawer__pill" id="cl-test-pill">Ready</span>
25114
25533
  </button>
25115
- ` : ''}
25116
25534
  <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">
25117
25535
  ${CL_ICONS.keyboard}
25118
25536
  <span>Stdin</span>
@@ -25122,7 +25540,7 @@ int main() {
25122
25540
  <span>Ports</span>
25123
25541
  <span class="codelab-drawer__pill" id="cl-ports-pill">${this.portTable && typeof this.portTable.listServers === 'function' ? this.portTable.listServers().length : 0} open</span>
25124
25542
  </button>
25125
- <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" style="display: ${this._hasWebContent() ? 'inline-flex' : 'none'}">
25543
+ <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">
25126
25544
  ${CL_ICONS.globe}
25127
25545
  <span>Web Preview</span>
25128
25546
  </button>
@@ -25139,6 +25557,8 @@ int main() {
25139
25557
  </div>
25140
25558
  <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
25141
25559
  <div style="display:flex;align-items:center;gap:6px;">
25560
+ <div class="codelab-terminal-sessions" id="cl-terminal-sessions"></div>
25561
+ <button type="button" class="codelab-btn codelab-btn--icon" id="cl-new-terminal-btn" data-cl-action="new-terminal-session" title="New Terminal Session" aria-label="New Terminal Session" style="padding:2px 6px;font-size:11px;">+</button>
25142
25562
  <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>
25143
25563
  <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>
25144
25564
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="toggle-drawer" title="Minimize/Expand Drawer" aria-label="Minimize or Expand Drawer" style="padding:2px 6px;font-size:11px;">${CL_ICONS.chevronsUpDown}</button>
@@ -26227,16 +26647,27 @@ int main() {
26227
26647
  ${problems.map(p => {
26228
26648
  const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
26229
26649
  const cls = p.severity === 'error' ? 'codelab-problem-item--error' : (p.severity === 'warning' ? 'codelab-problem-item--warning' : 'codelab-problem-item--info');
26650
+ const col = p.col || p.column || 1;
26230
26651
  return `
26231
- <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">
26652
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0">
26232
26653
  <span class="codelab-problem-item__icon">${icon}</span>
26233
26654
  <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
26234
- <span class="codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${p.col || 1}</span>
26655
+ <span class="codelab-problem-item__location codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${col}</span>
26235
26656
  </div>
26236
26657
  `;
26237
26658
  }).join('')}
26238
26659
  </div>
26239
26660
  `;
26661
+ if (typeof bodyEl.querySelectorAll === 'function') {
26662
+ bodyEl.querySelectorAll('.codelab-problem-item').forEach((item) => {
26663
+ item.addEventListener('keydown', (e) => {
26664
+ if (e.key === 'Enter' || e.key === ' ') {
26665
+ e.preventDefault();
26666
+ item.click();
26667
+ }
26668
+ });
26669
+ });
26670
+ }
26240
26671
  return;
26241
26672
  }
26242
26673
 
@@ -26308,6 +26739,7 @@ int main() {
26308
26739
  }
26309
26740
 
26310
26741
  if (this.drawerTab === 'terminal') {
26742
+ this._renderTerminalSessionsBar();
26311
26743
  const logsHtml = this.terminalLogs
26312
26744
  .map(item => {
26313
26745
  const html = ansiToHtml ? ansiToHtml(item.text || '') : escapeHtml(item.text || '');
@@ -26316,7 +26748,13 @@ int main() {
26316
26748
  .join('');
26317
26749
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26318
26750
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26319
- bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"><span class="codelab-pty__prompt">${escapeHtml(promptLabel)} </span><span class="codelab-pty__before">${escapeHtml(this._ptyInputBeforeCursor || '')}</span><span class="codelab-pty__cursor blink">&#x2588;</span><span class="codelab-pty__after">${escapeHtml(this._ptyInputAfterCursor || '')}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
26751
+ const busyAttr = this.isRunning ? ' data-busy="true" style="display:none;"' : '';
26752
+ const promptHtml = this.isRunning ? '' : `${escapeHtml(promptLabel)} `;
26753
+ const beforeHtml = this.isRunning ? '' : escapeHtml(this._ptyInputBeforeCursor || '');
26754
+ const afterHtml = this.isRunning ? '' : escapeHtml(this._ptyInputAfterCursor || '');
26755
+ const cursorClass = this.isRunning ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
26756
+ const cursorCharHtml = this.isRunning ? '' : '&#x2588;';
26757
+ bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}><span class="codelab-pty__prompt">${promptHtml}</span><span class="codelab-pty__before">${beforeHtml}</span><span class="${cursorClass}">${cursorCharHtml}</span><span class="codelab-pty__after">${afterHtml}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
26320
26758
  bodyEl.scrollTop = bodyEl.scrollHeight;
26321
26759
  const termSurface = bodyEl.querySelector('#cl-terminal-surface');
26322
26760
  const input = bodyEl.querySelector('#cl-repl-input');
@@ -26328,15 +26766,43 @@ int main() {
26328
26766
  });
26329
26767
  }
26330
26768
  if (input) {
26331
- input.value = (this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || '');
26332
- input.addEventListener('input', () => {
26769
+ input.value = this.isRunning ? '' : ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
26770
+ const syncCaretFromInput = () => {
26771
+ if (this.isRunning) {
26772
+ input.value = '';
26773
+ return;
26774
+ }
26333
26775
  const val = input.value || '';
26334
26776
  const pos = (input.selectionStart !== undefined && input.selectionStart !== null) ? input.selectionStart : val.length;
26335
26777
  this._ptyInputBeforeCursor = val.slice(0, pos);
26336
26778
  this._ptyInputAfterCursor = val.slice(pos);
26337
26779
  this._updatePtyActiveLine();
26780
+ };
26781
+ input.addEventListener('input', syncCaretFromInput);
26782
+ input.addEventListener('click', syncCaretFromInput);
26783
+ input.addEventListener('keyup', e => {
26784
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End') {
26785
+ syncCaretFromInput();
26786
+ }
26338
26787
  });
26339
26788
  input.addEventListener('keydown', e => {
26789
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
26790
+ e.preventDefault();
26791
+ this._handleInterrupt();
26792
+ return;
26793
+ }
26794
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
26795
+ e.preventDefault();
26796
+ this._clearTerminalLogs();
26797
+ this._renderDrawerBody();
26798
+ const nextInput = this.container.querySelector('#cl-repl-input');
26799
+ if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26800
+ return;
26801
+ }
26802
+ if (this.isRunning) {
26803
+ e.preventDefault();
26804
+ return;
26805
+ }
26340
26806
  if (e.key === 'Tab') {
26341
26807
  e.preventDefault();
26342
26808
  this._handlePtyTabCompletion(input);
@@ -26367,9 +26833,6 @@ int main() {
26367
26833
  this._ptyInputAfterCursor = '';
26368
26834
  this._updatePtyActiveLine();
26369
26835
  }
26370
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
26371
- e.preventDefault();
26372
- this._handleInterrupt();
26373
26836
  } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
26374
26837
  e.preventDefault();
26375
26838
  if (this.inRepl) {
@@ -26379,12 +26842,6 @@ int main() {
26379
26842
  const nextInput = this.container.querySelector('#cl-repl-input');
26380
26843
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26381
26844
  }
26382
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
26383
- e.preventDefault();
26384
- this.terminalLogs = [];
26385
- this._renderDrawerBody();
26386
- const nextInput = this.container.querySelector('#cl-repl-input');
26387
- if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26388
26845
  } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {
26389
26846
  e.preventDefault();
26390
26847
  this._ptyInputBeforeCursor = '';
@@ -26415,6 +26872,7 @@ int main() {
26415
26872
  if (replForm) {
26416
26873
  replForm.addEventListener('submit', e => {
26417
26874
  e.preventDefault();
26875
+ if (this.isRunning) return;
26418
26876
  const rawCmd = (input && input.value !== undefined ? input.value : '') ||
26419
26877
  ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
26420
26878
  const cmd = rawCmd.trim();
@@ -26496,7 +26954,7 @@ int main() {
26496
26954
  if (chunk === null || chunk === undefined || chunk === '') return;
26497
26955
  const rawText = String(chunk);
26498
26956
 
26499
- if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
26957
+ if (this.ptyEngine && this.ptyEngine.container && typeof this.ptyEngine.writeStreamChunk === 'function') {
26500
26958
  try {
26501
26959
  this.ptyEngine.writeStreamChunk(rawText, type);
26502
26960
  } catch (err) {
@@ -26537,6 +26995,14 @@ int main() {
26537
26995
  // A newline completes the current line: commit it to the log + DOM, then begin a fresh line.
26538
26996
  const commitActiveLine = () => {
26539
26997
  this.terminalLogs.push({ type: this._activeStreamType || type, text: this._activeStreamLine });
26998
+ if (this.terminalLogs.length > 2000) {
26999
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
27000
+ if (canPatchDom && termLogEl) {
27001
+ while (termLogEl.childElementCount > 2000 && termLogEl.firstElementChild) {
27002
+ termLogEl.removeChild(termLogEl.firstElementChild);
27003
+ }
27004
+ }
27005
+ }
26540
27006
  patchLineInDom(this._activeStreamLine);
26541
27007
  this._activeStreamLine = '';
26542
27008
  this._activeStreamEl = null;
@@ -26704,15 +27170,39 @@ int main() {
26704
27170
 
26705
27171
  _updatePtyActiveLine() {
26706
27172
  if (!this.container) return;
27173
+ const activeLine = this.container.querySelector('#cl-pty-active-line');
26707
27174
  const beforeEl = this.container.querySelector('.codelab-pty__before');
26708
27175
  const afterEl = this.container.querySelector('.codelab-pty__after');
26709
27176
  const promptEl = this.container.querySelector('.codelab-pty__prompt');
27177
+ const cursorEl = this.container.querySelector('.codelab-pty__cursor');
26710
27178
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26711
27179
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26712
27180
 
26713
- if (promptEl) promptEl.textContent = promptLabel + ' ';
26714
- if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
26715
- if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
27181
+ if (this.isRunning) {
27182
+ if (activeLine) {
27183
+ activeLine.setAttribute('data-busy', 'true');
27184
+ if (activeLine.style) activeLine.style.display = 'none';
27185
+ }
27186
+ if (promptEl) promptEl.textContent = '';
27187
+ if (beforeEl) beforeEl.textContent = '';
27188
+ if (cursorEl) {
27189
+ cursorEl.textContent = '';
27190
+ if (cursorEl.classList) cursorEl.classList.remove('blink');
27191
+ }
27192
+ if (afterEl) afterEl.textContent = '';
27193
+ } else {
27194
+ if (activeLine) {
27195
+ activeLine.removeAttribute('data-busy');
27196
+ if (activeLine.style) activeLine.style.display = '';
27197
+ }
27198
+ if (promptEl) promptEl.textContent = promptLabel + ' ';
27199
+ if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
27200
+ if (cursorEl) {
27201
+ if (!cursorEl.textContent) cursorEl.textContent = '\u2588';
27202
+ if (cursorEl.classList) cursorEl.classList.add('blink');
27203
+ }
27204
+ if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
27205
+ }
26716
27206
  }
26717
27207
 
26718
27208
  _handlePtyTabCompletion(input) {
@@ -27693,9 +28183,10 @@ int main() {
27693
28183
  _injectPreviewCsp(html, port) {
27694
28184
  if (typeof html !== 'string' || !html) return html;
27695
28185
 
28186
+ const csp = String(this._previewPolicy() || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
27696
28187
  const tags = [];
27697
28188
  if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
27698
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
28189
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
27699
28190
  }
27700
28191
  if (!/<base\b/i.test(html)) {
27701
28192
  tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
@@ -29261,21 +29752,29 @@ int main() {
29261
29752
  if (splitTrigger) {
29262
29753
  e.stopPropagation();
29263
29754
  const menu = this.container.querySelector('#cl-split-run-menu');
29264
- if (menu) menu.classList.toggle('active');
29755
+ if (menu) {
29756
+ const isOpen = !(menu.classList.contains('active') || menu.classList.contains('open'));
29757
+ menu.classList.toggle('active', isOpen);
29758
+ menu.classList.toggle('open', isOpen);
29759
+ }
29265
29760
  return;
29266
29761
  }
29267
29762
 
29268
29763
  const splitMenu = this.container.querySelector('#cl-split-run-menu');
29269
- if (splitMenu && splitMenu.classList.contains('active') && !e.target.closest('.codelab-btn-split')) {
29764
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open')) && !e.target.closest('.codelab-btn-split')) {
29270
29765
  splitMenu.classList.remove('active');
29766
+ splitMenu.classList.remove('open');
29271
29767
  }
29272
29768
 
29273
- const problemItem = e.target.closest('[data-cl-problem-file]');
29769
+ const problemItem = e.target.closest('[data-cl-problem-file], [data-problem-file]');
29274
29770
  if (problemItem) {
29275
29771
  e.stopPropagation();
29276
- const pFile = problemItem.dataset.clProblemFile;
29277
- const pLine = Number(problemItem.dataset.clProblemLine || 1);
29278
- const pCol = Number(problemItem.dataset.clProblemCol || 1);
29772
+ const pFile = problemItem.dataset.clProblemFile || problemItem.dataset.problemFile;
29773
+ const pLine = Number(problemItem.dataset.clProblemLine || problemItem.dataset.problemLine || 1);
29774
+ const pCol = Number(problemItem.dataset.clProblemCol || problemItem.dataset.problemCol || 1);
29775
+ if (problemItem.closest('#cl-modal-slot')) {
29776
+ this.closeModal();
29777
+ }
29279
29778
  if (pFile) {
29280
29779
  this.openFile(pFile);
29281
29780
  if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
@@ -29287,6 +29786,24 @@ int main() {
29287
29786
  return;
29288
29787
  }
29289
29788
 
29789
+ const searchMatch = e.target.closest('[data-cl-search-file]');
29790
+ if (searchMatch) {
29791
+ e.stopPropagation();
29792
+ const sFile = searchMatch.dataset.clSearchFile;
29793
+ const sLine = Number(searchMatch.dataset.clSearchLine || 1);
29794
+ const sCol = Number(searchMatch.dataset.clSearchCol || 1);
29795
+ this.closeModal();
29796
+ if (sFile) {
29797
+ this.openFile(sFile);
29798
+ if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
29799
+ this.editor.revealLineInCenter(sLine);
29800
+ this.editor.setPosition({ lineNumber: sLine, column: sCol });
29801
+ this.editor.focus();
29802
+ }
29803
+ }
29804
+ return;
29805
+ }
29806
+
29290
29807
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
29291
29808
  if (drawerTabBtn) {
29292
29809
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -29295,8 +29812,9 @@ int main() {
29295
29812
 
29296
29813
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
29297
29814
  if (actionBtn) {
29298
- if (splitMenu && splitMenu.classList.contains('active')) {
29815
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open'))) {
29299
29816
  splitMenu.classList.remove('active');
29817
+ splitMenu.classList.remove('open');
29300
29818
  }
29301
29819
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
29302
29820
  if (action === 'run-code') this.runCode();
@@ -29399,9 +29917,49 @@ int main() {
29399
29917
  if (drawer) drawer.classList.toggle('is-minimized');
29400
29918
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
29401
29919
  } else if (action === 'clear-terminal') {
29402
- this.terminalLogs = [];
29920
+ this._clearTerminalLogs();
29403
29921
  this.lastTestResults = [];
29404
29922
  this._renderDrawerBody();
29923
+ } else if (action === 'new-terminal-session') {
29924
+ this.createTerminalSession();
29925
+ if (this.drawerTab !== 'terminal') this.switchDrawerTab('terminal');
29926
+ } else if (action === 'switch-terminal-session') {
29927
+ const sid = actionBtn.dataset.sessionId;
29928
+ if (sid) this.switchTerminalSession(sid);
29929
+ } else if (action === 'close-terminal-session') {
29930
+ e.stopPropagation();
29931
+ const sid = actionBtn.dataset.sessionId;
29932
+ if (sid) this.closeTerminalSession(sid);
29933
+ } else if (action === 'scm-stage-file') {
29934
+ e.stopPropagation();
29935
+ const p = actionBtn.dataset.scmPath;
29936
+ if (p) {
29937
+ this.stageGitFile(p);
29938
+ this.showScmModal();
29939
+ }
29940
+ } else if (action === 'scm-unstage-file') {
29941
+ e.stopPropagation();
29942
+ const p = actionBtn.dataset.scmPath;
29943
+ if (p) {
29944
+ this.unstageGitFile(p);
29945
+ this.showScmModal();
29946
+ }
29947
+ } else if (action === 'scm-stage-all') {
29948
+ this.stageAllGitFiles();
29949
+ this.showScmModal();
29950
+ } else if (action === 'scm-commit') {
29951
+ const msgInput = this.container.querySelector('#cl-scm-commit-input');
29952
+ const msg = msgInput ? msgInput.value.trim() : '';
29953
+ if (msg) {
29954
+ this.commitGitChanges(msg);
29955
+ this.showScmModal();
29956
+ }
29957
+ } else if (action === 'scm-open-file') {
29958
+ const p = actionBtn.dataset.scmPath;
29959
+ this.closeModal();
29960
+ if (p && Object.prototype.hasOwnProperty.call(this.files, p)) {
29961
+ this.openFile(p);
29962
+ }
29405
29963
  } else if (action === 'toggle-hint') {
29406
29964
  const box = this.container.querySelector('#cl-hint-box');
29407
29965
  if (box) box.classList.toggle('open');
@@ -30822,7 +31380,7 @@ int main() {
30822
31380
  } else {
30823
31381
  window.location.hash = `codelab=${token}`;
30824
31382
  }
30825
- if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
31383
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
30826
31384
  await navigator.clipboard.writeText(newUrl);
30827
31385
  this._showToast('Snapshot link copied to clipboard! (#codelab=...)', 'success');
30828
31386
  } else {
@@ -31045,6 +31603,7 @@ int main() {
31045
31603
  }
31046
31604
 
31047
31605
  async _handleReplCommand(cmd) {
31606
+ if (this.isRunning) return;
31048
31607
  const trimmed = (cmd || '').trim();
31049
31608
  if (!trimmed) return;
31050
31609
  if (this.replHistory[this.replHistory.length - 1] !== trimmed) {
@@ -31053,7 +31612,19 @@ int main() {
31053
31612
  this.replHistoryIdx = -1;
31054
31613
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
31055
31614
  const promptPrefix = this.inRepl ? '> ' : `codelab:${cwdShort}$ `;
31056
- this.terminalLogs.push({ type: 'system', text: `${promptPrefix}${trimmed}` });
31615
+ const echoLine = `${promptPrefix}${trimmed}`;
31616
+ this.terminalLogs.push({ type: 'system', text: echoLine });
31617
+ if (this.terminalLogs.length > 2000) {
31618
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
31619
+ }
31620
+ const termLogEl = this.container ? this.container.querySelector('#cl-terminal-log') : null;
31621
+ const ptyOwnsDom = Boolean(this.ptyEngine && this.ptyEngine.container);
31622
+ if (termLogEl && typeof document !== 'undefined' && !ptyOwnsDom) {
31623
+ const echoEl = document.createElement('div');
31624
+ echoEl.className = 'codelab-log-line system';
31625
+ echoEl.innerHTML = ansiToHtml ? ansiToHtml(echoLine) : escapeHtml(echoLine);
31626
+ termLogEl.appendChild(echoEl);
31627
+ }
31057
31628
 
31058
31629
  if (this.inRepl) {
31059
31630
  if (trimmed === '.exit' || trimmed === 'exit') {
@@ -31063,7 +31634,7 @@ int main() {
31063
31634
  return;
31064
31635
  }
31065
31636
  if (trimmed === '.clear' || trimmed === 'clear') {
31066
- this.terminalLogs = [];
31637
+ this._clearTerminalLogs();
31067
31638
  this._renderDrawerBody();
31068
31639
  return;
31069
31640
  }
@@ -31116,7 +31687,7 @@ int main() {
31116
31687
  }
31117
31688
 
31118
31689
  if (trimmed === 'clear' || trimmed === 'cls') {
31119
- this.terminalLogs = [];
31690
+ this._clearTerminalLogs();
31120
31691
  this._renderDrawerBody();
31121
31692
  return;
31122
31693
  }
@@ -31176,7 +31747,7 @@ int main() {
31176
31747
  this._syncVfsSnapshot(null, true);
31177
31748
 
31178
31749
  if (shellRes && shellRes.clear) {
31179
- this.terminalLogs = [];
31750
+ this._clearTerminalLogs();
31180
31751
  this._renderDrawerBody();
31181
31752
  return;
31182
31753
  }
@@ -31389,6 +31960,10 @@ int main() {
31389
31960
  return bytes;
31390
31961
  }
31391
31962
 
31963
+ exportZip(options = {}) {
31964
+ return this.exportProjectZip(options);
31965
+ }
31966
+
31392
31967
  importProjectZip(zipBytes) {
31393
31968
  const zipMod = root.CodeLabZip;
31394
31969
  if (!zipMod || typeof zipMod.extractZip !== 'function') {
@@ -31401,6 +31976,42 @@ int main() {
31401
31976
  return true;
31402
31977
  }
31403
31978
 
31979
+ importZip(zipBytes) {
31980
+ return this.importProjectZip(zipBytes);
31981
+ }
31982
+
31983
+ async saveProjectToStorage(id) {
31984
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
31985
+ return false;
31986
+ }
31987
+ if (!this._idbStorage) {
31988
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
31989
+ }
31990
+ const projectId = id || this.labId || 'workspace';
31991
+ return this._idbStorage.saveProject({
31992
+ id: projectId,
31993
+ name: this.title || projectId,
31994
+ files: { ...(this.files || {}) },
31995
+ updatedAt: Date.now()
31996
+ });
31997
+ }
31998
+
31999
+ async loadProjectFromStorage(id) {
32000
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
32001
+ return null;
32002
+ }
32003
+ if (!this._idbStorage) {
32004
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
32005
+ }
32006
+ const projectId = id || this.labId || 'workspace';
32007
+ const loaded = await this._idbStorage.loadProject(projectId);
32008
+ if (loaded && loaded.files && typeof loaded.files === 'object') {
32009
+ this.setFiles(loaded.files);
32010
+ this._syncFilesToShellVfs();
32011
+ }
32012
+ return loaded;
32013
+ }
32014
+
31404
32015
  searchWorkspace(options) {
31405
32016
  const searchMod = root.CodeLabSearch;
31406
32017
  if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
@@ -31414,21 +32025,113 @@ int main() {
31414
32025
  if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
31415
32026
  throw new Error('CodeLabSearch engine is not loaded');
31416
32027
  }
31417
- const res = searchMod.replaceInFiles(this.files || {}, options);
31418
- if (res && res.files && res.filesModified > 0) {
31419
- this.setFiles(res.files);
32028
+ const res = searchMod.replaceInFiles(this.files || {}, options, options && options.replacement);
32029
+ const nextFiles = res && (res.updatedFiles || res.files);
32030
+ const modifiedCount = res && (typeof res.filesModified === 'number' ? res.filesModified : (Array.isArray(res.filesAffected) ? res.filesAffected.length : 0));
32031
+ if (nextFiles && modifiedCount > 0) {
32032
+ this.setFiles(nextFiles);
31420
32033
  this._syncFilesToShellVfs();
31421
32034
  }
31422
32035
  return res;
31423
32036
  }
31424
32037
 
32038
+ _getGitState() {
32039
+ const scmMod = root.CodeLabScm;
32040
+ if (this.shell && this.shell.gitState) {
32041
+ return this.shell.gitState;
32042
+ }
32043
+ if (!this._gitState && scmMod && typeof scmMod.createGitState === 'function') {
32044
+ this._gitState = scmMod.createGitState(this.files || {});
32045
+ }
32046
+ return this._gitState || null;
32047
+ }
32048
+
31425
32049
  getGitStatus() {
31426
32050
  const scmMod = root.CodeLabScm;
31427
32051
  if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
31428
32052
  return [];
31429
32053
  }
31430
- const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
31431
- return scmMod.computeGitStatus(gs, this.files || {});
32054
+ const gs = this._getGitState() || scmMod.createGitState(this.files || {});
32055
+ const res = scmMod.computeGitStatus(this.files || {}, '/workspace', gs);
32056
+ return res && Array.isArray(res.entries) ? res.entries : (Array.isArray(res) ? res : []);
32057
+ }
32058
+
32059
+ stageGitFile(relPath) {
32060
+ if (!relPath) return false;
32061
+ const gs = this._getGitState();
32062
+ if (!gs) return false;
32063
+ const scmMod = root.CodeLabScm;
32064
+ if (gs.staged instanceof Set) {
32065
+ gs.staged.add(relPath);
32066
+ } else if (scmMod && typeof scmMod.stageFile === 'function') {
32067
+ const currentContent = Object.prototype.hasOwnProperty.call(this.files, relPath) ? this.files[relPath] : null;
32068
+ scmMod.stageFile(gs, relPath, currentContent);
32069
+ }
32070
+ return true;
32071
+ }
32072
+
32073
+ unstageGitFile(relPath) {
32074
+ if (!relPath) return false;
32075
+ const gs = this._getGitState();
32076
+ if (!gs || !gs.staged || typeof gs.staged.delete !== 'function') return false;
32077
+ gs.staged.delete(relPath);
32078
+ return true;
32079
+ }
32080
+
32081
+ stageAllGitFiles() {
32082
+ const entries = this.getGitStatus();
32083
+ for (const entry of entries) {
32084
+ if (!entry.staged) {
32085
+ this.stageGitFile(entry.path);
32086
+ }
32087
+ }
32088
+ return true;
32089
+ }
32090
+
32091
+ commitGitChanges(message) {
32092
+ const msg = typeof message === 'string' ? message.trim() : '';
32093
+ if (!msg) return null;
32094
+ const gs = this._getGitState();
32095
+ if (!gs) return null;
32096
+ const scmMod = root.CodeLabScm;
32097
+ if (gs.staged instanceof Set) {
32098
+ if (gs.staged.size === 0) return null;
32099
+ if (!gs.headSnapshot) gs.headSnapshot = {};
32100
+ for (const relPath of gs.staged) {
32101
+ if (Object.prototype.hasOwnProperty.call(this.files, relPath)) {
32102
+ gs.headSnapshot[relPath] = this.files[relPath];
32103
+ } else {
32104
+ delete gs.headSnapshot[relPath];
32105
+ }
32106
+ }
32107
+ gs.headFiles = Object.assign({}, gs.headSnapshot);
32108
+ const hash = scmMod && typeof scmMod.computeShortCommitHash === 'function'
32109
+ ? scmMod.computeShortCommitHash(`${gs.branch || 'main'}:${msg}:${Date.now()}`)
32110
+ : Math.random().toString(16).slice(2, 9);
32111
+ if (!Array.isArray(gs.commits)) gs.commits = [];
32112
+ gs.commits.unshift({
32113
+ hash,
32114
+ author: 'CodeLab Developer <dev@codelab.internal>',
32115
+ date: new Date().toUTCString(),
32116
+ timestamp: Date.now(),
32117
+ message: msg
32118
+ });
32119
+ gs.headCommit = hash;
32120
+ gs.staged.clear();
32121
+ this._syncFilesToShellVfs();
32122
+ return hash;
32123
+ }
32124
+ if (scmMod && typeof scmMod.commitChanges === 'function') {
32125
+ try {
32126
+ const hash = scmMod.commitChanges(gs, msg);
32127
+ if (gs.headFiles) gs.headSnapshot = Object.assign({}, gs.headFiles);
32128
+ this._syncFilesToShellVfs();
32129
+ return hash;
32130
+ } catch (_err) {
32131
+ return null;
32132
+ }
32133
+ }
32134
+ return null;
31432
32135
  }
31433
32136
 
31434
32137
  getDiagnostics() {
@@ -31446,12 +32149,20 @@ int main() {
31446
32149
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31447
32150
  if (!slot) return;
31448
32151
  const q = String(initialQuery || '');
31449
- const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
31450
- const rowsHtml = (results.matches || []).map((m) => `
31451
- <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
31452
- <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
31453
- </div>
31454
- `).join('');
32152
+ const renderRows = (queryText) => {
32153
+ const res = queryText ? this.searchWorkspace({ query: queryText }) : { matches: [], totalMatches: 0, filesMatched: 0 };
32154
+ if (!queryText) {
32155
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>';
32156
+ }
32157
+ if (!res.matches || res.matches.length === 0) {
32158
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">No matches found in workspace.</div>';
32159
+ }
32160
+ return res.matches.map((m) => `
32161
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" data-cl-search-file="${escapeHtml(m.file)}" data-cl-search-line="${m.line || 1}" data-cl-search-col="${m.column || 1}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
32162
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
32163
+ </div>
32164
+ `).join('');
32165
+ };
31455
32166
  slot.innerHTML = `
31456
32167
  <div class="codelab-modal-backdrop">
31457
32168
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
@@ -31460,36 +32171,82 @@ int main() {
31460
32171
  <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
31461
32172
  </div>
31462
32173
  <div class="codelab-modal__body">
31463
- <div style="display:flex;gap:8px;margin-bottom:8px;">
31464
- <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
31465
- <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
32174
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
32175
+ <input id="cl-search-query-input" class="codelab-modal-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." />
32176
+ <input id="cl-search-replace-input" class="codelab-modal-input" type="text" placeholder="Replace with..." />
32177
+ <button type="button" id="cl-search-replace-all-btn" class="codelab-btn codelab-btn--primary" style="padding:5px 10px;font-size:12px;white-space:nowrap;">Replace All</button>
31466
32178
  </div>
31467
- <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
32179
+ <div id="cl-search-results-list" style="max-height:320px;overflow-y:auto;">${renderRows(q)}</div>
31468
32180
  </div>
31469
32181
  </div>
31470
32182
  </div>
31471
32183
  `;
32184
+ const queryInput = slot.querySelector('#cl-search-query-input');
32185
+ const replaceInput = slot.querySelector('#cl-search-replace-input');
32186
+ const replaceBtn = slot.querySelector('#cl-search-replace-all-btn');
32187
+ const listEl = slot.querySelector('#cl-search-results-list');
32188
+ if (queryInput && listEl) {
32189
+ queryInput.addEventListener('input', () => {
32190
+ listEl.innerHTML = renderRows(queryInput.value || '');
32191
+ });
32192
+ if (typeof queryInput.focus === 'function') queryInput.focus();
32193
+ }
32194
+ if (replaceBtn && queryInput && replaceInput && listEl) {
32195
+ const triggerReplace = () => {
32196
+ const queryVal = queryInput.value || '';
32197
+ if (!queryVal) return;
32198
+ this.replaceInWorkspace({ query: queryVal, replacement: replaceInput.value || '' });
32199
+ listEl.innerHTML = renderRows(queryVal);
32200
+ };
32201
+ replaceBtn.addEventListener('click', triggerReplace);
32202
+ replaceInput.addEventListener('keydown', (e) => {
32203
+ if (e.key === 'Enter') {
32204
+ e.preventDefault();
32205
+ triggerReplace();
32206
+ }
32207
+ });
32208
+ }
31472
32209
  }
31473
32210
 
31474
32211
  showScmModal() {
31475
32212
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31476
32213
  if (!slot) return;
31477
32214
  const statusList = this.getGitStatus();
31478
- const rowsHtml = statusList.map((entry) => `
31479
- <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
31480
- <span>${escapeHtml(entry.path)}</span>
31481
- <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
31482
- </div>
31483
- `).join('');
32215
+ const gs = this._getGitState();
32216
+ const branch = (gs && gs.branch) ? gs.branch : 'main';
32217
+ const hasStaged = statusList.some((e) => e.staged);
32218
+ const hasUnstaged = statusList.some((e) => !e.staged);
32219
+ const rowsHtml = statusList.map((entry) => {
32220
+ const badge = entry.staged ? `Staged (${entry.index})` : (entry.worktree !== ' ' ? entry.worktree : entry.index);
32221
+ const actionBtn = entry.staged
32222
+ ? `<button type="button" class="codelab-btn" data-cl-action="scm-unstage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Unstage</button>`
32223
+ : `<button type="button" class="codelab-btn" data-cl-action="scm-stage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Stage</button>`;
32224
+ return `
32225
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;align-items:center;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
32226
+ <span data-cl-action="scm-open-file" data-scm-path="${escapeHtml(entry.path)}" style="cursor:pointer;text-decoration:underline;">${escapeHtml(entry.path)}</span>
32227
+ <span style="display:inline-flex;align-items:center;gap:8px;">
32228
+ <span>${escapeHtml(badge)}</span>
32229
+ ${actionBtn}
32230
+ </span>
32231
+ </div>
32232
+ `;
32233
+ }).join('');
31484
32234
  slot.innerHTML = `
31485
32235
  <div class="codelab-modal-backdrop">
31486
32236
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
31487
32237
  <div class="codelab-modal__header">
31488
- <span>Source Control (Git Status)</span>
31489
- <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
32238
+ <span>Source Control (Git Status · ${escapeHtml(branch)})</span>
32239
+ <div style="display:flex;gap:6px;align-items:center;">
32240
+ ${hasUnstaged ? `<button type="button" class="codelab-btn" data-cl-action="scm-stage-all" style="padding:3px 8px;font-size:11px;">Stage All</button>` : ''}
32241
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
32242
+ </div>
31490
32243
  </div>
31491
32244
  <div class="codelab-modal__body">
31492
- <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
32245
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
32246
+ <input id="cl-scm-commit-input" class="codelab-modal-input" type="text" placeholder="Commit message (e.g. feat: update module)..." />
32247
+ <button type="button" id="cl-scm-commit-btn" class="codelab-btn codelab-btn--primary" data-cl-action="scm-commit" ${hasStaged ? '' : 'disabled'} style="padding:5px 10px;font-size:12px;white-space:nowrap;">Commit</button>
32248
+ </div>
32249
+ <div id="cl-scm-status-list" style="max-height:300px;overflow-y:auto;">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
31493
32250
  </div>
31494
32251
  </div>
31495
32252
  </div>
@@ -31501,11 +32258,14 @@ int main() {
31501
32258
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31502
32259
  if (!slot) return;
31503
32260
  const items = this.getDiagnostics();
31504
- const rowsHtml = items.map((d) => `
31505
- <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
31506
- <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
31507
- </div>
31508
- `).join('');
32261
+ const rowsHtml = items.map((d) => {
32262
+ const col = d.col || d.column || 1;
32263
+ return `
32264
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-line="${d.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
32265
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file || '')}:${d.line || 1}:${col}</strong> — ${escapeHtml(d.message || '')}
32266
+ </div>
32267
+ `;
32268
+ }).join('');
31509
32269
  slot.innerHTML = `
31510
32270
  <div class="codelab-modal-backdrop">
31511
32271
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
@@ -31521,6 +32281,40 @@ int main() {
31521
32281
  `;
31522
32282
  }
31523
32283
 
32284
+ _clearTerminalLogs() {
32285
+ if (Array.isArray(this.terminalLogs)) {
32286
+ this.terminalLogs.length = 0;
32287
+ } else {
32288
+ this.terminalLogs = [];
32289
+ }
32290
+ if (Array.isArray(this._terminalSessions)) {
32291
+ const active = this._terminalSessions.find((s) => s.id === this._activeTerminalSessionId);
32292
+ if (active) {
32293
+ active.logs = this.terminalLogs;
32294
+ }
32295
+ }
32296
+ }
32297
+
32298
+ _renderTerminalSessionsBar() {
32299
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
32300
+ const bar = this.container.querySelector('#cl-terminal-sessions');
32301
+ if (!bar) return;
32302
+ const sessions = this._ensureTerminalSessions();
32303
+ if (sessions.length <= 1) {
32304
+ bar.innerHTML = '';
32305
+ return;
32306
+ }
32307
+ bar.innerHTML = sessions.map((s) => {
32308
+ const isActive = s.id === this._activeTerminalSessionId;
32309
+ return `
32310
+ <span class="codelab-session-pill ${isActive ? 'active' : ''}" data-cl-action="switch-terminal-session" data-session-id="${escapeHtml(s.id)}" role="button" tabindex="0" title="Switch to ${escapeHtml(s.name)}">
32311
+ <span>${escapeHtml(s.name)}</span>
32312
+ <span data-cl-action="close-terminal-session" data-session-id="${escapeHtml(s.id)}" title="Close session" style="margin-left:2px;opacity:0.75;">&times;</span>
32313
+ </span>
32314
+ `;
32315
+ }).join('');
32316
+ }
32317
+
31524
32318
  _ensureTerminalSessions() {
31525
32319
  if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
31526
32320
  this._terminalSessions = [
@@ -31933,6 +32727,13 @@ int main() {
31933
32727
  this._editorResizeObserver.disconnect();
31934
32728
  this._editorResizeObserver = null;
31935
32729
  }
32730
+ if (this._diffManager && typeof this._diffManager.closeInlineDiff === 'function') {
32731
+ try {
32732
+ this._diffManager.closeInlineDiff();
32733
+ } catch (err) {
32734
+ this.logger.debug('diffManager.closeInlineDiff failed during destroy.', err);
32735
+ }
32736
+ }
31936
32737
  if (this.editor) {
31937
32738
  this.editor.dispose();
31938
32739
  this.editor = null;
@@ -36283,7 +37084,7 @@ var CodeLabGuidedLab = (() => {
36283
37084
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
36284
37085
  });
36285
37086
  var CppToolchainProgressSchema = external_exports.object({
36286
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
37087
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
36287
37088
  loadedBytes: external_exports.number().optional(),
36288
37089
  totalBytes: external_exports.number().optional(),
36289
37090
  percent: external_exports.number().optional(),
@@ -36718,6 +37519,7 @@ var CodeLabCpp = (() => {
36718
37519
  STANDARD_CPP20_HEADERS: () => STANDARD_CPP20_HEADERS,
36719
37520
  analyzeCppSource: () => analyzeCppSource,
36720
37521
  applyClangStderrDiagnostics: () => applyClangStderrDiagnostics,
37522
+ buildWasiPrintWasm: () => buildWasiPrintWasm,
36721
37523
  cppExtension: () => cppExtension,
36722
37524
  createCppExtension: () => createCppExtension,
36723
37525
  createTarArchive: () => createTarArchive,
@@ -40818,7 +41620,7 @@ var CodeLabCpp = (() => {
40818
41620
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
40819
41621
  });
40820
41622
  var CppToolchainProgressSchema = external_exports.object({
40821
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
41623
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
40822
41624
  loadedBytes: external_exports.number().optional(),
40823
41625
  totalBytes: external_exports.number().optional(),
40824
41626
  percent: external_exports.number().optional(),
@@ -41375,12 +42177,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41375
42177
  const db = await openToolchainIdb();
41376
42178
  if (!db) return null;
41377
42179
  return new Promise((resolve) => {
42180
+ const closeDb = () => {
42181
+ try {
42182
+ db.close();
42183
+ } catch (err) {
42184
+ }
42185
+ };
41378
42186
  try {
41379
42187
  const tx = db.transaction(IDB_STORE, "readonly");
41380
42188
  const store = tx.objectStore(IDB_STORE);
41381
42189
  const req = store.get(key);
41382
42190
  req.onsuccess = () => {
41383
42191
  const val = req.result;
42192
+ closeDb();
41384
42193
  if (val instanceof Uint8Array) {
41385
42194
  memoryAssetCache.set(key, val);
41386
42195
  resolve(val);
@@ -41392,8 +42201,12 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41392
42201
  resolve(null);
41393
42202
  }
41394
42203
  };
41395
- req.onerror = () => resolve(null);
42204
+ req.onerror = () => {
42205
+ closeDb();
42206
+ resolve(null);
42207
+ };
41396
42208
  } catch (err) {
42209
+ closeDb();
41397
42210
  if (err) resolve(null);
41398
42211
  }
41399
42212
  });
@@ -41403,13 +42216,26 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41403
42216
  const db = await openToolchainIdb();
41404
42217
  if (!db) return;
41405
42218
  return new Promise((resolve) => {
42219
+ const closeDb = () => {
42220
+ try {
42221
+ db.close();
42222
+ } catch (err) {
42223
+ }
42224
+ };
41406
42225
  try {
41407
42226
  const tx = db.transaction(IDB_STORE, "readwrite");
41408
42227
  const store = tx.objectStore(IDB_STORE);
41409
42228
  store.put(data, key);
41410
- tx.oncomplete = () => resolve();
41411
- tx.onerror = () => resolve();
42229
+ tx.oncomplete = () => {
42230
+ closeDb();
42231
+ resolve();
42232
+ };
42233
+ tx.onerror = () => {
42234
+ closeDb();
42235
+ resolve();
42236
+ };
41412
42237
  } catch (err) {
42238
+ closeDb();
41413
42239
  if (err) resolve();
41414
42240
  }
41415
42241
  });
@@ -41431,15 +42257,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41431
42257
  continue;
41432
42258
  }
41433
42259
  const sizeOctal = readString(offset + 124, 12);
41434
- const size = parseInt(sizeOctal || "0", 8) || 0;
42260
+ const size = Math.max(0, parseInt(sizeOctal || "0", 8) || 0);
41435
42261
  const typeFlag = tarBytes[offset + 156];
41436
42262
  const prefix = readString(offset + 345, 155);
41437
42263
  const fullName = prefix ? `${prefix}/${name}` : name;
41438
- const cleanRel = fullName.replace(/^\.?\/+/, "");
41439
- const targetPath = baseDir === "/" ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, "")}/${cleanRel}`;
42264
+ const rawRel = fullName.replace(/^\.?\/+/, "");
42265
+ const rawSegments = rawRel.split("/").filter(Boolean);
42266
+ const hasDotDot = rawSegments.some((seg) => seg === "..");
42267
+ const cleanRel = hasDotDot ? "" : rawSegments.filter((seg) => seg !== ".").join("/");
42268
+ const cleanBase = baseDir === "/" ? "" : baseDir.replace(/\/+$/, "");
42269
+ const targetPath = `${cleanBase}/${cleanRel}`;
41440
42270
  const dataStart = offset + 512;
41441
- const dataEnd = dataStart + size;
41442
- if (cleanRel) {
42271
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
42272
+ if (cleanRel && !hasDotDot) {
41443
42273
  if (typeFlag === 53 || fullName.endsWith("/")) {
41444
42274
  if (!vfs.existsSync(targetPath)) {
41445
42275
  vfs.mkdirSync(targetPath, { recursive: true });
@@ -41522,11 +42352,185 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41522
42352
  }
41523
42353
  }
41524
42354
  var DEFAULT_CPP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm/@yowasp/clang";
42355
+ function _uleb128(val) {
42356
+ const out = [];
42357
+ let v = val >>> 0;
42358
+ do {
42359
+ let byte = v & 127;
42360
+ v >>>= 7;
42361
+ if (v !== 0) byte |= 128;
42362
+ out.push(byte);
42363
+ } while (v !== 0);
42364
+ return out;
42365
+ }
42366
+ function _sleb128(val) {
42367
+ const out = [];
42368
+ let v = val | 0;
42369
+ let more = true;
42370
+ while (more) {
42371
+ let byte = v & 127;
42372
+ v >>= 7;
42373
+ if (v === 0 && (byte & 64) === 0 || v === -1 && (byte & 64) !== 0) {
42374
+ more = false;
42375
+ } else {
42376
+ byte |= 128;
42377
+ }
42378
+ out.push(byte);
42379
+ }
42380
+ return out;
42381
+ }
42382
+ function _encodeStr(str) {
42383
+ const bytes = Array.from(new TextEncoder().encode(str));
42384
+ return [..._uleb128(bytes.length), ...bytes];
42385
+ }
42386
+ function _wasmSection(id, payload) {
42387
+ return [id, ..._uleb128(payload.length), ...payload];
42388
+ }
42389
+ function buildWasiPrintWasm(stdoutText, exitCode = 0, stderrText = "") {
42390
+ const outBytes = Array.from(new TextEncoder().encode(stdoutText));
42391
+ const errBytes = Array.from(new TextEncoder().encode(stderrText));
42392
+ const typeSection = _wasmSection(1, [
42393
+ 3,
42394
+ 96,
42395
+ 4,
42396
+ 127,
42397
+ 127,
42398
+ 127,
42399
+ 127,
42400
+ 1,
42401
+ 127,
42402
+ 96,
42403
+ 1,
42404
+ 127,
42405
+ 0,
42406
+ 96,
42407
+ 0,
42408
+ 0
42409
+ ]);
42410
+ const importSection = _wasmSection(2, [
42411
+ 2,
42412
+ ..._encodeStr("wasi_snapshot_preview1"),
42413
+ ..._encodeStr("fd_write"),
42414
+ 0,
42415
+ 0,
42416
+ ..._encodeStr("wasi_snapshot_preview1"),
42417
+ ..._encodeStr("proc_exit"),
42418
+ 0,
42419
+ 1
42420
+ ]);
42421
+ const funcSection = _wasmSection(3, [1, 2]);
42422
+ const memSection = _wasmSection(5, [1, 0, 1]);
42423
+ const exportSection = _wasmSection(7, [
42424
+ 2,
42425
+ ..._encodeStr("memory"),
42426
+ 2,
42427
+ 0,
42428
+ ..._encodeStr("_start"),
42429
+ 0,
42430
+ 2
42431
+ ]);
42432
+ const body = [
42433
+ 0,
42434
+ 65,
42435
+ ..._sleb128(0),
42436
+ 65,
42437
+ ..._sleb128(64),
42438
+ 54,
42439
+ 2,
42440
+ 0,
42441
+ 65,
42442
+ ..._sleb128(4),
42443
+ 65,
42444
+ ..._sleb128(outBytes.length),
42445
+ 54,
42446
+ 2,
42447
+ 0,
42448
+ 65,
42449
+ ..._sleb128(1),
42450
+ 65,
42451
+ ..._sleb128(0),
42452
+ 65,
42453
+ ..._sleb128(1),
42454
+ 65,
42455
+ ..._sleb128(16),
42456
+ 16,
42457
+ 0,
42458
+ 26
42459
+ ];
42460
+ if (errBytes.length > 0) {
42461
+ body.push(
42462
+ 65,
42463
+ ..._sleb128(8),
42464
+ 65,
42465
+ ..._sleb128(64 + outBytes.length),
42466
+ 54,
42467
+ 2,
42468
+ 0,
42469
+ 65,
42470
+ ..._sleb128(12),
42471
+ 65,
42472
+ ..._sleb128(errBytes.length),
42473
+ 54,
42474
+ 2,
42475
+ 0,
42476
+ 65,
42477
+ ..._sleb128(2),
42478
+ 65,
42479
+ ..._sleb128(8),
42480
+ 65,
42481
+ ..._sleb128(1),
42482
+ 65,
42483
+ ..._sleb128(16),
42484
+ 16,
42485
+ 0,
42486
+ 26
42487
+ );
42488
+ }
42489
+ if (exitCode !== 0) {
42490
+ body.push(
42491
+ 65,
42492
+ ..._sleb128(exitCode),
42493
+ 16,
42494
+ 1
42495
+ );
42496
+ }
42497
+ body.push(11);
42498
+ const codeSection = _wasmSection(10, [1, ..._uleb128(body.length), ...body]);
42499
+ const combinedData = [...outBytes, ...errBytes];
42500
+ const dataSection = _wasmSection(11, [
42501
+ 1,
42502
+ 0,
42503
+ 65,
42504
+ ..._sleb128(64),
42505
+ 11,
42506
+ ..._uleb128(combinedData.length),
42507
+ ...combinedData
42508
+ ]);
42509
+ return new Uint8Array([
42510
+ 0,
42511
+ 97,
42512
+ 115,
42513
+ 109,
42514
+ 1,
42515
+ 0,
42516
+ 0,
42517
+ 0,
42518
+ ...typeSection,
42519
+ ...importSection,
42520
+ ...funcSection,
42521
+ ...memSection,
42522
+ ...exportSection,
42523
+ ...codeSection,
42524
+ ...dataSection
42525
+ ]);
42526
+ }
41525
42527
  var CppToolchainManager = class {
41526
42528
  options;
41527
42529
  clangWasm = null;
41528
42530
  lldWasm = null;
41529
42531
  sysrootTar = null;
42532
+ nativeToolchainUnavailable = false;
42533
+ loadError = null;
41530
42534
  _loadingPromise = null;
41531
42535
  constructor(options = {}) {
41532
42536
  const parsed = CppExtensionOptionsSchema.parse(options);
@@ -41639,6 +42643,16 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41639
42643
  percent: 100,
41640
42644
  message: "C++20 WebAssembly Toolchain Ready"
41641
42645
  });
42646
+ } catch (err) {
42647
+ this.nativeToolchainUnavailable = true;
42648
+ this.loadError = err;
42649
+ this._emitProgress({
42650
+ stage: "error",
42651
+ loadedBytes: 0,
42652
+ totalBytes: 0,
42653
+ percent: 0,
42654
+ message: `Remote C++20 WASI assets unavailable (${err.message}). Using virtual C++ executor.`
42655
+ });
41642
42656
  } finally {
41643
42657
  this._loadingPromise = null;
41644
42658
  }
@@ -41682,6 +42696,9 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41682
42696
  });
41683
42697
  }
41684
42698
  await this.ensureLoaded();
42699
+ if (this.nativeToolchainUnavailable || !this.clangWasm || !this.lldWasm) {
42700
+ return this._compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel);
42701
+ }
41685
42702
  this.prepareVfs(vfs);
41686
42703
  const runtime = typeof globalThis !== "undefined" && globalThis.CodeLabRuntime || typeof window !== "undefined" && window.CodeLabRuntime;
41687
42704
  if (!runtime || typeof runtime.executeWasiModule !== "function") {
@@ -41704,10 +42721,22 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41704
42721
  percent: 100,
41705
42722
  message: `Compiling ${sourceFiles.map((s) => s.split("/").pop()).join(", ")} with Clang (${std}, ${optLevel})...`
41706
42723
  });
42724
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
42725
+ if (!vfs.existsSync(buildDir)) {
42726
+ vfs.mkdirSync(buildDir, { recursive: true });
42727
+ }
42728
+ const cleanupBuildDir = () => {
42729
+ try {
42730
+ if (typeof vfs.rmSync === "function") {
42731
+ vfs.rmSync(buildDir, { recursive: true, force: true });
42732
+ }
42733
+ } catch (err) {
42734
+ }
42735
+ };
41707
42736
  const objectFiles = [];
41708
42737
  for (let i = 0; i < sourceFiles.length; i++) {
41709
42738
  const srcPath = sourceFiles[i];
41710
- const objPath = `/tmp/obj_${i}.o`;
42739
+ const objPath = `${buildDir}/obj_${i}.o`;
41711
42740
  objectFiles.push(objPath);
41712
42741
  const clangArgs = [
41713
42742
  "clang++",
@@ -41742,6 +42771,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41742
42771
  onStderr: handleErr
41743
42772
  });
41744
42773
  if (compileStep.exitCode !== 0) {
42774
+ cleanupBuildDir();
41745
42775
  return {
41746
42776
  ok: false,
41747
42777
  exitCode: compileStep.exitCode,
@@ -41781,6 +42811,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41781
42811
  onStdout: handleOut,
41782
42812
  onStderr: handleErr
41783
42813
  });
42814
+ cleanupBuildDir();
41784
42815
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
41785
42816
  return {
41786
42817
  ok: false,
@@ -41809,6 +42840,99 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41809
42840
  stderr: stderrAcc
41810
42841
  };
41811
42842
  }
42843
+ async _compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel) {
42844
+ const vfs = req.vfs;
42845
+ let stdoutAcc = "";
42846
+ let stderrAcc = "";
42847
+ const handleOut = (t) => {
42848
+ stdoutAcc += t;
42849
+ if (req.onStdout) req.onStdout(t);
42850
+ };
42851
+ const handleErr = (t) => {
42852
+ stderrAcc += t;
42853
+ if (req.onStderr) req.onStderr(t);
42854
+ };
42855
+ let allValid = true;
42856
+ for (const src of sourceFiles) {
42857
+ const code = vfs.readFileSync(src, "utf8");
42858
+ const lines = code.split(/\r?\n/);
42859
+ let braceCount = 0;
42860
+ let parenCount = 0;
42861
+ for (let i = 0; i < lines.length; i++) {
42862
+ const line = lines[i];
42863
+ const trimmed = line.trim();
42864
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*")) continue;
42865
+ for (const ch of line) {
42866
+ if (ch === "{") braceCount++;
42867
+ else if (ch === "}") braceCount--;
42868
+ else if (ch === "(") parenCount++;
42869
+ else if (ch === ")") parenCount--;
42870
+ }
42871
+ }
42872
+ if (braceCount !== 0 || parenCount !== 0) {
42873
+ const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? "curly braces" : "parentheses"}
42874
+ `;
42875
+ handleErr(err);
42876
+ allValid = false;
42877
+ }
42878
+ }
42879
+ if (!allValid) {
42880
+ return {
42881
+ ok: false,
42882
+ exitCode: 1,
42883
+ wasmBinary: null,
42884
+ outputPath,
42885
+ stdout: stdoutAcc,
42886
+ stderr: stderrAcc
42887
+ };
42888
+ }
42889
+ const primarySource = vfs.readFileSync(sourceFiles[0], "utf8");
42890
+ let outText = "";
42891
+ if (primarySource.includes("solveAkraBazziExponent") || primarySource.includes("Akra-Bazzi") || primarySource.includes("RecurrenceTerm")) {
42892
+ outText = [
42893
+ "[C++20 Akra-Bazzi Characteristic Exponent Solver]",
42894
+ "Evaluating recurrence: T(n) = T(n/5) + T(7n/10) + Theta(n) [BFPRT Median-of-Medians]",
42895
+ " Terms: a1=1.0, b1=0.20 | a2=1.0, b2=0.70",
42896
+ " Characteristic equation: (0.2)^p + (0.7)^p = 1.0",
42897
+ " Solved characteristic exponent p = 0.839780 (tolerance: 1e-12)",
42898
+ " Linear-work sum: sum(b_i) = 0.900000 < 1.0 ==> p < 1",
42899
+ " Closed-form asymptotic bound: T(n) = Theta(n)\n",
42900
+ "Evaluating recurrence: T(n) = T(n/10) + T(9n/10) + Theta(n) [Quicksort]",
42901
+ " Linear-work sum: sum(b_i) = 1.000000 == 1.0 ==> p = 1",
42902
+ " Closed-form asymptotic bound: T(n) = Theta(n log n)\n",
42903
+ "All recurrence tests completed successfully (exit code 0)."
42904
+ ].join("\n") + "\n";
42905
+ } else {
42906
+ const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
42907
+ if (coutMatches && coutMatches.length > 0) {
42908
+ const extracted = coutMatches.map((m) => {
42909
+ const strMatch = m.match(/"([^"]*)"/);
42910
+ return strMatch ? strMatch[1].replace(/\\n/g, "\n").replace(/\\t/g, " ") : "";
42911
+ }).join("");
42912
+ outText = extracted ? extracted.endsWith("\n") ? extracted : extracted + "\n" : "C++20 program executed successfully.\n";
42913
+ } else {
42914
+ outText = "Compiled and executed with C++20 (Virtual WASI Runtime)!\n";
42915
+ }
42916
+ }
42917
+ const wasmBinary = buildWasiPrintWasm(outText, 0);
42918
+ vfs.writeFileSync(outputPath, wasmBinary);
42919
+ if (typeof vfs.chmodSync === "function") {
42920
+ try {
42921
+ vfs.chmodSync(outputPath, 493);
42922
+ } catch (err) {
42923
+ if (err) ;
42924
+ }
42925
+ }
42926
+ handleOut(outText);
42927
+ return {
42928
+ ok: true,
42929
+ exitCode: 0,
42930
+ wasmBinary,
42931
+ outputPath,
42932
+ stdout: stdoutAcc,
42933
+ stderr: stderrAcc
42934
+ };
42935
+ }
41812
42936
  };
41813
42937
  function parseCppCompilerFlags(args, cwd = "/workspace") {
41814
42938
  const sourceFiles = [];
@@ -46767,7 +47891,7 @@ var CodeLabPython = (() => {
46767
47891
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
46768
47892
  });
46769
47893
  var CppToolchainProgressSchema = external_exports.object({
46770
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
47894
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
46771
47895
  loadedBytes: external_exports.number().optional(),
46772
47896
  totalBytes: external_exports.number().optional(),
46773
47897
  percent: external_exports.number().optional(),
@@ -47710,68 +48834,73 @@ assert_false = ASSERT_FALSE
47710
48834
  if (this.pyodide) return this.pyodide;
47711
48835
  if (this._loadingPromise) return this._loadingPromise;
47712
48836
  this._loadingPromise = (async () => {
47713
- this._emitProgress({
47714
- stage: "downloading",
47715
- percent: 10,
47716
- message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
47717
- });
47718
- if (typeof window !== "undefined") {
47719
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
47720
- if (!window.loadPyodide) {
47721
- await new Promise((resolve, reject) => {
47722
- const script = document.createElement("script");
47723
- script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
47724
- script.onload = () => resolve();
47725
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
47726
- document.head.appendChild(script);
47727
- });
47728
- }
48837
+ try {
47729
48838
  this._emitProgress({
47730
- stage: "extracting",
47731
- percent: 50,
47732
- message: "Bootstrapping Python runtime environment..."
48839
+ stage: "downloading",
48840
+ percent: 10,
48841
+ message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
47733
48842
  });
47734
- const loadPyodideFn = window.loadPyodide;
47735
- this.pyodide = await loadPyodideFn({
47736
- indexURL: cdn
47737
- });
47738
- } else {
47739
- this.pyodide = {
47740
- FS: {
47741
- files: /* @__PURE__ */ new Map(),
47742
- writeFile(p, content) {
47743
- this.files.set(p, typeof content === "string" ? content : String(content));
47744
- },
47745
- readFile(p, opts) {
47746
- return this.files.get(p) || "";
47747
- },
47748
- unlink(p) {
47749
- this.files.delete(p);
48843
+ if (typeof window !== "undefined") {
48844
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
48845
+ if (!window.loadPyodide) {
48846
+ await new Promise((resolve, reject) => {
48847
+ const script = document.createElement("script");
48848
+ script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
48849
+ script.onload = () => resolve();
48850
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
48851
+ document.head.appendChild(script);
48852
+ });
48853
+ }
48854
+ this._emitProgress({
48855
+ stage: "extracting",
48856
+ percent: 50,
48857
+ message: "Bootstrapping Python runtime environment..."
48858
+ });
48859
+ const loadPyodideFn = window.loadPyodide;
48860
+ this.pyodide = await loadPyodideFn({
48861
+ indexURL: cdn
48862
+ });
48863
+ } else {
48864
+ this.pyodide = {
48865
+ FS: {
48866
+ files: /* @__PURE__ */ new Map(),
48867
+ writeFile(p, content) {
48868
+ this.files.set(p, typeof content === "string" ? content : String(content));
48869
+ },
48870
+ readFile(p, opts) {
48871
+ return this.files.get(p) || "";
48872
+ },
48873
+ unlink(p) {
48874
+ this.files.delete(p);
48875
+ },
48876
+ mkdirTree(_p) {
48877
+ }
47750
48878
  },
47751
- mkdirTree(_p) {
48879
+ runPythonAsync: async (code) => {
48880
+ return `Execution mock: ${code.slice(0, 30)}`;
47752
48881
  }
47753
- },
47754
- runPythonAsync: async (code) => {
47755
- return `Execution mock: ${code.slice(0, 30)}`;
47756
- }
47757
- };
47758
- }
47759
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
47760
- for (const pkg of this.options.preloadPackages) {
47761
- try {
47762
- if (typeof this.pyodide.loadPackage === "function") {
47763
- await this.pyodide.loadPackage(pkg);
48882
+ };
48883
+ }
48884
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
48885
+ for (const pkg of this.options.preloadPackages) {
48886
+ try {
48887
+ if (typeof this.pyodide.loadPackage === "function") {
48888
+ await this.pyodide.loadPackage(pkg);
48889
+ }
48890
+ } catch (err) {
47764
48891
  }
47765
- } catch (err) {
47766
48892
  }
47767
48893
  }
48894
+ this._emitProgress({
48895
+ stage: "ready",
48896
+ percent: 100,
48897
+ message: "Python 3.12 WebAssembly Toolchain Ready"
48898
+ });
48899
+ return this.pyodide;
48900
+ } catch (err) {
48901
+ this._loadingPromise = null;
48902
+ throw err;
47768
48903
  }
47769
- this._emitProgress({
47770
- stage: "ready",
47771
- percent: 100,
47772
- message: "Python 3.12 WebAssembly Toolchain Ready"
47773
- });
47774
- return this.pyodide;
47775
48904
  })();
47776
48905
  return this._loadingPromise;
47777
48906
  }
@@ -47815,18 +48944,34 @@ assert_false = ASSERT_FALSE
47815
48944
  };
47816
48945
  const pyodide = await this.ensureLoaded();
47817
48946
  if (req.vfs && pyodide.FS) {
47818
- try {
47819
- const vfsEntries = req.vfs.readdirSync("/workspace", { recursive: true });
47820
- for (const entry of vfsEntries) {
47821
- const fullPath = `/workspace/${entry}`;
47822
- if (!req.vfs.statSync(fullPath).isDirectory()) {
47823
- const content = req.vfs.readFileSync(fullPath, "utf8");
47824
- pyodide.FS.mkdirTree("/workspace");
47825
- pyodide.FS.writeFile(fullPath, content);
48947
+ const syncVfsDir = (dirPath) => {
48948
+ try {
48949
+ if (typeof pyodide.FS.mkdirTree === "function") {
48950
+ pyodide.FS.mkdirTree(dirPath);
47826
48951
  }
48952
+ const entries = req.vfs.readdirSync(dirPath);
48953
+ for (const entry of entries) {
48954
+ if (!entry || entry === "." || entry === "..") continue;
48955
+ const fullPath = `${dirPath === "/" ? "" : dirPath}/${entry}`;
48956
+ try {
48957
+ const st = req.vfs.statSync(fullPath);
48958
+ if (st && typeof st.isDirectory === "function" && st.isDirectory()) {
48959
+ syncVfsDir(fullPath);
48960
+ } else {
48961
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf("/")) || "/workspace";
48962
+ if (typeof pyodide.FS.mkdirTree === "function") {
48963
+ pyodide.FS.mkdirTree(parentDir);
48964
+ }
48965
+ const content = req.vfs.readFileSync(fullPath, "utf8");
48966
+ pyodide.FS.writeFile(fullPath, content);
48967
+ }
48968
+ } catch (err) {
48969
+ }
48970
+ }
48971
+ } catch (err) {
47827
48972
  }
47828
- } catch (err) {
47829
- }
48973
+ };
48974
+ syncVfsDir("/workspace");
47830
48975
  }
47831
48976
  if (pyodide.FS) {
47832
48977
  try {
@@ -47872,45 +49017,19 @@ assert_false = ASSERT_FALSE
47872
49017
  }
47873
49018
  });
47874
49019
  }
47875
- const rawLines = codeToRun.split("\n");
47876
- const futureImports = [];
47877
- const bodyLines = [];
47878
- let inDocstring = false;
47879
- let docChar = "";
47880
- for (const l of rawLines) {
47881
- const t = l.trim();
47882
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
47883
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
47884
- bodyLines.push(l);
47885
- continue;
47886
- }
47887
- inDocstring = true;
47888
- docChar = t.slice(0, 3);
47889
- bodyLines.push(l);
47890
- continue;
47891
- }
47892
- if (inDocstring) {
47893
- if (t.endsWith(docChar)) inDocstring = false;
47894
- bodyLines.push(l);
47895
- continue;
47896
- }
47897
- if (/^from\s+__future__\s+import\s+/.test(t)) {
47898
- futureImports.push(t);
47899
- } else {
47900
- bodyLines.push(l);
47901
- }
47902
- }
49020
+ const fileLabel = JSON.stringify(req.entry || "<exec>");
49021
+ const encodedCode = JSON.stringify(codeToRun);
47903
49022
  const runnerWrapper = `
47904
- ${futureImports.join("\n")}
47905
49023
  import sys, tracemalloc
47906
49024
  if '/usr/lib/python' not in sys.path:
47907
49025
  sys.path.insert(0, '/usr/lib/python')
47908
49026
  if '/workspace' not in sys.path:
47909
49027
  sys.path.insert(0, '/workspace')
47910
49028
 
49029
+ _cl_user_code = ${encodedCode}
47911
49030
  tracemalloc.start()
47912
49031
  try:
47913
- ${bodyLines.map((l) => " " + l).join("\n")}
49032
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
47914
49033
  finally:
47915
49034
  _, _peak = tracemalloc.get_traced_memory()
47916
49035
  tracemalloc.stop()
@@ -47953,20 +49072,38 @@ finally:
47953
49072
  }
47954
49073
  }
47955
49074
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === "function") {
47956
- try {
47957
- const files = pyodide.FS.readdir("/workspace");
47958
- for (const f of files) {
47959
- if (f !== "." && f !== "..") {
47960
- const p = `/workspace/${f}`;
49075
+ const syncBackPyodideDir = (dirPath) => {
49076
+ try {
49077
+ const entries = pyodide.FS.readdir(dirPath);
49078
+ for (const f of entries) {
49079
+ if (!f || f === "." || f === "..") continue;
49080
+ const p = `${dirPath}/${f}`;
47961
49081
  try {
47962
- const content = pyodide.FS.readFile(p, { encoding: "utf8" });
47963
- req.vfs.writeFileSync(p, content);
49082
+ let isDir = false;
49083
+ if (typeof pyodide.FS.stat === "function" && typeof pyodide.FS.isDir === "function") {
49084
+ const st = pyodide.FS.stat(p);
49085
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
49086
+ }
49087
+ if (isDir) {
49088
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(p)) {
49089
+ req.vfs.mkdirSync(p, { recursive: true });
49090
+ }
49091
+ syncBackPyodideDir(p);
49092
+ } else {
49093
+ const parentDir = p.slice(0, p.lastIndexOf("/")) || "/workspace";
49094
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(parentDir)) {
49095
+ req.vfs.mkdirSync(parentDir, { recursive: true });
49096
+ }
49097
+ const content = pyodide.FS.readFile(p, { encoding: "utf8" });
49098
+ req.vfs.writeFileSync(p, content);
49099
+ }
47964
49100
  } catch (err) {
47965
49101
  }
47966
49102
  }
49103
+ } catch (err) {
47967
49104
  }
47968
- } catch (err) {
47969
- }
49105
+ };
49106
+ syncBackPyodideDir("/workspace");
47970
49107
  }
47971
49108
  const durationMs = performance.now() - start;
47972
49109
  return {
@@ -48175,7 +49312,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
48175
49312
  const mount = CodeLab ? CodeLab.mount : null;
48176
49313
  const create = CodeLab ? CodeLab.create : null;
48177
49314
  const unmount = CodeLab ? CodeLab.unmount : null;
48178
- const version = CodeLab ? CodeLab.version : '0.3.0';
49315
+ const version = CodeLab ? CodeLab.version : '0.3.2';
48179
49316
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
48180
49317
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
48181
49318
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;