@innovatorved/code-lab 0.1.3 → 0.1.5

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/shell.esm.js CHANGED
@@ -2354,38 +2354,362 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2354
2354
  } catch (_) {}
2355
2355
  }
2356
2356
 
2357
- function installPackage(pkgSpec, ctx) {
2358
- const parts = pkgSpec.split('@').filter(Boolean);
2359
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
2360
- const pkgVersion = parts[1] || '^1.0.0';
2357
+ // ---------------------------------------------------------------------------
2358
+ // Real npm package installation via the jsDelivr CDN
2359
+ // ---------------------------------------------------------------------------
2360
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
2361
+
2362
+ // Minimal offline registry, used only when the CDN is unreachable so common
2363
+ // demos still resolve without network access.
2364
+ const OFFLINE_PACKAGE_FALLBACKS = {
2365
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
2366
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
2367
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
2368
+ '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'
2369
+ };
2361
2370
 
2362
- const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2363
- if (!pkgData.dependencies) pkgData.dependencies = {};
2364
- pkgData.dependencies[pkgName] = pkgVersion;
2365
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2371
+ function packageCtxFetch(ctx) {
2372
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
2373
+ return ctx.shell.options.fetchImpl;
2374
+ }
2375
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
2376
+ return null;
2377
+ }
2366
2378
 
2367
- const targetDirs = ['/workspace/node_modules/' + pkgName];
2368
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
2369
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
2379
+ function parsePackageSpec(spec) {
2380
+ const raw = String(spec || '').trim();
2381
+ if (!raw) return { name: '', range: null };
2382
+ if (raw.startsWith('@')) {
2383
+ const at = raw.indexOf('@', 1);
2384
+ if (at === -1) return { name: raw, range: null };
2385
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2386
+ }
2387
+ const at = raw.indexOf('@');
2388
+ if (at <= 0) return { name: raw, range: null };
2389
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2390
+ }
2370
2391
 
