@innovatorved/code-lab 0.1.2 → 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/runtime.d.ts CHANGED
@@ -39,7 +39,7 @@ export declare const createVirtualFs: (options?: any) => any;
39
39
  export declare const createVirtualHttp: (portTable?: any, vfs?: any) => any;
40
40
  export declare const createVirtualNet: (portTable?: any) => any;
41
41
  export declare const transpileTS: (code: string, filename?: string) => string;
42
- export declare const preloadNpmPackages: (packages?: Record<string, any>) => void;
42
+ export declare const preloadNpmPackages: (files?: Record<string, any>, onProgressOrCache?: ((pkg: string) => void) | Map<string, string>, onProgress?: (pkg: string) => void) => Promise<Record<string, string>>;
43
43
  export declare const createVirtualPortTable: () => any;
44
44
  export declare const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult>;
45
45
  export declare const createWorkerRuntimeSource: () => string;
@@ -4679,8 +4679,22 @@ function __initVirtualRuntime(rootScope) {
4679
4679
  }
4680
4680
 
4681
4681
  const _npmPackageCache = new Map();
4682
+ const _npmMetadataCache = new Map();
4683
+
4684
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4685
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4686
+ // preloadNpmPackages(files)
4687
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4688
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4689
+ // preloadNpmPackages(files, existingCache, onProgress)
4690
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4691
+ let onProgress = null;
4692
+ let existingCache = _npmPackageCache;
4693
+ if (typeof secondArg === 'function') onProgress = secondArg;
4694
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4695
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4696
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4682
4697
 
4683
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4684
4698
  const specs = new Set();
