@innovatorved/code-lab 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -160,7 +160,12 @@ var CodeLabCsp = (() => {
160
160
  directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
161
161
  directive("frame-src", withData("frameSrc")),
162
162
  directive("form-action", [self]),
163
- directive("frame-ancestors", [options.frameAncestors || "'self'"])
163
+ directive("frame-ancestors", (() => {
164
+ const rawFa = typeof options.frameAncestors === "string" ? options.frameAncestors.trim() : "";
165
+ if (!rawFa) return ["'self'"];
166
+ const tokens = cleanSources(rawFa.split(/\s+/));
167
+ return tokens.length > 0 ? tokens : ["'self'"];
168
+ })())
164
169
  ].join("; ");
165
170
  }
166
171
  function describePreviewNetwork(config) {
@@ -198,15 +203,6 @@ var CodeLabCsp = (() => {
198
203
  };
199
204
  }
200
205
  function shim(name) {
201
- var blocked = false;
202
- try {
203
- var existing = window[name];
204
- if (existing) { existing.getItem('__codelab_probe__'); return; }
205
- } catch (err) {
206
- // Expected on an opaque origin: the accessor itself throws.
207
- blocked = Boolean(err);
208
- }
209
- void blocked;
210
206
  try {
211
207
  Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
212
208
  } catch (err) {
@@ -366,6 +362,7 @@ var CodeLabCsp = (() => {
366
362
  }
367
363
 
368
364
  window.addEventListener('message', function (event) {
365
+ if (event && event.source && event.source !== window.parent) return;
369
366
  var data = event && event.data;
370
367
  if (!data || typeof data !== 'object') return;
371
368
  if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
@@ -578,6 +575,8 @@ self.addEventListener('activate', (event) => {
578
575
  self.addEventListener('message', (event) => {
579
576
  const data = event && event.data;
580
577
  if (!data || data.type !== 'codelab:config') return;
578
+ // Reject configuration attempts originating from preview tabs/frames themselves.
579
+ if (event.source && event.source.url && /\/__preview\//.test(event.source.url)) return;
581
580
  const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
582
581
  if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
583
582
  configuredCsp = csp;
@@ -600,10 +599,15 @@ function parsePreviewPath(pathname) {
600
599
  return { port: Number(match[1]), path: match[2] || '/' };
601
600
  }
602
601
 
602
+ function escapeMetaAttr(val) {
603
+ return String(val || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
604
+ }
605
+
603
606
  function previewErrorResponse(status, title, message) {
604
607
  const csp = previewPolicy();
608
+ const safeCsp = escapeMetaAttr(csp);
605
609
  const body = `<!doctype html><meta charset="utf-8">` +
606
- `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
610
+ `<meta http-equiv="Content-Security-Policy" content="${safeCsp}">` +
607
611
  `<title>${title}</title>` +
608
612
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
609
613
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
@@ -620,14 +624,15 @@ function previewErrorResponse(status, title, message) {
620
624
  /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
621
625
  function injectPreviewHead(html, port) {
622
626
  const csp = previewPolicy();
627
+ const safeCsp = escapeMetaAttr(csp);
623
628
  const shims = previewShims();
624
629
  const tags = [];
625
630
  const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
626
631
  const hasBase = /<base\b/i.test(html);
627
632
  const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
628
633
 
629
- if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
630
- if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
634
+ if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${safeCsp}">`);
635
+ if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${Number(port) || 3000}/">`);
631
636
  if (!hasShims && shims) tags.push(shims);
632
637
  if (tags.length === 0) return html;
633
638
 
@@ -643,7 +648,8 @@ function injectPreviewHead(html, port) {
643
648
 
644
649
  async function proxyVirtualRequest(event, port, targetPath) {
645
650
  const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
646
- if (!clients || !clients.length) {
651
+ const workbenchClients = (clients || []).filter((c) => !c.url || !/\/__preview\//.test(c.url));
652
+ if (!workbenchClients.length) {
647
653
  return previewErrorResponse(
648
654
  503,
649
655
  'No active CodeLab workbench',
@@ -651,7 +657,7 @@ async function proxyVirtualRequest(event, port, targetPath) {
651
657
  );
652
658
  }
653
659
 
654
- const client = clients[0];
660
+ const client = workbenchClients[0];
655
661
  const channel = new MessageChannel();
656
662
  const request = event.request;
657
663
  const method = request.method || 'GET';
@@ -707,6 +713,17 @@ async function proxyVirtualRequest(event, port, targetPath) {
707
713
  const responseHeaders = new Headers((response && response.headers) || {});
708
714
  const contentType = responseHeaders.get('content-type') || '';
709
715
 
716
+ // Decode Uint8Array / ArrayBuffer HTML bodies so head injection always applies.
717
+ if (/text\/html/i.test(contentType) && responseBody && typeof responseBody !== 'string') {
718
+ try {
719
+ if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
720
+ responseBody = new TextDecoder('utf-8').decode(responseBody);
721
+ }
722
+ } catch (err) {
723
+ console.warn('[code-lab] preview-sw: failed to decode HTML buffer', err);
724
+ }
725
+ }
726
+
710
727
  // Inject the policy and a <base> so relative asset URLs in HTML responses
711
728
  // resolve under the `/__preview/:port/` namespace rather than the host root.
712
729
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -1134,22 +1134,40 @@ function __initVirtualRuntime(rootScope) {
1134
1134
  // =========================================================================
1135
1135
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1136
1136
  // =========================================================================
1137
- function createVirtualFs(initialFiles = {}) {
1137
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1138
1138
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1139
1139
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1140
1140
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1141
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1142
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1143
+ const customCwdGetter = typeof vfsOptions === 'function'
1144
+ ? vfsOptions
1145
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1141
1146
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1142
1147
  let nextFd = 10;
1143
1148
  let nextIno = 100;
1144
1149
  let mkdtempCounter = 1;
1145
1150
 
1151
+ function recordDeletedForInspector(p, data, mtimeMs) {
1152
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1153
+ if (deletedInspectorCache.has(p)) {
1154
+ deletedInspectorCache.delete(p);
1155
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1156
+ const oldestKey = deletedInspectorCache.keys().next().value;
1157
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1158
+ }
1159
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1160
+ }
1161
+
1146
1162
  function normPath(p) {
1147
1163
  if (typeof p !== 'string' || !p) {
1148
1164
  const err = new TypeError('path must be a non-empty string');
1149
1165
  err.code = 'ERR_INVALID_ARG_TYPE';
1150
1166
  throw err;
1151
1167
  }
1152
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1168
+ const baseCwd = typeof customCwdGetter === 'function'
1169
+ ? customCwdGetter()
1170
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1153
1171
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1154
1172
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1155
1173
  }
@@ -1200,9 +1218,13 @@ function __initVirtualRuntime(rootScope) {
1200
1218
  for (const [relPath, content] of Object.entries(initialFiles)) {
1201
1219
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1202
1220
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1203
- const fullPath = isSystemPath
1221
+ let fullPath = isSystemPath
1204
1222
  ? normPath(relPath)
1205
1223
  : normPath(`/workspace/${cleanRel}`);
1224
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1225
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1226
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1227
+ }
1206
1228
  ensureParentDirs(fullPath);
1207
1229
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1208
1230
  files.set(fullPath, {
@@ -1382,13 +1404,6 @@ function __initVirtualRuntime(rootScope) {
1382
1404
  fsyncSync(fd) {
1383
1405
  const entry = fdTable.get(fd);
1384
1406
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1385
- if (!entry.isDirectory && entry.inode) {
1386
- deletedInspectorCache.set(entry.path, {
1387
- data: entry.inode.data.slice(),
1388
- mtimeMs: entry.inode.mtimeMs,
1389
- deletedAtMs: null
1390
- });
1391
- }
1392
1407
  },
1393
1408
 
1394
1409
  fdatasyncSync(fd) {
@@ -1429,12 +1444,6 @@ function __initVirtualRuntime(rootScope) {
1429
1444
  inode.mtimeMs = Date.now();
1430
1445
  entry.pos = writePos + chunk.byteLength;
1431
1446
 
1432
- deletedInspectorCache.set(entry.path, {
1433
- data: inode.data.slice(),
1434
- mtimeMs: inode.mtimeMs,
1435
- deletedAtMs: null
1436
- });
1437
-
1438
1447
  return chunk.byteLength;
1439
1448
  },
1440
1449
 
@@ -1486,7 +1495,7 @@ function __initVirtualRuntime(rootScope) {
1486
1495
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1487
1496
  }
1488
1497
  }
1489
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1498
+ deletedInspectorCache.delete(np);
1490
1499
  },
1491
1500
 
1492
1501
  chmodSync(p, mode) {
@@ -1515,7 +1524,7 @@ function __initVirtualRuntime(rootScope) {
1515
1524
  combined.set(chunk, inode.data.byteLength);
1516
1525
  inode.data = combined;
1517
1526
  inode.mtimeMs = Date.now();
1518
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1527
+ deletedInspectorCache.delete(np);
1519
1528
  },
1520
1529
 
1521
1530
  truncateSync(p, len = 0) {
@@ -1531,7 +1540,6 @@ function __initVirtualRuntime(rootScope) {
1531
1540
  inode.data = grown;
1532
1541
  }
1533
1542
  inode.mtimeMs = Date.now();
1534
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1535
1543
  },
1536
1544
 
1537
1545
  renameSync(oldP, newP) {
@@ -1592,16 +1600,14 @@ function __initVirtualRuntime(rootScope) {
1592
1600
  if (fdEntry.path === src) fdEntry.path = dst;
1593
1601
  }
1594
1602
  deletedInspectorCache.delete(src);
1595
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1603
+ deletedInspectorCache.delete(dst);
1596
1604
  },
1597
1605
 
1598
1606
  unlinkSync(p) {
1599
1607
  const np = normPath(p);
1600
1608
  const inode = files.get(np);
1601
1609
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1602
- if (inode.data.byteLength > 0) {
1603
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1604
- }
1610
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1605
1611
  files.delete(np);
1606
1612
  },
1607
1613
 
@@ -1618,9 +1624,7 @@ function __initVirtualRuntime(rootScope) {
1618
1624
  for (const [fPath, inode] of Array.from(files.entries())) {
1619
1625
  if (fPath.startsWith(prefix)) {
1620
1626
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1621
- if (inode.data.byteLength > 0) {
1622
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1623
- }
1627
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1624
1628
  files.delete(fPath);
1625
1629
  }
1626
1630
  }
@@ -3194,6 +3198,7 @@ function __initVirtualRuntime(rootScope) {
3194
3198
  responseHeaders: {},
3195
3199
  _t0: performance.now()
3196
3200
  };
3201
+ if (httpTrace.length >= 500) httpTrace.shift();
3197
3202
  httpTrace.push(traceEntry);
3198
3203
  this._traceEntry = traceEntry;
3199
3204
 
@@ -4185,6 +4190,7 @@ function __initVirtualRuntime(rootScope) {
4185
4190
  this._peer = serverSocket;
4186
4191
  this.connecting = false;
4187
4192
 
4193
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4188
4194
  sharedTrace.push({
4189
4195
  protocol: 'TCP',
4190
4196
  event: 'connect',
@@ -6477,7 +6483,10 @@ function __initVirtualRuntime(rootScope) {
6477
6483
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6478
6484
  resourceTracker.pid = pid;
6479
6485
 
6480
- const vfs = optVfs || createVirtualFs(files);
6486
+ let currentCwd = '/workspace';
6487
+ _activeCwdGetter = () => currentCwd;
6488
+
6489
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6481
6490
  if (optVfs && files && typeof files === 'object') {
6482
6491
  for (const [fPath, content] of Object.entries(files)) {
6483
6492
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6871,8 +6880,6 @@ function __initVirtualRuntime(rootScope) {
6871
6880
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6872
6881
 
6873
6882
  let syncExecDepth = 0;
6874
- let currentCwd = '/workspace';
6875
- _activeCwdGetter = () => currentCwd;
6876
6883
 
6877
6884
  const sandboxProcess = Object.assign(new EventEmitter(), {
6878
6885
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
package/dist/runtime.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -1135,22 +1135,40 @@ function __initVirtualRuntime(rootScope) {
1135
1135
  // =========================================================================
1136
1136
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1137
1137
  // =========================================================================
1138
- function createVirtualFs(initialFiles = {}) {
1138
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1139
1139
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1140
1140
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1141
1141
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1142
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1143
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1144
+ const customCwdGetter = typeof vfsOptions === 'function'
1145
+ ? vfsOptions
1146
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1142
1147
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1143
1148
  let nextFd = 10;
1144
1149
  let nextIno = 100;
1145
1150
  let mkdtempCounter = 1;
1146
1151
 
1152
+ function recordDeletedForInspector(p, data, mtimeMs) {
1153
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1154
+ if (deletedInspectorCache.has(p)) {
1155
+ deletedInspectorCache.delete(p);
1156
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1157
+ const oldestKey = deletedInspectorCache.keys().next().value;
1158
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1159
+ }
1160
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1161
+ }
1162
+
1147
1163
  function normPath(p) {
1148
1164
  if (typeof p !== 'string' || !p) {
1149
1165
  const err = new TypeError('path must be a non-empty string');
1150
1166
  err.code = 'ERR_INVALID_ARG_TYPE';
1151
1167
  throw err;
1152
1168
  }
1153
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1169
+ const baseCwd = typeof customCwdGetter === 'function'
1170
+ ? customCwdGetter()
1171
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1154
1172
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1155
1173
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1156
1174
  }
@@ -1201,9 +1219,13 @@ function __initVirtualRuntime(rootScope) {
1201
1219
  for (const [relPath, content] of Object.entries(initialFiles)) {
1202
1220
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1203
1221
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1204
- const fullPath = isSystemPath
1222
+ let fullPath = isSystemPath
1205
1223
  ? normPath(relPath)
1206
1224
  : normPath(`/workspace/${cleanRel}`);
1225
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1226
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1227
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1228
+ }
1207
1229
  ensureParentDirs(fullPath);
1208
1230
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1209
1231
  files.set(fullPath, {
@@ -1383,13 +1405,6 @@ function __initVirtualRuntime(rootScope) {
1383
1405
  fsyncSync(fd) {
1384
1406
  const entry = fdTable.get(fd);
1385
1407
  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
1408
  },
1394
1409
 
1395
1410
  fdatasyncSync(fd) {
@@ -1430,12 +1445,6 @@ function __initVirtualRuntime(rootScope) {
1430
1445
  inode.mtimeMs = Date.now();
1431
1446
  entry.pos = writePos + chunk.byteLength;
1432
1447
 
1433
- deletedInspectorCache.set(entry.path, {
1434
- data: inode.data.slice(),
1435
- mtimeMs: inode.mtimeMs,
1436
- deletedAtMs: null
1437
- });
1438
-
1439
1448
  return chunk.byteLength;
1440
1449
  },
1441
1450
 
@@ -1487,7 +1496,7 @@ function __initVirtualRuntime(rootScope) {
1487
1496
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1488
1497
  }
1489
1498
  }
1490
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1499
+ deletedInspectorCache.delete(np);
1491
1500
  },
1492
1501
 
1493
1502
  chmodSync(p, mode) {
@@ -1516,7 +1525,7 @@ function __initVirtualRuntime(rootScope) {
1516
1525
  combined.set(chunk, inode.data.byteLength);
1517
1526
  inode.data = combined;
1518
1527
  inode.mtimeMs = Date.now();
1519
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1528
+ deletedInspectorCache.delete(np);
1520
1529
  },
1521
1530
 
1522
1531
  truncateSync(p, len = 0) {
@@ -1532,7 +1541,6 @@ function __initVirtualRuntime(rootScope) {
1532
1541
  inode.data = grown;
1533
1542
  }
1534
1543
  inode.mtimeMs = Date.now();
1535
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1536
1544
  },
1537
1545
 
1538
1546
  renameSync(oldP, newP) {
@@ -1593,16 +1601,14 @@ function __initVirtualRuntime(rootScope) {
1593
1601
  if (fdEntry.path === src) fdEntry.path = dst;
1594
1602
  }
1595
1603
  deletedInspectorCache.delete(src);
1596
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1604
+ deletedInspectorCache.delete(dst);
1597
1605
  },
1598
1606
 
1599
1607
  unlinkSync(p) {
1600
1608
  const np = normPath(p);
1601
1609
  const inode = files.get(np);
1602
1610
  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
- }
1611
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1606
1612
  files.delete(np);
1607
1613
  },
1608
1614
 
@@ -1619,9 +1625,7 @@ function __initVirtualRuntime(rootScope) {
1619
1625
  for (const [fPath, inode] of Array.from(files.entries())) {
1620
1626
  if (fPath.startsWith(prefix)) {
1621
1627
  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
- }
1628
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1625
1629
  files.delete(fPath);
1626
1630
  }
1627
1631
  }
@@ -3195,6 +3199,7 @@ function __initVirtualRuntime(rootScope) {
3195
3199
  responseHeaders: {},
3196
3200
  _t0: performance.now()
3197
3201
  };
3202
+ if (httpTrace.length >= 500) httpTrace.shift();
3198
3203
  httpTrace.push(traceEntry);
3199
3204
  this._traceEntry = traceEntry;
3200
3205
 
@@ -4186,6 +4191,7 @@ function __initVirtualRuntime(rootScope) {
4186
4191
  this._peer = serverSocket;
4187
4192
  this.connecting = false;
4188
4193
 
4194
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4189
4195
  sharedTrace.push({
4190
4196
  protocol: 'TCP',
4191
4197
  event: 'connect',
@@ -6478,7 +6484,10 @@ function __initVirtualRuntime(rootScope) {
6478
6484
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6479
6485
  resourceTracker.pid = pid;
6480
6486
 
6481
- const vfs = optVfs || createVirtualFs(files);
6487
+ let currentCwd = '/workspace';
6488
+ _activeCwdGetter = () => currentCwd;
6489
+
6490
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6482
6491
  if (optVfs && files && typeof files === 'object') {
6483
6492
  for (const [fPath, content] of Object.entries(files)) {
6484
6493
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6872,8 +6881,6 @@ function __initVirtualRuntime(rootScope) {
6872
6881
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6873
6882
 
6874
6883
  let syncExecDepth = 0;
6875
- let currentCwd = '/workspace';
6876
- _activeCwdGetter = () => currentCwd;
6877
6884
 
6878
6885
  const sandboxProcess = Object.assign(new EventEmitter(), {
6879
6886
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
package/dist/schemas.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  /**
3
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.2.0
3
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.3.2
4
4
  */
5
5
  export declare const GuidedStepSchema: z.ZodObject<{
6
6
  id: z.ZodString;
@@ -232,20 +232,20 @@ export declare const GuidedLabExtensionOptionsSchema: z.ZodObject<{
232
232
  }>;
233
233
  export type GuidedLabExtensionOptions = z.infer<typeof GuidedLabExtensionOptionsSchema>;
234
234
  export declare const CppToolchainProgressSchema: z.ZodObject<{
235
- stage: z.ZodEnum<["downloading", "caching", "extracting", "compiling", "linking", "ready"]>;
235
+ stage: z.ZodEnum<["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]>;
236
236
  loadedBytes: z.ZodOptional<z.ZodNumber>;
237
237
  totalBytes: z.ZodOptional<z.ZodNumber>;
238
238
  percent: z.ZodOptional<z.ZodNumber>;
239
239
  message: z.ZodOptional<z.ZodString>;
240
240
  }, "strip", z.ZodTypeAny, {
241
241
  message?: string;
242
- stage?: "downloading" | "caching" | "extracting" | "compiling" | "linking" | "ready";
242
+ stage?: "error" | "downloading" | "caching" | "extracting" | "compiling" | "linking" | "ready";
243
243
  loadedBytes?: number;
244
244
  totalBytes?: number;
245
245
  percent?: number;
246
246
  }, {
247
247
  message?: string;
248
- stage?: "downloading" | "caching" | "extracting" | "compiling" | "linking" | "ready";
248
+ stage?: "error" | "downloading" | "caching" | "extracting" | "compiling" | "linking" | "ready";
249
249
  loadedBytes?: number;
250
250
  totalBytes?: number;
251
251
  percent?: number;
@@ -4093,7 +4093,7 @@ var GuidedLabExtensionOptionsSchema = external_exports.object({
4093
4093
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
4094
4094
  });
4095
4095
  var CppToolchainProgressSchema = external_exports.object({
4096
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
4096
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
4097
4097
  loadedBytes: external_exports.number().optional(),
4098
4098
  totalBytes: external_exports.number().optional(),
4099
4099
  percent: external_exports.number().optional(),
package/dist/schemas.js CHANGED
@@ -4133,7 +4133,7 @@ var GuidedLabExtensionOptionsSchema = external_exports.object({
4133
4133
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
4134
4134
  });
4135
4135
  var CppToolchainProgressSchema = external_exports.object({
4136
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
4136
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
4137
4137
  loadedBytes: external_exports.number().optional(),
4138
4138
  totalBytes: external_exports.number().optional(),
4139
4139
  percent: external_exports.number().optional(),
package/dist/scm.d.ts CHANGED
@@ -27,9 +27,17 @@ export interface GitState {
27
27
  branches?: string[];
28
28
  headCommit: string;
29
29
  headFiles: Record<string, string>;
30
- staged: Map<string, string | null>;
30
+ headSnapshot?: Record<string, string>;
31
+ staged: Map<string, string | null> | Set<string>;
31
32
  commits: GitCommitRecord[];
32
33
  }
34
+ export interface GitStatusEntry {
35
+ path: string;
36
+ status: GitFileChangeType;
37
+ staged: boolean;
38
+ index: string;
39
+ worktree: string;
40
+ }
33
41
  export interface GitStatusResult {
34
42
  branch: string;
35
43
  headCommit: string;
@@ -38,6 +46,7 @@ export interface GitStatusResult {
38
46
  deleted: GitFileStatus[];
39
47
  staged: GitFileStatus[];
40
48
  unstaged: GitFileStatus[];
49
+ entries: GitStatusEntry[];
41
50
  hasChanges: boolean;
42
51
  isClean: boolean;
43
52
  }
@@ -51,8 +60,10 @@ export declare function computeShortCommitHash(input: string): string;
51
60
  export declare function createGitState(initialFiles?: Record<string, string>, branch?: string): GitState;
52
61
  /**
53
62
  * Computes working-tree and staging-area Git status against `gitState`.
63
+ * Supports both `computeGitStatus(vfsFiles, repoRoot, gitState)` and
64
+ * `computeGitStatus(gitState, vfsFiles)` calling conventions.
54
65
  */
55
- export declare function computeGitStatus(vfsFiles: Record<string, string>, _repoRoot?: string, gitState?: GitState): GitStatusResult;
66
+ export declare function computeGitStatus(arg1: Record<string, string> | GitState, arg2?: string | Record<string, string>, gitState?: GitState): GitStatusResult;
56
67
  /**
57
68
  * Stages a file addition, modification, or deletion (`currentContent === null`).
58
69
  */
package/dist/search.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  export interface SearchOptions {
11
11
  query?: string;
12
+ replacement?: string;
12
13
  caseSensitive?: boolean;
13
14
  wholeWord?: boolean;
14
15
  regex?: boolean;
@@ -50,8 +51,10 @@ export interface SearchResult extends Array<SearchMatchGroup> {
50
51
  }
51
52
  export interface ReplaceResult {
52
53
  updatedFiles: Record<string, string>;
54
+ files: Record<string, string>;
53
55
  replacedCount: number;
54
56
  filesAffected: string[];
57
+ filesModified: number;
55
58
  }
56
59
  /**
57
60
  * Escapes regex special characters in a literal string.
@@ -63,6 +66,7 @@ export declare function escapeRegex(text: string): string;
63
66
  export declare function normalizeSearchPath(filePath: string): string;
64
67
  /**
65
68
  * Matches a file path against a glob or literal substring filter.
69
+ * Supports comma-separated patterns (e.g. `*.ts, *.js`).
66
70
  */
67
71
  export declare function matchesGlob(filePath: string, pattern: string): boolean;
68
72
  /**
@@ -72,4 +76,4 @@ export declare function searchInFiles(files: Record<string, string>, queryOrOpti
72
76
  /**
73
77
  * Replaces occurrences of a query pattern across virtual workspace files.
74
78
  */
75
- export declare function replaceInFiles(files: Record<string, string>, arg2: string | SearchOptions, arg3: string, arg4?: SearchOptions | string[]): ReplaceResult;
79
+ export declare function replaceInFiles(files: Record<string, string>, arg2: string | SearchOptions, arg3?: string, arg4?: SearchOptions | string[]): ReplaceResult;