2371
- for (const modDir of targetDirs) {
2372
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
2373
- const modPkgPath = PosixPath.join(modDir, 'package.json');
2374
- const modIndexPath = PosixPath.join(modDir, 'index.js');
2375
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
2392
+ function pickConditionalEntry(value) {
2393
+ if (typeof value === 'string') return value;
2394
+ if (!value || typeof value !== 'object') return null;
2395
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2396
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
2397
+ if (value[key] !== undefined) {
2398
+ const picked = pickConditionalEntry(value[key]);
2399
+ if (picked) return picked;
2400
+ }
2401
+ }
2402
+ return null;
2403
+ }
2404
+
2405
+ function resolveEntryRelPath(pkgJson) {
2406
+ let entry = null;
2407
+ const exp = pkgJson && pkgJson.exports;
2408
+ if (typeof exp === 'string') {
2409
+ entry = exp;
2410
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
2411
+ entry = pickConditionalEntry(exp['.']);
2412
+ }
2413
+ if (!entry) {
2414
+ entry = pkgJson.main || pkgJson.module ||
2415
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2416
+ }
2417
+ entry = String(entry).replace(/^[./]+/, '');
2418
+ return entry || 'index.js';
2419
+ }
2420
+
2421
+ function stripRelPath(rel) {
2422
+ return String(rel || '').replace(/^[./]+/, '');
2423
+ }
2424
+
2425
+ function extractRelativeSpecifiers(code) {
2426
+ const out = new Set();
2427
+ const patterns = [
2428
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2429
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2430
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2431
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
2432
+ ];
2433
+ for (const re of patterns) {
2434
+ let m;
2435
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2436
+ }
2437
+ return Array.from(out);
2438
+ }
2439
+
2440
+ function normalizeRelPath(baseDir, rel) {
2441
+ const parts = String(baseDir || '').split('/').filter(Boolean);
2442
+ for (const seg of String(rel).split('/')) {
2443
+ if (!seg || seg === '.') continue;
2444
+ if (seg === '..') parts.pop();
2445
+ else parts.push(seg);
2446
+ }
2447
+ return parts.join('/');
2448
+ }
2449
+
2450
+ async function fetchTextFromCdn(fetchImpl, url) {
2451
+ try {
2452
+ const res = await fetchImpl(url);
2453
+ if (!res) return null;
2454
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2455
+ if (!ok) return null;
2456
+ if (typeof res.text === 'function') return await res.text();
2457
+ return String(res.body != null ? res.body : '');
2458
+ } catch (_) {
2459
+ return null;
2460
+ }
2461
+ }
2462
+
2463
+ async function resolvePackageMetadata(fetchImpl, name, range) {
2464
+ const urls = range
2465
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2466
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
2467
+ for (const url of urls) {
2468
+ const text = await fetchTextFromCdn(fetchImpl, url);
2469
+ if (!text) continue;
2470
+ try {
2471
+ const parsed = JSON.parse(text);
2472
+ if (parsed && parsed.version) return parsed;
2473
+ } catch (_) {}
2474
+ }
2475
+ return null;
2476
+ }
2477
+
2478
+ // Download a package's entry module, its relative submodules and record its
2479
+ // declared dependencies so the caller can resolve them transitively.
2480
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
2481
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
2482
+ if (!meta) {
2483
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
2484
+ if (fallback) {
2485
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
2486
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
2487
+ }
2488
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2489
+ }
2490
+
2491
+ const version = meta.version;
2492
+ const key = `${name}@${version}`;
2493
+ if (seen.has(key)) {
2494
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
2495
+ }
2496
+ seen.add(key);
2497
+
2498
+ const entry = resolveEntryRelPath(meta);
2499
+ const files = [];
2500
+ const visited = new Set();
2501
+ // Seed with the package entry plus any declared `exports` subpaths, so a
2502
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2503
+ const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2504
+ const expMap = meta.exports;
2505
+ if (expMap && typeof expMap === 'object') {
2506
+ let subCount = 0;
2507
+ for (const key of Object.keys(expMap)) {
2508
+ if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2509
+ const target = pickConditionalEntry(expMap[key]);
2510
+ if (target) { seed.push(target); subCount++; }
2511
+ }
2512
+ }
2513
+ let frontier = seed;
2514
+ while (frontier.length > 0) {
2515
+ const batch = [];
2516
+ for (const raw of frontier) {
2517
+ const rel = stripRelPath(raw);
2518
+ if (!rel || visited.has(rel)) continue;
2519
+ visited.add(rel);
2520
+ batch.push(rel);
2521
+ }
2522
+ frontier = [];
2523
+ if (batch.length === 0) break;
2524
+ const texts = await Promise.all(
2525
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2526
+ );
2527
+ for (let idx = 0; idx < batch.length; idx++) {
2528
+ const rel = batch[idx];
2529
+ const text = texts[idx];
2530
+ if (text === null) continue;
2531
+ files.push({ rel, content: text });
2532
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2533
+ for (const spec of extractRelativeSpecifiers(text)) {
2534
+ const target = normalizeRelPath(baseDir, spec);
2535
+ // Only guess extensions when the specifier omits one; non-existent
2536
+ // candidates 404 harmlessly.
2537
+ const cands = /\.[a-z0-9]+$/i.test(target)
2538
+ ? [target]
2539
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
2540
+ for (const cand of cands) {
2541
+ const c = stripRelPath(cand);
2542
+ if (c && !visited.has(c)) frontier.push(cand);
2543
+ }
2544
+ }
2545
+ }
2546
+ }
2547
+ // The declared entry may be missing on the CDN; fall back to index.js.
2548
+ if (!files.some(f => f.rel === entry)) {
2549
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2550
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2551
+ }
2552
+
2553
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2554
+ // so e.g. `npm install react-dom` also pulls in `react`.
2555
+ const depNames = Object.keys(meta.dependencies || {});
2556
+ const peerMeta = meta.peerDependenciesMeta || {};
2557
+ for (const peer of Object.keys(meta.peerDependencies || {})) {
2558
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
2559
+ if (depNames.indexOf(peer) === -1) depNames.push(peer);
2560
+ }
2561
+
2562
+ return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2563
+ }
2564
+
2565
+ function installTargetDirs(ctx, name) {
2566
+ const dirs = ['/workspace/node_modules/' + name];
2567
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
2568
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
2569
+ return dirs;
2570
+ }
2571
+
2572
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
2573
+ for (const dir of dirs) {
2574
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2575
+ for (const f of info.files) {
2576
+ const full = PosixPath.join(dir, f.rel);
2577
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2578
+ ctx.vfs.writeFileSync(full, f.content);
2579
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
2580
+ }
2581
+ const modPkgPath = PosixPath.join(dir, 'package.json');
2582
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2583
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
2584
+ const normalized = { '.': './' + (info.entry || 'index.js') };
2585
+ for (const key of Object.keys(info.pkgExports)) {
2586
+ if (key === '.' || key.indexOf('*') !== -1) continue;
2587
+ const target = pickConditionalEntry(info.pkgExports[key]);
2588
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
2589
+ }
2590
+ modPkg.exports = normalized;
2591
+ }
2592
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2376
2593
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2594
+ }
2595
+ }
2596
+
2597
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
2598
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
2599
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
2600
+ const isDev = Boolean(options.dev);
2601
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2602
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2377
2603
 
