@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/README.md +1 -1
- package/dist/code-lab.css +78 -31
- package/dist/code-lab.d.ts +3 -1
- package/dist/code-lab.esm.js +507 -114
- package/dist/code-lab.js +507 -114
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.esm.js +48 -3
- package/dist/runtime.js +48 -3
- package/dist/shell.esm.js +295 -40
- package/dist/shell.js +295 -40
- package/package.json +1 -1
- package/src/code-lab.css +78 -31
- package/src/runtime.js +48 -3
- package/src/runtime.ts +53 -4
- package/src/shell.js +295 -40
- package/src/shell.ts +295 -40
- package/src/workbench.js +164 -71
- package/src/workbench.ts +164 -71
package/src/runtime.js
CHANGED
|
@@ -4661,8 +4661,22 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4661
4661
|
}
|
|
4662
4662
|
|
|
4663
4663
|
const _npmPackageCache = new Map();
|
|
4664
|
+
const _npmMetadataCache = new Map();
|
|
4665
|
+
|
|
4666
|
+
async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
|
|
4667
|
+
// The 2nd/3rd arguments are overloaded for backwards compatibility:
|
|
4668
|
+
// preloadNpmPackages(files)
|
|
4669
|
+
// preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
|
|
4670
|
+
// preloadNpmPackages(files, existingCache) // package-text cache (Map)
|
|
4671
|
+
// preloadNpmPackages(files, existingCache, onProgress)
|
|
4672
|
+
const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
|
|
4673
|
+
let onProgress = null;
|
|
4674
|
+
let existingCache = _npmPackageCache;
|
|
4675
|
+
if (typeof secondArg === 'function') onProgress = secondArg;
|
|
4676
|
+
else if (isCacheLike(secondArg)) existingCache = secondArg;
|
|
4677
|
+
if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
|
|
4678
|
+
else if (isCacheLike(thirdArg)) existingCache = thirdArg;
|
|
4664
4679
|
|
|
4665
|
-
async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
|
|
4666
4680
|
const specs = new Set();
|
|
4667
4681
|
const builtinSet = new Set([
|
|
4668
4682
|
'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
|
|
@@ -4698,20 +4712,51 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4698
4712
|
while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
|
|
4699
4713
|
}
|
|
4700
4714
|
|
|
4715
|
+
// Follow declared dependencies transitively (best effort, bounded). Metadata
|
|
4716
|
+
// is memoised across calls so repeated preloads stay cheap.
|
|
4717
|
+
if (typeof fetch === 'function') {
|
|
4718
|
+
let pass = 0;
|
|
4719
|
+
while (pass < 6) {
|
|
4720
|
+
const pending = [];
|
|
4721
|
+
for (const pkg of specs) {
|
|
4722
|
+
if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
|
|
4723
|
+
}
|
|
4724
|
+
if (pending.length === 0) break;
|
|
4725
|
+
pass++;
|
|
4726
|
+
await Promise.all(pending.map(async (pkg) => {
|
|
4727
|
+
let deps = [];
|
|
4728
|
+
try {
|
|
4729
|
+
const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
|
|
4730
|
+
if (res && res.ok) {
|
|
4731
|
+
const meta = await res.json();
|
|
4732
|
+
deps = Object.keys((meta && meta.dependencies) || {});
|
|
4733
|
+
}
|
|
4734
|
+
} catch (_) {}
|
|
4735
|
+
_npmMetadataCache.set(pkg, deps);
|
|
4736
|
+
}));
|
|
4737
|
+
for (const pkg of pending) {
|
|
4738
|
+
for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
|
|
4739
|
+
}
|
|
4740
|
+
}
|
|
4741
|
+
}
|
|
4742
|
+
|
|
4701
4743
|
const loaded = {};
|
|
4702
4744
|
for (const pkg of specs) {
|
|
4703
4745
|
const nmKey = `node_modules/${pkg}/index.js`;
|
|
4704
4746
|
if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
|
|
4705
|
-
if (existingCache
|
|
4747
|
+
if (existingCache.has(pkg)) {
|
|
4706
4748
|
loaded[pkg] = existingCache.get(pkg);
|
|
4707
4749
|
continue;
|
|
4708
4750
|
}
|
|
4751
|
+
if (typeof onProgress === 'function') {
|
|
4752
|
+
try { onProgress(pkg); } catch (_) {}
|
|
4753
|
+
}
|
|
4709
4754
|
if (typeof fetch === 'function') {
|
|
4710
4755
|
try {
|
|
4711
4756
|
const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
|
|
4712
4757
|
if (res && res.ok) {
|
|
4713
4758
|
const text = await res.text();
|
|
4714
|
-
if (existingCache) existingCache.set(pkg, text);
|
|
4759
|
+
if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
|
|
4715
4760
|
loaded[pkg] = text;
|
|
4716
4761
|
}
|
|
4717
4762
|
} catch (_) {}
|
package/src/runtime.ts
CHANGED
|
@@ -4662,8 +4662,22 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4662
4662
|
}
|
|
4663
4663
|
|
|
4664
4664
|
const _npmPackageCache = new Map();
|
|
4665
|
+
const _npmMetadataCache = new Map();
|
|
4666
|
+
|
|
4667
|
+
async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
|
|
4668
|
+
// The 2nd/3rd arguments are overloaded for backwards compatibility:
|
|
4669
|
+
// preloadNpmPackages(files)
|
|
4670
|
+
// preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
|
|
4671
|
+
// preloadNpmPackages(files, existingCache) // package-text cache (Map)
|
|
4672
|
+
// preloadNpmPackages(files, existingCache, onProgress)
|
|
4673
|
+
const isCacheLike = (v: any) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
|
|
4674
|
+
let onProgress: any = null;
|
|
4675
|
+
let existingCache: any = _npmPackageCache;
|
|
4676
|
+
if (typeof secondArg === 'function') onProgress = secondArg;
|
|
4677
|
+
else if (isCacheLike(secondArg)) existingCache = secondArg;
|
|
4678
|
+
if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
|
|
4679
|
+
else if (isCacheLike(thirdArg)) existingCache = thirdArg;
|
|
4665
4680
|
|
|
4666
|
-
async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
|
|
4667
4681
|
const specs = new Set();
|
|
4668
4682
|
const builtinSet = new Set([
|
|
4669
4683
|
'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
|
|
@@ -4699,20 +4713,51 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4699
4713
|
while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
|
|
4700
4714
|
}
|
|
4701
4715
|
|
|
4716
|
+
// Follow declared dependencies transitively (best effort, bounded). Metadata
|
|
4717
|
+
// is memoised across calls so repeated preloads stay cheap.
|
|
4718
|
+
if (typeof fetch === 'function') {
|
|
4719
|
+
let pass = 0;
|
|
4720
|
+
while (pass < 6) {
|
|
4721
|
+
const pending: string[] = [];
|
|
4722
|
+
for (const pkg of specs) {
|
|
4723
|
+
if (!_npmMetadataCache.has(pkg)) pending.push(pkg as string);
|
|
4724
|
+
}
|
|
4725
|
+
if (pending.length === 0) break;
|
|
4726
|
+
pass++;
|
|
4727
|
+
await Promise.all(pending.map(async (pkg) => {
|
|
4728
|
+
let deps: string[] = [];
|
|
4729
|
+
try {
|
|
4730
|
+
const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
|
|
4731
|
+
if (res && res.ok) {
|
|
4732
|
+
const meta = await res.json();
|
|
4733
|
+
deps = Object.keys((meta && meta.dependencies) || {});
|
|
4734
|
+
}
|
|
4735
|
+
} catch (_) {}
|
|
4736
|
+
_npmMetadataCache.set(pkg, deps);
|
|
4737
|
+
}));
|
|
4738
|
+
for (const pkg of pending) {
|
|
4739
|
+
for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
|
|
4740
|
+
}
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
|
|
4702
4744
|
const loaded = {};
|
|
4703
4745
|
for (const pkg of specs) {
|
|
4704
4746
|
const nmKey = `node_modules/${pkg}/index.js`;
|
|
4705
4747
|
if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
|
|
4706
|
-
if (existingCache
|
|
4748
|
+
if (existingCache.has(pkg)) {
|
|
4707
4749
|
loaded[pkg] = existingCache.get(pkg);
|
|
4708
4750
|
continue;
|
|
4709
4751
|
}
|
|
4752
|
+
if (typeof onProgress === 'function') {
|
|
4753
|
+
try { onProgress(pkg); } catch (_) {}
|
|
4754
|
+
}
|
|
4710
4755
|
if (typeof fetch === 'function') {
|
|
4711
4756
|
try {
|
|
4712
4757
|
const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
|
|
4713
4758
|
if (res && res.ok) {
|
|
4714
4759
|
const text = await res.text();
|
|
4715
|
-
if (existingCache) existingCache.set(pkg, text);
|
|
4760
|
+
if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
|
|
4716
4761
|
loaded[pkg] = text;
|
|
4717
4762
|
}
|
|
4718
4763
|
} catch (_) {}
|
|
@@ -7502,7 +7547,11 @@ export const createVirtualFs: (options?: any) => any = _hostRuntime.createVirtua
|
|
|
7502
7547
|
export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _hostRuntime.createVirtualHttp;
|
|
7503
7548
|
export const createVirtualNet: (portTable?: any) => any = _hostRuntime.createVirtualNet;
|
|
7504
7549
|
export const transpileTS: (code: string, filename?: string) => string = _hostRuntime.transpileTS;
|
|
7505
|
-
export const preloadNpmPackages: (
|
|
7550
|
+
export const preloadNpmPackages: (
|
|
7551
|
+
files?: Record<string, any>,
|
|
7552
|
+
onProgressOrCache?: ((pkg: string) => void) | Map<string, string>,
|
|
7553
|
+
onProgress?: (pkg: string) => void
|
|
7554
|
+
) => Promise<Record<string, string>> = _hostRuntime.preloadNpmPackages;
|
|
7506
7555
|
export const createVirtualPortTable: () => any = _hostRuntime.createVirtualPortTable;
|
|
7507
7556
|
export const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInVirtualRuntime;
|
|
7508
7557
|
export const createWorkerRuntimeSource: () => string = _hostRuntime.createWorkerRuntimeSource;
|
package/src/shell.js
CHANGED
|
@@ -2009,6 +2009,16 @@
|
|
|
2009
2009
|
const requestedBranch = options.branch || parsed.branch || null;
|
|
2010
2010
|
const { owner, repo } = parsed;
|
|
2011
2011
|
|
|
2012
|
+
const signal = options.signal || null;
|
|
2013
|
+
const throwIfAborted = () => {
|
|
2014
|
+
if (signal && signal.aborted) {
|
|
2015
|
+
const abortErr = new Error('fatal: clone cancelled (SIGINT)');
|
|
2016
|
+
abortErr.name = 'AbortError';
|
|
2017
|
+
throw abortErr;
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
throwIfAborted();
|
|
2021
|
+
|
|
2012
2022
|
let resolvedBranch = requestedBranch;
|
|
2013
2023
|
let rawTreeEntries = null;
|
|
2014
2024
|
let repoNotFound = false;
|
|
@@ -2021,7 +2031,8 @@
|
|
|
2021
2031
|
try {
|
|
2022
2032
|
if (!resolvedBranch) {
|
|
2023
2033
|
const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
|
|
2024
|
-
headers: { Accept: 'application/vnd.github.v3+json' }
|
|
2034
|
+
headers: { Accept: 'application/vnd.github.v3+json' },
|
|
2035
|
+
signal
|
|
2025
2036
|
});
|
|
2026
2037
|
if (metaRes.status === 404) {
|
|
2027
2038
|
repoNotFound = true;
|
|
@@ -2039,9 +2050,10 @@
|
|
|
2039
2050
|
: Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
|
|
2040
2051
|
|
|
2041
2052
|
for (const cand of branchCandidates) {
|
|
2053
|
+
throwIfAborted();
|
|
2042
2054
|
const treeRes = await fetchFn(
|
|
2043
2055
|
`https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
|
|
2044
|
-
{ headers: { Accept: 'application/vnd.github.v3+json' } }
|
|
2056
|
+
{ headers: { Accept: 'application/vnd.github.v3+json' }, signal }
|
|
2045
2057
|
);
|
|
2046
2058
|
if (treeRes.ok) {
|
|
2047
2059
|
const treeJson = await treeRes.json();
|
|
@@ -2067,8 +2079,10 @@
|
|
|
2067
2079
|
: Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
|
|
2068
2080
|
|
|
2069
2081
|
for (const cand of branchCandidates) {
|
|
2082
|
+
throwIfAborted();
|
|
2070
2083
|
const flatRes = await fetchFn(
|
|
2071
|
-
`https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat
|
|
2084
|
+
`https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
|
|
2085
|
+
{ signal }
|
|
2072
2086
|
);
|
|
2073
2087
|
if (flatRes && flatRes.ok) {
|
|
2074
2088
|
const flatJson = await flatRes.json();
|
|
@@ -2137,28 +2151,34 @@
|
|
|
2137
2151
|
const BATCH_SIZE = 12;
|
|
2138
2152
|
|
|
2139
2153
|
for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
|
|
2154
|
+
throwIfAborted();
|
|
2140
2155
|
const batch = selectedFiles.slice(i, i + BATCH_SIZE);
|
|
2141
2156
|
await Promise.all(
|
|
2142
2157
|
batch.map(async (entry) => {
|
|
2158
|
+
throwIfAborted();
|
|
2143
2159
|
const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
|
|
2144
2160
|
const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
|
|
2145
2161
|
const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
|
|
2146
2162
|
|
|
2147
2163
|
let text = null;
|
|
2148
2164
|
try {
|
|
2149
|
-
const r1 = await fetchFn(rawUrl);
|
|
2165
|
+
const r1 = await fetchFn(rawUrl, { signal });
|
|
2150
2166
|
if (r1 && r1.ok) {
|
|
2151
2167
|
text = await r1.text();
|
|
2152
2168
|
}
|
|
2153
|
-
} catch (_) {
|
|
2169
|
+
} catch (_) {
|
|
2170
|
+
if (signal && signal.aborted) throw _;
|
|
2171
|
+
}
|
|
2154
2172
|
|
|
2155
2173
|
if (text === null) {
|
|
2156
2174
|
try {
|
|
2157
|
-
const r2 = await fetchFn(cdnUrl);
|
|
2175
|
+
const r2 = await fetchFn(cdnUrl, { signal });
|
|
2158
2176
|
if (r2 && r2.ok) {
|
|
2159
2177
|
text = await r2.text();
|
|
2160
2178
|
}
|
|
2161
|
-
} catch (_) {
|
|
2179
|
+
} catch (_) {
|
|
2180
|
+
if (signal && signal.aborted) throw _;
|
|
2181
|
+
}
|
|
2162
2182
|
}
|
|
2163
2183
|
|
|
2164
2184
|
if (text !== null && text.length <= maxFileSize) {
|
|
@@ -2182,6 +2202,8 @@
|
|
|
2182
2202
|
);
|
|
2183
2203
|
}
|
|
2184
2204
|
|
|
2205
|
+
throwIfAborted();
|
|
2206
|
+
|
|
2185
2207
|
if (onProgress) {
|
|
2186
2208
|
onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
|
|
2187
2209
|
}
|
|
@@ -2202,7 +2224,7 @@
|
|
|
2202
2224
|
try {
|
|
2203
2225
|
const commitsRes = await fetchFn(
|
|
2204
2226
|
`https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
|
|
2205
|
-
{ headers: { Accept: 'application/vnd.github.v3+json' } }
|
|
2227
|
+
{ headers: { Accept: 'application/vnd.github.v3+json' }, signal }
|
|
2206
2228
|
);
|
|
2207
2229
|
if (commitsRes && commitsRes.ok) {
|
|
2208
2230
|
const commitsJson = await commitsRes.json();
|
|
@@ -2314,38 +2336,221 @@
|
|
|
2314
2336
|
} catch (_) {}
|
|
2315
2337
|
}
|
|
2316
2338
|
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2339
|
+
// ---------------------------------------------------------------------------
|
|
2340
|
+
// Real npm package installation via the jsDelivr CDN
|
|
2341
|
+
// ---------------------------------------------------------------------------
|
|
2342
|
+
const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2343
|
+
|
|
2344
|
+
// Minimal offline registry, used only when the CDN is unreachable so common
|
|
2345
|
+
// demos still resolve without network access.
|
|
2346
|
+
const OFFLINE_PACKAGE_FALLBACKS = {
|
|
2347
|
+
'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
|
|
2348
|
+
'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
|
|
2349
|
+
'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
|
|
2350
|
+
'left-pad': 'module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };\n'
|
|
2351
|
+
};
|
|
2352
|
+
|
|
2353
|
+
function packageCtxFetch(ctx) {
|
|
2354
|
+
if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
|
|
2355
|
+
return ctx.shell.options.fetchImpl;
|
|
2356
|
+
}
|
|
2357
|
+
if (typeof fetch === 'function') return fetch.bind(globalThis);
|
|
2358
|
+
return null;
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
function parsePackageSpec(spec) {
|
|
2362
|
+
const raw = String(spec || '').trim();
|
|
2363
|
+
if (!raw) return { name: '', range: null };
|
|
2364
|
+
if (raw.startsWith('@')) {
|
|
2365
|
+
const at = raw.indexOf('@', 1);
|
|
2366
|
+
if (at === -1) return { name: raw, range: null };
|
|
2367
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2368
|
+
}
|
|
2369
|
+
const at = raw.indexOf('@');
|
|
2370
|
+
if (at <= 0) return { name: raw, range: null };
|
|
2371
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
function resolveEntryRelPath(pkgJson) {
|
|
2375
|
+
let entry = pkgJson.main || pkgJson.module ||
|
|
2376
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2377
|
+
entry = String(entry).replace(/^[./]+/, '');
|
|
2378
|
+
return entry || 'index.js';
|
|
2379
|
+
}
|
|
2380
|
+
|
|
2381
|
+
function stripRelPath(rel) {
|
|
2382
|
+
return String(rel || '').replace(/^[./]+/, '');
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
function extractRelativeSpecifiers(code) {
|
|
2386
|
+
const out = new Set();
|
|
2387
|
+
const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
|
|
2388
|
+
let m;
|
|
2389
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2390
|
+
return Array.from(out);
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
function normalizeRelPath(baseDir, rel) {
|
|
2394
|
+
const parts = String(baseDir || '').split('/').filter(Boolean);
|
|
2395
|
+
for (const seg of String(rel).split('/')) {
|
|
2396
|
+
if (!seg || seg === '.') continue;
|
|
2397
|
+
if (seg === '..') parts.pop();
|
|
2398
|
+
else parts.push(seg);
|
|
2399
|
+
}
|
|
2400
|
+
return parts.join('/');
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2404
|
+
try {
|
|
2405
|
+
const res = await fetchImpl(url);
|
|
2406
|
+
if (!res) return null;
|
|
2407
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2408
|
+
if (!ok) return null;
|
|
2409
|
+
if (typeof res.text === 'function') return await res.text();
|
|
2410
|
+
return String(res.body != null ? res.body : '');
|
|
2411
|
+
} catch (_) {
|
|
2412
|
+
return null;
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
2417
|
+
const urls = range
|
|
2418
|
+
? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
|
|
2419
|
+
: [`${CDN_NPM_BASE}/${name}/package.json`];
|
|
2420
|
+
for (const url of urls) {
|
|
2421
|
+
const text = await fetchTextFromCdn(fetchImpl, url);
|
|
2422
|
+
if (!text) continue;
|
|
2423
|
+
try {
|
|
2424
|
+
const parsed = JSON.parse(text);
|
|
2425
|
+
if (parsed && parsed.version) return parsed;
|
|
2426
|
+
} catch (_) {}
|
|
2427
|
+
}
|
|
2428
|
+
return null;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
// Download a package's entry module, its relative submodules and record its
|
|
2432
|
+
// declared dependencies so the caller can resolve them transitively.
|
|
2433
|
+
async function downloadPackageFiles(fetchImpl, name, range, seen) {
|
|
2434
|
+
const meta = await resolvePackageMetadata(fetchImpl, name, range);
|
|
2435
|
+
if (!meta) {
|
|
2436
|
+
const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
|
|
2437
|
+
if (fallback) {
|
|
2438
|
+
const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
|
|
2439
|
+
return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
|
|
2440
|
+
}
|
|
2441
|
+
return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
const version = meta.version;
|
|
2445
|
+
const key = `${name}@${version}`;
|
|
2446
|
+
if (seen.has(key)) {
|
|
2447
|
+
return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
|
|
2448
|
+
}
|
|
2449
|
+
seen.add(key);
|
|
2450
|
+
|
|
2451
|
+
const entry = resolveEntryRelPath(meta);
|
|
2452
|
+
const files = [];
|
|
2453
|
+
const visited = new Set();
|
|
2454
|
+
const queue = [entry];
|
|
2455
|
+
while (queue.length > 0) {
|
|
2456
|
+
const rel = stripRelPath(queue.shift());
|
|
2457
|
+
if (!rel || visited.has(rel)) continue;
|
|
2458
|
+
visited.add(rel);
|
|
2459
|
+
const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
|
|
2460
|
+
if (text === null) continue;
|
|
2461
|
+
files.push({ rel, content: text });
|
|
2462
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2463
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2464
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2465
|
+
for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
|
|
2466
|
+
const c = stripRelPath(cand);
|
|
2467
|
+
if (c && !visited.has(c)) { queue.push(cand); break; }
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
// The declared entry may be missing on the CDN; fall back to index.js.
|
|
2472
|
+
if (!files.some(f => f.rel === entry)) {
|
|
2473
|
+
const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
|
|
2474
|
+
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
|
|
2478
|
+
}
|
|
2479
|
+
|
|
2480
|
+
function installTargetDirs(ctx, name) {
|
|
2481
|
+
const dirs = ['/workspace/node_modules/' + name];
|
|
2482
|
+
const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
|
|
2483
|
+
if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
|
|
2484
|
+
return dirs;
|
|
2485
|
+
}
|
|
2486
|
+
|
|
2487
|
+
function writeInstalledPackageFiles(ctx, dirs, name, info) {
|
|
2488
|
+
for (const dir of dirs) {
|
|
2489
|
+
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2490
|
+
for (const f of info.files) {
|
|
2491
|
+
const full = PosixPath.join(dir, f.rel);
|
|
2492
|
+
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2493
|
+
ctx.vfs.writeFileSync(full, f.content);
|
|
2494
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2495
|
+
}
|
|
2496
|
+
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2497
|
+
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2498
|
+
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2499
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
async function installPackage(pkgSpec, ctx) {
|
|
2504
|
+
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2505
|
+
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2321
2506
|
|
|
2322
2507
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2323
2508
|
if (!pkgData.dependencies) pkgData.dependencies = {};
|
|
2324
|
-
pkgData.dependencies[pkgName] = pkgVersion;
|
|
2325
|
-
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2326
2509
|
|
|
2327
|
-
const
|
|
2328
|
-
const
|
|
2329
|
-
|
|
2510
|
+
const fetchImpl = packageCtxFetch(ctx);
|
|
2511
|
+
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
2512
|
+
? ctx.shell._cdnSeen
|
|
2513
|
+
: (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
|
|
2514
|
+
|
|
2515
|
+
const queue = [{ name: pkgName, range, direct: true }];
|
|
2516
|
+
const requested = new Set([pkgName]);
|
|
2517
|
+
const installed = [];
|
|
2518
|
+
let warning = null;
|
|
2519
|
+
let directVersion = null;
|
|
2520
|
+
|
|
2521
|
+
while (queue.length > 0) {
|
|
2522
|
+
const item = queue.shift();
|
|
2523
|
+
const info = fetchImpl
|
|
2524
|
+
? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
|
|
2525
|
+
: { ok: false, reason: `${item.name}: no fetch implementation available` };
|
|
2526
|
+
|
|
2527
|
+
if (!info.ok) {
|
|
2528
|
+
// Final fallback: an empty stub so offline demos still resolve the module.
|
|
2529
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
|
|
2530
|
+
version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
|
|
2531
|
+
});
|
|
2532
|
+
if (!warning) warning = info.reason;
|
|
2533
|
+
installed.push({ name: item.name, version: '0.0.0' });
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2330
2536
|
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
const modIndexPath = PosixPath.join(modDir, 'index.js');
|
|
2335
|
-
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
|
|
2336
|
-
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2537
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2538
|
+
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2539
|
+
if (item.direct) directVersion = info.version || null;
|
|
2337
2540
|
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
|
|
2541
|
+
for (const dep of (info.deps || [])) {
|
|
2542
|
+
const parsed = parsePackageSpec(dep);
|
|
2543
|
+
if (parsed.name && !requested.has(parsed.name)) {
|
|
2544
|
+
requested.add(parsed.name);
|
|
2545
|
+
queue.push({ name: parsed.name, range: null, direct: false });
|
|
2546
|
+
}
|
|
2345
2547
|
}
|
|
2346
|
-
ctx.vfs.writeFileSync(modIndexPath, code);
|
|
2347
|
-
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
|
|
2348
2548
|
}
|
|
2549
|
+
|
|
2550
|
+
pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
|
|
2551
|
+
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2552
|
+
|
|
2553
|
+
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2349
2554
|
}
|
|
2350
2555
|
|
|
2351
2556
|
function uninstallPackage(pkgName, ctx) {
|
|
@@ -4449,6 +4654,7 @@
|
|
|
4449
4654
|
targetDir,
|
|
4450
4655
|
branch: branchOpt,
|
|
4451
4656
|
fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
|
|
4657
|
+
signal: ctx.signal,
|
|
4452
4658
|
onFile: (absPath) => ctx.emitMutation('create', absPath),
|
|
4453
4659
|
onProgress: (ev) => {
|
|
4454
4660
|
if (!ev) return;
|
|
@@ -4489,6 +4695,9 @@
|
|
|
4489
4695
|
`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
|
|
4490
4696
|
return { code: 0, stdout, stderr: '' };
|
|
4491
4697
|
} catch (err) {
|
|
4698
|
+
if (ctx.signal && ctx.signal.aborted) {
|
|
4699
|
+
return { code: 130, stdout: '', stderr: '', aborted: true };
|
|
4700
|
+
}
|
|
4492
4701
|
const msg = err && err.message ? err.message : String(err);
|
|
4493
4702
|
if (canStream) streamLine(msg.endsWith('\n') ? msg : msg + '\n');
|
|
4494
4703
|
return { code: 128, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
|
|
@@ -4816,6 +5025,7 @@
|
|
|
4816
5025
|
targetDir: repoRoot,
|
|
4817
5026
|
branch: gitState.branch,
|
|
4818
5027
|
fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
|
|
5028
|
+
signal: ctx.signal,
|
|
4819
5029
|
onFile: (absPath) => ctx.emitMutation('change', absPath)
|
|
4820
5030
|
});
|
|
4821
5031
|
gitState.headSnapshot = Object.assign({}, result.headSnapshot);
|
|
@@ -4825,6 +5035,9 @@
|
|
|
4825
5035
|
stderr: ''
|
|
4826
5036
|
};
|
|
4827
5037
|
} catch (err) {
|
|
5038
|
+
if (ctx.signal && ctx.signal.aborted) {
|
|
5039
|
+
return { code: 130, stdout: '', stderr: '', aborted: true };
|
|
5040
|
+
}
|
|
4828
5041
|
const msg = err && err.message ? err.message : String(err);
|
|
4829
5042
|
return { code: 1, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
|
|
4830
5043
|
}
|
|
@@ -5014,6 +5227,18 @@
|
|
|
5014
5227
|
|
|
5015
5228
|
const sub = args[0];
|
|
5016
5229
|
|
|
5230
|
+
if (sub === '--version' || sub === '-v' || sub === '--revision') {
|
|
5231
|
+
return { code: 0, stdout: '1.1.20\n', stderr: '' };
|
|
5232
|
+
}
|
|
5233
|
+
|
|
5234
|
+
if (sub === '--help' || sub === '-h') {
|
|
5235
|
+
return {
|
|
5236
|
+
code: 0,
|
|
5237
|
+
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',
|
|
5238
|
+
stderr: ''
|
|
5239
|
+
};
|
|
5240
|
+
}
|
|
5241
|
+
|
|
5017
5242
|
if (sub === 'init') {
|
|
5018
5243
|
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5019
5244
|
const dirName = PosixPath.basename(ctx.cwd) || 'app';
|
|
@@ -5063,12 +5288,28 @@
|
|
|
5063
5288
|
return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
|
|
5064
5289
|
}
|
|
5065
5290
|
|
|
5066
|
-
if (sub === '
|
|
5291
|
+
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5067
5292
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5068
|
-
|
|
5069
|
-
|
|
5293
|
+
if (pkgs.length === 0) {
|
|
5294
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5295
|
+
const deps = Object.keys(pkgData.dependencies || {});
|
|
5296
|
+
const results = [];
|
|
5297
|
+
for (const p of deps) results.push(await installPackage(p, ctx));
|
|
5298
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5299
|
+
return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
5070
5300
|
}
|
|
5071
|
-
|
|
5301
|
+
const results = [];
|
|
5302
|
+
for (const p of pkgs) results.push(await installPackage(p, ctx));
|
|
5303
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5304
|
+
return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
5305
|
+
}
|
|
5306
|
+
|
|
5307
|
+
if (sub === 'add') {
|
|
5308
|
+
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5309
|
+
const results = [];
|
|
5310
|
+
for (const p of pkgs) results.push(await installPackage(p, ctx));
|
|
5311
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5312
|
+
return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
5072
5313
|
}
|
|
5073
5314
|
|
|
5074
5315
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5231,15 +5472,19 @@
|
|
|
5231
5472
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5232
5473
|
if (pkgs.length === 0) {
|
|
5233
5474
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5475
|
+
const results = [];
|
|
5234
5476
|
for (const p of Object.keys(pkgData.dependencies || {})) {
|
|
5235
|
-
installPackage(p, ctx);
|
|
5477
|
+
results.push(await installPackage(p, ctx));
|
|
5236
5478
|
}
|
|
5237
|
-
|
|
5479
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5480
|
+
return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
5238
5481
|
}
|
|
5482
|
+
const results = [];
|
|
5239
5483
|
for (const p of pkgs) {
|
|
5240
|
-
installPackage(p, ctx);
|
|
5484
|
+
results.push(await installPackage(p, ctx));
|
|
5241
5485
|
}
|
|
5242
|
-
|
|
5486
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
5487
|
+
return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
5243
5488
|
}
|
|
5244
5489
|
|
|
5245
5490
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5464,6 +5709,16 @@
|
|
|
5464
5709
|
return PosixPath.resolve(this.cwd, p);
|
|
5465
5710
|
}
|
|
5466
5711
|
|
|
5712
|
+
// True when `name` resolves to a shell function or coreutil (used by the
|
|
5713
|
+
// workbench to route recognised commands straight to the shell instead of
|
|
5714
|
+
// treating flag-looking input such as `node --version` as a JS expression).
|
|
5715
|
+
hasCommand(name) {
|
|
5716
|
+
if (!name) return false;
|
|
5717
|
+
const n = String(name);
|
|
5718
|
+
if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
|
|
5719
|
+
return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
|
|
5720
|
+
}
|
|
5721
|
+
|
|
5467
5722
|
_emitVfsMutation(type, absPath) {
|
|
5468
5723
|
if (!this.vfs) return;
|
|
5469
5724
|
const evt = { type, path: absPath, timestamp: Date.now() };
|