@innovatorved/code-lab 0.1.6 → 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/src/shell.ts CHANGED
@@ -1,64 +1,55 @@
1
1
  // @ts-nocheck
2
- 'use strict';
3
2
  /**
4
- * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils (TypeScript)
3
+ * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
5
4
  *
6
5
  * Full-fidelity, CSP-safe POSIX shell AST interpreter and 35+ standard UNIX
7
6
  * coreutils operating directly on the in-memory virtual filesystem (VFS).
8
7
  *
8
+ * Capabilities:
9
+ * - Deterministic lexer and AST parser (zero dynamic eval, zero new Function)
10
+ * - Pipelines (cmd1 | cmd2 | cmd3) with streaming stdin/stdout chaining
11
+ * - Output redirection (>, >>, 1>, 2>, 2>&1, 1>&2, &>)
12
+ * - Input redirection (<, 0<)
13
+ * - Logical operators (&&, ||, ;)
14
+ * - Background job execution (cmd &) with job table & PID tracking
15
+ * - Variable expansion ($VAR, ${VAR}, ${VAR:-def}, $?, $PWD, $HOME, $USER)
16
+ * - Command substitution ($(cmd), `cmd`)
17
+ * - Glob expansion (*.js, src/**\/*.ts, [0-9]*.txt) against VFS
18
+ * - 40+ UNIX coreutils (ls, cd, pwd, cat, head, tail, grep, find, wc, sort, uniq,
19
+ * sed, awk, cut, tr, diff, tree, cp, mv, rm, mkdir, touch, chmod, stat, echo,
20
+ * printf, env, export, unset, which, whoami, uname, date, sleep, true, false,
21
+ * clear, history, ps, jobs, kill, git, help, dirname, basename, seq, tee)
22
+ * - Bidirectional VFS mutation bridge (touch, mkdir, rm, mv, cp, echo >, sed -i)
23
+ *
9
24
  * (C) 2026 InnovatorVed / CodeLab. MIT License.
10
25
  */
11
26
 
