@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/ARCHITECTURE.md +2 -1
- package/README.md +4 -2
- package/dist/code-lab.css +49 -0
- package/dist/code-lab.esm.js +946 -70
- package/dist/code-lab.js +946 -70
- package/dist/runtime.esm.js +329 -18
- package/dist/runtime.js +329 -18
- package/dist/shell.esm.js +553 -51
- package/dist/shell.js +553 -51
- package/package.json +6 -2
- package/src/code-lab.css +49 -0
- package/src/runtime.js +329 -18
- package/src/runtime.ts +329 -18
- package/src/shell.js +553 -51
- package/src/shell.ts +553 -51
- package/src/workbench.js +64 -1
- package/src/workbench.ts +64 -1
package/src/shell.ts
CHANGED
|
@@ -2421,9 +2421,31 @@ function __initShellModule(root: any) {
|
|
|
2421
2421
|
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2422
2422
|
}
|
|
2423
2423
|
|
|
2424
|
+
function pickConditionalEntry(value) {
|
|
2425
|
+
if (typeof value === 'string') return value;
|
|
2426
|
+
if (!value || typeof value !== 'object') return null;
|
|
2427
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2428
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2429
|
+
if (value[key] !== undefined) {
|
|
2430
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2431
|
+
if (picked) return picked;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
return null;
|
|
2435
|
+
}
|
|
2436
|
+
|
|
2424
2437
|
function resolveEntryRelPath(pkgJson) {
|
|
2425
|
-
let entry =
|
|
2426
|
-
|
|
2438
|
+
let entry = null;
|
|
2439
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2440
|
+
if (typeof exp === 'string') {
|
|
2441
|
+
entry = exp;
|
|
2442
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2443
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2444
|
+
}
|
|
2445
|
+
if (!entry) {
|
|
2446
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2447
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2448
|
+
}
|
|
2427
2449
|
entry = String(entry).replace(/^[./]+/, '');
|
|
2428
2450
|
return entry || 'index.js';
|
|
2429
2451
|
}
|
|
@@ -2434,9 +2456,16 @@ function __initShellModule(root: any) {
|
|
|
2434
2456
|
|
|
2435
2457
|
function extractRelativeSpecifiers(code) {
|
|
2436
2458
|
const out = new Set();
|
|
2437
|
-
const
|
|
2438
|
-
|
|
2439
|
-
|
|
2459
|
+
const patterns = [
|
|
2460
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2461
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2462
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2463
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2464
|
+
];
|
|
2465
|
+
for (const re of patterns) {
|
|
2466
|
+
let m;
|
|
2467
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2468
|
+
}
|
|
2440
2469
|
return Array.from(out);
|
|
2441
2470
|
}
|
|
2442
2471
|
|
|
@@ -2501,20 +2530,49 @@ function __initShellModule(root: any) {
|
|
|
2501
2530
|
const entry = resolveEntryRelPath(meta);
|
|
2502
2531
|
const files = [];
|
|
2503
2532
|
const visited = new Set();
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2533
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2534
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2535
|
+
const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
|
|
2536
|
+
const expMap = meta.exports;
|
|
2537
|
+
if (expMap && typeof expMap === 'object') {
|
|
2538
|
+
let subCount = 0;
|
|
2539
|
+
for (const key of Object.keys(expMap)) {
|
|
2540
|
+
if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
|
|
2541
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2542
|
+
if (target) { seed.push(target); subCount++; }
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
let frontier = seed;
|
|
2546
|
+
while (frontier.length > 0) {
|
|
2547
|
+
const batch = [];
|
|
2548
|
+
for (const raw of frontier) {
|
|
2549
|
+
const rel = stripRelPath(raw);
|
|
2550
|
+
if (!rel || visited.has(rel)) continue;
|
|
2551
|
+
visited.add(rel);
|
|
2552
|
+
batch.push(rel);
|
|
2553
|
+
}
|
|
2554
|
+
frontier = [];
|
|
2555
|
+
if (batch.length === 0) break;
|
|
2556
|
+
const texts = await Promise.all(
|
|
2557
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2558
|
+
);
|
|
2559
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2560
|
+
const rel = batch[idx];
|
|
2561
|
+
const text = texts[idx];
|
|
2562
|
+
if (text === null) continue;
|
|
2563
|
+
files.push({ rel, content: text });
|
|
2564
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2565
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2566
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2567
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2568
|
+
// candidates 404 harmlessly.
|
|
2569
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2570
|
+
? [target]
|
|
2571
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2572
|
+
for (const cand of cands) {
|
|
2573
|
+
const c = stripRelPath(cand);
|
|
2574
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2575
|
+
}
|
|
2518
2576
|
}
|
|
2519
2577
|
}
|
|
2520
2578
|
}
|
|
@@ -2524,7 +2582,16 @@ function __initShellModule(root: any) {
|
|
|
2524
2582
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2525
2583
|
}
|
|
2526
2584
|
|
|
2527
|
-
|
|
2585
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2586
|
+
// so e.g. `npm install react-dom` also pulls in `react`.
|
|
2587
|
+
const depNames = Object.keys(meta.dependencies || {});
|
|
2588
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2589
|
+
for (const peer of Object.keys(meta.peerDependencies || {})) {
|
|
2590
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2591
|
+
if (depNames.indexOf(peer) === -1) depNames.push(peer);
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2528
2595
|
}
|
|
2529
2596
|
|
|
2530
2597
|
function installTargetDirs(ctx, name) {
|
|
@@ -2545,17 +2612,30 @@ function __initShellModule(root: any) {
|
|
|
2545
2612
|
}
|
|
2546
2613
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2547
2614
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2615
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2616
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2617
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2618
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2619
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2620
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2621
|
+
}
|
|
2622
|
+
modPkg.exports = normalized;
|
|
2623
|
+
}
|
|
2548
2624
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2549
2625
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2550
2626
|
}
|
|
2551
2627
|
}
|
|
2552
2628
|
|
|
2553
|
-
async function installPackage(pkgSpec, ctx) {
|
|
2629
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2630
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2631
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2632
|
+
const isDev = Boolean(options.dev);
|
|
2554
2633
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2555
2634
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2556
2635
|
|
|
2557
2636
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2558
|
-
|
|
2637
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2638
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2559
2639
|
|
|
2560
2640
|
const fetchImpl = packageCtxFetch(ctx);
|
|
2561
2641
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -2581,11 +2661,13 @@ function __initShellModule(root: any) {
|
|
|
2581
2661
|
});
|
|
2582
2662
|
if (!warning) warning = info.reason;
|
|
2583
2663
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
2664
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2584
2665
|
continue;
|
|
2585
2666
|
}
|
|
2586
2667
|
|
|
2587
2668
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2588
2669
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2670
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2589
2671
|
if (item.direct) directVersion = info.version || null;
|
|
2590
2672
|
|
|
2591
2673
|
for (const dep of (info.deps || [])) {
|
|
@@ -2597,12 +2679,71 @@ function __initShellModule(root: any) {
|
|
|
2597
2679
|
}
|
|
2598
2680
|
}
|
|
2599
2681
|
|
|
2600
|
-
pkgData
|
|
2682
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2601
2683
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2602
2684
|
|
|
2603
2685
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2604
2686
|
}
|
|
2605
2687
|
|
|
2688
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2689
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2690
|
+
function createInstallEmitter(ctx, sink) {
|
|
2691
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2692
|
+
return function emit(text) {
|
|
2693
|
+
if (!text) return;
|
|
2694
|
+
sink.push(text);
|
|
2695
|
+
if (stream) stream(text);
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
function formatInstallLine(info) {
|
|
2700
|
+
if (!info || !info.name) return '';
|
|
2701
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2702
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
function countInstalledPackages(results) {
|
|
2706
|
+
const seen = new Set();
|
|
2707
|
+
for (const r of results) {
|
|
2708
|
+
if (!r) continue;
|
|
2709
|
+
if (r.name) seen.add(r.name);
|
|
2710
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2711
|
+
}
|
|
2712
|
+
return seen.size;
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2716
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2717
|
+
// "saved N package(s)".
|
|
2718
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2719
|
+
const options = opts || {};
|
|
2720
|
+
const manager = options.manager || 'bun';
|
|
2721
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2722
|
+
const out = [];
|
|
2723
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2724
|
+
const started = Date.now();
|
|
2725
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2726
|
+
const results = [];
|
|
2727
|
+
for (const p of pkgs) {
|
|
2728
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2729
|
+
}
|
|
2730
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2731
|
+
const count = countInstalledPackages(results);
|
|
2732
|
+
const ms = Date.now() - started;
|
|
2733
|
+
if (manager === 'npm') {
|
|
2734
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2735
|
+
} else if (manager === 'pnpm') {
|
|
2736
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2737
|
+
} else {
|
|
2738
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2739
|
+
}
|
|
2740
|
+
return {
|
|
2741
|
+
code: 0,
|
|
2742
|
+
stdout: out.join(''),
|
|
2743
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2744
|
+
};
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2606
2747
|
function uninstallPackage(pkgName, ctx) {
|
|
2607
2748
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2608
2749
|
let changed = false;
|
|
@@ -2654,9 +2795,261 @@ function __initShellModule(root: any) {
|
|
|
2654
2795
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2655
2796
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2656
2797
|
}
|
|
2798
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2799
|
+
if (fallback) return fallback;
|
|
2657
2800
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2658
2801
|
}
|
|
2659
2802
|
|
|
2803
|
+
// ---------------------------------------------------------------------------
|
|
2804
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2805
|
+
//
|
|
2806
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2807
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2808
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2809
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2810
|
+
// ---------------------------------------------------------------------------
|
|
2811
|
+
|
|
2812
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2813
|
+
|
|
2814
|
+
const PREVIEW_MIME = {
|
|
2815
|
+
'.html': 'text/html; charset=utf-8',
|
|
2816
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2817
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2818
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2819
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2820
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2821
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2822
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2823
|
+
'.css': 'text/css; charset=utf-8',
|
|
2824
|
+
'.json': 'application/json; charset=utf-8',
|
|
2825
|
+
'.map': 'application/json; charset=utf-8',
|
|
2826
|
+
'.svg': 'image/svg+xml',
|
|
2827
|
+
'.png': 'image/png',
|
|
2828
|
+
'.jpg': 'image/jpeg',
|
|
2829
|
+
'.jpeg': 'image/jpeg',
|
|
2830
|
+
'.gif': 'image/gif',
|
|
2831
|
+
'.webp': 'image/webp',
|
|
2832
|
+
'.ico': 'image/x-icon',
|
|
2833
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2834
|
+
};
|
|
2835
|
+
|
|
2836
|
+
function previewMimeFor(p) {
|
|
2837
|
+
const lower = String(p).toLowerCase();
|
|
2838
|
+
const dot = lower.lastIndexOf('.');
|
|
2839
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2840
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2841
|
+
}
|
|
2842
|
+
|
|
2843
|
+
function isPreviewScriptPath(p) {
|
|
2844
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2848
|
+
function extractBareSpecifiers(code) {
|
|
2849
|
+
const out = new Set();
|
|
2850
|
+
const patterns = [
|
|
2851
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2852
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2853
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2854
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2855
|
+
];
|
|
2856
|
+
for (const re of patterns) {
|
|
2857
|
+
let m;
|
|
2858
|
+
while ((m = re.exec(code)) !== null) {
|
|
2859
|
+
const spec = m[1];
|
|
2860
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2861
|
+
out.add(spec);
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
return Array.from(out);
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
function normalizeVersionRange(range) {
|
|
2868
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2869
|
+
const v = range.trim();
|
|
2870
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2871
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2872
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2876
|
+
try {
|
|
2877
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2878
|
+
if (vfs.existsSync(modPkg)) {
|
|
2879
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2880
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2881
|
+
}
|
|
2882
|
+
} catch (_) {}
|
|
2883
|
+
try {
|
|
2884
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2885
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2886
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2887
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2888
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2889
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2890
|
+
}
|
|
2891
|
+
} catch (_) {}
|
|
2892
|
+
return 'latest';
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2895
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2896
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2897
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2898
|
+
return `${base}${sub}/+esm`;
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2902
|
+
const imports = {};
|
|
2903
|
+
for (const spec of specifiers) {
|
|
2904
|
+
const parts = String(spec).split('/');
|
|
2905
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2906
|
+
if (!pkgName) continue;
|
|
2907
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2908
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2909
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2910
|
+
}
|
|
2911
|
+
return imports;
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2915
|
+
const scripts = [];
|
|
2916
|
+
const walk = (dir, depth) => {
|
|
2917
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2918
|
+
let entries = [];
|
|
2919
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2920
|
+
for (const name of entries) {
|
|
2921
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2922
|
+
const full = PosixPath.join(dir, name);
|
|
2923
|
+
let st;
|
|
2924
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2925
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2926
|
+
if (dirFlag) {
|
|
2927
|
+
walk(full, depth + 1);
|
|
2928
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2929
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2932
|
+
};
|
|
2933
|
+
walk(rootDir, 0);
|
|
2934
|
+
return scripts;
|
|
2935
|
+
}
|
|
2936
|
+
|
|
2937
|
+
function injectPreviewExtras(html, importMap) {
|
|
2938
|
+
let out = html;
|
|
2939
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2940
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2941
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2942
|
+
} else {
|
|
2943
|
+
out = importMapTag + '\n' + out;
|
|
2944
|
+
}
|
|
2945
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2946
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2947
|
+
else out = out + '\n' + shim;
|
|
2948
|
+
return out;
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2952
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2953
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2954
|
+
|
|
2955
|
+
let port = Number(preferredPort) || 3000;
|
|
2956
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
2957
|
+
while (taken.has(port)) port++;
|
|
2958
|
+
|
|
2959
|
+
const specifiers = new Set();
|
|
2960
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
2961
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
2962
|
+
}
|
|
2963
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
2964
|
+
|
|
2965
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
2966
|
+
const isDir = (p) => {
|
|
2967
|
+
try {
|
|
2968
|
+
const st = ctx.vfs.statSync(p);
|
|
2969
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
2970
|
+
} catch (_) { return false; }
|
|
2971
|
+
};
|
|
2972
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
2973
|
+
|
|
2974
|
+
const handler = async (request) => {
|
|
2975
|
+
let pathname = '/';
|
|
2976
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
2977
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
2978
|
+
let target = PosixPath.join(rootDir, rel);
|
|
2979
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
2980
|
+
|
|
2981
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
2982
|
+
target = PosixPath.join(target, 'index.html');
|
|
2983
|
+
}
|
|
2984
|
+
if (!exists(target) && !hasExt) {
|
|
2985
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
2986
|
+
// the way a bundler / dev server would.
|
|
2987
|
+
const cands = [
|
|
2988
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
2989
|
+
target + '.mjs', target + '.cjs',
|
|
2990
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
2991
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
2992
|
+
];
|
|
2993
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
2994
|
+
}
|
|
2995
|
+
if (!exists(target) && !hasExt) {
|
|
2996
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
2997
|
+
}
|
|
2998
|
+
if (!exists(target)) {
|
|
2999
|
+
return new Response(
|
|
3000
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
3001
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
3002
|
+
);
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
let body = readText(target);
|
|
3006
|
+
if (body === null) body = '';
|
|
3007
|
+
if (/\.html?$/i.test(target)) {
|
|
3008
|
+
body = injectPreviewExtras(body, importMap);
|
|
3009
|
+
} else if (isPreviewScriptPath(target)) {
|
|
3010
|
+
try {
|
|
3011
|
+
const rm = getRuntimeModule();
|
|
3012
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3013
|
+
body = rm.transpileForBrowser(body, target);
|
|
3014
|
+
}
|
|
3015
|
+
} catch (_) {}
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
3019
|
+
};
|
|
3020
|
+
|
|
3021
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3022
|
+
return portTable.registerServer(port, {
|
|
3023
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
3024
|
+
fetch: handler,
|
|
3025
|
+
name: 'code-lab-serve',
|
|
3026
|
+
pid,
|
|
3027
|
+
root: rootDir
|
|
3028
|
+
});
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3032
|
+
// transparently redirected to the built-in preview server.
|
|
3033
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3034
|
+
|
|
3035
|
+
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
3036
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3037
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3038
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3039
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3040
|
+
if (ctx.vfs.existsSync(binPath)) return null;
|
|
3041
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3042
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3043
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3044
|
+
const entry = registerPreviewServer(ctx, ctx.cwd, port);
|
|
3045
|
+
if (!entry) return null;
|
|
3046
|
+
return {
|
|
3047
|
+
code: 0,
|
|
3048
|
+
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`,
|
|
3049
|
+
stderr: ''
|
|
3050
|
+
};
|
|
3051
|
+
}
|
|
3052
|
+
|
|
2660
3053
|
function evaluatePosixTest(args, ctx) {
|
|
2661
3054
|
const cleanArgs = [...args];
|
|
2662
3055
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -5155,7 +5548,8 @@ function __initShellModule(root: any) {
|
|
|
5155
5548
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
5156
5549
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
5157
5550
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
5158
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5551
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5552
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
5159
5553
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
5160
5554
|
return { code: 0, stdout, stderr: '' };
|
|
5161
5555
|
},
|
|
@@ -5340,26 +5734,25 @@ function __initShellModule(root: any) {
|
|
|
5340
5734
|
|
|
5341
5735
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5342
5736
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5737
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5343
5738
|
if (pkgs.length === 0) {
|
|
5344
5739
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5345
|
-
const deps = Object.keys(pkgData.dependencies || {});
|
|
5346
|
-
|
|
5347
|
-
|
|
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` : '' };
|
|
5740
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5741
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5742
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5350
5743
|
}
|
|
5351
|
-
|
|
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` : '' };
|
|
5744
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5355
5745
|
}
|
|
5356
5746
|
|
|
5357
5747
|
if (sub === 'add') {
|
|
5358
|
-
|
|
5359
|
-
const
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5748
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5749
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5750
|
+
if (pkgs.length === 0) {
|
|
5751
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5752
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5753
|
+
}
|
|
5754
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5755
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5363
5756
|
}
|
|
5364
5757
|
|
|
5365
5758
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5519,22 +5912,14 @@ function __initShellModule(root: any) {
|
|
|
5519
5912
|
}
|
|
5520
5913
|
|
|
5521
5914
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5522
|
-
|
|
5915
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5916
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5523
5917
|
if (pkgs.length === 0) {
|
|
5524
5918
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
results.push(await installPackage(p, ctx));
|
|
5528
|
-
}
|
|
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` : '' };
|
|
5531
|
-
}
|
|
5532
|
-
const results = [];
|
|
5533
|
-
for (const p of pkgs) {
|
|
5534
|
-
results.push(await installPackage(p, ctx));
|
|
5919
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5920
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5535
5921
|
}
|
|
5536
|
-
|
|
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` : '' };
|
|
5922
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5538
5923
|
}
|
|
5539
5924
|
|
|
5540
5925
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5586,6 +5971,123 @@ function __initShellModule(root: any) {
|
|
|
5586
5971
|
return await this.npx(args, ctx);
|
|
5587
5972
|
},
|
|
5588
5973
|
|
|
5974
|
+
async pnpm(args, ctx) {
|
|
5975
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
5976
|
+
return {
|
|
5977
|
+
code: 0,
|
|
5978
|
+
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',
|
|
5979
|
+
stderr: ''
|
|
5980
|
+
};
|
|
5981
|
+
}
|
|
5982
|
+
const sub = args[0];
|
|
5983
|
+
if (sub === '--version' || sub === '-v') {
|
|
5984
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
5985
|
+
}
|
|
5986
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
5987
|
+
|
|
5988
|
+
if (sub === 'init') {
|
|
5989
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5990
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
5991
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
5992
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
5993
|
+
version: '1.0.0',
|
|
5994
|
+
main: 'index.js',
|
|
5995
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
5996
|
+
}, null, 2) + '\n');
|
|
5997
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
5998
|
+
}
|
|
5999
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
6000
|
+
}
|
|
6001
|
+
|
|
6002
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
6003
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6004
|
+
if (pkgs.length === 0) {
|
|
6005
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6006
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6007
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
6008
|
+
}
|
|
6009
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
6010
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
6011
|
+
}
|
|
6012
|
+
|
|
6013
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
6014
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6015
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
6016
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
6017
|
+
}
|
|
6018
|
+
|
|
6019
|
+
if (sub === 'list' || sub === 'ls') {
|
|
6020
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
6021
|
+
}
|
|
6022
|
+
|
|
6023
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
6024
|
+
const scriptName = args[1];
|
|
6025
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
6026
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
6027
|
+
}
|
|
6028
|
+
|
|
6029
|
+
if (sub === 'test') {
|
|
6030
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6031
|
+
}
|
|
6032
|
+
|
|
6033
|
+
if (sub === 'exec') {
|
|
6034
|
+
const cmd = args[1];
|
|
6035
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6036
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6037
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6038
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6039
|
+
}
|
|
6040
|
+
|
|
6041
|
+
if (sub === 'dlx') {
|
|
6042
|
+
return await this.npx(args.slice(1), ctx);
|
|
6043
|
+
}
|
|
6044
|
+
|
|
6045
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6046
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6047
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6048
|
+
}
|
|
6049
|
+
|
|
6050
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6051
|
+
},
|
|
6052
|
+
|
|
6053
|
+
async serve(args, ctx) {
|
|
6054
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6055
|
+
return {
|
|
6056
|
+
code: 0,
|
|
6057
|
+
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',
|
|
6058
|
+
stderr: ''
|
|
6059
|
+
};
|
|
6060
|
+
}
|
|
6061
|
+
const rootArg = (() => {
|
|
6062
|
+
const positionals = [];
|
|
6063
|
+
for (let i = 0; i < args.length; i++) {
|
|
6064
|
+
const a = args[i];
|
|
6065
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6066
|
+
if (a.startsWith('-')) continue;
|
|
6067
|
+
positionals.push(a);
|
|
6068
|
+
}
|
|
6069
|
+
return positionals[0];
|
|
6070
|
+
})();
|
|
6071
|
+
let port = 3000;
|
|
6072
|
+
for (let i = 0; i < args.length; i++) {
|
|
6073
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6074
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6075
|
+
}
|
|
6076
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6077
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6078
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6079
|
+
}
|
|
6080
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6081
|
+
if (!entry) {
|
|
6082
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6083
|
+
}
|
|
6084
|
+
return {
|
|
6085
|
+
code: 0,
|
|
6086
|
+
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`,
|
|
6087
|
+
stderr: ''
|
|
6088
|
+
};
|
|
6089
|
+
},
|
|
6090
|
+
|
|
5589
6091
|
// -----------------------------------------------------------------------
|
|
5590
6092
|
// Port Table & HTTP Inspection: ports, curl
|
|
5591
6093
|
// -----------------------------------------------------------------------
|