@innovatorved/code-lab 0.1.4 → 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.js CHANGED
@@ -2390,9 +2390,31 @@
2390
2390
  return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2391
2391
  }
2392
2392
 
2393
+ function pickConditionalEntry(value) {
2394
+ if (typeof value === 'string') return value;
2395
+ if (!value || typeof value !== 'object') return null;
2396
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2397
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
2398
+ if (value[key] !== undefined) {
2399
+ const picked = pickConditionalEntry(value[key]);
2400
+ if (picked) return picked;
2401
+ }
2402
+ }
2403
+ return null;
2404
+ }
2405
+
2393
2406
  function resolveEntryRelPath(pkgJson) {
2394
- let entry = pkgJson.main || pkgJson.module ||
2395
- (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2407
+ let entry = null;
2408
+ const exp = pkgJson && pkgJson.exports;
2409
+ if (typeof exp === 'string') {
2410
+ entry = exp;
2411
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
2412
+ entry = pickConditionalEntry(exp['.']);
2413
+ }
2414
+ if (!entry) {
2415
+ entry = pkgJson.main || pkgJson.module ||
2416
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2417
+ }
2396
2418
  entry = String(entry).replace(/^[./]+/, '');
2397
2419
  return entry || 'index.js';
2398
2420
  }
@@ -2403,9 +2425,16 @@
2403
2425
 
2404
2426
  function extractRelativeSpecifiers(code) {
2405
2427
  const out = new Set();
2406
- const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2407
- let m;
2408
- while ((m = re.exec(code)) !== null) out.add(m[1]);
2428
+ const patterns = [
2429
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2430
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2431
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2432
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
2433
+ ];
2434
+ for (const re of patterns) {
2435
+ let m;
2436
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2437
+ }
2409
2438
  return Array.from(out);
2410
2439
  }
2411
2440
 
@@ -2470,20 +2499,49 @@
2470
2499
  const entry = resolveEntryRelPath(meta);
2471
2500
  const files = [];
2472
2501
  const visited = new Set();
2473
- const queue = [entry];
2474
- while (queue.length > 0) {
2475
- const rel = stripRelPath(queue.shift());
2476
- if (!rel || visited.has(rel)) continue;
2477
- visited.add(rel);
2478
- const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2479
- if (text === null) continue;
2480
- files.push({ rel, content: text });
2481
- const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2482
- for (const spec of extractRelativeSpecifiers(text)) {
2483
- const target = normalizeRelPath(baseDir, spec);
2484
- for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2485
- const c = stripRelPath(cand);
2486
- if (c && !visited.has(c)) { queue.push(cand); break; }
2502
+ // Seed with the package entry plus any declared `exports` subpaths, so a
2503
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2504
+ const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2505
+ const expMap = meta.exports;
2506
+ if (expMap && typeof expMap === 'object') {
2507
+ let subCount = 0;
2508
+ for (const key of Object.keys(expMap)) {
2509
+ if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2510
+ const target = pickConditionalEntry(expMap[key]);
2511
+ if (target) { seed.push(target); subCount++; }
2512
+ }
2513
+ }
2514
+ let frontier = seed;
2515
+ while (frontier.length > 0) {
2516
+ const batch = [];
2517
+ for (const raw of frontier) {
2518
+ const rel = stripRelPath(raw);
2519
+ if (!rel || visited.has(rel)) continue;
2520
+ visited.add(rel);
2521
+ batch.push(rel);
2522
+ }
2523
+ frontier = [];
2524
+ if (batch.length === 0) break;
2525
+ const texts = await Promise.all(
2526
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2527
+ );
2528
+ for (let idx = 0; idx < batch.length; idx++) {
2529
+ const rel = batch[idx];
2530
+ const text = texts[idx];
2531
+ if (text === null) continue;
2532
+ files.push({ rel, content: text });
2533
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2534
+ for (const spec of extractRelativeSpecifiers(text)) {
2535
+ const target = normalizeRelPath(baseDir, spec);
2536
+ // Only guess extensions when the specifier omits one; non-existent
2537
+ // candidates 404 harmlessly.
2538
+ const cands = /\.[a-z0-9]+$/i.test(target)
2539
+ ? [target]
2540
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
2541
+ for (const cand of cands) {
2542
+ const c = stripRelPath(cand);
2543
+ if (c && !visited.has(c)) frontier.push(cand);
2544
+ }
2487
2545
  }
2488
2546
  }
2489
2547
  }
@@ -2493,7 +2551,16 @@
2493
2551
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2494
2552
  }
2495
2553
 
2496
- return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2554
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2555
+ // so e.g. `npm install react-dom` also pulls in `react`.
2556
+ const depNames = Object.keys(meta.dependencies || {});
2557
+ const peerMeta = meta.peerDependenciesMeta || {};
2558
+ for (const peer of Object.keys(meta.peerDependencies || {})) {
2559
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
2560
+ if (depNames.indexOf(peer) === -1) depNames.push(peer);
2561
+ }
2562
+
2563
+ return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2497
2564
  }
2498
2565
 
2499
2566
  function installTargetDirs(ctx, name) {
@@ -2514,17 +2581,30 @@
2514
2581
  }
2515
2582
  const modPkgPath = PosixPath.join(dir, 'package.json');
2516
2583
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2584
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
2585
+ const normalized = { '.': './' + (info.entry || 'index.js') };
2586
+ for (const key of Object.keys(info.pkgExports)) {
2587
+ if (key === '.' || key.indexOf('*') !== -1) continue;
2588
+ const target = pickConditionalEntry(info.pkgExports[key]);
2589
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
2590
+ }
2591
+ modPkg.exports = normalized;
2592
+ }
2517
2593
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2518
2594
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2519
2595
  }
