@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/src/shell.ts CHANGED
@@ -2386,38 +2386,221 @@ function __initShellModule(root: any) {
2386
2386
  } catch (_) {}
2387
2387
  }
2388
2388
 
2389
- function installPackage(pkgSpec, ctx) {
2390
- const parts = pkgSpec.split('@').filter(Boolean);
2391
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
2392
- const pkgVersion = parts[1] || '^1.0.0';
2389
+ // ---------------------------------------------------------------------------
2390
+ // Real npm package installation via the jsDelivr CDN
2391
+ // ---------------------------------------------------------------------------
2392
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
2393
+
2394
+ // Minimal offline registry, used only when the CDN is unreachable so common
2395
+ // demos still resolve without network access.
2396
+ const OFFLINE_PACKAGE_FALLBACKS = {
2397
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
2398
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
2399
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
2400
+ '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'
2401
+ };
2402
+
2403
+ function packageCtxFetch(ctx) {
2404
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
2405
+ return ctx.shell.options.fetchImpl;
2406
+ }
2407
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
2408
+ return null;
2409
+ }
2410
+
2411
+ function parsePackageSpec(spec) {
2412
+ const raw = String(spec || '').trim();
2413
+ if (!raw) return { name: '', range: null };
2414
+ if (raw.startsWith('@')) {
2415
+ const at = raw.indexOf('@', 1);
2416
+ if (at === -1) return { name: raw, range: null };
2417
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2418
+ }
2419
+ const at = raw.indexOf('@');
2420
+ if (at <= 0) return { name: raw, range: null };
2421
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2422
+ }
2423
+
2424
+ function resolveEntryRelPath(pkgJson) {
2425
+ let entry = pkgJson.main || pkgJson.module ||
2426
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2427
+ entry = String(entry).replace(/^[./]+/, '');
2428
+ return entry || 'index.js';
2429
+ }
2430
+
2431
+ function stripRelPath(rel) {
2432
+ return String(rel || '').replace(/^[./]+/, '');
2433
+ }
2434
+
2435
+ function extractRelativeSpecifiers(code) {
2436
+ const out = new Set();
2437
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2438
+ let m;
2439
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2440
+ return Array.from(out);
2441
+ }
2442
+
2443
+ function normalizeRelPath(baseDir, rel) {
2444
+ const parts = String(baseDir || '').split('/').filter(Boolean);
2445
+ for (const seg of String(rel).split('/')) {
2446
+ if (!seg || seg === '.') continue;
2447
+ if (seg === '..') parts.pop();
2448
+ else parts.push(seg);
2449
+ }
2450
+ return parts.join('/');
2451
+ }
2452
+
2453
+ async function fetchTextFromCdn(fetchImpl, url) {
2454
+ try {
2455
+ const res = await fetchImpl(url);
2456
+ if (!res) return null;
2457
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2458
+ if (!ok) return null;
2459
+ if (typeof res.text === 'function') return await res.text();
2460
+ return String(res.body != null ? res.body : '');
2461
+ } catch (_) {
2462
+ return null;
2463
+ }
2464
+ }
2465
+
2466
+ async function resolvePackageMetadata(fetchImpl, name, range) {
2467
+ const urls = range
2468
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2469
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
2470
+ for (const url of urls) {
2471
+ const text = await fetchTextFromCdn(fetchImpl, url);
2472
+ if (!text) continue;
2473
+ try {
2474
+ const parsed = JSON.parse(text);
2475
+ if (parsed && parsed.version) return parsed;
2476
+ } catch (_) {}
2477
+ }
2478
+ return null;
2479
+ }
2480
+
2481
+ // Download a package's entry module, its relative submodules and record its
2482
+ // declared dependencies so the caller can resolve them transitively.
2483
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
2484
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
2485
+ if (!meta) {
2486
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
2487
+ if (fallback) {
2488
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
2489
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
2490
+ }
2491
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2492
+ }
2493
+
2494
+ const version = meta.version;
2495
+ const key = `${name}@${version}`;
2496
+ if (seen.has(key)) {
2497
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
2498
+ }
2499
+ seen.add(key);
2500
+
2501
+ const entry = resolveEntryRelPath(meta);
2502
+ const files = [];
2503
+ const visited = new Set();
2504
+ const queue = [entry];
2505
+ while (queue.length > 0) {
2506
+ const rel = stripRelPath(queue.shift());
2507
+ if (!rel || visited.has(rel)) continue;
2508
+ visited.add(rel);
2509
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2510
+ if (text === null) continue;
2511
+ files.push({ rel, content: text });
2512
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2513
+ for (const spec of extractRelativeSpecifiers(text)) {
2514
+ const target = normalizeRelPath(baseDir, spec);
2515
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2516
+ const c = stripRelPath(cand);
2517
+ if (c && !visited.has(c)) { queue.push(cand); break; }
2518
+ }
2519
+ }
2520
+ }
2521
+ // The declared entry may be missing on the CDN; fall back to index.js.
2522
+ if (!files.some(f => f.rel === entry)) {
2523
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2524
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2525
+ }
2526
+
2527
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2528
+ }
2529
+
2530
+ function installTargetDirs(ctx, name) {
2531
+ const dirs = ['/workspace/node_modules/' + name];
2532
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
2533
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
2534
+ return dirs;
2535
+ }
2536
+
2537
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
2538
+ for (const dir of dirs) {
2539
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2540
+ for (const f of info.files) {
2541
+ const full = PosixPath.join(dir, f.rel);
2542
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2543
+ ctx.vfs.writeFileSync(full, f.content);
2544
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
2545
+ }
2546
+ const modPkgPath = PosixPath.join(dir, 'package.json');
2547
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2548
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2549
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2550
+ }
2551
+ }
2552
+
2553
+ async function installPackage(pkgSpec, ctx) {
2554
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2555
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2393
2556
 
2394
2557
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2395
2558
  if (!pkgData.dependencies) pkgData.dependencies = {};
2396
- pkgData.dependencies[pkgName] = pkgVersion;
2397
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2398
2559
 
2399
- const targetDirs = ['/workspace/node_modules/' + pkgName];
2400
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
2401
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
2560
+ const fetchImpl = packageCtxFetch(ctx);
2561
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
2562
+ ? ctx.shell._cdnSeen
2563
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
2564
+
2565
+ const queue = [{ name: pkgName, range, direct: true }];
2566
+ const requested = new Set([pkgName]);
2567
+ const installed = [];
2568
+ let warning = null;
2569
+ let directVersion = null;
2570
+
2571
+ while (queue.length > 0) {
2572
+ const item = queue.shift();
2573
+ const info = fetchImpl
2574
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
2575
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
2576
+
2577
+ if (!info.ok) {
2578
+ // Final fallback: an empty stub so offline demos still resolve the module.
2579
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
2580
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
2581
+ });
2582
+ if (!warning) warning = info.reason;
2583
+ installed.push({ name: item.name, version: '0.0.0' });
2584
+ continue;
2585
+ }
2402
2586
 