12
- import type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions } from './schemas.js';
13
-
14
- export type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions };
15
-
16
- export interface CloneResult {
17
- owner: string;
18
- repo: string;
19
- branch: string;
20
- url: string;
21
- targetDir: string;
22
- count: number;
23
- fileCount: number;
24
- filesWritten: number;
25
- totalBytes: number;
26
- commits: Array<{ hash: string; author: string; date: string; message: string }>;
27
- headSnapshot: Record<string, string>;
28
- }
29
-
30
- export interface ShellExecResult {
31
- code: number;
32
- exitCode?: number;
33
- ok?: boolean;
34
- stdout: string;
35
- stderr: string;
36
- controlFlow?: { type: string; count?: number; code?: number };
37
- aborted?: boolean;
38
- }
39
-
40
- export interface ShellExecOptions {
41
- cwd?: string;
42
- env?: Record<string, string>;
43
- vfs?: any;
44
- portTable?: any;
45
- onStdout?: (chunk: string) => void;
46
- onStderr?: (chunk: string) => void;
47
- stdin?: string;
48
- fetchImpl?: any;
49
- onProgress?: (event: CloneProgressEvent) => void;
50
- signal?: AbortSignal;
51
- }
52
-
53
- function __initShellModule(root: any) {
54
-
27
+ (function (root, factory) {
28
+ const exports = factory(root);
29
+ if (root) {
30
+ root.CodeLabShell = exports;
31
+ root.createPosixShell = exports.createPosixShell;
32
+ root.PosixShell = exports.PosixShell;
33
+ root.parseShellCommand = exports.parseShellCommand;
34
+ root.tokenizeShell = exports.tokenizeShell;
35
+ root.COREUTILS = exports.COREUTILS;
36
+ root.createVirtualPortTable = exports.createVirtualPortTable;
37
+ root.parseGitHubRepoUrl = exports.parseGitHubRepoUrl;
38
+ root.cloneGitHubRepository = exports.cloneGitHubRepository;
39
+ }
40
+ if (typeof module !== 'undefined' && module.exports) {
41
+ module.exports = exports;
42
+ } else if (typeof define === 'function' && define.amd) {
43
+ define([], function () { return exports; });
44
+ }
45
+ })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
55
46
  'use strict';
56
47
 
57
48
  function getRuntimeModule() {
58
49
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
59
50
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
60
51
  try {
61
- if (typeof require !== 'undefined') { try { return require('./runtime.js'); } catch (_) {} try { return require('./runtime'); } catch (_) {} try { return require('../dist/runtime.js'); } catch (_) {} }
52
+ if (typeof require !== 'undefined') return require('./runtime.js');
62
53
  } catch (_) {}
63
54
  return null;
64
55
  }
@@ -1995,325 +1986,302 @@ function __initShellModule(root: any) {
1995
1986
  return 10 + depth * 0.1;
1996
1987
  }
1997
1988
 
1998
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
1989
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
1999
1990
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
1991
+ if (onProgress) {
1992
+ onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
1993
+ }
1994
+ const parsed = parseGitHubRepoUrl(repoInput);
1995
+ if (!parsed) {
1996
+ throw new Error(`fatal: repository '${repoInput}' does not exist or is not a valid GitHub repository URL`);
1997
+ }
1998
+ if (!vfs) {
1999
+ throw new Error('fatal: virtual filesystem (vfs) is required to clone repository');
2000
+ }
2000
2001
 
2001
- try {
2002
- if (onProgress) {
2003
- onProgress({
2004
- phase: 'connecting',
2005
- message: `Connecting to repository '${repoInput}'...`
2006
- });
2007
- }
2002
+ const fetchFn = options.fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
2003
+ if (!fetchFn) {
2004
+ throw new Error('fatal: global fetch API is unavailable in this environment');
2005
+ }
2008
2006
 
2009
- const parsed = parseGitHubRepoUrl(repoInput);
2010
- if (!parsed) {
2011
- throw new Error(`fatal: repository '${repoInput}' does not exist or is not a valid GitHub repository URL`);
2012
- }
2013
- if (!vfs) {
2014
- throw new Error('fatal: virtual filesystem (vfs) is required to clone repository');
2015
- }
2007
+ const targetDir = PosixPath.normalize(options.targetDir || '/workspace');
2008
+ const maxFiles = options.maxFiles || 250;
2009
+ const maxFileSize = options.maxFileSize || 512 * 1024;
2010
+ const requestedBranch = options.branch || parsed.branch || null;
2011
+ const { owner, repo } = parsed;
2016
2012
 
2017
- const fetchFn = options.fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
2018
- if (!fetchFn) {
2019
- throw new Error('fatal: global fetch API is unavailable in this environment');
2013
+ const signal = options.signal || null;
2014
+ const throwIfAborted = () => {
2015
+ if (signal && signal.aborted) {
2016
+ const abortErr = new Error('fatal: clone cancelled (SIGINT)');
2017
+ abortErr.name = 'AbortError';
2018
+ throw abortErr;
2020
2019
  }
2020
+ };
2021
+ throwIfAborted();
2021
2022
 
2022
- const targetDir = PosixPath.normalize(options.targetDir || '/workspace');
2023
- const maxFiles = options.maxFiles || 250;
2024
- const maxFileSize = options.maxFileSize || 512 * 1024;
2025
- const requestedBranch = options.branch || parsed.branch || null;
2026
- const { owner, repo } = parsed;
2023
+ let resolvedBranch = requestedBranch;
2024
+ let rawTreeEntries = null;
2025
+ let repoNotFound = false;
2027
2026
 
2028
- const signal = options.signal || null;
2029
- const throwIfAborted = () => {
2030
- if (signal && signal.aborted) {
2031
- const abortErr = new Error('fatal: clone cancelled (SIGINT)');
2032
- abortErr.name = 'AbortError';
2033
- throw abortErr;
2034
- }
2035
- };
2036
- throwIfAborted();
2027
+ if (onProgress) {
2028
+ onProgress({ phase: 'metadata', message: `Fetching repository metadata for ${owner}/${repo}...` });
2029
+ }
2037
2030
 
2038
- if (onProgress) {
2039
- onProgress({
2040
- phase: 'metadata',
2041
- message: `Fetching repository metadata for ${owner}/${repo}...`
2031
+ // Strategy A: GitHub REST API (with automatic fallback if rate-limited)
2032
+ try {
2033
+ if (!resolvedBranch) {
2034
+ const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2035
+ headers: { Accept: 'application/vnd.github.v3+json' },
2036
+ signal
2042
2037
  });
2043
- }
2044
-
2045
- let resolvedBranch = requestedBranch;
2046
- let rawTreeEntries = null;
2047
- let repoNotFound = false;
2048
-
2049
- // Strategy A: GitHub REST API (with automatic fallback if rate-limited)
2050
- try {
2051
- if (!resolvedBranch) {
2052
- const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2053
- headers: { Accept: 'application/vnd.github.v3+json' },
2054
- signal
2055
- });
2056
- if (metaRes.status === 404) {
2057
- repoNotFound = true;
2058
- } else if (metaRes.ok) {
2059
- const metaJson = await metaRes.json();
2060
- if (metaJson && metaJson.default_branch) {
2061
- resolvedBranch = metaJson.default_branch;
2062
- }
2063
- }
2064
- }
2065
-
2066
- if (!repoNotFound) {
2067
- const branchCandidates = requestedBranch
2068
- ? [requestedBranch]
2069
- : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2070
-
2071
- for (const cand of branchCandidates) {
2072
- throwIfAborted();
2073
- const treeRes = await fetchFn(
2074
- `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2075
- { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2076
- );
2077
- if (treeRes.ok) {
2078
- const treeJson = await treeRes.json();
2079
- if (treeJson && Array.isArray(treeJson.tree)) {
2080
- resolvedBranch = cand;
2081
- rawTreeEntries = treeJson.tree
2082
- .filter((item) => item && item.type === 'blob' && item.path)
2083
- .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
2084
- break;
2085
- }
2038
+ if (metaRes.status === 404) {
2039
+ repoNotFound = true;
2040
+ } else if (metaRes.ok) {
2041
+ const metaJson = await metaRes.json();
2042
+ if (metaJson && metaJson.default_branch) {
2043
+ resolvedBranch = metaJson.default_branch;
2044
+ }
2045
+ }
2046
+ }
2047
+
2048
+ if (!repoNotFound) {
2049
+ const branchCandidates = requestedBranch
2050
+ ? [requestedBranch]
2051
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2052
+
2053
+ for (const cand of branchCandidates) {
2054
+ throwIfAborted();
2055
+ const treeRes = await fetchFn(
2056
+ `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2057
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2058
+ );
2059
+ if (treeRes.ok) {
2060
+ const treeJson = await treeRes.json();
2061
+ if (treeJson && Array.isArray(treeJson.tree)) {
2062
+ resolvedBranch = cand;
2063
+ rawTreeEntries = treeJson.tree
2064
+ .filter((item) => item && item.type === 'blob' && item.path)
2065
+ .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
2066
+ break;
2086
2067
  }
2087
2068
  }
2088
2069
  }
2089
- } catch (_) {
2090
- // Network or rate limit error on api.github.com; proceed to Strategy B
2091
2070
  }
2071
+ } catch (_) {
2072
+ // Network or rate limit error on api.github.com; proceed to Strategy B
2073
+ }
2092
2074
 
2093
- // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
2094
- if (!rawTreeEntries && !repoNotFound) {
2095
- try {
2096
- const branchCandidates = requestedBranch
2097
- ? [requestedBranch]
2098
- : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2099
-
2100
- for (const cand of branchCandidates) {
2101
- throwIfAborted();
2102
- const flatRes = await fetchFn(
2103
- `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2104
- { signal }
2105
- );
2106
- if (flatRes && flatRes.ok) {
2107
- const flatJson = await flatRes.json();
2108
- if (flatJson && Array.isArray(flatJson.files) && flatJson.files.length > 0) {
2109
- resolvedBranch = cand;
2110
- rawTreeEntries = flatJson.files
2111
- .filter((f) => f && f.name)
2112
- .map((f) => ({ path: f.name.replace(/^\/+/, ''), size: f.size || 0 }));
2113
- break;
2114
- }
2075
+ // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
2076
+ if (!rawTreeEntries && !repoNotFound) {
2077
+ try {
2078
+ const branchCandidates = requestedBranch
2079
+ ? [requestedBranch]
2080
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2081
+
2082
+ for (const cand of branchCandidates) {
2083
+ throwIfAborted();
2084
+ const flatRes = await fetchFn(
2085
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2086
+ { signal }
2087
+ );
2088
+ if (flatRes && flatRes.ok) {
2089
+ const flatJson = await flatRes.json();
2090
+ if (flatJson && Array.isArray(flatJson.files) && flatJson.files.length > 0) {
2091
+ resolvedBranch = cand;
2092
+ rawTreeEntries = flatJson.files
2093
+ .filter((f) => f && f.name)
2094
+ .map((f) => ({ path: f.name.replace(/^\/+/, ''), size: f.size || 0 }));
2095
+ break;
2115
2096
  }
2116
2097
  }
2117
- } catch (_) {}
2118
- }
2098
+ }
2099
+ } catch (_) {}
2100
+ }
2119
2101
 
2120
- if (repoNotFound || !rawTreeEntries) {
2121
- throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2122
- }
2102
+ if (repoNotFound || !rawTreeEntries) {
2103
+ throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2104
+ }
2123
2105
 
2124
- // Filter subpath if specified (e.g. /tree/main/examples)
2125
- const subPrefix = parsed.subpath ? parsed.subpath.replace(/^\/+|\/+$/g, '') + '/' : null;
2126
- const filtered = [];
2127
- for (const item of rawTreeEntries) {
2128
- let destPath = item.path;
2129
- if (subPrefix) {
2130
- if (item.path === parsed.subpath) {
2131
- destPath = PosixPath.basename(item.path);
2132
- } else if (item.path.startsWith(subPrefix)) {
2133
- destPath = item.path.slice(subPrefix.length);
2134
- } else {
2135
- continue;
2136
- }
2137
- }
2138
- if (!destPath || destPath.startsWith('.git/') || destPath.includes('/node_modules/') || destPath.startsWith('node_modules/')) {
2139
- continue;
2140
- }
2141
- if (BINARY_OR_HEAVY_EXT_RE.test(destPath)) {
2142
- continue;
2143
- }
2144
- if (item.size && item.size > maxFileSize) {
2106
+ // Filter subpath if specified (e.g. /tree/main/examples)
2107
+ const subPrefix = parsed.subpath ? parsed.subpath.replace(/^\/+|\/+$/g, '') + '/' : null;
2108
+ const filtered = [];
2109
+ for (const item of rawTreeEntries) {
2110
+ let destPath = item.path;
2111
+ if (subPrefix) {
2112
+ if (item.path === parsed.subpath) {
2113
+ destPath = PosixPath.basename(item.path);
2114
+ } else if (item.path.startsWith(subPrefix)) {
2115
+ destPath = item.path.slice(subPrefix.length);
2116
+ } else {
2145
2117
  continue;
2146
2118
  }
2147
- filtered.push({
2148
- repoPath: item.path,
2149
- destPath,
2150
- size: item.size || 0,
2151
- priority: scoreRepoFilePriority(destPath)
2152
- });
2153
2119
  }
2120
+ if (!destPath || destPath.startsWith('.git/') || destPath.includes('/node_modules/') || destPath.startsWith('node_modules/')) {
2121
+ continue;
2122
+ }
2123
+ if (BINARY_OR_HEAVY_EXT_RE.test(destPath)) {
2124
+ continue;
2125
+ }
2126
+ if (item.size && item.size > maxFileSize) {
2127
+ continue;
2128
+ }
2129
+ filtered.push({
2130
+ repoPath: item.path,
2131
+ destPath,
2132
+ size: item.size || 0,
2133
+ priority: scoreRepoFilePriority(destPath)
2134
+ });
2135
+ }
2154
2136
 
2155
- filtered.sort((a, b) => a.priority - b.priority || a.destPath.localeCompare(b.destPath));
2156
- const selectedFiles = filtered.slice(0, maxFiles);
2157
- const totalToDownload = selectedFiles.length;
2137
+ filtered.sort((a, b) => a.priority - b.priority || a.destPath.localeCompare(b.destPath));
2138
+ const selectedFiles = filtered.slice(0, maxFiles);
2139
+ const totalToDownload = selectedFiles.length;
2158
2140
 
2159
- if (onProgress) {
2160
- onProgress({
2161
- phase: 'downloading',
2162
- message: `Downloading files (0/${totalToDownload})...`,
2163
- loaded: 0,
2164
- total: totalToDownload
2165
- });
2166
- }
2141
+ if (onProgress) {
2142
+ onProgress({ phase: 'downloading', message: `Downloading files (0/${totalToDownload})...`, loaded: 0, total: totalToDownload });
2143
+ }
2167
2144
 
2168
- if (!vfs.existsSync(targetDir)) {
2169
- vfs.mkdirSync(targetDir, { recursive: true });
2170
- }
2145
+ if (!vfs.existsSync(targetDir)) {
2146
+ vfs.mkdirSync(targetDir, { recursive: true });
2147
+ }
2171
2148
 
2172
- const headSnapshot = {};
2173
- let filesWritten = 0;
2174
- let totalBytes = 0;
2175
- const BATCH_SIZE = 12;
2149
+ const headSnapshot = {};
2150
+ let filesWritten = 0;
2151
+ let totalBytes = 0;
2152
+ const BATCH_SIZE = 12;
2176
2153
 
2177
- for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2178
- throwIfAborted();
2179
- const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2180
- await Promise.all(
2181
- batch.map(async (entry) => {
2182
- throwIfAborted();
2183
- const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2184
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2185
- const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2154
+ for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2155
+ throwIfAborted();
2156
+ const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2157
+ await Promise.all(
2158
+ batch.map(async (entry) => {
2159
+ throwIfAborted();
2160
+ const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2161
+ const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2162
+ const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2163
+
2164
+ let text = null;
2165
+ try {
2166
+ const r1 = await fetchFn(rawUrl, { signal });
2167
+ if (r1 && r1.ok) {
2168
+ text = await r1.text();
2169
+ }
2170
+ } catch (_) {
2171
+ if (signal && signal.aborted) throw _;
2172
+ }
2186
2173
 
2187
- let text = null;
2174
+ if (text === null) {
2188
2175
  try {
2189
- const r1 = await fetchFn(rawUrl, { signal });
2190
- if (r1 && r1.ok) {
2191
- text = await r1.text();
2176
+ const r2 = await fetchFn(cdnUrl, { signal });
2177
+ if (r2 && r2.ok) {
2178
+ text = await r2.text();
2192
2179
  }
2193
2180
  } catch (_) {
2194
2181
  if (signal && signal.aborted) throw _;
2195
2182
  }
2183
+ }
2196
2184
 
2197
- if (text === null) {
2198
- try {
2199
- const r2 = await fetchFn(cdnUrl, { signal });
2200
- if (r2 && r2.ok) {
2201
- text = await r2.text();
2202
- }
2203
- } catch (_) {
2204
- if (signal && signal.aborted) throw _;
2205
- }
2185
+ if (text !== null && text.length <= maxFileSize) {
2186
+ const absPath = PosixPath.join(targetDir, entry.destPath);
2187
+ const parentDir = PosixPath.dirname(absPath);
2188
+ if (!vfs.existsSync(parentDir)) {
2189
+ vfs.mkdirSync(parentDir, { recursive: true });
2206
2190
  }
2207
-
2208
- if (text !== null && text.length <= maxFileSize) {
2209
- const absPath = PosixPath.join(targetDir, entry.destPath);
2210
- const parentDir = PosixPath.dirname(absPath);
2211
- if (!vfs.existsSync(parentDir)) {
2212
- vfs.mkdirSync(parentDir, { recursive: true });
2213
- }
2214
- vfs.writeFileSync(absPath, text);
2215
- headSnapshot[entry.destPath] = text;
2216
- filesWritten++;
2217
- totalBytes += text.length;
2218
-
2219
- if (onProgress) {
2220
- onProgress({
2221
- phase: 'downloading',
2222
- message: `Downloading files (${filesWritten}/${totalToDownload}): ${entry.destPath}`,
2223
- loaded: filesWritten,
2224
- total: totalToDownload
2225
- });
2226
- }
2227
-
2228
- if (typeof options.onFile === 'function') {
2229
- options.onFile(absPath, text, entry.destPath);
2230
- }
2191
+ vfs.writeFileSync(absPath, text);
2192
+ headSnapshot[entry.destPath] = text;
2193
+ filesWritten++;
2194
+ totalBytes += text.length;
2195
+ if (onProgress) {
2196
+ onProgress({ phase: 'downloading', message: `Downloading files (${filesWritten}/${totalToDownload}): ${entry.destPath}`, loaded: filesWritten, total: totalToDownload });
2231
2197
  }
2232
- })
2233
- );
2234
- }
2198
+ if (typeof options.onFile === 'function') {
2199
+ options.onFile(absPath, text, entry.destPath);
2200
+ }
2201
+ }
2202
+ })
2203
+ );
2204
+ }
2235
2205
 
2236
- throwIfAborted();
2206
+ throwIfAborted();
2237
2207
 
2238
- if (onProgress) {
2239
- onProgress({
2240
- phase: 'mounting',
2241
- message: `Mounting files and writing Git metadata into ${targetDir}...`,
2242
- loaded: filesWritten,
2243
- total: totalToDownload
2244
- });
2245
- }
2208
+ if (onProgress) {
2209
+ onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
2210
+ }
2246
2211
 
2247
- // Write .git metadata inside targetDir
2248
- const gitDir = PosixPath.join(targetDir, '.git');
2249
- if (!vfs.existsSync(gitDir)) {
2250
- vfs.mkdirSync(gitDir, { recursive: true });
2251
- }
2252
- vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${resolvedBranch}\n`);
2253
- vfs.writeFileSync(
2254
- PosixPath.join(gitDir, 'config'),
2255
- `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n[remote "origin"]\n\turl = ${parsed.url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[branch "${resolvedBranch}"]\n\tremote = origin\n\tmerge = refs/heads/${resolvedBranch}\n`
2212
+ // Write .git metadata inside targetDir
2213
+ const gitDir = PosixPath.join(targetDir, '.git');
2214
+ if (!vfs.existsSync(gitDir)) {
2215
+ vfs.mkdirSync(gitDir, { recursive: true });
2216
+ }
2217
+ vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${resolvedBranch}\n`);
2218
+ vfs.writeFileSync(
2219
+ PosixPath.join(gitDir, 'config'),
2220
+ `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n[remote "origin"]\n\turl = ${parsed.url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[branch "${resolvedBranch}"]\n\tremote = origin\n\tmerge = refs/heads/${resolvedBranch}\n`
2221
+ );
2222
+
2223
+ // Fetch recent commits (best-effort)
2224
+ let commits = [];
2225
+ try {
2226
+ const commitsRes = await fetchFn(
2227
+ `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2228
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2256
2229
  );
2230
+ if (commitsRes && commitsRes.ok) {
2231
+ const commitsJson = await commitsRes.json();
2232
+ if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2233
+ commits = commitsJson.map((c) => ({
2234
+ hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2235
+ author:
2236
+ c.commit && c.commit.author
2237
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2238
+ : `${owner} <${owner}@users.noreply.github.com>`,
2239
+ date:
2240
+ c.commit && c.commit.author && c.commit.author.date
2241
+ ? new Date(c.commit.author.date).toUTCString()
2242
+ : new Date().toUTCString(),
2243
+ message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2244
+ }));
2245
+ }
2246
+ }
2247
+ } catch (_) {}
2257
2248
 
2258
- // Fetch recent commits (best-effort)
2259
- let commits = [];
2260
- try {
2261
- const commitsRes = await fetchFn(
2262
- `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2263
- { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2264
- );
2265
- if (commitsRes && commitsRes.ok) {
2266
- const commitsJson = await commitsRes.json();
2267
- if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2268
- commits = commitsJson.map((c) => ({
2269
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2270
- author:
2271
- c.commit && c.commit.author
2272
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2273
- : `${owner} <${owner}@users.noreply.github.com>`,
2274
- date:
2275
- c.commit && c.commit.author && c.commit.author.date
2276
- ? new Date(c.commit.author.date).toUTCString()
2277
- : new Date().toUTCString(),
2278
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2279
- }));
2280
- }
2249
+ if (commits.length === 0) {
2250
+ commits = [
2251
+ {
2252
+ hash: 'a1b2c3d',
2253
+ author: `${owner} <${owner}@users.noreply.github.com>`,
2254
+ date: new Date().toUTCString(),
2255
+ message: `Clone ${owner}/${repo} (${resolvedBranch})`
2281
2256
  }
2282
- } catch (_) {}
2257
+ ];
2258
+ }
2283
2259
 
2284
- if (commits.length === 0) {
2285
- commits = [
2286
- {
2287
- hash: 'a1b2c3d',
2288
- author: `${owner} <${owner}@users.noreply.github.com>`,
2289
- date: new Date().toUTCString(),
2290
- message: `Clone ${owner}/${repo} (${resolvedBranch})`
2291
- }
2292
- ];
2293
- }
2260
+ if (onProgress) {
2261
+ onProgress({ phase: 'ready', message: `Repository cloned successfully (${filesWritten} files).`, loaded: filesWritten, total: totalToDownload });
2262
+ }
2294
2263
 
2295
- if (onProgress) {
2296
- onProgress({
2297
- phase: 'ready',
2298
- message: `Repository cloned successfully (${filesWritten} files).`,
2299
- loaded: filesWritten,
2300
- total: totalToDownload
2301
- });
2302
- }
2264
+ return {
2265
+ owner,
2266
+ repo,
2267
+ branch: resolvedBranch,
2268
+ url: parsed.url,
2269
+ targetDir,
2270
+ count: filesWritten,
2271
+ fileCount: filesWritten,
2272
+ filesWritten,
2273
+ totalBytes,
2274
+ commits,
2275
+ headSnapshot
2276
+ };
2277
+ }
2303
2278
 
2304
- return {
2305
- owner,
2306
- repo,
2307
- branch: resolvedBranch,
2308
- url: parsed.url,
2309
- targetDir,
2310
- count: filesWritten,
2311
- fileCount: filesWritten,
2312
- filesWritten,
2313
- totalBytes,
2314
- commits,
2315
- headSnapshot
2316
- };
2279
+ // Public wrapper: guarantee an `error` progress event when the clone fails
2280
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
2281
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2282
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2283
+ try {
2284
+ return await _cloneGitHubRepository(repoInput, vfs, options);
2317
2285
  } catch (err) {
2318
2286
  if (onProgress) {
2319
2287
  onProgress({
@@ -2643,16 +2611,16 @@ function __initShellModule(root: any) {
2643
2611
  // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2644
2612
  // needs color-convert. Resolving transitive names as "latest" silently breaks
2645
2613
  // the tree (ansi-styles@6 has no deps at all).
2646
- const depSpecs: Array<{ name: string; range: string | null }> = [];
2647
- const depSeen = new Set<string>();
2648
- const declared = (meta.dependencies || {}) as Record<string, string>;
2614
+ const depSpecs = [];
2615
+ const depSeen = new Set();
2616
+ const declared = meta.dependencies || {};
2649
2617
  for (const depName of Object.keys(declared)) {
2650
2618
  if (depSeen.has(depName)) continue;
2651
2619
  depSeen.add(depName);
2652
2620
  depSpecs.push({ name: depName, range: declared[depName] || null });
2653
2621
  }
2654
2622
  const peerMeta = meta.peerDependenciesMeta || {};
2655
- const peers = (meta.peerDependencies || {}) as Record<string, string>;
2623
+ const peers = meta.peerDependencies || {};
2656
2624
  for (const peer of Object.keys(peers)) {
2657
2625
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
2658
2626
  if (depSeen.has(peer)) continue;
@@ -7304,17 +7272,11 @@ function __initShellModule(root: any) {
7304
7272
  parseGitHubRepoUrl,
7305
7273
  cloneGitHubRepository
7306
7274
  };
7275
+ });
7307
7276
 
7308
- }
7309
-
7310
- const _hostShell: any = __initShellModule(typeof globalThis !== 'undefined' ? globalThis : this);
7311
-
7312
- if (typeof globalThis !== 'undefined') {
7313
- (globalThis as any).CodeLabShell = _hostShell;
7314
- }
7315
- if (typeof module !== 'undefined' && module.exports) {
7316
- module.exports = _hostShell;
7317
- }
7277
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
7278
+ const _hostShell: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabShell : undefined)
7279
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
7318
7280
 
7319
7281
  export const createPosixShell: (options?: any) => any = _hostShell.createPosixShell;
7320
7282
  export const parseShellCommand: (cmd: string) => any = _hostShell.parseShellCommand;
@@ -7325,7 +7287,7 @@ export const PosixPath: any = _hostShell.PosixPath;
7325
7287
  export const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[] = _hostShell.expandGlob;
7326
7288
  export const createVirtualPortTable: () => any = _hostShell.createVirtualPortTable;
7327
7289
  export const parseGitHubRepoUrl: (input: string) => any = _hostShell.parseGitHubRepoUrl;
7328
- export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: GitHubCloneOptions) => Promise<CloneResult> = _hostShell.cloneGitHubRepository;
7290
+ export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any> = _hostShell.cloneGitHubRepository;
7329
7291
  export const CodeLabShell: any = _hostShell;
7330
7292
 
7331
7293
  export default _hostShell;