2520
2596
  }
2521
2597
 
2522
- async function installPackage(pkgSpec, ctx) {
2598
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
2599
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
2600
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
2601
+ const isDev = Boolean(options.dev);
2523
2602
  const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2524
2603
  if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2525
2604
 
2526
2605
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2527
- if (!pkgData.dependencies) pkgData.dependencies = {};
2606
+ const depField = isDev ? 'devDependencies' : 'dependencies';
2607
+ if (!pkgData[depField]) pkgData[depField] = {};
2528
2608
 
2529
2609
  const fetchImpl = packageCtxFetch(ctx);
2530
2610
  const seen = (ctx.shell && ctx.shell._cdnSeen)
@@ -2550,11 +2630,13 @@
2550
2630
  });
2551
2631
  if (!warning) warning = info.reason;
2552
2632
  installed.push({ name: item.name, version: '0.0.0' });
2633
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
2553
2634
  continue;
2554
2635
  }
2555
2636
 
2556
2637
  writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2557
2638
  installed.push({ name: item.name, version: info.version || '1.0.0' });
2639
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
2558
2640
  if (item.direct) directVersion = info.version || null;
2559
2641
 
2560
2642
  for (const dep of (info.deps || [])) {
@@ -2566,12 +2648,71 @@
2566
2648
  }
2567
2649
  }
2568
2650
 
2569
- pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2651
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2570
2652
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2571
2653
 
2572
2654
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
2573
2655
  }
2574
2656
 
