@innovatorved/code-lab 0.1.3 → 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/README.md CHANGED
@@ -22,7 +22,7 @@ Browser-native code IDE workbench, modular guided challenge engine (`@innovatorv
22
22
  - **Bun**: Native `.ts` transpilation, `Bun.serve()`, `Bun.file()`, `Bun.write()`, `Bun.spawn()`, `Bun.password`, `Bun.hash()`, `bun:test`, and VFS-backed `bun:sqlite`.
23
23
  - **Persistent HTTP/TCP Servers & Dual Web Preview**: Start background servers (`node server.js &` or `bun run server.ts &`), query them with `curl http://localhost:3000` or global `fetch()`, and view live responses in the Ports table, an embedded **Web Preview** tab (URL bar, back/forward, device frames), or a popped-out browser tab backed by a virtual-loopback Service Worker (`/__preview/:port/*`). Public URLs (e.g. `https://example.com`) entered in the preview URL bar open in a real browser tab instead of the virtual frame.
24
24
  - **GitHub-Flavored Markdown Engine**: Zero-dependency GFM renderer (tables with column alignment, `[!NOTE]` / `[!TIP]` / `[!IMPORTANT]` / `[!WARNING]` / `[!CAUTION]` callout alerts, task-list checkboxes, and syntax-highlighted code blocks with one-click copy) powering the Guide tab, hints, and `.md` file previews.
25
- - **NPM & Bun Package Management**: `npm i <pkg>` and `bun add <pkg>` resolve dependencies from npm / esm.sh into virtual `/workspace/node_modules/<pkg>` and update `package.json`.
25
+ - **NPM & Bun Package Management**: `npm i <pkg>` / `bun add <pkg>` / `bun install` fetch the real package (and its transitive dependencies) from the jsDelivr CDN into virtual `/workspace/node_modules/<pkg>` and update `package.json`; packages stay `require()`-able from `node`/`bun run`, with a bundled offline fallback for common demo packages.
26
26
  - **Guided Step-by-Step Challenges**: TutorialKit / Codedamn-style curriculum extension with targeted instructions, hints, automated test verification per step, and reference solutions.
27
27
  - **Headless Runtime**: Programmatic execution engine (`@innovatorved/code-lab/runtime`) for grading, testing, or automated evaluation with zero UI.
28
28
 
@@ -273,7 +273,8 @@ export interface CodeLabRuntimeAPI {
273
273
  executeInVirtualRuntime(options?: CodeLabExecutionOptions): Promise<CodeLabExecutionResult>;
274
274
  executeInWorker(options?: CodeLabExecutionOptions): Promise<CodeLabExecutionResult>;
275
275
  cancelWorkerExecution(reason?: string, instanceId?: string): boolean;
276
- preloadNpmPackages(files?: Record<string, string>, existingCache?: Map<string, string>): Promise<Record<string, string>>;
276
+ preloadNpmPackages(files?: Record<string, string>, onProgress?: (pkg: string) => void): Promise<Record<string, string>>;
277
+ preloadNpmPackages(files: Record<string, string> | undefined, existingCache: Map<string, string>, onProgress?: (pkg: string) => void): Promise<Record<string, string>>;
277
278
  transpileTS(source: string, filename?: string): string;
278
279
  createVirtualFs(initialFiles?: Record<string, string>): any;
279
280
  createVirtualHttp(resourceTracker?: any, sharedTrace?: any[], activePortTable?: any): any;
@@ -4681,8 +4681,22 @@ function __initVirtualRuntime(rootScope) {
4681
4681
  }
4682
4682
 
4683
4683
  const _npmPackageCache = new Map();
4684
+ const _npmMetadataCache = new Map();
4685
+
4686
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4687
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4688
+ // preloadNpmPackages(files)
4689
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4690
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4691
+ // preloadNpmPackages(files, existingCache, onProgress)
4692
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4693
+ let onProgress = null;
4694
+ let existingCache = _npmPackageCache;
4695
+ if (typeof secondArg === 'function') onProgress = secondArg;
4696
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4697
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4698
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4684
4699
 
4685
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4686
4700
  const specs = new Set();
4687
4701
  const builtinSet = new Set([
4688
4702
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4718,20 +4732,51 @@ function __initVirtualRuntime(rootScope) {
4718
4732
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4719
4733
  }
4720
4734
 
4735
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4736
+ // is memoised across calls so repeated preloads stay cheap.
4737
+ if (typeof fetch === 'function') {
4738
+ let pass = 0;
4739
+ while (pass < 6) {
4740
+ const pending = [];
4741
+ for (const pkg of specs) {
4742
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4743
+ }
4744
+ if (pending.length === 0) break;
4745
+ pass++;
4746
+ await Promise.all(pending.map(async (pkg) => {
4747
+ let deps = [];
4748
+ try {
4749
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4750
+ if (res && res.ok) {
4751
+ const meta = await res.json();
4752
+ deps = Object.keys((meta && meta.dependencies) || {});
4753
+ }
4754
+ } catch (_) {}
4755
+ _npmMetadataCache.set(pkg, deps);
4756
+ }));
4757
+ for (const pkg of pending) {
4758
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4759
+ }
4760
+ }
4761
+ }
4762
+
4721
4763
  const loaded = {};
4722
4764
  for (const pkg of specs) {
4723
4765
  const nmKey = `node_modules/${pkg}/index.js`;
4724
4766
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4725
- if (existingCache && existingCache.has(pkg)) {
4767
+ if (existingCache.has(pkg)) {
4726
4768
  loaded[pkg] = existingCache.get(pkg);
4727
4769
  continue;
4728
4770
  }
4771
+ if (typeof onProgress === 'function') {
4772
+ try { onProgress(pkg); } catch (_) {}
4773
+ }
4729
4774
  if (typeof fetch === 'function') {
4730
4775
  try {
4731
4776
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4732
4777
  if (res && res.ok) {
4733
4778
  const text = await res.text();
4734
- if (existingCache) existingCache.set(pkg, text);
4779
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4735
4780
  loaded[pkg] = text;
4736
4781
  }
4737
4782
  } catch (_) {}
@@ -9826,38 +9871,221 @@ if (typeof module !== 'undefined' && module.exports) {
9826
9871
  } catch (_) {}
9827
9872
  }
9828
9873
 
9829
- function installPackage(pkgSpec, ctx) {
9830
- const parts = pkgSpec.split('@').filter(Boolean);
9831
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
9832
- const pkgVersion = parts[1] || '^1.0.0';
9874
+ // ---------------------------------------------------------------------------
9875
+ // Real npm package installation via the jsDelivr CDN
9876
+ // ---------------------------------------------------------------------------
9877
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
9878
+
9879
+ // Minimal offline registry, used only when the CDN is unreachable so common
9880
+ // demos still resolve without network access.
9881
+ const OFFLINE_PACKAGE_FALLBACKS = {
9882
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
9883
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
9884
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
9885
+ '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'
9886
+ };
9887
+
9888
+ function packageCtxFetch(ctx) {
9889
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
9890
+ return ctx.shell.options.fetchImpl;
9891
+ }
9892
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
9893
+ return null;
9894
+ }
9895
+
9896
+ function parsePackageSpec(spec) {
9897
+ const raw = String(spec || '').trim();
9898
+ if (!raw) return { name: '', range: null };
9899
+ if (raw.startsWith('@')) {
9900
+ const at = raw.indexOf('@', 1);
9901
+ if (at === -1) return { name: raw, range: null };
9902
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9903
+ }
9904
+ const at = raw.indexOf('@');
9905
+ if (at <= 0) return { name: raw, range: null };
9906
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9907
+ }
9908
+
9909
+ function resolveEntryRelPath(pkgJson) {
9910
+ let entry = pkgJson.main || pkgJson.module ||
9911
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
9912
+ entry = String(entry).replace(/^[./]+/, '');
9913
+ return entry || 'index.js';
9914
+ }
9915
+
9916
+ function stripRelPath(rel) {
9917
+ return String(rel || '').replace(/^[./]+/, '');
9918
+ }
9919
+
9920
+ function extractRelativeSpecifiers(code) {
9921
+ const out = new Set();
9922
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
9923
+ let m;
9924
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
9925
+ return Array.from(out);
9926
+ }
9927
+
9928
+ function normalizeRelPath(baseDir, rel) {
9929
+ const parts = String(baseDir || '').split('/').filter(Boolean);
9930
+ for (const seg of String(rel).split('/')) {
9931
+ if (!seg || seg === '.') continue;
9932
+ if (seg === '..') parts.pop();
9933
+ else parts.push(seg);
9934
+ }
9935
+ return parts.join('/');
9936
+ }
9937
+
9938
+ async function fetchTextFromCdn(fetchImpl, url) {
9939
+ try {
9940
+ const res = await fetchImpl(url);
9941
+ if (!res) return null;
9942
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
9943
+ if (!ok) return null;
9944
+ if (typeof res.text === 'function') return await res.text();
9945
+ return String(res.body != null ? res.body : '');
9946
+ } catch (_) {
9947
+ return null;
9948
+ }
9949
+ }
9950
+
9951
+ async function resolvePackageMetadata(fetchImpl, name, range) {
9952
+ const urls = range
9953
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
9954
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
9955
+ for (const url of urls) {
9956
+ const text = await fetchTextFromCdn(fetchImpl, url);
9957
+ if (!text) continue;
9958
+ try {
9959
+ const parsed = JSON.parse(text);
9960
+ if (parsed && parsed.version) return parsed;
9961
+ } catch (_) {}
9962
+ }
9963
+ return null;
9964
+ }
9965
+
9966
+ // Download a package's entry module, its relative submodules and record its
9967
+ // declared dependencies so the caller can resolve them transitively.
9968
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
9969
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
9970
+ if (!meta) {
9971
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
9972
+ if (fallback) {
9973
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
9974
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
9975
+ }
9976
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
9977
+ }
9978
+
9979
+ const version = meta.version;
9980
+ const key = `${name}@${version}`;
9981
+ if (seen.has(key)) {
9982
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
9983
+ }
9984
+ seen.add(key);
9985
+
9986
+ const entry = resolveEntryRelPath(meta);
9987
+ const files = [];
9988
+ const visited = new Set();
9989
+ const queue = [entry];
9990
+ while (queue.length > 0) {
9991
+ const rel = stripRelPath(queue.shift());
9992
+ if (!rel || visited.has(rel)) continue;
9993
+ visited.add(rel);
9994
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
9995
+ if (text === null) continue;
9996
+ files.push({ rel, content: text });
9997
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
9998
+ for (const spec of extractRelativeSpecifiers(text)) {
9999
+ const target = normalizeRelPath(baseDir, spec);
10000
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
10001
+ const c = stripRelPath(cand);
10002
+ if (c && !visited.has(c)) { queue.push(cand); break; }
10003
+ }
10004
+ }
10005
+ }
10006
+ // The declared entry may be missing on the CDN; fall back to index.js.
10007
+ if (!files.some(f => f.rel === entry)) {
10008
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
10009
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10010
+ }
10011
+
10012
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
10013
+ }
10014
+
10015
+ function installTargetDirs(ctx, name) {
10016
+ const dirs = ['/workspace/node_modules/' + name];
10017
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
10018
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
10019
+ return dirs;
10020
+ }
10021
+
10022
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
10023
+ for (const dir of dirs) {
10024
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10025
+ for (const f of info.files) {
10026
+ const full = PosixPath.join(dir, f.rel);
10027
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10028
+ ctx.vfs.writeFileSync(full, f.content);
10029
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
10030
+ }
10031
+ const modPkgPath = PosixPath.join(dir, 'package.json');
10032
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
10033
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
10034
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10035
+ }
10036
+ }
10037
+
10038
+ async function installPackage(pkgSpec, ctx) {
10039
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10040
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
9833
10041
 
9834
10042
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
9835
10043
  if (!pkgData.dependencies) pkgData.dependencies = {};
9836
- pkgData.dependencies[pkgName] = pkgVersion;
9837
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
9838
10044
 
9839
- const targetDirs = ['/workspace/node_modules/' + pkgName];
9840
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
9841
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
10045
+ const fetchImpl = packageCtxFetch(ctx);
10046
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
10047
+ ? ctx.shell._cdnSeen
10048
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
10049
+
10050
+ const queue = [{ name: pkgName, range, direct: true }];
10051
+ const requested = new Set([pkgName]);
10052
+ const installed = [];
10053
+ let warning = null;
10054
+ let directVersion = null;
10055
+
10056
+ while (queue.length > 0) {
10057
+ const item = queue.shift();
10058
+ const info = fetchImpl
10059
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
10060
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
10061
+
10062
+ if (!info.ok) {
10063
+ // Final fallback: an empty stub so offline demos still resolve the module.
10064
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
10065
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
10066
+ });
10067
+ if (!warning) warning = info.reason;
10068
+ installed.push({ name: item.name, version: '0.0.0' });
10069
+ continue;
10070
+ }
9842
10071
 
9843
- for (const modDir of targetDirs) {
9844
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
9845
- const modPkgPath = PosixPath.join(modDir, 'package.json');
9846
- const modIndexPath = PosixPath.join(modDir, 'index.js');
9847
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
9848
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10072
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
10073
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
10074
+ if (item.direct) directVersion = info.version || null;
9849
10075
 
9850
- let code = 'module.exports = {};\n';
9851
- if (pkgName === 'is-even') {
9852
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
9853
- } else if (pkgName === 'tiny-invariant') {
9854
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
9855
- } else if (pkgName === 'lodash') {
9856
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
10076
+ for (const dep of (info.deps || [])) {
10077
+ const parsed = parsePackageSpec(dep);
10078
+ if (parsed.name && !requested.has(parsed.name)) {
10079
+ requested.add(parsed.name);
10080
+ queue.push({ name: parsed.name, range: null, direct: false });
10081
+ }
9857
10082
  }
9858
- ctx.vfs.writeFileSync(modIndexPath, code);
9859
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
9860
10083
  }
10084
+
10085
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
10086
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10087
+
10088
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
9861
10089
  }
9862
10090
 
9863
10091
  function uninstallPackage(pkgName, ctx) {
@@ -12534,6 +12762,18 @@ if (typeof module !== 'undefined' && module.exports) {
12534
12762
 
12535
12763
  const sub = args[0];
12536
12764
 
12765
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
12766
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
12767
+ }
12768
+
12769
+ if (sub === '--help' || sub === '-h') {
12770
+ return {
12771
+ code: 0,
12772
+ 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',
12773
+ stderr: ''
12774
+ };
12775
+ }
12776
+
12537
12777
  if (sub === 'init') {
12538
12778
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
12539
12779
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -12583,12 +12823,28 @@ if (typeof module !== 'undefined' && module.exports) {
12583
12823
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
12584
12824
  }
12585
12825
 
12586
- if (sub === 'add') {
12826
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
12587
12827
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12588
- for (const p of pkgs) {
12589
- installPackage(p, ctx);
12828
+ if (pkgs.length === 0) {
12829
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12830
+ const deps = Object.keys(pkgData.dependencies || {});
12831
+ const results = [];
12832
+ for (const p of deps) results.push(await installPackage(p, ctx));
12833
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12834
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12590
12835
  }
12591
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
12836
+ const results = [];
12837
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12838
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12839
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12840
+ }
12841
+
12842
+ if (sub === 'add') {
12843
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12844
+ const results = [];
12845
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12846
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12847
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12592
12848
  }
12593
12849
 
12594
12850
  if (sub === 'remove' || sub === 'rm') {
@@ -12751,15 +13007,19 @@ if (typeof module !== 'undefined' && module.exports) {
12751
13007
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12752
13008
  if (pkgs.length === 0) {
12753
13009
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13010
+ const results = [];
12754
13011
  for (const p of Object.keys(pkgData.dependencies || {})) {
12755
- installPackage(p, ctx);
13012
+ results.push(await installPackage(p, ctx));
12756
13013
  }
12757
- return { code: 0, stdout: 'up to date\n', stderr: '' };
13014
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13015
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
12758
13016
  }
13017
+ const results = [];
12759
13018
  for (const p of pkgs) {
12760
- installPackage(p, ctx);
13019
+ results.push(await installPackage(p, ctx));
12761
13020
  }
12762
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
13021
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13022
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
12763
13023
  }
12764
13024
 
12765
13025
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -12984,6 +13244,16 @@ if (typeof module !== 'undefined' && module.exports) {
12984
13244
  return PosixPath.resolve(this.cwd, p);
12985
13245
  }
12986
13246
 
13247
+ // True when `name` resolves to a shell function or coreutil (used by the
13248
+ // workbench to route recognised commands straight to the shell instead of
13249
+ // treating flag-looking input such as `node --version` as a JS expression).
13250
+ hasCommand(name) {
13251
+ if (!name) return false;
13252
+ const n = String(name);
13253
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
13254
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
13255
+ }
13256
+
12987
13257
  _emitVfsMutation(type, absPath) {
12988
13258
  if (!this.vfs) return;
12989
13259
  const evt = { type, path: absPath, timestamp: Date.now() };
@@ -21070,14 +21340,14 @@ declare module 'bun:sqlite' {
21070
21340
  </div>
21071
21341
  ${pkgs.length === 0 ? `
21072
21342
  <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;">
21073
- 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.
21343
+ 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.
21074
21344
  </div>
21075
21345
  ` : `
21076
21346
  <div style="display:flex;flex-direction:column;gap:6px;">
21077
21347
  ${pkgs.map(p => `
21078
21348
  <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;">
21079
21349
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
21080
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
21350
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
21081
21351
  </div>
21082
21352
  `).join('')}
21083
21353
  </div>
@@ -21211,9 +21481,14 @@ declare module 'bun:sqlite' {
21211
21481
  if (detectedList.length > 0) {
21212
21482
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
21213
21483
  }
21214
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21215
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
21484
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21485
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
21216
21486
  });
21487
+ // Hand the fetched module sources to the runtime so the Web Worker
21488
+ // (which has an isolated module cache) can resolve them from node_modules.
21489
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
21490
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
21491
+ }
21217
21492
  }
21218
21493
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
21219
21494
  let res;
@@ -21550,8 +21825,17 @@ declare module 'bun:sqlite' {
21550
21825
  return;
21551
21826
  }
21552
21827
 
21553
- 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)
21554
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
21828
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
21829
+ const shellKnowsCommand = Boolean(
21830
+ firstWord &&
21831
+ this.shell &&
21832
+ typeof this.shell.hasCommand === 'function' &&
21833
+ this.shell.hasCommand(firstWord)
21834
+ );
21835
+ const looksLikeJsExpr = !shellKnowsCommand && (
21836
+ /^(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)
21837
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
21838
+ );
21555
21839
 
21556
21840
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
21557
21841
  const abortCtrl = new AbortController();