@vite-hub/sandbox 0.0.4 → 0.1.0
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 +327 -34
- package/dist/cloudflare-DO0h3Ncf.js +281 -0
- package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
- package/dist/crabbox-BFCdf41h.js +1106 -0
- package/dist/error-diagnostics-BSysPv-D.js +166 -0
- package/dist/error-diagnostics-dGQqfgLt.js +99 -0
- package/dist/file-listing-DECFTdSl.js +26 -0
- package/dist/file-lock-CxyVl4Cv.js +73 -0
- package/dist/index-CXej1Bt0.d.ts +519 -0
- package/dist/index.d.ts +2 -69
- package/dist/index.js +277 -1183
- package/dist/internal/cloudflare.d.ts +4 -0
- package/dist/internal/cloudflare.js +16 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +97 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +16 -0
- package/dist/module-types-BfyRBaiP.js +7 -0
- package/dist/module-types-Cis4hrF1.d.ts +95 -0
- package/dist/remote-1Jz2oUMK.js +247 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-DrmrW5m5.js +42 -0
- package/dist/session-DD0S1PDC.js +337 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/ssh.d.ts +55 -0
- package/dist/ssh.js +219 -0
- package/dist/task/index.d.ts +67 -0
- package/dist/task/index.js +1523 -0
- package/dist/task/runtime/empty-registry.d.ts +6 -0
- package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
- package/dist/task/runtime/provider-loader.d.ts +20 -0
- package/dist/task/runtime/provider-loader.js +19 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
- package/dist/task/runtime/providers/cloudflare.js +26 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
- package/dist/task/runtime/state.d.ts +24 -0
- package/dist/task/runtime/state.js +73 -0
- package/dist/task/vite.d.ts +360 -0
- package/dist/{vite.js → task/vite.js} +964 -645
- package/dist/toolchain-BUVXtQ2m.js +527 -0
- package/dist/trusted-host-DNMJ-Oig.js +872 -0
- package/dist/vercel-Jtxa9TJx.js +279 -0
- package/package.json +99 -48
- package/dist/cloudflare-env-QQV4uzCT.js +0 -14
- package/dist/module-types-DKYItiOu.d.ts +0 -93
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-D0UihePq.d.ts +0 -21
- package/dist/runtime/empty-registry.d.ts +0 -6
- package/dist/runtime/provider-loader.d.ts +0 -2
- package/dist/runtime/provider-loader.js +0 -15
- package/dist/runtime/providers/cloudflare.d.ts +0 -29
- package/dist/runtime/providers/cloudflare.js +0 -25
- package/dist/runtime/providers/vercel.d.ts +0 -121
- package/dist/runtime/state.d.ts +0 -26
- package/dist/runtime/state.js +0 -72
- package/dist/vite.d.ts +0 -48
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
|
|
2
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
|
|
3
|
+
import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
|
|
4
|
+
import { i as abortable, n as isRuntimeString, r as runtimeRecord } from "./runtime-type-DrmrW5m5.js";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { maxSatisfying, minVersion, rcompare, valid, validRange } from "semver";
|
|
7
|
+
//#region src/internal/toolchain.ts
|
|
8
|
+
var toolchain_exports = /* @__PURE__ */ __exportAll({
|
|
9
|
+
nodeDistribution: () => nodeDistribution,
|
|
10
|
+
normalizeToolchain: () => normalizeToolchain,
|
|
11
|
+
parsePackageManager: () => parsePackageManager,
|
|
12
|
+
provisionToolchain: () => provisionToolchain,
|
|
13
|
+
readProjectFilesWithShell: () => readProjectFilesWithShell,
|
|
14
|
+
readToolchainPins: () => readToolchainPins,
|
|
15
|
+
resolveNodeVersion: () => resolveNodeVersion,
|
|
16
|
+
toolchainProjectFiles: () => toolchainProjectFiles,
|
|
17
|
+
toolchainReadsProject: () => toolchainReadsProject,
|
|
18
|
+
verifyToolchain: () => verifyToolchain
|
|
19
|
+
});
|
|
20
|
+
/** Project files that can pin the toolchain, relative to the project root. */
|
|
21
|
+
const toolchainProjectFiles = [
|
|
22
|
+
"package.json",
|
|
23
|
+
".node-version",
|
|
24
|
+
".nvmrc"
|
|
25
|
+
];
|
|
26
|
+
const defaultNodeDistribution = "https://nodejs.org/dist";
|
|
27
|
+
const defaultMuslNodeDistribution = "https://unofficial-builds.nodejs.org/download/release";
|
|
28
|
+
const defaultNpmRegistry = "https://registry.npmjs.org";
|
|
29
|
+
const indexCacheMilliseconds = 3e5;
|
|
30
|
+
const readyMarker = ".vitehub-toolchain";
|
|
31
|
+
const packageManagerNames = /* @__PURE__ */ new Set([
|
|
32
|
+
"npm",
|
|
33
|
+
"pnpm",
|
|
34
|
+
"yarn"
|
|
35
|
+
]);
|
|
36
|
+
const architectures = /* @__PURE__ */ new Map([
|
|
37
|
+
["aarch64", "arm64"],
|
|
38
|
+
["amd64", "x64"],
|
|
39
|
+
["arm64", "arm64"],
|
|
40
|
+
["armv7l", "armv7l"],
|
|
41
|
+
["ppc64le", "ppc64le"],
|
|
42
|
+
["s390x", "s390x"],
|
|
43
|
+
["x86_64", "x64"]
|
|
44
|
+
]);
|
|
45
|
+
const toolchainKeys = /* @__PURE__ */ new Set([
|
|
46
|
+
"fallbackNode",
|
|
47
|
+
"node",
|
|
48
|
+
"packageManager"
|
|
49
|
+
]);
|
|
50
|
+
const indexCache = /* @__PURE__ */ new Map();
|
|
51
|
+
const downloads = /* @__PURE__ */ new Map();
|
|
52
|
+
const downloadTimeoutMilliseconds = 6e5;
|
|
53
|
+
/** Validate a Sandbox or Driver toolchain declaration. */
|
|
54
|
+
function normalizeToolchain(value, label = "sandbox.toolchain") {
|
|
55
|
+
if (value === void 0) return;
|
|
56
|
+
if (value === "project") return Object.freeze({
|
|
57
|
+
node: "project",
|
|
58
|
+
packageManager: "project"
|
|
59
|
+
});
|
|
60
|
+
const options = runtimeRecord(value);
|
|
61
|
+
if (!options) throw sandboxErrorDiagnostics.SANDBOX_R0146({ message: `[vitehub] ${label} must be "project" or an object with node, packageManager, or fallbackNode.` });
|
|
62
|
+
const unknown = Object.keys(options).find((key) => !toolchainKeys.has(key));
|
|
63
|
+
if (unknown) throw sandboxErrorDiagnostics.SANDBOX_R0146({ message: `[vitehub] ${label}.${unknown} is not supported. Use node, packageManager, or fallbackNode.` });
|
|
64
|
+
const node = options.node ?? "project";
|
|
65
|
+
const packageManager = options.packageManager ?? "project";
|
|
66
|
+
if (!isVersionText(node)) throw sandboxErrorDiagnostics.SANDBOX_R0146({ message: `[vitehub] ${label}.node must be "project" or a Node.js version, range, or alias.` });
|
|
67
|
+
if (packageManager !== false && !isVersionText(packageManager)) throw sandboxErrorDiagnostics.SANDBOX_R0146({ message: `[vitehub] ${label}.packageManager must be "project", false, or a name@version value such as "pnpm@10.2.0".` });
|
|
68
|
+
if (packageManager !== false && packageManager !== "project") parsePackageManager(packageManager, `${label}.packageManager`);
|
|
69
|
+
const fallbackNode = options.fallbackNode;
|
|
70
|
+
if (fallbackNode !== void 0 && !isVersionText(fallbackNode)) throw sandboxErrorDiagnostics.SANDBOX_R0146({ message: `[vitehub] ${label}.fallbackNode must be a Node.js version, range, or alias.` });
|
|
71
|
+
return Object.freeze({
|
|
72
|
+
...fallbackNode === void 0 ? {} : { fallbackNode: fallbackNode.trim() },
|
|
73
|
+
node: node.trim(),
|
|
74
|
+
packageManager: packageManager === false ? false : packageManager.trim()
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** Whether pins come from project files. */
|
|
78
|
+
function toolchainReadsProject(toolchain) {
|
|
79
|
+
return toolchain.node === "project" || toolchain.packageManager === "project";
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Read Node.js and package manager pins. Node.js resolution order:
|
|
83
|
+
* devEngines.runtime, .node-version, .nvmrc, volta.node, engines.node, fallbackNode.
|
|
84
|
+
*/
|
|
85
|
+
function readToolchainPins(toolchain, files) {
|
|
86
|
+
const manifest = parseManifest(files["package.json"]);
|
|
87
|
+
const node = toolchain.node === "project" ? projectNodePin(manifest, files) ?? (toolchain.fallbackNode ? {
|
|
88
|
+
source: "toolchain.fallbackNode",
|
|
89
|
+
version: toolchain.fallbackNode
|
|
90
|
+
} : void 0) : {
|
|
91
|
+
source: "toolchain.node",
|
|
92
|
+
version: toolchain.node
|
|
93
|
+
};
|
|
94
|
+
if (!node) throw sandboxErrorDiagnostics.SANDBOX_R0147({ message: "[vitehub] Sandbox toolchain could not find a Node.js version. Add package.json devEngines.runtime, .node-version, .nvmrc, volta.node, or engines.node to the project, or set toolchain.fallbackNode." });
|
|
95
|
+
const packageManager = toolchain.packageManager === false ? void 0 : toolchain.packageManager === "project" ? projectPackageManagerPin(manifest) : parsePackageManager(toolchain.packageManager, "toolchain.packageManager");
|
|
96
|
+
return Object.freeze({
|
|
97
|
+
node: Object.freeze(node),
|
|
98
|
+
...packageManager ? { packageManager: Object.freeze(packageManager) } : {}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function projectNodePin(manifest, files) {
|
|
102
|
+
const runtime = runtimeRecord(manifest?.devEngines)?.runtime;
|
|
103
|
+
for (const entry of Array.isArray(runtime) ? runtime : runtime ? [runtime] : []) {
|
|
104
|
+
const value = runtimeRecord(entry);
|
|
105
|
+
if (value?.name === "node" && isVersionText(value.version)) return {
|
|
106
|
+
source: "package.json#devEngines.runtime",
|
|
107
|
+
version: value.version.trim()
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
for (const file of [".node-version", ".nvmrc"]) {
|
|
111
|
+
const version = versionFile(files[file]);
|
|
112
|
+
if (version) return {
|
|
113
|
+
source: file,
|
|
114
|
+
version
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const volta = runtimeRecord(manifest?.volta)?.node;
|
|
118
|
+
if (isVersionText(volta)) return {
|
|
119
|
+
source: "package.json#volta.node",
|
|
120
|
+
version: volta.trim()
|
|
121
|
+
};
|
|
122
|
+
const engines = runtimeRecord(manifest?.engines)?.node;
|
|
123
|
+
if (isVersionText(engines)) return {
|
|
124
|
+
source: "package.json#engines.node",
|
|
125
|
+
version: engines.trim()
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function projectPackageManagerPin(manifest) {
|
|
129
|
+
if (manifest?.packageManager !== void 0) {
|
|
130
|
+
if (!isRuntimeString(manifest.packageManager)) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: "[vitehub] package.json packageManager must be a name@version string." });
|
|
131
|
+
return parsePackageManager(manifest.packageManager, "package.json#packageManager");
|
|
132
|
+
}
|
|
133
|
+
const declared = runtimeRecord(manifest?.devEngines)?.packageManager;
|
|
134
|
+
const entry = (Array.isArray(declared) ? declared : declared ? [declared] : []).map(runtimeRecord).find((value) => isRuntimeString(value?.name));
|
|
135
|
+
if (!entry) return;
|
|
136
|
+
const source = "package.json#devEngines.packageManager";
|
|
137
|
+
if (!isVersionText(entry.version)) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: `[vitehub] ${source} must declare a version for ${String(entry.name)}.` });
|
|
138
|
+
return parsePackageManager(`${String(entry.name)}@${entry.version.trim()}`, source);
|
|
139
|
+
}
|
|
140
|
+
/** Parse `name@version[+algorithm.hex]`, the package.json packageManager format. */
|
|
141
|
+
function parsePackageManager(value, source) {
|
|
142
|
+
const match = /^([a-z]+)@([^+\s]+)(?:\+(sha1|sha224|sha256|sha384|sha512)\.([0-9a-fA-F]+))?$/.exec(value.trim());
|
|
143
|
+
if (!match) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: `[vitehub] ${source} must be name@version, such as pnpm@10.2.0. Received ${JSON.stringify(value)}.` });
|
|
144
|
+
const [, name, version, algorithm, digest] = match;
|
|
145
|
+
if (name === "bun") throw sandboxErrorDiagnostics.SANDBOX_R0149({ message: `[vitehub] ${source} selects bun, which the Sandbox toolchain does not provision yet. Install bun in the Sandbox image or set toolchain.packageManager to false.` });
|
|
146
|
+
if (!isPackageManagerName(name)) throw sandboxErrorDiagnostics.SANDBOX_R0149({ message: `[vitehub] ${source} selects unsupported package manager ${name}. Expected npm, pnpm, or yarn.` });
|
|
147
|
+
if (!valid(version) && !validRange(version)) throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: `[vitehub] ${source} has an invalid ${name} version: ${version}.` });
|
|
148
|
+
return {
|
|
149
|
+
...algorithm ? { integrity: `${algorithm}.${digest.toLowerCase()}` } : {},
|
|
150
|
+
name,
|
|
151
|
+
source,
|
|
152
|
+
version
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** Detect the target OS, architecture, and C library with POSIX tools. */
|
|
156
|
+
async function detectToolchainPlatform(target) {
|
|
157
|
+
const result = await target.run([
|
|
158
|
+
"uname -s",
|
|
159
|
+
"uname -m",
|
|
160
|
+
"if ls /lib/ld-musl-* >/dev/null 2>&1 || (ldd --version 2>&1 | grep -qi musl); then echo musl; else echo glibc; fi"
|
|
161
|
+
].join("\n"));
|
|
162
|
+
const [system = "", machine = "", libc = ""] = result.stdout.trim().split(/\r?\n/).map((line) => line.trim());
|
|
163
|
+
if (result.exitCode !== 0) throw toolchainCommandError("detect the Sandbox platform", result);
|
|
164
|
+
const os = system === "Linux" ? "linux" : system === "Darwin" ? "darwin" : void 0;
|
|
165
|
+
const arch = architectures.get(machine);
|
|
166
|
+
if (!os || !arch) throw sandboxErrorDiagnostics.SANDBOX_R0150({ message: `[vitehub] Sandbox toolchain does not support ${system || "an unknown OS"} ${machine || "on an unknown architecture"}. Supported systems are Linux and macOS.` });
|
|
167
|
+
return {
|
|
168
|
+
arch,
|
|
169
|
+
libc: os === "linux" && libc === "musl" ? "musl" : "glibc",
|
|
170
|
+
os
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** Official Node.js distribution for the platform. musl builds come from unofficial-builds. */
|
|
174
|
+
function nodeDistribution(platform, environment = processEnvironment()) {
|
|
175
|
+
const musl = platform.libc === "musl";
|
|
176
|
+
const base = trimSlash(musl ? environment.VITEHUB_NODE_MUSL_DIST_URL || defaultMuslNodeDistribution : environment.VITEHUB_NODE_DIST_URL || defaultNodeDistribution);
|
|
177
|
+
const suffix = `${platform.os}-${platform.arch}${musl ? "-musl" : ""}`;
|
|
178
|
+
return {
|
|
179
|
+
archive: (version) => `node-v${version}-${suffix}.tar.gz`,
|
|
180
|
+
base,
|
|
181
|
+
file: musl ? `linux-${platform.arch}-musl` : platform.os === "darwin" ? `osx-${platform.arch}-tar` : `linux-${platform.arch}`,
|
|
182
|
+
key: (version) => `node-v${version}-${suffix}`,
|
|
183
|
+
url: (version, file) => `${base}/v${version}/${file}`
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** Resolve a version, range, or alias to one exact Node.js release. */
|
|
187
|
+
async function resolveNodeVersion(spec, platform, signal) {
|
|
188
|
+
const value = spec.trim().replace(/^v(?=\d)/, "");
|
|
189
|
+
const exact = valid(value);
|
|
190
|
+
if (exact) return exact;
|
|
191
|
+
const distribution = nodeDistribution(platform);
|
|
192
|
+
const releases = (await nodeReleases(distribution.base, signal)).filter((release) => !release.files || release.files.includes(distribution.file));
|
|
193
|
+
const alias = value.toLowerCase();
|
|
194
|
+
const lts = /^lts(?:\/(.+))?$/.exec(alias);
|
|
195
|
+
let match;
|
|
196
|
+
if (alias === "node" || alias === "latest" || alias === "current") match = releases[0];
|
|
197
|
+
else if (lts) {
|
|
198
|
+
const name = lts[1] === void 0 || lts[1] === "*" ? void 0 : lts[1];
|
|
199
|
+
match = releases.find((release) => release.lts && (!name || release.lts.toLowerCase() === name));
|
|
200
|
+
} else if (validRange(value)) {
|
|
201
|
+
const version = maxSatisfying(releases.map((release) => release.version), value);
|
|
202
|
+
match = version ? releases.find((release) => release.version === version) : void 0;
|
|
203
|
+
} else throw sandboxErrorDiagnostics.SANDBOX_R0151({ message: `[vitehub] Sandbox toolchain cannot parse Node.js version ${JSON.stringify(spec)}.` });
|
|
204
|
+
if (!match) throw sandboxErrorDiagnostics.SANDBOX_R0151({ message: `[vitehub] No Node.js release for ${distribution.file} matches ${JSON.stringify(spec)} in ${distribution.base}/index.json.` });
|
|
205
|
+
return match.version;
|
|
206
|
+
}
|
|
207
|
+
async function nodeReleases(base, signal) {
|
|
208
|
+
const url = `${base}/index.json`;
|
|
209
|
+
const cached = indexCache.get(url);
|
|
210
|
+
if (cached && cached.expires > Date.now()) return await cached.value;
|
|
211
|
+
const value = fetchBytes(url, "Node.js release index", signal).then((bytes) => {
|
|
212
|
+
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
213
|
+
if (!Array.isArray(parsed)) throw new TypeError("index.json is not a list");
|
|
214
|
+
return parsed.flatMap((entry) => {
|
|
215
|
+
const record = runtimeRecord(entry);
|
|
216
|
+
const version = isRuntimeString(record?.version) ? valid(record.version) : null;
|
|
217
|
+
if (!version) return [];
|
|
218
|
+
return [{
|
|
219
|
+
...Array.isArray(record?.files) ? { files: record.files.filter(isRuntimeString) } : {},
|
|
220
|
+
lts: isRuntimeString(record?.lts) ? record.lts : false,
|
|
221
|
+
version
|
|
222
|
+
}];
|
|
223
|
+
}).sort((left, right) => rcompare(left.version, right.version));
|
|
224
|
+
});
|
|
225
|
+
indexCache.set(url, {
|
|
226
|
+
expires: Date.now() + indexCacheMilliseconds,
|
|
227
|
+
value
|
|
228
|
+
});
|
|
229
|
+
value.catch(() => indexCache.delete(url));
|
|
230
|
+
return await value;
|
|
231
|
+
}
|
|
232
|
+
function registryPackage(name, version) {
|
|
233
|
+
if (name !== "yarn") return name;
|
|
234
|
+
const lowest = valid(version) ?? minVersion(version)?.version;
|
|
235
|
+
return lowest && Number(lowest.split(".")[0]) >= 2 ? "@yarnpkg/cli-dist" : "yarn";
|
|
236
|
+
}
|
|
237
|
+
function registryUrl(environment = processEnvironment()) {
|
|
238
|
+
return trimSlash(environment.VITEHUB_NPM_REGISTRY_URL || defaultNpmRegistry);
|
|
239
|
+
}
|
|
240
|
+
async function resolvePackageManagerVersion(pin, signal) {
|
|
241
|
+
const exact = valid(pin.version);
|
|
242
|
+
const name = registryPackage(pin.name, pin.version);
|
|
243
|
+
if (exact) return {
|
|
244
|
+
name,
|
|
245
|
+
version: exact
|
|
246
|
+
};
|
|
247
|
+
const document = runtimeRecord(JSON.parse(new TextDecoder().decode(await fetchBytes(`${registryUrl()}/${encodePackageName(name)}`, `${name} registry metadata`, signal, { accept: "application/vnd.npm.install-v1+json" }))));
|
|
248
|
+
const versions = Object.keys(runtimeRecord(document?.versions) ?? {});
|
|
249
|
+
const version = maxSatisfying(versions, pin.version);
|
|
250
|
+
if (!version) throw sandboxErrorDiagnostics.SANDBOX_R0151({ message: `[vitehub] No ${name} release matches ${JSON.stringify(pin.version)} from ${pin.source}.` });
|
|
251
|
+
return {
|
|
252
|
+
name,
|
|
253
|
+
version
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
async function packageVersionMetadata(name, version, signal) {
|
|
257
|
+
const document = runtimeRecord(JSON.parse(new TextDecoder().decode(await fetchBytes(`${registryUrl()}/${encodePackageName(name)}/${encodeURIComponent(version)}`, `${name}@${version} registry metadata`, signal))));
|
|
258
|
+
const dist = runtimeRecord(document?.dist);
|
|
259
|
+
const declared = isRuntimeString(document?.bin) ? { [name.split("/").at(-1)]: document.bin } : Object.fromEntries(Object.entries(runtimeRecord(document?.bin) ?? {}).flatMap(([command, path]) => isRuntimeString(path) ? [[command, path]] : []));
|
|
260
|
+
const bin = Object.fromEntries(Object.entries(declared).map(([command, path]) => [command, path.replace(/^(?:\.\/)+/, "")]));
|
|
261
|
+
if (!isRuntimeString(dist?.tarball) || !isRuntimeString(dist.integrity) || !dist.integrity.startsWith("sha512-")) throw sandboxErrorDiagnostics.SANDBOX_R0152({ message: `[vitehub] ${name}@${version} registry metadata has no sha512 integrity.` });
|
|
262
|
+
if (!Object.keys(bin).length || Object.entries(bin).some(([command, path]) => !/^[A-Za-z0-9._-]+$/.test(command) || !safeRelativePath(path))) throw sandboxErrorDiagnostics.SANDBOX_R0152({ message: `[vitehub] ${name}@${version} registry metadata has no usable bin entries.` });
|
|
263
|
+
return {
|
|
264
|
+
bin,
|
|
265
|
+
integrity: dist.integrity,
|
|
266
|
+
tarball: dist.tarball
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Install the toolchain into the target. Returns PATH entries to prepend, in
|
|
271
|
+
* order. Call verifyToolchain with the final Sandbox environment afterwards.
|
|
272
|
+
*/
|
|
273
|
+
async function provisionToolchain(toolchain, target) {
|
|
274
|
+
const signal = target.abortSignal;
|
|
275
|
+
const pins = toolchain.pins ?? readToolchainPins(toolchain, await target.readProjectFiles(toolchainProjectFiles));
|
|
276
|
+
const platform = await detectToolchainPlatform(target);
|
|
277
|
+
const distribution = nodeDistribution(platform);
|
|
278
|
+
const nodeVersion = await resolveNodeVersion(pins.node.version, platform, signal);
|
|
279
|
+
const packageManager = pins.packageManager ? {
|
|
280
|
+
pin: pins.packageManager,
|
|
281
|
+
...await resolvePackageManagerVersion(pins.packageManager, signal)
|
|
282
|
+
} : void 0;
|
|
283
|
+
const nodeKey = distribution.key(nodeVersion);
|
|
284
|
+
const packageKey = packageManager ? `${packageManager.name.replace(/^@/, "").replace("/", "-")}-${packageManager.version}${packageManager.pin.integrity ? `-${packageManager.pin.integrity.replace(/[^A-Za-z0-9_-]/g, "_")}` : ""}` : void 0;
|
|
285
|
+
const nodeRoot = joinPath(target.cacheRoot, nodeKey);
|
|
286
|
+
const packageRoot = packageKey ? joinPath(target.cacheRoot, packageKey) : void 0;
|
|
287
|
+
const state = await target.run([
|
|
288
|
+
`test -f ${shellQuote(joinPath(nodeRoot, readyMarker))} && echo node-ready || echo node-missing`,
|
|
289
|
+
packageRoot ? `test -f ${shellQuote(joinPath(packageRoot, readyMarker))} && echo package-ready || echo package-missing` : "echo package-none",
|
|
290
|
+
target.reuseExactNode ? "command -v node >/dev/null 2>&1 && node -v 2>/dev/null || echo none" : "echo none"
|
|
291
|
+
].join("\n"));
|
|
292
|
+
if (state.exitCode !== 0) throw toolchainCommandError("inspect the toolchain cache", state);
|
|
293
|
+
const [nodeState, packageState, existingNode] = state.stdout.trim().split(/\r?\n/).map((line) => line.trim());
|
|
294
|
+
const reuseNode = target.reuseExactNode === true && existingNode === `v${nodeVersion}`;
|
|
295
|
+
if (!reuseNode && nodeState !== "node-ready") await installEntry(target, nodeKey, async () => {
|
|
296
|
+
const file = distribution.archive(nodeVersion);
|
|
297
|
+
const expected = new TextDecoder().decode(await fetchBytes(distribution.url(nodeVersion, "SHASUMS256.txt"), `Node.js ${nodeVersion} SHASUMS256.txt`, signal)).split(/\r?\n/).map((line) => /^([0-9a-f]{64})\s+\*?(\S+)$/.exec(line.trim())).find((match) => match?.[2] === file)?.[1];
|
|
298
|
+
if (!expected) throw sandboxErrorDiagnostics.SANDBOX_R0151({ message: `[vitehub] Node.js ${nodeVersion} has no ${file} in ${distribution.url(nodeVersion, "SHASUMS256.txt")}.` });
|
|
299
|
+
const url = distribution.url(nodeVersion, file);
|
|
300
|
+
return {
|
|
301
|
+
archive: await download(url, `Node.js ${nodeVersion}`, signal, (bytes) => {
|
|
302
|
+
const actual = createHash("sha256").update(bytes).digest("hex");
|
|
303
|
+
if (actual !== expected) throw sandboxErrorDiagnostics.SANDBOX_R0153({ message: `[vitehub] Node.js archive checksum mismatch for ${url}: expected sha256 ${expected}, received ${actual}.` });
|
|
304
|
+
}),
|
|
305
|
+
metadata: {
|
|
306
|
+
name: "node",
|
|
307
|
+
sha256: expected,
|
|
308
|
+
url,
|
|
309
|
+
version: nodeVersion
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
});
|
|
313
|
+
if (packageManager && packageRoot && packageKey && packageState !== "package-ready") {
|
|
314
|
+
const { name, pin, version } = packageManager;
|
|
315
|
+
await installEntry(target, packageKey, async () => {
|
|
316
|
+
const metadata = await packageVersionMetadata(name, version, signal);
|
|
317
|
+
return {
|
|
318
|
+
archive: await download(metadata.tarball, `${name}@${version}`, signal, async (bytes) => {
|
|
319
|
+
const actual = `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
|
|
320
|
+
if (actual !== metadata.integrity) throw sandboxErrorDiagnostics.SANDBOX_R0153({ message: `[vitehub] ${name}@${version} integrity mismatch: expected ${metadata.integrity}, received ${actual}.` });
|
|
321
|
+
if (pin.integrity) await verifyPackageManagerHash(pin, name, bytes);
|
|
322
|
+
}),
|
|
323
|
+
metadata: {
|
|
324
|
+
integrity: metadata.integrity,
|
|
325
|
+
name,
|
|
326
|
+
url: metadata.tarball,
|
|
327
|
+
version
|
|
328
|
+
},
|
|
329
|
+
shims: metadata.bin
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
const bin = [...packageRoot ? [joinPath(packageRoot, "bin")] : [], ...reuseNode ? [] : [joinPath(nodeRoot, "bin")]];
|
|
334
|
+
return Object.freeze({
|
|
335
|
+
bin: Object.freeze(bin),
|
|
336
|
+
node: Object.freeze({
|
|
337
|
+
source: pins.node.source,
|
|
338
|
+
version: nodeVersion
|
|
339
|
+
}),
|
|
340
|
+
...packageManager ? { packageManager: Object.freeze({
|
|
341
|
+
name: pins.packageManager.name,
|
|
342
|
+
source: pins.packageManager.source,
|
|
343
|
+
version: packageManager.version
|
|
344
|
+
}) } : {}
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Check the versions that Sandbox commands see. `run` must use the final Sandbox
|
|
349
|
+
* environment, so login profiles that reset PATH fail here.
|
|
350
|
+
*/
|
|
351
|
+
async function verifyToolchain(toolchain, cacheRoot, run) {
|
|
352
|
+
const packageManager = toolchain.packageManager;
|
|
353
|
+
const result = await run([
|
|
354
|
+
`cd -- ${shellQuote(cacheRoot)}`,
|
|
355
|
+
"node -v",
|
|
356
|
+
...packageManager ? [`${packageManager.name} --version`] : []
|
|
357
|
+
].join(" && "));
|
|
358
|
+
const [node, reported] = result.stdout.trim().split(/\r?\n/).map((line) => line.trim());
|
|
359
|
+
if (result.exitCode === 0 && node === `v${toolchain.node.version}` && (!packageManager || reported === packageManager.version)) return;
|
|
360
|
+
const details = result.exitCode === 0 ? `node -v reported ${node || "<empty>"}${packageManager ? ` and ${packageManager.name} --version reported ${reported || "<empty>"}` : ""}` : (result.stderr || result.stdout).trim().slice(0, 1e3) || `exit ${result.exitCode}`;
|
|
361
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0154({ message: `[vitehub] Sandbox toolchain verification failed for Node.js ${toolchain.node.version}${packageManager ? ` and ${packageManager.name} ${packageManager.version}` : ""}: ${details}` });
|
|
362
|
+
}
|
|
363
|
+
async function installEntry(target, key, prepare) {
|
|
364
|
+
const release = await target.lock?.(key);
|
|
365
|
+
try {
|
|
366
|
+
target.abortSignal?.throwIfAborted();
|
|
367
|
+
const final = joinPath(target.cacheRoot, key);
|
|
368
|
+
if (release) {
|
|
369
|
+
if ((await target.run(`test -f ${shellQuote(joinPath(final, readyMarker))}`)).exitCode === 0) return;
|
|
370
|
+
}
|
|
371
|
+
const { archive, metadata, shims } = await prepare();
|
|
372
|
+
const archivePath = joinPath(target.scratch, `.vitehub-toolchain-${randomUUID()}.tgz`);
|
|
373
|
+
await target.write(archivePath, archive);
|
|
374
|
+
target.abortSignal?.throwIfAborted();
|
|
375
|
+
const result = await target.run(installScript({
|
|
376
|
+
archive: archivePath,
|
|
377
|
+
cacheRoot: target.cacheRoot,
|
|
378
|
+
key,
|
|
379
|
+
metadata,
|
|
380
|
+
shims
|
|
381
|
+
}));
|
|
382
|
+
if (result.exitCode !== 0) throw toolchainCommandError(`install ${key}`, result);
|
|
383
|
+
} finally {
|
|
384
|
+
await release?.();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Extract into a private staging directory, then publish with an atomic
|
|
389
|
+
* symbolic link. A concurrent installer that loses the race keeps the winner.
|
|
390
|
+
*/
|
|
391
|
+
function installScript(options) {
|
|
392
|
+
const final = joinPath(options.cacheRoot, options.key);
|
|
393
|
+
const lines = [
|
|
394
|
+
"set -eu",
|
|
395
|
+
"umask 022",
|
|
396
|
+
`archive=${shellQuote(options.archive)}`,
|
|
397
|
+
`cache=${shellQuote(options.cacheRoot)}`,
|
|
398
|
+
`final=${shellQuote(final)}`,
|
|
399
|
+
`if [ -f "$final/${readyMarker}" ]; then rm -f -- "$archive"; exit 0; fi`,
|
|
400
|
+
`mkdir -p -- "$cache/.store"`,
|
|
401
|
+
`staging=$(mktemp -d "$cache/.store/${options.key}.XXXXXX")`,
|
|
402
|
+
`cleanup() { chmod -R u+w -- "$staging" 2>/dev/null || true; rm -rf -- "$staging" "$archive"; }`,
|
|
403
|
+
"trap cleanup EXIT HUP INT TERM"
|
|
404
|
+
];
|
|
405
|
+
if (options.shims) {
|
|
406
|
+
lines.push(`mkdir -- "$staging/package" "$staging/bin"`, `tar -xzf "$archive" -C "$staging/package" --strip-components=1`);
|
|
407
|
+
for (const [command, path] of Object.entries(options.shims)) {
|
|
408
|
+
const shim = `"$staging/bin/"${shellQuote(command)}`;
|
|
409
|
+
lines.push(`test -f "$staging/package/"${shellQuote(path)}`, `printf '%s\\n' '#!/bin/sh' ${shellQuote(`exec node ${shellQuote(joinPath(final, "package", path))} "$@"`)} > ${shim}`, `chmod 755 ${shim}`);
|
|
410
|
+
}
|
|
411
|
+
} else lines.push(`tar -xzf "$archive" -C "$staging" --strip-components=1`, `test -x "$staging/bin/node"`);
|
|
412
|
+
lines.push(`printf '%s\\n' ${shellQuote(JSON.stringify(options.metadata))} > "$staging/${readyMarker}"`, `chmod -R a-w -- "$staging"`, `if ln -sn ".store/$(basename -- "$staging")" "$final" 2>/dev/null; then trap - EXIT HUP INT TERM; rm -f -- "$archive"; exit 0; fi`, `test -f "$final/${readyMarker}"`);
|
|
413
|
+
return `${lines.join("\n")}\n`;
|
|
414
|
+
}
|
|
415
|
+
async function verifyPackageManagerHash(pin, name, tarball) {
|
|
416
|
+
const [algorithm = "", expected = ""] = pin.integrity?.split(".") ?? [];
|
|
417
|
+
const contents = name === "@yarnpkg/cli-dist" ? await tarEntry(tarball, "bin/yarn.js") : tarball;
|
|
418
|
+
const actual = contents ? createHash(algorithm).update(contents).digest("hex") : void 0;
|
|
419
|
+
if (actual !== expected) throw sandboxErrorDiagnostics.SANDBOX_R0153({ message: `[vitehub] ${pin.name}@${pin.version} does not match the ${algorithm} hash from ${pin.source}: expected ${expected}, received ${actual ?? "<missing>"}.` });
|
|
420
|
+
}
|
|
421
|
+
/** Read one regular file from a gzipped npm package tarball. */
|
|
422
|
+
async function tarEntry(gzipped, path) {
|
|
423
|
+
const stream = new Blob([Uint8Array.from(gzipped)]).stream().pipeThrough(new DecompressionStream("gzip"));
|
|
424
|
+
const bytes = new Uint8Array(await new Response(stream).arrayBuffer());
|
|
425
|
+
const decoder = new TextDecoder();
|
|
426
|
+
const field = (offset, length) => decoder.decode(bytes.subarray(offset, offset + length)).replace(/\0.*$/s, "");
|
|
427
|
+
let longName;
|
|
428
|
+
for (let offset = 0; offset + 512 <= bytes.length;) {
|
|
429
|
+
const name = field(offset, 100);
|
|
430
|
+
if (!name) break;
|
|
431
|
+
const size = Number.parseInt(field(offset + 124, 12).trim() || "0", 8);
|
|
432
|
+
const type = field(offset + 156, 1);
|
|
433
|
+
const prefix = field(offset + 345, 155);
|
|
434
|
+
const data = offset + 512;
|
|
435
|
+
const entryName = longName ?? (prefix ? `${prefix}/${name}` : name);
|
|
436
|
+
longName = void 0;
|
|
437
|
+
if (type === "x" || type === "L") {
|
|
438
|
+
const text = decoder.decode(bytes.subarray(data, data + size));
|
|
439
|
+
longName = type === "L" ? text.replace(/\0.*$/s, "") : /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text)?.[1];
|
|
440
|
+
} else if ((type === "0" || type === "") && entryName.split("/").slice(1).join("/") === path) return bytes.subarray(data, data + size);
|
|
441
|
+
offset = data + Math.ceil(size / 512) * 512;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function download(url, label, signal, verify) {
|
|
445
|
+
let pending = downloads.get(url);
|
|
446
|
+
if (!pending) {
|
|
447
|
+
pending = fetchBytes(url, label, AbortSignal.timeout(downloadTimeoutMilliseconds));
|
|
448
|
+
downloads.set(url, pending);
|
|
449
|
+
pending.then(() => downloads.delete(url), () => downloads.delete(url));
|
|
450
|
+
}
|
|
451
|
+
const bytes = await abortable(pending, signal);
|
|
452
|
+
await verify(bytes);
|
|
453
|
+
return bytes;
|
|
454
|
+
}
|
|
455
|
+
async function fetchBytes(url, label, signal, headers) {
|
|
456
|
+
let response;
|
|
457
|
+
try {
|
|
458
|
+
response = await fetch(url, {
|
|
459
|
+
headers,
|
|
460
|
+
signal
|
|
461
|
+
});
|
|
462
|
+
} catch (error) {
|
|
463
|
+
signal?.throwIfAborted();
|
|
464
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0155({
|
|
465
|
+
message: `[vitehub] Sandbox toolchain could not download ${label} from ${url}: ${error instanceof Error ? error.message : String(error)}`,
|
|
466
|
+
cause: error
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
if (!response.ok) throw sandboxErrorDiagnostics.SANDBOX_R0155({ message: `[vitehub] Sandbox toolchain could not download ${label} from ${url}: HTTP ${response.status}.` });
|
|
470
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
471
|
+
}
|
|
472
|
+
function toolchainCommandError(operation, result) {
|
|
473
|
+
const detail = (result.stderr || result.stdout).trim().slice(0, 1e3);
|
|
474
|
+
return sandboxErrorDiagnostics.SANDBOX_R0154({ message: `[vitehub] Sandbox toolchain failed to ${operation} (exit ${result.exitCode})${detail ? `: ${detail}` : "."}` });
|
|
475
|
+
}
|
|
476
|
+
/** Read project files through a POSIX shell. Missing files resolve to undefined. */
|
|
477
|
+
async function readProjectFilesWithShell(run, directory, paths) {
|
|
478
|
+
const marker = `vitehub-${randomUUID()}`;
|
|
479
|
+
const result = await run(paths.map((path) => {
|
|
480
|
+
const file = shellQuote(joinPath(directory, path));
|
|
481
|
+
return `if [ -f ${file} ]; then printf '%s\\n' ${shellQuote(`${marker}:file`)}; base64 < ${file} | tr -d '\\n'; printf '\\n'; else printf '%s\\n\\n' ${shellQuote(`${marker}:missing`)}; fi`;
|
|
482
|
+
}).join("\n"));
|
|
483
|
+
if (result.exitCode !== 0) throw toolchainCommandError("read project files", result);
|
|
484
|
+
const lines = result.stdout.split("\n");
|
|
485
|
+
const files = {};
|
|
486
|
+
paths.forEach((path, index) => {
|
|
487
|
+
const state = lines[index * 2];
|
|
488
|
+
if (state !== `${marker}:file` && state !== `${marker}:missing`) throw toolchainCommandError("read project files", result);
|
|
489
|
+
files[path] = state === `${marker}:file` ? Buffer.from(lines[index * 2 + 1] ?? "", "base64").toString("utf8") : void 0;
|
|
490
|
+
});
|
|
491
|
+
return files;
|
|
492
|
+
}
|
|
493
|
+
function parseManifest(text) {
|
|
494
|
+
if (text === void 0) return;
|
|
495
|
+
try {
|
|
496
|
+
const value = runtimeRecord(JSON.parse(text));
|
|
497
|
+
if (value) return value;
|
|
498
|
+
} catch {}
|
|
499
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0148({ message: "[vitehub] Sandbox toolchain cannot parse package.json as a JSON object." });
|
|
500
|
+
}
|
|
501
|
+
function versionFile(text) {
|
|
502
|
+
return text?.split(/\r?\n/).map((value) => value.replace(/#.*$/, "").trim()).find(Boolean) || void 0;
|
|
503
|
+
}
|
|
504
|
+
function isVersionText(value) {
|
|
505
|
+
return isRuntimeString(value) && Boolean(value.trim()) && !/[\0\n\r]/.test(value);
|
|
506
|
+
}
|
|
507
|
+
function isPackageManagerName(value) {
|
|
508
|
+
return value !== void 0 && packageManagerNames.has(value);
|
|
509
|
+
}
|
|
510
|
+
function safeRelativePath(path) {
|
|
511
|
+
const normalized = path.replace(/^\.\//, "");
|
|
512
|
+
return Boolean(normalized) && !normalized.startsWith("/") && !normalized.split("/").includes("..") && !/[\0\n\r]/.test(normalized);
|
|
513
|
+
}
|
|
514
|
+
function encodePackageName(name) {
|
|
515
|
+
return name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
|
|
516
|
+
}
|
|
517
|
+
function joinPath(...parts) {
|
|
518
|
+
return parts.join("/").replace(/\/{2,}/g, "/");
|
|
519
|
+
}
|
|
520
|
+
function trimSlash(value) {
|
|
521
|
+
return value.replace(/\/+$/, "");
|
|
522
|
+
}
|
|
523
|
+
function processEnvironment() {
|
|
524
|
+
return globalThis.process?.env ?? {};
|
|
525
|
+
}
|
|
526
|
+
//#endregion
|
|
527
|
+
export { verifyToolchain as a, toolchain_exports as i, provisionToolchain as n, toolchainProjectFiles as r, normalizeToolchain as t };
|