2657
+ // Build a live install log: each line is streamed to the terminal as it
2658
+ // happens (when possible) and accumulated so the command can also return it.
2659
+ function createInstallEmitter(ctx, sink) {
2660
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
2661
+ return function emit(text) {
2662
+ if (!text) return;
2663
+ sink.push(text);
2664
+ if (stream) stream(text);
2665
+ };
2666
+ }
2667
+
2668
+ function formatInstallLine(info) {
2669
+ if (!info || !info.name) return '';
2670
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
2671
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
2672
+ }
2673
+
2674
+ function countInstalledPackages(results) {
2675
+ const seen = new Set();
2676
+ for (const r of results) {
2677
+ if (!r) continue;
2678
+ if (r.name) seen.add(r.name);
2679
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
2680
+ }
2681
+ return seen.size;
2682
+ }
2683
+
2684
+ // Resolve + install a list of specs while printing a realistic transcript,
2685
+ // so `npm install` / `bun add` look like the real tools instead of a terse
2686
+ // "saved N package(s)".
2687
+ async function runInstallTranscript(pkgs, ctx, opts) {
2688
+ const options = opts || {};
2689
+ const manager = options.manager || 'bun';
2690
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
2691
+ const out = [];
2692
+ const emit = createInstallEmitter(ctx, out);
2693
+ const started = Date.now();
2694
+ emit(`${header}\n\nResolving dependencies...\n`);
2695
+ const results = [];
2696
+ for (const p of pkgs) {
2697
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
2698
+ }
2699
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
2700
+ const count = countInstalledPackages(results);
2701
+ const ms = Date.now() - started;
2702
+ if (manager === 'npm') {
2703
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
2704
+ } else if (manager === 'pnpm') {
2705
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
2706
+ } else {
2707
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
2708
+ }
2709
+ return {
2710
+ code: 0,
2711
+ stdout: out.join(''),
2712
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
2713
+ };
2714
+ }
2715
+
2575
2716
  function uninstallPackage(pkgName, ctx) {
2576
2717
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2577
2718
  let changed = false;
@@ -2623,9 +2764,261 @@
2623
2764
  if (scriptArgs && scriptArgs.length > 0) {
2624
2765
  cmd += ' ' + scriptArgs.join(' ');
2625
2766
  }
2767
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2768
+ if (fallback) return fallback;
2626
2769
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
2627
2770
  }
2628
2771
 
