@innovatorved/code-lab 0.1.5 → 0.1.7

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.d.ts CHANGED
@@ -1,56 +1,27 @@
1
1
  /**
2
- * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils (TypeScript)
2
+ * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
3
3
  *
4
4
  * Full-fidelity, CSP-safe POSIX shell AST interpreter and 35+ standard UNIX
5
5
  * coreutils operating directly on the in-memory virtual filesystem (VFS).
6
6
  *
7
+ * Capabilities:
8
+ * - Deterministic lexer and AST parser (zero dynamic eval, zero new Function)
9
+ * - Pipelines (cmd1 | cmd2 | cmd3) with streaming stdin/stdout chaining
10
+ * - Output redirection (>, >>, 1>, 2>, 2>&1, 1>&2, &>)
11
+ * - Input redirection (<, 0<)
12
+ * - Logical operators (&&, ||, ;)
13
+ * - Background job execution (cmd &) with job table & PID tracking
14
+ * - Variable expansion ($VAR, ${VAR}, ${VAR:-def}, $?, $PWD, $HOME, $USER)
15
+ * - Command substitution ($(cmd), `cmd`)
16
+ * - Glob expansion (*.js, src/**\/*.ts, [0-9]*.txt) against VFS
17
+ * - 40+ UNIX coreutils (ls, cd, pwd, cat, head, tail, grep, find, wc, sort, uniq,
18
+ * sed, awk, cut, tr, diff, tree, cp, mv, rm, mkdir, touch, chmod, stat, echo,
19
+ * printf, env, export, unset, which, whoami, uname, date, sleep, true, false,
20
+ * clear, history, ps, jobs, kill, git, help, dirname, basename, seq, tee)
21
+ * - Bidirectional VFS mutation bridge (touch, mkdir, rm, mv, cp, echo >, sed -i)
22
+ *
7
23
  * (C) 2026 InnovatorVed / CodeLab. MIT License.
8
24
  */
9
- import type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions } from './schemas.js';
10
- export type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions };
11
- export interface CloneResult {
12
- owner: string;
13
- repo: string;
14
- branch: string;
15
- url: string;
16
- targetDir: string;
17
- count: number;
18
- fileCount: number;
19
- filesWritten: number;
20
- totalBytes: number;
21
- commits: Array<{
22
- hash: string;
23
- author: string;
24
- date: string;
25
- message: string;
26
- }>;
27
- headSnapshot: Record<string, string>;
28
- }
29
- export interface ShellExecResult {
30
- code: number;
31
- exitCode?: number;
32
- ok?: boolean;
33
- stdout: string;
34
- stderr: string;
35
- controlFlow?: {
36
- type: string;
37
- count?: number;
38
- code?: number;
39
- };
40
- aborted?: boolean;
41
- }
42
- export interface ShellExecOptions {
43
- cwd?: string;
44
- env?: Record<string, string>;
45
- vfs?: any;
46
- portTable?: any;
47
- onStdout?: (chunk: string) => void;
48
- onStderr?: (chunk: string) => void;
49
- stdin?: string;
50
- fetchImpl?: any;
51
- onProgress?: (event: CloneProgressEvent) => void;
52
- signal?: AbortSignal;
53
- }
54
25
  declare const _hostShell: any;
55
26
  export declare const createPosixShell: (options?: any) => any;
56
27
  export declare const parseShellCommand: (cmd: string) => any;
@@ -61,6 +32,6 @@ export declare const PosixPath: any;
61
32
  export declare const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[];
62
33
  export declare const createVirtualPortTable: () => any;
63
34
  export declare const parseGitHubRepoUrl: (input: string) => any;
64
- export declare const cloneGitHubRepository: (repoInput: string, vfs: any, options?: GitHubCloneOptions) => Promise<CloneResult>;
35
+ export declare const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any>;
65
36
  export declare const CodeLabShell: any;
66
37
  export default _hostShell;
