@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/dist/shell.js
CHANGED
|
@@ -2390,9 +2390,40 @@
|
|
|
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
|
+
// `exports` subpaths may be an array of fallbacks, e.g.
|
|
2396
|
+
// `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
|
|
2397
|
+
if (Array.isArray(value)) {
|
|
2398
|
+
for (const item of value) {
|
|
2399
|
+
const picked = pickConditionalEntry(item);
|
|
2400
|
+
if (picked) return picked;
|
|
2401
|
+
}
|
|
2402
|
+
return null;
|
|
2403
|
+
}
|
|
2404
|
+
if (!value || typeof value !== 'object') return null;
|
|
2405
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2406
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2407
|
+
if (value[key] !== undefined) {
|
|
2408
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2409
|
+
if (picked) return picked;
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
return null;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2393
2415
|
function resolveEntryRelPath(pkgJson) {
|
|
2394
|
-
let entry =
|
|
2395
|
-
|
|
2416
|
+
let entry = null;
|
|
2417
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2418
|
+
if (typeof exp === 'string') {
|
|
2419
|
+
entry = exp;
|
|
2420
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2421
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2422
|
+
}
|
|
2423
|
+
if (!entry) {
|
|
2424
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2425
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2426
|
+
}
|
|
2396
2427
|
entry = String(entry).replace(/^[./]+/, '');
|
|
2397
2428
|
return entry || 'index.js';
|
|
2398
2429
|
}
|
|
@@ -2403,9 +2434,16 @@
|
|
|
2403
2434
|
|
|
2404
2435
|
function extractRelativeSpecifiers(code) {
|
|
2405
2436
|
const out = new Set();
|
|
2406
|
-
const
|
|
2407
|
-
|
|
2408
|
-
|
|
2437
|
+
const patterns = [
|
|
2438
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2439
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2440
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2441
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2442
|
+
];
|
|
2443
|
+
for (const re of patterns) {
|
|
2444
|
+
let m;
|
|
2445
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2446
|
+
}
|
|
2409
2447
|
return Array.from(out);
|
|
2410
2448
|
}
|
|
2411
2449
|
|
|
@@ -2419,17 +2457,50 @@
|
|
|
2419
2457
|
return parts.join('/');
|
|
2420
2458
|
}
|
|
2421
2459
|
|
|
2460
|
+
// Small promise-based delay. Used only for CDN retry backoff; falls back to an
|
|
2461
|
+
// immediate resolve if `setTimeout` is unavailable in the host.
|
|
2462
|
+
function cdnBackoff(ms) {
|
|
2463
|
+
return new Promise((resolve) => {
|
|
2464
|
+
if (typeof setTimeout === 'function') setTimeout(resolve, ms);
|
|
2465
|
+
else resolve();
|
|
2466
|
+
});
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2422
2469
|
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2470
|
+
// A single flaky jsDelivr response used to silently produce an *incomplete*
|
|
2471
|
+
// install (the module graph then failed at require-time). Retry transient
|
|
2472
|
+
// failures (network error, 429/408, 5xx) but treat 4xx as final.
|
|
2473
|
+
const maxAttempts = 3;
|
|
2474
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
2475
|
+
try {
|
|
2476
|
+
const res = await fetchImpl(url);
|
|
2477
|
+
if (!res) {
|
|
2478
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2479
|
+
return null;
|
|
2480
|
+
}
|
|
2481
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2482
|
+
if (!ok) {
|
|
2483
|
+
const transient = res.status >= 500 || res.status === 429 || res.status === 408;
|
|
2484
|
+
if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2485
|
+
return null;
|
|
2486
|
+
}
|
|
2487
|
+
// jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
|
|
2488
|
+
// and an HTML directory listing. Storing that as a module both corrupts the
|
|
2489
|
+
// package and later collides with the real directory (EISDIR).
|
|
2490
|
+
const contentType = (res.headers && typeof res.headers.get === 'function')
|
|
2491
|
+
? (res.headers.get('content-type') || '')
|
|
2492
|
+
: '';
|
|
2493
|
+
const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
|
|
2494
|
+
if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
|
|
2495
|
+
const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
|
|
2496
|
+
if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
|
|
2497
|
+
return text;
|
|
2498
|
+
} catch (_) {
|
|
2499
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2500
|
+
return null;
|
|
2501
|
+
}
|
|
2432
2502
|
}
|
|
2503
|
+
return null;
|
|
2433
2504
|
}
|
|
2434
2505
|
|
|
2435
2506
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
@@ -2470,20 +2541,62 @@
|
|
|
2470
2541
|
const entry = resolveEntryRelPath(meta);
|
|
2471
2542
|
const files = [];
|
|
2472
2543
|
const visited = new Set();
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2544
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2545
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2546
|
+
// A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
|
|
2547
|
+
// resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
|
|
2548
|
+
// too or the package installs with only its manifest.
|
|
2549
|
+
const seed = [
|
|
2550
|
+
entry,
|
|
2551
|
+
`${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
|
|
2552
|
+
`${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
|
|
2553
|
+
];
|
|
2554
|
+
const expMap = meta.exports;
|
|
2555
|
+
if (expMap && typeof expMap === 'object') {
|
|
2556
|
+
// Seed *every* declared subpath. A low cap silently dropped the tail of
|
|
2557
|
+
// packages that list each file in `exports` (lit-html has 29 keys, so
|
|
2558
|
+
// `lit-html/is-server.js` was never fetched and `require` failed later).
|
|
2559
|
+
// Wildcard keys (`./*`) need no seeding — their files are reached through
|
|
2560
|
+
// the relative-require closure or fetched on demand.
|
|
2561
|
+
for (const key of Object.keys(expMap)) {
|
|
2562
|
+
if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
|
|
2563
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2564
|
+
if (target) seed.push(target);
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
let frontier = seed;
|
|
2568
|
+
while (frontier.length > 0) {
|
|
2569
|
+
const batch = [];
|
|
2570
|
+
for (const raw of frontier) {
|
|
2571
|
+
const rel = stripRelPath(raw);
|
|
2572
|
+
// Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
|
|
2573
|
+
// be fetched as files — that is what produced the EISDIR crash.
|
|
2574
|
+
if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
|
|
2575
|
+
visited.add(rel);
|
|
2576
|
+
batch.push(rel);
|
|
2577
|
+
}
|
|
2578
|
+
frontier = [];
|
|
2579
|
+
if (batch.length === 0) break;
|
|
2580
|
+
const texts = await Promise.all(
|
|
2581
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2582
|
+
);
|
|
2583
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2584
|
+
const rel = batch[idx];
|
|
2585
|
+
const text = texts[idx];
|
|
2586
|
+
if (text === null) continue;
|
|
2587
|
+
files.push({ rel, content: text });
|
|
2588
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2589
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2590
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2591
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2592
|
+
// candidates 404 harmlessly.
|
|
2593
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2594
|
+
? [target]
|
|
2595
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2596
|
+
for (const cand of cands) {
|
|
2597
|
+
const c = stripRelPath(cand);
|
|
2598
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2599
|
+
}
|
|
2487
2600
|
}
|
|
2488
2601
|
}
|
|
2489
2602
|
}
|
|
@@ -2493,7 +2606,30 @@
|
|
|
2493
2606
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2494
2607
|
}
|
|
2495
2608
|
|
|
2496
|
-
|
|
2609
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2610
|
+
// so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
|
|
2611
|
+
// preserved (not just the names) so transitives resolve to the version the
|
|
2612
|
+
// parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
|
|
2613
|
+
// needs color-convert. Resolving transitive names as "latest" silently breaks
|
|
2614
|
+
// the tree (ansi-styles@6 has no deps at all).
|
|
2615
|
+
const depSpecs = [];
|
|
2616
|
+
const depSeen = new Set();
|
|
2617
|
+
const declared = meta.dependencies || {};
|
|
2618
|
+
for (const depName of Object.keys(declared)) {
|
|
2619
|
+
if (depSeen.has(depName)) continue;
|
|
2620
|
+
depSeen.add(depName);
|
|
2621
|
+
depSpecs.push({ name: depName, range: declared[depName] || null });
|
|
2622
|
+
}
|
|
2623
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2624
|
+
const peers = meta.peerDependencies || {};
|
|
2625
|
+
for (const peer of Object.keys(peers)) {
|
|
2626
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2627
|
+
if (depSeen.has(peer)) continue;
|
|
2628
|
+
depSeen.add(peer);
|
|
2629
|
+
depSpecs.push({ name: peer, range: peers[peer] || null });
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2497
2633
|
}
|
|
2498
2634
|
|
|
2499
2635
|
function installTargetDirs(ctx, name) {
|
|
@@ -2507,24 +2643,43 @@
|
|
|
2507
2643
|
for (const dir of dirs) {
|
|
2508
2644
|
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2509
2645
|
for (const f of info.files) {
|
|
2646
|
+
if (!f || !f.rel || f.rel.endsWith('/')) continue;
|
|
2510
2647
|
const full = PosixPath.join(dir, f.rel);
|
|
2648
|
+
// Never overwrite a directory with a file body (defensive: a stray
|
|
2649
|
+
// directory target would otherwise raise EISDIR).
|
|
2650
|
+
try {
|
|
2651
|
+
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
2652
|
+
} catch (_) {}
|
|
2511
2653
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2512
2654
|
ctx.vfs.writeFileSync(full, f.content);
|
|
2513
2655
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2514
2656
|
}
|
|
2515
2657
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2516
2658
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2659
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2660
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2661
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2662
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2663
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2664
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2665
|
+
}
|
|
2666
|
+
modPkg.exports = normalized;
|
|
2667
|
+
}
|
|
2517
2668
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2518
2669
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2519
2670
|
}
|
|
2520
2671
|
}
|
|
2521
2672
|
|
|
2522
|
-
async function installPackage(pkgSpec, ctx) {
|
|
2673
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2674
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2675
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2676
|
+
const isDev = Boolean(options.dev);
|
|
2523
2677
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2524
2678
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2525
2679
|
|
|
2526
2680
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2527
|
-
|
|
2681
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2682
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2528
2683
|
|
|
2529
2684
|
const fetchImpl = packageCtxFetch(ctx);
|
|
2530
2685
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -2550,28 +2705,90 @@
|
|
|
2550
2705
|
});
|
|
2551
2706
|
if (!warning) warning = info.reason;
|
|
2552
2707
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
2708
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2553
2709
|
continue;
|
|
2554
2710
|
}
|
|
2555
2711
|
|
|
2556
2712
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2557
2713
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2714
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2558
2715
|
if (item.direct) directVersion = info.version || null;
|
|
2559
2716
|
|
|
2560
2717
|
for (const dep of (info.deps || [])) {
|
|
2561
|
-
const
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2718
|
+
const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
|
|
2719
|
+
const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
|
|
2720
|
+
if (depName && !requested.has(depName)) {
|
|
2721
|
+
requested.add(depName);
|
|
2722
|
+
queue.push({ name: depName, range: depRange || null, direct: false });
|
|
2565
2723
|
}
|
|
2566
2724
|
}
|
|
2567
2725
|
}
|
|
2568
2726
|
|
|
2569
|
-
pkgData
|
|
2727
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2570
2728
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2571
2729
|
|
|
2572
2730
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2573
2731
|
}
|
|
2574
2732
|
|
|
2733
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2734
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2735
|
+
function createInstallEmitter(ctx, sink) {
|
|
2736
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2737
|
+
return function emit(text) {
|
|
2738
|
+
if (!text) return;
|
|
2739
|
+
sink.push(text);
|
|
2740
|
+
if (stream) stream(text);
|
|
2741
|
+
};
|
|
2742
|
+
}
|
|
2743
|
+
|
|
2744
|
+
function formatInstallLine(info) {
|
|
2745
|
+
if (!info || !info.name) return '';
|
|
2746
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2747
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
function countInstalledPackages(results) {
|
|
2751
|
+
const seen = new Set();
|
|
2752
|
+
for (const r of results) {
|
|
2753
|
+
if (!r) continue;
|
|
2754
|
+
if (r.name) seen.add(r.name);
|
|
2755
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2756
|
+
}
|
|
2757
|
+
return seen.size;
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2761
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2762
|
+
// "saved N package(s)".
|
|
2763
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2764
|
+
const options = opts || {};
|
|
2765
|
+
const manager = options.manager || 'bun';
|
|
2766
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2767
|
+
const out = [];
|
|
2768
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2769
|
+
const started = Date.now();
|
|
2770
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2771
|
+
const results = [];
|
|
2772
|
+
for (const p of pkgs) {
|
|
2773
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2774
|
+
}
|
|
2775
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2776
|
+
const count = countInstalledPackages(results);
|
|
2777
|
+
const ms = Date.now() - started;
|
|
2778
|
+
if (manager === 'npm') {
|
|
2779
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2780
|
+
} else if (manager === 'pnpm') {
|
|
2781
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2782
|
+
} else {
|
|
2783
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2784
|
+
}
|
|
2785
|
+
return {
|
|
2786
|
+
code: 0,
|
|
2787
|
+
stdout: out.join(''),
|
|
2788
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2575
2792
|
function uninstallPackage(pkgName, ctx) {
|
|
2576
2793
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2577
2794
|
let changed = false;
|
|
@@ -2623,9 +2840,269 @@
|
|
|
2623
2840
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2624
2841
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2625
2842
|
}
|
|
2843
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2844
|
+
if (fallback) return fallback;
|
|
2626
2845
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2627
2846
|
}
|
|
2628
2847
|
|
|
2848
|
+
// ---------------------------------------------------------------------------
|
|
2849
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2850
|
+
//
|
|
2851
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2852
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2853
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2854
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2855
|
+
// ---------------------------------------------------------------------------
|
|
2856
|
+
|
|
2857
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2858
|
+
|
|
2859
|
+
const PREVIEW_MIME = {
|
|
2860
|
+
'.html': 'text/html; charset=utf-8',
|
|
2861
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2862
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2863
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2864
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2865
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2866
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2867
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2868
|
+
'.css': 'text/css; charset=utf-8',
|
|
2869
|
+
'.json': 'application/json; charset=utf-8',
|
|
2870
|
+
'.map': 'application/json; charset=utf-8',
|
|
2871
|
+
'.svg': 'image/svg+xml',
|
|
2872
|
+
'.png': 'image/png',
|
|
2873
|
+
'.jpg': 'image/jpeg',
|
|
2874
|
+
'.jpeg': 'image/jpeg',
|
|
2875
|
+
'.gif': 'image/gif',
|
|
2876
|
+
'.webp': 'image/webp',
|
|
2877
|
+
'.ico': 'image/x-icon',
|
|
2878
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2879
|
+
};
|
|
2880
|
+
|
|
2881
|
+
function previewMimeFor(p) {
|
|
2882
|
+
const lower = String(p).toLowerCase();
|
|
2883
|
+
const dot = lower.lastIndexOf('.');
|
|
2884
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2885
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
function isPreviewScriptPath(p) {
|
|
2889
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2890
|
+
}
|
|
2891
|
+
|
|
2892
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2893
|
+
function extractBareSpecifiers(code) {
|
|
2894
|
+
const out = new Set();
|
|
2895
|
+
const patterns = [
|
|
2896
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2897
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2898
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2899
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2900
|
+
];
|
|
2901
|
+
for (const re of patterns) {
|
|
2902
|
+
let m;
|
|
2903
|
+
while ((m = re.exec(code)) !== null) {
|
|
2904
|
+
const spec = m[1];
|
|
2905
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2906
|
+
out.add(spec);
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
return Array.from(out);
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
function normalizeVersionRange(range) {
|
|
2913
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2914
|
+
const v = range.trim();
|
|
2915
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2916
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2917
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2921
|
+
try {
|
|
2922
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2923
|
+
if (vfs.existsSync(modPkg)) {
|
|
2924
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2925
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2926
|
+
}
|
|
2927
|
+
} catch (_) {}
|
|
2928
|
+
try {
|
|
2929
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2930
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2931
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2932
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2933
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2934
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2935
|
+
}
|
|
2936
|
+
} catch (_) {}
|
|
2937
|
+
return 'latest';
|
|
2938
|
+
}
|
|
2939
|
+
|
|
2940
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2941
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2942
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2943
|
+
return `${base}${sub}/+esm`;
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2947
|
+
const imports = {};
|
|
2948
|
+
for (const spec of specifiers) {
|
|
2949
|
+
const parts = String(spec).split('/');
|
|
2950
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2951
|
+
if (!pkgName) continue;
|
|
2952
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2953
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2954
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2955
|
+
}
|
|
2956
|
+
return imports;
|
|
2957
|
+
}
|
|
2958
|
+
|
|
2959
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2960
|
+
const scripts = [];
|
|
2961
|
+
const walk = (dir, depth) => {
|
|
2962
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2963
|
+
let entries = [];
|
|
2964
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2965
|
+
for (const name of entries) {
|
|
2966
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2967
|
+
const full = PosixPath.join(dir, name);
|
|
2968
|
+
let st;
|
|
2969
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2970
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2971
|
+
if (dirFlag) {
|
|
2972
|
+
walk(full, depth + 1);
|
|
2973
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2974
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
};
|
|
2978
|
+
walk(rootDir, 0);
|
|
2979
|
+
return scripts;
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
function injectPreviewExtras(html, importMap) {
|
|
2983
|
+
let out = html;
|
|
2984
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2985
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2986
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2987
|
+
} else {
|
|
2988
|
+
out = importMapTag + '\n' + out;
|
|
2989
|
+
}
|
|
2990
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2991
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2992
|
+
else out = out + '\n' + shim;
|
|
2993
|
+
return out;
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2997
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2998
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2999
|
+
|
|
3000
|
+
let port = Number(preferredPort) || 3000;
|
|
3001
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
3002
|
+
while (taken.has(port)) port++;
|
|
3003
|
+
|
|
3004
|
+
const specifiers = new Set();
|
|
3005
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
3006
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
3007
|
+
}
|
|
3008
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
3009
|
+
|
|
3010
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
3011
|
+
const isDir = (p) => {
|
|
3012
|
+
try {
|
|
3013
|
+
const st = ctx.vfs.statSync(p);
|
|
3014
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
3015
|
+
} catch (_) { return false; }
|
|
3016
|
+
};
|
|
3017
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
3018
|
+
|
|
3019
|
+
const handler = async (request) => {
|
|
3020
|
+
let pathname = '/';
|
|
3021
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
3022
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
3023
|
+
let target = PosixPath.join(rootDir, rel);
|
|
3024
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
3025
|
+
|
|
3026
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
3027
|
+
target = PosixPath.join(target, 'index.html');
|
|
3028
|
+
}
|
|
3029
|
+
if (!exists(target) && !hasExt) {
|
|
3030
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
3031
|
+
// the way a bundler / dev server would.
|
|
3032
|
+
const cands = [
|
|
3033
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
3034
|
+
target + '.mjs', target + '.cjs',
|
|
3035
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
3036
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
3037
|
+
];
|
|
3038
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
3039
|
+
}
|
|
3040
|
+
if (!exists(target) && !hasExt) {
|
|
3041
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
3042
|
+
}
|
|
3043
|
+
if (!exists(target)) {
|
|
3044
|
+
return new Response(
|
|
3045
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
3046
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
3047
|
+
);
|
|
3048
|
+
}
|
|
3049
|
+
|
|
3050
|
+
let body = readText(target);
|
|
3051
|
+
if (body === null) body = '';
|
|
3052
|
+
if (/\.html?$/i.test(target)) {
|
|
3053
|
+
body = injectPreviewExtras(body, importMap);
|
|
3054
|
+
} else if (isPreviewScriptPath(target)) {
|
|
3055
|
+
try {
|
|
3056
|
+
const rm = getRuntimeModule();
|
|
3057
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3058
|
+
body = rm.transpileForBrowser(body, target);
|
|
3059
|
+
}
|
|
3060
|
+
} catch (_) {}
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
3064
|
+
};
|
|
3065
|
+
|
|
3066
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3067
|
+
return portTable.registerServer(port, {
|
|
3068
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
3069
|
+
fetch: handler,
|
|
3070
|
+
name: 'code-lab-serve',
|
|
3071
|
+
pid,
|
|
3072
|
+
root: rootDir
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
3075
|
+
|
|
3076
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3077
|
+
// transparently redirected to the built-in preview server.
|
|
3078
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3079
|
+
// The same tools, when typed directly at the prompt (`ng serve`, `vite`).
|
|
3080
|
+
// `serve` is omitted: it is a first-class builtin shell command.
|
|
3081
|
+
const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
|
|
3082
|
+
|
|
3083
|
+
function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
|
|
3084
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3085
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3086
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3087
|
+
const force = Boolean(opts && opts.force);
|
|
3088
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3089
|
+
if (!force && ctx.vfs.existsSync(binPath)) return null;
|
|
3090
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3091
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3092
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3093
|
+
const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
|
|
3094
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
3095
|
+
if (!entry) return null;
|
|
3096
|
+
const note = force
|
|
3097
|
+
? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
|
|
3098
|
+
: `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
|
|
3099
|
+
return {
|
|
3100
|
+
code: 0,
|
|
3101
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
3102
|
+
stderr: ''
|
|
3103
|
+
};
|
|
3104
|
+
}
|
|
3105
|
+
|
|
2629
3106
|
function evaluatePosixTest(args, ctx) {
|
|
2630
3107
|
const cleanArgs = [...args];
|
|
2631
3108
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -5124,7 +5601,8 @@
|
|
|
5124
5601
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
5125
5602
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
5126
5603
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
5127
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5604
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5605
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
5128
5606
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
5129
5607
|
return { code: 0, stdout, stderr: '' };
|
|
5130
5608
|
},
|
|
@@ -5309,26 +5787,25 @@
|
|
|
5309
5787
|
|
|
5310
5788
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5311
5789
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5790
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5312
5791
|
if (pkgs.length === 0) {
|
|
5313
5792
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5314
|
-
const deps = Object.keys(pkgData.dependencies || {});
|
|
5315
|
-
|
|
5316
|
-
|
|
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` : '' };
|
|
5793
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5794
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5795
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5319
5796
|
}
|
|
5320
|
-
|
|
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` : '' };
|
|
5797
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5324
5798
|
}
|
|
5325
5799
|
|
|
5326
5800
|
if (sub === 'add') {
|
|
5327
|
-
|
|
5328
|
-
const
|
|
5329
|
-
|
|
5330
|
-
|
|
5331
|
-
|
|
5801
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5802
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5803
|
+
if (pkgs.length === 0) {
|
|
5804
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5805
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5806
|
+
}
|
|
5807
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5808
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5332
5809
|
}
|
|
5333
5810
|
|
|
5334
5811
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5488,22 +5965,14 @@
|
|
|
5488
5965
|
}
|
|
5489
5966
|
|
|
5490
5967
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5491
|
-
|
|
5968
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5969
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5492
5970
|
if (pkgs.length === 0) {
|
|
5493
5971
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5494
|
-
|
|
5495
|
-
|
|
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` : '' };
|
|
5500
|
-
}
|
|
5501
|
-
const results = [];
|
|
5502
|
-
for (const p of pkgs) {
|
|
5503
|
-
results.push(await installPackage(p, ctx));
|
|
5972
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5973
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5504
5974
|
}
|
|
5505
|
-
|
|
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` : '' };
|
|
5975
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5507
5976
|
}
|
|
5508
5977
|
|
|
5509
5978
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5555,6 +6024,123 @@
|
|
|
5555
6024
|
return await this.npx(args, ctx);
|
|
5556
6025
|
},
|
|
5557
6026
|
|
|
6027
|
+
async pnpm(args, ctx) {
|
|
6028
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
6029
|
+
return {
|
|
6030
|
+
code: 0,
|
|
6031
|
+
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',
|
|
6032
|
+
stderr: ''
|
|
6033
|
+
};
|
|
6034
|
+
}
|
|
6035
|
+
const sub = args[0];
|
|
6036
|
+
if (sub === '--version' || sub === '-v') {
|
|
6037
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
6038
|
+
}
|
|
6039
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
6040
|
+
|
|
6041
|
+
if (sub === 'init') {
|
|
6042
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
6043
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
6044
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
6045
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
6046
|
+
version: '1.0.0',
|
|
6047
|
+
main: 'index.js',
|
|
6048
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
6049
|
+
}, null, 2) + '\n');
|
|
6050
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
6051
|
+
}
|
|
6052
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
6053
|
+
}
|
|
6054
|
+
|
|
6055
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
6056
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6057
|
+
if (pkgs.length === 0) {
|
|
6058
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6059
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6060
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
6061
|
+
}
|
|
6062
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
6063
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
6064
|
+
}
|
|
6065
|
+
|
|
6066
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
6067
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6068
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
6069
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
6070
|
+
}
|
|
6071
|
+
|
|
6072
|
+
if (sub === 'list' || sub === 'ls') {
|
|
6073
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
6074
|
+
}
|
|
6075
|
+
|
|
6076
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
6077
|
+
const scriptName = args[1];
|
|
6078
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
6079
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
6080
|
+
}
|
|
6081
|
+
|
|
6082
|
+
if (sub === 'test') {
|
|
6083
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6084
|
+
}
|
|
6085
|
+
|
|
6086
|
+
if (sub === 'exec') {
|
|
6087
|
+
const cmd = args[1];
|
|
6088
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6089
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6090
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6091
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6092
|
+
}
|
|
6093
|
+
|
|
6094
|
+
if (sub === 'dlx') {
|
|
6095
|
+
return await this.npx(args.slice(1), ctx);
|
|
6096
|
+
}
|
|
6097
|
+
|
|
6098
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6099
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6100
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6101
|
+
}
|
|
6102
|
+
|
|
6103
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6104
|
+
},
|
|
6105
|
+
|
|
6106
|
+
async serve(args, ctx) {
|
|
6107
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6108
|
+
return {
|
|
6109
|
+
code: 0,
|
|
6110
|
+
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',
|
|
6111
|
+
stderr: ''
|
|
6112
|
+
};
|
|
6113
|
+
}
|
|
6114
|
+
const rootArg = (() => {
|
|
6115
|
+
const positionals = [];
|
|
6116
|
+
for (let i = 0; i < args.length; i++) {
|
|
6117
|
+
const a = args[i];
|
|
6118
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6119
|
+
if (a.startsWith('-')) continue;
|
|
6120
|
+
positionals.push(a);
|
|
6121
|
+
}
|
|
6122
|
+
return positionals[0];
|
|
6123
|
+
})();
|
|
6124
|
+
let port = 3000;
|
|
6125
|
+
for (let i = 0; i < args.length; i++) {
|
|
6126
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6127
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6128
|
+
}
|
|
6129
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6130
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6131
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6132
|
+
}
|
|
6133
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6134
|
+
if (!entry) {
|
|
6135
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6136
|
+
}
|
|
6137
|
+
return {
|
|
6138
|
+
code: 0,
|
|
6139
|
+
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`,
|
|
6140
|
+
stderr: ''
|
|
6141
|
+
};
|
|
6142
|
+
},
|
|
6143
|
+
|
|
5558
6144
|
// -----------------------------------------------------------------------
|
|
5559
6145
|
// Port Table & HTTP Inspection: ports, curl
|
|
5560
6146
|
// -----------------------------------------------------------------------
|
|
@@ -6611,6 +7197,13 @@
|
|
|
6611
7197
|
Object.assign(context.env, this.env);
|
|
6612
7198
|
context.cwd = this.cwd;
|
|
6613
7199
|
}
|
|
7200
|
+
} else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
|
|
7201
|
+
// A native dev server (vite/ng/astro/…) typed directly. It cannot run in
|
|
7202
|
+
// this runtime — whether or not it was installed — so route it to the
|
|
7203
|
+
// built-in preview server rather than reporting a misleading "command
|
|
7204
|
+
// not found".
|
|
7205
|
+
const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
|
|
7206
|
+
res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
|
|
6614
7207
|
} else if (typeof this.options.onProcessSpawn === 'function') {
|
|
6615
7208
|
const spawned = await this.options.onProcessSpawn(cmdName, args, {
|
|
6616
7209
|
cwd: this.cwd,
|