2378
- let code = 'module.exports = {};\n';
2379
- if (pkgName === 'is-even') {
2380
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
2381
- } else if (pkgName === 'tiny-invariant') {
2382
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
2383
- } else if (pkgName === 'lodash') {
2384
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
2604
+ const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2605
+ const depField = isDev ? 'devDependencies' : 'dependencies';
2606
+ if (!pkgData[depField]) pkgData[depField] = {};
2607
+
2608
+ const fetchImpl = packageCtxFetch(ctx);
2609
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
2610
+ ? ctx.shell._cdnSeen
2611
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
2612
+
2613
+ const queue = [{ name: pkgName, range, direct: true }];
2614
+ const requested = new Set([pkgName]);
2615
+ const installed = [];
2616
+ let warning = null;
2617
+ let directVersion = null;
2618
+
2619
+ while (queue.length > 0) {
2620
+ const item = queue.shift();
2621
+ const info = fetchImpl
2622
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
2623
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
2624
+
2625
+ if (!info.ok) {
2626
+ // Final fallback: an empty stub so offline demos still resolve the module.
2627
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
2628
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
2629
+ });
2630
+ if (!warning) warning = info.reason;
2631
+ installed.push({ name: item.name, version: '0.0.0' });
2632
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
2633
+ continue;
2634
+ }
2635
+
2636
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2637
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
2638
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
2639
+ if (item.direct) directVersion = info.version || null;
2640
+
2641
+ for (const dep of (info.deps || [])) {
2642
+ const parsed = parsePackageSpec(dep);
2643
+ if (parsed.name && !requested.has(parsed.name)) {
2644
+ requested.add(parsed.name);
2645
+ queue.push({ name: parsed.name, range: null, direct: false });
2646
+ }
2385
2647
  }
2386
- ctx.vfs.writeFileSync(modIndexPath, code);
2387
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
2388
2648
  }
2649
+
2650
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2651
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2652
+
2653
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
2654
+ }
2655
+
2656
+ // Build a live install log: each line is streamed to the terminal as it
2657
+ // happens (when possible) and accumulated so the command can also return it.
2658
+ function createInstallEmitter(ctx, sink) {
2659
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
2660
+ return function emit(text) {
2661
+ if (!text) return;
2662
+ sink.push(text);
2663
+ if (stream) stream(text);
2664
+ };
2665
+ }
2666
+
2667
+ function formatInstallLine(info) {
2668
+ if (!info || !info.name) return '';
2669
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
2670
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
2671
+ }
2672
+
2673
+ function countInstalledPackages(results) {
2674
+ const seen = new Set();
2675
+ for (const r of results) {
2676
+ if (!r) continue;
2677
+ if (r.name) seen.add(r.name);
2678
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
2679
+ }
2680
+ return seen.size;
2681
+ }
2682
+
2683
+ // Resolve + install a list of specs while printing a realistic transcript,
2684
+ // so `npm install` / `bun add` look like the real tools instead of a terse
2685
+ // "saved N package(s)".
2686
+ async function runInstallTranscript(pkgs, ctx, opts) {
2687
+ const options = opts || {};
2688
+ const manager = options.manager || 'bun';
2689
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
2690
+ const out = [];
2691
+ const emit = createInstallEmitter(ctx, out);
2692
+ const started = Date.now();
2693
+ emit(`${header}\n\nResolving dependencies...\n`);
2694
+ const results = [];
2695
+ for (const p of pkgs) {
2696
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
2697
+ }
2698
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
2699
+ const count = countInstalledPackages(results);
2700
+ const ms = Date.now() - started;
2701
+ if (manager === 'npm') {
2702
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
2703
+ } else if (manager === 'pnpm') {
2704
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
2705
+ } else {
2706
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
2707
+ }
2708
+ return {
2709
+ code: 0,
2710
+ stdout: out.join(''),
2711
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
2712
+ };
2389
2713
  }
