@innovatorved/code-lab 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +2 -1
- package/README.md +4 -2
- package/dist/code-lab.css +49 -0
- package/dist/code-lab.d.ts +2 -1
- package/dist/code-lab.esm.js +1227 -67
- package/dist/code-lab.js +1227 -67
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.esm.js +377 -21
- package/dist/runtime.js +377 -21
- package/dist/shell.esm.js +766 -39
- package/dist/shell.js +766 -39
- package/package.json +6 -2
- package/src/code-lab.css +49 -0
- package/src/runtime.js +377 -21
- package/src/runtime.ts +382 -22
- package/src/shell.js +766 -39
- package/src/shell.ts +766 -39
- package/src/workbench.js +84 -7
- package/src/workbench.ts +84 -7
package/src/shell.js
CHANGED
|
@@ -2336,38 +2336,362 @@
|
|
|
2336
2336
|
} catch (_) {}
|
|
2337
2337
|
}
|
|
2338
2338
|
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2339
|
+
// ---------------------------------------------------------------------------
|
|
2340
|
+
// Real npm package installation via the jsDelivr CDN
|
|
2341
|
+
// ---------------------------------------------------------------------------
|
|
2342
|
+
const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2343
|
+
|
|
2344
|
+
// Minimal offline registry, used only when the CDN is unreachable so common
|
|
2345
|
+
// demos still resolve without network access.
|
|
2346
|
+
const OFFLINE_PACKAGE_FALLBACKS = {
|
|
2347
|
+
'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
|
|
2348
|
+
'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
|
|
2349
|
+
'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
|
|
2350
|
+
'left-pad': 'module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };\n'
|
|
2351
|
+
};
|
|
2343
2352
|
|
|
2344
|
-
|
|
2345
|
-
if (
|
|
2346
|
-
|
|
2347
|
-
|
|
2353
|
+
function packageCtxFetch(ctx) {
|
|
2354
|
+
if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
|
|
2355
|
+
return ctx.shell.options.fetchImpl;
|
|
2356
|
+
}
|
|
2357
|
+
if (typeof fetch === 'function') return fetch.bind(globalThis);
|
|
2358
|
+
return null;
|
|
2359
|
+
}
|
|
2348
2360
|
|
|
2349
|
-
|
|
2350
|
-
const
|
|
2351
|
-
if (!
|
|
2361
|
+
function parsePackageSpec(spec) {
|
|
2362
|
+
const raw = String(spec || '').trim();
|
|
2363
|
+
if (!raw) return { name: '', range: null };
|
|
2364
|
+
if (raw.startsWith('@')) {
|
|
2365
|
+
const at = raw.indexOf('@', 1);
|
|
2366
|
+
if (at === -1) return { name: raw, range: null };
|
|
2367
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2368
|
+
}
|
|
2369
|
+
const at = raw.indexOf('@');
|
|
2370
|
+
if (at <= 0) return { name: raw, range: null };
|
|
2371
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2372
|
+
}
|
|
2352
2373
|
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2374
|
+
function pickConditionalEntry(value) {
|
|
2375
|
+
if (typeof value === 'string') return value;
|
|
2376
|
+
if (!value || typeof value !== 'object') return null;
|
|
2377
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2378
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2379
|
+
if (value[key] !== undefined) {
|
|
2380
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2381
|
+
if (picked) return picked;
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
return null;
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
function resolveEntryRelPath(pkgJson) {
|
|
2388
|
+
let entry = null;
|
|
2389
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2390
|
+
if (typeof exp === 'string') {
|
|
2391
|
+
entry = exp;
|
|
2392
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2393
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2394
|
+
}
|
|
2395
|
+
if (!entry) {
|
|
2396
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2397
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2398
|
+
}
|
|
2399
|
+
entry = String(entry).replace(/^[./]+/, '');
|
|
2400
|
+
return entry || 'index.js';
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
function stripRelPath(rel) {
|
|
2404
|
+
return String(rel || '').replace(/^[./]+/, '');
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
function extractRelativeSpecifiers(code) {
|
|
2408
|
+
const out = new Set();
|
|
2409
|
+
const patterns = [
|
|
2410
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2411
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2412
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2413
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2414
|
+
];
|
|
2415
|
+
for (const re of patterns) {
|
|
2416
|
+
let m;
|
|
2417
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2418
|
+
}
|
|
2419
|
+
return Array.from(out);
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
function normalizeRelPath(baseDir, rel) {
|
|
2423
|
+
const parts = String(baseDir || '').split('/').filter(Boolean);
|
|
2424
|
+
for (const seg of String(rel).split('/')) {
|
|
2425
|
+
if (!seg || seg === '.') continue;
|
|
2426
|
+
if (seg === '..') parts.pop();
|
|
2427
|
+
else parts.push(seg);
|
|
2428
|
+
}
|
|
2429
|
+
return parts.join('/');
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2433
|
+
try {
|
|
2434
|
+
const res = await fetchImpl(url);
|
|
2435
|
+
if (!res) return null;
|
|
2436
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2437
|
+
if (!ok) return null;
|
|
2438
|
+
if (typeof res.text === 'function') return await res.text();
|
|
2439
|
+
return String(res.body != null ? res.body : '');
|
|
2440
|
+
} catch (_) {
|
|
2441
|
+
return null;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
2446
|
+
const urls = range
|
|
2447
|
+
? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
|
|
2448
|
+
: [`${CDN_NPM_BASE}/${name}/package.json`];
|
|
2449
|
+
for (const url of urls) {
|
|
2450
|
+
const text = await fetchTextFromCdn(fetchImpl, url);
|
|
2451
|
+
if (!text) continue;
|
|
2452
|
+
try {
|
|
2453
|
+
const parsed = JSON.parse(text);
|
|
2454
|
+
if (parsed && parsed.version) return parsed;
|
|
2455
|
+
} catch (_) {}
|
|
2456
|
+
}
|
|
2457
|
+
return null;
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
// Download a package's entry module, its relative submodules and record its
|
|
2461
|
+
// declared dependencies so the caller can resolve them transitively.
|
|
2462
|
+
async function downloadPackageFiles(fetchImpl, name, range, seen) {
|
|
2463
|
+
const meta = await resolvePackageMetadata(fetchImpl, name, range);
|
|
2464
|
+
if (!meta) {
|
|
2465
|
+
const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
|
|
2466
|
+
if (fallback) {
|
|
2467
|
+
const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
|
|
2468
|
+
return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
|
|
2469
|
+
}
|
|
2470
|
+
return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
|
|
2471
|
+
}
|
|
2472
|
+
|
|
2473
|
+
const version = meta.version;
|
|
2474
|
+
const key = `${name}@${version}`;
|
|
2475
|
+
if (seen.has(key)) {
|
|
2476
|
+
return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
|
|
2477
|
+
}
|
|
2478
|
+
seen.add(key);
|
|
2479
|
+
|
|
2480
|
+
const entry = resolveEntryRelPath(meta);
|
|
2481
|
+
const files = [];
|
|
2482
|
+
const visited = new Set();
|
|
2483
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2484
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2485
|
+
const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
|
|
2486
|
+
const expMap = meta.exports;
|
|
2487
|
+
if (expMap && typeof expMap === 'object') {
|
|
2488
|
+
let subCount = 0;
|
|
2489
|
+
for (const key of Object.keys(expMap)) {
|
|
2490
|
+
if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
|
|
2491
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2492
|
+
if (target) { seed.push(target); subCount++; }
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
let frontier = seed;
|
|
2496
|
+
while (frontier.length > 0) {
|
|
2497
|
+
const batch = [];
|
|
2498
|
+
for (const raw of frontier) {
|
|
2499
|
+
const rel = stripRelPath(raw);
|
|
2500
|
+
if (!rel || visited.has(rel)) continue;
|
|
2501
|
+
visited.add(rel);
|
|
2502
|
+
batch.push(rel);
|
|
2503
|
+
}
|
|
2504
|
+
frontier = [];
|
|
2505
|
+
if (batch.length === 0) break;
|
|
2506
|
+
const texts = await Promise.all(
|
|
2507
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2508
|
+
);
|
|
2509
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2510
|
+
const rel = batch[idx];
|
|
2511
|
+
const text = texts[idx];
|
|
2512
|
+
if (text === null) continue;
|
|
2513
|
+
files.push({ rel, content: text });
|
|
2514
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2515
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2516
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2517
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2518
|
+
// candidates 404 harmlessly.
|
|
2519
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2520
|
+
? [target]
|
|
2521
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2522
|
+
for (const cand of cands) {
|
|
2523
|
+
const c = stripRelPath(cand);
|
|
2524
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
// The declared entry may be missing on the CDN; fall back to index.js.
|
|
2530
|
+
if (!files.some(f => f.rel === entry)) {
|
|
2531
|
+
const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
|
|
2532
|
+
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2536
|
+
// so e.g. `npm install react-dom` also pulls in `react`.
|
|
2537
|
+
const depNames = Object.keys(meta.dependencies || {});
|
|
2538
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2539
|
+
for (const peer of Object.keys(meta.peerDependencies || {})) {
|
|
2540
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2541
|
+
if (depNames.indexOf(peer) === -1) depNames.push(peer);
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
function installTargetDirs(ctx, name) {
|
|
2548
|
+
const dirs = ['/workspace/node_modules/' + name];
|
|
2549
|
+
const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
|
|
2550
|
+
if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
|
|
2551
|
+
return dirs;
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
function writeInstalledPackageFiles(ctx, dirs, name, info) {
|
|
2555
|
+
for (const dir of dirs) {
|
|
2556
|
+
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2557
|
+
for (const f of info.files) {
|
|
2558
|
+
const full = PosixPath.join(dir, f.rel);
|
|
2559
|
+
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2560
|
+
ctx.vfs.writeFileSync(full, f.content);
|
|
2561
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2562
|
+
}
|
|
2563
|
+
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2564
|
+
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2565
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2566
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2567
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2568
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2569
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2570
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2571
|
+
}
|
|
2572
|
+
modPkg.exports = normalized;
|
|
2573
|
+
}
|
|
2574
|
+
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2358
2575
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2580
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2581
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2582
|
+
const isDev = Boolean(options.dev);
|
|
2583
|
+
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2584
|
+
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2359
2585
|
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2586
|
+
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2587
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2588
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2589
|
+
|
|
2590
|
+
const fetchImpl = packageCtxFetch(ctx);
|
|
2591
|
+
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
2592
|
+
? ctx.shell._cdnSeen
|
|
2593
|
+
: (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
|
|
2594
|
+
|
|
2595
|
+
const queue = [{ name: pkgName, range, direct: true }];
|
|
2596
|
+
const requested = new Set([pkgName]);
|
|
2597
|
+
const installed = [];
|
|
2598
|
+
let warning = null;
|
|
2599
|
+
let directVersion = null;
|
|
2600
|
+
|
|
2601
|
+
while (queue.length > 0) {
|
|
2602
|
+
const item = queue.shift();
|
|
2603
|
+
const info = fetchImpl
|
|
2604
|
+
? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
|
|
2605
|
+
: { ok: false, reason: `${item.name}: no fetch implementation available` };
|
|
2606
|
+
|
|
2607
|
+
if (!info.ok) {
|
|
2608
|
+
// Final fallback: an empty stub so offline demos still resolve the module.
|
|
2609
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
|
|
2610
|
+
version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
|
|
2611
|
+
});
|
|
2612
|
+
if (!warning) warning = info.reason;
|
|
2613
|
+
installed.push({ name: item.name, version: '0.0.0' });
|
|
2614
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2615
|
+
continue;
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2619
|
+
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2620
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2621
|
+
if (item.direct) directVersion = info.version || null;
|
|
2622
|
+
|
|
2623
|
+
for (const dep of (info.deps || [])) {
|
|
2624
|
+
const parsed = parsePackageSpec(dep);
|
|
2625
|
+
if (parsed.name && !requested.has(parsed.name)) {
|
|
2626
|
+
requested.add(parsed.name);
|
|
2627
|
+
queue.push({ name: parsed.name, range: null, direct: false });
|
|
2628
|
+
}
|
|
2367
2629
|
}
|
|
2368
|
-
ctx.vfs.writeFileSync(modIndexPath, code);
|
|
2369
|
-
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
|
|
2370
2630
|
}
|
|
2631
|
+
|
|
2632
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2633
|
+
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2634
|
+
|
|
2635
|
+
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2638
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2639
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2640
|
+
function createInstallEmitter(ctx, sink) {
|
|
2641
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2642
|
+
return function emit(text) {
|
|
2643
|
+
if (!text) return;
|
|
2644
|
+
sink.push(text);
|
|
2645
|
+
if (stream) stream(text);
|
|
2646
|
+
};
|
|
2647
|
+
}
|
|
2648
|
+
|
|
2649
|
+
function formatInstallLine(info) {
|
|
2650
|
+
if (!info || !info.name) return '';
|
|
2651
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2652
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2653
|
+
}
|
|
2654
|
+
|
|
2655
|
+
function countInstalledPackages(results) {
|
|
2656
|
+
const seen = new Set();
|
|
2657
|
+
for (const r of results) {
|
|
2658
|
+
if (!r) continue;
|
|
2659
|
+
if (r.name) seen.add(r.name);
|
|
2660
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2661
|
+
}
|
|
2662
|
+
return seen.size;
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2666
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2667
|
+
// "saved N package(s)".
|
|
2668
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2669
|
+
const options = opts || {};
|
|
2670
|
+
const manager = options.manager || 'bun';
|
|
2671
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2672
|
+
const out = [];
|
|
2673
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2674
|
+
const started = Date.now();
|
|
2675
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2676
|
+
const results = [];
|
|
2677
|
+
for (const p of pkgs) {
|
|
2678
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2679
|
+
}
|
|
2680
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2681
|
+
const count = countInstalledPackages(results);
|
|
2682
|
+
const ms = Date.now() - started;
|
|
2683
|
+
if (manager === 'npm') {
|
|
2684
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2685
|
+
} else if (manager === 'pnpm') {
|
|
2686
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2687
|
+
} else {
|
|
2688
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2689
|
+
}
|
|
2690
|
+
return {
|
|
2691
|
+
code: 0,
|
|
2692
|
+
stdout: out.join(''),
|
|
2693
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2694
|
+
};
|
|
2371
2695
|
}
|
|
2372
2696
|
|
|
2373
2697
|
function uninstallPackage(pkgName, ctx) {
|
|
@@ -2421,9 +2745,261 @@
|
|
|
2421
2745
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2422
2746
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2423
2747
|
}
|
|
2748
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2749
|
+
if (fallback) return fallback;
|
|
2424
2750
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2425
2751
|
}
|
|
2426
2752
|
|
|
2753
|
+
// ---------------------------------------------------------------------------
|
|
2754
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2755
|
+
//
|
|
2756
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2757
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2758
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2759
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2760
|
+
// ---------------------------------------------------------------------------
|
|
2761
|
+
|
|
2762
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2763
|
+
|
|
2764
|
+
const PREVIEW_MIME = {
|
|
2765
|
+
'.html': 'text/html; charset=utf-8',
|
|
2766
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2767
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2768
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2769
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2770
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2771
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2772
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2773
|
+
'.css': 'text/css; charset=utf-8',
|
|
2774
|
+
'.json': 'application/json; charset=utf-8',
|
|
2775
|
+
'.map': 'application/json; charset=utf-8',
|
|
2776
|
+
'.svg': 'image/svg+xml',
|
|
2777
|
+
'.png': 'image/png',
|
|
2778
|
+
'.jpg': 'image/jpeg',
|
|
2779
|
+
'.jpeg': 'image/jpeg',
|
|
2780
|
+
'.gif': 'image/gif',
|
|
2781
|
+
'.webp': 'image/webp',
|
|
2782
|
+
'.ico': 'image/x-icon',
|
|
2783
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2784
|
+
};
|
|
2785
|
+
|
|
2786
|
+
function previewMimeFor(p) {
|
|
2787
|
+
const lower = String(p).toLowerCase();
|
|
2788
|
+
const dot = lower.lastIndexOf('.');
|
|
2789
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2790
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
function isPreviewScriptPath(p) {
|
|
2794
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2795
|
+
}
|
|
2796
|
+
|
|
2797
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2798
|
+
function extractBareSpecifiers(code) {
|
|
2799
|
+
const out = new Set();
|
|
2800
|
+
const patterns = [
|
|
2801
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2802
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2803
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2804
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2805
|
+
];
|
|
2806
|
+
for (const re of patterns) {
|
|
2807
|
+
let m;
|
|
2808
|
+
while ((m = re.exec(code)) !== null) {
|
|
2809
|
+
const spec = m[1];
|
|
2810
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2811
|
+
out.add(spec);
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
return Array.from(out);
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
function normalizeVersionRange(range) {
|
|
2818
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2819
|
+
const v = range.trim();
|
|
2820
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2821
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2822
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2826
|
+
try {
|
|
2827
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2828
|
+
if (vfs.existsSync(modPkg)) {
|
|
2829
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2830
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2831
|
+
}
|
|
2832
|
+
} catch (_) {}
|
|
2833
|
+
try {
|
|
2834
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2835
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2836
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2837
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2838
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2839
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2840
|
+
}
|
|
2841
|
+
} catch (_) {}
|
|
2842
|
+
return 'latest';
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2846
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2847
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2848
|
+
return `${base}${sub}/+esm`;
|
|
2849
|
+
}
|
|
2850
|
+
|
|
2851
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2852
|
+
const imports = {};
|
|
2853
|
+
for (const spec of specifiers) {
|
|
2854
|
+
const parts = String(spec).split('/');
|
|
2855
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2856
|
+
if (!pkgName) continue;
|
|
2857
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2858
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2859
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2860
|
+
}
|
|
2861
|
+
return imports;
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2865
|
+
const scripts = [];
|
|
2866
|
+
const walk = (dir, depth) => {
|
|
2867
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2868
|
+
let entries = [];
|
|
2869
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2870
|
+
for (const name of entries) {
|
|
2871
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2872
|
+
const full = PosixPath.join(dir, name);
|
|
2873
|
+
let st;
|
|
2874
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2875
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2876
|
+
if (dirFlag) {
|
|
2877
|
+
walk(full, depth + 1);
|
|
2878
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2879
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
};
|
|
2883
|
+
walk(rootDir, 0);
|
|
2884
|
+
return scripts;
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
function injectPreviewExtras(html, importMap) {
|
|
2888
|
+
let out = html;
|
|
2889
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2890
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2891
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2892
|
+
} else {
|
|
2893
|
+
out = importMapTag + '\n' + out;
|
|
2894
|
+
}
|
|
2895
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2896
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2897
|
+
else out = out + '\n' + shim;
|
|
2898
|
+
return out;
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2902
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2903
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2904
|
+
|
|
2905
|
+
let port = Number(preferredPort) || 3000;
|
|
2906
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
2907
|
+
while (taken.has(port)) port++;
|
|
2908
|
+
|
|
2909
|
+
const specifiers = new Set();
|
|
2910
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
2911
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
2912
|
+
}
|
|
2913
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
2914
|
+
|
|
2915
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
2916
|
+
const isDir = (p) => {
|
|
2917
|
+
try {
|
|
2918
|
+
const st = ctx.vfs.statSync(p);
|
|
2919
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
2920
|
+
} catch (_) { return false; }
|
|
2921
|
+
};
|
|
2922
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
2923
|
+
|
|
2924
|
+
const handler = async (request) => {
|
|
2925
|
+
let pathname = '/';
|
|
2926
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
2927
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
2928
|
+
let target = PosixPath.join(rootDir, rel);
|
|
2929
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
2930
|
+
|
|
2931
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
2932
|
+
target = PosixPath.join(target, 'index.html');
|
|
2933
|
+
}
|
|
2934
|
+
if (!exists(target) && !hasExt) {
|
|
2935
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
2936
|
+
// the way a bundler / dev server would.
|
|
2937
|
+
const cands = [
|
|
2938
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
2939
|
+
target + '.mjs', target + '.cjs',
|
|
2940
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
2941
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
2942
|
+
];
|
|
2943
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
2944
|
+
}
|
|
2945
|
+
if (!exists(target) && !hasExt) {
|
|
2946
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
2947
|
+
}
|
|
2948
|
+
if (!exists(target)) {
|
|
2949
|
+
return new Response(
|
|
2950
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
2951
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
2952
|
+
);
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
let body = readText(target);
|
|
2956
|
+
if (body === null) body = '';
|
|
2957
|
+
if (/\.html?$/i.test(target)) {
|
|
2958
|
+
body = injectPreviewExtras(body, importMap);
|
|
2959
|
+
} else if (isPreviewScriptPath(target)) {
|
|
2960
|
+
try {
|
|
2961
|
+
const rm = getRuntimeModule();
|
|
2962
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
2963
|
+
body = rm.transpileForBrowser(body, target);
|
|
2964
|
+
}
|
|
2965
|
+
} catch (_) {}
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
2969
|
+
};
|
|
2970
|
+
|
|
2971
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
2972
|
+
return portTable.registerServer(port, {
|
|
2973
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
2974
|
+
fetch: handler,
|
|
2975
|
+
name: 'code-lab-serve',
|
|
2976
|
+
pid,
|
|
2977
|
+
root: rootDir
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2981
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
2982
|
+
// transparently redirected to the built-in preview server.
|
|
2983
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
2984
|
+
|
|
2985
|
+
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
2986
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
2987
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
2988
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
2989
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
2990
|
+
if (ctx.vfs.existsSync(binPath)) return null;
|
|
2991
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
2992
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
2993
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
2994
|
+
const entry = registerPreviewServer(ctx, ctx.cwd, port);
|
|
2995
|
+
if (!entry) return null;
|
|
2996
|
+
return {
|
|
2997
|
+
code: 0,
|
|
2998
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
2999
|
+
stderr: ''
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
|
|
2427
3003
|
function evaluatePosixTest(args, ctx) {
|
|
2428
3004
|
const cleanArgs = [...args];
|
|
2429
3005
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -4922,7 +5498,8 @@
|
|
|
4922
5498
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
4923
5499
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
4924
5500
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
4925
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5501
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5502
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
4926
5503
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
4927
5504
|
return { code: 0, stdout, stderr: '' };
|
|
4928
5505
|
},
|
|
@@ -5044,6 +5621,18 @@
|
|
|
5044
5621
|
|
|
5045
5622
|
const sub = args[0];
|
|
5046
5623
|
|
|
5624
|
+
if (sub === '--version' || sub === '-v' || sub === '--revision') {
|
|
5625
|
+
return { code: 0, stdout: '1.1.20\n', stderr: '' };
|
|
5626
|
+
}
|
|
5627
|
+
|
|
5628
|
+
if (sub === '--help' || sub === '-h') {
|
|
5629
|
+
return {
|
|
5630
|
+
code: 0,
|
|
5631
|
+
stdout: 'Bun v1.1.20\nUsage: bun <command> [flags]\n\nCommands:\n run <file|script> Run a file or package script\n install, i, add Install dependencies\n remove, rm Remove dependencies\n test Run tests\n init Scaffold a new project\n -e <code> Evaluate JavaScript\n',
|
|
5632
|
+
stderr: ''
|
|
5633
|
+
};
|
|
5634
|
+
}
|
|
5635
|
+
|
|
5047
5636
|
if (sub === 'init') {
|
|
5048
5637
|
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5049
5638
|
const dirName = PosixPath.basename(ctx.cwd) || 'app';
|
|
@@ -5093,12 +5682,27 @@
|
|
|
5093
5682
|
return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
|
|
5094
5683
|
}
|
|
5095
5684
|
|
|
5096
|
-
if (sub === '
|
|
5685
|
+
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5097
5686
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5098
|
-
|
|
5099
|
-
|
|
5687
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5688
|
+
if (pkgs.length === 0) {
|
|
5689
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5690
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5691
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5692
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5100
5693
|
}
|
|
5101
|
-
return {
|
|
5694
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5695
|
+
}
|
|
5696
|
+
|
|
5697
|
+
if (sub === 'add') {
|
|
5698
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5699
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5700
|
+
if (pkgs.length === 0) {
|
|
5701
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5702
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5703
|
+
}
|
|
5704
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5705
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5102
5706
|
}
|
|
5103
5707
|
|
|
5104
5708
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5258,18 +5862,14 @@
|
|
|
5258
5862
|
}
|
|
5259
5863
|
|
|
5260
5864
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5261
|
-
|
|
5865
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5866
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5262
5867
|
if (pkgs.length === 0) {
|
|
5263
5868
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
}
|
|
5267
|
-
return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5869
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5870
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5268
5871
|
}
|
|
5269
|
-
|
|
5270
|
-
installPackage(p, ctx);
|
|
5271
|
-
}
|
|
5272
|
-
return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
|
|
5872
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5273
5873
|
}
|
|
5274
5874
|
|
|
5275
5875
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5321,6 +5921,123 @@
|
|
|
5321
5921
|
return await this.npx(args, ctx);
|
|
5322
5922
|
},
|
|
5323
5923
|
|
|
5924
|
+
async pnpm(args, ctx) {
|
|
5925
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
5926
|
+
return {
|
|
5927
|
+
code: 0,
|
|
5928
|
+
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',
|
|
5929
|
+
stderr: ''
|
|
5930
|
+
};
|
|
5931
|
+
}
|
|
5932
|
+
const sub = args[0];
|
|
5933
|
+
if (sub === '--version' || sub === '-v') {
|
|
5934
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
5935
|
+
}
|
|
5936
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
5937
|
+
|
|
5938
|
+
if (sub === 'init') {
|
|
5939
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5940
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
5941
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
5942
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
5943
|
+
version: '1.0.0',
|
|
5944
|
+
main: 'index.js',
|
|
5945
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
5946
|
+
}, null, 2) + '\n');
|
|
5947
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
5948
|
+
}
|
|
5949
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
5950
|
+
}
|
|
5951
|
+
|
|
5952
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
5953
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
5954
|
+
if (pkgs.length === 0) {
|
|
5955
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5956
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5957
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
5958
|
+
}
|
|
5959
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
5960
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
5961
|
+
}
|
|
5962
|
+
|
|
5963
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
5964
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
5965
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
5966
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
5967
|
+
}
|
|
5968
|
+
|
|
5969
|
+
if (sub === 'list' || sub === 'ls') {
|
|
5970
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
5971
|
+
}
|
|
5972
|
+
|
|
5973
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
5974
|
+
const scriptName = args[1];
|
|
5975
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
5976
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
5977
|
+
}
|
|
5978
|
+
|
|
5979
|
+
if (sub === 'test') {
|
|
5980
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
5981
|
+
}
|
|
5982
|
+
|
|
5983
|
+
if (sub === 'exec') {
|
|
5984
|
+
const cmd = args[1];
|
|
5985
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
5986
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
5987
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
5988
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
5989
|
+
}
|
|
5990
|
+
|
|
5991
|
+
if (sub === 'dlx') {
|
|
5992
|
+
return await this.npx(args.slice(1), ctx);
|
|
5993
|
+
}
|
|
5994
|
+
|
|
5995
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5996
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
5997
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
5998
|
+
}
|
|
5999
|
+
|
|
6000
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6001
|
+
},
|
|
6002
|
+
|
|
6003
|
+
async serve(args, ctx) {
|
|
6004
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6005
|
+
return {
|
|
6006
|
+
code: 0,
|
|
6007
|
+
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',
|
|
6008
|
+
stderr: ''
|
|
6009
|
+
};
|
|
6010
|
+
}
|
|
6011
|
+
const rootArg = (() => {
|
|
6012
|
+
const positionals = [];
|
|
6013
|
+
for (let i = 0; i < args.length; i++) {
|
|
6014
|
+
const a = args[i];
|
|
6015
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6016
|
+
if (a.startsWith('-')) continue;
|
|
6017
|
+
positionals.push(a);
|
|
6018
|
+
}
|
|
6019
|
+
return positionals[0];
|
|
6020
|
+
})();
|
|
6021
|
+
let port = 3000;
|
|
6022
|
+
for (let i = 0; i < args.length; i++) {
|
|
6023
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6024
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6025
|
+
}
|
|
6026
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6027
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6028
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6029
|
+
}
|
|
6030
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6031
|
+
if (!entry) {
|
|
6032
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6033
|
+
}
|
|
6034
|
+
return {
|
|
6035
|
+
code: 0,
|
|
6036
|
+
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`,
|
|
6037
|
+
stderr: ''
|
|
6038
|
+
};
|
|
6039
|
+
},
|
|
6040
|
+
|
|
5324
6041
|
// -----------------------------------------------------------------------
|
|
5325
6042
|
// Port Table & HTTP Inspection: ports, curl
|
|
5326
6043
|
// -----------------------------------------------------------------------
|
|
@@ -5494,6 +6211,16 @@
|
|
|
5494
6211
|
return PosixPath.resolve(this.cwd, p);
|
|
5495
6212
|
}
|
|
5496
6213
|
|
|
6214
|
+
// True when `name` resolves to a shell function or coreutil (used by the
|
|
6215
|
+
// workbench to route recognised commands straight to the shell instead of
|
|
6216
|
+
// treating flag-looking input such as `node --version` as a JS expression).
|
|
6217
|
+
hasCommand(name) {
|
|
6218
|
+
if (!name) return false;
|
|
6219
|
+
const n = String(name);
|
|
6220
|
+
if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
|
|
6221
|
+
return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
|
|
6222
|
+
}
|
|
6223
|
+
|
|
5497
6224
|
_emitVfsMutation(type, absPath) {
|
|
5498
6225
|
if (!this.vfs) return;
|
|
5499
6226
|
const evt = { type, path: absPath, timestamp: Date.now() };
|