@innovatorved/code-lab 0.1.3 → 0.1.4

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/dist/shell.esm.js CHANGED
@@ -2354,38 +2354,221 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2354
2354
  } catch (_) {}
2355
2355
  }
2356
2356
 
2357
- function installPackage(pkgSpec, ctx) {
2358
- const parts = pkgSpec.split('@').filter(Boolean);
2359
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
2360
- const pkgVersion = parts[1] || '^1.0.0';
2357
+ // ---------------------------------------------------------------------------
2358
+ // Real npm package installation via the jsDelivr CDN
2359
+ // ---------------------------------------------------------------------------
2360
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
2361
+
2362
+ // Minimal offline registry, used only when the CDN is unreachable so common
2363
+ // demos still resolve without network access.
2364
+ const OFFLINE_PACKAGE_FALLBACKS = {
2365
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
2366
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
2367
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
2368
+ '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'
2369
+ };
2370
+
2371
+ function packageCtxFetch(ctx) {
2372
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
2373
+ return ctx.shell.options.fetchImpl;
2374
+ }
2375
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
2376
+ return null;
2377
+ }
2378
+
2379
+ function parsePackageSpec(spec) {
2380
+ const raw = String(spec || '').trim();
2381
+ if (!raw) return { name: '', range: null };
2382
+ if (raw.startsWith('@')) {
2383
+ const at = raw.indexOf('@', 1);
2384
+ if (at === -1) return { name: raw, range: null };
2385
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2386
+ }
2387
+ const at = raw.indexOf('@');
2388
+ if (at <= 0) return { name: raw, range: null };
2389
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2390
+ }
2391
+
2392
+ function resolveEntryRelPath(pkgJson) {
2393
+ let entry = pkgJson.main || pkgJson.module ||
2394
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2395
+ entry = String(entry).replace(/^[./]+/, '');
2396
+ return entry || 'index.js';
2397
+ }
2398
+
2399
+ function stripRelPath(rel) {
2400
+ return String(rel || '').replace(/^[./]+/, '');
2401
+ }
2402
+
2403
+ function extractRelativeSpecifiers(code) {
2404
+ const out = new Set();
2405
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2406
+ let m;
2407
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2408
+ return Array.from(out);
2409
+ }
2410
+
2411
+ function normalizeRelPath(baseDir, rel) {
2412
+ const parts = String(baseDir || '').split('/').filter(Boolean);
2413
+ for (const seg of String(rel).split('/')) {
2414
+ if (!seg || seg === '.') continue;
2415
+ if (seg === '..') parts.pop();
2416
+ else parts.push(seg);
2417
+ }
2418
+ return parts.join('/');
2419
+ }
2420
+
2421
+ async function fetchTextFromCdn(fetchImpl, url) {
2422
+ try {
2423
+ const res = await fetchImpl(url);
2424
+ if (!res) return null;
2425
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2426
+ if (!ok) return null;
2427
+ if (typeof res.text === 'function') return await res.text();
2428
+ return String(res.body != null ? res.body : '');
2429
+ } catch (_) {
2430
+ return null;
2431
+ }
2432
+ }
2433
+
2434
+ async function resolvePackageMetadata(fetchImpl, name, range) {
2435
+ const urls = range
2436
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2437
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
2438
+ for (const url of urls) {
2439
+ const text = await fetchTextFromCdn(fetchImpl, url);
2440
+ if (!text) continue;
2441
+ try {
2442
+ const parsed = JSON.parse(text);
2443
+ if (parsed && parsed.version) return parsed;
2444
+ } catch (_) {}
2445
+ }
2446
+ return null;
2447
+ }
2448
+
2449
+ // Download a package's entry module, its relative submodules and record its
2450
+ // declared dependencies so the caller can resolve them transitively.
2451
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
2452
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
2453
+ if (!meta) {
2454
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
2455
+ if (fallback) {
2456
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
2457
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
2458
+ }
2459
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2460
+ }
2461
+
2462
+ const version = meta.version;
2463
+ const key = `${name}@${version}`;
2464
+ if (seen.has(key)) {
2465
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
2466
+ }
2467
+ seen.add(key);
2468
+
2469
+ const entry = resolveEntryRelPath(meta);
2470
+ const files = [];
2471
+ const visited = new Set();
2472
+ const queue = [entry];
2473
+ while (queue.length > 0) {
2474
+ const rel = stripRelPath(queue.shift());
2475
+ if (!rel || visited.has(rel)) continue;
2476
+ visited.add(rel);
2477
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2478
+ if (text === null) continue;
2479
+ files.push({ rel, content: text });
2480
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2481
+ for (const spec of extractRelativeSpecifiers(text)) {
2482
+ const target = normalizeRelPath(baseDir, spec);
2483
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2484
+ const c = stripRelPath(cand);
2485
+ if (c && !visited.has(c)) { queue.push(cand); break; }
2486
+ }
2487
+ }
2488
+ }
2489
+ // The declared entry may be missing on the CDN; fall back to index.js.
2490
+ if (!files.some(f => f.rel === entry)) {
2491
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2492
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2493
+ }
2494
+
2495
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2496
+ }
2497
+
2498
+ function installTargetDirs(ctx, name) {
2499
+ const dirs = ['/workspace/node_modules/' + name];
2500
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
2501
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
2502
+ return dirs;
2503
+ }
2504
+
2505
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
2506
+ for (const dir of dirs) {
2507
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2508
+ for (const f of info.files) {
2509
+ const full = PosixPath.join(dir, f.rel);
2510
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2511
+ ctx.vfs.writeFileSync(full, f.content);
2512
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
2513
+ }
2514
+ const modPkgPath = PosixPath.join(dir, 'package.json');
2515
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2516
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2517
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2518
+ }
2519
+ }
2520
+
2521
+ async function installPackage(pkgSpec, ctx) {
2522
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2523
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2361
2524
 
2362
2525
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2363
2526
  if (!pkgData.dependencies) pkgData.dependencies = {};
2364
- pkgData.dependencies[pkgName] = pkgVersion;
2365
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2366
2527
 
2367
- const targetDirs = ['/workspace/node_modules/' + pkgName];
2368
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
2369
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
2528
+ const fetchImpl = packageCtxFetch(ctx);
2529
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
2530
+ ? ctx.shell._cdnSeen
2531
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
2532
+
2533
+ const queue = [{ name: pkgName, range, direct: true }];
2534
+ const requested = new Set([pkgName]);
2535
+ const installed = [];
2536
+ let warning = null;
2537
+ let directVersion = null;
2538
+
2539
+ while (queue.length > 0) {
2540
+ const item = queue.shift();
2541
+ const info = fetchImpl
2542
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
2543
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
2544
+
2545
+ if (!info.ok) {
2546
+ // Final fallback: an empty stub so offline demos still resolve the module.
2547
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
2548
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
2549
+ });
2550
+ if (!warning) warning = info.reason;
2551
+ installed.push({ name: item.name, version: '0.0.0' });
2552
+ continue;
2553
+ }
2370
2554
 