4685
4699
  const builtinSet = new Set([
4686
4700
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4716,20 +4730,51 @@ function __initVirtualRuntime(rootScope) {
4716
4730
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4717
4731
  }
4718
4732
 
4733
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4734
+ // is memoised across calls so repeated preloads stay cheap.
4735
+ if (typeof fetch === 'function') {
4736
+ let pass = 0;
4737
+ while (pass < 6) {
4738
+ const pending = [];
4739
+ for (const pkg of specs) {
4740
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4741
+ }
4742
+ if (pending.length === 0) break;
4743
+ pass++;
4744
+ await Promise.all(pending.map(async (pkg) => {
4745
+ let deps = [];
4746
+ try {
4747
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4748
+ if (res && res.ok) {
4749
+ const meta = await res.json();
4750
+ deps = Object.keys((meta && meta.dependencies) || {});
4751
+ }
4752
+ } catch (_) {}
4753
+ _npmMetadataCache.set(pkg, deps);
4754
+ }));
4755
+ for (const pkg of pending) {
4756
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4757
+ }
4758
+ }
4759
+ }
4760
+
4719
4761
  const loaded = {};
4720
4762
  for (const pkg of specs) {
4721
4763
  const nmKey = `node_modules/${pkg}/index.js`;
4722
4764
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4723
- if (existingCache && existingCache.has(pkg)) {
4765
+ if (existingCache.has(pkg)) {
4724
4766
  loaded[pkg] = existingCache.get(pkg);
4725
4767
  continue;
4726
4768
  }
4769
+ if (typeof onProgress === 'function') {
4770
+ try { onProgress(pkg); } catch (_) {}
4771
+ }
4727
4772
  if (typeof fetch === 'function') {
4728
4773
  try {
4729
4774
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4730
4775
  if (res && res.ok) {
4731
4776
  const text = await res.text();
4732
- if (existingCache) existingCache.set(pkg, text);
4777
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4733
4778
  loaded[pkg] = text;
4734
4779
  }
4735
4780
  } catch (_) {}
package/dist/runtime.js CHANGED
@@ -4680,8 +4680,22 @@ function __initVirtualRuntime(rootScope) {
4680
4680
  }
4681
4681
 
4682
4682
  const _npmPackageCache = new Map();
4683
+ const _npmMetadataCache = new Map();
4684
+
4685
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4686
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4687
+ // preloadNpmPackages(files)
4688
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4689
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4690
+ // preloadNpmPackages(files, existingCache, onProgress)
4691
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4692
+ let onProgress = null;
4693
+ let existingCache = _npmPackageCache;
4694
+ if (typeof secondArg === 'function') onProgress = secondArg;
4695
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4696
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4697
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4683
4698
 
4684
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4685
4699
  const specs = new Set();
4686
4700
  const builtinSet = new Set([
4687
4701
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4717,20 +4731,51 @@ function __initVirtualRuntime(rootScope) {
4717
4731
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4718
4732
  }
4719
4733
 
4734
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4735
+ // is memoised across calls so repeated preloads stay cheap.
4736
+ if (typeof fetch === 'function') {
4737
+ let pass = 0;
4738
+ while (pass < 6) {
4739
+ const pending = [];
4740
+ for (const pkg of specs) {
4741
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4742
+ }
4743
+ if (pending.length === 0) break;
4744
+ pass++;
4745
+ await Promise.all(pending.map(async (pkg) => {
4746
+ let deps = [];
4747
+ try {
4748
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4749
+ if (res && res.ok) {
4750
+ const meta = await res.json();
4751
+ deps = Object.keys((meta && meta.dependencies) || {});
4752
+ }
4753
+ } catch (_) {}
4754
+ _npmMetadataCache.set(pkg, deps);
4755
+ }));
4756
+ for (const pkg of pending) {
4757
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4758
+ }
4759
+ }
4760
+ }
4761
+
4720
4762
  const loaded = {};
4721
4763
  for (const pkg of specs) {
4722
4764
  const nmKey = `node_modules/${pkg}/index.js`;
4723
4765
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4724
- if (existingCache && existingCache.has(pkg)) {
4766
+ if (existingCache.has(pkg)) {
4725
4767
  loaded[pkg] = existingCache.get(pkg);
4726
4768
  continue;
4727
4769
  }
4770
+ if (typeof onProgress === 'function') {
4771
+ try { onProgress(pkg); } catch (_) {}
4772
+ }
4728
4773
  if (typeof fetch === 'function') {
4729
4774
  try {
4730
4775
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4731
4776
  if (res && res.ok) {
4732
4777
  const text = await res.text();
4733
- if (existingCache) existingCache.set(pkg, text);
4778
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4734
4779
  loaded[pkg] = text;
4735
4780
  }
4736
4781
  } catch (_) {}
package/dist/shell.esm.js CHANGED
@@ -2027,6 +2027,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2027
2027
  const requestedBranch = options.branch || parsed.branch || null;
2028
2028
  const { owner, repo } = parsed;
2029
2029
 
2030
+ const signal = options.signal || null;
2031
+ const throwIfAborted = () => {
2032
+ if (signal && signal.aborted) {
2033
+ const abortErr = new Error('fatal: clone cancelled (SIGINT)');
2034
+ abortErr.name = 'AbortError';
2035
+ throw abortErr;
2036
+ }
2037
+ };
2038
+ throwIfAborted();
2039
+
2030
2040
  let resolvedBranch = requestedBranch;
2031
2041
  let rawTreeEntries = null;
2032
2042
  let repoNotFound = false;
@@ -2039,7 +2049,8 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2039
2049
  try {
2040
2050
  if (!resolvedBranch) {
2041
2051
  const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2042
- headers: { Accept: 'application/vnd.github.v3+json' }
2052
+ headers: { Accept: 'application/vnd.github.v3+json' },
2053
+ signal
2043
2054
  });
2044
2055
  if (metaRes.status === 404) {
2045
2056
  repoNotFound = true;
@@ -2057,9 +2068,10 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2057
2068
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2058
2069
 
2059
2070
  for (const cand of branchCandidates) {
2071
+ throwIfAborted();
2060
2072
  const treeRes = await fetchFn(
2061
2073
  `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2062
- { headers: { Accept: 'application/vnd.github.v3+json' } }
2074
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2063
2075
  );
2064
2076
  if (treeRes.ok) {
2065
2077
  const treeJson = await treeRes.json();
@@ -2085,8 +2097,10 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2085
2097
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2086
2098
 
2087
2099
  for (const cand of branchCandidates) {
2100
+ throwIfAborted();
2088
2101
  const flatRes = await fetchFn(
2089
- `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`
2102
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2103
+ { signal }
2090
2104
  );
2091
2105
  if (flatRes && flatRes.ok) {
2092
2106
  const flatJson = await flatRes.json();
@@ -2155,28 +2169,34 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2155
2169
  const BATCH_SIZE = 12;
2156
2170
 
2157
2171
  for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2172
+ throwIfAborted();
2158
2173
  const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2159
2174
  await Promise.all(
2160
2175
  batch.map(async (entry) => {
2176
+ throwIfAborted();
2161
2177
  const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2162
2178
  const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2163
2179
  const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2164
2180
 
2165
2181
  let text = null;
2166
2182
  try {
2167
- const r1 = await fetchFn(rawUrl);
2183
+ const r1 = await fetchFn(rawUrl, { signal });
2168
2184
  if (r1 && r1.ok) {
2169
2185
  text = await r1.text();
2170
2186
  }
2171
- } catch (_) {}
2187
+ } catch (_) {
2188
+ if (signal && signal.aborted) throw _;
2189
+ }
2172
2190
 
2173
2191
  if (text === null) {
2174
2192
  try {
2175
- const r2 = await fetchFn(cdnUrl);
2193
+ const r2 = await fetchFn(cdnUrl, { signal });
2176
2194
  if (r2 && r2.ok) {
2177
2195
  text = await r2.text();
2178
2196
  }
2179
- } catch (_) {}
2197
+ } catch (_) {
2198
+ if (signal && signal.aborted) throw _;
2199
+ }
2180
2200
  }
2181
2201
 
2182
2202
  if (text !== null && text.length <= maxFileSize) {
@@ -2200,6 +2220,8 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2200
2220
  );
2201
2221
  }
2202
2222
 
2223
+ throwIfAborted();
2224
+
2203
2225
  if (onProgress) {
2204
2226
  onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
2205
2227
  }
@@ -2220,7 +2242,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2220
2242
  try {
2221
2243
  const commitsRes = await fetchFn(
2222
2244
  `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2223
- { headers: { Accept: 'application/vnd.github.v3+json' } }
2245
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2224
2246
  );
2225
2247
  if (commitsRes && commitsRes.ok) {
2226
2248
  const commitsJson = await commitsRes.json();
@@ -2332,38 +2354,221 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2332
2354
  } catch (_) {}
2333
2355
  }
2334
2356
 
2335
- function installPackage(pkgSpec, ctx) {
2336
- const parts = pkgSpec.split('@').filter(Boolean);
2337
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
2338
- 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 };
2339
2524
 
2340
2525
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2341
2526
  if (!pkgData.dependencies) pkgData.dependencies = {};
2342
- pkgData.dependencies[pkgName] = pkgVersion;
2343
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2344
2527
 
2345
- const targetDirs = ['/workspace/node_modules/' + pkgName];
2346
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
2347
- 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
+ }
2348
2554
 
2349
- for (const modDir of targetDirs) {
2350
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
2351
- const modPkgPath = PosixPath.join(modDir, 'package.json');
2352
- const modIndexPath = PosixPath.join(modDir, 'index.js');
2353
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
2354
- 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;
2355
2558
 
2356
- let code = 'module.exports = {};\n';
2357
- if (pkgName === 'is-even') {
2358
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
2359
- } else if (pkgName === 'tiny-invariant') {
2360
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
2361
- } else if (pkgName === 'lodash') {
2362
- 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
+ }
2363
2565
  }
2364
- ctx.vfs.writeFileSync(modIndexPath, code);
2365
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
2366
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 };
2367
2572
  }
2368
2573
 
2369
2574
  function uninstallPackage(pkgName, ctx) {
@@ -4467,6 +4672,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
4467
4672
  targetDir,
4468
4673
  branch: branchOpt,
4469
4674
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
4675
+ signal: ctx.signal,
4470
4676
  onFile: (absPath) => ctx.emitMutation('create', absPath),
4471
4677
  onProgress: (ev) => {
4472
4678
  if (!ev) return;
@@ -4507,6 +4713,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
4507
4713
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
4508
4714
  return { code: 0, stdout, stderr: '' };
4509
4715
  } catch (err) {
4716
+ if (ctx.signal && ctx.signal.aborted) {
4717
+ return { code: 130, stdout: '', stderr: '', aborted: true };
4718
+ }
4510
4719
  const msg = err && err.message ? err.message : String(err);
4511
4720
  if (canStream) streamLine(msg.endsWith('\n') ? msg : msg + '\n');
4512
4721
  return { code: 128, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
@@ -4834,6 +5043,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
4834
5043
  targetDir: repoRoot,
4835
5044
  branch: gitState.branch,
4836
5045
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
5046
+ signal: ctx.signal,
4837
5047
  onFile: (absPath) => ctx.emitMutation('change', absPath)
4838
5048
  });
4839
5049
  gitState.headSnapshot = Object.assign({}, result.headSnapshot);
@@ -4843,6 +5053,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
4843
5053
  stderr: ''
4844
5054
  };
4845
5055
  } catch (err) {
5056
+ if (ctx.signal && ctx.signal.aborted) {
5057
+ return { code: 130, stdout: '', stderr: '', aborted: true };
5058
+ }
4846
5059
  const msg = err && err.message ? err.message : String(err);
4847
5060
  return { code: 1, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
4848
5061
  }
@@ -5032,6 +5245,18 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5032
5245
 
5033
5246
  const sub = args[0];
5034
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
+
5035
5260
  if (sub === 'init') {
5036
5261
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5037
5262
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -5081,12 +5306,28 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5081
5306
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
5082
5307
  }
5083
5308
 
5084
- if (sub === 'add') {
5309
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
5085
5310
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5086
- for (const p of pkgs) {
5087
- 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` : '' };
5088
5318
  }
5089
- 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` : '' };
5090
5331
  }
5091
5332
 
5092
5333
  if (sub === 'remove' || sub === 'rm') {
@@ -5249,15 +5490,19 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5249
5490
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5250
5491
  if (pkgs.length === 0) {
5251
5492
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5493
+ const results = [];
5252
5494
  for (const p of Object.keys(pkgData.dependencies || {})) {
5253
- installPackage(p, ctx);
5495
+ results.push(await installPackage(p, ctx));
5254
5496
  }
5255
- 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` : '' };
5256
5499
  }
5500
+ const results = [];
5257
5501
  for (const p of pkgs) {
5258
- installPackage(p, ctx);
5502
+ results.push(await installPackage(p, ctx));
5259
5503
  }
5260
- 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` : '' };
5261
5506
  }
5262
5507
 
5263
5508
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5482,6 +5727,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5482
5727
  return PosixPath.resolve(this.cwd, p);
5483
5728
  }
5484
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
+
5485
5740
  _emitVfsMutation(type, absPath) {
5486
5741
  if (!this.vfs) return;
5487
5742
  const evt = { type, path: absPath, timestamp: Date.now() };