@innovatorved/code-lab 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/ARCHITECTURE.md +8 -4
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +70 -158
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +298 -2
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +35284 -18253
  12. package/dist/code-lab.js +40434 -23431
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/diagnostics.d.ts +5 -0
  15. package/dist/extensions/cpp.esm.js +19532 -3772
  16. package/dist/extensions/cpp.js +19529 -3769
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19666 -3843
  21. package/dist/extensions/python.js +19668 -3845
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  58. package/dist/packages/ui/src/themes.d.ts +35 -0
  59. package/dist/preview-sw.js +82 -24
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +503 -73
  62. package/dist/runtime.js +501 -73
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +13 -2
  67. package/dist/search.d.ts +5 -1
  68. package/dist/shell.d.ts +1 -1
  69. package/dist/shell.esm.js +435 -54
  70. package/dist/shell.js +435 -54
  71. package/dist/terminal.esm.js +242 -54
  72. package/dist/terminal.js +242 -54
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/dist/zip.d.ts +4 -3
  77. package/package.json +37 -8
  78. package/packages/commands/README.md +7 -0
  79. package/packages/commands/package.json +16 -0
  80. package/packages/commands/src/index.ts +467 -0
  81. package/packages/commands/tsconfig.json +22 -0
  82. package/packages/core/README.md +12 -0
  83. package/packages/core/package.json +13 -0
  84. package/packages/core/src/di.ts +147 -0
  85. package/packages/core/src/disposable.ts +112 -0
  86. package/packages/core/src/errors.ts +205 -0
  87. package/packages/core/src/events.ts +157 -0
  88. package/packages/core/src/index.ts +49 -0
  89. package/packages/core/src/path.ts +118 -0
  90. package/packages/core/src/registry.ts +61 -0
  91. package/packages/core/tsconfig.json +19 -0
  92. package/packages/editor/README.md +9 -0
  93. package/packages/editor/package.json +18 -0
  94. package/packages/editor/src/index.ts +344 -0
  95. package/packages/editor/tsconfig.json +24 -0
  96. package/packages/fs/README.md +7 -0
  97. package/packages/fs/package.json +16 -0
  98. package/packages/fs/src/backends.ts +301 -0
  99. package/packages/fs/src/index.ts +18 -0
  100. package/packages/fs/src/types.ts +44 -0
  101. package/packages/fs/src/vfs-service.ts +257 -0
  102. package/packages/fs/tsconfig.json +22 -0
  103. package/packages/preview/README.md +3 -0
  104. package/packages/preview/package.json +16 -0
  105. package/packages/preview/src/index.ts +125 -0
  106. package/packages/preview/tsconfig.json +22 -0
  107. package/packages/runtime/README.md +3 -0
  108. package/packages/runtime/package.json +17 -0
  109. package/packages/runtime/src/index.ts +134 -0
  110. package/packages/runtime/tsconfig.json +23 -0
  111. package/packages/settings/README.md +7 -0
  112. package/packages/settings/package.json +16 -0
  113. package/packages/settings/src/builtin-schemas.ts +235 -0
  114. package/packages/settings/src/configuration-service.ts +543 -0
  115. package/packages/settings/src/index.ts +37 -0
  116. package/packages/settings/src/jsonc.ts +189 -0
  117. package/packages/settings/src/schema.ts +164 -0
  118. package/packages/settings/tsconfig.json +22 -0
  119. package/packages/sql/README.md +12 -0
  120. package/packages/sql/package.json +13 -0
  121. package/packages/sql/src/completions.ts +359 -0
  122. package/packages/sql/src/diagnostics.ts +200 -0
  123. package/packages/sql/src/formatter.ts +271 -0
  124. package/packages/sql/src/index.ts +54 -0
  125. package/packages/sql/src/sql-editor.ts +802 -0
  126. package/packages/sql/src/styles.ts +501 -0
  127. package/packages/sql/src/tokenizer.ts +457 -0
  128. package/packages/sql/src/types.ts +148 -0
  129. package/packages/sql/tsconfig.json +19 -0
  130. package/packages/terminal/README.md +3 -0
  131. package/packages/terminal/package.json +16 -0
  132. package/packages/terminal/src/index.ts +183 -0
  133. package/packages/terminal/tsconfig.json +22 -0
  134. package/packages/ui/README.md +8 -0
  135. package/packages/ui/package.json +18 -0
  136. package/packages/ui/src/index.ts +36 -0
  137. package/packages/ui/src/observability.ts +175 -0
  138. package/packages/ui/src/plugin-registry.ts +274 -0
  139. package/packages/ui/src/settings-dialog.ts +293 -0
  140. package/packages/ui/src/themes.ts +174 -0
  141. package/packages/ui/tsconfig.json +24 -0
  142. package/src/code-lab.css +298 -2
  143. package/src/csp.ts +7 -10
  144. package/src/diagnostics.ts +42 -3
  145. package/src/extensions/cpp.ts +105 -24
  146. package/src/extensions/python.ts +260 -116
  147. package/src/extensions/umbrella.ts +5 -0
  148. package/src/index.ts +1 -1
  149. package/src/modular-kernel.ts +11 -0
  150. package/src/preview-sw.js +73 -12
  151. package/src/runtime.ts +501 -74
  152. package/src/schemas.ts +62 -62
  153. package/src/scm.ts +106 -19
  154. package/src/search.ts +71 -27
  155. package/src/shell.ts +433 -53
  156. package/src/terminal.ts +239 -52
  157. package/src/workbench/diff-editor.ts +106 -18
  158. package/src/workbench/drawer.ts +17 -4
  159. package/src/workbench/guided-pane.ts +12 -2
  160. package/src/workbench/icons.ts +5 -2
  161. package/src/workbench/share.ts +37 -8
  162. package/src/workbench/styles.ts +2 -1
  163. package/src/workbench/toolbar.ts +15 -4
  164. package/src/workbench.ts +2877 -284
  165. package/src/zip.ts +29 -7
  166. package/dist/runtime/index.d.ts +0 -4
  167. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  168. package/dist/shell/index.d.ts +0 -4
  169. package/src/runtime/index.ts +0 -5
  170. package/src/shell/coreutils/compilers-cli.ts +0 -103
  171. package/src/shell/index.ts +0 -5
