@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
@@ -27,7 +27,12 @@ export type DiagnosticListener = (items: DiagnosticItem[]) => void;
27
27
  export declare class DiagnosticsStore {
28
28
  private readonly items;
29
29
  private readonly listeners;
30
+ private batchDepth;
31
+ private batchDirty;
32
+ private normalizeItem;
30
33
  add(item: DiagnosticItem): void;
34
+ setMany(items: ReadonlyArray<DiagnosticItem>, clearSource?: string): void;
35
+ batch(fn: () => void): void;
31
36
  remove(id: string): void;
32
37
  clear(source?: string): void;
33
38
  getAll(): DiagnosticItem[];
@@ -4649,12 +4649,19 @@ async function getCachedAsset(key) {
4649
4649
  const db = await openToolchainIdb();
4650
4650
  if (!db) return null;
4651
4651
  return new Promise((resolve) => {
4652
+ const closeDb = () => {
4653
+ try {
4654
+ db.close();
4655
+ } catch (err) {
4656
+ }
4657
+ };
4652
4658
  try {
4653
4659
  const tx = db.transaction(IDB_STORE, "readonly");
4654
4660
  const store = tx.objectStore(IDB_STORE);
4655
4661
  const req = store.get(key);
4656
4662
  req.onsuccess = () => {
4657
4663
  const val = req.result;
4664
+ closeDb();
4658
4665
  if (val instanceof Uint8Array) {
4659
4666
  memoryAssetCache.set(key, val);
4660
4667
  resolve(val);
@@ -4666,8 +4673,12 @@ async function getCachedAsset(key) {
4666
4673
  resolve(null);
4667
4674
  }
4668
4675
  };
4669
- req.onerror = () => resolve(null);
4676
+ req.onerror = () => {
4677
+ closeDb();
4678
+ resolve(null);
4679
+ };
4670
4680
  } catch (err) {
4681
+ closeDb();
4671
4682
  if (err) resolve(null);
4672
4683
  }
4673
4684
  });
@@ -4677,13 +4688,26 @@ async function setCachedAsset(key, data) {
4677
4688
  const db = await openToolchainIdb();
4678
4689
  if (!db) return;
4679
4690
  return new Promise((resolve) => {
4691
+ const closeDb = () => {
4692
+ try {
4693
+ db.close();
4694
+ } catch (err) {
4695
+ }
4696
+ };
4680
4697
  try {
4681
4698
  const tx = db.transaction(IDB_STORE, "readwrite");
4682
4699
  const store = tx.objectStore(IDB_STORE);
4683
4700
  store.put(data, key);
4684
- tx.oncomplete = () => resolve();
4685
- tx.onerror = () => resolve();
4701
+ tx.oncomplete = () => {
4702
+ closeDb();
4703
+ resolve();
4704
+ };
4705
+ tx.onerror = () => {
4706
+ closeDb();
4707
+ resolve();
4708
+ };
4686
4709
  } catch (err) {
4710
+ closeDb();
4687
4711
  if (err) resolve();
4688
4712
  }
4689
4713
  });
@@ -4705,15 +4729,19 @@ function extractTarToVfs(tarBytes, vfs, baseDir = "/") {
4705
4729
  continue;
4706
4730
  }
4707
4731
  const sizeOctal = readString(offset + 124, 12);
4708
- const size = parseInt(sizeOctal || "0", 8) || 0;
4732
+ const size = Math.max(0, parseInt(sizeOctal || "0", 8) || 0);
4709
4733
  const typeFlag = tarBytes[offset + 156];
4710
4734
  const prefix = readString(offset + 345, 155);
4711
4735
  const fullName = prefix ? `${prefix}/${name}` : name;
4712
- const cleanRel = fullName.replace(/^\.?\/+/, "");
4713
- const targetPath = baseDir === "/" ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, "")}/${cleanRel}`;
4736
+ const rawRel = fullName.replace(/^\.?\/+/, "");
4737
+ const rawSegments = rawRel.split("/").filter(Boolean);
4738
+ const hasDotDot = rawSegments.some((seg) => seg === "..");
4739
+ const cleanRel = hasDotDot ? "" : rawSegments.filter((seg) => seg !== ".").join("/");
4740
+ const cleanBase = baseDir === "/" ? "" : baseDir.replace(/\/+$/, "");
4741
+ const targetPath = `${cleanBase}/${cleanRel}`;
4714
4742
  const dataStart = offset + 512;
4715
- const dataEnd = dataStart + size;
4716
- if (cleanRel) {
4743
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
4744
+ if (cleanRel && !hasDotDot) {
4717
4745
  if (typeFlag === 53 || fullName.endsWith("/")) {
4718
4746
  if (!vfs.existsSync(targetPath)) {
4719
4747
  vfs.mkdirSync(targetPath, { recursive: true });
@@ -5165,10 +5193,22 @@ var CppToolchainManager = class {
5165
5193
  percent: 100,
5166
5194
  message: `Compiling ${sourceFiles.map((s) => s.split("/").pop()).join(", ")} with Clang (${std}, ${optLevel})...`
5167
5195
  });
5196
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
5197
+ if (!vfs.existsSync(buildDir)) {
5198
+ vfs.mkdirSync(buildDir, { recursive: true });
5199
+ }
5200
+ const cleanupBuildDir = () => {
5201
+ try {
5202
+ if (typeof vfs.rmSync === "function") {
5203
+ vfs.rmSync(buildDir, { recursive: true, force: true });
5204
+ }
5205
+ } catch (err) {
5206
+ }
5207
+ };
5168
5208
  const objectFiles = [];
5169
5209
  for (let i = 0; i < sourceFiles.length; i++) {
5170
5210
  const srcPath = sourceFiles[i];
5171
- const objPath = `/tmp/obj_${i}.o`;
5211
+ const objPath = `${buildDir}/obj_${i}.o`;
5172
5212
  objectFiles.push(objPath);
5173
5213
  const clangArgs = [
5174
5214
  "clang++",
@@ -5203,6 +5243,7 @@ var CppToolchainManager = class {
5203
5243
  onStderr: handleErr
5204
5244
  });
5205
5245
  if (compileStep.exitCode !== 0) {
5246
+ cleanupBuildDir();
5206
5247
  return {
5207
5248
  ok: false,
5208
5249
  exitCode: compileStep.exitCode,
@@ -5242,6 +5283,7 @@ var CppToolchainManager = class {
5242
5283
  onStdout: handleOut,
5243
5284
  onStderr: handleErr
5244
5285
  });
5286
+ cleanupBuildDir();
5245
5287
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
5246
5288
  return {
5247
5289
  ok: false,
@@ -4685,12 +4685,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4685
4685
  const db = await openToolchainIdb();
4686
4686
  if (!db) return null;
4687
4687
  return new Promise((resolve) => {
4688
+ const closeDb = () => {
4689
+ try {
4690
+ db.close();
4691
+ } catch (err) {
4692
+ }
4693
+ };
4688
4694
  try {
4689
4695
  const tx = db.transaction(IDB_STORE, "readonly");
4690
4696
  const store = tx.objectStore(IDB_STORE);
4691
4697
  const req = store.get(key);
4692
4698
  req.onsuccess = () => {
4693
4699
  const val = req.result;
4700
+ closeDb();
4694
4701
  if (val instanceof Uint8Array) {
4695
4702
  memoryAssetCache.set(key, val);
4696
4703
  resolve(val);
@@ -4702,8 +4709,12 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4702
4709
  resolve(null);
4703
4710
  }
4704
4711
  };
4705
- req.onerror = () => resolve(null);
4712
+ req.onerror = () => {
4713
+ closeDb();
4714
+ resolve(null);
4715
+ };
4706
4716
  } catch (err) {
4717
+ closeDb();
4707
4718
  if (err) resolve(null);
4708
4719
  }
4709
4720
  });
@@ -4713,13 +4724,26 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4713
4724
  const db = await openToolchainIdb();
4714
4725
  if (!db) return;
4715
4726
  return new Promise((resolve) => {
4727
+ const closeDb = () => {
4728
+ try {
4729
+ db.close();
4730
+ } catch (err) {
4731
+ }
4732
+ };
4716
4733
  try {
4717
4734
  const tx = db.transaction(IDB_STORE, "readwrite");
4718
4735
  const store = tx.objectStore(IDB_STORE);
4719
4736
  store.put(data, key);
4720
- tx.oncomplete = () => resolve();
4721
- tx.onerror = () => resolve();
4737
+ tx.oncomplete = () => {
4738
+ closeDb();
4739
+ resolve();
4740
+ };
4741
+ tx.onerror = () => {
4742
+ closeDb();
4743
+ resolve();
4744
+ };
4722
4745
  } catch (err) {
4746
+ closeDb();
4723
4747
  if (err) resolve();
4724
4748
  }
4725
4749
  });
@@ -4741,15 +4765,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4741
4765
  continue;
4742
4766
  }
4743
4767
  const sizeOctal = readString(offset + 124, 12);
4744
- const size = parseInt(sizeOctal || "0", 8) || 0;
4768
+ const size = Math.max(0, parseInt(sizeOctal || "0", 8) || 0);
4745
4769
  const typeFlag = tarBytes[offset + 156];
4746
4770
  const prefix = readString(offset + 345, 155);
4747
4771
  const fullName = prefix ? `${prefix}/${name}` : name;
4748
- const cleanRel = fullName.replace(/^\.?\/+/, "");
4749
- const targetPath = baseDir === "/" ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, "")}/${cleanRel}`;
4772
+ const rawRel = fullName.replace(/^\.?\/+/, "");
4773
+ const rawSegments = rawRel.split("/").filter(Boolean);
4774
+ const hasDotDot = rawSegments.some((seg) => seg === "..");
4775
+ const cleanRel = hasDotDot ? "" : rawSegments.filter((seg) => seg !== ".").join("/");
4776
+ const cleanBase = baseDir === "/" ? "" : baseDir.replace(/\/+$/, "");
4777
+ const targetPath = `${cleanBase}/${cleanRel}`;
4750
4778
  const dataStart = offset + 512;
4751
- const dataEnd = dataStart + size;
4752
- if (cleanRel) {
4779
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
4780
+ if (cleanRel && !hasDotDot) {
4753
4781
  if (typeFlag === 53 || fullName.endsWith("/")) {
4754
4782
  if (!vfs.existsSync(targetPath)) {
4755
4783
  vfs.mkdirSync(targetPath, { recursive: true });
@@ -5201,10 +5229,22 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5201
5229
  percent: 100,
5202
5230
  message: `Compiling ${sourceFiles.map((s) => s.split("/").pop()).join(", ")} with Clang (${std}, ${optLevel})...`
5203
5231
  });
5232
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
5233
+ if (!vfs.existsSync(buildDir)) {
5234
+ vfs.mkdirSync(buildDir, { recursive: true });
5235
+ }
5236
+ const cleanupBuildDir = () => {
5237
+ try {
5238
+ if (typeof vfs.rmSync === "function") {
5239
+ vfs.rmSync(buildDir, { recursive: true, force: true });
5240
+ }
5241
+ } catch (err) {
5242
+ }
5243
+ };
5204
5244
  const objectFiles = [];
5205
5245
  for (let i = 0; i < sourceFiles.length; i++) {
5206
5246
  const srcPath = sourceFiles[i];
5207
- const objPath = `/tmp/obj_${i}.o`;
5247
+ const objPath = `${buildDir}/obj_${i}.o`;
5208
5248
  objectFiles.push(objPath);
5209
5249
  const clangArgs = [
5210
5250
  "clang++",
@@ -5239,6 +5279,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5239
5279
  onStderr: handleErr
5240
5280
  });
5241
5281
  if (compileStep.exitCode !== 0) {
5282
+ cleanupBuildDir();
5242
5283
  return {
5243
5284
  ok: false,
5244
5285
  exitCode: compileStep.exitCode,
@@ -5278,6 +5319,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5278
5319
  onStdout: handleOut,
5279
5320
  onStderr: handleErr
5280
5321
  });
5322
+ cleanupBuildDir();
5281
5323
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
5282
5324
  return {
5283
5325
  ok: false,
@@ -5035,68 +5035,73 @@ var PythonToolchainManager = class {
5035
5035
  if (this.pyodide) return this.pyodide;
5036
5036
  if (this._loadingPromise) return this._loadingPromise;
5037
5037
  this._loadingPromise = (async () => {
5038
- this._emitProgress({
5039
- stage: "downloading",
5040
- percent: 10,
5041
- message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
5042
- });
5043
- if (typeof window !== "undefined") {
5044
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
5045
- if (!window.loadPyodide) {
5046
- await new Promise((resolve, reject) => {
5047
- const script = document.createElement("script");
5048
- script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
5049
- script.onload = () => resolve();
5050
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
5051
- document.head.appendChild(script);
5052
- });
5053
- }
5038
+ try {
5054
5039
  this._emitProgress({
5055
- stage: "extracting",
5056
- percent: 50,
5057
- message: "Bootstrapping Python runtime environment..."
5040
+ stage: "downloading",
5041
+ percent: 10,
5042
+ message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
5058
5043
  });
5059
- const loadPyodideFn = window.loadPyodide;
5060
- this.pyodide = await loadPyodideFn({
5061
- indexURL: cdn
5062
- });
5063
- } else {
5064
- this.pyodide = {
5065
- FS: {
5066
- files: /* @__PURE__ */ new Map(),
5067
- writeFile(p, content) {
5068
- this.files.set(p, typeof content === "string" ? content : String(content));
5069
- },
5070
- readFile(p, opts) {
5071
- return this.files.get(p) || "";
5072
- },
5073
- unlink(p) {
5074
- this.files.delete(p);
5044
+ if (typeof window !== "undefined") {
5045
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
5046
+ if (!window.loadPyodide) {
5047
+ await new Promise((resolve, reject) => {
5048
+ const script = document.createElement("script");
5049
+ script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
5050
+ script.onload = () => resolve();
5051
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
5052
+ document.head.appendChild(script);
5053
+ });
5054
+ }
5055
+ this._emitProgress({
5056
+ stage: "extracting",
5057
+ percent: 50,
5058
+ message: "Bootstrapping Python runtime environment..."
5059
+ });
5060
+ const loadPyodideFn = window.loadPyodide;
5061
+ this.pyodide = await loadPyodideFn({
5062
+ indexURL: cdn
5063
+ });
5064
+ } else {
5065
+ this.pyodide = {
5066
+ FS: {
5067
+ files: /* @__PURE__ */ new Map(),
5068
+ writeFile(p, content) {
5069
+ this.files.set(p, typeof content === "string" ? content : String(content));
5070
+ },
5071
+ readFile(p, opts) {
5072
+ return this.files.get(p) || "";
5073
+ },
5074
+ unlink(p) {
5075
+ this.files.delete(p);
5076
+ },
5077
+ mkdirTree(_p) {
5078
+ }
5075
5079
  },
5076
- mkdirTree(_p) {
5080
+ runPythonAsync: async (code) => {
5081
+ return `Execution mock: ${code.slice(0, 30)}`;
5077
5082
  }
5078
- },
5079
- runPythonAsync: async (code) => {
5080
- return `Execution mock: ${code.slice(0, 30)}`;
5081
- }
5082
- };
5083
- }
5084
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
5085
- for (const pkg of this.options.preloadPackages) {
5086
- try {
5087
- if (typeof this.pyodide.loadPackage === "function") {
5088
- await this.pyodide.loadPackage(pkg);
5083
+ };
5084
+ }
5085
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
5086
+ for (const pkg of this.options.preloadPackages) {
5087
+ try {
5088
+ if (typeof this.pyodide.loadPackage === "function") {
5089
+ await this.pyodide.loadPackage(pkg);
5090
+ }
5091
+ } catch (err) {
5089
5092
  }
5090
- } catch (err) {
5091
5093
  }
5092
5094
  }
5095
+ this._emitProgress({
5096
+ stage: "ready",
5097
+ percent: 100,
5098
+ message: "Python 3.12 WebAssembly Toolchain Ready"
5099
+ });
5100
+ return this.pyodide;
5101
+ } catch (err) {
5102
+ this._loadingPromise = null;
5103
+ throw err;
5093
5104
  }
5094
- this._emitProgress({
5095
- stage: "ready",
5096
- percent: 100,
5097
- message: "Python 3.12 WebAssembly Toolchain Ready"
5098
- });
5099
- return this.pyodide;
5100
5105
  })();
5101
5106
  return this._loadingPromise;
5102
5107
  }
@@ -5140,18 +5145,34 @@ var PythonToolchainManager = class {
5140
5145
  };
5141
5146
  const pyodide = await this.ensureLoaded();
5142
5147
  if (req.vfs && pyodide.FS) {
5143
- try {
5144
- const vfsEntries = req.vfs.readdirSync("/workspace", { recursive: true });
5145
- for (const entry of vfsEntries) {
5146
- const fullPath = `/workspace/${entry}`;
5147
- if (!req.vfs.statSync(fullPath).isDirectory()) {
5148
- const content = req.vfs.readFileSync(fullPath, "utf8");
5149
- pyodide.FS.mkdirTree("/workspace");
5150
- pyodide.FS.writeFile(fullPath, content);
5148
+ const syncVfsDir = (dirPath) => {
5149
+ try {
5150
+ if (typeof pyodide.FS.mkdirTree === "function") {
5151
+ pyodide.FS.mkdirTree(dirPath);
5151
5152
  }
5153
+ const entries = req.vfs.readdirSync(dirPath);
5154
+ for (const entry of entries) {
5155
+ if (!entry || entry === "." || entry === "..") continue;
5156
+ const fullPath = `${dirPath === "/" ? "" : dirPath}/${entry}`;
5157
+ try {
5158
+ const st = req.vfs.statSync(fullPath);
5159
+ if (st && typeof st.isDirectory === "function" && st.isDirectory()) {
5160
+ syncVfsDir(fullPath);
5161
+ } else {
5162
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf("/")) || "/workspace";
5163
+ if (typeof pyodide.FS.mkdirTree === "function") {
5164
+ pyodide.FS.mkdirTree(parentDir);
5165
+ }
5166
+ const content = req.vfs.readFileSync(fullPath, "utf8");
5167
+ pyodide.FS.writeFile(fullPath, content);
5168
+ }
5169
+ } catch (err) {
5170
+ }
5171
+ }
5172
+ } catch (err) {
5152
5173
  }
5153
- } catch (err) {
5154
- }
5174
+ };
5175
+ syncVfsDir("/workspace");
5155
5176
  }
5156
5177
  if (pyodide.FS) {
5157
5178
  try {
@@ -5197,45 +5218,19 @@ var PythonToolchainManager = class {
5197
5218
  }
5198
5219
  });
5199
5220
  }
5200
- const rawLines = codeToRun.split("\n");
5201
- const futureImports = [];
5202
- const bodyLines = [];
5203
- let inDocstring = false;
5204
- let docChar = "";
5205
- for (const l of rawLines) {
5206
- const t = l.trim();
5207
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
5208
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
5209
- bodyLines.push(l);
5210
- continue;
5211
- }
5212
- inDocstring = true;
5213
- docChar = t.slice(0, 3);
5214
- bodyLines.push(l);
5215
- continue;
5216
- }
5217
- if (inDocstring) {
5218
- if (t.endsWith(docChar)) inDocstring = false;
5219
- bodyLines.push(l);
5220
- continue;
5221
- }
5222
- if (/^from\s+__future__\s+import\s+/.test(t)) {
5223
- futureImports.push(t);
5224
- } else {
5225
- bodyLines.push(l);
5226
- }
5227
- }
5221
+ const fileLabel = JSON.stringify(req.entry || "<exec>");
5222
+ const encodedCode = JSON.stringify(codeToRun);
5228
5223
  const runnerWrapper = `
5229
- ${futureImports.join("\n")}
5230
5224
  import sys, tracemalloc
5231
5225
  if '/usr/lib/python' not in sys.path:
5232
5226
  sys.path.insert(0, '/usr/lib/python')
5233
5227
  if '/workspace' not in sys.path:
5234
5228
  sys.path.insert(0, '/workspace')
5235
5229
 
5230
+ _cl_user_code = ${encodedCode}
5236
5231
  tracemalloc.start()
5237
5232
  try:
5238
- ${bodyLines.map((l) => " " + l).join("\n")}
5233
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
5239
5234
  finally:
5240
5235
  _, _peak = tracemalloc.get_traced_memory()
5241
5236
  tracemalloc.stop()
@@ -5278,20 +5273,38 @@ finally:
5278
5273
  }
5279
5274
  }
5280
5275
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === "function") {
5281
- try {
5282
- const files = pyodide.FS.readdir("/workspace");
5283
- for (const f of files) {
5284
- if (f !== "." && f !== "..") {
5285
- const p = `/workspace/${f}`;
5276
+ const syncBackPyodideDir = (dirPath) => {
5277
+ try {
5278
+ const entries = pyodide.FS.readdir(dirPath);
5279
+ for (const f of entries) {
5280
+ if (!f || f === "." || f === "..") continue;
5281
+ const p = `${dirPath}/${f}`;
5286
5282
  try {
5287
- const content = pyodide.FS.readFile(p, { encoding: "utf8" });
5288
- req.vfs.writeFileSync(p, content);
5283
+ let isDir = false;
5284
+ if (typeof pyodide.FS.stat === "function" && typeof pyodide.FS.isDir === "function") {
5285
+ const st = pyodide.FS.stat(p);
5286
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
5287
+ }
5288
+ if (isDir) {
5289
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(p)) {
5290
+ req.vfs.mkdirSync(p, { recursive: true });
5291
+ }
5292
+ syncBackPyodideDir(p);
5293
+ } else {
5294
+ const parentDir = p.slice(0, p.lastIndexOf("/")) || "/workspace";
5295
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(parentDir)) {
5296
+ req.vfs.mkdirSync(parentDir, { recursive: true });
5297
+ }
5298
+ const content = pyodide.FS.readFile(p, { encoding: "utf8" });
5299
+ req.vfs.writeFileSync(p, content);
5300
+ }
5289
5301
  } catch (err) {
5290
5302
  }
5291
5303
  }
5304
+ } catch (err) {
5292
5305
  }
5293
- } catch (err) {
5294
- }
5306
+ };
5307
+ syncBackPyodideDir("/workspace");
5295
5308
  }
5296
5309
  const durationMs = performance.now() - start;
5297
5310
  return {