@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.js
CHANGED
|
@@ -2371,9 +2371,40 @@
|
|
|
2371
2371
|
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2372
2372
|
}
|
|
2373
2373
|
|
|
2374
|
+
function pickConditionalEntry(value) {
|
|
2375
|
+
if (typeof value === 'string') return value;
|
|
2376
|
+
// `exports` subpaths may be an array of fallbacks, e.g.
|
|
2377
|
+
// `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
|
|
2378
|
+
if (Array.isArray(value)) {
|
|
2379
|
+
for (const item of value) {
|
|
2380
|
+
const picked = pickConditionalEntry(item);
|
|
2381
|
+
if (picked) return picked;
|
|
2382
|
+
}
|
|
2383
|
+
return null;
|
|
2384
|
+
}
|
|
2385
|
+
if (!value || typeof value !== 'object') return null;
|
|
2386
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2387
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2388
|
+
if (value[key] !== undefined) {
|
|
2389
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2390
|
+
if (picked) return picked;
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
return null;
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2374
2396
|
function resolveEntryRelPath(pkgJson) {
|
|
2375
|
-
let entry =
|
|
2376
|
-
|
|
2397
|
+
let entry = null;
|
|
2398
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2399
|
+
if (typeof exp === 'string') {
|
|
2400
|
+
entry = exp;
|
|
2401
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2402
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2403
|
+
}
|
|
2404
|
+
if (!entry) {
|
|
2405
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2406
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2407
|
+
}
|
|
2377
2408
|
entry = String(entry).replace(/^[./]+/, '');
|
|
2378
2409
|
return entry || 'index.js';
|
|
2379
2410
|
}
|
|
@@ -2384,9 +2415,16 @@
|
|
|
2384
2415
|
|
|
2385
2416
|
function extractRelativeSpecifiers(code) {
|
|
2386
2417
|
const out = new Set();
|
|
2387
|
-
const
|
|
2388
|
-
|
|
2389
|
-
|
|
2418
|
+
const patterns = [
|
|
2419
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2420
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2421
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2422
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2423
|
+
];
|
|
2424
|
+
for (const re of patterns) {
|
|
2425
|
+
let m;
|
|
2426
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2427
|
+
}
|
|
2390
2428
|
return Array.from(out);
|
|
2391
2429
|
}
|
|
2392
2430
|
|
|
@@ -2400,17 +2438,50 @@
|
|
|
2400
2438
|
return parts.join('/');
|
|
2401
2439
|
}
|
|
2402
2440
|
|
|
2441
|
+
// Small promise-based delay. Used only for CDN retry backoff; falls back to an
|
|
2442
|
+
// immediate resolve if `setTimeout` is unavailable in the host.
|
|
2443
|
+
function cdnBackoff(ms) {
|
|
2444
|
+
return new Promise((resolve) => {
|
|
2445
|
+
if (typeof setTimeout === 'function') setTimeout(resolve, ms);
|
|
2446
|
+
else resolve();
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2403
2450
|
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2451
|
+
// A single flaky jsDelivr response used to silently produce an *incomplete*
|
|
2452
|
+
// install (the module graph then failed at require-time). Retry transient
|
|
2453
|
+
// failures (network error, 429/408, 5xx) but treat 4xx as final.
|
|
2454
|
+
const maxAttempts = 3;
|
|
2455
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
2456
|
+
try {
|
|
2457
|
+
const res = await fetchImpl(url);
|
|
2458
|
+
if (!res) {
|
|
2459
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2460
|
+
return null;
|
|
2461
|
+
}
|
|
2462
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2463
|
+
if (!ok) {
|
|
2464
|
+
const transient = res.status >= 500 || res.status === 429 || res.status === 408;
|
|
2465
|
+
if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2466
|
+
return null;
|
|
2467
|
+
}
|
|
2468
|
+
// jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
|
|
2469
|
+
// and an HTML directory listing. Storing that as a module both corrupts the
|
|
2470
|
+
// package and later collides with the real directory (EISDIR).
|
|
2471
|
+
const contentType = (res.headers && typeof res.headers.get === 'function')
|
|
2472
|
+
? (res.headers.get('content-type') || '')
|
|
2473
|
+
: '';
|
|
2474
|
+
const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
|
|
2475
|
+
if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
|
|
2476
|
+
const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
|
|
2477
|
+
if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
|
|
2478
|
+
return text;
|
|
2479
|
+
} catch (_) {
|
|
2480
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
2481
|
+
return null;
|
|
2482
|
+
}
|
|
2413
2483
|
}
|
|
2484
|
+
return null;
|
|
2414
2485
|
}
|
|
2415
2486
|
|
|
2416
2487
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
@@ -2451,20 +2522,62 @@
|
|
|
2451
2522
|
const entry = resolveEntryRelPath(meta);
|
|
2452
2523
|
const files = [];
|
|
2453
2524
|
const visited = new Set();
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2525
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2526
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2527
|
+
// A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
|
|
2528
|
+
// resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
|
|
2529
|
+
// too or the package installs with only its manifest.
|
|
2530
|
+
const seed = [
|
|
2531
|
+
entry,
|
|
2532
|
+
`${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
|
|
2533
|
+
`${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
|
|
2534
|
+
];
|
|
2535
|
+
const expMap = meta.exports;
|
|
2536
|
+
if (expMap && typeof expMap === 'object') {
|
|
2537
|
+
// Seed *every* declared subpath. A low cap silently dropped the tail of
|
|
2538
|
+
// packages that list each file in `exports` (lit-html has 29 keys, so
|
|
2539
|
+
// `lit-html/is-server.js` was never fetched and `require` failed later).
|
|
2540
|
+
// Wildcard keys (`./*`) need no seeding — their files are reached through
|
|
2541
|
+
// the relative-require closure or fetched on demand.
|
|
2542
|
+
for (const key of Object.keys(expMap)) {
|
|
2543
|
+
if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
|
|
2544
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2545
|
+
if (target) seed.push(target);
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
let frontier = seed;
|
|
2549
|
+
while (frontier.length > 0) {
|
|
2550
|
+
const batch = [];
|
|
2551
|
+
for (const raw of frontier) {
|
|
2552
|
+
const rel = stripRelPath(raw);
|
|
2553
|
+
// Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
|
|
2554
|
+
// be fetched as files — that is what produced the EISDIR crash.
|
|
2555
|
+
if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
|
|
2556
|
+
visited.add(rel);
|
|
2557
|
+
batch.push(rel);
|
|
2558
|
+
}
|
|
2559
|
+
frontier = [];
|
|
2560
|
+
if (batch.length === 0) break;
|
|
2561
|
+
const texts = await Promise.all(
|
|
2562
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2563
|
+
);
|
|
2564
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2565
|
+
const rel = batch[idx];
|
|
2566
|
+
const text = texts[idx];
|
|
2567
|
+
if (text === null) continue;
|
|
2568
|
+
files.push({ rel, content: text });
|
|
2569
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2570
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2571
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2572
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2573
|
+
// candidates 404 harmlessly.
|
|
2574
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2575
|
+
? [target]
|
|
2576
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2577
|
+
for (const cand of cands) {
|
|
2578
|
+
const c = stripRelPath(cand);
|
|
2579
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2580
|
+
}
|
|
2468
2581
|
}
|
|
2469
2582
|
}
|
|
2470
2583
|
}
|
|
@@ -2474,7 +2587,30 @@
|
|
|
2474
2587
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2475
2588
|
}
|
|
2476
2589
|
|
|
2477
|
-
|
|
2590
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2591
|
+
// so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
|
|
2592
|
+
// preserved (not just the names) so transitives resolve to the version the
|
|
2593
|
+
// parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
|
|
2594
|
+
// needs color-convert. Resolving transitive names as "latest" silently breaks
|
|
2595
|
+
// the tree (ansi-styles@6 has no deps at all).
|
|
2596
|
+
const depSpecs = [];
|
|
2597
|
+
const depSeen = new Set();
|
|
2598
|
+
const declared = meta.dependencies || {};
|
|
2599
|
+
for (const depName of Object.keys(declared)) {
|
|
2600
|
+
if (depSeen.has(depName)) continue;
|
|
2601
|
+
depSeen.add(depName);
|
|
2602
|
+
depSpecs.push({ name: depName, range: declared[depName] || null });
|
|
2603
|
+
}
|
|
2604
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2605
|
+
const peers = meta.peerDependencies || {};
|
|
2606
|
+
for (const peer of Object.keys(peers)) {
|
|
2607
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2608
|
+
if (depSeen.has(peer)) continue;
|
|
2609
|
+
depSeen.add(peer);
|
|
2610
|
+
depSpecs.push({ name: peer, range: peers[peer] || null });
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2613
|
+
return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2478
2614
|
}
|
|
2479
2615
|
|
|
2480
2616
|
function installTargetDirs(ctx, name) {
|
|
@@ -2488,24 +2624,43 @@
|
|
|
2488
2624
|
for (const dir of dirs) {
|
|
2489
2625
|
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2490
2626
|
for (const f of info.files) {
|
|
2627
|
+
if (!f || !f.rel || f.rel.endsWith('/')) continue;
|
|
2491
2628
|
const full = PosixPath.join(dir, f.rel);
|
|
2629
|
+
// Never overwrite a directory with a file body (defensive: a stray
|
|
2630
|
+
// directory target would otherwise raise EISDIR).
|
|
2631
|
+
try {
|
|
2632
|
+
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
2633
|
+
} catch (_) {}
|
|
2492
2634
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2493
2635
|
ctx.vfs.writeFileSync(full, f.content);
|
|
2494
2636
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2495
2637
|
}
|
|
2496
2638
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2497
2639
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2640
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2641
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2642
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2643
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2644
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2645
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2646
|
+
}
|
|
2647
|
+
modPkg.exports = normalized;
|
|
2648
|
+
}
|
|
2498
2649
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2499
2650
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2500
2651
|
}
|
|
2501
2652
|
}
|
|
2502
2653
|
|
|
2503
|
-
async function installPackage(pkgSpec, ctx) {
|
|
2654
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2655
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2656
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2657
|
+
const isDev = Boolean(options.dev);
|
|
2504
2658
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2505
2659
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2506
2660
|
|
|
2507
2661
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2508
|
-
|
|
2662
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2663
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2509
2664
|
|
|
2510
2665
|
const fetchImpl = packageCtxFetch(ctx);
|
|
2511
2666
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -2531,28 +2686,90 @@
|
|
|
2531
2686
|
});
|
|
2532
2687
|
if (!warning) warning = info.reason;
|
|
2533
2688
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
2689
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2534
2690
|
continue;
|
|
2535
2691
|
}
|
|
2536
2692
|
|
|
2537
2693
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2538
2694
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2695
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2539
2696
|
if (item.direct) directVersion = info.version || null;
|
|
2540
2697
|
|
|
2541
2698
|
for (const dep of (info.deps || [])) {
|
|
2542
|
-
const
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2699
|
+
const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
|
|
2700
|
+
const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
|
|
2701
|
+
if (depName && !requested.has(depName)) {
|
|
2702
|
+
requested.add(depName);
|
|
2703
|
+
queue.push({ name: depName, range: depRange || null, direct: false });
|
|
2546
2704
|
}
|
|
2547
2705
|
}
|
|
2548
2706
|
}
|
|
2549
2707
|
|
|
2550
|
-
pkgData
|
|
2708
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2551
2709
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2552
2710
|
|
|
2553
2711
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2554
2712
|
}
|
|
2555
2713
|
|
|
2714
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2715
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2716
|
+
function createInstallEmitter(ctx, sink) {
|
|
2717
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2718
|
+
return function emit(text) {
|
|
2719
|
+
if (!text) return;
|
|
2720
|
+
sink.push(text);
|
|
2721
|
+
if (stream) stream(text);
|
|
2722
|
+
};
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
function formatInstallLine(info) {
|
|
2726
|
+
if (!info || !info.name) return '';
|
|
2727
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2728
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
function countInstalledPackages(results) {
|
|
2732
|
+
const seen = new Set();
|
|
2733
|
+
for (const r of results) {
|
|
2734
|
+
if (!r) continue;
|
|
2735
|
+
if (r.name) seen.add(r.name);
|
|
2736
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2737
|
+
}
|
|
2738
|
+
return seen.size;
|
|
2739
|
+
}
|
|
2740
|
+
|
|
2741
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2742
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2743
|
+
// "saved N package(s)".
|
|
2744
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2745
|
+
const options = opts || {};
|
|
2746
|
+
const manager = options.manager || 'bun';
|
|
2747
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2748
|
+
const out = [];
|
|
2749
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2750
|
+
const started = Date.now();
|
|
2751
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2752
|
+
const results = [];
|
|
2753
|
+
for (const p of pkgs) {
|
|
2754
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2755
|
+
}
|
|
2756
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2757
|
+
const count = countInstalledPackages(results);
|
|
2758
|
+
const ms = Date.now() - started;
|
|
2759
|
+
if (manager === 'npm') {
|
|
2760
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2761
|
+
} else if (manager === 'pnpm') {
|
|
2762
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2763
|
+
} else {
|
|
2764
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2765
|
+
}
|
|
2766
|
+
return {
|
|
2767
|
+
code: 0,
|
|
2768
|
+
stdout: out.join(''),
|
|
2769
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2770
|
+
};
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2556
2773
|
function uninstallPackage(pkgName, ctx) {
|
|
2557
2774
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2558
2775
|
let changed = false;
|
|
@@ -2604,9 +2821,269 @@
|
|
|
2604
2821
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2605
2822
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2606
2823
|
}
|
|
2824
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2825
|
+
if (fallback) return fallback;
|
|
2607
2826
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2608
2827
|
}
|
|
2609
2828
|
|
|
2829
|
+
// ---------------------------------------------------------------------------
|
|
2830
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2831
|
+
//
|
|
2832
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2833
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2834
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2835
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2836
|
+
// ---------------------------------------------------------------------------
|
|
2837
|
+
|
|
2838
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2839
|
+
|
|
2840
|
+
const PREVIEW_MIME = {
|
|
2841
|
+
'.html': 'text/html; charset=utf-8',
|
|
2842
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2843
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2844
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2845
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2846
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2847
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2848
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2849
|
+
'.css': 'text/css; charset=utf-8',
|
|
2850
|
+
'.json': 'application/json; charset=utf-8',
|
|
2851
|
+
'.map': 'application/json; charset=utf-8',
|
|
2852
|
+
'.svg': 'image/svg+xml',
|
|
2853
|
+
'.png': 'image/png',
|
|
2854
|
+
'.jpg': 'image/jpeg',
|
|
2855
|
+
'.jpeg': 'image/jpeg',
|
|
2856
|
+
'.gif': 'image/gif',
|
|
2857
|
+
'.webp': 'image/webp',
|
|
2858
|
+
'.ico': 'image/x-icon',
|
|
2859
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2860
|
+
};
|
|
2861
|
+
|
|
2862
|
+
function previewMimeFor(p) {
|
|
2863
|
+
const lower = String(p).toLowerCase();
|
|
2864
|
+
const dot = lower.lastIndexOf('.');
|
|
2865
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2866
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
function isPreviewScriptPath(p) {
|
|
2870
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2871
|
+
}
|
|
2872
|
+
|
|
2873
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2874
|
+
function extractBareSpecifiers(code) {
|
|
2875
|
+
const out = new Set();
|
|
2876
|
+
const patterns = [
|
|
2877
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2878
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2879
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2880
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2881
|
+
];
|
|
2882
|
+
for (const re of patterns) {
|
|
2883
|
+
let m;
|
|
2884
|
+
while ((m = re.exec(code)) !== null) {
|
|
2885
|
+
const spec = m[1];
|
|
2886
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2887
|
+
out.add(spec);
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
return Array.from(out);
|
|
2891
|
+
}
|
|
2892
|
+
|
|
2893
|
+
function normalizeVersionRange(range) {
|
|
2894
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2895
|
+
const v = range.trim();
|
|
2896
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2897
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2898
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2902
|
+
try {
|
|
2903
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2904
|
+
if (vfs.existsSync(modPkg)) {
|
|
2905
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2906
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2907
|
+
}
|
|
2908
|
+
} catch (_) {}
|
|
2909
|
+
try {
|
|
2910
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2911
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2912
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2913
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2914
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2915
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2916
|
+
}
|
|
2917
|
+
} catch (_) {}
|
|
2918
|
+
return 'latest';
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2922
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2923
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2924
|
+
return `${base}${sub}/+esm`;
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2928
|
+
const imports = {};
|
|
2929
|
+
for (const spec of specifiers) {
|
|
2930
|
+
const parts = String(spec).split('/');
|
|
2931
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2932
|
+
if (!pkgName) continue;
|
|
2933
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2934
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2935
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2936
|
+
}
|
|
2937
|
+
return imports;
|
|
2938
|
+
}
|
|
2939
|
+
|
|
2940
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2941
|
+
const scripts = [];
|
|
2942
|
+
const walk = (dir, depth) => {
|
|
2943
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2944
|
+
let entries = [];
|
|
2945
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2946
|
+
for (const name of entries) {
|
|
2947
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2948
|
+
const full = PosixPath.join(dir, name);
|
|
2949
|
+
let st;
|
|
2950
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2951
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2952
|
+
if (dirFlag) {
|
|
2953
|
+
walk(full, depth + 1);
|
|
2954
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2955
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
};
|
|
2959
|
+
walk(rootDir, 0);
|
|
2960
|
+
return scripts;
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
function injectPreviewExtras(html, importMap) {
|
|
2964
|
+
let out = html;
|
|
2965
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2966
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2967
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2968
|
+
} else {
|
|
2969
|
+
out = importMapTag + '\n' + out;
|
|
2970
|
+
}
|
|
2971
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2972
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2973
|
+
else out = out + '\n' + shim;
|
|
2974
|
+
return out;
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2978
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2979
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2980
|
+
|
|
2981
|
+
let port = Number(preferredPort) || 3000;
|
|
2982
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
2983
|
+
while (taken.has(port)) port++;
|
|
2984
|
+
|
|
2985
|
+
const specifiers = new Set();
|
|
2986
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
2987
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
2988
|
+
}
|
|
2989
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
2990
|
+
|
|
2991
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
2992
|
+
const isDir = (p) => {
|
|
2993
|
+
try {
|
|
2994
|
+
const st = ctx.vfs.statSync(p);
|
|
2995
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
2996
|
+
} catch (_) { return false; }
|
|
2997
|
+
};
|
|
2998
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
2999
|
+
|
|
3000
|
+
const handler = async (request) => {
|
|
3001
|
+
let pathname = '/';
|
|
3002
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
3003
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
3004
|
+
let target = PosixPath.join(rootDir, rel);
|
|
3005
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
3006
|
+
|
|
3007
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
3008
|
+
target = PosixPath.join(target, 'index.html');
|
|
3009
|
+
}
|
|
3010
|
+
if (!exists(target) && !hasExt) {
|
|
3011
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
3012
|
+
// the way a bundler / dev server would.
|
|
3013
|
+
const cands = [
|
|
3014
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
3015
|
+
target + '.mjs', target + '.cjs',
|
|
3016
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
3017
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
3018
|
+
];
|
|
3019
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
3020
|
+
}
|
|
3021
|
+
if (!exists(target) && !hasExt) {
|
|
3022
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
3023
|
+
}
|
|
3024
|
+
if (!exists(target)) {
|
|
3025
|
+
return new Response(
|
|
3026
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
3027
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
3028
|
+
);
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
let body = readText(target);
|
|
3032
|
+
if (body === null) body = '';
|
|
3033
|
+
if (/\.html?$/i.test(target)) {
|
|
3034
|
+
body = injectPreviewExtras(body, importMap);
|
|
3035
|
+
} else if (isPreviewScriptPath(target)) {
|
|
3036
|
+
try {
|
|
3037
|
+
const rm = getRuntimeModule();
|
|
3038
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3039
|
+
body = rm.transpileForBrowser(body, target);
|
|
3040
|
+
}
|
|
3041
|
+
} catch (_) {}
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
3045
|
+
};
|
|
3046
|
+
|
|
3047
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3048
|
+
return portTable.registerServer(port, {
|
|
3049
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
3050
|
+
fetch: handler,
|
|
3051
|
+
name: 'code-lab-serve',
|
|
3052
|
+
pid,
|
|
3053
|
+
root: rootDir
|
|
3054
|
+
});
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3058
|
+
// transparently redirected to the built-in preview server.
|
|
3059
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3060
|
+
// The same tools, when typed directly at the prompt (`ng serve`, `vite`).
|
|
3061
|
+
// `serve` is omitted: it is a first-class builtin shell command.
|
|
3062
|
+
const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
|
|
3063
|
+
|
|
3064
|
+
function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
|
|
3065
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3066
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3067
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3068
|
+
const force = Boolean(opts && opts.force);
|
|
3069
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3070
|
+
if (!force && ctx.vfs.existsSync(binPath)) return null;
|
|
3071
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3072
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3073
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3074
|
+
const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
|
|
3075
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
3076
|
+
if (!entry) return null;
|
|
3077
|
+
const note = force
|
|
3078
|
+
? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
|
|
3079
|
+
: `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
|
|
3080
|
+
return {
|
|
3081
|
+
code: 0,
|
|
3082
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
3083
|
+
stderr: ''
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
|
|
2610
3087
|
function evaluatePosixTest(args, ctx) {
|
|
2611
3088
|
const cleanArgs = [...args];
|
|
2612
3089
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -5105,7 +5582,8 @@
|
|
|
5105
5582
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
5106
5583
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
5107
5584
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
5108
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5585
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5586
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
5109
5587
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
5110
5588
|
return { code: 0, stdout, stderr: '' };
|
|
5111
5589
|
},
|
|
@@ -5290,26 +5768,25 @@
|
|
|
5290
5768
|
|
|
5291
5769
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5292
5770
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5771
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5293
5772
|
if (pkgs.length === 0) {
|
|
5294
5773
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5295
|
-
const deps = Object.keys(pkgData.dependencies || {});
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5299
|
-
return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
5774
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5775
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5776
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5300
5777
|
}
|
|
5301
|
-
|
|
5302
|
-
for (const p of pkgs) results.push(await installPackage(p, ctx));
|
|
5303
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5304
|
-
return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
5778
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5305
5779
|
}
|
|
5306
5780
|
|
|
5307
5781
|
if (sub === 'add') {
|
|
5308
|
-
|
|
5309
|
-
const
|
|
5310
|
-
|
|
5311
|
-
|
|
5312
|
-
|
|
5782
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5783
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5784
|
+
if (pkgs.length === 0) {
|
|
5785
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5786
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5787
|
+
}
|
|
5788
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5789
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5313
5790
|
}
|
|
5314
5791
|
|
|
5315
5792
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5469,22 +5946,14 @@
|
|
|
5469
5946
|
}
|
|
5470
5947
|
|
|
5471
5948
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5472
|
-
|
|
5949
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5950
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5473
5951
|
if (pkgs.length === 0) {
|
|
5474
5952
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5475
|
-
|
|
5476
|
-
|
|
5477
|
-
results.push(await installPackage(p, ctx));
|
|
5478
|
-
}
|
|
5479
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5480
|
-
return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
5481
|
-
}
|
|
5482
|
-
const results = [];
|
|
5483
|
-
for (const p of pkgs) {
|
|
5484
|
-
results.push(await installPackage(p, ctx));
|
|
5953
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5954
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5485
5955
|
}
|
|
5486
|
-
|
|
5487
|
-
return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
5956
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5488
5957
|
}
|
|
5489
5958
|
|
|
5490
5959
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5536,6 +6005,123 @@
|
|
|
5536
6005
|
return await this.npx(args, ctx);
|
|
5537
6006
|
},
|
|
5538
6007
|
|
|
6008
|
+
async pnpm(args, ctx) {
|
|
6009
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
6010
|
+
return {
|
|
6011
|
+
code: 0,
|
|
6012
|
+
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',
|
|
6013
|
+
stderr: ''
|
|
6014
|
+
};
|
|
6015
|
+
}
|
|
6016
|
+
const sub = args[0];
|
|
6017
|
+
if (sub === '--version' || sub === '-v') {
|
|
6018
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
6019
|
+
}
|
|
6020
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
6021
|
+
|
|
6022
|
+
if (sub === 'init') {
|
|
6023
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
6024
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
6025
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
6026
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
6027
|
+
version: '1.0.0',
|
|
6028
|
+
main: 'index.js',
|
|
6029
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
6030
|
+
}, null, 2) + '\n');
|
|
6031
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
6032
|
+
}
|
|
6033
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
6034
|
+
}
|
|
6035
|
+
|
|
6036
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
6037
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6038
|
+
if (pkgs.length === 0) {
|
|
6039
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6040
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6041
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
6042
|
+
}
|
|
6043
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
6044
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
6045
|
+
}
|
|
6046
|
+
|
|
6047
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
6048
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6049
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
6050
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
6051
|
+
}
|
|
6052
|
+
|
|
6053
|
+
if (sub === 'list' || sub === 'ls') {
|
|
6054
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
6055
|
+
}
|
|
6056
|
+
|
|
6057
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
6058
|
+
const scriptName = args[1];
|
|
6059
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
6060
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
6061
|
+
}
|
|
6062
|
+
|
|
6063
|
+
if (sub === 'test') {
|
|
6064
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6065
|
+
}
|
|
6066
|
+
|
|
6067
|
+
if (sub === 'exec') {
|
|
6068
|
+
const cmd = args[1];
|
|
6069
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6070
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6071
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6072
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6073
|
+
}
|
|
6074
|
+
|
|
6075
|
+
if (sub === 'dlx') {
|
|
6076
|
+
return await this.npx(args.slice(1), ctx);
|
|
6077
|
+
}
|
|
6078
|
+
|
|
6079
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6080
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6081
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6082
|
+
}
|
|
6083
|
+
|
|
6084
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6085
|
+
},
|
|
6086
|
+
|
|
6087
|
+
async serve(args, ctx) {
|
|
6088
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6089
|
+
return {
|
|
6090
|
+
code: 0,
|
|
6091
|
+
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',
|
|
6092
|
+
stderr: ''
|
|
6093
|
+
};
|
|
6094
|
+
}
|
|
6095
|
+
const rootArg = (() => {
|
|
6096
|
+
const positionals = [];
|
|
6097
|
+
for (let i = 0; i < args.length; i++) {
|
|
6098
|
+
const a = args[i];
|
|
6099
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6100
|
+
if (a.startsWith('-')) continue;
|
|
6101
|
+
positionals.push(a);
|
|
6102
|
+
}
|
|
6103
|
+
return positionals[0];
|
|
6104
|
+
})();
|
|
6105
|
+
let port = 3000;
|
|
6106
|
+
for (let i = 0; i < args.length; i++) {
|
|
6107
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6108
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6109
|
+
}
|
|
6110
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6111
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6112
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6113
|
+
}
|
|
6114
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6115
|
+
if (!entry) {
|
|
6116
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6117
|
+
}
|
|
6118
|
+
return {
|
|
6119
|
+
code: 0,
|
|
6120
|
+
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`,
|
|
6121
|
+
stderr: ''
|
|
6122
|
+
};
|
|
6123
|
+
},
|
|
6124
|
+
|
|
5539
6125
|
// -----------------------------------------------------------------------
|
|
5540
6126
|
// Port Table & HTTP Inspection: ports, curl
|
|
5541
6127
|
// -----------------------------------------------------------------------
|
|
@@ -6592,6 +7178,13 @@
|
|
|
6592
7178
|
Object.assign(context.env, this.env);
|
|
6593
7179
|
context.cwd = this.cwd;
|
|
6594
7180
|
}
|
|
7181
|
+
} else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
|
|
7182
|
+
// A native dev server (vite/ng/astro/…) typed directly. It cannot run in
|
|
7183
|
+
// this runtime — whether or not it was installed — so route it to the
|
|
7184
|
+
// built-in preview server rather than reporting a misleading "command
|
|
7185
|
+
// not found".
|
|
7186
|
+
const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
|
|
7187
|
+
res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
|
|
6595
7188
|
} else if (typeof this.options.onProcessSpawn === 'function') {
|
|
6596
7189
|
const spawned = await this.options.onProcessSpawn(cmdName, args, {
|
|
6597
7190
|
cwd: this.cwd,
|