2403
- for (const modDir of targetDirs) {
2404
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
2405
- const modPkgPath = PosixPath.join(modDir, 'package.json');
2406
- const modIndexPath = PosixPath.join(modDir, 'index.js');
2407
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
2408
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2587
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2588
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
2589
+ if (item.direct) directVersion = info.version || null;
2409
2590
 
2410
- let code = 'module.exports = {};\n';
2411
- if (pkgName === 'is-even') {
2412
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
2413
- } else if (pkgName === 'tiny-invariant') {
2414
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
2415
- } else if (pkgName === 'lodash') {
2416
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
2591
+ for (const dep of (info.deps || [])) {
2592
+ const parsed = parsePackageSpec(dep);
2593
+ if (parsed.name && !requested.has(parsed.name)) {
2594
+ requested.add(parsed.name);
2595
+ queue.push({ name: parsed.name, range: null, direct: false });
2596
+ }
2417
2597
  }
2418
- ctx.vfs.writeFileSync(modIndexPath, code);
2419
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
2420
2598
  }
2599
+
2600
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2601
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2602
+
2603
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
2421
2604
  }
2422
2605
 
2423
2606
  function uninstallPackage(pkgName, ctx) {
@@ -5094,6 +5277,18 @@ function __initShellModule(root: any) {
5094
5277
 
5095
5278
  const sub = args[0];
5096
5279
 
5280
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
5281
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
5282
+ }
5283
+
5284
+ if (sub === '--help' || sub === '-h') {
5285
+ return {
5286
+ code: 0,
5287
+ 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',
5288
+ stderr: ''
5289
+ };
5290
+ }
5291
+
5097
5292
  if (sub === 'init') {
5098
5293
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5099
5294
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -5143,12 +5338,28 @@ function __initShellModule(root: any) {
5143
5338
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
5144
5339
  }
5145
5340
 
5146
- if (sub === 'add') {
5341
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
5147
5342
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5148
- for (const p of pkgs) {
5149
- installPackage(p, ctx);
5343
+ if (pkgs.length === 0) {
5344
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5345
+ const deps = Object.keys(pkgData.dependencies || {});
5346
+ const results = [];
5347
+ for (const p of deps) results.push(await installPackage(p, ctx));
5348
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5349
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5150
5350
  }
5151
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
5351
+ const results = [];
5352
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5353
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5354
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5355
+ }
5356
+
5357
+ if (sub === 'add') {
5358
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5359
+ const results = [];
5360
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5361
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5362
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5152
5363
  }
5153
5364
 
5154
5365
  if (sub === 'remove' || sub === 'rm') {
@@ -5311,15 +5522,19 @@ function __initShellModule(root: any) {
5311
5522
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5312
5523
  if (pkgs.length === 0) {
5313
5524
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5525
+ const results = [];
5314
5526
  for (const p of Object.keys(pkgData.dependencies || {})) {
5315
- installPackage(p, ctx);
5527
+ results.push(await installPackage(p, ctx));
5316
5528
  }
5317
- return { code: 0, stdout: 'up to date\n', stderr: '' };
5529
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5530
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5318
5531
  }
5532
+ const results = [];
5319
5533
  for (const p of pkgs) {
5320
- installPackage(p, ctx);
5534
+ results.push(await installPackage(p, ctx));
5321
5535
  }
5322
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
5536
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5537
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5323
5538
  }
5324
5539
 
5325
5540
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5544,6 +5759,16 @@ function __initShellModule(root: any) {
5544
5759
  return PosixPath.resolve(this.cwd, p);
5545
5760
  }
5546
5761
 
5762
+ // True when `name` resolves to a shell function or coreutil (used by the
5763
+ // workbench to route recognised commands straight to the shell instead of
5764
+ // treating flag-looking input such as `node --version` as a JS expression).
5765
+ hasCommand(name) {
5766
+ if (!name) return false;
5767
+ const n = String(name);
5768
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
5769
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
5770
+ }
5771
+
5547
5772
  _emitVfsMutation(type, absPath) {
5548
5773
  if (!this.vfs) return;
5549
5774
  const evt = { type, path: absPath, timestamp: Date.now() };
package/src/workbench.js CHANGED
@@ -6085,14 +6085,14 @@ declare module 'bun:sqlite' {
6085
6085
  </div>
6086
6086
  ${pkgs.length === 0 ? `
6087
6087
  <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;">
6088
- 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.
6088
+ 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.
6089
6089
  </div>
6090
6090
  ` : `
6091
6091
  <div style="display:flex;flex-direction:column;gap:6px;">
6092
6092
  ${pkgs.map(p => `
6093
6093
  <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;">
6094
6094
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
6095
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
6095
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
6096
6096
  </div>
6097
6097
  `).join('')}
6098
6098
  </div>
@@ -6226,9 +6226,14 @@ declare module 'bun:sqlite' {
6226
6226
  if (detectedList.length > 0) {
6227
6227
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
6228
6228
  }
6229
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
6230
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
6229
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
6230
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
6231
6231
  });
6232
+ // Hand the fetched module sources to the runtime so the Web Worker
6233
+ // (which has an isolated module cache) can resolve them from node_modules.
6234
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
6235
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
6236
+ }
6232
6237
  }
6233
6238
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
6234
6239
  let res;
@@ -6565,8 +6570,17 @@ declare module 'bun:sqlite' {
6565
6570
  return;
6566
6571
  }
6567
6572
 
6568
- 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)
6569
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
6573
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
6574
+ const shellKnowsCommand = Boolean(
6575
+ firstWord &&
6576
+ this.shell &&
6577
+ typeof this.shell.hasCommand === 'function' &&
6578
+ this.shell.hasCommand(firstWord)
6579
+ );
6580
+ const looksLikeJsExpr = !shellKnowsCommand && (
6581
+ /^(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)
6582
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
6583
+ );
6570
6584
 
6571
6585
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
6572
6586
  const abortCtrl = new AbortController();
package/src/workbench.ts CHANGED
@@ -6086,14 +6086,14 @@ declare module 'bun:sqlite' {
6086
6086
  </div>
6087
6087
  ${pkgs.length === 0 ? `
6088
6088
  <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;">
6089
- 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.
6089
+ 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.
6090
6090
  </div>
6091
6091
  ` : `
6092
6092
  <div style="display:flex;flex-direction:column;gap:6px;">
6093
6093
  ${pkgs.map(p => `
6094
6094
  <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;">
6095
6095
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
6096
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
6096
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
6097
6097
  </div>
6098
6098
  `).join('')}
6099
6099
  </div>
@@ -6227,9 +6227,14 @@ declare module 'bun:sqlite' {
6227
6227
  if (detectedList.length > 0) {
6228
6228
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
6229
6229
  }
6230
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
6231
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
6230
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
6231
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
6232
6232
  });
6233
+ // Hand the fetched module sources to the runtime so the Web Worker
6234
+ // (which has an isolated module cache) can resolve them from node_modules.
6235
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
6236
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
6237
+ }
6233
6238
  }
6234
6239
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
6235
6240
  let res;
@@ -6566,8 +6571,17 @@ declare module 'bun:sqlite' {
6566
6571
  return;
6567
6572
  }
6568
6573
 
6569
- 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)
6570
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
6574
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
6575
+ const shellKnowsCommand = Boolean(
6576
+ firstWord &&
6577
+ this.shell &&
6578
+ typeof this.shell.hasCommand === 'function' &&
6579
+ this.shell.hasCommand(firstWord)
6580
+ );
6581
+ const looksLikeJsExpr = !shellKnowsCommand && (
6582
+ /^(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)
6583
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
6584
+ );
6571
6585
 
6572
6586
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
6573
6587
  const abortCtrl = new AbortController();