package/dist/shell.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.7 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -16,6 +16,7 @@
16
16
  */
17
17
  const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
18
18
  (function () {
19
+ // @ts-nocheck
19
20
  /**
20
21
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
21
22
  *
@@ -2003,7 +2004,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2003
2004
  return 10 + depth * 0.1;
2004
2005
  }
2005
2006
 
2006
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2007
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
2007
2008
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2008
2009
  if (onProgress) {
2009
2010
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -2293,6 +2294,23 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2293
2294
  };
2294
2295
  }
2295
2296
 
2297
+ // Public wrapper: guarantee an `error` progress event when the clone fails
2298
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
2299
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2300
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2301
+ try {
2302
+ return await _cloneGitHubRepository(repoInput, vfs, options);
2303
+ } catch (err) {
2304
+ if (onProgress) {
2305
+ onProgress({
2306
+ phase: 'error',
2307
+ message: err && err.message ? err.message : String(err)
2308
+ });
2309
+ }
2310
+ throw err;
2311
+ }
2312
+ }
2313
+
2296
2314
  // =========================================================================
2297
2315
  // Package Management Helpers (npm / bun virtual modules & scripts)
2298
2316
  // =========================================================================
@@ -2391,6 +2409,15 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2391
2409
 
2392
2410
  function pickConditionalEntry(value) {
2393
2411
  if (typeof value === 'string') return value;
2412
+ // `exports` subpaths may be an array of fallbacks, e.g.
2413
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
2414
+ if (Array.isArray(value)) {
2415
+ for (const item of value) {
2416
+ const picked = pickConditionalEntry(item);
2417
+ if (picked) return picked;
2418
+ }
2419
+ return null;
2420
+ }
2394
2421
  if (!value || typeof value !== 'object') return null;
2395
2422
  // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2396
2423
  for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
@@ -2447,17 +2474,50 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2447
2474
  return parts.join('/');
2448
2475
  }
2449
2476
 
2477
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
2478
+ // immediate resolve if `setTimeout` is unavailable in the host.
2479
+ function cdnBackoff(ms) {
2480
+ return new Promise((resolve) => {
2481
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
2482
+ else resolve();
2483
+ });
2484
+ }
2485
+
2450
2486
  async function fetchTextFromCdn(fetchImpl, url) {
2451
- try {
2452
- const res = await fetchImpl(url);
2453
- if (!res) return null;
2454
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2455
- if (!ok) return null;
2456
- if (typeof res.text === 'function') return await res.text();
2457
- return String(res.body != null ? res.body : '');
2458
- } catch (_) {
2459
- return null;
2487
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
2488
+ // install (the module graph then failed at require-time). Retry transient
2489
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
2490
+ const maxAttempts = 3;
2491
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2492
+ try {
2493
+ const res = await fetchImpl(url);
2494
+ if (!res) {
2495
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2496
+ return null;
2497
+ }
2498
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2499
+ if (!ok) {
2500
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
2501
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2502
+ return null;
2503
+ }
2504
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
2505
+ // and an HTML directory listing. Storing that as a module both corrupts the
2506
+ // package and later collides with the real directory (EISDIR).
2507
+ const contentType = (res.headers && typeof res.headers.get === 'function')
2508
+ ? (res.headers.get('content-type') || '')
2509
+ : '';
2510
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
2511
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
2512
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
2513
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
2514
+ return text;
2515
+ } catch (_) {
2516
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2517
+ return null;
2518
+ }
2460
2519
  }
2520
+ return null;
2461
2521
  }
2462
2522
 
2463
2523
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -2500,14 +2560,25 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2500
2560
  const visited = new Set();
2501
2561
  // Seed with the package entry plus any declared `exports` subpaths, so a
2502
2562
  // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2503
- const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2563
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
2564
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
2565
+ // too or the package installs with only its manifest.
2566
+ const seed = [
2567
+ entry,
2568
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
2569
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
2570
+ ];
2504
2571
  const expMap = meta.exports;
2505
2572
  if (expMap && typeof expMap === 'object') {
2506
- let subCount = 0;
2573
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
2574
+ // packages that list each file in `exports` (lit-html has 29 keys, so
2575
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
2576
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
2577
+ // the relative-require closure or fetched on demand.
2507
2578
  for (const key of Object.keys(expMap)) {
2508
- if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2579
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
2509
2580
  const target = pickConditionalEntry(expMap[key]);
2510
- if (target) { seed.push(target); subCount++; }
2581
+ if (target) seed.push(target);
2511
2582
  }
2512
2583
  }
2513
2584
  let frontier = seed;
@@ -2515,7 +2586,9 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2515
2586
  const batch = [];
2516
2587
  for (const raw of frontier) {
2517
2588
  const rel = stripRelPath(raw);
2518
- if (!rel || visited.has(rel)) continue;
2589
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
2590
+ // be fetched as files — that is what produced the EISDIR crash.
2591
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
2519
2592
  visited.add(rel);
2520
2593
  batch.push(rel);
2521
2594
  }
@@ -2551,15 +2624,29 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2551
2624
  }
2552
2625
 
2553
2626
  // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2554
- // so e.g. `npm install react-dom` also pulls in `react`.
2555
- const depNames = Object.keys(meta.dependencies || {});
2627
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
2628
+ // preserved (not just the names) so transitives resolve to the version the
2629
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2630
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
2631
+ // the tree (ansi-styles@6 has no deps at all).
2632
+ const depSpecs = [];
2633
+ const depSeen = new Set();
2634
+ const declared = meta.dependencies || {};
2635
+ for (const depName of Object.keys(declared)) {
2636
+ if (depSeen.has(depName)) continue;
2637
+ depSeen.add(depName);
2638
+ depSpecs.push({ name: depName, range: declared[depName] || null });
2639
+ }
2556
2640
  const peerMeta = meta.peerDependenciesMeta || {};
2557
- for (const peer of Object.keys(meta.peerDependencies || {})) {
2641
+ const peers = meta.peerDependencies || {};
2642
+ for (const peer of Object.keys(peers)) {
2558
2643
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
2559
- if (depNames.indexOf(peer) === -1) depNames.push(peer);
2644
+ if (depSeen.has(peer)) continue;
2645
+ depSeen.add(peer);
2646
+ depSpecs.push({ name: peer, range: peers[peer] || null });
2560
2647
  }
2561
2648
 
2562
- return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2649
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2563
2650
  }
2564
2651
 
2565
2652
  function installTargetDirs(ctx, name) {
@@ -2573,7 +2660,13 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2573
2660
  for (const dir of dirs) {
2574
2661
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2575
2662
  for (const f of info.files) {
2663
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
2576
2664
  const full = PosixPath.join(dir, f.rel);
2665
+ // Never overwrite a directory with a file body (defensive: a stray
2666
+ // directory target would otherwise raise EISDIR).
2667
+ try {
2668
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2669
+ } catch (_) {}
2577
2670
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2578
2671
  ctx.vfs.writeFileSync(full, f.content);
2579
2672
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -2639,10 +2732,11 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2639
2732
  if (item.direct) directVersion = info.version || null;
2640
2733
 
2641
2734
  for (const dep of (info.deps || [])) {
2642
- const parsed = parsePackageSpec(dep);
2643
- if (parsed.name && !requested.has(parsed.name)) {
2644
- requested.add(parsed.name);
2645
- queue.push({ name: parsed.name, range: null, direct: false });
2735
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
2736
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
2737
+ if (depName && !requested.has(depName)) {
2738
+ requested.add(depName);
2739
+ queue.push({ name: depName, range: depRange || null, direct: false });
2646
2740
  }
2647
2741
  }
2648
2742
  }
@@ -2999,21 +3093,29 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2999
3093
  // Common dev-server commands that cannot run inside the virtual runtime are
3000
3094
  // transparently redirected to the built-in preview server.
3001
3095
  const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3096
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
3097
+ // `serve` is omitted: it is a first-class builtin shell command.
3098
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
3002
3099
 
3003
- function tryDevScriptFallback(scriptName, cmd, ctx) {
3100
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
3004
3101
  if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3005
3102
  // Only fall back when the referenced tool is not actually installed.
3006
3103
  const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3104
+ const force = Boolean(opts && opts.force);
3007
3105
  const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3008
- if (ctx.vfs.existsSync(binPath)) return null;
3106
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
3009
3107
  const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3010
3108
  const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3011
3109
  const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3012
- const entry = registerPreviewServer(ctx, ctx.cwd, port);
3110
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
3111
+ const entry = registerPreviewServer(ctx, rootDir, port);
3013
3112
  if (!entry) return null;
3113
+ const note = force
3114
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
3115
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
3014
3116
  return {
3015
3117
  code: 0,
3016
- 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`,
3118
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3017
3119
  stderr: ''
3018
3120
  };
3019
3121
  }
@@ -7112,6 +7214,13 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
7112
7214
  Object.assign(context.env, this.env);
7113
7215
  context.cwd = this.cwd;
7114
7216
  }
7217
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
7218
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
7219
+ // this runtime — whether or not it was installed — so route it to the
7220
+ // built-in preview server rather than reporting a misleading "command
7221
+ // not found".
7222
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
7223
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
7115
7224
  } else if (typeof this.options.onProcessSpawn === 'function') {
7116
7225
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
7117
7226
  cwd: this.cwd,
@@ -7183,6 +7292,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
7183
7292
  };
7184
7293
  });
7185
7294
 
7295
+
7186
7296
  })();
7187
7297
 
7188
7298
  const CodeLabShell = _root.CodeLabShell;
package/dist/shell.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.7 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -17,6 +17,7 @@
17
17
  (function (root) {
18
18
  'use strict';
19
19
  (function () {
20
+ // @ts-nocheck
20
21
  /**
21
22
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
22
23
  *
@@ -2004,7 +2005,7 @@
2004
2005
  return 10 + depth * 0.1;
2005
2006
  }
2006
2007
 
2007
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2008
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
2008
2009
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2009
2010
  if (onProgress) {
2010
2011
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -2294,6 +2295,23 @@
2294
2295
  };
2295
2296
  }
2296
2297
 
2298
+ // Public wrapper: guarantee an `error` progress event when the clone fails
2299
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
2300
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2301
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2302
+ try {
2303
+ return await _cloneGitHubRepository(repoInput, vfs, options);
2304
+ } catch (err) {
2305
+ if (onProgress) {
2306
+ onProgress({
2307
+ phase: 'error',
2308
+ message: err && err.message ? err.message : String(err)
2309
+ });
2310
+ }
2311
+ throw err;
2312
+ }
2313
+ }
2314
+
2297
2315
  // =========================================================================
2298
2316
  // Package Management Helpers (npm / bun virtual modules & scripts)
2299
2317
  // =========================================================================
@@ -2392,6 +2410,15 @@
2392
2410
 
2393
2411
  function pickConditionalEntry(value) {
2394
2412
  if (typeof value === 'string') return value;
2413
+ // `exports` subpaths may be an array of fallbacks, e.g.
2414
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
2415
+ if (Array.isArray(value)) {
2416
+ for (const item of value) {
2417
+ const picked = pickConditionalEntry(item);
2418
+ if (picked) return picked;
2419
+ }
2420
+ return null;
2421
+ }
2395
2422
  if (!value || typeof value !== 'object') return null;
2396
2423
  // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2397
2424
  for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
@@ -2448,17 +2475,50 @@
2448
2475
  return parts.join('/');
2449
2476
  }
2450
2477
 
2478
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
2479
+ // immediate resolve if `setTimeout` is unavailable in the host.
2480
+ function cdnBackoff(ms) {
2481
+ return new Promise((resolve) => {
2482
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
2483
+ else resolve();
2484
+ });
2485
+ }
2486
+
2451
2487
  async function fetchTextFromCdn(fetchImpl, url) {
2452
- try {
2453
- const res = await fetchImpl(url);
2454
- if (!res) return null;
2455
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2456
- if (!ok) return null;
2457
- if (typeof res.text === 'function') return await res.text();
2458
- return String(res.body != null ? res.body : '');
2459
- } catch (_) {
2460
- return null;
2488
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
2489
+ // install (the module graph then failed at require-time). Retry transient
2490
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
2491
+ const maxAttempts = 3;
2492
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2493
+ try {
2494
+ const res = await fetchImpl(url);
2495
+ if (!res) {
2496
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2497
+ return null;
2498
+ }
2499
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2500
+ if (!ok) {
2501
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
2502
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2503
+ return null;
2504
+ }
2505
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
2506
+ // and an HTML directory listing. Storing that as a module both corrupts the
2507
+ // package and later collides with the real directory (EISDIR).
2508
+ const contentType = (res.headers && typeof res.headers.get === 'function')
2509
+ ? (res.headers.get('content-type') || '')
2510
+ : '';
2511
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
2512
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
2513
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
2514
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
2515
+ return text;
2516
+ } catch (_) {
2517
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2518
+ return null;
2519
+ }
2461
2520
  }
2521
+ return null;
2462
2522
  }
2463
2523
 
2464
2524
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -2501,14 +2561,25 @@
2501
2561
  const visited = new Set();
2502
2562
  // Seed with the package entry plus any declared `exports` subpaths, so a
2503
2563
  // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2504
- const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2564
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
2565
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
2566
+ // too or the package installs with only its manifest.
2567
+ const seed = [
2568
+ entry,
2569
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
2570
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
2571
+ ];
2505
2572
  const expMap = meta.exports;
2506
2573
  if (expMap && typeof expMap === 'object') {
2507
- let subCount = 0;
2574
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
2575
+ // packages that list each file in `exports` (lit-html has 29 keys, so
2576
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
2577
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
2578
+ // the relative-require closure or fetched on demand.
2508
2579
  for (const key of Object.keys(expMap)) {
2509
- if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2580
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
2510
2581
  const target = pickConditionalEntry(expMap[key]);
2511
- if (target) { seed.push(target); subCount++; }
2582
+ if (target) seed.push(target);
2512
2583
  }
2513
2584
  }
2514
2585
  let frontier = seed;
@@ -2516,7 +2587,9 @@
2516
2587
  const batch = [];
2517
2588
  for (const raw of frontier) {
2518
2589
  const rel = stripRelPath(raw);
2519
- if (!rel || visited.has(rel)) continue;
2590
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
2591
+ // be fetched as files — that is what produced the EISDIR crash.
2592
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
2520
2593
  visited.add(rel);
2521
2594
  batch.push(rel);
2522
2595
  }
@@ -2552,15 +2625,29 @@
2552
2625
  }
2553
2626
 
2554
2627
  // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2555
- // so e.g. `npm install react-dom` also pulls in `react`.
2556
- const depNames = Object.keys(meta.dependencies || {});
2628
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
2629
+ // preserved (not just the names) so transitives resolve to the version the
2630
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2631
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
2632
+ // the tree (ansi-styles@6 has no deps at all).
2633
+ const depSpecs = [];
2634
+ const depSeen = new Set();
2635
+ const declared = meta.dependencies || {};
2636
+ for (const depName of Object.keys(declared)) {
2637
+ if (depSeen.has(depName)) continue;
2638
+ depSeen.add(depName);
2639
+ depSpecs.push({ name: depName, range: declared[depName] || null });
2640
+ }
2557
2641
  const peerMeta = meta.peerDependenciesMeta || {};
2558
- for (const peer of Object.keys(meta.peerDependencies || {})) {
2642
+ const peers = meta.peerDependencies || {};
2643
+ for (const peer of Object.keys(peers)) {
2559
2644
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
2560
- if (depNames.indexOf(peer) === -1) depNames.push(peer);
2645
+ if (depSeen.has(peer)) continue;
2646
+ depSeen.add(peer);
2647
+ depSpecs.push({ name: peer, range: peers[peer] || null });
2561
2648
  }
2562
2649
 
2563
- return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2650
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2564
2651
  }
2565
2652
 
2566
2653
  function installTargetDirs(ctx, name) {
@@ -2574,7 +2661,13 @@
2574
2661
  for (const dir of dirs) {
2575
2662
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2576
2663
  for (const f of info.files) {
2664
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
2577
2665
  const full = PosixPath.join(dir, f.rel);
2666
+ // Never overwrite a directory with a file body (defensive: a stray
2667
+ // directory target would otherwise raise EISDIR).
2668
+ try {
2669
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2670
+ } catch (_) {}
2578
2671
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2579
2672
  ctx.vfs.writeFileSync(full, f.content);
2580
2673
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -2640,10 +2733,11 @@
2640
2733
  if (item.direct) directVersion = info.version || null;
2641
2734
 
2642
2735
  for (const dep of (info.deps || [])) {
2643
- const parsed = parsePackageSpec(dep);
2644
- if (parsed.name && !requested.has(parsed.name)) {
2645
- requested.add(parsed.name);
2646
- queue.push({ name: parsed.name, range: null, direct: false });
2736
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
2737
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
2738
+ if (depName && !requested.has(depName)) {
2739
+ requested.add(depName);
2740
+ queue.push({ name: depName, range: depRange || null, direct: false });
2647
2741
  }
2648
2742
  }
2649
2743
  }
@@ -3000,21 +3094,29 @@
3000
3094
  // Common dev-server commands that cannot run inside the virtual runtime are
3001
3095
  // transparently redirected to the built-in preview server.
3002
3096
  const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3097
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
3098
+ // `serve` is omitted: it is a first-class builtin shell command.
3099
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
3003
3100
 
3004
- function tryDevScriptFallback(scriptName, cmd, ctx) {
3101
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
3005
3102
  if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3006
3103
  // Only fall back when the referenced tool is not actually installed.
3007
3104
  const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3105
+ const force = Boolean(opts && opts.force);
3008
3106
  const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3009
- if (ctx.vfs.existsSync(binPath)) return null;
3107
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
3010
3108
  const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3011
3109
  const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3012
3110
  const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3013
- const entry = registerPreviewServer(ctx, ctx.cwd, port);
3111
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
3112
+ const entry = registerPreviewServer(ctx, rootDir, port);
3014
3113
  if (!entry) return null;
3114
+ const note = force
3115
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
3116
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
3015
3117
  return {
3016
3118
  code: 0,
3017
- 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`,
3119
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3018
3120
  stderr: ''
3019
3121
  };
3020
3122
  }
@@ -7113,6 +7215,13 @@
7113
7215
  Object.assign(context.env, this.env);
7114
7216
  context.cwd = this.cwd;
7115
7217
  }
7218
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
7219
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
7220
+ // this runtime — whether or not it was installed — so route it to the
7221
+ // built-in preview server rather than reporting a misleading "command
7222
+ // not found".
7223
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
7224
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
7116
7225
  } else if (typeof this.options.onProcessSpawn === 'function') {
7117
7226
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
7118
7227
  cwd: this.cwd,
@@ -7184,6 +7293,7 @@
7184
7293
  };
7185
7294
  });
7186
7295
 
7296
+
7187
7297
  })();
7188
7298
 
7189
7299
  if (typeof module !== 'undefined' && module.exports) {