@innovatorved/code-lab 0.1.4 → 0.1.6
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.d.ts +3 -1
- package/dist/code-lab.esm.js +1472 -87
- package/dist/code-lab.js +1462 -86
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.esm.js +783 -32
- package/dist/runtime.js +740 -21
- package/dist/schemas.esm.js +4191 -0
- package/dist/schemas.js +4207 -0
- package/dist/shell.esm.js +657 -64
- package/dist/shell.js +657 -64
- package/dist/terminal.esm.js +7 -1
- package/package.json +9 -4
- package/src/code-lab.css +49 -0
- package/src/runtime.js +740 -21
- package/src/runtime.ts +741 -21
- package/src/shell.js +657 -64
- package/src/shell.ts +657 -64
- package/src/workbench.js +64 -1
- package/src/workbench.ts +64 -1
package/src/shell.ts
CHANGED
|
@@ -2421,9 +2421,40 @@ 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
|
+
// `exports` subpaths may be an array of fallbacks, e.g.
|
|
2427
|
+
// `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
|
|
2428
|
+
if (Array.isArray(value)) {
|
|
2429
|
+
for (const item of value) {
|
|
2430
|
+
const picked = pickConditionalEntry(item);
|
|
2431
|
+
if (picked) return picked;
|
|
2432
|
+
}
|
|
2433
|
+
return null;
|
|
2434
|
+
}
|
|
2435
|
+
if (!value || typeof value !== 'object') return null;
|
|
2436
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2437
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2438
|
+
if (value[key] !== undefined) {
|
|
2439
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2440
|
+
if (picked) return picked;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
return null;
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2424
2446
|
function resolveEntryRelPath(pkgJson) {
|
|
2425
|
-
let entry =
|
|
2426
|
-
|
|
2447
|
+
let entry = null;
|
|
2448
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2449
|
+
if (typeof exp === 'string') {
|
|
2450
|
+
entry = exp;
|
|
2451
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2452
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2453
|
+
}
|
|
2454
|
+
if (!entry) {
|
|
2455
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2456
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2457
|
+
}
|
|
2427
2458
|
entry = String(entry).replace(/^[./]+/, '');
|
|
2428
2459
|
return entry || 'index.js';
|
|
2429
2460
|
}
|
|
@@ -2434,9 +2465,16 @@ function __initShellModule(root: any) {
|
|
|
2434
2465
|
|
|
2435
2466
|
function extractRelativeSpecifiers(code) {
|
|
2436
2467
|
const out = new Set();
|
|
2437
|
-
const
|
|
2438
|
-
|
|
2439
|
-
|
|
2468
|
+
const patterns = [
|
|
2469
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2470
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2471
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2472
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2473
|
+
];
|
|
2474
|
+
for (const re of patterns) {
|
|
2475
|
+
let m;
|
|
2476
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2477
|
+
}
|
|
2440
2478
|
return Array.from(out);
|
|
2441
2479
|
}
|
|
2442
2480
|
|
|
@@ -2450,17 +2488,50 @@ function __initShellModule(root: any) {
|
|
|
2450
2488
|
return parts.join('/');
|
|
2451
2489
|
}
|
|
2452
2490
|
|
|
2491
|
+
// Small promise-based delay. Used only for CDN retry backoff; falls back to an
|
|
2492
|
+
// immediate resolve if `setTimeout` is unavailable in the host.
|
|
2493
|
+
function cdnBackoff(ms) {
|
|
2494
|
+
return new Promise((resolve) => {
|
|
2495
|
+
if (typeof setTimeout === 'function') setTimeout(resolve, ms);
|
|
2496
|
+
else resolve();
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2453
2500
|
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2501
|
+
// A single flaky jsDelivr response used to silently produce an *incomplete*
|
|
2502
|
+
// install (the module graph then failed at require-time). Retry transient
|
|
2503
|
+
// failures (network error, 429/408, 5xx) but treat 4xx as final.
|
|
2504
|
+
const maxAttempts = 3;
|
|
2505
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
2506
|
+
try {
|
|
2507
|
+
const res = await fetchImpl(url);
|
|
2508
|
+
if (!res) {
|
|
2509
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2510
|
+
return null;
|
|
2511
|
+
}
|
|
2512
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2513
|
+
if (!ok) {
|
|
2514
|
+
const transient = res.status >= 500 || res.status === 429 || res.status === 408;
|
|
2515
|
+
if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2516
|
+
return null;
|
|
2517
|
+
}
|
|
2518
|
+
// jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
|
|
2519
|
+
// and an HTML directory listing. Storing that as a module both corrupts the
|
|
2520
|
+
// package and later collides with the real directory (EISDIR).
|
|
2521
|
+
const contentType = (res.headers && typeof res.headers.get === 'function')
|
|
2522
|
+
? (res.headers.get('content-type') || '')
|
|
2523
|
+
: '';
|
|
2524
|
+
const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
|
|
2525
|
+
if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
|
|
2526
|
+
const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
|
|
2527
|
+
if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
|
|
2528
|
+
return text;
|
|
2529
|
+
} catch (_) {
|
|
2530
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2531
|
+
return null;
|
|
2532
|
+
}
|
|
2463
2533
|
}
|
|
2534
|
+
return null;
|
|
2464
2535
|
}
|
|
2465
2536
|
|
|
2466
2537
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
@@ -2501,20 +2572,62 @@ function __initShellModule(root: any) {
|
|
|
2501
2572
|
const entry = resolveEntryRelPath(meta);
|
|
2502
2573
|
const files = [];
|
|
2503
2574
|
const visited = new Set();
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2575
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2576
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2577
|
+
// A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
|
|
2578
|
+
// resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
|
|
2579
|
+
// too or the package installs with only its manifest.
|
|
2580
|
+
const seed = [
|
|
2581
|
+
entry,
|
|
2582
|
+
`${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
|
|
2583
|
+
`${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
|
|
2584
|
+
];
|
|
2585
|
+
const expMap = meta.exports;
|
|
2586
|
+
if (expMap && typeof expMap === 'object') {
|
|
2587
|
+
// Seed *every* declared subpath. A low cap silently dropped the tail of
|
|
2588
|
+
// packages that list each file in `exports` (lit-html has 29 keys, so
|
|
2589
|
+
// `lit-html/is-server.js` was never fetched and `require` failed later).
|
|
2590
|
+
// Wildcard keys (`./*`) need no seeding — their files are reached through
|
|
2591
|
+
// the relative-require closure or fetched on demand.
|
|
2592
|
+
for (const key of Object.keys(expMap)) {
|
|
2593
|
+
if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
|
|
2594
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2595
|
+
if (target) seed.push(target);
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
let frontier = seed;
|
|
2599
|
+
while (frontier.length > 0) {
|
|
2600
|
+
const batch = [];
|
|
2601
|
+
for (const raw of frontier) {
|
|
2602
|
+
const rel = stripRelPath(raw);
|
|
2603
|
+
// Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
|
|
2604
|
+
// be fetched as files — that is what produced the EISDIR crash.
|
|
2605
|
+
if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
|
|
2606
|
+
visited.add(rel);
|
|
2607
|
+
batch.push(rel);
|
|
2608
|
+
}
|
|
2609
|
+
frontier = [];
|
|
2610
|
+
if (batch.length === 0) break;
|
|
2611
|
+
const texts = await Promise.all(
|
|
2612
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2613
|
+
);
|
|
2614
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2615
|
+
const rel = batch[idx];
|
|
2616
|
+
const text = texts[idx];
|
|
2617
|
+
if (text === null) continue;
|
|
2618
|
+
files.push({ rel, content: text });
|
|
2619
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2620
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2621
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2622
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2623
|
+
// candidates 404 harmlessly.
|
|
2624
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2625
|
+
? [target]
|
|
2626
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2627
|
+
for (const cand of cands) {
|
|
2628
|
+
const c = stripRelPath(cand);
|
|
2629
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2630
|
+
}
|
|
2518
2631
|
}
|
|
2519
2632
|
}
|
|
2520
2633
|
}
|
|
@@ -2524,7 +2637,30 @@ function __initShellModule(root: any) {
|
|
|
2524
2637
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2525
2638
|
}
|
|
2526
2639
|
|
|
2527
|
-
|
|
2640
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2641
|
+
// so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
|
|
2642
|
+
// preserved (not just the names) so transitives resolve to the version the
|
|
2643
|
+
// parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
|
|
2644
|
+
// needs color-convert. Resolving transitive names as "latest" silently breaks
|
|
2645
|
+
// the tree (ansi-styles@6 has no deps at all).
|
|
2646
|
+
const depSpecs: Array<{ name: string; range: string | null }> = [];
|
|
2647
|
+
const depSeen = new Set<string>();
|
|
2648
|
+
const declared = (meta.dependencies || {}) as Record<string, string>;
|
|
2649
|
+
for (const depName of Object.keys(declared)) {
|
|
2650
|
+
if (depSeen.has(depName)) continue;
|
|
2651
|
+
depSeen.add(depName);
|
|
2652
|
+
depSpecs.push({ name: depName, range: declared[depName] || null });
|
|
2653
|
+
}
|
|
2654
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2655
|
+
const peers = (meta.peerDependencies || {}) as Record<string, string>;
|
|
2656
|
+
for (const peer of Object.keys(peers)) {
|
|
2657
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2658
|
+
if (depSeen.has(peer)) continue;
|
|
2659
|
+
depSeen.add(peer);
|
|
2660
|
+
depSpecs.push({ name: peer, range: peers[peer] || null });
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2528
2664
|
}
|
|
2529
2665
|
|
|
2530
2666
|
function installTargetDirs(ctx, name) {
|
|
@@ -2538,24 +2674,43 @@ function __initShellModule(root: any) {
|
|
|
2538
2674
|
for (const dir of dirs) {
|
|
2539
2675
|
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2540
2676
|
for (const f of info.files) {
|
|
2677
|
+
if (!f || !f.rel || f.rel.endsWith('/')) continue;
|
|
2541
2678
|
const full = PosixPath.join(dir, f.rel);
|
|
2679
|
+
// Never overwrite a directory with a file body (defensive: a stray
|
|
2680
|
+
// directory target would otherwise raise EISDIR).
|
|
2681
|
+
try {
|
|
2682
|
+
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
2683
|
+
} catch (_) {}
|
|
2542
2684
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2543
2685
|
ctx.vfs.writeFileSync(full, f.content);
|
|
2544
2686
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2545
2687
|
}
|
|
2546
2688
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2547
2689
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2690
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2691
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2692
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2693
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2694
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2695
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2696
|
+
}
|
|
2697
|
+
modPkg.exports = normalized;
|
|
2698
|
+
}
|
|
2548
2699
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2549
2700
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2550
2701
|
}
|
|
2551
2702
|
}
|
|
2552
2703
|
|
|
2553
|
-
async function installPackage(pkgSpec, ctx) {
|
|
2704
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2705
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2706
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2707
|
+
const isDev = Boolean(options.dev);
|
|
2554
2708
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2555
2709
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2556
2710
|
|
|
2557
2711
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2558
|
-
|
|
2712
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2713
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2559
2714
|
|
|
2560
2715
|
const fetchImpl = packageCtxFetch(ctx);
|
|
2561
2716
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -2581,28 +2736,90 @@ function __initShellModule(root: any) {
|
|
|
2581
2736
|
});
|
|
2582
2737
|
if (!warning) warning = info.reason;
|
|
2583
2738
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
2739
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2584
2740
|
continue;
|
|
2585
2741
|
}
|
|
2586
2742
|
|
|
2587
2743
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2588
2744
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2745
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2589
2746
|
if (item.direct) directVersion = info.version || null;
|
|
2590
2747
|
|
|
2591
2748
|
for (const dep of (info.deps || [])) {
|
|
2592
|
-
const
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2749
|
+
const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
|
|
2750
|
+
const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
|
|
2751
|
+
if (depName && !requested.has(depName)) {
|
|
2752
|
+
requested.add(depName);
|
|
2753
|
+
queue.push({ name: depName, range: depRange || null, direct: false });
|
|
2596
2754
|
}
|
|
2597
2755
|
}
|
|
2598
2756
|
}
|
|
2599
2757
|
|
|
2600
|
-
pkgData
|
|
2758
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2601
2759
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2602
2760
|
|
|
2603
2761
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2604
2762
|
}
|
|
2605
2763
|
|
|
2764
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2765
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2766
|
+
function createInstallEmitter(ctx, sink) {
|
|
2767
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2768
|
+
return function emit(text) {
|
|
2769
|
+
if (!text) return;
|
|
2770
|
+
sink.push(text);
|
|
2771
|
+
if (stream) stream(text);
|
|
2772
|
+
};
|
|
2773
|
+
}
|
|
2774
|
+
|
|
2775
|
+
function formatInstallLine(info) {
|
|
2776
|
+
if (!info || !info.name) return '';
|
|
2777
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2778
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
function countInstalledPackages(results) {
|
|
2782
|
+
const seen = new Set();
|
|
2783
|
+
for (const r of results) {
|
|
2784
|
+
if (!r) continue;
|
|
2785
|
+
if (r.name) seen.add(r.name);
|
|
2786
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2787
|
+
}
|
|
2788
|
+
return seen.size;
|
|
2789
|
+
}
|
|
2790
|
+
|
|
2791
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2792
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2793
|
+
// "saved N package(s)".
|
|
2794
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2795
|
+
const options = opts || {};
|
|
2796
|
+
const manager = options.manager || 'bun';
|
|
2797
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2798
|
+
const out = [];
|
|
2799
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2800
|
+
const started = Date.now();
|
|
2801
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2802
|
+
const results = [];
|
|
2803
|
+
for (const p of pkgs) {
|
|
2804
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2805
|
+
}
|
|
2806
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2807
|
+
const count = countInstalledPackages(results);
|
|
2808
|
+
const ms = Date.now() - started;
|
|
2809
|
+
if (manager === 'npm') {
|
|
2810
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2811
|
+
} else if (manager === 'pnpm') {
|
|
2812
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2813
|
+
} else {
|
|
2814
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2815
|
+
}
|
|
2816
|
+
return {
|
|
2817
|
+
code: 0,
|
|
2818
|
+
stdout: out.join(''),
|
|
2819
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2820
|
+
};
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2606
2823
|
function uninstallPackage(pkgName, ctx) {
|
|
2607
2824
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2608
2825
|
let changed = false;
|
|
@@ -2654,9 +2871,269 @@ function __initShellModule(root: any) {
|
|
|
2654
2871
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2655
2872
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2656
2873
|
}
|
|
2874
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2875
|
+
if (fallback) return fallback;
|
|
2657
2876
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2658
2877
|
}
|
|
2659
2878
|
|
|
2879
|
+
// ---------------------------------------------------------------------------
|
|
2880
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2881
|
+
//
|
|
2882
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2883
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2884
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2885
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2886
|
+
// ---------------------------------------------------------------------------
|
|
2887
|
+
|
|
2888
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2889
|
+
|
|
2890
|
+
const PREVIEW_MIME = {
|
|
2891
|
+
'.html': 'text/html; charset=utf-8',
|
|
2892
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2893
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2894
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2895
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2896
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2897
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2898
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2899
|
+
'.css': 'text/css; charset=utf-8',
|
|
2900
|
+
'.json': 'application/json; charset=utf-8',
|
|
2901
|
+
'.map': 'application/json; charset=utf-8',
|
|
2902
|
+
'.svg': 'image/svg+xml',
|
|
2903
|
+
'.png': 'image/png',
|
|
2904
|
+
'.jpg': 'image/jpeg',
|
|
2905
|
+
'.jpeg': 'image/jpeg',
|
|
2906
|
+
'.gif': 'image/gif',
|
|
2907
|
+
'.webp': 'image/webp',
|
|
2908
|
+
'.ico': 'image/x-icon',
|
|
2909
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2910
|
+
};
|
|
2911
|
+
|
|
2912
|
+
function previewMimeFor(p) {
|
|
2913
|
+
const lower = String(p).toLowerCase();
|
|
2914
|
+
const dot = lower.lastIndexOf('.');
|
|
2915
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2916
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
function isPreviewScriptPath(p) {
|
|
2920
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2924
|
+
function extractBareSpecifiers(code) {
|
|
2925
|
+
const out = new Set();
|
|
2926
|
+
const patterns = [
|
|
2927
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2928
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2929
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2930
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2931
|
+
];
|
|
2932
|
+
for (const re of patterns) {
|
|
2933
|
+
let m;
|
|
2934
|
+
while ((m = re.exec(code)) !== null) {
|
|
2935
|
+
const spec = m[1];
|
|
2936
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2937
|
+
out.add(spec);
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
return Array.from(out);
|
|
2941
|
+
}
|
|
2942
|
+
|
|
2943
|
+
function normalizeVersionRange(range) {
|
|
2944
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2945
|
+
const v = range.trim();
|
|
2946
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2947
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2948
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2952
|
+
try {
|
|
2953
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2954
|
+
if (vfs.existsSync(modPkg)) {
|
|
2955
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2956
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2957
|
+
}
|
|
2958
|
+
} catch (_) {}
|
|
2959
|
+
try {
|
|
2960
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2961
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2962
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2963
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2964
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2965
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2966
|
+
}
|
|
2967
|
+
} catch (_) {}
|
|
2968
|
+
return 'latest';
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2972
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2973
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2974
|
+
return `${base}${sub}/+esm`;
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2978
|
+
const imports = {};
|
|
2979
|
+
for (const spec of specifiers) {
|
|
2980
|
+
const parts = String(spec).split('/');
|
|
2981
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2982
|
+
if (!pkgName) continue;
|
|
2983
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2984
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2985
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2986
|
+
}
|
|
2987
|
+
return imports;
|
|
2988
|
+
}
|
|
2989
|
+
|
|
2990
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2991
|
+
const scripts = [];
|
|
2992
|
+
const walk = (dir, depth) => {
|
|
2993
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2994
|
+
let entries = [];
|
|
2995
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2996
|
+
for (const name of entries) {
|
|
2997
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2998
|
+
const full = PosixPath.join(dir, name);
|
|
2999
|
+
let st;
|
|
3000
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
3001
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
3002
|
+
if (dirFlag) {
|
|
3003
|
+
walk(full, depth + 1);
|
|
3004
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
3005
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
};
|
|
3009
|
+
walk(rootDir, 0);
|
|
3010
|
+
return scripts;
|
|
3011
|
+
}
|
|
3012
|
+
|
|
3013
|
+
function injectPreviewExtras(html, importMap) {
|
|
3014
|
+
let out = html;
|
|
3015
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
3016
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
3017
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
3018
|
+
} else {
|
|
3019
|
+
out = importMapTag + '\n' + out;
|
|
3020
|
+
}
|
|
3021
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
3022
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
3023
|
+
else out = out + '\n' + shim;
|
|
3024
|
+
return out;
|
|
3025
|
+
}
|
|
3026
|
+
|
|
3027
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
3028
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
3029
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
3030
|
+
|
|
3031
|
+
let port = Number(preferredPort) || 3000;
|
|
3032
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
3033
|
+
while (taken.has(port)) port++;
|
|
3034
|
+
|
|
3035
|
+
const specifiers = new Set();
|
|
3036
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
3037
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
3038
|
+
}
|
|
3039
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
3040
|
+
|
|
3041
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
3042
|
+
const isDir = (p) => {
|
|
3043
|
+
try {
|
|
3044
|
+
const st = ctx.vfs.statSync(p);
|
|
3045
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
3046
|
+
} catch (_) { return false; }
|
|
3047
|
+
};
|
|
3048
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
3049
|
+
|
|
3050
|
+
const handler = async (request) => {
|
|
3051
|
+
let pathname = '/';
|
|
3052
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
3053
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
3054
|
+
let target = PosixPath.join(rootDir, rel);
|
|
3055
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
3056
|
+
|
|
3057
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
3058
|
+
target = PosixPath.join(target, 'index.html');
|
|
3059
|
+
}
|
|
3060
|
+
if (!exists(target) && !hasExt) {
|
|
3061
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
3062
|
+
// the way a bundler / dev server would.
|
|
3063
|
+
const cands = [
|
|
3064
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
3065
|
+
target + '.mjs', target + '.cjs',
|
|
3066
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
3067
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
3068
|
+
];
|
|
3069
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
3070
|
+
}
|
|
3071
|
+
if (!exists(target) && !hasExt) {
|
|
3072
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
3073
|
+
}
|
|
3074
|
+
if (!exists(target)) {
|
|
3075
|
+
return new Response(
|
|
3076
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
3077
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
3078
|
+
);
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
let body = readText(target);
|
|
3082
|
+
if (body === null) body = '';
|
|
3083
|
+
if (/\.html?$/i.test(target)) {
|
|
3084
|
+
body = injectPreviewExtras(body, importMap);
|
|
3085
|
+
} else if (isPreviewScriptPath(target)) {
|
|
3086
|
+
try {
|
|
3087
|
+
const rm = getRuntimeModule();
|
|
3088
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3089
|
+
body = rm.transpileForBrowser(body, target);
|
|
3090
|
+
}
|
|
3091
|
+
} catch (_) {}
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
3095
|
+
};
|
|
3096
|
+
|
|
3097
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3098
|
+
return portTable.registerServer(port, {
|
|
3099
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
3100
|
+
fetch: handler,
|
|
3101
|
+
name: 'code-lab-serve',
|
|
3102
|
+
pid,
|
|
3103
|
+
root: rootDir
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3108
|
+
// transparently redirected to the built-in preview server.
|
|
3109
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3110
|
+
// The same tools, when typed directly at the prompt (`ng serve`, `vite`).
|
|
3111
|
+
// `serve` is omitted: it is a first-class builtin shell command.
|
|
3112
|
+
const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
|
|
3113
|
+
|
|
3114
|
+
function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
|
|
3115
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3116
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3117
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3118
|
+
const force = Boolean(opts && opts.force);
|
|
3119
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3120
|
+
if (!force && ctx.vfs.existsSync(binPath)) return null;
|
|
3121
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3122
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3123
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3124
|
+
const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
|
|
3125
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
3126
|
+
if (!entry) return null;
|
|
3127
|
+
const note = force
|
|
3128
|
+
? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
|
|
3129
|
+
: `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
|
|
3130
|
+
return {
|
|
3131
|
+
code: 0,
|
|
3132
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
3133
|
+
stderr: ''
|
|
3134
|
+
};
|
|
3135
|
+
}
|
|
3136
|
+
|
|
2660
3137
|
function evaluatePosixTest(args, ctx) {
|
|
2661
3138
|
const cleanArgs = [...args];
|
|
2662
3139
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -5155,7 +5632,8 @@ function __initShellModule(root: any) {
|
|
|
5155
5632
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
5156
5633
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
5157
5634
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
5158
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5635
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5636
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
5159
5637
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
5160
5638
|
return { code: 0, stdout, stderr: '' };
|
|
5161
5639
|
},
|
|
@@ -5340,26 +5818,25 @@ function __initShellModule(root: any) {
|
|
|
5340
5818
|
|
|
5341
5819
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5342
5820
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5821
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5343
5822
|
if (pkgs.length === 0) {
|
|
5344
5823
|
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` : '' };
|
|
5824
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5825
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5826
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5350
5827
|
}
|
|
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` : '' };
|
|
5828
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5355
5829
|
}
|
|
5356
5830
|
|
|
5357
5831
|
if (sub === 'add') {
|
|
5358
|
-
|
|
5359
|
-
const
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5832
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5833
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5834
|
+
if (pkgs.length === 0) {
|
|
5835
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5836
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5837
|
+
}
|
|
5838
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5839
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5363
5840
|
}
|
|
5364
5841
|
|
|
5365
5842
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5519,22 +5996,14 @@ function __initShellModule(root: any) {
|
|
|
5519
5996
|
}
|
|
5520
5997
|
|
|
5521
5998
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5522
|
-
|
|
5999
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
6000
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5523
6001
|
if (pkgs.length === 0) {
|
|
5524
6002
|
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));
|
|
6003
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6004
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5535
6005
|
}
|
|
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` : '' };
|
|
6006
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5538
6007
|
}
|
|
5539
6008
|
|
|
5540
6009
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5586,6 +6055,123 @@ function __initShellModule(root: any) {
|
|
|
5586
6055
|
return await this.npx(args, ctx);
|
|
5587
6056
|
},
|
|
5588
6057
|
|
|
6058
|
+
async pnpm(args, ctx) {
|
|
6059
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
6060
|
+
return {
|
|
6061
|
+
code: 0,
|
|
6062
|
+
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',
|
|
6063
|
+
stderr: ''
|
|
6064
|
+
};
|
|
6065
|
+
}
|
|
6066
|
+
const sub = args[0];
|
|
6067
|
+
if (sub === '--version' || sub === '-v') {
|
|
6068
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
6069
|
+
}
|
|
6070
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
6071
|
+
|
|
6072
|
+
if (sub === 'init') {
|
|
6073
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
6074
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
6075
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
6076
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
6077
|
+
version: '1.0.0',
|
|
6078
|
+
main: 'index.js',
|
|
6079
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
6080
|
+
}, null, 2) + '\n');
|
|
6081
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
6082
|
+
}
|
|
6083
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
6084
|
+
}
|
|
6085
|
+
|
|
6086
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
6087
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6088
|
+
if (pkgs.length === 0) {
|
|
6089
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6090
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6091
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
6092
|
+
}
|
|
6093
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
6094
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
6095
|
+
}
|
|
6096
|
+
|
|
6097
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
6098
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6099
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
6100
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
6101
|
+
}
|
|
6102
|
+
|
|
6103
|
+
if (sub === 'list' || sub === 'ls') {
|
|
6104
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
6105
|
+
}
|
|
6106
|
+
|
|
6107
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
6108
|
+
const scriptName = args[1];
|
|
6109
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
6110
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
6111
|
+
}
|
|
6112
|
+
|
|
6113
|
+
if (sub === 'test') {
|
|
6114
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6115
|
+
}
|
|
6116
|
+
|
|
6117
|
+
if (sub === 'exec') {
|
|
6118
|
+
const cmd = args[1];
|
|
6119
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6120
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6121
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6122
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6123
|
+
}
|
|
6124
|
+
|
|
6125
|
+
if (sub === 'dlx') {
|
|
6126
|
+
return await this.npx(args.slice(1), ctx);
|
|
6127
|
+
}
|
|
6128
|
+
|
|
6129
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6130
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6131
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6132
|
+
}
|
|
6133
|
+
|
|
6134
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6135
|
+
},
|
|
6136
|
+
|
|
6137
|
+
async serve(args, ctx) {
|
|
6138
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6139
|
+
return {
|
|
6140
|
+
code: 0,
|
|
6141
|
+
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',
|
|
6142
|
+
stderr: ''
|
|
6143
|
+
};
|
|
6144
|
+
}
|
|
6145
|
+
const rootArg = (() => {
|
|
6146
|
+
const positionals = [];
|
|
6147
|
+
for (let i = 0; i < args.length; i++) {
|
|
6148
|
+
const a = args[i];
|
|
6149
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6150
|
+
if (a.startsWith('-')) continue;
|
|
6151
|
+
positionals.push(a);
|
|
6152
|
+
}
|
|
6153
|
+
return positionals[0];
|
|
6154
|
+
})();
|
|
6155
|
+
let port = 3000;
|
|
6156
|
+
for (let i = 0; i < args.length; i++) {
|
|
6157
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6158
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6159
|
+
}
|
|
6160
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6161
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6162
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6163
|
+
}
|
|
6164
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6165
|
+
if (!entry) {
|
|
6166
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6167
|
+
}
|
|
6168
|
+
return {
|
|
6169
|
+
code: 0,
|
|
6170
|
+
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`,
|
|
6171
|
+
stderr: ''
|
|
6172
|
+
};
|
|
6173
|
+
},
|
|
6174
|
+
|
|
5589
6175
|
// -----------------------------------------------------------------------
|
|
5590
6176
|
// Port Table & HTTP Inspection: ports, curl
|
|
5591
6177
|
// -----------------------------------------------------------------------
|
|
@@ -6642,6 +7228,13 @@ function __initShellModule(root: any) {
|
|
|
6642
7228
|
Object.assign(context.env, this.env);
|
|
6643
7229
|
context.cwd = this.cwd;
|
|
6644
7230
|
}
|
|
7231
|
+
} else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
|
|
7232
|
+
// A native dev server (vite/ng/astro/…) typed directly. It cannot run in
|
|
7233
|
+
// this runtime — whether or not it was installed — so route it to the
|
|
7234
|
+
// built-in preview server rather than reporting a misleading "command
|
|
7235
|
+
// not found".
|
|
7236
|
+
const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
|
|
7237
|
+
res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
|
|
6645
7238
|
} else if (typeof this.options.onProcessSpawn === 'function') {
|
|
6646
7239
|
const spawned = await this.options.onProcessSpawn(cmdName, args, {
|
|
6647
7240
|
cwd: this.cwd,
|