2390
2714
 
2391
2715
  function uninstallPackage(pkgName, ctx) {
@@ -2439,9 +2763,261 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2439
2763
  if (scriptArgs && scriptArgs.length > 0) {
2440
2764
  cmd += ' ' + scriptArgs.join(' ');
2441
2765
  }
2766
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2767
+ if (fallback) return fallback;
2442
2768
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
2443
2769
  }
2444
2770
 
2771
+ // ---------------------------------------------------------------------------
2772
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
2773
+ //
2774
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
2775
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
2776
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
2777
+ // `+esm` builds through an injected import map — no bundler required.
2778
+ // ---------------------------------------------------------------------------
2779
+
2780
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
2781
+
2782
+ const PREVIEW_MIME = {
2783
+ '.html': 'text/html; charset=utf-8',
2784
+ '.htm': 'text/html; charset=utf-8',
2785
+ '.js': 'text/javascript; charset=utf-8',
2786
+ '.mjs': 'text/javascript; charset=utf-8',
2787
+ '.cjs': 'text/javascript; charset=utf-8',
2788
+ '.jsx': 'text/javascript; charset=utf-8',
2789
+ '.ts': 'text/javascript; charset=utf-8',
2790
+ '.tsx': 'text/javascript; charset=utf-8',
2791
+ '.css': 'text/css; charset=utf-8',
2792
+ '.json': 'application/json; charset=utf-8',
2793
+ '.map': 'application/json; charset=utf-8',
2794
+ '.svg': 'image/svg+xml',
2795
+ '.png': 'image/png',
2796
+ '.jpg': 'image/jpeg',
2797
+ '.jpeg': 'image/jpeg',
2798
+ '.gif': 'image/gif',
2799
+ '.webp': 'image/webp',
2800
+ '.ico': 'image/x-icon',
2801
+ '.txt': 'text/plain; charset=utf-8'
2802
+ };
2803
+
2804
+ function previewMimeFor(p) {
2805
+ const lower = String(p).toLowerCase();
2806
+ const dot = lower.lastIndexOf('.');
2807
+ if (dot === -1) return 'application/octet-stream';
2808
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
2809
+ }
2810
+
2811
+ function isPreviewScriptPath(p) {
2812
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
2813
+ }
2814
+
2815
+ // Collect bare (non-relative) module specifiers referenced by a source file.
2816
+ function extractBareSpecifiers(code) {
2817
+ const out = new Set();
2818
+ const patterns = [
2819
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2820
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2821
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2822
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
2823
+ ];
2824
+ for (const re of patterns) {
2825
+ let m;
2826
+ while ((m = re.exec(code)) !== null) {
2827
+ const spec = m[1];
2828
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
2829
+ out.add(spec);
2830
+ }
2831
+ }
2832
+ return Array.from(out);
2833
+ }
2834
+
2835
+ function normalizeVersionRange(range) {
2836
+ if (!range || typeof range !== 'string') return 'latest';
2837
+ const v = range.trim();
2838
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
2839
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
2840
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
2841
+ }
2842
+
2843
+ function resolveBareVersion(vfs, rootDir, pkgName) {
2844
+ try {
2845
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
2846
+ if (vfs.existsSync(modPkg)) {
2847
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2848
+ if (parsed && parsed.version) return parsed.version;
2849
+ }
2850
+ } catch (_) {}
2851
+ try {
2852
+ for (const dir of [rootDir, '/workspace']) {
2853
+ const pkgPath = PosixPath.join(dir, 'package.json');
2854
+ if (!vfs.existsSync(pkgPath)) continue;
2855
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
2856
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2857
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2858
+ }
2859
+ } catch (_) {}
2860
+ return 'latest';
2861
+ }
2862
+
2863
+ function cdnEsmUrl(pkgName, version, subpath) {
2864
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
2865
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
2866
+ return `${base}${sub}/+esm`;
2867
+ }
2868
+
2869
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
2870
+ const imports = {};
2871
+ for (const spec of specifiers) {
2872
+ const parts = String(spec).split('/');
2873
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
2874
+ if (!pkgName) continue;
2875
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
2876
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
2877
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
2878
+ }
2879
+ return imports;
2880
+ }
2881
+
2882
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
2883
+ const scripts = [];
2884
+ const walk = (dir, depth) => {
2885
+ if (depth > 8 || scripts.length >= maxFiles) return;
2886
+ let entries = [];
2887
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
2888
+ for (const name of entries) {
2889
+ if (name === 'node_modules' || name.startsWith('.')) continue;
2890
+ const full = PosixPath.join(dir, name);
2891
+ let st;
2892
+ try { st = vfs.statSync(full); } catch (_) { continue; }
2893
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
2894
+ if (dirFlag) {
2895
+ walk(full, depth + 1);
2896
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
2897
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
2898
+ }
2899
+ }
2900
+ };
2901
+ walk(rootDir, 0);
2902
+ return scripts;
2903
+ }
2904
+
2905
+ function injectPreviewExtras(html, importMap) {
2906
+ let out = html;
2907
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
2908
+ if (/<head[^>]*>/i.test(out)) {
2909
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
2910
+ } else {
2911
+ out = importMapTag + '\n' + out;
2912
+ }
2913
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
2914
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
2915
+ else out = out + '\n' + shim;
2916
+ return out;
2917
+ }
2918
+
2919
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
2920
+ const portTable = ctx.shell && ctx.shell.portTable;
2921
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
2922
+
2923
+ let port = Number(preferredPort) || 3000;
2924
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
2925
+ while (taken.has(port)) port++;
2926
+
2927
+ const specifiers = new Set();
2928
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
2929
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
2930
+ }
2931
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
2932
+
2933
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
2934
+ const isDir = (p) => {
2935
+ try {
2936
+ const st = ctx.vfs.statSync(p);
2937
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
2938
+ } catch (_) { return false; }
2939
+ };
2940
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
2941
+
2942
+ const handler = async (request) => {
2943
+ let pathname = '/';
2944
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
2945
+ const rel = pathname.replace(/^\/+/, '');
2946
+ let target = PosixPath.join(rootDir, rel);
2947
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
2948
+
2949
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
2950
+ target = PosixPath.join(target, 'index.html');
2951
+ }
2952
+ if (!exists(target) && !hasExt) {
2953
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
2954
+ // the way a bundler / dev server would.
2955
+ const cands = [
2956
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
2957
+ target + '.mjs', target + '.cjs',
2958
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
2959
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
2960
+ ];
2961
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
2962
+ }
2963
+ if (!exists(target) && !hasExt) {
2964
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
2965
+ }
2966
+ if (!exists(target)) {
2967
+ return new Response(
2968
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
2969
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
2970
+ );
2971
+ }
2972
+
2973
+ let body = readText(target);
2974
+ if (body === null) body = '';
2975
+ if (/\.html?$/i.test(target)) {
2976
+ body = injectPreviewExtras(body, importMap);
2977
+ } else if (isPreviewScriptPath(target)) {
2978
+ try {
2979
+ const rm = getRuntimeModule();
2980
+ if (rm && typeof rm.transpileForBrowser === 'function') {
2981
+ body = rm.transpileForBrowser(body, target);
2982
+ }
2983
+ } catch (_) {}
2984
+ }
2985
+
2986
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
2987
+ };
2988
+
2989
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
2990
+ return portTable.registerServer(port, {
2991
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
2992
+ fetch: handler,
2993
+ name: 'code-lab-serve',
2994
+ pid,
2995
+ root: rootDir
2996
+ });
2997
+ }
2998
+
2999
+ // Common dev-server commands that cannot run inside the virtual runtime are
3000
+ // transparently redirected to the built-in preview server.
3001
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3002
+
3003
+ function tryDevScriptFallback(scriptName, cmd, ctx) {
3004
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3005
+ // Only fall back when the referenced tool is not actually installed.
3006
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3007
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3008
+ if (ctx.vfs.existsSync(binPath)) return null;
3009
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3010
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3011
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3012
+ const entry = registerPreviewServer(ctx, ctx.cwd, port);
3013
+ if (!entry) return null;
3014
+ return {
3015
+ code: 0,
3016
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3017
+ stderr: ''
3018
+ };
3019
+ }
3020
+
2445
3021
  function evaluatePosixTest(args, ctx) {
2446
3022
  const cleanArgs = [...args];
2447
3023
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -4940,7 +5516,8 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
4940
5516
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
4941
5517
  stdout += ' history, ps, jobs, kill Process and job management\n';
4942
5518
  stdout += ' git [status diff log] Built-in version control\n';
4943
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
5519
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5520
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
4944
5521
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
4945
5522
  return { code: 0, stdout, stderr: '' };
4946
5523
  },
