@innovatorved/code-lab 0.1.2 → 0.1.4

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.
package/dist/code-lab.js CHANGED
@@ -4682,8 +4682,22 @@ function __initVirtualRuntime(rootScope) {
4682
4682
  }
4683
4683
 
4684
4684
  const _npmPackageCache = new Map();
4685
+ const _npmMetadataCache = new Map();
4686
+
4687
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4688
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4689
+ // preloadNpmPackages(files)
4690
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4691
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4692
+ // preloadNpmPackages(files, existingCache, onProgress)
4693
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4694
+ let onProgress = null;
4695
+ let existingCache = _npmPackageCache;
4696
+ if (typeof secondArg === 'function') onProgress = secondArg;
4697
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4698
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4699
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4685
4700
 
4686
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4687
4701
  const specs = new Set();
4688
4702
  const builtinSet = new Set([
4689
4703
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4719,20 +4733,51 @@ function __initVirtualRuntime(rootScope) {
4719
4733
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4720
4734
  }
4721
4735
 
4736
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4737
+ // is memoised across calls so repeated preloads stay cheap.
4738
+ if (typeof fetch === 'function') {
4739
+ let pass = 0;
4740
+ while (pass < 6) {
4741
+ const pending = [];
4742
+ for (const pkg of specs) {
4743
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4744
+ }
4745
+ if (pending.length === 0) break;
4746
+ pass++;
4747
+ await Promise.all(pending.map(async (pkg) => {
4748
+ let deps = [];
4749
+ try {
4750
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4751
+ if (res && res.ok) {
4752
+ const meta = await res.json();
4753
+ deps = Object.keys((meta && meta.dependencies) || {});
4754
+ }
4755
+ } catch (_) {}
4756
+ _npmMetadataCache.set(pkg, deps);
4757
+ }));
4758
+ for (const pkg of pending) {
4759
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4760
+ }
4761
+ }
4762
+ }
4763
+
4722
4764
  const loaded = {};
4723
4765
  for (const pkg of specs) {
4724
4766
  const nmKey = `node_modules/${pkg}/index.js`;
4725
4767
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4726
- if (existingCache && existingCache.has(pkg)) {
4768
+ if (existingCache.has(pkg)) {
4727
4769
  loaded[pkg] = existingCache.get(pkg);
4728
4770
  continue;
4729
4771
  }
4772
+ if (typeof onProgress === 'function') {
4773
+ try { onProgress(pkg); } catch (_) {}
4774
+ }
4730
4775
  if (typeof fetch === 'function') {
4731
4776
  try {
4732
4777
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4733
4778
  if (res && res.ok) {
4734
4779
  const text = await res.text();
4735
- if (existingCache) existingCache.set(pkg, text);
4780
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4736
4781
  loaded[pkg] = text;
4737
4782
  }
4738
4783
  } catch (_) {}
@@ -9502,6 +9547,16 @@ if (typeof module !== 'undefined' && module.exports) {
9502
9547
  const requestedBranch = options.branch || parsed.branch || null;
9503
9548
  const { owner, repo } = parsed;
9504
9549
 
9550
+ const signal = options.signal || null;
9551
+ const throwIfAborted = () => {
9552
+ if (signal && signal.aborted) {
9553
+ const abortErr = new Error('fatal: clone cancelled (SIGINT)');
9554
+ abortErr.name = 'AbortError';
9555
+ throw abortErr;
9556
+ }
9557
+ };
9558
+ throwIfAborted();
9559
+
9505
9560
  let resolvedBranch = requestedBranch;
9506
9561
  let rawTreeEntries = null;
9507
9562
  let repoNotFound = false;
@@ -9514,7 +9569,8 @@ if (typeof module !== 'undefined' && module.exports) {
9514
9569
  try {
9515
9570
  if (!resolvedBranch) {
9516
9571
  const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
9517
- headers: { Accept: 'application/vnd.github.v3+json' }
9572
+ headers: { Accept: 'application/vnd.github.v3+json' },
9573
+ signal
9518
9574
  });
9519
9575
  if (metaRes.status === 404) {
9520
9576
  repoNotFound = true;
@@ -9532,9 +9588,10 @@ if (typeof module !== 'undefined' && module.exports) {
9532
9588
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
9533
9589
 
9534
9590
  for (const cand of branchCandidates) {
9591
+ throwIfAborted();
9535
9592
  const treeRes = await fetchFn(
9536
9593
  `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
9537
- { headers: { Accept: 'application/vnd.github.v3+json' } }
9594
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
9538
9595
  );
9539
9596
  if (treeRes.ok) {
9540
9597
  const treeJson = await treeRes.json();
@@ -9560,8 +9617,10 @@ if (typeof module !== 'undefined' && module.exports) {
9560
9617
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
9561
9618
 
9562
9619
  for (const cand of branchCandidates) {
9620
+ throwIfAborted();
9563
9621
  const flatRes = await fetchFn(
9564
- `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`
9622
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
9623
+ { signal }
9565
9624
  );
9566
9625
  if (flatRes && flatRes.ok) {
9567
9626
  const flatJson = await flatRes.json();
@@ -9630,28 +9689,34 @@ if (typeof module !== 'undefined' && module.exports) {
9630
9689
  const BATCH_SIZE = 12;
9631
9690
 
9632
9691
  for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
9692
+ throwIfAborted();
9633
9693
  const batch = selectedFiles.slice(i, i + BATCH_SIZE);
9634
9694
  await Promise.all(
9635
9695
  batch.map(async (entry) => {
9696
+ throwIfAborted();
9636
9697
  const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
9637
9698
  const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
9638
9699
  const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
9639
9700
 
9640
9701
  let text = null;
9641
9702
  try {
9642
- const r1 = await fetchFn(rawUrl);
9703
+ const r1 = await fetchFn(rawUrl, { signal });
9643
9704
  if (r1 && r1.ok) {
9644
9705
  text = await r1.text();
9645
9706
  }
9646
- } catch (_) {}
9707
+ } catch (_) {
9708
+ if (signal && signal.aborted) throw _;
9709
+ }
9647
9710
 
9648
9711
  if (text === null) {
9649
9712
  try {
9650
- const r2 = await fetchFn(cdnUrl);
9713
+ const r2 = await fetchFn(cdnUrl, { signal });
9651
9714
  if (r2 && r2.ok) {
9652
9715
  text = await r2.text();
9653
9716
  }
9654
- } catch (_) {}
9717
+ } catch (_) {
9718
+ if (signal && signal.aborted) throw _;
9719
+ }
9655
9720
  }
9656
9721
 
9657
9722
  if (text !== null && text.length <= maxFileSize) {
@@ -9675,6 +9740,8 @@ if (typeof module !== 'undefined' && module.exports) {
9675
9740
  );
9676
9741
  }
9677
9742
 
9743
+ throwIfAborted();
9744
+
9678
9745
  if (onProgress) {
9679
9746
  onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
9680
9747
  }
@@ -9695,7 +9762,7 @@ if (typeof module !== 'undefined' && module.exports) {
9695
9762
  try {
9696
9763
  const commitsRes = await fetchFn(
9697
9764
  `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
9698
- { headers: { Accept: 'application/vnd.github.v3+json' } }
9765
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
9699
9766
  );
9700
9767
  if (commitsRes && commitsRes.ok) {
9701
9768
  const commitsJson = await commitsRes.json();
@@ -9807,38 +9874,221 @@ if (typeof module !== 'undefined' && module.exports) {
9807
9874
  } catch (_) {}
9808
9875
  }
9809
9876
 
9810
- function installPackage(pkgSpec, ctx) {
9811
- const parts = pkgSpec.split('@').filter(Boolean);
9812
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
9813
- const pkgVersion = parts[1] || '^1.0.0';
9877
+ // ---------------------------------------------------------------------------
9878
+ // Real npm package installation via the jsDelivr CDN
9879
+ // ---------------------------------------------------------------------------
9880
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
9881
+
9882
+ // Minimal offline registry, used only when the CDN is unreachable so common
9883
+ // demos still resolve without network access.
9884
+ const OFFLINE_PACKAGE_FALLBACKS = {
9885
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
9886
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
9887
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
9888
+ 'left-pad': 'module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };\n'
9889
+ };
9890
+
9891
+ function packageCtxFetch(ctx) {
9892
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
9893
+ return ctx.shell.options.fetchImpl;
9894
+ }
9895
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
9896
+ return null;
9897
+ }
9898
+
9899
+ function parsePackageSpec(spec) {
9900
+ const raw = String(spec || '').trim();
9901
+ if (!raw) return { name: '', range: null };
9902
+ if (raw.startsWith('@')) {
9903
+ const at = raw.indexOf('@', 1);
9904
+ if (at === -1) return { name: raw, range: null };
9905
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9906
+ }
9907
+ const at = raw.indexOf('@');
9908
+ if (at <= 0) return { name: raw, range: null };
9909
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9910
+ }
9911
+
9912
+ function resolveEntryRelPath(pkgJson) {
9913
+ let entry = pkgJson.main || pkgJson.module ||
9914
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
9915
+ entry = String(entry).replace(/^[./]+/, '');
9916
+ return entry || 'index.js';
9917
+ }
9918
+
9919
+ function stripRelPath(rel) {
9920
+ return String(rel || '').replace(/^[./]+/, '');
9921
+ }
9922
+
9923
+ function extractRelativeSpecifiers(code) {
9924
+ const out = new Set();
9925
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
9926
+ let m;
9927
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
9928
+ return Array.from(out);
9929
+ }
9930
+
9931
+ function normalizeRelPath(baseDir, rel) {
9932
+ const parts = String(baseDir || '').split('/').filter(Boolean);
9933
+ for (const seg of String(rel).split('/')) {
9934
+ if (!seg || seg === '.') continue;
9935
+ if (seg === '..') parts.pop();
9936
+ else parts.push(seg);
9937
+ }
9938
+ return parts.join('/');
9939
+ }
9940
+
9941
+ async function fetchTextFromCdn(fetchImpl, url) {
9942
+ try {
9943
+ const res = await fetchImpl(url);
9944
+ if (!res) return null;
9945
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
9946
+ if (!ok) return null;
9947
+ if (typeof res.text === 'function') return await res.text();
9948
+ return String(res.body != null ? res.body : '');
9949
+ } catch (_) {
9950
+ return null;
9951
+ }
9952
+ }
9953
+
9954
+ async function resolvePackageMetadata(fetchImpl, name, range) {
9955
+ const urls = range
9956
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
9957
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
9958
+ for (const url of urls) {
9959
+ const text = await fetchTextFromCdn(fetchImpl, url);
9960
+ if (!text) continue;
9961
+ try {
9962
+ const parsed = JSON.parse(text);
9963
+ if (parsed && parsed.version) return parsed;
9964
+ } catch (_) {}
9965
+ }
9966
+ return null;
9967
+ }
9968
+
9969
+ // Download a package's entry module, its relative submodules and record its
9970
+ // declared dependencies so the caller can resolve them transitively.
9971
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
9972
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
9973
+ if (!meta) {
9974
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
9975
+ if (fallback) {
9976
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
9977
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
9978
+ }
9979
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
9980
+ }
9981
+
9982
+ const version = meta.version;
9983
+ const key = `${name}@${version}`;
9984
+ if (seen.has(key)) {
9985
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
9986
+ }
9987
+ seen.add(key);
9988
+
9989
+ const entry = resolveEntryRelPath(meta);
9990
+ const files = [];
9991
+ const visited = new Set();
9992
+ const queue = [entry];
9993
+ while (queue.length > 0) {
9994
+ const rel = stripRelPath(queue.shift());
9995
+ if (!rel || visited.has(rel)) continue;
9996
+ visited.add(rel);
9997
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
9998
+ if (text === null) continue;
9999
+ files.push({ rel, content: text });
10000
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
10001
+ for (const spec of extractRelativeSpecifiers(text)) {
10002
+ const target = normalizeRelPath(baseDir, spec);
10003
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
10004
+ const c = stripRelPath(cand);
10005
+ if (c && !visited.has(c)) { queue.push(cand); break; }
10006
+ }
10007
+ }
10008
+ }
10009
+ // The declared entry may be missing on the CDN; fall back to index.js.
10010
+ if (!files.some(f => f.rel === entry)) {
10011
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
10012
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10013
+ }
10014
+
10015
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
10016
+ }
10017
+
10018
+ function installTargetDirs(ctx, name) {
10019
+ const dirs = ['/workspace/node_modules/' + name];
10020
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
10021
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
10022
+ return dirs;
10023
+ }
10024
+
10025
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
10026
+ for (const dir of dirs) {
10027
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10028
+ for (const f of info.files) {
10029
+ const full = PosixPath.join(dir, f.rel);
10030
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10031
+ ctx.vfs.writeFileSync(full, f.content);
10032
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
10033
+ }
10034
+ const modPkgPath = PosixPath.join(dir, 'package.json');
10035
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
10036
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
10037
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10038
+ }
10039
+ }
10040
+
10041
+ async function installPackage(pkgSpec, ctx) {
10042
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10043
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
9814
10044
 
9815
10045
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
9816
10046
  if (!pkgData.dependencies) pkgData.dependencies = {};
9817
- pkgData.dependencies[pkgName] = pkgVersion;
9818
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
9819
10047
 
9820
- const targetDirs = ['/workspace/node_modules/' + pkgName];
9821
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
9822
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
10048
+ const fetchImpl = packageCtxFetch(ctx);
10049
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
10050
+ ? ctx.shell._cdnSeen
10051
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
10052
+
10053
+ const queue = [{ name: pkgName, range, direct: true }];
10054
+ const requested = new Set([pkgName]);
10055
+ const installed = [];
10056
+ let warning = null;
10057
+ let directVersion = null;
10058
+
10059
+ while (queue.length > 0) {
10060
+ const item = queue.shift();
10061
+ const info = fetchImpl
10062
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
10063
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
10064
+
10065
+ if (!info.ok) {
10066
+ // Final fallback: an empty stub so offline demos still resolve the module.
10067
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
10068
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
10069
+ });
10070
+ if (!warning) warning = info.reason;
10071
+ installed.push({ name: item.name, version: '0.0.0' });
10072
+ continue;
10073
+ }
9823
10074
 
9824
- for (const modDir of targetDirs) {
9825
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
9826
- const modPkgPath = PosixPath.join(modDir, 'package.json');
9827
- const modIndexPath = PosixPath.join(modDir, 'index.js');
9828
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
9829
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10075
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
10076
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
10077
+ if (item.direct) directVersion = info.version || null;
9830
10078
 
9831
- let code = 'module.exports = {};\n';
9832
- if (pkgName === 'is-even') {
9833
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
9834
- } else if (pkgName === 'tiny-invariant') {
9835
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
9836
- } else if (pkgName === 'lodash') {
9837
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
10079
+ for (const dep of (info.deps || [])) {
10080
+ const parsed = parsePackageSpec(dep);
10081
+ if (parsed.name && !requested.has(parsed.name)) {
10082
+ requested.add(parsed.name);
10083
+ queue.push({ name: parsed.name, range: null, direct: false });
10084
+ }
9838
10085
  }
9839
- ctx.vfs.writeFileSync(modIndexPath, code);
9840
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
9841
10086
  }
10087
+
10088
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
10089
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10090
+
10091
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
9842
10092
  }
9843
10093
 
9844
10094
  function uninstallPackage(pkgName, ctx) {
@@ -11942,6 +12192,7 @@ if (typeof module !== 'undefined' && module.exports) {
11942
12192
  targetDir,
11943
12193
  branch: branchOpt,
11944
12194
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
12195
+ signal: ctx.signal,
11945
12196
  onFile: (absPath) => ctx.emitMutation('create', absPath),
11946
12197
  onProgress: (ev) => {
11947
12198
  if (!ev) return;
@@ -11982,6 +12233,9 @@ if (typeof module !== 'undefined' && module.exports) {
11982
12233
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
11983
12234
  return { code: 0, stdout, stderr: '' };
11984
12235
  } catch (err) {
12236
+ if (ctx.signal && ctx.signal.aborted) {
12237
+ return { code: 130, stdout: '', stderr: '', aborted: true };
12238
+ }
11985
12239
  const msg = err && err.message ? err.message : String(err);
11986
12240
  if (canStream) streamLine(msg.endsWith('\n') ? msg : msg + '\n');
11987
12241
  return { code: 128, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
@@ -12309,6 +12563,7 @@ if (typeof module !== 'undefined' && module.exports) {
12309
12563
  targetDir: repoRoot,
12310
12564
  branch: gitState.branch,
12311
12565
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
12566
+ signal: ctx.signal,
12312
12567
  onFile: (absPath) => ctx.emitMutation('change', absPath)
12313
12568
  });
12314
12569
  gitState.headSnapshot = Object.assign({}, result.headSnapshot);
@@ -12318,6 +12573,9 @@ if (typeof module !== 'undefined' && module.exports) {
12318
12573
  stderr: ''
12319
12574
  };
12320
12575
  } catch (err) {
12576
+ if (ctx.signal && ctx.signal.aborted) {
12577
+ return { code: 130, stdout: '', stderr: '', aborted: true };
12578
+ }
12321
12579
  const msg = err && err.message ? err.message : String(err);
12322
12580
  return { code: 1, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
12323
12581
  }
@@ -12507,6 +12765,18 @@ if (typeof module !== 'undefined' && module.exports) {
12507
12765
 
12508
12766
  const sub = args[0];
12509
12767
 
12768
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
12769
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
12770
+ }
12771
+
12772
+ if (sub === '--help' || sub === '-h') {
12773
+ return {
12774
+ code: 0,
12775
+ stdout: 'Bun v1.1.20\nUsage: bun <command> [flags]\n\nCommands:\n run <file|script> Run a file or package script\n install, i, add Install dependencies\n remove, rm Remove dependencies\n test Run tests\n init Scaffold a new project\n -e <code> Evaluate JavaScript\n',
12776
+ stderr: ''
12777
+ };
12778
+ }
12779
+
12510
12780
  if (sub === 'init') {
12511
12781
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
12512
12782
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -12556,12 +12826,28 @@ if (typeof module !== 'undefined' && module.exports) {
12556
12826
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
12557
12827
  }
12558
12828
 
12559
- if (sub === 'add') {
12829
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
12560
12830
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12561
- for (const p of pkgs) {
12562
- installPackage(p, ctx);
12831
+ if (pkgs.length === 0) {
12832
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12833
+ const deps = Object.keys(pkgData.dependencies || {});
12834
+ const results = [];
12835
+ for (const p of deps) results.push(await installPackage(p, ctx));
12836
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12837
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12563
12838
  }
12564
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
12839
+ const results = [];
12840
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12841
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12842
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12843
+ }
12844
+
12845
+ if (sub === 'add') {
12846
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12847
+ const results = [];
12848
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12849
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12850
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12565
12851
  }
12566
12852
 
12567
12853
  if (sub === 'remove' || sub === 'rm') {
@@ -12724,15 +13010,19 @@ if (typeof module !== 'undefined' && module.exports) {
12724
13010
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12725
13011
  if (pkgs.length === 0) {
12726
13012
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13013
+ const results = [];
12727
13014
  for (const p of Object.keys(pkgData.dependencies || {})) {
12728
- installPackage(p, ctx);
13015
+ results.push(await installPackage(p, ctx));
12729
13016
  }
12730
- return { code: 0, stdout: 'up to date\n', stderr: '' };
13017
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13018
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
12731
13019
  }
13020
+ const results = [];
12732
13021
  for (const p of pkgs) {
12733
- installPackage(p, ctx);
13022
+ results.push(await installPackage(p, ctx));
12734
13023
  }
12735
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
13024
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13025
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
12736
13026
  }
12737
13027
 
12738
13028
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -12957,6 +13247,16 @@ if (typeof module !== 'undefined' && module.exports) {
12957
13247
  return PosixPath.resolve(this.cwd, p);
12958
13248
  }
12959
13249
 
13250
+ // True when `name` resolves to a shell function or coreutil (used by the
13251
+ // workbench to route recognised commands straight to the shell instead of
13252
+ // treating flag-looking input such as `node --version` as a JS expression).
13253
+ hasCommand(name) {
13254
+ if (!name) return false;
13255
+ const n = String(name);
13256
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
13257
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
13258
+ }
13259
+
12960
13260
  _emitVfsMutation(type, absPath) {
12961
13261
  if (!this.vfs) return;
12962
13262
  const evt = { type, path: absPath, timestamp: Date.now() };
@@ -16133,6 +16433,9 @@ declare module 'bun:sqlite' {
16133
16433
  this.folders = new Set(this.savedState?.folders || []);
16134
16434
  this.collapsedFolders = new Set(this.savedState?.collapsedFolders || []);
16135
16435
  this.explorerFolder = this.savedState?.explorerFolder || ''; // '' = workspace root, else folder path scope
16436
+ this.explorerWidth = (typeof this.savedState?.explorerWidth === 'number' && this.savedState.explorerWidth >= 120)
16437
+ ? this.savedState.explorerWidth
16438
+ : 196;
16136
16439
  this.folderSwitcherOpen = false;
16137
16440
  this.creatingItem = null; // { type: 'file' | 'folder', parentFolder: string } | null
16138
16441
  this.renamingItem = null;
@@ -16470,7 +16773,8 @@ declare module 'bun:sqlite' {
16470
16773
  activeFile: this.activeFile,
16471
16774
  folders: Array.from(this.folders || []),
16472
16775
  collapsedFolders: Array.from(this.collapsedFolders || []),
16473
- explorerFolder: this.explorerFolder || ''
16776
+ explorerFolder: this.explorerFolder || '',
16777
+ explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined
16474
16778
  };
16475
16779
  this.savedState = state;
16476
16780
  if (this.options && this.options.persistState === false) {
@@ -16651,6 +16955,13 @@ declare module 'bun:sqlite' {
16651
16955
  if (stopBtn) {
16652
16956
  stopBtn.style.display = this.isRunning ? 'inline-flex' : 'none';
16653
16957
  }
16958
+ const ctrlCBtn = this.container.querySelector('#cl-ctrl-c-btn');
16959
+ if (ctrlCBtn) {
16960
+ ctrlCBtn.classList.toggle('is-running', Boolean(this.isRunning));
16961
+ ctrlCBtn.title = this.isRunning
16962
+ ? 'Send Ctrl+C — interrupt the running command'
16963
+ : 'Send Ctrl+C (clears the current input line)';
16964
+ }
16654
16965
  this.container.querySelectorAll('[data-cl-action="run-demo"], [data-cl-action="run-tests"], [data-cl-action="verify-step"]').forEach(btn => {
16655
16966
  btn.disabled = this.isRunning;
16656
16967
  });
@@ -16665,8 +16976,9 @@ declare module 'bun:sqlite' {
16665
16976
  const themeAttr = this.themeOption !== 'auto' ? `data-theme="${escapeHtml(this.themeOption)}"` : '';
16666
16977
  const brandLabel = (this.title && this.title !== 'custom-lab' && this.title !== this.labId) ? this.title : 'code-lab';
16667
16978
  const isGuideCollapsed = !this.hasGuidedLab || this.mode === 'sandbox' || !this.steps.length;
16979
+ const explorerStyle = `style="--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px"`;
16668
16980
  this.container.innerHTML = `
16669
- <div class="codelab codelab-workbench ${isGuideCollapsed ? 'guide-collapsed' : ''}" id="codelab-${escapeHtml(this.labId)}" ${themeAttr}>
16981
+ <div class="codelab codelab-workbench ${isGuideCollapsed ? 'guide-collapsed' : ''}" id="codelab-${escapeHtml(this.labId)}" ${themeAttr} ${explorerStyle}>
16670
16982
  <!-- Top Bar -->
16671
16983
  <div class="codelab-topbar codelab-toolbar">
16672
16984
  <div class="codelab-topbar__left">
@@ -16782,6 +17094,9 @@ declare module 'bun:sqlite' {
16782
17094
  <div class="codelab-explorer__list" id="cl-explorer-list"></div>
16783
17095
  </div>
16784
17096
 
17097
+ <!-- Explorer Resize Splitter -->
17098
+ <div class="codelab-splitter-files" id="cl-splitter-files" role="separator" aria-orientation="vertical" title="Drag to resize file explorer (double-click to reset)"></div>
17099
+
16785
17100
  <!-- Editor Column -->
16786
17101
  <div class="codelab-editor-col">
16787
17102
  <div class="codelab-tabs codelab-file-tabs" id="cl-file-tabs" role="tablist" aria-label="Open Files"></div>
@@ -16835,6 +17150,7 @@ declare module 'bun:sqlite' {
16835
17150
  </button>
16836
17151
  </div>
16837
17152
  <div style="display:flex;align-items:center;gap:6px;">
17153
+ <button type="button" class="codelab-btn codelab-btn--icon codelab-btn--ctrl-c" id="cl-ctrl-c-btn" data-cl-action="interrupt" title="Send Ctrl+C — interrupt a running command" aria-label="Send Ctrl+C interrupt" style="padding:2px 8px;font-size:11px;font-family:var(--cl-font-mono);">Ctrl+C</button>
16838
17154
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="clear-terminal" title="Clear Output" style="padding:2px 6px;font-size:11px;">Clear</button>
16839
17155
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="toggle-drawer" title="Minimize/Expand Drawer" aria-label="Minimize or Expand Drawer" style="padding:2px 6px;font-size:11px;">${CL_ICONS.chevronsUpDown}</button>
16840
17156
  </div>
@@ -17976,10 +18292,10 @@ declare module 'bun:sqlite' {
17976
18292
  this._ptyInputAfterCursor = '';
17977
18293
  this._updatePtyActiveLine();
17978
18294
  }
17979
- } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {
18295
+ } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
17980
18296
  e.preventDefault();
17981
18297
  this._handleInterrupt();
17982
- } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'd') {
18298
+ } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
17983
18299
  e.preventDefault();
17984
18300
  if (this.inRepl) {
17985
18301
  this.inRepl = false;
@@ -17988,7 +18304,7 @@ declare module 'bun:sqlite' {
17988
18304
  const nextInput = this.container.querySelector('#cl-repl-input');
17989
18305
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
17990
18306
  }
17991
- } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'l') {
18307
+ } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
17992
18308
  e.preventDefault();
17993
18309
  this.terminalLogs = [];
17994
18310
  this._renderDrawerBody();
@@ -19733,41 +20049,18 @@ declare module 'bun:sqlite' {
19733
20049
 
19734
20050
  _renderEmptyEditorContent(emptyEl) {
19735
20051
  if (!emptyEl) return;
19736
- const fileBtns = this._orderedFileNames().map(f => {
19737
- const ext = f.endsWith('.ts') ? 'ts' : f.endsWith('.js') ? 'js' : f.endsWith('.json') ? 'json' : f.endsWith('.md') ? 'md' : 'txt';
19738
- return `
19739
- <button type="button" class="codelab-empty-file-btn" data-cl-file="${escapeHtml(f)}" title="Open ${escapeHtml(f)}">
19740
- <span class="codelab-tab__ext codelab-tab__ext--${ext}">${ext.toUpperCase()}</span>
19741
- <span>${escapeHtml(f)}</span>
19742
- </button>
19743
- `;
19744
- }).join('');
19745
-
19746
20052
  emptyEl.innerHTML = `
19747
20053
  <div class="codelab-empty-editor__inner">
19748
- <div class="codelab-empty-editor__icon" aria-hidden="true">
19749
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
19750
- <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
19751
- <polyline points="14 2 14 8 20 8"/>
19752
- </svg>
19753
- </div>
19754
- <h2 class="codelab-empty-editor__title">No Open Editors</h2>
19755
- <p class="codelab-empty-editor__subtitle">Select a file from the explorer on the left or click a workspace file below to open.</p>
19756
- <div class="codelab-empty-editor__files" role="group" aria-label="Workspace Files">
19757
- ${fileBtns}
19758
- </div>
19759
- <div class="codelab-empty-editor__actions">
19760
- <button type="button" class="codelab-btn codelab-btn--run" data-cl-action="run-demo" title="Run demo.js (⇧⌘↵)">
19761
- ${CL_ICONS.play}
19762
- <span>Run Demo</span>
19763
- <span class="codelab-btn__kbd">⇧⌘↵</span>
20054
+ <div class="codelab-empty-editor__watermark" aria-hidden="true">code-lab</div>
20055
+ <div class="codelab-empty-editor__shortcuts" role="group" aria-label="Quick actions">
20056
+ <button type="button" class="codelab-empty-shortcut" data-cl-action="command-palette-files">
20057
+ <span>Go to File</span><kbd>⌘P</kbd>
19764
20058
  </button>
19765
- <button type="button" class="codelab-btn codelab-btn--test" data-cl-action="run-tests" title="Run Test Suite (⌘↵)">
19766
- ${CL_ICONS.check}
19767
- <span>Run Tests</span>
19768
- <span class="codelab-btn__kbd">⌘↵</span>
20059
+ <button type="button" class="codelab-empty-shortcut" data-cl-action="command-palette">
20060
+ <span>Show All Commands</span><kbd>⌘⇧P</kbd>
19769
20061
  </button>
19770
20062
  </div>
20063
+ <p class="codelab-empty-editor__subtitle">No editors open. Select a file from the Explorer to start editing.</p>
19771
20064
  </div>
19772
20065
  `;
19773
20066
  }
@@ -19837,7 +20130,7 @@ declare module 'bun:sqlite' {
19837
20130
  this.openCommandPalette('files');
19838
20131
  return;
19839
20132
  }
19840
- if ((e.metaKey || e.ctrlKey) && keyLower === 'c') {
20133
+ if (e.ctrlKey && !e.metaKey && keyLower === 'c') {
19841
20134
  const hasSelection = typeof window !== 'undefined' && window.getSelection && window.getSelection().toString().length > 0;
19842
20135
  if (!hasSelection && (this.isRunning || this._activeCommandAbortController)) {
19843
20136
  e.preventDefault();
@@ -20139,6 +20432,7 @@ declare module 'bun:sqlite' {
20139
20432
  if (action === 'run-demo') this.runDemo();
20140
20433
  else if (action === 'run-tests') this.runTests();
20141
20434
  else if (action === 'stop-run') this.stopExecution();
20435
+ else if (action === 'interrupt') this._handleInterrupt();
20142
20436
  else if (action === 'verify-step') this.verifyCurrentStep();
20143
20437
  else if (action === 'show-diff') this.showSolutionModal();
20144
20438
  else if (action === 'compare-diff') {
@@ -20732,6 +21026,48 @@ declare module 'bun:sqlite' {
20732
21026
  hSplitter.addEventListener('pointerup', onUp);
20733
21027
  });
20734
21028
  }
21029
+
21030
+ const fSplitter = this.container.querySelector('#cl-splitter-files');
21031
+ if (fSplitter) {
21032
+ const applyWidth = (w) => {
21033
+ this.explorerWidth = Math.round(w);
21034
+ shell.style.setProperty('--cl-explorer-width', `${this.explorerWidth}px`);
21035
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
21036
+ };
21037
+
21038
+ fSplitter.addEventListener('dblclick', () => {
21039
+ applyWidth(196);
21040
+ this._saveState();
21041
+ });
21042
+
21043
+ fSplitter.addEventListener('pointerdown', e => {
21044
+ e.preventDefault();
21045
+ fSplitter.classList.add('is-dragging');
21046
+ shell.classList.add('is-resizing');
21047
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
21048
+
21049
+ const onMove = ev => {
21050
+ const ws = this.container.querySelector('.codelab-workspace');
21051
+ const rect = (ws || shell).getBoundingClientRect();
21052
+ const minW = 140;
21053
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.5));
21054
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(ev.clientX - rect.left)));
21055
+ applyWidth(nextW);
21056
+ };
21057
+
21058
+ const onUp = ev => {
21059
+ fSplitter.classList.remove('is-dragging');
21060
+ shell.classList.remove('is-resizing');
21061
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
21062
+ fSplitter.removeEventListener('pointermove', onMove);
21063
+ fSplitter.removeEventListener('pointerup', onUp);
21064
+ this._saveState();
21065
+ };
21066
+
21067
+ fSplitter.addEventListener('pointermove', onMove);
21068
+ fSplitter.addEventListener('pointerup', onUp);
21069
+ });
21070
+ }
20735
21071
  }
20736
21072
 
20737
21073
  selectStep(idx, shouldJump = true) {
@@ -21011,14 +21347,14 @@ declare module 'bun:sqlite' {
21011
21347
  </div>
21012
21348
  ${pkgs.length === 0 ? `
21013
21349
  <div style="padding:12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);color:var(--cl-fg-muted);font-size:12.5px;">
21014
- No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>esm.sh</strong> when you run or test.
21350
+ No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>jsDelivr</strong> when you run or test.
21015
21351
  </div>
21016
21352
  ` : `
21017
21353
  <div style="display:flex;flex-direction:column;gap:6px;">
21018
21354
  ${pkgs.map(p => `
21019
21355
  <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);font-family:var(--cl-font-mono);font-size:12px;">
21020
21356
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
21021
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
21357
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
21022
21358
  </div>
21023
21359
  `).join('')}
21024
21360
  </div>
@@ -21128,6 +21464,12 @@ declare module 'bun:sqlite' {
21128
21464
  }
21129
21465
 
21130
21466
  // ── Execution Engine (Web Worker + Virtual Node Runtime) ───────────────
21467
+ _isAbortResult(res, signal) {
21468
+ if (signal && signal.aborted) return true;
21469
+ if (!res || typeof res !== 'object') return false;
21470
+ return Boolean(res.cancelled || res.aborted || res.exitCode === 130);
21471
+ }
21472
+
21131
21473
  async _executeRuntime(execOptions) {
21132
21474
  const t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
21133
21475
  const payload = {
@@ -21146,9 +21488,14 @@ declare module 'bun:sqlite' {
21146
21488
  if (detectedList.length > 0) {
21147
21489
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
21148
21490
  }
21149
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21150
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
21491
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21492
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
21151
21493
  });
21494
+ // Hand the fetched module sources to the runtime so the Web Worker
21495
+ // (which has an isolated module cache) can resolve them from node_modules.
21496
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
21497
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
21498
+ }
21152
21499
  }
21153
21500
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
21154
21501
  let res;
@@ -21164,7 +21511,11 @@ declare module 'bun:sqlite' {
21164
21511
  this._setRuntimeStatus('idle', 'Ready · Node v22 VFS');
21165
21512
  return res;
21166
21513
  } catch (err) {
21167
- this._setRuntimeStatus('error', 'Execution error');
21514
+ if (payload.signal && payload.signal.aborted) {
21515
+ this._setRuntimeStatus('idle', 'Ready · Node v22 VFS');
21516
+ } else {
21517
+ this._setRuntimeStatus('error', 'Execution error');
21518
+ }
21168
21519
  throw err;
21169
21520
  }
21170
21521
  }
@@ -21206,18 +21557,21 @@ declare module 'bun:sqlite' {
21206
21557
  }
21207
21558
  });
21208
21559
  this._flushTerminalStream();
21560
+ const aborted = this._isAbortResult(res, abortCtrl.signal);
21209
21561
 
21210
- if (!streamedStdout && res.stdout) {
21562
+ if (!aborted && !streamedStdout && res.stdout) {
21211
21563
  this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
21212
21564
  }
21213
- if (!streamedStderr && res.stderr) {
21565
+ if (!aborted && !streamedStderr && res.stderr) {
21214
21566
  this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
21215
21567
  }
21216
- if (res.error) {
21568
+ if (!aborted && res.error) {
21217
21569
  this.terminalLogs.push({ type: 'stderr', text: formatErrorText(res.error) });
21218
21570
  }
21219
- this.lastFsSnapshot = res.fsSnapshot || [];
21220
- this.lastHttpTrace = res.httpTrace || [];
21571
+ if (!aborted) {
21572
+ this.lastFsSnapshot = res.fsSnapshot || [];
21573
+ this.lastHttpTrace = res.httpTrace || [];
21574
+ }
21221
21575
 
21222
21576
  if (this.onRun) {
21223
21577
  try { this.onRun(res); } catch (_) {}
@@ -21225,7 +21579,9 @@ declare module 'bun:sqlite' {
21225
21579
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
21226
21580
  } catch (err) {
21227
21581
  this._flushTerminalStream();
21228
- this.terminalLogs.push({ type: 'stderr', text: `Execution error: ${formatErrorText(err)}` });
21582
+ if (!(abortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
21583
+ this.terminalLogs.push({ type: 'stderr', text: `Execution error: ${formatErrorText(err)}` });
21584
+ }
21229
21585
  } finally {
21230
21586
  if (this._activeCommandAbortController === abortCtrl) {
21231
21587
  this._activeCommandAbortController = null;
@@ -21274,18 +21630,21 @@ declare module 'bun:sqlite' {
21274
21630
  }
21275
21631
  });
21276
21632
  this._flushTerminalStream();
21633
+ const aborted = this._isAbortResult(res, abortCtrl.signal);
21277
21634
 
21278
- this.lastTestResults = res.testResults || [];
21279
- this.lastFsSnapshot = res.fsSnapshot || [];
21280
- this.lastHttpTrace = res.httpTrace || [];
21635
+ if (!aborted) {
21636
+ this.lastTestResults = res.testResults || [];
21637
+ this.lastFsSnapshot = res.fsSnapshot || [];
21638
+ this.lastHttpTrace = res.httpTrace || [];
21639
+ }
21281
21640
 
21282
- if (!streamedStdout && res.stdout) {
21641
+ if (!aborted && !streamedStdout && res.stdout) {
21283
21642
  this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
21284
21643
  }
21285
- if (!streamedStderr && res.stderr) {
21644
+ if (!aborted && !streamedStderr && res.stderr) {
21286
21645
  this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
21287
21646
  }
21288
- if (res.error) {
21647
+ if (!aborted && res.error) {
21289
21648
  this.terminalLogs.push({ type: 'stderr', text: formatErrorText(res.error) });
21290
21649
  }
21291
21650
 
@@ -21336,7 +21695,9 @@ declare module 'bun:sqlite' {
21336
21695
  }
21337
21696
  } catch (err) {
21338
21697
  this._flushTerminalStream();
21339
- this.terminalLogs.push({ type: 'stderr', text: `Test runner error: ${formatErrorText(err)}` });
21698
+ if (!(abortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
21699
+ this.terminalLogs.push({ type: 'stderr', text: `Test runner error: ${formatErrorText(err)}` });
21700
+ }
21340
21701
  } finally {
21341
21702
  if (this._activeCommandAbortController === abortCtrl) {
21342
21703
  this._activeCommandAbortController = null;
@@ -21427,16 +21788,19 @@ declare module 'bun:sqlite' {
21427
21788
  onStderr: (c) => { streamedStderr = true; this._appendTerminalStream('stderr', c); }
21428
21789
  });
21429
21790
  this._flushTerminalStream();
21791
+ const aborted = this._isAbortResult(res, abortCtrl.signal);
21430
21792
  const cleanStdout = res.stdout ? res.stdout.replace(/\n$/, '') : '';
21431
- if (!streamedStdout && cleanStdout) this.terminalLogs.push({ type: 'stdout', text: cleanStdout });
21432
- if (!streamedStderr && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
21433
- if (res.replValue !== undefined && cleanStdout !== String(res.replValue)) {
21793
+ if (!aborted && !streamedStdout && cleanStdout) this.terminalLogs.push({ type: 'stdout', text: cleanStdout });
21794
+ if (!aborted && !streamedStderr && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
21795
+ if (!aborted && res.replValue !== undefined && cleanStdout !== String(res.replValue)) {
21434
21796
  this.terminalLogs.push({ type: 'success', text: `→ ${res.replValue}` });
21435
21797
  }
21436
- if (res.error) this.terminalLogs.push({ type: 'stderr', text: formatErrorText(res.error) });
21798
+ if (!aborted && res.error) this.terminalLogs.push({ type: 'stderr', text: formatErrorText(res.error) });
21437
21799
  } catch (err) {
21438
21800
  this._flushTerminalStream();
21439
- this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21801
+ if (!(abortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
21802
+ this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21803
+ }
21440
21804
  } finally {
21441
21805
  if (this._activeCommandAbortController === abortCtrl) {
21442
21806
  this._activeCommandAbortController = null;
@@ -21468,8 +21832,17 @@ declare module 'bun:sqlite' {
21468
21832
  return;
21469
21833
  }
21470
21834
 
21471
- const looksLikeJsExpr = /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
21472
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
21835
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
21836
+ const shellKnowsCommand = Boolean(
21837
+ firstWord &&
21838
+ this.shell &&
21839
+ typeof this.shell.hasCommand === 'function' &&
21840
+ this.shell.hasCommand(firstWord)
21841
+ );
21842
+ const looksLikeJsExpr = !shellKnowsCommand && (
21843
+ /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
21844
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
21845
+ );
21473
21846
 
21474
21847
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
21475
21848
  const abortCtrl = new AbortController();
@@ -21495,6 +21868,7 @@ declare module 'bun:sqlite' {
21495
21868
  signal: abortCtrl.signal
21496
21869
  });
21497
21870
  this._flushTerminalStream();
21871
+ const aborted = this._isAbortResult(shellRes, abortCtrl.signal);
21498
21872
  this.cwd = this.shell.cwd || this.cwd;
21499
21873
  this._syncVfsSnapshot(null, true);
21500
21874
 
@@ -21514,10 +21888,10 @@ declare module 'bun:sqlite' {
21514
21888
 
21515
21889
  const isCmdNotFound = shellRes && shellRes.exitCode === 127 && typeof shellRes.stderr === 'string' && shellRes.stderr.includes('command not found');
21516
21890
  if (!isCmdNotFound) {
21517
- if (shellRes && shellRes.stdout && !streamedStdout) {
21891
+ if (!aborted && shellRes && shellRes.stdout && !streamedStdout) {
21518
21892
  this.terminalLogs.push({ type: 'stdout', text: shellRes.stdout.replace(/\n$/, '') });
21519
21893
  }
21520
- if (shellRes && shellRes.stderr && !streamedStderr) {
21894
+ if (!aborted && shellRes && shellRes.stderr && !streamedStderr) {
21521
21895
  this.terminalLogs.push({ type: 'stderr', text: shellRes.stderr.replace(/\n$/, '') });
21522
21896
  }
21523
21897
  this._renderDrawerBody();
@@ -21530,7 +21904,9 @@ declare module 'bun:sqlite' {
21530
21904
  }
21531
21905
  } catch (err) {
21532
21906
  this._flushTerminalStream();
21533
- this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21907
+ if (!(abortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
21908
+ this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21909
+ }
21534
21910
  this._renderDrawerBody();
21535
21911
  return;
21536
21912
  } finally {
@@ -21566,17 +21942,18 @@ declare module 'bun:sqlite' {
21566
21942
  }
21567
21943
  });
21568
21944
  this._flushTerminalStream();
21945
+ const aborted = this._isAbortResult(res, fallbackAbortCtrl.signal);
21569
21946
  const cleanStdout = res.stdout ? res.stdout.replace(/\n$/, '') : '';
21570
- if (!streamedFallbackStdout && cleanStdout) {
21947
+ if (!aborted && !streamedFallbackStdout && cleanStdout) {
21571
21948
  this.terminalLogs.push({ type: 'stdout', text: cleanStdout });
21572
21949
  }
21573
- if (!streamedFallbackStderr && res.stderr) {
21950
+ if (!aborted && !streamedFallbackStderr && res.stderr) {
21574
21951
  this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
21575
21952
  }
21576
- if (res.replValue !== undefined && cleanStdout !== String(res.replValue)) {
21953
+ if (!aborted && res.replValue !== undefined && cleanStdout !== String(res.replValue)) {
21577
21954
  this.terminalLogs.push({ type: 'success', text: `→ ${res.replValue}` });
21578
21955
  }
21579
- if (res.error) {
21956
+ if (!aborted && res.error) {
21580
21957
  const errStr = formatErrorText(res.error);
21581
21958
  if (/^[a-zA-Z0-9_-]+$/.test(trimmed) && errStr.includes(`ReferenceError: ${trimmed} is not defined`)) {
21582
21959
  this.terminalLogs.push({ type: 'stderr', text: `codelab: ${trimmed}: command not found (type "help" for commands or enter a JS/TS expression)` });
@@ -21586,7 +21963,9 @@ declare module 'bun:sqlite' {
21586
21963
  }
21587
21964
  } catch (err) {
21588
21965
  this._flushTerminalStream();
21589
- this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21966
+ if (!(fallbackAbortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
21967
+ this.terminalLogs.push({ type: 'stderr', text: formatErrorText(err) });
21968
+ }
21590
21969
  } finally {
21591
21970
  if (this._activeCommandAbortController === fallbackAbortCtrl) {
21592
21971
  this._activeCommandAbortController = null;
@@ -21838,8 +22217,13 @@ declare module 'bun:sqlite' {
21838
22217
  const intoRoot = options.intoRoot !== false;
21839
22218
  const targetDir = intoRoot ? '/workspace' : `/workspace/${parsed.repo}`;
21840
22219
  const cmdDisplay = `git clone ${repoInput}${intoRoot ? ' .' : ''}`;
22220
+ this.drawerTab = 'terminal';
21841
22221
  this.terminalLogs.push({ type: 'cmd', text: cmdDisplay });
22222
+ this.isRunning = true;
22223
+ const abortCtrl = new AbortController();
22224
+ this._activeCommandAbortController = abortCtrl;
21842
22225
  this._renderDrawerBody();
22226
+ this._updateRunStateUI();
21843
22227
 
21844
22228
  try {
21845
22229
  if (intoRoot && this.shell && this.shell.vfs) {
@@ -21862,6 +22246,7 @@ declare module 'bun:sqlite' {
21862
22246
  maxFiles: options.maxFiles || 250,
21863
22247
  maxFileSize: options.maxFileSize || 512 * 1024,
21864
22248
  fetchImpl: options.fetchImpl || (this.shell && this.shell.options ? this.shell.options.fetchImpl : undefined),
22249
+ signal: abortCtrl.signal,
21865
22250
  onProgress: options.onProgress
21866
22251
  });
21867
22252
 
@@ -21933,10 +22318,18 @@ declare module 'bun:sqlite' {
21933
22318
  this._emitEvent('repo:cloned', eventDetail);
21934
22319
  return result;
21935
22320
  } catch (err) {
21936
- const msg = err && err.message ? err.message : String(err);
21937
- this.terminalLogs.push({ type: 'stderr', text: msg });
22321
+ if (!(abortCtrl.signal.aborted || (err && err.name === 'AbortError'))) {
22322
+ const msg = err && err.message ? err.message : String(err);
22323
+ this.terminalLogs.push({ type: 'stderr', text: msg });
22324
+ }
21938
22325
  this._renderDrawerBody();
21939
22326
  throw err;
22327
+ } finally {
22328
+ if (this._activeCommandAbortController === abortCtrl) {
22329
+ this._activeCommandAbortController = null;
22330
+ }
22331
+ this.isRunning = false;
22332
+ this._updateRunStateUI();
21940
22333
  }
21941
22334
  }
21942
22335