package/dist/runtime.js CHANGED
@@ -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.4.0 — 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
@@ -87,6 +87,7 @@ var CodeLabLogger = (() => {
87
87
  } catch (err) {
88
88
  sinkError = err;
89
89
  }
90
+ void sinkError;
90
91
  }
91
92
  const consoleObj = typeof console !== "undefined" ? console : null;
92
93
  const fn = consoleObj ? consoleObj[level] : null;
@@ -1135,22 +1136,40 @@ function __initVirtualRuntime(rootScope) {
1135
1136
  // =========================================================================
1136
1137
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1137
1138
  // =========================================================================
1138
- function createVirtualFs(initialFiles = {}) {
1139
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1139
1140
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1140
1141
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1141
1142
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1143
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1144
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1145
+ const customCwdGetter = typeof vfsOptions === 'function'
1146
+ ? vfsOptions
1147
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1142
1148
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1143
1149
  let nextFd = 10;
1144
1150
  let nextIno = 100;
1145
1151
  let mkdtempCounter = 1;
1146
1152
 
1153
+ function recordDeletedForInspector(p, data, mtimeMs) {
1154
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1155
+ if (deletedInspectorCache.has(p)) {
1156
+ deletedInspectorCache.delete(p);
1157
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1158
+ const oldestKey = deletedInspectorCache.keys().next().value;
1159
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1160
+ }
1161
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1162
+ }
1163
+
1147
1164
  function normPath(p) {
1148
1165
  if (typeof p !== 'string' || !p) {
1149
1166
  const err = new TypeError('path must be a non-empty string');
1150
1167
  err.code = 'ERR_INVALID_ARG_TYPE';
1151
1168
  throw err;
1152
1169
  }
1153
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1170
+ const baseCwd = typeof customCwdGetter === 'function'
1171
+ ? customCwdGetter()
1172
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1154
1173
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1155
1174
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1156
1175
  }
@@ -1201,9 +1220,13 @@ function __initVirtualRuntime(rootScope) {
1201
1220
  for (const [relPath, content] of Object.entries(initialFiles)) {
1202
1221
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1203
1222
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1204
- const fullPath = isSystemPath
1223
+ let fullPath = isSystemPath
1205
1224
  ? normPath(relPath)
1206
1225
  : normPath(`/workspace/${cleanRel}`);
1226
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1227
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1228
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1229
+ }
1207
1230
  ensureParentDirs(fullPath);
1208
1231
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1209
1232
  files.set(fullPath, {
@@ -1216,7 +1239,13 @@ function __initVirtualRuntime(rootScope) {
1216
1239
  });
1217
1240
  }
1218
1241
 
1242
+ let _activeStdin = '';
1243
+
1219
1244
  const fsShim = {
1245
+ _setActiveStdin(text) {
1246
+ _activeStdin = text !== undefined && text !== null ? String(text) : '';
1247
+ },
1248
+
1220
1249
  existsSync(p) {
1221
1250
  try {
1222
1251
  const np = normPath(p);
@@ -1383,13 +1412,6 @@ function __initVirtualRuntime(rootScope) {
1383
1412
  fsyncSync(fd) {
1384
1413
  const entry = fdTable.get(fd);
1385
1414
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1386
- if (!entry.isDirectory && entry.inode) {
1387
- deletedInspectorCache.set(entry.path, {
1388
- data: entry.inode.data.slice(),
1389
- mtimeMs: entry.inode.mtimeMs,
1390
- deletedAtMs: null
1391
- });
1392
- }
1393
1415
  },
1394
1416
 
1395
1417
  fdatasyncSync(fd) {
@@ -1430,12 +1452,6 @@ function __initVirtualRuntime(rootScope) {
1430
1452
  inode.mtimeMs = Date.now();
1431
1453
  entry.pos = writePos + chunk.byteLength;
1432
1454
 
1433
- deletedInspectorCache.set(entry.path, {
1434
- data: inode.data.slice(),
1435
- mtimeMs: inode.mtimeMs,
1436
- deletedAtMs: null
1437
- });
1438
-
1439
1455
  return chunk.byteLength;
1440
1456
  },
1441
1457
 
@@ -1454,6 +1470,11 @@ function __initVirtualRuntime(rootScope) {
1454
1470
  },
1455
1471
 
1456
1472
  readFileSync(p, opts) {
1473
+ if (p === 0 || p === '/dev/stdin') {
1474
+ const stdinBuf = VirtualBuffer.from(String(_activeStdin || ''), 'utf8');
1475
+ const encoding = typeof opts === 'string' ? opts : (opts && opts.encoding);
1476
+ return encoding ? stdinBuf.toString(encoding) : stdinBuf;
1477
+ }
1457
1478
  const np = normPath(p);
1458
1479
  if (dirs.has(np)) throw fsError('EISDIR', 'read', p, 'illegal operation on a directory');
1459
1480
  const inode = files.get(np);
@@ -1487,7 +1508,7 @@ function __initVirtualRuntime(rootScope) {
1487
1508
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1488
1509
  }
1489
1510
  }
1490
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1511
+ deletedInspectorCache.delete(np);
1491
1512
  },
1492
1513
 
1493
1514
  chmodSync(p, mode) {
@@ -1516,7 +1537,7 @@ function __initVirtualRuntime(rootScope) {
1516
1537
  combined.set(chunk, inode.data.byteLength);
1517
1538
  inode.data = combined;
1518
1539
  inode.mtimeMs = Date.now();
1519
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1540
+ deletedInspectorCache.delete(np);
1520
1541
  },
1521
1542
 
1522
1543
  truncateSync(p, len = 0) {
@@ -1532,7 +1553,6 @@ function __initVirtualRuntime(rootScope) {
1532
1553
  inode.data = grown;
1533
1554
  }
1534
1555
  inode.mtimeMs = Date.now();
1535
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1536
1556
  },
1537
1557
 
1538
1558
  renameSync(oldP, newP) {
@@ -1593,16 +1613,14 @@ function __initVirtualRuntime(rootScope) {
1593
1613
  if (fdEntry.path === src) fdEntry.path = dst;
1594
1614
  }
1595
1615
  deletedInspectorCache.delete(src);
1596
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1616
+ deletedInspectorCache.delete(dst);
1597
1617
  },
1598
1618
 
1599
1619
  unlinkSync(p) {
1600
1620
  const np = normPath(p);
1601
1621
  const inode = files.get(np);
1602
1622
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1603
- if (inode.data.byteLength > 0) {
1604
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1605
- }
1623
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1606
1624
  files.delete(np);
1607
1625
  },
1608
1626
 
@@ -1619,9 +1637,7 @@ function __initVirtualRuntime(rootScope) {
1619
1637
  for (const [fPath, inode] of Array.from(files.entries())) {
1620
1638
  if (fPath.startsWith(prefix)) {
1621
1639
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1622
- if (inode.data.byteLength > 0) {
1623
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1624
- }
1640
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1625
1641
  files.delete(fPath);
1626
1642
  }
1627
1643
  }
@@ -1818,6 +1834,10 @@ function __initVirtualRuntime(rootScope) {
1818
1834
 
1819
1835
  items.sort((a, b) => a.path.localeCompare(b.path));
1820
1836
  return items;
1837
+ },
1838
+
1839
+ _listOpenFds() {
1840
+ return Array.from(fdTable.keys());
1821
1841
  }
1822
1842
  };
1823
1843
 
@@ -1972,6 +1992,13 @@ function __initVirtualRuntime(rootScope) {
1972
1992
  };
1973
1993
 
1974
1994
  fsShim.promises = fsPromises;
1995
+ fsShim._exportRawState = () => {
1996
+ const clonedFiles = new Map();
1997
+ for (const [k, v] of files.entries()) {
1998
+ clonedFiles.set(k, v.data instanceof Uint8Array ? v.data.slice() : new Uint8Array(v.data || 0));
1999
+ }
2000
+ return { files: clonedFiles, dirs: new Set(dirs) };
2001
+ };
1975
2002
 
1976
2003
  return fsShim;
1977
2004
  }
@@ -3195,6 +3222,7 @@ function __initVirtualRuntime(rootScope) {
3195
3222
  responseHeaders: {},
3196
3223
  _t0: performance.now()
3197
3224
  };
3225
+ if (httpTrace.length >= 500) httpTrace.shift();
3198
3226
  httpTrace.push(traceEntry);
3199
3227
  this._traceEntry = traceEntry;
3200
3228
 
@@ -4186,6 +4214,7 @@ function __initVirtualRuntime(rootScope) {
4186
4214
  this._peer = serverSocket;
4187
4215
  this.connecting = false;
4188
4216
 
4217
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4189
4218
  sharedTrace.push({
4190
4219
  protocol: 'TCP',
4191
4220
  event: 'connect',
@@ -4700,13 +4729,17 @@ function __initVirtualRuntime(rootScope) {
4700
4729
  function transpileTS(source, filename = 'module.ts', opts = {}) {
4701
4730
  // `keepEsm` leaves `import`/`export` statements intact so the output can run
4702
4731
  // natively in a browser as an ES module (used by the built-in preview server).
4703
- const keepEsm = Boolean(opts && opts.keepEsm);
4704
- const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
4732
+ const keepEsm = Boolean(opts && (opts.keepEsm || opts.expressionOnly));
4733
+ const expressionOnly = Boolean(opts && opts.expressionOnly);
4734
+ const isTS = expressionOnly
4735
+ || /\.(ts|tsx|mts|cts)$/i.test(filename)
4705
4736
  || /^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(source);
4706
- const hasESM = /^\s*(?:import|export)\b/m.test(source)
4737
+ const hasESM = !expressionOnly && (
4738
+ /^\s*(?:import|export)\b/m.test(source)
4707
4739
  || /\bexport\s*\{/.test(source)
4708
4740
  || /\bimport\s*\{/.test(source)
4709
- || /\bexport\s+default\b/.test(source);
4741
+ || /\bexport\s+default\b/.test(source)
4742
+ );
4710
4743
  const hasJsx = detectJsxSyntax(source, filename);
4711
4744
  if (!isTS && !hasESM && !hasJsx) return source;
4712
4745
 
@@ -4714,7 +4747,7 @@ function __initVirtualRuntime(rootScope) {
4714
4747
  if (hasJsx) {
4715
4748
  const { pragma, frag } = readJsxPragma(source);
4716
4749
  const hasReactBinding = /\bimport\s+(?!type\b)(?:\*\s+as\s+React\b|React\b)|(?:\bconst|\blet|\bvar|\bfunction|\bclass)\s+React\b|\bReact\s*=/.test(source);
4717
- const needsReact = pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4750
+ const needsReact = !expressionOnly && pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4718
4751
  const transformed = jsxTransform(source, { pragma, frag });
4719
4752
  if (transformed !== source) {
4720
4753
  source = transformed;
@@ -4802,18 +4835,80 @@ function __initVirtualRuntime(rootScope) {
4802
4835
  i = j;
4803
4836
  continue;
4804
4837
  }
4805
- // Template literal
4838
+ // Template literal (recursively transpile TypeScript inside ${...} expressions)
4806
4839
  if (ch === '`') {
4807
4840
  let j = i + 1;
4808
- let depth = 0;
4841
+ let rebuilt = '`';
4809
4842
  while (j < len) {
4810
- if (source[j] === '\\') { j += 2; continue; }
4811
- if (source[j] === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4812
- if (source[j] === '}' && depth > 0) { depth--; j++; continue; }
4813
- if (source[j] === '`' && depth === 0) { j++; break; }
4843
+ if (source[j] === '\\') {
4844
+ rebuilt += source.slice(j, j + 2);
4845
+ j += 2;
4846
+ continue;
4847
+ }
4848
+ if (source[j] === '`' ) {
4849
+ rebuilt += '`';
4850
+ j++;
4851
+ break;
4852
+ }
4853
+ if (source[j] === '$' && source[j + 1] === '{') {
4854
+ j += 2;
4855
+ const exprStart = j;
4856
+ let braceDepth = 1;
4857
+ while (j < len && braceDepth > 0) {
4858
+ const ec = source[j];
4859
+ const en = source[j + 1];
4860
+ if (ec === '/' && en === '/') {
4861
+ j += 2;
4862
+ while (j < len && source[j] !== '\n') j++;
4863
+ continue;
4864
+ }
4865
+ if (ec === '/' && en === '*') {
4866
+ j += 2;
4867
+ while (j < len && !(source[j] === '*' && source[j + 1] === '/')) j++;
4868
+ j += 2;
4869
+ continue;
4870
+ }
4871
+ if (ec === "'" || ec === '"') {
4872
+ const q = ec;
4873
+ j++;
4874
+ while (j < len && source[j] !== q && source[j] !== '\n') {
4875
+ if (source[j] === '\\') j += 2;
4876
+ else j++;
4877
+ }
4878
+ if (j < len && source[j] === q) j++;
4879
+ continue;
4880
+ }
4881
+ if (ec === '`') {
4882
+ j++;
4883
+ let nestedDepth = 0;
4884
+ while (j < len) {
4885
+ if (source[j] === '\\') { j += 2; continue; }
4886
+ if (source[j] === '$' && source[j + 1] === '{') { nestedDepth++; j += 2; continue; }
4887
+ if (source[j] === '}' && nestedDepth > 0) { nestedDepth--; j++; continue; }
4888
+ if (source[j] === '`' && nestedDepth === 0) { j++; break; }
4889
+ j++;
4890
+ }
4891
+ continue;
4892
+ }
4893
+ if (ec === '{') braceDepth++;
4894
+ else if (ec === '}') {
4895
+ braceDepth--;
4896
+ if (braceDepth === 0) break;
4897
+ }
4898
+ j++;
4899
+ }
4900
+ const rawExpr = source.slice(exprStart, j);
4901
+ const transpiledExpr = isTS
4902
+ ? transpileTS(rawExpr, filename, { expressionOnly: true })
4903
+ : rawExpr;
4904
+ rebuilt += '${' + transpiledExpr + '}';
4905
+ if (j < len && source[j] === '}') j++;
4906
+ continue;
4907
+ }
4908
+ rebuilt += source[j];
4814
4909
  j++;
4815
4910
  }
4816
- code += mask(source.slice(i, j));
4911
+ code += mask(rebuilt);
4817
4912
  i = j;
4818
4913
  continue;
4819
4914
  }
@@ -5187,8 +5282,8 @@ function __initVirtualRuntime(rootScope) {
5187
5282
  };
5188
5283
  code = stripReturnTypes(code);
5189
5284
 
5190
- // Strip parameter type annotations inside `(...)` (supports multi-line parameter lists and default value `()` calls)
5191
- code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, (full, inner) => {
5285
+ // Strip parameter type annotations inside `(...)` from innermost parens outward so nested callbacks work
5286
+ const stripParensParamTypes = (full, inner) => {
5192
5287
  if (!inner.includes(':')) return full;
5193
5288
  if (inner.includes('?') && !/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(inner)) return full;
5194
5289
  if (/[{}]/.test(inner) && !/\}\s*\??\s*:/.test(inner) && !/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(inner)) {
@@ -5202,7 +5297,12 @@ function __initVirtualRuntime(rootScope) {
5202
5297
  const parts = splitTopLevel(inner, ',');
5203
5298
  const cleaned = parts.map((part) => cleanSingleParam(part));
5204
5299
  return `(${cleaned.join(',')})`;
5205
- });
5300
+ };
5301
+ do {
5302
+ prevCode = code;
5303
+ code = code.replace(/\(([^()]*)\)/g, stripParensParamTypes);
5304
+ } while (code !== prevCode);
5305
+ code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, stripParensParamTypes);
5206
5306
 
5207
5307
  // Strip variable type annotations: `const x: Type =`, `let y: Type =`
5208
5308
  code = code.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g, '$1 $2 =');
@@ -5333,7 +5433,31 @@ function __initVirtualRuntime(rootScope) {
5333
5433
  hasEsmExport = true;
5334
5434
  return `Object.assign(exports, require(${mod.trim()}));`;
5335
5435
  });
5336
- code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5436
+ const collectBindingIds = (pattern) => {
5437
+ const ids = [];
5438
+ const inner = pattern.trim().replace(/^[\[{]|[\]}]$/g, '');
5439
+ const isObj = pattern.trim().startsWith('{');
5440
+ for (const rawPart of splitTopLevel(inner, ',')) {
5441
+ let part = rawPart.trim();
5442
+ if (!part) continue;
5443
+ if (part.startsWith('...')) {
5444
+ part = part.slice(3).trim();
5445
+ } else if (isObj && part.includes(':')) {
5446
+ const colonIdx = part.indexOf(':');
5447
+ part = part.slice(colonIdx + 1).trim();
5448
+ }
5449
+ const eqIdx = part.indexOf('=');
5450
+ if (eqIdx !== -1) part = part.slice(0, eqIdx).trim();
5451
+ if ((part.startsWith('{') && part.endsWith('}')) || (part.startsWith('[') && part.endsWith(']'))) {
5452
+ ids.push(...collectBindingIds(part));
5453
+ } else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part)) {
5454
+ ids.push(part);
5455
+ }
5456
+ }
5457
+ return ids;
5458
+ };
5459
+
5460
+ code = code.replace(/\bexport\s+default\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5337
5461
  hasEsmExport = true;
5338
5462
  defaultExportName = name;
5339
5463
  return `${kw} ${name}`;
@@ -5342,11 +5466,16 @@ function __initVirtualRuntime(rootScope) {
5342
5466
  hasEsmExport = true;
5343
5467
  return 'exports.default = ';
5344
5468
  });
5345
- code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5469
+ code = code.replace(/\bexport\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5346
5470
  hasEsmExport = true;
5347
5471
  exportedNames.push(name);
5348
5472
  return `${kw} ${name}`;
5349
5473
  });
5474
+ code = code.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm, (_, kw, pat) => {
5475
+ hasEsmExport = true;
5476
+ exportedNames.push(...collectBindingIds(pat));
5477
+ return `${kw} ${pat} =`;
5478
+ });
5350
5479
  code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5351
5480
  hasEsmExport = true;
5352
5481
  exportedNames.push(name);
@@ -6478,7 +6607,16 @@ function __initVirtualRuntime(rootScope) {
6478
6607
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6479
6608
  resourceTracker.pid = pid;
6480
6609
 
6481
- const vfs = optVfs || createVirtualFs(files);
6610
+ const prevCwdGetter = _activeCwdGetter;
6611
+ let currentCwd = (typeof options.cwd === 'string' && options.cwd.trim())
6612
+ ? VirtualPath.resolve('/workspace', options.cwd.trim())
6613
+ : '/workspace';
6614
+ _activeCwdGetter = () => currentCwd;
6615
+
6616
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6617
+ const initialOpenFds = typeof vfs._listOpenFds === 'function'
6618
+ ? new Set(vfs._listOpenFds())
6619
+ : null;
6482
6620
  if (optVfs && files && typeof files === 'object') {
6483
6621
  for (const [fPath, content] of Object.entries(files)) {
6484
6622
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6491,6 +6629,9 @@ function __initVirtualRuntime(rootScope) {
6491
6629
  }
6492
6630
  }
6493
6631
  }
6632
+ if (typeof vfs._setActiveStdin === 'function') {
6633
+ vfs._setActiveStdin(options && options.stdin ? String(options.stdin) : '');
6634
+ }
6494
6635
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
6495
6636
  const vnet = createVirtualNet(resourceTracker, vhttp.getTrace());
6496
6637
 
@@ -6513,6 +6654,10 @@ function __initVirtualRuntime(rootScope) {
6513
6654
  }
6514
6655
  }
6515
6656
 
6657
+ const initialVfsState = (options && options._captureVfsDiff && typeof vfs._exportRawState === 'function')
6658
+ ? vfs._exportRawState()
6659
+ : null;
6660
+
6516
6661
  // Custom timer wrappers supporting .unref() / .ref() and active handle tracking
6517
6662
  function makeTimerHandle(rawId, isInterval) {
6518
6663
  const handle = {
@@ -6872,11 +7017,9 @@ function __initVirtualRuntime(rootScope) {
6872
7017
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6873
7018
 
6874
7019
  let syncExecDepth = 0;
6875
- let currentCwd = '/workspace';
6876
- _activeCwdGetter = () => currentCwd;
6877
7020
 
6878
7021
  const sandboxProcess = Object.assign(new EventEmitter(), {
6879
- env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
7022
+ env: Object.assign({ NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' }, options.env || {}),
6880
7023
  argv: argv || ['node', entry.startsWith('/') ? entry : `/workspace/${entry}`],
6881
7024
  argv0: 'node',
6882
7025
  execArgv: [],
@@ -6956,6 +7099,9 @@ function __initVirtualRuntime(rootScope) {
6956
7099
  }
6957
7100
 
6958
7101
  // Immediately cancel all active timers and immediates
7102
+ if (typeof vfs._setActiveStdin === 'function') {
7103
+ vfs._setActiveStdin('');
7104
+ }
6959
7105
  for (const rawId of resourceTracker.allTimers) {
6960
7106
  clearTimeout(rawId);
6961
7107
  clearInterval(rawId);
@@ -8871,6 +9017,9 @@ function __initVirtualRuntime(rootScope) {
8871
9017
  hasExited = true;
8872
9018
  try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
8873
9019
  }
9020
+ if (typeof vfs._setActiveStdin === 'function') {
9021
+ vfs._setActiveStdin('');
9022
+ }
8874
9023
  for (const rawId of resourceTracker.allTimers) {
8875
9024
  clearTimeout(rawId);
8876
9025
  clearInterval(rawId);
@@ -8887,12 +9036,56 @@ function __initVirtualRuntime(rootScope) {
8887
9036
  if (!isBackground) {
8888
9037
  vhttp.closeAllServers();
8889
9038
  vnet.closeAllServers();
9039
+ if (initialOpenFds && typeof vfs._listOpenFds === 'function' && typeof vfs.closeSync === 'function') {
9040
+ for (const fd of vfs._listOpenFds()) {
9041
+ if (!initialOpenFds.has(fd)) {
9042
+ try { vfs.closeSync(fd); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime closeSync leak cleanup failed', { fd, err }); }
9043
+ }
9044
+ }
9045
+ }
8890
9046
  }
9047
+ _activeCwdGetter = prevCwdGetter;
8891
9048
  }
8892
9049
 
8893
9050
  const failedTests = testResults.filter((t) => !t.passed).length;
8894
9051
  if (failedTests > 0 && exitCode === 0) exitCode = 1;
8895
9052
 
9053
+ let vfsChanges = undefined;
9054
+ if (initialVfsState && typeof vfs._exportRawState === 'function') {
9055
+ const finalVfsState = vfs._exportRawState();
9056
+ const modifiedFiles = {};
9057
+ const deletedFiles = [];
9058
+ const createdDirs = [];
9059
+ const isNodeModulesPath = (p) => p === '/workspace/node_modules' || p.startsWith('/workspace/node_modules/');
9060
+ const bytesEqual = (a, b) => {
9061
+ if (!a || !b || a.byteLength !== b.byteLength) return false;
9062
+ for (let i = 0; i < a.byteLength; i++) {
9063
+ if (a[i] !== b[i]) return false;
9064
+ }
9065
+ return true;
9066
+ };
9067
+
9068
+ for (const d of finalVfsState.dirs) {
9069
+ if (!initialVfsState.dirs.has(d) && !isNodeModulesPath(d)) {
9070
+ createdDirs.push(d);
9071
+ }
9072
+ }
9073
+ for (const [fPath, data] of finalVfsState.files.entries()) {
9074
+ if (isNodeModulesPath(fPath)) continue;
9075
+ const prev = initialVfsState.files.get(fPath);
9076
+ if (!prev || !bytesEqual(prev, data)) {
9077
+ modifiedFiles[fPath] = data;
9078
+ }
9079
+ }
9080
+ for (const fPath of initialVfsState.files.keys()) {
9081
+ if (isNodeModulesPath(fPath)) continue;
9082
+ if (!finalVfsState.files.has(fPath)) {
9083
+ deletedFiles.push(fPath);
9084
+ }
9085
+ }
9086
+ vfsChanges = { modifiedFiles, deletedFiles, createdDirs };
9087
+ }
9088
+
8896
9089
  return {
8897
9090
  ok: exitCode === 0,
8898
9091
  exitCode,
@@ -8908,6 +9101,7 @@ function __initVirtualRuntime(rootScope) {
8908
9101
  failed: failedTests
8909
9102
  },
8910
9103
  fsSnapshot: typeof vfs.getSnapshot === 'function' ? vfs.getSnapshot() : [],
9104
+ ...(vfsChanges ? { vfsChanges } : {}),
8911
9105
  httpTrace: [...vhttp.getTrace(), ...vnet.getTrace()],
8912
9106
  replValue: replValue !== undefined ? formatConsoleArg(replValue) : undefined
8913
9107
  };
@@ -9296,14 +9490,70 @@ function __initVirtualRuntime(rootScope) {
9296
9490
 
9297
9491
  exec(sql) {
9298
9492
  const cleaned = stripSqlComments(sql);
9299
- const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
9493
+ const statements = [];
9494
+ let cur = '';
9495
+ let i = 0;
9496
+ while (i < cleaned.length) {
9497
+ const ch = cleaned[i];
9498
+ if (ch === "'" || ch === '"') {
9499
+ const quote = ch;
9500
+ cur += ch;
9501
+ i++;
9502
+ while (i < cleaned.length) {
9503
+ if (cleaned[i] === quote && cleaned[i + 1] === quote) {
9504
+ cur += quote + quote;
9505
+ i += 2;
9506
+ continue;
9507
+ }
9508
+ if (cleaned[i] === '\\' && quote === '"') {
9509
+ cur += cleaned.slice(i, i + 2);
9510
+ i += 2;
9511
+ continue;
9512
+ }
9513
+ cur += cleaned[i];
9514
+ if (cleaned[i] === quote) {
9515
+ i++;
9516
+ break;
9517
+ }
9518
+ i++;
9519
+ }
9520
+ continue;
9521
+ }
9522
+ if (ch === ';') {
9523
+ const trimmed = cur.trim();
9524
+ if (trimmed) statements.push(trimmed);
9525
+ cur = '';
9526
+ i++;
9527
+ continue;
9528
+ }
9529
+ cur += ch;
9530
+ i++;
9531
+ }
9532
+ if (cur.trim()) statements.push(cur.trim());
9300
9533
  for (const s of statements) {
9301
9534
  this.run(s);
9302
9535
  }
9303
9536
  }
9304
9537
 
9305
9538
  transaction(fn) {
9306
- return (...args) => fn(...args);
9539
+ const db = this;
9540
+ return (...args) => {
9541
+ const snapshot = new Map();
9542
+ for (const [tblName, tbl] of db.tables.entries()) {
9543
+ snapshot.set(tblName, {
9544
+ columns: tbl.columns.map((c) => Object.assign({}, c)),
9545
+ rows: tbl.rows.map((r) => Object.assign({}, r)),
9546
+ autoInc: tbl.autoInc
9547
+ });
9548
+ }
9549
+ try {
9550
+ return fn(...args);
9551
+ } catch (err) {
9552
+ db.tables = snapshot;
9553
+ db._persistToVfs();
9554
+ throw err;
9555
+ }
9556
+ };
9307
9557
  }
9308
9558
 
9309
9559
  close() {
@@ -9592,9 +9842,11 @@ function __workerMessageLoop(workerScope) {
9592
9842
  const msg = event.data || {};
9593
9843
  const { requestId, type, payload = {} } = msg;
9594
9844
  if (type !== 'execute') return;
9845
+ workerScope.postMessage({ requestId, type: 'started' });
9595
9846
  try {
9596
9847
  const result = await runtime.executeInVirtualRuntime({
9597
9848
  ...payload,
9849
+ _captureVfsDiff: true,
9598
9850
  onStdout(text) {
9599
9851
  workerScope.postMessage({ requestId, type: 'stdout', text });
9600
9852
  },
@@ -9646,7 +9898,10 @@ function _ensureWorkerUrl() {
9646
9898
  }
9647
9899
 
9648
9900
  function _ensureWarmWorker() {
9649
- if (_warmWorker) return _warmWorker;
9901
+ if (_warmWorker && typeof Worker === 'function' && _warmWorker instanceof Worker) {
9902
+ return _warmWorker;
9903
+ }
9904
+ if (_warmWorker) _destroyWarmWorker();
9650
9905
  _warmWorker = new Worker(_ensureWorkerUrl());
9651
9906
  return _warmWorker;
9652
9907
  }
@@ -9659,6 +9914,14 @@ function _destroyWarmWorker() {
9659
9914
  _warmWorkerBusy = false;
9660
9915
  }
9661
9916
 
9917
+ _hostRuntime.destroyWorkerPool = function destroyWorkerPool() {
9918
+ _destroyWarmWorker();
9919
+ if (_cachedWorkerUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
9920
+ try { URL.revokeObjectURL(_cachedWorkerUrl); } catch (err) { _hostLogger.debug('revokeObjectURL failed', err); }
9921
+ }
9922
+ _cachedWorkerUrl = null;
9923
+ };
9924
+
9662
9925
  _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Execution cancelled', instanceId) {
9663
9926
  let cancelledAny = false;
9664
9927
  for (const [jobId, job] of Array.from(_activeWorkerJobs.entries())) {
@@ -9671,11 +9934,118 @@ _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Ex
9671
9934
  return cancelledAny;
9672
9935
  };
9673
9936
 
9937
+ function _extractWorkerFilesFromVfs(vfs) {
9938
+ const extracted = {};
9939
+ if (!vfs || typeof vfs !== 'object') return extracted;
9940
+ try {
9941
+ if (typeof vfs._exportRawState === 'function') {
9942
+ const st = vfs._exportRawState();
9943
+ for (const [absPath, bytes] of st.files.entries()) {
9944
+ extracted[absPath] = bytes;
9945
+ }
9946
+ return extracted;
9947
+ }
9948
+ if (vfs.files instanceof Map) {
9949
+ for (const [absPath, entry] of vfs.files.entries()) {
9950
+ if (!entry) continue;
9951
+ const data = entry.data !== undefined ? entry.data : entry;
9952
+ if (typeof data === 'string') {
9953
+ extracted[absPath] = data;
9954
+ } else if (data instanceof Uint8Array) {
9955
+ extracted[absPath] = data.slice();
9956
+ } else if (ArrayBuffer.isView(data)) {
9957
+ extracted[absPath] = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
9958
+ }
9959
+ }
9960
+ return extracted;
9961
+ }
9962
+ if (typeof vfs.readdirSync === 'function' && typeof vfs.readFileSync === 'function') {
9963
+ const walk = (dir) => {
9964
+ let entries = [];
9965
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
9966
+ for (const name of entries) {
9967
+ const full = dir === '/' ? '/' + name : dir + '/' + name;
9968
+ let isDir = false;
9969
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
9970
+ if (isDir) walk(full);
9971
+ else {
9972
+ try {
9973
+ const raw = vfs.readFileSync(full);
9974
+ extracted[full] = raw instanceof Uint8Array
9975
+ ? raw.slice()
9976
+ : (typeof raw === 'string' ? raw : String(raw ?? ''));
9977
+ } catch (err) {
9978
+ _hostLogger.debug('_extractWorkerFilesFromVfs: skip unreadable entry', full, err);
9979
+ }
9980
+ }
9981
+ }
9982
+ };
9983
+ walk('/workspace');
9984
+ walk('/tmp');
9985
+ }
9986
+ } catch (err) {
9987
+ _hostLogger.debug('_extractWorkerFilesFromVfs failed', err);
9988
+ }
9989
+ return extracted;
9990
+ }
9991
+
9992
+ function _applyWorkerVfsChanges(vfs, vfsChanges) {
9993
+ if (!vfs || !vfsChanges || typeof vfsChanges !== 'object') return;
9994
+ const { createdDirs = [], modifiedFiles = {}, deletedFiles = [] } = vfsChanges;
9995
+ try {
9996
+ if (Array.isArray(createdDirs) && typeof vfs.mkdirSync === 'function') {
9997
+ for (const dir of createdDirs) {
9998
+ try {
9999
+ vfs.mkdirSync(dir, { recursive: true });
10000
+ } catch (err) {
10001
+ _hostLogger.debug('_applyWorkerVfsChanges: mkdirSync failed', dir, err);
10002
+ }
10003
+ }
10004
+ }
10005
+ if (modifiedFiles && typeof modifiedFiles === 'object') {
10006
+ for (const [absPath, rawBytes] of Object.entries(modifiedFiles)) {
10007
+ const slashIdx = absPath.lastIndexOf('/');
10008
+ if (slashIdx > 0 && typeof vfs.mkdirSync === 'function') {
10009
+ try {
10010
+ vfs.mkdirSync(absPath.slice(0, slashIdx), { recursive: true });
10011
+ } catch (err) {
10012
+ _hostLogger.debug('_applyWorkerVfsChanges: parent mkdirSync failed', absPath, err);
10013
+ }
10014
+ }
10015
+ const payload = rawBytes instanceof Uint8Array
10016
+ ? rawBytes
10017
+ : (ArrayBuffer.isView(rawBytes)
10018
+ ? new Uint8Array(rawBytes.buffer, rawBytes.byteOffset, rawBytes.byteLength)
10019
+ : rawBytes);
10020
+ if (typeof vfs.writeFileSync === 'function') {
10021
+ vfs.writeFileSync(absPath, payload);
10022
+ } else if (typeof vfs.writeFile === 'function') {
10023
+ vfs.writeFile(absPath, payload);
10024
+ }
10025
+ }
10026
+ }
10027
+ if (Array.isArray(deletedFiles)) {
10028
+ for (const absPath of deletedFiles) {
10029
+ try {
10030
+ if (typeof vfs.unlinkSync === 'function') vfs.unlinkSync(absPath);
10031
+ else if (typeof vfs.rmSync === 'function') vfs.rmSync(absPath, { force: true });
10032
+ } catch (err) {
10033
+ _hostLogger.debug('_applyWorkerVfsChanges: delete failed', absPath, err);
10034
+ }
10035
+ }
10036
+ }
10037
+ } catch (err) {
10038
+ _hostLogger.debug('_applyWorkerVfsChanges failed', err);
10039
+ }
10040
+ }
10041
+
9674
10042
  _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9675
10043
  const isNonJs =
9676
10044
  Boolean(options.wasmBinary) ||
9677
10045
  Boolean(options.cppCompiler) ||
9678
10046
  Boolean(options.pythonCompiler) ||
10047
+ Boolean(options.activePortTable) ||
10048
+ Boolean(options.portTable) ||
9679
10049
  (typeof options.entry === 'string' && /\.(cpp|cc|cxx|wasm|py)$/i.test(options.entry));
9680
10050
  if (
9681
10051
  isNonJs ||
@@ -9695,6 +10065,10 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9695
10065
  _hostRuntime.cancelWorkerExecution('Execution cancelled by new run', instanceId);
9696
10066
  }
9697
10067
 
10068
+ const mergedFiles = options.vfs
10069
+ ? Object.assign(_extractWorkerFilesFromVfs(options.vfs), options.files || {})
10070
+ : options.files;
10071
+
9698
10072
  return new Promise((resolve) => {
9699
10073
  let worker;
9700
10074
  let isWarmWorker = false;
@@ -9713,9 +10087,23 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9713
10087
  return;
9714
10088
  }
9715
10089
 
10090
+ const startTime = typeof performance !== 'undefined' ? performance.now() : Date.now();
9716
10091
  const timeoutMs = options.timeoutMs || 15000;
9717
10092
  let settled = false;
10093
+ let userCodeStarted = false;
9718
10094
  let abortListener = null;
10095
+ const streamedStdoutChunks = [];
10096
+ const streamedStderrChunks = [];
10097
+ const streamedTestResults = [];
10098
+
10099
+ const buildTestSummary = () => {
10100
+ const failed = streamedTestResults.filter((t) => !t.passed).length;
10101
+ return {
10102
+ total: streamedTestResults.length,
10103
+ passed: streamedTestResults.length - failed,
10104
+ failed
10105
+ };
10106
+ };
9719
10107
 
9720
10108
  function releaseWorker(terminateWorker) {
9721
10109
  if (options.signal && abortListener) {
@@ -9742,14 +10130,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9742
10130
  if (settled) return;
9743
10131
  settled = true;
9744
10132
  releaseWorker(true);
10133
+ const timeoutMsg = `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`;
9745
10134
  resolve({
9746
10135
  ok: false,
9747
10136
  timedOut: true,
9748
10137
  exitCode: 124,
9749
10138
  durationMs: timeoutMs,
9750
- stdout: '',
9751
- stderr: `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`,
9752
- testResults: [],
10139
+ stdout: streamedStdoutChunks.join(''),
10140
+ stderr: streamedStderrChunks.join('') + timeoutMsg,
10141
+ testResults: streamedTestResults.slice(),
10142
+ testSummary: buildTestSummary(),
9753
10143
  fsSnapshot: [],
9754
10144
  httpTrace: [],
9755
10145
  error: { message: `Execution timed out after ${timeoutMs}ms` }
@@ -9764,14 +10154,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9764
10154
  settled = true;
9765
10155
  clearTimeout(timer);
9766
10156
  releaseWorker(true);
10157
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
9767
10158
  resolve({
9768
10159
  ok: false,
9769
10160
  cancelled: true,
9770
10161
  exitCode: 130,
9771
- durationMs: 0,
9772
- stdout: '',
9773
- stderr: `${reason}\n`,
9774
- testResults: [],
10162
+ durationMs: elapsed,
10163
+ stdout: streamedStdoutChunks.join(''),
10164
+ stderr: streamedStderrChunks.join('') + `${reason}\n`,
10165
+ testResults: streamedTestResults.slice(),
10166
+ testSummary: buildTestSummary(),
9775
10167
  fsSnapshot: [],
9776
10168
  httpTrace: [],
9777
10169
  error: { message: reason }
@@ -9795,16 +10187,27 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9795
10187
  worker.onmessage = (event) => {
9796
10188
  const msg = event.data || {};
9797
10189
  if (msg.requestId !== requestId) return;
9798
- if (msg.type === 'stdout' && typeof options.onStdout === 'function') {
9799
- options.onStdout(msg.text);
9800
- } else if (msg.type === 'stderr' && typeof options.onStderr === 'function') {
9801
- options.onStderr(msg.text);
9802
- } else if (msg.type === 'test-result' && typeof options.onTestResult === 'function') {
9803
- options.onTestResult(msg.testResult);
10190
+ if (msg.type === 'started') {
10191
+ userCodeStarted = true;
10192
+ } else if (msg.type === 'stdout') {
10193
+ userCodeStarted = true;
10194
+ if (typeof msg.text === 'string') streamedStdoutChunks.push(msg.text);
10195
+ if (typeof options.onStdout === 'function') options.onStdout(msg.text);
10196
+ } else if (msg.type === 'stderr') {
10197
+ userCodeStarted = true;
10198
+ if (typeof msg.text === 'string') streamedStderrChunks.push(msg.text);
10199
+ if (typeof options.onStderr === 'function') options.onStderr(msg.text);
10200
+ } else if (msg.type === 'test-result') {
10201
+ userCodeStarted = true;
10202
+ if (msg.testResult) streamedTestResults.push(msg.testResult);
10203
+ if (typeof options.onTestResult === 'function') options.onTestResult(msg.testResult);
9804
10204
  } else if (msg.type === 'complete') {
9805
10205
  if (settled) return;
9806
10206
  settled = true;
9807
10207
  clearTimeout(timer);
10208
+ if (options.vfs && msg.result && msg.result.vfsChanges) {
10209
+ _applyWorkerVfsChanges(options.vfs, msg.result.vfsChanges);
10210
+ }
9808
10211
  // Release `_warmWorker` for instant reuse, or terminate ephemeral concurrent worker
9809
10212
  releaseWorker(false);
9810
10213
  resolve(msg.result);
@@ -9813,13 +10216,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9813
10216
  settled = true;
9814
10217
  clearTimeout(timer);
9815
10218
  releaseWorker(false);
10219
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10220
+ const errLine = (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n';
9816
10221
  resolve({
9817
10222
  ok: false,
9818
10223
  exitCode: 1,
9819
- durationMs: 0,
9820
- stdout: '',
9821
- stderr: (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n',
9822
- testResults: [],
10224
+ durationMs: elapsed,
10225
+ stdout: streamedStdoutChunks.join(''),
10226
+ stderr: streamedStderrChunks.join('') + errLine,
10227
+ testResults: streamedTestResults.slice(),
10228
+ testSummary: buildTestSummary(),
9823
10229
  fsSnapshot: [],
9824
10230
  httpTrace: [],
9825
10231
  error: { message: msg.error?.message || 'Worker execution error', stack: msg.error?.stack }
@@ -9827,19 +10233,40 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9827
10233
  }
9828
10234
  };
9829
10235
 
9830
- worker.onerror = () => {
10236
+ worker.onerror = (errEvent) => {
9831
10237
  if (settled) return;
9832
10238
  settled = true;
9833
10239
  clearTimeout(timer);
9834
10240
  releaseWorker(true);
9835
- resolve(_hostRuntime.executeInVirtualRuntime(options));
10241
+ // Only fall back to in-process execution if the host blocked Blob Worker startup
10242
+ // BEFORE user code ever started. Never re-run crashed user code on the main thread.
10243
+ if (!userCodeStarted && options.allowMainThreadFallback !== false) {
10244
+ resolve(_hostRuntime.executeInVirtualRuntime(options));
10245
+ return;
10246
+ }
10247
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10248
+ const errMsg = (errEvent && errEvent.message)
10249
+ ? String(errEvent.message)
10250
+ : 'Uncaught fatal error in Web Worker execution';
10251
+ resolve({
10252
+ ok: false,
10253
+ exitCode: 1,
10254
+ durationMs: elapsed,
10255
+ stdout: streamedStdoutChunks.join(''),
10256
+ stderr: streamedStderrChunks.join('') + errMsg + '\n',
10257
+ testResults: streamedTestResults.slice(),
10258
+ testSummary: buildTestSummary(),
10259
+ fsSnapshot: [],
10260
+ httpTrace: [],
10261
+ error: { message: errMsg }
10262
+ });
9836
10263
  };
9837
10264
 
9838
10265
  worker.postMessage({
9839
10266
  requestId,
9840
10267
  type: 'execute',
9841
10268
  payload: {
9842
- files: options.files,
10269
+ files: mergedFiles,
9843
10270
  entry: options.entry,
9844
10271
  mode: options.mode,
9845
10272
  replCode: options.replCode,
@@ -9855,7 +10282,8 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9855
10282
  printReplResult: options.printReplResult,
9856
10283
  stdin: options.stdin,
9857
10284
  wasmBinary: options.wasmBinary,
9858
- env: options.env
10285
+ env: options.env,
10286
+ cwd: options.cwd
9859
10287
  }
9860
10288
  });
9861
10289
  });