@@ -5062,6 +5639,18 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5062
5639
 
5063
5640
  const sub = args[0];
5064
5641
 
5642
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
5643
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
5644
+ }
5645
+
5646
+ if (sub === '--help' || sub === '-h') {
5647
+ return {
5648
+ code: 0,
5649
+ 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',
5650
+ stderr: ''
5651
+ };
5652
+ }
5653
+
5065
5654
  if (sub === 'init') {
5066
5655
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5067
5656
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -5111,12 +5700,27 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5111
5700
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
5112
5701
  }
5113
5702
 
5114
- if (sub === 'add') {
5703
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
5115
5704
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5116
- for (const p of pkgs) {
5117
- installPackage(p, ctx);
5705
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5706
+ if (pkgs.length === 0) {
5707
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5708
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5709
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5710
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
5118
5711
  }
5119
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
5712
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5713
+ }
5714
+
5715
+ if (sub === 'add') {
5716
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5717
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5718
+ if (pkgs.length === 0) {
5719
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5720
+ pkgs = Object.keys(pkgData.dependencies || {});
5721
+ }
5722
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5723
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5120
5724
  }
5121
5725
 
5122
5726
  if (sub === 'remove' || sub === 'rm') {
@@ -5276,18 +5880,14 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5276
5880
  }
5277
5881
 
5278
5882
  if (sub === 'i' || sub === 'install' || sub === 'add') {
5279
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5883
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5884
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
5280
5885
  if (pkgs.length === 0) {
5281
5886
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5282
- for (const p of Object.keys(pkgData.dependencies || {})) {
5283
- installPackage(p, ctx);
5284
- }
5285
- return { code: 0, stdout: 'up to date\n', stderr: '' };
5887
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5888
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5286
5889
  }
5287
- for (const p of pkgs) {
5288
- installPackage(p, ctx);
5289
- }
5290
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
5890
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
5291
5891
  }
5292
5892
 
5293
5893
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5339,6 +5939,123 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5339
5939
  return await this.npx(args, ctx);
5340
5940
  },
