@innovatorved/code-lab 0.3.1 → 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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -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 +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — 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` : "";
@@ -2420,11 +2579,15 @@ var CodeLabWorkbenchComponents = (() => {
2420
2579
  ${items.map((item) => {
2421
2580
  const icon = item.severity === "error" ? "\u2717" : item.severity === "warning" ? "\u26A0" : "\u2139";
2422
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;
2423
2586
  return `
2424
- <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}">
2425
2588
  <span style="font-weight:bold;">${icon}</span>
2426
- <span>${item.message}</span>
2427
- <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>
2428
2591
  </div>
2429
2592
  `;
2430
2593
  }).join("")}
@@ -2432,7 +2595,7 @@ var CodeLabWorkbenchComponents = (() => {
2432
2595
  `;
2433
2596
  }
2434
2597
  function renderStdinPanelHtml(workbench) {
2435
- const val = workbench.customStdin || "";
2598
+ const val = escapeHtml2(workbench.customStdin || "");
2436
2599
  return `
2437
2600
  <div class="codelab-stdin-panel">
2438
2601
  <div class="codelab-stdin-panel__header">
@@ -2450,6 +2613,9 @@ var CodeLabWorkbenchComponents = (() => {
2450
2613
  CodeLabDiffEditorManager: () => CodeLabDiffEditorManager,
2451
2614
  computeSimpleDiff: () => computeSimpleDiff
2452
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
+ }
2453
2619
  function computeSimpleDiff(oldText, newText) {
2454
2620
  const oldLines = String(oldText || "").split("\n");
2455
2621
  const newLines = String(newText || "").split("\n");
@@ -2535,11 +2701,24 @@ var CodeLabWorkbenchComponents = (() => {
2535
2701
  diffContainer.style.display = "flex";
2536
2702
  if (editorHost) editorHost.style.display = "none";
2537
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);
2538
2717
  diffContainer.innerHTML = `
2539
2718
  <div class="codelab-diff-toolbar">
2540
2719
  <span style="font-weight:600;display:inline-flex;align-items:center;gap:6px;">
2541
2720
  ${CL_ICONS.diff}
2542
- <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>
2543
2722
  </span>
2544
2723
  <div class="codelab-segmented" style="margin-left:16px;">
2545
2724
  <button type="button" class="codelab-segmented__btn ${target === "starter" ? "active" : ""}" id="cl-diff-toggle-starter">Starter</button>
@@ -2554,16 +2733,14 @@ var CodeLabWorkbenchComponents = (() => {
2554
2733
  <div class="codelab-diff-host" id="cl-diff-editor-slot"></div>
2555
2734
  `;
2556
2735
  const slot = diffContainer.querySelector("#cl-diff-editor-slot");
2557
- if (!this.diffEditor) {
2558
- this.diffEditor = monaco.editor.createDiffEditor(slot, {
2559
- readOnly: false,
2560
- originalEditable: false,
2561
- theme: this.workbench.theme === "light" ? "vs" : "vs-dark",
2562
- renderSideBySide: true,
2563
- automaticLayout: true,
2564
- minimap: { enabled: false }
2565
- });
2566
- }
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
+ });
2567
2744
  const lang = file.endsWith(".ts") ? "typescript" : file.endsWith(".cpp") ? "cpp" : file.endsWith(".py") ? "python" : "javascript";
2568
2745
  this.originalModel = monaco.editor.createModel(refCode, lang);
2569
2746
  this.modifiedModel = monaco.editor.createModel(currentCode, lang);
@@ -2585,13 +2762,20 @@ var CodeLabWorkbenchComponents = (() => {
2585
2762
  this.openInlineDiff(file, "solution");
2586
2763
  });
2587
2764
  diffContainer.querySelector("#cl-diff-revert-btn")?.addEventListener("click", () => {
2588
- 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] || "";
2589
2767
  this.workbench.files[file] = starterCode;
2590
2768
  this.closeInlineDiff();
2591
2769
  this.workbench.openFile(file);
2592
2770
  });
2593
2771
  diffContainer.querySelector("#cl-diff-apply-btn")?.addEventListener("click", () => {
2594
- 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] || "";
2595
2779
  this.workbench.files[file] = solutionCode;
2596
2780
  this.closeInlineDiff();
2597
2781
  this.workbench.openFile(file);
@@ -2806,21 +2990,53 @@ var CodeLabWorkbenchComponents = (() => {
2806
2990
  }
2807
2991
  return bufferToBase64Url(rawBytes);
2808
2992
  }
2993
+ var MAX_DECOMPRESSED_SNAPSHOT_BYTES = 5 * 1024 * 1024;
2809
2994
  async function decompressWorkspaceSnapshot(encoded) {
2810
2995
  if (!encoded || typeof encoded !== "string") return null;
2811
2996
  try {
2812
2997
  const bytes = base64UrlToBuffer(encoded);
2998
+ if (bytes.byteLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
2999
+ throw new Error("Snapshot payload exceeds maximum allowed size");
3000
+ }
2813
3001
  if (typeof DecompressionStream !== "undefined") {
2814
3002
  try {
2815
3003
  const ds = new DecompressionStream("deflate-raw");
2816
3004
  const writer = ds.writable.getWriter();
2817
- writer.write(bytes);
2818
- writer.close();
2819
- const response = new Response(ds.readable);
2820
- 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
+ }
2821
3034
  const text = new TextDecoder().decode(decompressed);
2822
3035
  return JSON.parse(text);
2823
3036
  } catch (err) {
3037
+ if (err instanceof Error && err.message.includes("safety limit")) {
3038
+ throw err;
3039
+ }
2824
3040
  const rawText2 = new TextDecoder().decode(bytes);
2825
3041
  return JSON.parse(rawText2);
2826
3042
  }
@@ -2914,6 +3130,9 @@ var CodeLabWorkbenchComponents = (() => {
2914
3130
  __export(guided_pane_exports, {
2915
3131
  renderStepPillsHtml: () => renderStepPillsHtml
2916
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
+ }
2917
3136
  function renderStepPillsHtml(steps, activeIndex, completedStepIds) {
2918
3137
  if (!steps || steps.length === 0) return "";
2919
3138
  return `
@@ -2922,10 +3141,11 @@ var CodeLabWorkbenchComponents = (() => {
2922
3141
  const isPassed = completedStepIds.has(step.id);
2923
3142
  const isActive = idx === activeIndex;
2924
3143
  const cls = `codelab-step-pill ${isActive ? "active" : ""} ${isPassed ? "passed" : ""}`;
3144
+ const safeTitle = escapeHtml4(step.title);
2925
3145
  return `
2926
- <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}">
2927
3147
  <span class="codelab-step-pill__num">${isPassed ? CL_ICONS.check : idx + 1}</span>
2928
- <span class="codelab-step-pill__label">${step.title}</span>
3148
+ <span class="codelab-step-pill__label">${safeTitle}</span>
2929
3149
  </button>
2930
3150
  `;
2931
3151
  }).join("")}
@@ -3975,22 +4195,40 @@ function __initVirtualRuntime(rootScope) {
3975
4195
  // =========================================================================
3976
4196
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
3977
4197
  // =========================================================================
3978
- function createVirtualFs(initialFiles = {}) {
4198
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
3979
4199
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
3980
4200
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
3981
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);
3982
4207
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
3983
4208
  let nextFd = 10;
3984
4209
  let nextIno = 100;
3985
4210
  let mkdtempCounter = 1;
3986
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
+
3987
4223
  function normPath(p) {
3988
4224
  if (typeof p !== 'string' || !p) {
3989
4225
  const err = new TypeError('path must be a non-empty string');
3990
4226
  err.code = 'ERR_INVALID_ARG_TYPE';
3991
4227
  throw err;
3992
4228
  }
3993
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
4229
+ const baseCwd = typeof customCwdGetter === 'function'
4230
+ ? customCwdGetter()
4231
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
3994
4232
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
3995
4233
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
3996
4234
  }
@@ -4041,9 +4279,13 @@ function __initVirtualRuntime(rootScope) {
4041
4279
  for (const [relPath, content] of Object.entries(initialFiles)) {
4042
4280
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
4043
4281
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
4044
- const fullPath = isSystemPath
4282
+ let fullPath = isSystemPath
4045
4283
  ? normPath(relPath)
4046
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
+ }
4047
4289
  ensureParentDirs(fullPath);
4048
4290
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
4049
4291
  files.set(fullPath, {
@@ -4223,13 +4465,6 @@ function __initVirtualRuntime(rootScope) {
4223
4465
  fsyncSync(fd) {
4224
4466
  const entry = fdTable.get(fd);
4225
4467
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
4226
- if (!entry.isDirectory && entry.inode) {
4227
- deletedInspectorCache.set(entry.path, {
4228
- data: entry.inode.data.slice(),
4229
- mtimeMs: entry.inode.mtimeMs,
4230
- deletedAtMs: null
4231
- });
4232
- }
4233
4468
  },
4234
4469
 
4235
4470
  fdatasyncSync(fd) {
@@ -4270,12 +4505,6 @@ function __initVirtualRuntime(rootScope) {
4270
4505
  inode.mtimeMs = Date.now();
4271
4506
  entry.pos = writePos + chunk.byteLength;
4272
4507
 
4273
- deletedInspectorCache.set(entry.path, {
4274
- data: inode.data.slice(),
4275
- mtimeMs: inode.mtimeMs,
4276
- deletedAtMs: null
4277
- });
4278
-
4279
4508
  return chunk.byteLength;
4280
4509
  },
4281
4510
 
@@ -4327,7 +4556,7 @@ function __initVirtualRuntime(rootScope) {
4327
4556
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
4328
4557
  }
4329
4558
  }
4330
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4559
+ deletedInspectorCache.delete(np);
4331
4560
  },
4332
4561
 
4333
4562
  chmodSync(p, mode) {
@@ -4356,7 +4585,7 @@ function __initVirtualRuntime(rootScope) {
4356
4585
  combined.set(chunk, inode.data.byteLength);
4357
4586
  inode.data = combined;
4358
4587
  inode.mtimeMs = Date.now();
4359
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4588
+ deletedInspectorCache.delete(np);
4360
4589
  },
4361
4590
 
4362
4591
  truncateSync(p, len = 0) {
@@ -4372,7 +4601,6 @@ function __initVirtualRuntime(rootScope) {
4372
4601
  inode.data = grown;
4373
4602
  }
4374
4603
  inode.mtimeMs = Date.now();
4375
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4376
4604
  },
4377
4605
 
4378
4606
  renameSync(oldP, newP) {
@@ -4433,16 +4661,14 @@ function __initVirtualRuntime(rootScope) {
4433
4661
  if (fdEntry.path === src) fdEntry.path = dst;
4434
4662
  }
4435
4663
  deletedInspectorCache.delete(src);
4436
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4664
+ deletedInspectorCache.delete(dst);
4437
4665
  },
4438
4666
 
4439
4667
  unlinkSync(p) {
4440
4668
  const np = normPath(p);
4441
4669
  const inode = files.get(np);
4442
4670
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
4443
- if (inode.data.byteLength > 0) {
4444
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4445
- }
4671
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
4446
4672
  files.delete(np);
4447
4673
  },
4448
4674
 
@@ -4459,9 +4685,7 @@ function __initVirtualRuntime(rootScope) {
4459
4685
  for (const [fPath, inode] of Array.from(files.entries())) {
4460
4686
  if (fPath.startsWith(prefix)) {
4461
4687
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
4462
- if (inode.data.byteLength > 0) {
4463
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4464
- }
4688
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
4465
4689
  files.delete(fPath);
4466
4690
  }
4467
4691
  }
@@ -6035,6 +6259,7 @@ function __initVirtualRuntime(rootScope) {
6035
6259
  responseHeaders: {},
6036
6260
  _t0: performance.now()
6037
6261
  };
6262
+ if (httpTrace.length >= 500) httpTrace.shift();
6038
6263
  httpTrace.push(traceEntry);
6039
6264
  this._traceEntry = traceEntry;
6040
6265
 
@@ -7026,6 +7251,7 @@ function __initVirtualRuntime(rootScope) {
7026
7251
  this._peer = serverSocket;
7027
7252
  this.connecting = false;
7028
7253
 
7254
+ if (sharedTrace.length >= 500) sharedTrace.shift();
7029
7255
  sharedTrace.push({
7030
7256
  protocol: 'TCP',
7031
7257
  event: 'connect',
@@ -9318,7 +9544,10 @@ function __initVirtualRuntime(rootScope) {
9318
9544
  const activePortTable = optPortTable || portTable || _defaultPortTable;
9319
9545
  resourceTracker.pid = pid;
9320
9546
 
9321
- const vfs = optVfs || createVirtualFs(files);
9547
+ let currentCwd = '/workspace';
9548
+ _activeCwdGetter = () => currentCwd;
9549
+
9550
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
9322
9551
  if (optVfs && files && typeof files === 'object') {
9323
9552
  for (const [fPath, content] of Object.entries(files)) {
9324
9553
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -9712,8 +9941,6 @@ function __initVirtualRuntime(rootScope) {
9712
9941
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
9713
9942
 
9714
9943
  let syncExecDepth = 0;
9715
- let currentCwd = '/workspace';
9716
- _activeCwdGetter = () => currentCwd;
9717
9944
 
9718
9945
  const sandboxProcess = Object.assign(new EventEmitter(), {
9719
9946
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
@@ -15622,6 +15849,13 @@ if (typeof module !== 'undefined' && module.exports) {
15622
15849
  return out;
15623
15850
  }
15624
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
+
15625
15859
  async function runPackageScript(scriptName, scriptArgs, ctx) {
15626
15860
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
15627
15861
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -15629,7 +15863,7 @@ if (typeof module !== 'undefined' && module.exports) {
15629
15863
  }
15630
15864
  let cmd = pkgData.scripts[scriptName];
15631
15865
  if (scriptArgs && scriptArgs.length > 0) {
15632
- cmd += ' ' + scriptArgs.join(' ');
15866
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
15633
15867
  }
15634
15868
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
15635
15869
  if (fallback) return fallback;
@@ -15882,6 +16116,11 @@ if (typeof module !== 'undefined' && module.exports) {
15882
16116
  const isFile = (p) => exists(p) && !isDir(p);
15883
16117
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
15884
16118
 
16119
+ const isWithinRoot = (p) => {
16120
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
16121
+ return p === rootDir || p.startsWith(rootPrefix);
16122
+ };
16123
+
15885
16124
  const resolveLocalTarget = (baseDir, rawSpec) => {
15886
16125
  if (!rawSpec || typeof rawSpec !== 'string') return null;
15887
16126
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -15889,6 +16128,7 @@ if (typeof module !== 'undefined' && module.exports) {
15889
16128
  const candidateBase = clean.startsWith('/')
15890
16129
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
15891
16130
  : PosixPath.join(baseDir, clean);
16131
+ if (!isWithinRoot(candidateBase)) return null;
15892
16132
  if (isFile(candidateBase)) return candidateBase;
15893
16133
  const cands = [
15894
16134
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -15897,7 +16137,7 @@ if (typeof module !== 'undefined' && module.exports) {
15897
16137
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
15898
16138
  ];
15899
16139
  for (const c of cands) {
15900
- if (isFile(c)) return c;
16140
+ if (isWithinRoot(c) && isFile(c)) return c;
15901
16141
  }
15902
16142
  return null;
15903
16143
  };
@@ -16026,7 +16266,7 @@ if (typeof module !== 'undefined' && module.exports) {
16026
16266
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
16027
16267
  needsTailwindBrowser = true;
16028
16268
  }
16029
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
16269
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
16030
16270
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
16031
16271
  });
16032
16272
 
@@ -16038,7 +16278,7 @@ if (typeof module !== 'undefined' && module.exports) {
16038
16278
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
16039
16279
  const rawScript = readText(scriptTarget);
16040
16280
  if (rawScript === null) return fullTag;
16041
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
16281
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
16042
16282
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
16043
16283
  const typeAttr = isMod ? ' type="module"' : '';
16044
16284
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -16061,6 +16301,12 @@ if (typeof module !== 'undefined' && module.exports) {
16061
16301
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
16062
16302
  const rel = pathname.replace(/^\/+/, '');
16063
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
+ }
16064
16310
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
16065
16311
 
16066
16312
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -16085,8 +16331,13 @@ if (typeof module !== 'undefined' && module.exports) {
16085
16331
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
16086
16332
  }
16087
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;');
16088
16339
  return new Response(
16089
- `<!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>`,
16090
16341
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
16091
16342
  );
16092
16343
  }
@@ -18237,13 +18488,17 @@ if (typeof module !== 'undefined' && module.exports) {
18237
18488
 
18238
18489
  const count = Math.max(1, result.filesWritten);
18239
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
+ }
18240
18495
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
18241
18496
  const stdout =
18242
18497
  `Cloning into '${dirDisplayName}'...\n` +
18243
18498
  `remote: Enumerating objects: ${count}, done.\n` +
18244
18499
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
18245
18500
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
18246
- return { code: 0, stdout, stderr: '' };
18501
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
18247
18502
  } catch (err) {
18248
18503
  if (ctx.signal && ctx.signal.aborted) {
18249
18504
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -19306,7 +19561,8 @@ if (typeof module !== 'undefined' && module.exports) {
19306
19561
  if (ctx.vfs.existsSync(binPath)) {
19307
19562
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
19308
19563
  }
19309
- 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 });
19310
19566
  },
19311
19567
 
19312
19568
  async bunx(args, ctx) {
@@ -19377,7 +19633,8 @@ if (typeof module !== 'undefined' && module.exports) {
19377
19633
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
19378
19634
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
19379
19635
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
19380
- 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 });
19381
19638
  }
19382
19639
 
19383
19640
  if (sub === 'dlx') {
@@ -20560,18 +20817,27 @@ if (typeof module !== 'undefined' && module.exports) {
20560
20817
  if (item.background) {
20561
20818
  const pid = this.nextPid++;
20562
20819
  const jobId = this.nextJobId++;
20820
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20563
20821
  const job = {
20564
20822
  id: jobId,
20565
20823
  pid,
20566
20824
  command: trimmed,
20567
20825
  status: 'Running',
20568
- startTime: Date.now()
20826
+ startTime: Date.now(),
20827
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20569
20828
  };
20570
20829
  this.jobs.set(jobId, job);
20571
20830
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20572
20831
 
20573
- // Run in background promise
20574
- 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
+ })
20575
20841
  .then(res => {
20576
20842
  if (job.status !== 'Terminated') {
20577
20843
  job.status = 'Done';
@@ -20725,17 +20991,24 @@ if (typeof module !== 'undefined' && module.exports) {
20725
20991
  if (item.background) {
20726
20992
  const pid = this.nextPid++;
20727
20993
  const jobId = this.nextJobId++;
20994
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20728
20995
  const job = {
20729
20996
  id: jobId,
20730
20997
  pid,
20731
20998
  command: 'background',
20732
20999
  status: 'Running',
20733
- startTime: Date.now()
21000
+ startTime: Date.now(),
21001
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20734
21002
  };
20735
21003
  this.jobs.set(jobId, job);
20736
21004
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20737
21005
 
20738
- 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
+ })
20739
21012
  .then(res => {
20740
21013
  if (job.status !== 'Terminated') {
20741
21014
  job.status = 'Done';
@@ -20851,7 +21124,11 @@ if (typeof module !== 'undefined' && module.exports) {
20851
21124
  wordItems.push(...(innerCtx.positionalArgs || []));
20852
21125
  }
20853
21126
 
21127
+ let loopIter = 0;
20854
21128
  for (const val of wordItems) {
21129
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21130
+ await new Promise((r) => setTimeout(r, 0));
21131
+ }
20855
21132
  if (innerCtx.signal && innerCtx.signal.aborted) {
20856
21133
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20857
21134
  }
@@ -20896,7 +21173,11 @@ if (typeof module !== 'undefined' && module.exports) {
20896
21173
  let combinedStderr = '';
20897
21174
  let lastCode = 0;
20898
21175
 
21176
+ let loopIter = 0;
20899
21177
  while (true) {
21178
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21179
+ await new Promise((r) => setTimeout(r, 0));
21180
+ }
20900
21181
  if (innerCtx.signal && innerCtx.signal.aborted) {
20901
21182
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20902
21183
  }
@@ -21363,7 +21644,9 @@ if (typeof module !== 'undefined' && module.exports) {
21363
21644
 
21364
21645
  // Route any remaining unstreamed output
21365
21646
  if (res.stdout) {
21366
- if (streamedStdoutBytes > 0) {
21647
+ if (res.alreadyStreamed) {
21648
+ stdoutOut = res.stdout;
21649
+ } else if (streamedStdoutBytes > 0) {
21367
21650
  if (res.stdout.length > streamedStdoutBytes) {
21368
21651
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
21369
21652
  }
@@ -21722,6 +22005,14 @@ if (typeof module !== 'undefined' && module.exports) {
21722
22005
 
21723
22006
  const parseAnsiToHtml = ansiToHtml;
21724
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
+
21725
22016
  class PTYTerminalEngine {
21726
22017
  constructor(container, options = {}) {
21727
22018
  if (
@@ -21736,6 +22027,9 @@ if (typeof module !== 'undefined' && module.exports) {
21736
22027
  }
21737
22028
  this.container = container || null;
21738
22029
  this.options = options || {};
22030
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
22031
+ ? this.options.maxScrollback
22032
+ : MAX_SCROLLBACK;
21739
22033
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
21740
22034
  this.cwd = this.options.cwd || '/workspace';
21741
22035
  this.replMode = Boolean(this.options.replMode);
@@ -21749,6 +22043,7 @@ if (typeof module !== 'undefined' && module.exports) {
21749
22043
  this.searchQuery = '';
21750
22044
  this.searchMatchIdx = -1;
21751
22045
  this._readLineQueue = [];
22046
+ this.isBusy = false;
21752
22047
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
21753
22048
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
21754
22049
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -21899,13 +22194,40 @@ if (typeof module !== 'undefined' && module.exports) {
21899
22194
  this.writeStreamChunk(String(data) + '\n', type);
21900
22195
  }
21901
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
+
21902
22225
  _getActiveLine(type) {
21903
22226
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
21904
22227
  return this.logs[this._targetLineIdx];
21905
22228
  }
21906
22229
  if (this._activeLineCommitted || this.logs.length === 0) {
21907
- const newLine = { text: '', type };
21908
- this.logs.push(newLine);
22230
+ const newLine = this._pushLog({ text: '', type });
21909
22231
  this._activeLineCommitted = false;
21910
22232
  this._cursorCol = 0;
21911
22233
  this._targetLineIdx = this.logs.length - 1;
@@ -21922,7 +22244,7 @@ if (typeof module !== 'undefined' && module.exports) {
21922
22244
  const logEl = this.container.querySelector('#cl-terminal-log');
21923
22245
  if (!logEl) return;
21924
22246
  const lineEl = document.createElement('div');
21925
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22247
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21926
22248
  lineEl.innerHTML = ansiToHtml(line.text);
21927
22249
  logEl.appendChild(lineEl);
21928
22250
  this._activeLineEl = lineEl;
@@ -21945,7 +22267,7 @@ if (typeof module !== 'undefined' && module.exports) {
21945
22267
  }
21946
22268
  }
21947
22269
  if (lineEl) {
21948
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22270
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21949
22271
  lineEl.innerHTML = ansiToHtml(line.text);
21950
22272
  }
21951
22273
  }
@@ -21984,17 +22306,29 @@ if (typeof module !== 'undefined' && module.exports) {
21984
22306
  return [...this.history];
21985
22307
  }
21986
22308
 
21987
- readLine(promptText = '') {
21988
- const prevPrompt = this.promptOverride;
21989
- if (promptText) {
21990
- 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
+ }
21991
22318
  }
22319
+ }
22320
+
22321
+ readLine(promptText = '') {
21992
22322
  return new Promise((resolve) => {
21993
- this._readLineQueue.push((line) => {
21994
- this.promptOverride = prevPrompt;
21995
- this.updateActiveLine();
21996
- resolve(line);
21997
- });
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();
21998
22332
  });
21999
22333
  }
22000
22334
 
@@ -22064,6 +22398,10 @@ if (typeof module !== 'undefined' && module.exports) {
22064
22398
  if (input) {
22065
22399
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
22066
22400
  this._addListener(input, 'input', () => {
22401
+ if (this.isCommandRunning()) {
22402
+ input.value = '';
22403
+ return;
22404
+ }
22067
22405
  if (input.value !== this.buffer) {
22068
22406
  this.buffer = input.value;
22069
22407
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -22105,6 +22443,35 @@ if (typeof module !== 'undefined' && module.exports) {
22105
22443
  const key = e.key;
22106
22444
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
22107
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
+
22108
22475
  if (isCtrl && (key === 'r' || key === 'R')) {
22109
22476
  if (e.preventDefault) e.preventDefault();
22110
22477
  if (!this.searchMode) {
@@ -22236,33 +22603,11 @@ if (typeof module !== 'undefined' && module.exports) {
22236
22603
  return;
22237
22604
  }
22238
22605
 
22239
- if (isCtrl && (key === 'l' || key === 'L')) {
22240
- if (e.preventDefault) e.preventDefault();
22241
- this.clear();
22242
- return;
22243
- }
22244
-
22245
- if (isCtrl && (key === 'c' || key === 'C')) {
22246
- if (e.preventDefault) e.preventDefault();
22247
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
22248
- this.buffer = '';
22249
- this.cursor = 0;
22250
- this.historyIdx = -1;
22251
- if (this.replMode) {
22252
- this.replMode = false;
22253
- }
22254
- if (this.onInterrupt) {
22255
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
22256
- }
22257
- this.render();
22258
- return;
22259
- }
22260
-
22261
22606
  if (isCtrl && (key === 'd' || key === 'D')) {
22262
22607
  if (this.buffer === '') {
22263
22608
  if (e.preventDefault) e.preventDefault();
22264
22609
  if (this.replMode) {
22265
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
22610
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
22266
22611
  this.replMode = false;
22267
22612
  this.render();
22268
22613
  return;
@@ -22356,14 +22701,41 @@ if (typeof module !== 'undefined' && module.exports) {
22356
22701
  }
22357
22702
 
22358
22703
  // Print candidate matches
22359
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
22360
- 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(' ') });
22361
22706
  this.render();
22362
22707
  }
22363
22708
  }
22364
22709
 
22365
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
+
22366
22737
  const line = this.buffer;
22738
+ const promptSnap = this.getPrompt();
22367
22739
  this.buffer = '';
22368
22740
  this.cursor = 0;
22369
22741
  this.historyIdx = -1;
@@ -22371,22 +22743,49 @@ if (typeof module !== 'undefined' && module.exports) {
22371
22743
  this.searchQuery = '';
22372
22744
  this.searchMatchIdx = -1;
22373
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
+
22374
22754
  if (line.trim()) {
22375
22755
  if (this.history[this.history.length - 1] !== line.trim()) {
22376
22756
  this.history.push(line.trim());
22377
22757
  }
22378
22758
  }
22379
22759
 
22380
- if (this._readLineQueue && this._readLineQueue.length > 0) {
22381
- const resolver = this._readLineQueue.shift();
22760
+ if (!this.onCommand) {
22382
22761
  this.updateActiveLine();
22383
- resolver(line);
22384
22762
  return;
22385
22763
  }
22386
22764
 
22765
+ this.isBusy = true;
22387
22766
  this.updateActiveLine();
22388
- if (this.onCommand) {
22389
- 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();
22390
22789
  }
22391
22790
  }
22392
22791
 
@@ -22399,6 +22798,16 @@ if (typeof module !== 'undefined' && module.exports) {
22399
22798
  const lineEl = this.container.querySelector('#cl-pty-active-line');
22400
22799
  if (!lineEl) return;
22401
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
+
22402
22811
  const prompt = this.searchMode
22403
22812
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
22404
22813
  : this.getPrompt();
@@ -22419,21 +22828,24 @@ if (typeof module !== 'undefined' && module.exports) {
22419
22828
  );
22420
22829
 
22421
22830
  const logsHtml = this.logs
22422
- .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>`)
22423
22832
  .join('');
22424
22833
 
22425
- const prompt = this.searchMode
22426
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
22427
- : this.getPrompt();
22428
- const before = this.buffer.slice(0, this.cursor);
22429
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
22430
- 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';
22431
22843
 
22432
22844
  this.container.innerHTML = `
22433
22845
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
22434
22846
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
22435
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
22436
- <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>
22437
22849
  </div>
22438
22850
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
22439
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)}">
@@ -22543,7 +22955,7 @@ if (typeof module !== 'undefined' && module.exports) {
22543
22955
 
22544
22956
  // The bundler rewrites this literal from package.json at build time. Keeping
22545
22957
  // the fallback in sync lets tests require src/workbench.js directly.
22546
- const CODELAB_VERSION = '0.3.1';
22958
+ const CODELAB_VERSION = '0.3.2';
22547
22959
 
22548
22960
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
22549
22961
  const NODE_AMBIENT_DTS = `
@@ -23118,11 +23530,16 @@ declare module 'bun:sqlite' {
23118
23530
  if (!str) return '';
23119
23531
  let text = String(str);
23120
23532
 
23121
- // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
23122
- 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) => {
23123
23537
  const cleanUrl = sanitizeUrl(url);
23124
23538
  const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
23125
- 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`;
23126
23543
  });
23127
23544
 
23128
23545
  // Strikethrough: ~~del~~
@@ -23140,6 +23557,10 @@ declare module 'bun:sqlite' {
23140
23557
  text = text.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
23141
23558
  text = text.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');
23142
23559
 
23560
+ if (inlineLinks.length > 0) {
23561
+ text = text.replace(/\x00CLLINK(\d+)\x00/g, (_, i) => inlineLinks[Number(i)] || '');
23562
+ }
23563
+
23143
23564
  return text;
23144
23565
  }
23145
23566
 
@@ -23327,7 +23748,7 @@ declare module 'bun:sqlite' {
23327
23748
  const lang = (info || '').trim().split(/\s+/)[0] || '';
23328
23749
  const idx = codeBlocks.length;
23329
23750
  codeBlocks.push(renderCodeBlock(code || '', lang));
23330
- return `\n\n\x00CODEBLOCK_${idx}\x00\n\n`;
23751
+ return `\n\n\x00CLCODEBLOCK${idx}\x00\n\n`;
23331
23752
  });
23332
23753
 
23333
23754
  // Phase 2: Inline Code Span Extraction
@@ -23339,7 +23760,7 @@ declare module 'bun:sqlite' {
23339
23760
  }
23340
23761
  const idx = inlineCodes.length;
23341
23762
  inlineCodes.push(`<code class="codelab-inline-code">${escapeHtml(clean)}</code>`);
23342
- return `\x00INLINECODE_${idx}\x00`;
23763
+ return `\x00CLINLINECODE${idx}\x00`;
23343
23764
  });
23344
23765
 
23345
23766
  // Phase 2b: Autolinks are the only inline construct that uses angle
@@ -23352,7 +23773,7 @@ declare module 'bun:sqlite' {
23352
23773
  autolinks.push(
23353
23774
  `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
23354
23775
  );
23355
- return `\x00AUTOLINK_${idx}\x00`;
23776
+ return `\x00CLAUTOLINK${idx}\x00`;
23356
23777
  });
23357
23778
 
23358
23779
  // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
@@ -23387,7 +23808,7 @@ declare module 'bun:sqlite' {
23387
23808
  }
23388
23809
  const idx = calloutBlocks.length;
23389
23810
  calloutBlocks.push(blockHtml);
23390
- return `\n\n\x00CALLOUT_${idx}\x00\n\n`;
23811
+ return `\n\n\x00CLCALLOUT${idx}\x00\n\n`;
23391
23812
  });
23392
23813
 
23393
23814
  // Phase 4: GFM Tables with Column Alignments
@@ -23397,7 +23818,7 @@ declare module 'bun:sqlite' {
23397
23818
  if (rendered === tableText) return match;
23398
23819
  const idx = tableBlocks.length;
23399
23820
  tableBlocks.push(rendered);
23400
- return `\n\n\x00TABLE_${idx}\x00\n\n`;
23821
+ return `\n\n\x00CLTABLE${idx}\x00\n\n`;
23401
23822
  });
23402
23823
 
23403
23824
  // Phase 5: Task Lists & Nested Lists
@@ -23406,7 +23827,7 @@ declare module 'bun:sqlite' {
23406
23827
  text = text.replace(/(?:^[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*(?:\n[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*|\n[ ]{2,}[^\n]*)*)+/gm, (match) => {
23407
23828
  const idx = listBlocks.length;
23408
23829
  listBlocks.push(renderListBlock(match, taskCounter));
23409
- return `\n\n\x00LIST_${idx}\x00\n\n`;
23830
+ return `\n\n\x00CLLIST${idx}\x00\n\n`;
23410
23831
  });
23411
23832
 
23412
23833
  // Phase 6: Headings, Horizontal Rules, Paragraphs & Inline Spans
@@ -23428,18 +23849,18 @@ declare module 'bun:sqlite' {
23428
23849
  const trimmed = p.trim();
23429
23850
  if (!trimmed) return '';
23430
23851
  if (/^<(h[1-6]|hr|pre|div|blockquote|table|ul|ol)/i.test(trimmed)) return trimmed;
23431
- 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;
23432
23853
  return `<p>${renderInlineFormatting(trimmed).replace(/\n/g, '<br>')}</p>`;
23433
23854
  }).filter(Boolean).join('\n');
23434
23855
 
23435
23856
  // Phase 7: Placeholder Restoration (Reverse order)
23436
23857
  let finalHtml = paras
23437
- .replace(/\x00LIST_(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
23438
- .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
23439
- .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
23440
- .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
23441
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
23442
- .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)] || '');
23443
23864
 
23444
23865
  return finalHtml;
23445
23866
  }
@@ -24442,9 +24863,18 @@ int main() {
24442
24863
  if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
24443
24864
  try {
24444
24865
  if (!this._idbStorage) {
24445
- this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
24446
- }
24447
- 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') {
24448
24878
  Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
24449
24879
  this.logger.debug('Async WorkspaceStorage save skipped.', err);
24450
24880
  });
@@ -24771,6 +25201,7 @@ int main() {
24771
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 => {
24772
25202
  btn.disabled = this.isRunning;
24773
25203
  });
25204
+ this._updatePtyActiveLine();
24774
25205
  }
24775
25206
 
24776
25207
  _hasWebContent() {
@@ -24877,6 +25308,7 @@ int main() {
24877
25308
 
24878
25309
  let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
24879
25310
  if (!stdinTab) {
25311
+ const testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
24880
25312
  const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
24881
25313
  if (afterTab) {
24882
25314
  afterTab.insertAdjacentHTML('afterend', `
@@ -25125,6 +25557,8 @@ int main() {
25125
25557
  </div>
25126
25558
  <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
25127
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>
25128
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>
25129
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>
25130
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>
@@ -26213,16 +26647,27 @@ int main() {
26213
26647
  ${problems.map(p => {
26214
26648
  const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
26215
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;
26216
26651
  return `
26217
- <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">
26218
26653
  <span class="codelab-problem-item__icon">${icon}</span>
26219
26654
  <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
26220
- <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>
26221
26656
  </div>
26222
26657
  `;
26223
26658
  }).join('')}
26224
26659
  </div>
26225
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
+ }
26226
26671
  return;
26227
26672
  }
26228
26673
 
@@ -26294,6 +26739,7 @@ int main() {
26294
26739
  }
26295
26740
 
26296
26741
  if (this.drawerTab === 'terminal') {
26742
+ this._renderTerminalSessionsBar();
26297
26743
  const logsHtml = this.terminalLogs
26298
26744
  .map(item => {
26299
26745
  const html = ansiToHtml ? ansiToHtml(item.text || '') : escapeHtml(item.text || '');
@@ -26302,7 +26748,13 @@ int main() {
26302
26748
  .join('');
26303
26749
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26304
26750
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26305
- 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>`;
26306
26758
  bodyEl.scrollTop = bodyEl.scrollHeight;
26307
26759
  const termSurface = bodyEl.querySelector('#cl-terminal-surface');
26308
26760
  const input = bodyEl.querySelector('#cl-repl-input');
@@ -26314,15 +26766,43 @@ int main() {
26314
26766
  });
26315
26767
  }
26316
26768
  if (input) {
26317
- input.value = (this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || '');
26318
- 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
+ }
26319
26775
  const val = input.value || '';
26320
26776
  const pos = (input.selectionStart !== undefined && input.selectionStart !== null) ? input.selectionStart : val.length;
26321
26777
  this._ptyInputBeforeCursor = val.slice(0, pos);
26322
26778
  this._ptyInputAfterCursor = val.slice(pos);
26323
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
+ }
26324
26787
  });
26325
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
+ }
26326
26806
  if (e.key === 'Tab') {
26327
26807
  e.preventDefault();
26328
26808
  this._handlePtyTabCompletion(input);
@@ -26353,9 +26833,6 @@ int main() {
26353
26833
  this._ptyInputAfterCursor = '';
26354
26834
  this._updatePtyActiveLine();
26355
26835
  }
26356
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
26357
- e.preventDefault();
26358
- this._handleInterrupt();
26359
26836
  } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
26360
26837
  e.preventDefault();
26361
26838
  if (this.inRepl) {
@@ -26365,12 +26842,6 @@ int main() {
26365
26842
  const nextInput = this.container.querySelector('#cl-repl-input');
26366
26843
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26367
26844
  }
26368
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
26369
- e.preventDefault();
26370
- this.terminalLogs = [];
26371
- this._renderDrawerBody();
26372
- const nextInput = this.container.querySelector('#cl-repl-input');
26373
- if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26374
26845
  } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {
26375
26846
  e.preventDefault();
26376
26847
  this._ptyInputBeforeCursor = '';
@@ -26401,6 +26872,7 @@ int main() {
26401
26872
  if (replForm) {
26402
26873
  replForm.addEventListener('submit', e => {
26403
26874
  e.preventDefault();
26875
+ if (this.isRunning) return;
26404
26876
  const rawCmd = (input && input.value !== undefined ? input.value : '') ||
26405
26877
  ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
26406
26878
  const cmd = rawCmd.trim();
@@ -26482,7 +26954,7 @@ int main() {
26482
26954
  if (chunk === null || chunk === undefined || chunk === '') return;
26483
26955
  const rawText = String(chunk);
26484
26956
 
26485
- if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
26957
+ if (this.ptyEngine && this.ptyEngine.container && typeof this.ptyEngine.writeStreamChunk === 'function') {
26486
26958
  try {
26487
26959
  this.ptyEngine.writeStreamChunk(rawText, type);
26488
26960
  } catch (err) {
@@ -26523,6 +26995,14 @@ int main() {
26523
26995
  // A newline completes the current line: commit it to the log + DOM, then begin a fresh line.
26524
26996
  const commitActiveLine = () => {
26525
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
+ }
26526
27006
  patchLineInDom(this._activeStreamLine);
26527
27007
  this._activeStreamLine = '';
26528
27008
  this._activeStreamEl = null;
@@ -26690,15 +27170,39 @@ int main() {
26690
27170
 
26691
27171
  _updatePtyActiveLine() {
26692
27172
  if (!this.container) return;
27173
+ const activeLine = this.container.querySelector('#cl-pty-active-line');
26693
27174
  const beforeEl = this.container.querySelector('.codelab-pty__before');
26694
27175
  const afterEl = this.container.querySelector('.codelab-pty__after');
26695
27176
  const promptEl = this.container.querySelector('.codelab-pty__prompt');
27177
+ const cursorEl = this.container.querySelector('.codelab-pty__cursor');
26696
27178
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26697
27179
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26698
27180
 
26699
- if (promptEl) promptEl.textContent = promptLabel + ' ';
26700
- if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
26701
- 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
+ }
26702
27206
  }
26703
27207
 
26704
27208
  _handlePtyTabCompletion(input) {
@@ -27679,9 +28183,10 @@ int main() {
27679
28183
  _injectPreviewCsp(html, port) {
27680
28184
  if (typeof html !== 'string' || !html) return html;
27681
28185
 
28186
+ const csp = String(this._previewPolicy() || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
27682
28187
  const tags = [];
27683
28188
  if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
27684
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
28189
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
27685
28190
  }
27686
28191
  if (!/<base\b/i.test(html)) {
27687
28192
  tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
@@ -29247,21 +29752,29 @@ int main() {
29247
29752
  if (splitTrigger) {
29248
29753
  e.stopPropagation();
29249
29754
  const menu = this.container.querySelector('#cl-split-run-menu');
29250
- 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
+ }
29251
29760
  return;
29252
29761
  }
29253
29762
 
29254
29763
  const splitMenu = this.container.querySelector('#cl-split-run-menu');
29255
- 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')) {
29256
29765
  splitMenu.classList.remove('active');
29766
+ splitMenu.classList.remove('open');
29257
29767
  }
29258
29768
 
29259
- const problemItem = e.target.closest('[data-cl-problem-file]');
29769
+ const problemItem = e.target.closest('[data-cl-problem-file], [data-problem-file]');
29260
29770
  if (problemItem) {
29261
29771
  e.stopPropagation();
29262
- const pFile = problemItem.dataset.clProblemFile;
29263
- const pLine = Number(problemItem.dataset.clProblemLine || 1);
29264
- 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
+ }
29265
29778
  if (pFile) {
29266
29779
  this.openFile(pFile);
29267
29780
  if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
@@ -29273,6 +29786,24 @@ int main() {
29273
29786
  return;
29274
29787
  }
29275
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
+
29276
29807
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
29277
29808
  if (drawerTabBtn) {
29278
29809
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -29281,8 +29812,9 @@ int main() {
29281
29812
 
29282
29813
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
29283
29814
  if (actionBtn) {
29284
- if (splitMenu && splitMenu.classList.contains('active')) {
29815
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open'))) {
29285
29816
  splitMenu.classList.remove('active');
29817
+ splitMenu.classList.remove('open');
29286
29818
  }
29287
29819
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
29288
29820
  if (action === 'run-code') this.runCode();
@@ -29385,9 +29917,49 @@ int main() {
29385
29917
  if (drawer) drawer.classList.toggle('is-minimized');
29386
29918
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
29387
29919
  } else if (action === 'clear-terminal') {
29388
- this.terminalLogs = [];
29920
+ this._clearTerminalLogs();
29389
29921
  this.lastTestResults = [];
29390
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
+ }
29391
29963
  } else if (action === 'toggle-hint') {
29392
29964
  const box = this.container.querySelector('#cl-hint-box');
29393
29965
  if (box) box.classList.toggle('open');
@@ -31031,6 +31603,7 @@ int main() {
31031
31603
  }
31032
31604
 
31033
31605
  async _handleReplCommand(cmd) {
31606
+ if (this.isRunning) return;
31034
31607
  const trimmed = (cmd || '').trim();
31035
31608
  if (!trimmed) return;
31036
31609
  if (this.replHistory[this.replHistory.length - 1] !== trimmed) {
@@ -31039,7 +31612,19 @@ int main() {
31039
31612
  this.replHistoryIdx = -1;
31040
31613
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
31041
31614
  const promptPrefix = this.inRepl ? '> ' : `codelab:${cwdShort}$ `;
31042
- 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
+ }
31043
31628
 
31044
31629
  if (this.inRepl) {
31045
31630
  if (trimmed === '.exit' || trimmed === 'exit') {
@@ -31049,7 +31634,7 @@ int main() {
31049
31634
  return;
31050
31635
  }
31051
31636
  if (trimmed === '.clear' || trimmed === 'clear') {
31052
- this.terminalLogs = [];
31637
+ this._clearTerminalLogs();
31053
31638
  this._renderDrawerBody();
31054
31639
  return;
31055
31640
  }
@@ -31102,7 +31687,7 @@ int main() {
31102
31687
  }
31103
31688
 
31104
31689
  if (trimmed === 'clear' || trimmed === 'cls') {
31105
- this.terminalLogs = [];
31690
+ this._clearTerminalLogs();
31106
31691
  this._renderDrawerBody();
31107
31692
  return;
31108
31693
  }
@@ -31162,7 +31747,7 @@ int main() {
31162
31747
  this._syncVfsSnapshot(null, true);
31163
31748
 
31164
31749
  if (shellRes && shellRes.clear) {
31165
- this.terminalLogs = [];
31750
+ this._clearTerminalLogs();
31166
31751
  this._renderDrawerBody();
31167
31752
  return;
31168
31753
  }
@@ -31375,6 +31960,10 @@ int main() {
31375
31960
  return bytes;
31376
31961
  }
31377
31962
 
31963
+ exportZip(options = {}) {
31964
+ return this.exportProjectZip(options);
31965
+ }
31966
+
31378
31967
  importProjectZip(zipBytes) {
31379
31968
  const zipMod = root.CodeLabZip;
31380
31969
  if (!zipMod || typeof zipMod.extractZip !== 'function') {
@@ -31387,6 +31976,42 @@ int main() {
31387
31976
  return true;
31388
31977
  }
31389
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
+
31390
32015
  searchWorkspace(options) {
31391
32016
  const searchMod = root.CodeLabSearch;
31392
32017
  if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
@@ -31400,21 +32025,113 @@ int main() {
31400
32025
  if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
31401
32026
  throw new Error('CodeLabSearch engine is not loaded');
31402
32027
  }
31403
- const res = searchMod.replaceInFiles(this.files || {}, options);
31404
- if (res && res.files && res.filesModified > 0) {
31405
- 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);
31406
32033
  this._syncFilesToShellVfs();
31407
32034
  }
31408
32035
  return res;
31409
32036
  }
31410
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
+
31411
32049
  getGitStatus() {
31412
32050
  const scmMod = root.CodeLabScm;
31413
32051
  if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
31414
32052
  return [];
31415
32053
  }
31416
- const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
31417
- 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;
31418
32135
  }
31419
32136
 
31420
32137
  getDiagnostics() {
@@ -31432,12 +32149,20 @@ int main() {
31432
32149
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31433
32150
  if (!slot) return;
31434
32151
  const q = String(initialQuery || '');
31435
- const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
31436
- const rowsHtml = (results.matches || []).map((m) => `
31437
- <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;">
31438
- <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
31439
- </div>
31440
- `).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
+ };
31441
32166
  slot.innerHTML = `
31442
32167
  <div class="codelab-modal-backdrop">
31443
32168
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
@@ -31446,36 +32171,82 @@ int main() {
31446
32171
  <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
31447
32172
  </div>
31448
32173
  <div class="codelab-modal__body">
31449
- <div style="display:flex;gap:8px;margin-bottom:8px;">
31450
- <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
31451
- <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>
31452
32178
  </div>
31453
- <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>
31454
32180
  </div>
31455
32181
  </div>
31456
32182
  </div>
31457
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
+ }
31458
32209
  }
31459
32210
 
31460
32211
  showScmModal() {
31461
32212
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31462
32213
  if (!slot) return;
31463
32214
  const statusList = this.getGitStatus();
31464
- const rowsHtml = statusList.map((entry) => `
31465
- <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;">
31466
- <span>${escapeHtml(entry.path)}</span>
31467
- <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
31468
- </div>
31469
- `).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('');
31470
32234
  slot.innerHTML = `
31471
32235
  <div class="codelab-modal-backdrop">
31472
32236
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
31473
32237
  <div class="codelab-modal__header">
31474
- <span>Source Control (Git Status)</span>
31475
- <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>
31476
32243
  </div>
31477
32244
  <div class="codelab-modal__body">
31478
- <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>
31479
32250
  </div>
31480
32251
  </div>
31481
32252
  </div>
@@ -31487,11 +32258,14 @@ int main() {
31487
32258
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31488
32259
  if (!slot) return;
31489
32260
  const items = this.getDiagnostics();
31490
- const rowsHtml = items.map((d) => `
31491
- <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;">
31492
- <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
31493
- </div>
31494
- `).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('');
31495
32269
  slot.innerHTML = `
31496
32270
  <div class="codelab-modal-backdrop">
31497
32271
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
@@ -31507,6 +32281,40 @@ int main() {
31507
32281
  `;
31508
32282
  }
31509
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
+
31510
32318
  _ensureTerminalSessions() {
31511
32319
  if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
31512
32320
  this._terminalSessions = [
@@ -31919,6 +32727,13 @@ int main() {
31919
32727
  this._editorResizeObserver.disconnect();
31920
32728
  this._editorResizeObserver = null;
31921
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
+ }
31922
32737
  if (this.editor) {
31923
32738
  this.editor.dispose();
31924
32739
  this.editor = null;
@@ -41362,12 +42177,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41362
42177
  const db = await openToolchainIdb();
41363
42178
  if (!db) return null;
41364
42179
  return new Promise((resolve) => {
42180
+ const closeDb = () => {
42181
+ try {
42182
+ db.close();
42183
+ } catch (err) {
42184
+ }
42185
+ };
41365
42186
  try {
41366
42187
  const tx = db.transaction(IDB_STORE, "readonly");
41367
42188
  const store = tx.objectStore(IDB_STORE);
41368
42189
  const req = store.get(key);
41369
42190
  req.onsuccess = () => {
41370
42191
  const val = req.result;
42192
+ closeDb();
41371
42193
  if (val instanceof Uint8Array) {
41372
42194
  memoryAssetCache.set(key, val);
41373
42195
  resolve(val);
@@ -41379,8 +42201,12 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41379
42201
  resolve(null);
41380
42202
  }
41381
42203
  };
41382
- req.onerror = () => resolve(null);
42204
+ req.onerror = () => {
42205
+ closeDb();
42206
+ resolve(null);
42207
+ };
41383
42208
  } catch (err) {
42209
+ closeDb();
41384
42210
  if (err) resolve(null);
41385
42211
  }
41386
42212
  });
@@ -41390,13 +42216,26 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41390
42216
  const db = await openToolchainIdb();
41391
42217
  if (!db) return;
41392
42218
  return new Promise((resolve) => {
42219
+ const closeDb = () => {
42220
+ try {
42221
+ db.close();
42222
+ } catch (err) {
42223
+ }
42224
+ };
41393
42225
  try {
41394
42226
  const tx = db.transaction(IDB_STORE, "readwrite");
41395
42227
  const store = tx.objectStore(IDB_STORE);
41396
42228
  store.put(data, key);
41397
- tx.oncomplete = () => resolve();
41398
- tx.onerror = () => resolve();
42229
+ tx.oncomplete = () => {
42230
+ closeDb();
42231
+ resolve();
42232
+ };
42233
+ tx.onerror = () => {
42234
+ closeDb();
42235
+ resolve();
42236
+ };
41399
42237
  } catch (err) {
42238
+ closeDb();
41400
42239
  if (err) resolve();
41401
42240
  }
41402
42241
  });
@@ -41418,15 +42257,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41418
42257
  continue;
41419
42258
  }
41420
42259
  const sizeOctal = readString(offset + 124, 12);
41421
- const size = parseInt(sizeOctal || "0", 8) || 0;
42260
+ const size = Math.max(0, parseInt(sizeOctal || "0", 8) || 0);
41422
42261
  const typeFlag = tarBytes[offset + 156];
41423
42262
  const prefix = readString(offset + 345, 155);
41424
42263
  const fullName = prefix ? `${prefix}/${name}` : name;
41425
- const cleanRel = fullName.replace(/^\.?\/+/, "");
41426
- 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}`;
41427
42270
  const dataStart = offset + 512;
41428
- const dataEnd = dataStart + size;
41429
- if (cleanRel) {
42271
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
42272
+ if (cleanRel && !hasDotDot) {
41430
42273
  if (typeFlag === 53 || fullName.endsWith("/")) {
41431
42274
  if (!vfs.existsSync(targetPath)) {
41432
42275
  vfs.mkdirSync(targetPath, { recursive: true });
@@ -41878,10 +42721,22 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41878
42721
  percent: 100,
41879
42722
  message: `Compiling ${sourceFiles.map((s) => s.split("/").pop()).join(", ")} with Clang (${std}, ${optLevel})...`
41880
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
+ };
41881
42736
  const objectFiles = [];
41882
42737
  for (let i = 0; i < sourceFiles.length; i++) {
41883
42738
  const srcPath = sourceFiles[i];
41884
- const objPath = `/tmp/obj_${i}.o`;
42739
+ const objPath = `${buildDir}/obj_${i}.o`;
41885
42740
  objectFiles.push(objPath);
41886
42741
  const clangArgs = [
41887
42742
  "clang++",
@@ -41916,6 +42771,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41916
42771
  onStderr: handleErr
41917
42772
  });
41918
42773
  if (compileStep.exitCode !== 0) {
42774
+ cleanupBuildDir();
41919
42775
  return {
41920
42776
  ok: false,
41921
42777
  exitCode: compileStep.exitCode,
@@ -41955,6 +42811,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41955
42811
  onStdout: handleOut,
41956
42812
  onStderr: handleErr
41957
42813
  });
42814
+ cleanupBuildDir();
41958
42815
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
41959
42816
  return {
41960
42817
  ok: false,
@@ -47977,68 +48834,73 @@ assert_false = ASSERT_FALSE
47977
48834
  if (this.pyodide) return this.pyodide;
47978
48835
  if (this._loadingPromise) return this._loadingPromise;
47979
48836
  this._loadingPromise = (async () => {
47980
- this._emitProgress({
47981
- stage: "downloading",
47982
- percent: 10,
47983
- message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
47984
- });
47985
- if (typeof window !== "undefined") {
47986
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
47987
- if (!window.loadPyodide) {
47988
- await new Promise((resolve, reject) => {
47989
- const script = document.createElement("script");
47990
- script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
47991
- script.onload = () => resolve();
47992
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
47993
- document.head.appendChild(script);
47994
- });
47995
- }
48837
+ try {
47996
48838
  this._emitProgress({
47997
- stage: "extracting",
47998
- percent: 50,
47999
- message: "Bootstrapping Python runtime environment..."
48839
+ stage: "downloading",
48840
+ percent: 10,
48841
+ message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
48000
48842
  });
48001
- const loadPyodideFn = window.loadPyodide;
48002
- this.pyodide = await loadPyodideFn({
48003
- indexURL: cdn
48004
- });
48005
- } else {
48006
- this.pyodide = {
48007
- FS: {
48008
- files: /* @__PURE__ */ new Map(),
48009
- writeFile(p, content) {
48010
- this.files.set(p, typeof content === "string" ? content : String(content));
48011
- },
48012
- readFile(p, opts) {
48013
- return this.files.get(p) || "";
48014
- },
48015
- unlink(p) {
48016
- 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
+ }
48017
48878
  },
48018
- mkdirTree(_p) {
48879
+ runPythonAsync: async (code) => {
48880
+ return `Execution mock: ${code.slice(0, 30)}`;
48019
48881
  }
48020
- },
48021
- runPythonAsync: async (code) => {
48022
- return `Execution mock: ${code.slice(0, 30)}`;
48023
- }
48024
- };
48025
- }
48026
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
48027
- for (const pkg of this.options.preloadPackages) {
48028
- try {
48029
- if (typeof this.pyodide.loadPackage === "function") {
48030
- 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) {
48031
48891
  }
48032
- } catch (err) {
48033
48892
  }
48034
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;
48035
48903
  }
48036
- this._emitProgress({
48037
- stage: "ready",
48038
- percent: 100,
48039
- message: "Python 3.12 WebAssembly Toolchain Ready"
48040
- });
48041
- return this.pyodide;
48042
48904
  })();
48043
48905
  return this._loadingPromise;
48044
48906
  }
@@ -48082,18 +48944,34 @@ assert_false = ASSERT_FALSE
48082
48944
  };
48083
48945
  const pyodide = await this.ensureLoaded();
48084
48946
  if (req.vfs && pyodide.FS) {
48085
- try {
48086
- const vfsEntries = req.vfs.readdirSync("/workspace", { recursive: true });
48087
- for (const entry of vfsEntries) {
48088
- const fullPath = `/workspace/${entry}`;
48089
- if (!req.vfs.statSync(fullPath).isDirectory()) {
48090
- const content = req.vfs.readFileSync(fullPath, "utf8");
48091
- pyodide.FS.mkdirTree("/workspace");
48092
- pyodide.FS.writeFile(fullPath, content);
48947
+ const syncVfsDir = (dirPath) => {
48948
+ try {
48949
+ if (typeof pyodide.FS.mkdirTree === "function") {
48950
+ pyodide.FS.mkdirTree(dirPath);
48093
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) {
48094
48972
  }
48095
- } catch (err) {
48096
- }
48973
+ };
48974
+ syncVfsDir("/workspace");
48097
48975
  }
48098
48976
  if (pyodide.FS) {
48099
48977
  try {
@@ -48139,45 +49017,19 @@ assert_false = ASSERT_FALSE
48139
49017
  }
48140
49018
  });
48141
49019
  }
48142
- const rawLines = codeToRun.split("\n");
48143
- const futureImports = [];
48144
- const bodyLines = [];
48145
- let inDocstring = false;
48146
- let docChar = "";
48147
- for (const l of rawLines) {
48148
- const t = l.trim();
48149
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
48150
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
48151
- bodyLines.push(l);
48152
- continue;
48153
- }
48154
- inDocstring = true;
48155
- docChar = t.slice(0, 3);
48156
- bodyLines.push(l);
48157
- continue;
48158
- }
48159
- if (inDocstring) {
48160
- if (t.endsWith(docChar)) inDocstring = false;
48161
- bodyLines.push(l);
48162
- continue;
48163
- }
48164
- if (/^from\s+__future__\s+import\s+/.test(t)) {
48165
- futureImports.push(t);
48166
- } else {
48167
- bodyLines.push(l);
48168
- }
48169
- }
49020
+ const fileLabel = JSON.stringify(req.entry || "<exec>");
49021
+ const encodedCode = JSON.stringify(codeToRun);
48170
49022
  const runnerWrapper = `
48171
- ${futureImports.join("\n")}
48172
49023
  import sys, tracemalloc
48173
49024
  if '/usr/lib/python' not in sys.path:
48174
49025
  sys.path.insert(0, '/usr/lib/python')
48175
49026
  if '/workspace' not in sys.path:
48176
49027
  sys.path.insert(0, '/workspace')
48177
49028
 
49029
+ _cl_user_code = ${encodedCode}
48178
49030
  tracemalloc.start()
48179
49031
  try:
48180
- ${bodyLines.map((l) => " " + l).join("\n")}
49032
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
48181
49033
  finally:
48182
49034
  _, _peak = tracemalloc.get_traced_memory()
48183
49035
  tracemalloc.stop()
@@ -48220,20 +49072,38 @@ finally:
48220
49072
  }
48221
49073
  }
48222
49074
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === "function") {
48223
- try {
48224
- const files = pyodide.FS.readdir("/workspace");
48225
- for (const f of files) {
48226
- if (f !== "." && f !== "..") {
48227
- 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}`;
48228
49081
  try {
48229
- const content = pyodide.FS.readFile(p, { encoding: "utf8" });
48230
- 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
+ }
48231
49100
  } catch (err) {
48232
49101
  }
48233
49102
  }
49103
+ } catch (err) {
48234
49104
  }
48235
- } catch (err) {
48236
- }
49105
+ };
49106
+ syncBackPyodideDir("/workspace");
48237
49107
  }
48238
49108
  const durationMs = performance.now() - start;
48239
49109
  return {
@@ -48442,7 +49312,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
48442
49312
  const mount = CodeLab ? CodeLab.mount : null;
48443
49313
  const create = CodeLab ? CodeLab.create : null;
48444
49314
  const unmount = CodeLab ? CodeLab.unmount : null;
48445
- const version = CodeLab ? CodeLab.version : '0.3.1';
49315
+ const version = CodeLab ? CodeLab.version : '0.3.2';
48446
49316
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
48447
49317
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
48448
49318
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;