2772
+ // ---------------------------------------------------------------------------
2773
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
2774
+ //
2775
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
2776
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
2777
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
2778
+ // `+esm` builds through an injected import map — no bundler required.
2779
+ // ---------------------------------------------------------------------------
2780
+
2781
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
2782
+
2783
+ const PREVIEW_MIME = {
2784
+ '.html': 'text/html; charset=utf-8',
2785
+ '.htm': 'text/html; charset=utf-8',
2786
+ '.js': 'text/javascript; charset=utf-8',
2787
+ '.mjs': 'text/javascript; charset=utf-8',
2788
+ '.cjs': 'text/javascript; charset=utf-8',
2789
+ '.jsx': 'text/javascript; charset=utf-8',
2790
+ '.ts': 'text/javascript; charset=utf-8',
2791
+ '.tsx': 'text/javascript; charset=utf-8',
2792
+ '.css': 'text/css; charset=utf-8',
2793
+ '.json': 'application/json; charset=utf-8',
2794
+ '.map': 'application/json; charset=utf-8',
2795
+ '.svg': 'image/svg+xml',
2796
+ '.png': 'image/png',
2797
+ '.jpg': 'image/jpeg',
2798
+ '.jpeg': 'image/jpeg',
2799
+ '.gif': 'image/gif',
2800
+ '.webp': 'image/webp',
2801
+ '.ico': 'image/x-icon',
2802
+ '.txt': 'text/plain; charset=utf-8'
2803
+ };
2804
+
2805
+ function previewMimeFor(p) {
2806
+ const lower = String(p).toLowerCase();
2807
+ const dot = lower.lastIndexOf('.');
2808
+ if (dot === -1) return 'application/octet-stream';
2809
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
2810
+ }
2811
+
2812
+ function isPreviewScriptPath(p) {
2813
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
2814
+ }
2815
+
2816
+ // Collect bare (non-relative) module specifiers referenced by a source file.
2817
+ function extractBareSpecifiers(code) {
2818
+ const out = new Set();
2819
+ const patterns = [
2820
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2821
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2822
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2823
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
2824
+ ];
2825
+ for (const re of patterns) {
2826
+ let m;
2827
+ while ((m = re.exec(code)) !== null) {
2828
+ const spec = m[1];
2829
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
2830
+ out.add(spec);
2831
+ }
2832
+ }
2833
+ return Array.from(out);
2834
+ }
2835
+
2836
+ function normalizeVersionRange(range) {
2837
+ if (!range || typeof range !== 'string') return 'latest';
2838
+ const v = range.trim();
2839
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
2840
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
2841
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
2842
+ }
2843
+
2844
+ function resolveBareVersion(vfs, rootDir, pkgName) {
2845
+ try {
2846
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
2847
+ if (vfs.existsSync(modPkg)) {
2848
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2849
+ if (parsed && parsed.version) return parsed.version;
2850
+ }
2851
+ } catch (_) {}
2852
+ try {
2853
+ for (const dir of [rootDir, '/workspace']) {
2854
+ const pkgPath = PosixPath.join(dir, 'package.json');
2855
+ if (!vfs.existsSync(pkgPath)) continue;
2856
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
2857
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2858
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2859
+ }
2860
+ } catch (_) {}
2861
+ return 'latest';
2862
+ }
2863
+
2864
+ function cdnEsmUrl(pkgName, version, subpath) {
2865
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
2866
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
2867
+ return `${base}${sub}/+esm`;
2868
+ }
2869
+
2870
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
2871
+ const imports = {};
2872
+ for (const spec of specifiers) {
2873
+ const parts = String(spec).split('/');
2874
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
2875
+ if (!pkgName) continue;
2876
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
2877
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
2878
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
2879
+ }
2880
+ return imports;
2881
+ }
2882
+
2883
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
2884
+ const scripts = [];
2885
+ const walk = (dir, depth) => {
2886
+ if (depth > 8 || scripts.length >= maxFiles) return;
2887
+ let entries = [];
2888
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
2889
+ for (const name of entries) {
2890
+ if (name === 'node_modules' || name.startsWith('.')) continue;
2891
+ const full = PosixPath.join(dir, name);
2892
+ let st;
2893
+ try { st = vfs.statSync(full); } catch (_) { continue; }
2894
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
2895
+ if (dirFlag) {
2896
+ walk(full, depth + 1);
2897
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
2898
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
2899
+ }
2900
+ }
2901
+ };
2902
+ walk(rootDir, 0);
2903
+ return scripts;
2904
+ }
2905
+
2906
+ function injectPreviewExtras(html, importMap) {
2907
+ let out = html;
2908
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
2909
+ if (/<head[^>]*>/i.test(out)) {
2910
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
2911
+ } else {
2912
+ out = importMapTag + '\n' + out;
2913
+ }
2914
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
2915
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
2916
+ else out = out + '\n' + shim;
2917
+ return out;
2918
+ }
2919
+
2920
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
2921
+ const portTable = ctx.shell && ctx.shell.portTable;
2922
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
2923
+
2924
+ let port = Number(preferredPort) || 3000;
2925
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
2926
+ while (taken.has(port)) port++;
2927
+
2928
+ const specifiers = new Set();
2929
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
2930
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
2931
+ }
2932
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
2933
+
2934
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
2935
+ const isDir = (p) => {
2936
+ try {
2937
+ const st = ctx.vfs.statSync(p);
2938
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
2939
+ } catch (_) { return false; }
2940
+ };
2941
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
2942
+
2943
+ const handler = async (request) => {
2944
+ let pathname = '/';
2945
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
2946
+ const rel = pathname.replace(/^\/+/, '');
2947
+ let target = PosixPath.join(rootDir, rel);
2948
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
2949
+
2950
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
2951
+ target = PosixPath.join(target, 'index.html');
2952
+ }
2953
+ if (!exists(target) && !hasExt) {
2954
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
2955
+ // the way a bundler / dev server would.
2956
+ const cands = [
2957
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
2958
+ target + '.mjs', target + '.cjs',
2959
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
2960
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
2961
+ ];
2962
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
2963
+ }
2964
+ if (!exists(target) && !hasExt) {
2965
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
2966
+ }
2967
+ if (!exists(target)) {
2968
+ return new Response(
2969
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
2970
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
2971
+ );
2972
+ }
2973
+
2974
+ let body = readText(target);
2975
+ if (body === null) body = '';
2976
+ if (/\.html?$/i.test(target)) {
2977
+ body = injectPreviewExtras(body, importMap);
2978
+ } else if (isPreviewScriptPath(target)) {
2979
+ try {
2980
+ const rm = getRuntimeModule();
2981
+ if (rm && typeof rm.transpileForBrowser === 'function') {
2982
+ body = rm.transpileForBrowser(body, target);
2983
+ }
2984
+ } catch (_) {}
2985
+ }
2986
+
2987
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
2988
+ };
2989
+
2990
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
2991
+ return portTable.registerServer(port, {
2992
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
2993
+ fetch: handler,
2994
+ name: 'code-lab-serve',
2995
+ pid,
2996
+ root: rootDir
2997
+ });
2998
+ }
2999
+
3000
+ // Common dev-server commands that cannot run inside the virtual runtime are
3001
+ // transparently redirected to the built-in preview server.
3002
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3003
+
3004
+ function tryDevScriptFallback(scriptName, cmd, ctx) {
3005
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3006
+ // Only fall back when the referenced tool is not actually installed.
3007
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3008
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3009
+ if (ctx.vfs.existsSync(binPath)) return null;
3010
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3011
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3012
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3013
+ const entry = registerPreviewServer(ctx, ctx.cwd, port);
3014
+ if (!entry) return null;
3015
+ return {
3016
+ code: 0,
3017
+ 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`,
3018
+ stderr: ''
3019
+ };
3020
+ }
3021
+
2629
3022
  function evaluatePosixTest(args, ctx) {
2630
3023
  const cleanArgs = [...args];
2631
3024
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -5124,7 +5517,8 @@
5124
5517
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
5125
5518
  stdout += ' history, ps, jobs, kill Process and job management\n';
5126
5519
  stdout += ' git [status diff log] Built-in version control\n';
5127
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
5520
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5521
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
5128
5522
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
5129
5523
  return { code: 0, stdout, stderr: '' };
5130
5524
  },
@@ -5309,26 +5703,25 @@
5309
5703
 
5310
5704
  if (sub === 'install' || sub === 'i' || sub === 'ci') {
5311
5705
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5706
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5312
5707
  if (pkgs.length === 0) {
5313
5708
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5314
- const deps = Object.keys(pkgData.dependencies || {});
5315
- const results = [];
5316
- for (const p of deps) results.push(await installPackage(p, ctx));
5317
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5318
- return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5709
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5710
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5711
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
5319
5712
  }
5320
- const results = [];
5321
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5322
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5323
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5713
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5324
5714
  }
5325
5715
 
5326
5716
  if (sub === 'add') {
5327
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5328
- const results = [];
5329
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5330
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5331
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5717
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5718
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5719
+ if (pkgs.length === 0) {
5720
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5721
+ pkgs = Object.keys(pkgData.dependencies || {});
5722
+ }
5723
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5724
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5332
5725
  }
5333
5726
 
5334
5727
  if (sub === 'remove' || sub === 'rm') {
@@ -5488,22 +5881,14 @@
5488
5881
  }
5489
5882
 
5490
5883
  if (sub === 'i' || sub === 'install' || sub === 'add') {
5491
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5884
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5885
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
5492
5886
  if (pkgs.length === 0) {
5493
5887
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5494
- const results = [];
5495
- for (const p of Object.keys(pkgData.dependencies || {})) {
5496
- results.push(await installPackage(p, ctx));
5497
- }
5498
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5499
- return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5888
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5889
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5500
5890
  }
5501
- const results = [];
5502
- for (const p of pkgs) {
5503
- results.push(await installPackage(p, ctx));
5504
- }
5505
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5506
- return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5891
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
5507
5892
  }
5508
5893
 
5509
5894
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5555,6 +5940,123 @@
5555
5940
  return await this.npx(args, ctx);
5556
5941
  },
5557
5942
 
5943
+ async pnpm(args, ctx) {
5944
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
5945
+ return {
5946
+ code: 0,
5947
+ 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',
5948
+ stderr: ''
5949
+ };
5950
+ }
5951
+ const sub = args[0];
5952
+ if (sub === '--version' || sub === '-v') {
5953
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
5954
+ }
5955
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
5956
+
5957
+ if (sub === 'init') {
5958
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5959
+ if (!ctx.vfs.existsSync(pkgPath)) {
5960
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
5961
+ name: PosixPath.basename(ctx.cwd) || 'app',
5962
+ version: '1.0.0',
5963
+ main: 'index.js',
5964
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
5965
+ }, null, 2) + '\n');
5966
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
5967
+ }
5968
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
5969
+ }
5970
+
5971
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
5972
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5973
+ if (pkgs.length === 0) {
5974
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5975
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5976
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
5977
+ }
5978
+ const verb = (sub === 'add') ? 'add' : 'install';
5979
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
5980
+ }
5981
+
5982
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
5983
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5984
+ for (const p of pkgs) uninstallPackage(p, ctx);
5985
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
5986
+ }
5987
+
5988
+ if (sub === 'list' || sub === 'ls') {
5989
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
5990
+ }
5991
+
5992
+ if (sub === 'run' || sub === 'run-script') {
5993
+ const scriptName = args[1];
5994
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
5995
+ return await runPackageScript(scriptName, args.slice(2), ctx);
5996
+ }
5997
+
5998
+ if (sub === 'test') {
5999
+ return await runPackageScript('test', args.slice(1), ctx);
6000
+ }
6001
+
6002
+ if (sub === 'exec') {
6003
+ const cmd = args[1];
6004
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6005
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6006
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6007
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6008
+ }
6009
+
6010
+ if (sub === 'dlx') {
6011
+ return await this.npx(args.slice(1), ctx);
6012
+ }
6013
+
6014
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
6015
+ if (pkgData.scripts && pkgData.scripts[sub]) {
6016
+ return await runPackageScript(sub, args.slice(1), ctx);
6017
+ }
6018
+
6019
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
6020
+ },
6021
+
6022
+ async serve(args, ctx) {
6023
+ if (args[0] === '--help' || args[0] === '-h') {
6024
+ return {
6025
+ code: 0,
6026
+ 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',
6027
+ stderr: ''
6028
+ };
6029
+ }
6030
+ const rootArg = (() => {
6031
+ const positionals = [];
6032
+ for (let i = 0; i < args.length; i++) {
6033
+ const a = args[i];
6034
+ if (a === '--port' || a === '-p') { i++; continue; }
6035
+ if (a.startsWith('-')) continue;
6036
+ positionals.push(a);
6037
+ }
6038
+ return positionals[0];
6039
+ })();
6040
+ let port = 3000;
6041
+ for (let i = 0; i < args.length; i++) {
6042
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
6043
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
6044
+ }
6045
+ const rootDir = ctx.resolvePath(rootArg || '.');
6046
+ if (!ctx.vfs.existsSync(rootDir)) {
6047
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
6048
+ }
6049
+ const entry = registerPreviewServer(ctx, rootDir, port);
6050
+ if (!entry) {
6051
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
6052
+ }
6053
+ return {
6054
+ code: 0,
6055
+ 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`,
6056
+ stderr: ''
6057
+ };
6058
+ },
6059
+
5558
6060
  // -----------------------------------------------------------------------
5559
6061
  // Port Table & HTTP Inspection: ports, curl
5560
6062
  // -----------------------------------------------------------------------