5341
5941
 
5942
+ async pnpm(args, ctx) {
5943
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
5944
+ return {
5945
+ code: 0,
5946
+ stdout: 'pnpm v9.0.0\nUsage: pnpm <command>\n\nCommands:\n install, i Install all dependencies\n add <pkg> Add a dependency (-D for dev)\n remove, rm Remove a dependency\n list, ls List dependencies\n run <script> Run a package script\n exec <cmd> Run a command from node_modules/.bin\n dlx <pkg> Fetch and run a package\n --version, -v Print the version\n',
5947
+ stderr: ''
5948
+ };
5949
+ }
5950
+ const sub = args[0];
5951
+ if (sub === '--version' || sub === '-v') {
5952
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
5953
+ }
5954
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
5955
+
5956
+ if (sub === 'init') {
5957
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5958
+ if (!ctx.vfs.existsSync(pkgPath)) {
5959
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
5960
+ name: PosixPath.basename(ctx.cwd) || 'app',
5961
+ version: '1.0.0',
5962
+ main: 'index.js',
5963
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
5964
+ }, null, 2) + '\n');
5965
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
5966
+ }
5967
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
5968
+ }
5969
+
5970
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
5971
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5972
+ if (pkgs.length === 0) {
5973
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5974
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5975
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
5976
+ }
5977
+ const verb = (sub === 'add') ? 'add' : 'install';
5978
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
5979
+ }
5980
+
5981
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
5982
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5983
+ for (const p of pkgs) uninstallPackage(p, ctx);
5984
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
5985
+ }
5986
+
5987
+ if (sub === 'list' || sub === 'ls') {
5988
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
5989
+ }
5990
+
5991
+ if (sub === 'run' || sub === 'run-script') {
5992
+ const scriptName = args[1];
5993
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
5994
+ return await runPackageScript(scriptName, args.slice(2), ctx);
5995
+ }
5996
+
5997
+ if (sub === 'test') {
5998
+ return await runPackageScript('test', args.slice(1), ctx);
5999
+ }
6000
+
6001
+ if (sub === 'exec') {
6002
+ const cmd = args[1];
6003
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6004
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6005
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6006
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6007
+ }
6008
+
6009
+ if (sub === 'dlx') {
6010
+ return await this.npx(args.slice(1), ctx);
6011
+ }
6012
+
6013
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
6014
+ if (pkgData.scripts && pkgData.scripts[sub]) {
6015
+ return await runPackageScript(sub, args.slice(1), ctx);
6016
+ }
6017
+
6018
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
6019
+ },
6020
+
6021
+ async serve(args, ctx) {
6022
+ if (args[0] === '--help' || args[0] === '-h') {
6023
+ return {
6024
+ code: 0,
6025
+ stdout: 'Usage: serve [dir] [--port <n>]\n\n Starts the built-in CodeLab preview server on the virtual port table.\n HTML/CSS/JS are served statically, .ts/.tsx/.jsx are transpiled to\n browser-native ESM on the fly, and bare imports resolve to jsDelivr ESM.\n\n Open the Web Preview drawer (or http://127.0.0.1:<port>/) to view it.\n',
6026
+ stderr: ''
6027
+ };
6028
+ }
6029
+ const rootArg = (() => {
6030
+ const positionals = [];
6031
+ for (let i = 0; i < args.length; i++) {
6032
+ const a = args[i];
6033
+ if (a === '--port' || a === '-p') { i++; continue; }
6034
+ if (a.startsWith('-')) continue;
6035
+ positionals.push(a);
6036
+ }
6037
+ return positionals[0];
6038
+ })();
6039
+ let port = 3000;
6040
+ for (let i = 0; i < args.length; i++) {
6041
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
6042
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
6043
+ }
6044
+ const rootDir = ctx.resolvePath(rootArg || '.');
6045
+ if (!ctx.vfs.existsSync(rootDir)) {
6046
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
6047
+ }
6048
+ const entry = registerPreviewServer(ctx, rootDir, port);
6049
+ if (!entry) {
6050
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
6051
+ }
6052
+ return {
6053
+ code: 0,
6054
+ stdout: `\n ⚡ CodeLab preview server\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n ➜ Root: ${rootDir}\n ➜ Preview: open the Web Preview drawer for port ${entry.port}\n\n`,
6055
+ stderr: ''
6056
+ };
6057
+ },
6058
+
5342
6059
  // -----------------------------------------------------------------------
5343
6060
  // Port Table & HTTP Inspection: ports, curl
5344
6061
  // -----------------------------------------------------------------------
@@ -5512,6 +6229,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5512
6229
  return PosixPath.resolve(this.cwd, p);
5513
6230
  }
5514
6231
 
6232
+ // True when `name` resolves to a shell function or coreutil (used by the
6233
+ // workbench to route recognised commands straight to the shell instead of
6234
+ // treating flag-looking input such as `node --version` as a JS expression).
6235
+ hasCommand(name) {
6236
+ if (!name) return false;
6237
+ const n = String(name);
6238
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
6239
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
6240
+ }
6241
+
5515
6242
  _emitVfsMutation(type, absPath) {
5516
6243
  if (!this.vfs) return;
5517
6244
  const evt = { type, path: absPath, timestamp: Date.now() };