2371
- for (const modDir of targetDirs) {
2372
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
2373
- const modPkgPath = PosixPath.join(modDir, 'package.json');
2374
- const modIndexPath = PosixPath.join(modDir, 'index.js');
2375
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
2376
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2555
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2556
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
2557
+ if (item.direct) directVersion = info.version || null;
2377
2558
 
2378
- let code = 'module.exports = {};\n';
2379
- if (pkgName === 'is-even') {
2380
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
2381
- } else if (pkgName === 'tiny-invariant') {
2382
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
2383
- } else if (pkgName === 'lodash') {
2384
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
2559
+ for (const dep of (info.deps || [])) {
2560
+ const parsed = parsePackageSpec(dep);
2561
+ if (parsed.name && !requested.has(parsed.name)) {
2562
+ requested.add(parsed.name);
2563
+ queue.push({ name: parsed.name, range: null, direct: false });
2564
+ }
2385
2565
  }
2386
- ctx.vfs.writeFileSync(modIndexPath, code);
2387
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
2388
2566
  }
2567
+
2568
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2569
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2570
+
2571
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
2389
2572
  }
2390
2573
 
2391
2574
  function uninstallPackage(pkgName, ctx) {
@@ -5062,6 +5245,18 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5062
5245
 
5063
5246
  const sub = args[0];
5064
5247
 
5248
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
5249
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
5250
+ }
5251
+
5252
+ if (sub === '--help' || sub === '-h') {
5253
+ return {
5254
+ code: 0,
5255
+ 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',
5256
+ stderr: ''
5257
+ };
5258
+ }
5259
+
5065
5260
  if (sub === 'init') {
5066
5261
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5067
5262
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -5111,12 +5306,28 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5111
5306
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
5112
5307
  }
5113
5308
 
5114
- if (sub === 'add') {
5309
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
5115
5310
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5116
- for (const p of pkgs) {
5117
- installPackage(p, ctx);
5311
+ if (pkgs.length === 0) {
5312
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5313
+ const deps = Object.keys(pkgData.dependencies || {});
5314
+ const results = [];
5315
+ for (const p of deps) results.push(await installPackage(p, ctx));
5316
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5317
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5118
5318
  }
5119
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
5319
+ const results = [];
5320
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5321
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5322
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5323
+ }
5324
+
5325
+ if (sub === 'add') {
5326
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5327
+ const results = [];
5328
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5329
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5330
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5120
5331
  }
5121
5332
 
5122
5333
  if (sub === 'remove' || sub === 'rm') {
@@ -5279,15 +5490,19 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5279
5490
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5280
5491
  if (pkgs.length === 0) {
5281
5492
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5493
+ const results = [];
5282
5494
  for (const p of Object.keys(pkgData.dependencies || {})) {
5283
- installPackage(p, ctx);
5495
+ results.push(await installPackage(p, ctx));
5284
5496
  }
5285
- return { code: 0, stdout: 'up to date\n', stderr: '' };
5497
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5498
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5286
5499
  }
5500
+ const results = [];
5287
5501
  for (const p of pkgs) {
5288
- installPackage(p, ctx);
5502
+ results.push(await installPackage(p, ctx));
5289
5503
  }
5290
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
5504
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5505
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5291
5506
  }
5292
5507
 
5293
5508
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5512,6 +5727,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5512
5727
  return PosixPath.resolve(this.cwd, p);
5513
5728
  }
5514
5729
 
5730
+ // True when `name` resolves to a shell function or coreutil (used by the
5731
+ // workbench to route recognised commands straight to the shell instead of
5732
+ // treating flag-looking input such as `node --version` as a JS expression).
5733
+ hasCommand(name) {
5734
+ if (!name) return false;
5735
+ const n = String(name);
5736
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
5737
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
5738
+ }
5739
+
5515
5740
  _emitVfsMutation(type, absPath) {
5516
5741
  if (!this.vfs) return;
5517
5742
  const evt = { type, path: absPath, timestamp: Date.now() };