@vite-hub/sandbox 0.0.4 → 0.3.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 +395 -37
- package/dist/abortable-CR01hzfi.js +57 -0
- package/dist/cloudflare-Cog_r2Me.js +910 -0
- package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
- package/dist/cloudflare-failure-CFQhalfh.js +50 -0
- package/dist/container-CqfD8yuE.js +868 -0
- package/dist/crabbox-sbV3Zjuo.js +1110 -0
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/file-listing-CHtRrfo1.js +26 -0
- package/dist/file-lock-D0-XPogS.js +74 -0
- package/dist/index-DsoQAUb7.d.ts +594 -0
- package/dist/index.d.ts +2 -69
- package/dist/index.js +281 -1182
- package/dist/internal/cloudflare.d.ts +176 -0
- package/dist/internal/cloudflare.js +8 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +96 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +8 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/module-types-B0LQ5H2S.js +7 -0
- package/dist/module-types-DCeJbS9Z.d.ts +110 -0
- package/dist/process-sweep-CMaujWE5.js +33 -0
- package/dist/provider-resolution-C6AQzuFG.js +133 -0
- package/dist/remote-70ZVZZlq.js +265 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/session-e0lyzjJ3.js +338 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +63 -0
- package/dist/ssh.js +286 -0
- package/dist/task/index.d.ts +69 -0
- package/dist/task/index.js +1414 -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 +18 -0
- package/dist/task/runtime/provider-loader.js +16 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
- package/dist/task/runtime/providers/cloudflare.js +27 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/task/runtime/providers/vercel.js +85 -0
- package/dist/task/runtime/state.d.ts +27 -0
- package/dist/task/runtime/state.js +82 -0
- package/dist/task/vite.d.ts +486 -0
- package/dist/task/vite.js +3966 -0
- package/dist/toolchain-BIVGMRty.js +528 -0
- package/dist/trusted-host-kxkpaQcs.js +714 -0
- package/dist/vercel-BGGrNpza.js +352 -0
- package/package.json +105 -51
- 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/providers/vercel.js +0 -51
- package/dist/runtime/state.d.ts +0 -26
- package/dist/runtime/state.js +0 -72
- package/dist/vite.d.ts +0 -48
- package/dist/vite.js +0 -3324
package/dist/index.js
CHANGED
|
@@ -1,1219 +1,318 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
//#region src/
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const validated = validateDefinitionOptions(functionName, input, {
|
|
25
|
-
allowedKeys: [
|
|
26
|
-
"run",
|
|
27
|
-
"timeout",
|
|
28
|
-
"env",
|
|
29
|
-
"project"
|
|
30
|
-
],
|
|
31
|
-
invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env, project)"
|
|
32
|
-
});
|
|
33
|
-
if (!validated) throw new TypeError(`[vitehub] \`${functionName}()\` requires an options object.`);
|
|
34
|
-
if (typeof validated.project !== "undefined" && typeof validated.project !== "boolean") throw new TypeError(`[vitehub] \`${functionName}()\` project must be a boolean.`);
|
|
35
|
-
const { project: _project, run, ...options } = validated;
|
|
36
|
-
assertDefinitionHandler(functionName, run, "Sandbox handler in `run`");
|
|
37
|
-
return {
|
|
38
|
-
run,
|
|
39
|
-
options: Object.keys(options).length ? options : void 0
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
function defineSandbox(input) {
|
|
43
|
-
return createSandboxDefinition("defineSandbox", input);
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region src/internal/shared/request-payload.ts
|
|
47
|
-
async function readRequestPayload(event, fallback = {}) {
|
|
48
|
-
return await event.req.json().catch(() => fallback);
|
|
49
|
-
}
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/sandbox/errors.ts
|
|
52
|
-
function sanitizeSandboxDetail(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
|
|
53
|
-
if (value === null || typeof value === "boolean") return value;
|
|
54
|
-
if (typeof value === "string") return value.slice(0, 16384);
|
|
55
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
56
|
-
if (!value || typeof value !== "object" || depth >= 8 || seen.has(value)) return void 0;
|
|
57
|
-
seen.add(value);
|
|
58
|
-
try {
|
|
59
|
-
if (Array.isArray(value)) return value.slice(0, 128).flatMap((item) => {
|
|
60
|
-
const sanitized = sanitizeSandboxDetail(item, depth + 1, seen);
|
|
61
|
-
return sanitized === void 0 ? [] : [sanitized];
|
|
62
|
-
});
|
|
63
|
-
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return void 0;
|
|
64
|
-
const result = {};
|
|
65
|
-
for (const [key, item] of Object.entries(value).slice(0, 128)) {
|
|
66
|
-
if (!key || key.length > 128) continue;
|
|
67
|
-
result[key] = sanitizeSandboxDetail(item, depth + 1, seen);
|
|
1
|
+
import { n as isBuiltInSandboxRuntime, t as hasDeclaredSandboxRuntimeMember } from "./runtime-DHp6ImeP.js";
|
|
2
|
+
import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
5
|
+
import { isAbsolute, posix, relative, resolve } from "node:path";
|
|
6
|
+
import { normalizeExecutionAuthority } from "@vite-hub/runtime";
|
|
7
|
+
//#region src/index.ts
|
|
8
|
+
const reservedRuntimeNames = /* @__PURE__ */ new Set([
|
|
9
|
+
"cloudflare",
|
|
10
|
+
"container",
|
|
11
|
+
"crabbox",
|
|
12
|
+
"trusted-host",
|
|
13
|
+
"vercel"
|
|
14
|
+
]);
|
|
15
|
+
async function resolveSandboxRuntime(value) {
|
|
16
|
+
if (isSandboxRuntime(value)) {
|
|
17
|
+
if (reservedRuntimeNames.has(value.name) && !isBuiltInSandboxRuntime(value)) throw sandboxErrorDiagnostics.SANDBOX_R0030({ message: `[vitehub] Custom Sandbox runtimes cannot use the reserved name "${value.name}". Select the built-in runtime by value instead.` });
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
if (typeof value === "string") {
|
|
21
|
+
if (value === "crabbox") {
|
|
22
|
+
const { createCrabboxRuntime } = await import("./crabbox-sbV3Zjuo.js");
|
|
23
|
+
return createCrabboxRuntime();
|
|
68
24
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
25
|
+
if (value === "trusted-host") {
|
|
26
|
+
const { createTrustedHostRuntime } = await import("./trusted-host-kxkpaQcs.js");
|
|
27
|
+
return createTrustedHostRuntime();
|
|
28
|
+
}
|
|
29
|
+
if (value === "vercel") {
|
|
30
|
+
const { createVercelRuntime } = await import("./vercel-BGGrNpza.js").then((n) => n.r);
|
|
31
|
+
return createVercelRuntime();
|
|
32
|
+
}
|
|
33
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0031({ message: `[vitehub] Unknown Sandbox runtime "${value}". Expected "crabbox", "trusted-host", "vercel", a tagged built-in configuration, or a custom runtime.` });
|
|
74
34
|
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
function sandboxError(message, metadata = {}) {
|
|
81
|
-
const { cause, code = "SANDBOX_RUNTIME_ERROR", details, httpStatus, method, provider } = metadata;
|
|
82
|
-
return new ViteHubError(code, message.slice(0, 16384) || "Sandbox execution failed.", {
|
|
83
|
-
cause,
|
|
84
|
-
details: sanitizeSandboxDetails({
|
|
85
|
-
...provider === void 0 ? {} : { provider },
|
|
86
|
-
...method === void 0 ? {} : { method },
|
|
87
|
-
...httpStatus === void 0 ? {} : { httpStatus },
|
|
88
|
-
...sanitizeSandboxDetails(details)
|
|
89
|
-
})
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
function isSandboxError(value) {
|
|
93
|
-
return getViteHubErrorShape(value)?.code.startsWith("SANDBOX_") === true;
|
|
94
|
-
}
|
|
95
|
-
//#endregion
|
|
96
|
-
//#region src/internal/shared/validation.ts
|
|
97
|
-
const VALIDATION_FAILED = "Validation failed";
|
|
98
|
-
function isObject(value) {
|
|
99
|
-
return !!value && typeof value === "object";
|
|
100
|
-
}
|
|
101
|
-
function hasStandardValidator(value) {
|
|
102
|
-
return isObject(value) && "~standard" in value && isObject(value["~standard"]) && typeof value["~standard"].validate === "function";
|
|
103
|
-
}
|
|
104
|
-
function isErrorWithHttpMetadata(error) {
|
|
105
|
-
if (!(error instanceof Error)) return false;
|
|
106
|
-
const e = error;
|
|
107
|
-
return typeof e.status === "number" || typeof e.statusCode === "number" || typeof e.statusText === "string" || typeof e.statusMessage === "string";
|
|
108
|
-
}
|
|
109
|
-
function readIssues(value) {
|
|
110
|
-
if (!isObject(value)) return void 0;
|
|
111
|
-
if (Array.isArray(value.issues)) return value.issues;
|
|
112
|
-
if (isObject(value.data) && Array.isArray(value.data.issues)) return value.data.issues;
|
|
113
|
-
}
|
|
114
|
-
function readStatusCode(value) {
|
|
115
|
-
if (!isObject(value)) return 400;
|
|
116
|
-
if (typeof value.statusCode === "number") return value.statusCode;
|
|
117
|
-
if (typeof value.status === "number") return value.status;
|
|
118
|
-
return 400;
|
|
119
|
-
}
|
|
120
|
-
function readStatusText(value) {
|
|
121
|
-
if (!isObject(value)) return VALIDATION_FAILED;
|
|
122
|
-
if (typeof value.statusMessage === "string" && value.statusMessage) return value.statusMessage;
|
|
123
|
-
if (typeof value.statusText === "string" && value.statusText) return value.statusText;
|
|
124
|
-
return VALIDATION_FAILED;
|
|
125
|
-
}
|
|
126
|
-
function readMessage(value) {
|
|
127
|
-
if (value instanceof Error) return value.message || "Validation failed";
|
|
128
|
-
if (isObject(value) && typeof value.message === "string" && value.message) return value.message;
|
|
129
|
-
return VALIDATION_FAILED;
|
|
130
|
-
}
|
|
131
|
-
function readData(value, issues) {
|
|
132
|
-
const base = isObject(value) && isObject(value.data) ? { ...value.data } : {};
|
|
133
|
-
const message = value instanceof Error ? VALIDATION_FAILED : typeof base.message === "string" && base.message || readMessage(value);
|
|
134
|
-
return {
|
|
135
|
-
...base,
|
|
136
|
-
message,
|
|
137
|
-
...issues ? { issues } : {}
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
function createValidationError(cause) {
|
|
141
|
-
if (isErrorWithHttpMetadata(cause)) return cause;
|
|
142
|
-
const statusCode = readStatusCode(cause);
|
|
143
|
-
const statusText = readStatusText(cause);
|
|
144
|
-
const data = readData(cause, readIssues(cause));
|
|
145
|
-
return Object.assign(sandboxError(readMessage(cause), {
|
|
146
|
-
cause,
|
|
147
|
-
code: "SANDBOX_VALIDATION_ERROR",
|
|
148
|
-
details: data,
|
|
149
|
-
httpStatus: statusCode
|
|
150
|
-
}), {
|
|
151
|
-
status: statusCode,
|
|
152
|
-
statusCode,
|
|
153
|
-
statusText,
|
|
154
|
-
statusMessage: statusText,
|
|
155
|
-
data
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
async function readValidatedPayload(payload, validate, options) {
|
|
159
|
-
if (hasStandardValidator(validate)) {
|
|
160
|
-
const result = await validate["~standard"].validate(payload);
|
|
161
|
-
if (result.issues?.length) throw createValidationError(options?.onError?.({
|
|
162
|
-
issues: result.issues,
|
|
163
|
-
value: payload
|
|
164
|
-
}) || {
|
|
165
|
-
issues: result.issues,
|
|
166
|
-
message: "Validation failed"
|
|
167
|
-
});
|
|
168
|
-
return result.value;
|
|
35
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw sandboxErrorDiagnostics.SANDBOX_R0032({ message: "[vitehub] Sandbox requires an explicit built-in runtime value or custom runtime object." });
|
|
36
|
+
const { kind, ...options } = value;
|
|
37
|
+
if (kind === "crabbox") {
|
|
38
|
+
const { createCrabboxRuntime } = await import("./crabbox-sbV3Zjuo.js");
|
|
39
|
+
return createCrabboxRuntime(options);
|
|
169
40
|
}
|
|
170
|
-
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
issues: [{ message: "Validation failed" }],
|
|
174
|
-
value: payload
|
|
175
|
-
}) || { message: "Validation failed" });
|
|
176
|
-
if (result === true || result == null) return payload;
|
|
177
|
-
return result;
|
|
178
|
-
} catch (error) {
|
|
179
|
-
throw createValidationError(error);
|
|
41
|
+
if (kind === "trusted-host") {
|
|
42
|
+
const { createTrustedHostRuntime } = await import("./trusted-host-kxkpaQcs.js");
|
|
43
|
+
return createTrustedHostRuntime(options);
|
|
180
44
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS = [
|
|
185
|
-
1e3,
|
|
186
|
-
2e3,
|
|
187
|
-
5e3,
|
|
188
|
-
1e4,
|
|
189
|
-
15e3
|
|
190
|
-
];
|
|
191
|
-
const CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE = /container is starting|currently provisioning|retry in a moment|network connection lost|not listening in the tcp address|durable object reset|code was updated|aborterror|aborted|maximum number of running container instances exceeded|there is no container instance that can be provided to this durable object|cloudflare box [a-z][a-z0-9]* timed out after \d+ms/i;
|
|
192
|
-
function collectCloudflareErrorMessages(error, ...extraMessages) {
|
|
193
|
-
return [
|
|
194
|
-
error instanceof Error ? error.message : String(error),
|
|
195
|
-
error instanceof Error && error.cause instanceof Error ? error.cause.message : "",
|
|
196
|
-
...extraMessages
|
|
197
|
-
].filter(Boolean).join("\n");
|
|
198
|
-
}
|
|
199
|
-
//#endregion
|
|
200
|
-
//#region src/internal/shared/named-resource.ts
|
|
201
|
-
function resolveNamedResourceName(feature, name) {
|
|
202
|
-
if (!name) throw new Error(`[vitehub] ${upperFirst(feature)} name is required. An explicit name is required.`);
|
|
203
|
-
return name;
|
|
204
|
-
}
|
|
205
|
-
function createUnknownNamedResourceError(feature, name) {
|
|
206
|
-
return /* @__PURE__ */ new Error(`[vitehub] Unknown ${feature} "${name}".`);
|
|
207
|
-
}
|
|
208
|
-
function createInvalidNamedResourceError(feature, name) {
|
|
209
|
-
return /* @__PURE__ */ new Error(`[vitehub] ${upperFirst(feature)} "${name}" is invalid.`);
|
|
210
|
-
}
|
|
211
|
-
function readRuntimeValue(read, fallback) {
|
|
212
|
-
const value = read({});
|
|
213
|
-
return typeof value === "undefined" ? fallback() : value;
|
|
214
|
-
}
|
|
215
|
-
async function loadRegistryEntry(registry, name) {
|
|
216
|
-
const entry = registry[name];
|
|
217
|
-
if (!entry) return void 0;
|
|
218
|
-
if (typeof entry === "function") return (await entry()).default;
|
|
219
|
-
return entry;
|
|
220
|
-
}
|
|
221
|
-
//#endregion
|
|
222
|
-
//#region src/internal/shared/resource-runtime.ts
|
|
223
|
-
function readFeatureRuntimeConfig(readConfig, getFallbackConfig) {
|
|
224
|
-
return readRuntimeValue((config) => readConfig(config), getFallbackConfig);
|
|
225
|
-
}
|
|
226
|
-
async function loadResourceRuntimeContext(options, name) {
|
|
227
|
-
const resolvedName = resolveNamedResourceName(options.feature, name);
|
|
228
|
-
const [config, definition] = await Promise.all([Promise.resolve(readFeatureRuntimeConfig(options.readConfig, options.getFallbackConfig)), loadRegistryEntry(options.registry.entries, resolvedName)]);
|
|
229
|
-
if (!definition) throw createUnknownNamedResourceError(options.feature, resolvedName);
|
|
230
|
-
if (options.registry.validate && !options.registry.validate(definition)) throw createInvalidNamedResourceError(options.feature, resolvedName);
|
|
231
|
-
return {
|
|
232
|
-
feature: options.feature,
|
|
233
|
-
name: resolvedName,
|
|
234
|
-
event: void 0,
|
|
235
|
-
config,
|
|
236
|
-
definition
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
function createResourceRuntime(options) {
|
|
240
|
-
async function load(name) {
|
|
241
|
-
return await loadResourceRuntimeContext(options, name);
|
|
45
|
+
if (kind === "cloudflare") {
|
|
46
|
+
const { createCloudflareRuntime } = await import("./cloudflare-Cog_r2Me.js").then((n) => n.t);
|
|
47
|
+
return createCloudflareRuntime(options);
|
|
242
48
|
}
|
|
243
|
-
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
return {
|
|
247
|
-
provider,
|
|
248
|
-
handle: await options.port.create(provider, context)
|
|
249
|
-
};
|
|
49
|
+
if (kind === "vercel") {
|
|
50
|
+
const { createVercelRuntime } = await import("./vercel-BGGrNpza.js").then((n) => n.r);
|
|
51
|
+
return createVercelRuntime(options);
|
|
250
52
|
}
|
|
251
|
-
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
if (!cache) return (await createHandle(context)).handle;
|
|
255
|
-
const { provider } = await createHandleWithoutConstruct(context, options.port);
|
|
256
|
-
if (!cache.isSafe(provider, context)) return await options.port.create(provider, context);
|
|
257
|
-
const cacheKey = cache.getKey?.(context) ?? context.name;
|
|
258
|
-
const existing = cache.store.get(cacheKey);
|
|
259
|
-
if (existing) return await existing;
|
|
260
|
-
const pending = Promise.resolve(options.port.create(provider, context)).catch((error) => {
|
|
261
|
-
cache.store.delete(cacheKey);
|
|
262
|
-
throw error;
|
|
263
|
-
});
|
|
264
|
-
cache.store.set(cacheKey, pending);
|
|
265
|
-
return await pending;
|
|
53
|
+
if (kind === "container") {
|
|
54
|
+
const { createContainerRuntime } = await import("./container-CqfD8yuE.js");
|
|
55
|
+
return createContainerRuntime(options);
|
|
266
56
|
}
|
|
267
|
-
|
|
268
|
-
load,
|
|
269
|
-
get
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
async function createHandleWithoutConstruct(context, port) {
|
|
273
|
-
const provider = await port.resolve(context);
|
|
274
|
-
await port.validate?.(provider, context);
|
|
275
|
-
return { provider };
|
|
276
|
-
}
|
|
277
|
-
//#endregion
|
|
278
|
-
//#region src/internal/shared/utils.ts
|
|
279
|
-
async function sleep(ms) {
|
|
280
|
-
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
57
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0033({ message: `[vitehub] Unknown Sandbox runtime kind "${String(kind)}". Expected "crabbox", "trusted-host", "cloudflare", "container", or "vercel".` });
|
|
281
58
|
}
|
|
282
|
-
|
|
283
|
-
//#region src/runtime/binary-sidecars.ts
|
|
284
|
-
const SANDBOX_VALUE_MARKER = "vitehub:sandbox:value";
|
|
285
|
-
function isPlainObject(value) {
|
|
59
|
+
function isSandboxRuntime(value) {
|
|
286
60
|
if (!value || typeof value !== "object") return false;
|
|
287
|
-
const
|
|
288
|
-
return
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
61
|
+
const runtime = value;
|
|
62
|
+
return hasDeclaredSandboxRuntimeMember(runtime, "name") && hasDeclaredSandboxRuntimeMember(runtime, "open") && hasDeclaredSandboxRuntimeMember(runtime, "prepare") && typeof runtime.name === "string" && typeof runtime.open === "function" && typeof runtime.prepare === "function";
|
|
63
|
+
}
|
|
64
|
+
const reservedEnvironment = /* @__PURE__ */ new Set([
|
|
65
|
+
"CODEX_HOME",
|
|
66
|
+
"HOME",
|
|
67
|
+
"INIT_CWD",
|
|
68
|
+
"OLDPWD",
|
|
69
|
+
"PWD",
|
|
70
|
+
"XDG_CACHE_HOME",
|
|
71
|
+
"XDG_CONFIG_HOME",
|
|
72
|
+
"XDG_STATE_HOME"
|
|
73
|
+
]);
|
|
74
|
+
async function resolveSandbox(definition, context, options = {}) {
|
|
75
|
+
if (!definition || typeof definition !== "object") throw sandboxErrorDiagnostics.SANDBOX_R0034({ message: "[vitehub] Sandbox requires a definition." });
|
|
76
|
+
const runtime = await resolveSandboxRuntime(definition.runtime);
|
|
77
|
+
if (definition.cwd !== void 0 && definition.checkout !== void 0) throw sandboxErrorDiagnostics.SANDBOX_R0035({ message: "[vitehub] Sandbox checkout cannot be combined with cwd." });
|
|
78
|
+
const cwdValue = await resolveValue(definition.cwd, context);
|
|
79
|
+
const cwd = cwdValue === void 0 ? void 0 : resolve(resolveString(cwdValue, "cwd"));
|
|
80
|
+
const checkout = definition.checkout ? {
|
|
81
|
+
ref: resolveString(await resolveValue(definition.checkout.ref, context), "checkout ref"),
|
|
82
|
+
remote: resolveString(await resolveValue(definition.checkout.remote, context), "checkout remote"),
|
|
83
|
+
sha: resolveSha(await resolveValue(definition.checkout.sha, context))
|
|
84
|
+
} : void 0;
|
|
85
|
+
const plan = resolvePlan(definition, context, cwd || process.cwd());
|
|
86
|
+
const toolchain = await resolveToolchain(definition.toolchain, checkout ? void 0 : cwd || process.cwd());
|
|
87
|
+
const requirements = normalizeRequirements([
|
|
88
|
+
...checkout ? ["git"] : [],
|
|
89
|
+
...toolchain ? ["node", ...toolchain.pins?.packageManager ? [toolchain.pins.packageManager.name] : []] : [],
|
|
90
|
+
...definition.requires || [],
|
|
91
|
+
...options.requires || []
|
|
92
|
+
]);
|
|
93
|
+
const input = {
|
|
94
|
+
...checkout ? { checkout } : {},
|
|
95
|
+
...cwd ? { cwd } : {},
|
|
96
|
+
identity: planIdentity(plan, requirements, checkout, toolchain),
|
|
97
|
+
plan,
|
|
98
|
+
requirements,
|
|
99
|
+
...toolchain ? { toolchain } : {}
|
|
319
100
|
};
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
state.directory ||= abortable(sandbox.files.mkdir(assetsDir, {
|
|
327
|
-
recursive: true,
|
|
328
|
-
signal
|
|
329
|
-
}));
|
|
330
|
-
await state.directory;
|
|
331
|
-
const bytes = blob ? new Uint8Array(await entry.arrayBuffer()) : entry;
|
|
332
|
-
throwIfAborted();
|
|
333
|
-
await abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }));
|
|
334
|
-
return tagged({
|
|
335
|
-
id,
|
|
336
|
-
kind: blob ? "blob" : buffer ? "buffer" : "uint8array",
|
|
337
|
-
...blob && entry.type ? { type: entry.type } : {},
|
|
338
|
-
tag: "binary"
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
if (isObjectRecord(entry) && applyToJSON && typeof entry.toJSON === "function") try {
|
|
342
|
-
return await encode(Reflect.apply(entry.toJSON, entry, [key]), ancestors, key, false);
|
|
343
|
-
} catch (error) {
|
|
344
|
-
if (isSandboxError(error)) throw error;
|
|
345
|
-
throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
|
|
346
|
-
}
|
|
347
|
-
if (Array.isArray(entry)) {
|
|
348
|
-
if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
|
|
349
|
-
const nextAncestors = new Set(ancestors).add(entry);
|
|
350
|
-
return await Promise.all(entry.map((item, index) => encode(item, nextAncestors, String(index))));
|
|
351
|
-
}
|
|
352
|
-
if (!isObjectRecord(entry)) return entry;
|
|
353
|
-
if (isBoxedJsonPrimitive(entry)) return await encode(entry.valueOf(), ancestors, key, false);
|
|
354
|
-
if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
|
|
355
|
-
const nextAncestors = new Set(ancestors).add(entry);
|
|
356
|
-
let sourceEntries;
|
|
357
|
-
try {
|
|
358
|
-
sourceEntries = Object.entries(entry).filter(([entryKey, item]) => applyToJSON || entryKey !== "toJSON" || typeof item !== "function");
|
|
359
|
-
} catch (error) {
|
|
360
|
-
throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
|
|
361
|
-
}
|
|
362
|
-
const entries = await Promise.all(sourceEntries.map(async ([entryKey, item]) => [entryKey, await encode(item, nextAncestors, entryKey)]));
|
|
363
|
-
return hasMarker(entry) ? tagged({
|
|
364
|
-
entries,
|
|
365
|
-
tag: "object"
|
|
366
|
-
}) : Object.fromEntries(entries);
|
|
367
|
-
}
|
|
368
|
-
return await encode(value, /* @__PURE__ */ new Set());
|
|
369
|
-
}
|
|
370
|
-
async function decodeSandboxValue(sandbox, value, assetsDir, label) {
|
|
371
|
-
if (Array.isArray(value)) return await Promise.all(value.map((entry) => decodeSandboxValue(sandbox, entry, assetsDir, label)));
|
|
372
|
-
if (!isPlainObject(value)) return value;
|
|
373
|
-
if (!hasMarker(value)) return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await decodeSandboxValue(sandbox, entry, assetsDir, label)])));
|
|
374
|
-
const descriptor = value[SANDBOX_VALUE_MARKER];
|
|
375
|
-
if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
|
|
376
|
-
if (descriptor.tag === "object") {
|
|
377
|
-
if (!Array.isArray(descriptor.entries) || !descriptor.entries.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string")) throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
|
|
378
|
-
return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [key, await decodeSandboxValue(sandbox, entry, assetsDir, label)])));
|
|
101
|
+
const prepared = await runtime.prepare(input);
|
|
102
|
+
let executionAuthority;
|
|
103
|
+
try {
|
|
104
|
+
executionAuthority = normalizeExecutionAuthority(prepared.executionAuthority);
|
|
105
|
+
} catch {
|
|
106
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0036({ message: `[vitehub] Sandbox runtime ${runtime.name} must declare executionAuthority.` });
|
|
379
107
|
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
}
|
|
388
|
-
//#endregion
|
|
389
|
-
//#region src/runtime/error-normalization.ts
|
|
390
|
-
function readSandboxErrorMetadata(error) {
|
|
391
|
-
if (!error || typeof error !== "object") return void 0;
|
|
392
|
-
const metadata = error;
|
|
393
|
-
const shape = getViteHubErrorShape(error);
|
|
394
|
-
return {
|
|
395
|
-
code: shape?.code || (typeof metadata.code === "string" ? metadata.code : void 0),
|
|
396
|
-
provider: typeof shape?.details?.provider === "string" ? shape.details.provider : typeof metadata.provider === "string" ? metadata.provider : void 0,
|
|
397
|
-
cause: metadata.cause,
|
|
398
|
-
details: shape?.details || (typeof metadata.details === "object" && metadata.details !== null ? metadata.details : void 0)
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
function toSandboxError(error) {
|
|
402
|
-
if (isSandboxError(error)) return error;
|
|
403
|
-
const metadata = readSandboxErrorMetadata(error);
|
|
404
|
-
if (error instanceof Error) return sandboxError(error.message || "Sandbox execution failed.", {
|
|
405
|
-
code: sandboxCode(metadata?.code),
|
|
406
|
-
provider: metadata?.provider,
|
|
407
|
-
details: metadata?.details,
|
|
408
|
-
cause: metadata?.cause ?? error
|
|
108
|
+
const homeState = plan.state.map((state) => {
|
|
109
|
+
const preparedState = prepared.home?.state.find((target) => target.path === state.path);
|
|
110
|
+
if (typeof preparedState?.identity !== "string" || !preparedState.identity) throw sandboxErrorDiagnostics.SANDBOX_R0037({ message: `[vitehub] Sandbox runtime ${runtime.name} must declare an opaque Home state identity for ${state.path}.` });
|
|
111
|
+
return Object.freeze({
|
|
112
|
+
identity: preparedState.identity,
|
|
113
|
+
path: state.path
|
|
114
|
+
});
|
|
409
115
|
});
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
116
|
+
const sandboxPlan = Object.freeze({
|
|
117
|
+
...prepared,
|
|
118
|
+
executionAuthority,
|
|
119
|
+
home: Object.freeze({ state: Object.freeze(homeState) }),
|
|
120
|
+
...toolchain ? { toolchain: Object.freeze({
|
|
121
|
+
...toolchain.pins?.node ? { node: toolchain.pins.node } : {},
|
|
122
|
+
...toolchain.pins?.packageManager ? { packageManager: toolchain.pins.packageManager } : {},
|
|
123
|
+
source: toolchain.pins ? "project" : "checkout"
|
|
124
|
+
}) } : {}
|
|
415
125
|
});
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
] : [
|
|
431
|
-
` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
|
|
432
|
-
` const definition = mod?.default`,
|
|
433
|
-
` if (!definition || typeof definition.run !== 'function')`,
|
|
434
|
-
` throw new Error('Sandbox Definition must default-export defineSandbox({ run }).')`,
|
|
435
|
-
` const result = await definition.run(input.payload, input.context)`
|
|
436
|
-
];
|
|
437
|
-
return [
|
|
438
|
-
`import { mkdir, readFile, writeFile } from 'node:fs/promises'`,
|
|
439
|
-
`import { Buffer } from 'node:buffer'`,
|
|
440
|
-
`import { pathToFileURL } from 'node:url'`,
|
|
441
|
-
``,
|
|
442
|
-
`function normalizeError(error) {`,
|
|
443
|
-
` if (error instanceof Error) {`,
|
|
444
|
-
` return {`,
|
|
445
|
-
` name: error.name,`,
|
|
446
|
-
` message: error.message,`,
|
|
447
|
-
` stack: error.stack,`,
|
|
448
|
-
` cause: error.cause ? String(error.cause) : undefined,`,
|
|
449
|
-
` }`,
|
|
450
|
-
` }`,
|
|
451
|
-
` return {`,
|
|
452
|
-
` name: 'Error',`,
|
|
453
|
-
` message: String(error),`,
|
|
454
|
-
` }`,
|
|
455
|
-
`}`,
|
|
456
|
-
``,
|
|
457
|
-
`const valueMarker = ${JSON.stringify("vitehub:sandbox:value")}`,
|
|
458
|
-
``,
|
|
459
|
-
`function isPlainObject(value) {`,
|
|
460
|
-
` if (!value || typeof value !== 'object') return false`,
|
|
461
|
-
` const prototype = Object.getPrototypeOf(value)`,
|
|
462
|
-
` return prototype === Object.prototype || prototype === null`,
|
|
463
|
-
`}`,
|
|
464
|
-
``,
|
|
465
|
-
`function hasMarker(value) {`,
|
|
466
|
-
` return Object.prototype.hasOwnProperty.call(value, valueMarker)`,
|
|
467
|
-
`}`,
|
|
468
|
-
``,
|
|
469
|
-
`function isBoxedJsonPrimitive(value) {`,
|
|
470
|
-
` return value instanceof Boolean`,
|
|
471
|
-
` || value instanceof Number`,
|
|
472
|
-
` || value instanceof String`,
|
|
473
|
-
` || Object.getPrototypeOf(value) === BigInt.prototype`,
|
|
474
|
-
`}`,
|
|
475
|
-
``,
|
|
476
|
-
`function invalidDescriptor(label) {`,
|
|
477
|
-
` return new TypeError('Sandbox ' + label + ' contains an invalid binary sidecar descriptor.')`,
|
|
478
|
-
`}`,
|
|
479
|
-
``,
|
|
480
|
-
`async function reviveValue(value, assetsDir, label) {`,
|
|
481
|
-
` if (Array.isArray(value))`,
|
|
482
|
-
` return await Promise.all(value.map(entry => reviveValue(entry, assetsDir, label)))`,
|
|
483
|
-
` if (!value || typeof value !== 'object') return value`,
|
|
484
|
-
` if (!hasMarker(value)) {`,
|
|
485
|
-
` return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [`,
|
|
486
|
-
` key,`,
|
|
487
|
-
` await reviveValue(entry, assetsDir, label),`,
|
|
488
|
-
` ])))`,
|
|
489
|
-
` }`,
|
|
490
|
-
` const descriptor = value[valueMarker]`,
|
|
491
|
-
` if (!isPlainObject(descriptor) || typeof descriptor.tag !== 'string')`,
|
|
492
|
-
` throw invalidDescriptor(label)`,
|
|
493
|
-
` if (descriptor.tag === 'object') {`,
|
|
494
|
-
` if (!Array.isArray(descriptor.entries) || !descriptor.entries.every(entry => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'))`,
|
|
495
|
-
` throw invalidDescriptor(label)`,
|
|
496
|
-
` return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [`,
|
|
497
|
-
` key,`,
|
|
498
|
-
` await reviveValue(entry, assetsDir, label),`,
|
|
499
|
-
` ])))`,
|
|
500
|
-
` }`,
|
|
501
|
-
` if (descriptor.tag !== 'binary'`,
|
|
502
|
-
` || !Number.isSafeInteger(descriptor.id)`,
|
|
503
|
-
` || Object.is(descriptor.id, -0)`,
|
|
504
|
-
` || descriptor.id < 0`,
|
|
505
|
-
` || (descriptor.kind !== 'blob' && descriptor.kind !== 'buffer' && descriptor.kind !== 'uint8array')`,
|
|
506
|
-
` || (typeof descriptor.type !== 'undefined' && typeof descriptor.type !== 'string'))`,
|
|
507
|
-
` throw invalidDescriptor(label)`,
|
|
508
|
-
` const bytes = new Uint8Array(await readFile(assetsDir + '/' + descriptor.id))`,
|
|
509
|
-
` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
|
|
510
|
-
`}`,
|
|
511
|
-
``,
|
|
512
|
-
`async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
|
|
513
|
-
` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
|
|
514
|
-
` const buffer = Buffer.isBuffer(value)`,
|
|
515
|
-
` if (blob || value instanceof Uint8Array) {`,
|
|
516
|
-
` const id = state.nextId++`,
|
|
517
|
-
` state.directory ||= mkdir(assetsDir, { recursive: true })`,
|
|
518
|
-
` await state.directory`,
|
|
519
|
-
` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
|
|
520
|
-
` await writeFile(assetsDir + '/' + id, bytes)`,
|
|
521
|
-
` return { [valueMarker]: {`,
|
|
522
|
-
` id,`,
|
|
523
|
-
` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
|
|
524
|
-
` ...(blob && value.type ? { type: value.type } : {}),`,
|
|
525
|
-
` tag: 'binary',`,
|
|
526
|
-
` } }`,
|
|
527
|
-
` }`,
|
|
528
|
-
` if (value && typeof value === 'object' && applyToJSON && typeof value.toJSON === 'function')`,
|
|
529
|
-
` return await extractValue(Reflect.apply(value.toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
|
|
530
|
-
` if (Array.isArray(value)) {`,
|
|
531
|
-
` if (ancestors.has(value))`,
|
|
532
|
-
` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
|
|
533
|
-
` const nextAncestors = new Set(ancestors).add(value)`,
|
|
534
|
-
` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
|
|
535
|
-
` }`,
|
|
536
|
-
` if (!value || typeof value !== 'object') return value`,
|
|
537
|
-
` if (isBoxedJsonPrimitive(value)) return await extractValue(value.valueOf(), assetsDir, state, ancestors, key, false)`,
|
|
538
|
-
` if (ancestors.has(value))`,
|
|
539
|
-
` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
|
|
540
|
-
` const nextAncestors = new Set(ancestors).add(value)`,
|
|
541
|
-
` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
|
|
542
|
-
` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
|
|
543
|
-
` entryKey,`,
|
|
544
|
-
` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
|
|
545
|
-
` ]))`,
|
|
546
|
-
` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
|
|
547
|
-
`}`,
|
|
548
|
-
``,
|
|
549
|
-
`async function serializeSuccess(result, assetsDir) {`,
|
|
550
|
-
` try {`,
|
|
551
|
-
` const encoded = await extractValue(result, assetsDir)`,
|
|
552
|
-
` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
|
|
553
|
-
` const type = typeof value`,
|
|
554
|
-
` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
|
|
555
|
-
` throw new TypeError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
|
|
556
|
-
` if (type === 'number' && !Number.isFinite(value))`,
|
|
557
|
-
` throw new TypeError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
|
|
558
|
-
` return value`,
|
|
559
|
-
` })`,
|
|
560
|
-
` }`,
|
|
561
|
-
` catch (error) {`,
|
|
562
|
-
` if (error instanceof TypeError && error.message.startsWith('Sandbox result must be JSON-serializable'))`,
|
|
563
|
-
` throw error`,
|
|
564
|
-
` throw new TypeError('Sandbox result must be JSON-serializable.', { cause: error })`,
|
|
565
|
-
` }`,
|
|
566
|
-
`}`,
|
|
567
|
-
``,
|
|
568
|
-
`export async function main(argv = process.argv.slice(2)) {`,
|
|
569
|
-
` const [inputPath, outputPath] = argv`,
|
|
570
|
-
` try {`,
|
|
571
|
-
` const raw = await readFile(inputPath, 'utf8')`,
|
|
572
|
-
` const input = await reviveValue(JSON.parse(raw || '{}'), inputPath + '.files', 'input')`,
|
|
573
|
-
...invocation,
|
|
574
|
-
` const output = await serializeSuccess(result, outputPath + '.files')`,
|
|
575
|
-
` await writeFile(outputPath, output)`,
|
|
576
|
-
` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
577
|
-
` }`,
|
|
578
|
-
` catch (error) {`,
|
|
579
|
-
` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
|
|
580
|
-
` await writeFile(outputPath, output)`,
|
|
581
|
-
` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
582
|
-
` process.exitCode = 1`,
|
|
583
|
-
` }`,
|
|
584
|
-
`}`,
|
|
585
|
-
``,
|
|
586
|
-
`await main()`,
|
|
587
|
-
``
|
|
588
|
-
].join("\n");
|
|
589
|
-
}
|
|
590
|
-
//#endregion
|
|
591
|
-
//#region src/runtime/execution-files.ts
|
|
592
|
-
const DEFAULT_DEFINITION_ENTRY = "definition.js";
|
|
593
|
-
function normalizeSandboxDefinitionBundle(source) {
|
|
594
|
-
if (typeof source === "string") return {
|
|
595
|
-
entry: DEFAULT_DEFINITION_ENTRY,
|
|
596
|
-
modules: { [DEFAULT_DEFINITION_ENTRY]: source }
|
|
597
|
-
};
|
|
598
|
-
return source;
|
|
599
|
-
}
|
|
600
|
-
function createExecutionFiles(definitionName) {
|
|
601
|
-
const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
602
|
-
const baseDir = `/tmp/vitehub-sandbox/${definitionName.replace(/[^a-z0-9/_-]/gi, "_")}-${nonce}`;
|
|
603
|
-
return {
|
|
604
|
-
baseDir,
|
|
605
|
-
entryPath: `${baseDir}/entry.mjs`,
|
|
606
|
-
inputAssetsDir: `${baseDir}/input.json.files`,
|
|
607
|
-
inputPath: `${baseDir}/input.json`,
|
|
608
|
-
outputAssetsDir: `${baseDir}/output.json.files`,
|
|
609
|
-
outputPath: `${baseDir}/output.json`
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
function resolveSandboxModulePath(baseDir, modulePath) {
|
|
613
|
-
if (modulePath === ".") return baseDir;
|
|
614
|
-
return `${baseDir}/${modulePath}`;
|
|
615
|
-
}
|
|
616
|
-
function normalizeSandboxBundlePath(path) {
|
|
617
|
-
const slashPath = path.replace(/\\/g, "/");
|
|
618
|
-
const normalized = slashPath.replace(/^\/+|\/+$/g, "");
|
|
619
|
-
const parts = normalized.split("/").filter(Boolean);
|
|
620
|
-
if (!normalized || slashPath.startsWith("/") || /^[A-Za-z]:\//.test(slashPath) || parts.some((part) => part === "." || part === "..")) throw new Error(`[vitehub] Sandbox bundle path must stay inside the project: ${path}.`);
|
|
621
|
-
return parts.join("/");
|
|
622
|
-
}
|
|
623
|
-
async function writeSandboxDefinitionBundle(sandbox, baseDir, bundle) {
|
|
624
|
-
const files = Object.entries({
|
|
625
|
-
...bundle.project ? Object.fromEntries(Object.entries(bundle.project.files).map(([path, file]) => [path, Uint8Array.from(Buffer.from(file.contents, file.encoding))])) : {},
|
|
626
|
-
...bundle.modules
|
|
627
|
-
}).map(([path, source]) => ({
|
|
628
|
-
path: normalizeSandboxBundlePath(path),
|
|
629
|
-
source
|
|
630
|
-
}));
|
|
631
|
-
const modes = Object.entries(bundle.project?.files || {}).filter(([, file]) => Boolean(file.mode)).map(([path, file]) => ({
|
|
632
|
-
mode: file.mode,
|
|
633
|
-
path: normalizeSandboxBundlePath(path)
|
|
634
|
-
}));
|
|
635
|
-
await sandbox.files.remove(baseDir, { recursive: true });
|
|
636
|
-
await sandbox.files.mkdir(baseDir, { recursive: true });
|
|
637
|
-
await Promise.all(files.map(async ({ path, source }) => {
|
|
638
|
-
const parent = dirname(path);
|
|
639
|
-
if (parent !== ".") await sandbox.files.mkdir(`${baseDir}/${parent}`, { recursive: true });
|
|
640
|
-
await sandbox.files.write(`${baseDir}/${path}`, typeof source === "string" ? new TextEncoder().encode(source) : source);
|
|
641
|
-
}));
|
|
642
|
-
await Promise.all(modes.map(async ({ mode, path }) => {
|
|
643
|
-
await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`]);
|
|
644
|
-
}));
|
|
645
|
-
}
|
|
646
|
-
//#endregion
|
|
647
|
-
//#region src/runtime/output-recovery.ts
|
|
648
|
-
const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
|
|
649
|
-
const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
|
|
650
|
-
const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
|
|
651
|
-
const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
|
|
652
|
-
const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
|
|
653
|
-
const HANDLER_DIAGNOSTIC_LENGTH = 16384;
|
|
654
|
-
function getErrorMessage(error) {
|
|
655
|
-
if (error instanceof Error) return error.message;
|
|
656
|
-
if (error && typeof error === "object") {
|
|
657
|
-
const candidate = error;
|
|
658
|
-
if (typeof candidate.message === "string" && candidate.message) return candidate.message;
|
|
659
|
-
if (typeof candidate.stderr === "string" && candidate.stderr) return candidate.stderr;
|
|
660
|
-
if (typeof candidate.stdout === "string" && candidate.stdout) return candidate.stdout;
|
|
661
|
-
}
|
|
662
|
-
if (error === void 0) return void 0;
|
|
663
|
-
return String(error);
|
|
664
|
-
}
|
|
665
|
-
function isRecoverableCloudflareExecError(error) {
|
|
666
|
-
const metadata = readSandboxErrorMetadata(error);
|
|
667
|
-
if (metadata?.provider && metadata.provider !== "cloudflare") return false;
|
|
668
|
-
if (metadata?.code === "SANDBOX_TIMEOUT" || metadata?.code === "SANDBOX_TRANSPORT_ERROR") return true;
|
|
669
|
-
return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
|
|
670
|
-
}
|
|
671
|
-
function createHandlerError(message, provider, details) {
|
|
672
|
-
const publicDetails = {};
|
|
673
|
-
for (const [key, value] of Object.entries(details || {})) if (typeof value === "string") publicDetails[key] = value.slice(0, HANDLER_DIAGNOSTIC_LENGTH);
|
|
674
|
-
else if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) publicDetails[key] = value;
|
|
675
|
-
return sandboxError(message.slice(0, HANDLER_DIAGNOSTIC_LENGTH) || "Sandbox handler failed.", {
|
|
676
|
-
code: "SANDBOX_HANDLER_ERROR",
|
|
677
|
-
provider,
|
|
678
|
-
details: Object.keys(publicDetails).length ? publicDetails : void 0
|
|
126
|
+
return Object.freeze({
|
|
127
|
+
async open(options) {
|
|
128
|
+
options?.signal?.throwIfAborted();
|
|
129
|
+
const session = await runtime.open(input, {
|
|
130
|
+
...options,
|
|
131
|
+
executionAuthority: sandboxPlan.executionAuthority
|
|
132
|
+
});
|
|
133
|
+
if (toolchain && !session.toolchain) {
|
|
134
|
+
await session.close().catch(() => void 0);
|
|
135
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0156({ message: `[vitehub] Sandbox runtime ${runtime.name} does not provision toolchains. Use a built-in runtime or remove sandbox.toolchain.` });
|
|
136
|
+
}
|
|
137
|
+
return session;
|
|
138
|
+
},
|
|
139
|
+
plan: sandboxPlan
|
|
679
140
|
});
|
|
680
141
|
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
142
|
+
/** Read toolchain pins now unless they come from a checkout that exists only after open. */
|
|
143
|
+
async function resolveToolchain(declaration, projectRoot) {
|
|
144
|
+
if (declaration === void 0) return;
|
|
145
|
+
const [{ normalizeToolchain, readToolchainPins, toolchainReadsProject }, { readHostProjectFiles }] = await Promise.all([import("./toolchain-BIVGMRty.js").then((n) => n.i), import("./internal/host-toolchain.js")]);
|
|
146
|
+
const toolchain = normalizeToolchain(declaration, "sandbox.toolchain");
|
|
147
|
+
if (!toolchain) return;
|
|
148
|
+
if (!projectRoot && toolchainReadsProject(toolchain)) return toolchain;
|
|
149
|
+
const files = toolchainReadsProject(toolchain) ? await readHostProjectFiles(projectRoot) : {};
|
|
150
|
+
return Object.freeze({
|
|
151
|
+
...toolchain,
|
|
152
|
+
pins: readToolchainPins(toolchain, files)
|
|
686
153
|
});
|
|
687
154
|
}
|
|
688
|
-
function
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
if (markerIndex < 0) continue;
|
|
701
|
-
return line.slice(markerIndex + 18);
|
|
702
|
-
}
|
|
703
|
-
return null;
|
|
704
|
-
}
|
|
705
|
-
function previewExecutionStream(stream) {
|
|
706
|
-
if (!stream) return void 0;
|
|
707
|
-
return stream.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH);
|
|
708
|
-
}
|
|
709
|
-
function getExecutionDiagnostics(execution) {
|
|
710
|
-
return {
|
|
711
|
-
args: Array.isArray(execution?.meta?.args) ? execution?.meta?.args : void 0,
|
|
712
|
-
command: typeof execution?.meta?.command === "string" ? execution.meta.command : void 0,
|
|
713
|
-
cwd: typeof execution?.meta?.cwd === "string" ? execution.meta.cwd : void 0,
|
|
714
|
-
exitCode: typeof execution?.code === "undefined" ? void 0 : execution.code,
|
|
715
|
-
stderrPreview: previewExecutionStream(execution?.stderr),
|
|
716
|
-
stdoutPreview: previewExecutionStream(execution?.stdout)
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
function getErrorDiagnostics(error) {
|
|
720
|
-
if (!error || typeof error !== "object" || !("details" in error)) return {};
|
|
721
|
-
const details = error.details;
|
|
722
|
-
if (!details || typeof details !== "object") return {};
|
|
723
|
-
return {
|
|
724
|
-
args: Array.isArray(details.args) ? details.args : void 0,
|
|
725
|
-
command: typeof details.command === "string" ? details.command : void 0,
|
|
726
|
-
cwd: typeof details.cwd === "string" ? details.cwd : void 0,
|
|
727
|
-
exitCode: typeof details.exitCode === "number" || details.exitCode === null ? details.exitCode : void 0,
|
|
728
|
-
spawnErrorCode: typeof details.spawnErrorCode === "string" ? details.spawnErrorCode : void 0,
|
|
729
|
-
spawnErrorMessage: typeof details.spawnErrorMessage === "string" ? details.spawnErrorMessage : void 0,
|
|
730
|
-
stderrPreview: typeof details.stderrPreview === "string" ? details.stderrPreview : void 0,
|
|
731
|
-
stdoutPreview: typeof details.stdoutPreview === "string" ? details.stdoutPreview : void 0
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
function resolveExecOutputRecoveryTimeout(timeout) {
|
|
735
|
-
if (!timeout || timeout <= 0) return DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS;
|
|
736
|
-
return Math.min(MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.max(MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.floor(timeout * .1)));
|
|
737
|
-
}
|
|
738
|
-
function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, details) {
|
|
739
|
-
return createHandlerError("Sandbox definition execution failed before producing an output file.", sandbox.provider, {
|
|
740
|
-
outputPath,
|
|
741
|
-
cause: getErrorMessage(error),
|
|
742
|
-
recoveryTimeout,
|
|
743
|
-
...details,
|
|
744
|
-
...getErrorDiagnostics(error),
|
|
745
|
-
...getExecutionDiagnostics(execution)
|
|
155
|
+
function planIdentity(plan, requirements, checkout, toolchain) {
|
|
156
|
+
const value = JSON.stringify({
|
|
157
|
+
checkout,
|
|
158
|
+
toolchain,
|
|
159
|
+
env: Object.keys(plan.env).toSorted(),
|
|
160
|
+
files: Object.keys(plan.files).toSorted(),
|
|
161
|
+
requirements,
|
|
162
|
+
state: plan.state.map(({ key, path, seed }) => ({
|
|
163
|
+
key,
|
|
164
|
+
path,
|
|
165
|
+
seed: Object.keys(seed).toSorted()
|
|
166
|
+
})).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
|
|
746
167
|
});
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
if (
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
168
|
+
const fingerprint = createHash("sha256").update(value).digest("hex");
|
|
169
|
+
return Object.keys(plan.env).length > 0 || Object.keys(plan.files).length > 0 || plan.state.some(({ seed }) => Object.keys(seed).length > 0) ? `${fingerprint}-${randomUUID()}` : fingerprint;
|
|
170
|
+
}
|
|
171
|
+
function resolvePlan(definition, context, sourceRoot) {
|
|
172
|
+
if (definition.home !== void 0 && (!definition.home || typeof definition.home !== "object" || Array.isArray(definition.home))) throw sandboxErrorDiagnostics.SANDBOX_R0038({ message: "[vitehub] Sandbox home must be a declarative object." });
|
|
173
|
+
const env = Object.fromEntries(Object.entries(optionalRecord(definition.env, "env")).map(([name, value]) => {
|
|
174
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw sandboxErrorDiagnostics.SANDBOX_R0039({ message: `[vitehub] Invalid Sandbox environment variable: ${name}` });
|
|
175
|
+
if (reservedEnvironment.has(name)) throw sandboxErrorDiagnostics.SANDBOX_R0040({ message: `[vitehub] ${name} is managed by the Sandbox runtime.` });
|
|
176
|
+
return [name, async () => {
|
|
177
|
+
const resolved = await resolveValue(value, context);
|
|
178
|
+
if (resolved === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0041({ message: `[vitehub] Sandbox environment value ${name} is required.` });
|
|
179
|
+
return resolveString(resolved, `environment value ${name}`);
|
|
180
|
+
}];
|
|
181
|
+
}));
|
|
182
|
+
const files = normalizeFiles(definition.home?.files, context, "home.files", sourceRoot);
|
|
183
|
+
const state = Object.entries(optionalRecord(definition.home?.state, "home.state")).map(([path, value]) => {
|
|
184
|
+
const target = relativePath(path, "home.state target");
|
|
185
|
+
if (!value || typeof value !== "object" || typeof value.key !== "string" || !value.key.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0042({ message: `[vitehub] Sandbox state ${path} requires a non-empty key.` });
|
|
186
|
+
return {
|
|
187
|
+
key: value.key.trim(),
|
|
188
|
+
path: target,
|
|
189
|
+
projections: [],
|
|
190
|
+
seed: normalizeFiles(value.seed, context, `home.state ${path} seed`, sourceRoot)
|
|
191
|
+
};
|
|
766
192
|
});
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
}
|
|
772
|
-
async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution) {
|
|
773
|
-
const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
|
|
774
|
-
if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
|
|
775
|
-
return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
|
|
776
|
-
}
|
|
777
|
-
async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution) {
|
|
778
|
-
const executionOutput = extractSandboxOutputFromExecution(execution) || extractSandboxOutputFromExecution(error);
|
|
779
|
-
if (executionOutput) return executionOutput;
|
|
780
|
-
try {
|
|
781
|
-
const output = await sandbox.readFile(outputPath);
|
|
782
|
-
if (tryParseSandboxOutput(output)) return output;
|
|
783
|
-
} catch {
|
|
784
|
-
return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
|
|
193
|
+
const stateKeys = /* @__PURE__ */ new Set();
|
|
194
|
+
for (const value of state) {
|
|
195
|
+
if (stateKeys.has(value.key)) throw sandboxErrorDiagnostics.SANDBOX_R0043({ message: `[vitehub] Sandbox state keys must be unique: ${value.key}` });
|
|
196
|
+
stateKeys.add(value.key);
|
|
785
197
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
const projectPreparations = /* @__PURE__ */ new Map();
|
|
792
|
-
function toJson(value, label) {
|
|
793
|
-
try {
|
|
794
|
-
return JSON.stringify(value);
|
|
795
|
-
} catch (error) {
|
|
796
|
-
throw sandboxError(`Sandbox ${label} must be JSON-serializable.`, {
|
|
797
|
-
code: "SANDBOX_SERIALIZATION_ERROR",
|
|
798
|
-
details: { label },
|
|
799
|
-
cause: error
|
|
800
|
-
});
|
|
198
|
+
validateTargets(Object.keys(files), state.map((value) => value.path));
|
|
199
|
+
for (const value of state) {
|
|
200
|
+
const projectedFiles = Object.keys(files).filter((file) => isDescendant(file, value.path)).map((file) => file.slice(value.path.length + 1));
|
|
201
|
+
value.projections.push(...projectedFiles.toSorted());
|
|
202
|
+
validateFileTargets([...Object.keys(value.seed), ...projectedFiles], `home.state ${value.path} projected`);
|
|
801
203
|
}
|
|
802
|
-
}
|
|
803
|
-
function resolveLauncher() {
|
|
804
204
|
return {
|
|
805
|
-
|
|
806
|
-
|
|
205
|
+
env: Object.freeze(env),
|
|
206
|
+
files: Object.freeze(files),
|
|
207
|
+
state: Object.freeze(state)
|
|
807
208
|
};
|
|
808
209
|
}
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
preparation = prepareSandboxProjectAtomically(sandbox, {
|
|
823
|
-
...bundle,
|
|
824
|
-
project
|
|
825
|
-
}, projectDir, marker, options);
|
|
826
|
-
projectPreparations.set(preparationKey, preparation);
|
|
827
|
-
preparation.finally(() => {
|
|
828
|
-
if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
|
|
829
|
-
}).catch(() => {});
|
|
830
|
-
}
|
|
831
|
-
try {
|
|
832
|
-
await preparation;
|
|
833
|
-
} catch (error) {
|
|
834
|
-
if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
|
|
835
|
-
if (owned || options.signal?.aborted) throw error;
|
|
836
|
-
continue;
|
|
837
|
-
}
|
|
838
|
-
if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
|
|
839
|
-
}
|
|
840
|
-
return projectDir;
|
|
841
|
-
}
|
|
842
|
-
async function prepareSandboxProjectAtomically(sandbox, bundle, projectDir, marker, options) {
|
|
843
|
-
if (await sandbox.exists(marker)) return;
|
|
844
|
-
const staging = `${projectDir}.staging-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
845
|
-
try {
|
|
846
|
-
await sandbox.mkdir(staging, { recursive: true });
|
|
847
|
-
await writeSandboxDefinitionBundle(sandbox, staging, bundle);
|
|
848
|
-
const result = await executeLauncher(sandbox, bundle.project.install.command, bundle.project.install.args, {
|
|
849
|
-
...options,
|
|
850
|
-
cwd: resolveSandboxModulePath(staging, bundle.project.install.cwd)
|
|
851
|
-
});
|
|
852
|
-
if (!result.ok) throw sandboxError("Sandbox package preparation failed.", {
|
|
853
|
-
code: "SANDBOX_EXECUTION_ERROR",
|
|
854
|
-
details: {
|
|
855
|
-
command: bundle.project.install.command,
|
|
856
|
-
exitCode: result.code,
|
|
857
|
-
stderr: result.stderr
|
|
858
|
-
}
|
|
859
|
-
});
|
|
860
|
-
await sandbox.mkdir(`${staging}/.vitehub`, { recursive: true });
|
|
861
|
-
await sandbox.writeFile(`${staging}/.vitehub/prepared`, bundle.project.digest);
|
|
862
|
-
const published = await sandbox.exec("node", [
|
|
863
|
-
"-e",
|
|
864
|
-
"import(\"node:fs/promises\").then(({ rename }) => rename(process.argv[1], process.argv[2]))",
|
|
865
|
-
staging,
|
|
866
|
-
projectDir
|
|
867
|
-
], { signal: options.signal });
|
|
868
|
-
if (!published.ok && !await sandbox.exists(marker)) throw sandboxError("Sandbox package preparation could not publish its project.", {
|
|
869
|
-
code: "SANDBOX_EXECUTION_ERROR",
|
|
870
|
-
details: {
|
|
871
|
-
exitCode: published.code,
|
|
872
|
-
stderr: published.stderr
|
|
873
|
-
}
|
|
874
|
-
});
|
|
875
|
-
} finally {
|
|
876
|
-
await sandbox.exec("rm", [
|
|
877
|
-
"-rf",
|
|
878
|
-
"--",
|
|
879
|
-
staging
|
|
880
|
-
]).catch(() => {});
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
async function executeLauncher(sandbox, command, args, options) {
|
|
884
|
-
return await sandbox.exec(command, args, {
|
|
885
|
-
cwd: options.cwd,
|
|
886
|
-
env: options.env,
|
|
887
|
-
signal: options.signal,
|
|
888
|
-
timeout: options.timeout
|
|
889
|
-
});
|
|
890
|
-
}
|
|
891
|
-
async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, deadline, lifecycle) {
|
|
892
|
-
const bundle = normalizeSandboxDefinitionBundle(source);
|
|
893
|
-
const files = createExecutionFiles(definitionName);
|
|
894
|
-
const throwIfAborted = () => {
|
|
895
|
-
if (signal?.aborted) throw createTimeoutError(sandbox.provider, definitionOptions?.timeout || 0);
|
|
896
|
-
};
|
|
897
|
-
await sandbox.mkdir(files.baseDir, { recursive: true });
|
|
898
|
-
try {
|
|
899
|
-
throwIfAborted();
|
|
900
|
-
let inputJson = bundle.project ? toJson(await encodeSandboxValue(sandbox, {
|
|
901
|
-
payload,
|
|
902
|
-
context
|
|
903
|
-
}, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
|
|
904
|
-
const bundleBaseDir = await prepareSandboxProject(sandbox, bundle, files.baseDir, {
|
|
905
|
-
deadline,
|
|
906
|
-
signal,
|
|
907
|
-
timeout: definitionOptions?.timeout
|
|
908
|
-
});
|
|
909
|
-
if (!bundle.project) await writeSandboxDefinitionBundle(sandbox, bundleBaseDir, bundle);
|
|
910
|
-
inputJson ||= toJson(await encodeSandboxValue(sandbox, {
|
|
911
|
-
payload,
|
|
912
|
-
context
|
|
913
|
-
}, files.inputAssetsDir, "payload/context", signal), "payload/context");
|
|
914
|
-
const definitionPath = resolveSandboxModulePath(bundleBaseDir, bundle.entry);
|
|
915
|
-
throwIfAborted();
|
|
916
|
-
await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution)), sandbox.writeFile(files.inputPath, inputJson)]);
|
|
917
|
-
throwIfAborted();
|
|
918
|
-
const launcher = resolveLauncher();
|
|
919
|
-
const execArgs = [
|
|
920
|
-
...launcher.args,
|
|
921
|
-
files.entryPath,
|
|
922
|
-
files.inputPath,
|
|
923
|
-
files.outputPath
|
|
924
|
-
];
|
|
925
|
-
let outputRaw = "";
|
|
926
|
-
let execution;
|
|
927
|
-
try {
|
|
928
|
-
lifecycle?.onHandlerStart?.();
|
|
929
|
-
execution = await executeLauncher(sandbox, launcher.command, execArgs, {
|
|
930
|
-
cwd: bundle.project ? resolveSandboxModulePath(bundleBaseDir, bundle.project.packagePath) : files.baseDir,
|
|
931
|
-
deadline,
|
|
932
|
-
env: definitionOptions?.env,
|
|
933
|
-
signal,
|
|
934
|
-
timeout: definitionOptions?.timeout
|
|
935
|
-
});
|
|
936
|
-
outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution);
|
|
937
|
-
} catch (error) {
|
|
938
|
-
if (readSandboxErrorMetadata(error)?.details?.operation === "createSession") throw error;
|
|
939
|
-
if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
|
|
940
|
-
else {
|
|
941
|
-
const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
|
|
942
|
-
if (recoveredOutput == null) throw error;
|
|
943
|
-
outputRaw = recoveredOutput;
|
|
944
|
-
}
|
|
210
|
+
function normalizeFiles(input, context, label, sourceRoot) {
|
|
211
|
+
const files = Object.fromEntries(Object.entries(optionalRecord(input, label)).map(([path, value]) => {
|
|
212
|
+
const target = relativePath(path, `${label} target`);
|
|
213
|
+
if (!value || typeof value !== "object") throw sandboxErrorDiagnostics.SANDBOX_R0044({ message: `[vitehub] Sandbox file ${path} requires from or contents.` });
|
|
214
|
+
const hasFrom = "from" in value;
|
|
215
|
+
const hasContents = "contents" in value;
|
|
216
|
+
const ownsFrom = Object.hasOwn(value, "from");
|
|
217
|
+
const ownsContents = Object.hasOwn(value, "contents");
|
|
218
|
+
if (hasFrom !== ownsFrom || hasContents !== ownsContents) throw sandboxErrorDiagnostics.SANDBOX_R0046({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
|
|
219
|
+
if (hasFrom && ownsFrom) {
|
|
220
|
+
if (Object.keys(value).length !== 1 || typeof value.from !== "string") throw sandboxErrorDiagnostics.SANDBOX_R0045({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
|
|
221
|
+
const source = relativePath(value.from, `${label} source`);
|
|
222
|
+
return [target, { resolve: async () => await readProjectFile(source) }];
|
|
945
223
|
}
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
if (
|
|
962
|
-
|
|
963
|
-
"--",
|
|
964
|
-
files.baseDir
|
|
965
|
-
]).catch(() => {});
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context, lifecycle) {
|
|
969
|
-
const timeout = definitionOptions?.timeout;
|
|
970
|
-
if (timeout === void 0 || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, void 0, void 0, lifecycle);
|
|
971
|
-
let timeoutId;
|
|
972
|
-
const abortController = new AbortController();
|
|
973
|
-
const deadline = Date.now() + timeout;
|
|
974
|
-
try {
|
|
975
|
-
return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, abortController.signal, deadline, lifecycle), new Promise((_, reject) => {
|
|
976
|
-
timeoutId = setTimeout(() => {
|
|
977
|
-
const timeoutError = createTimeoutError(sandbox.provider, timeout);
|
|
978
|
-
abortController.abort(timeoutError);
|
|
979
|
-
reject(timeoutError);
|
|
980
|
-
}, timeout);
|
|
981
|
-
})]);
|
|
982
|
-
} finally {
|
|
983
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
224
|
+
if (!(hasContents && ownsContents) || Object.keys(value).length !== 1) throw sandboxErrorDiagnostics.SANDBOX_R0046({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
|
|
225
|
+
return [target, { resolve: async () => {
|
|
226
|
+
const resolved = await resolveValue(value.contents, context);
|
|
227
|
+
if (resolved === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0047({ message: `[vitehub] Sandbox file ${path} is required.` });
|
|
228
|
+
if (typeof resolved === "string") return new TextEncoder().encode(resolved);
|
|
229
|
+
if (isUint8ArrayValue(resolved)) return resolved;
|
|
230
|
+
throw sandboxErrorDiagnostics.SANDBOX_R0048({ message: `[vitehub] Sandbox file ${path} must resolve to text or bytes.` });
|
|
231
|
+
} }];
|
|
232
|
+
}));
|
|
233
|
+
validateFileTargets(Object.keys(files), label);
|
|
234
|
+
return files;
|
|
235
|
+
async function readProjectFile(path) {
|
|
236
|
+
const root = await realpath(sourceRoot).catch(() => resolve(sourceRoot));
|
|
237
|
+
const source = await realpath(resolve(root, path)).catch(() => void 0);
|
|
238
|
+
const sourcePath = source ? relative(root, source) : void 0;
|
|
239
|
+
if (!source || !sourcePath || sourcePath.startsWith("..") || isAbsolute(sourcePath)) throw sandboxErrorDiagnostics.SANDBOX_R0049({ message: `[vitehub] Sandbox project file is unavailable: ${path}` });
|
|
240
|
+
return new Uint8Array(await readFile(source));
|
|
984
241
|
}
|
|
985
242
|
}
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
function createSandboxExecutionBox(session, provider) {
|
|
989
|
-
return {
|
|
990
|
-
executionAuthority: session.executionAuthority,
|
|
991
|
-
id: session.id,
|
|
992
|
-
files: session.files,
|
|
993
|
-
provider,
|
|
994
|
-
async close() {
|
|
995
|
-
await session.close();
|
|
996
|
-
},
|
|
997
|
-
async exec(command, args, options) {
|
|
998
|
-
return await session.exec(command, args, options);
|
|
999
|
-
},
|
|
1000
|
-
async exists(path) {
|
|
1001
|
-
return await session.files.exists(path);
|
|
1002
|
-
},
|
|
1003
|
-
async mkdir(path, options) {
|
|
1004
|
-
await session.files.mkdir(path, options);
|
|
1005
|
-
},
|
|
1006
|
-
async readFile(path) {
|
|
1007
|
-
const contents = await session.files.read(path);
|
|
1008
|
-
if (!contents) throw new Error(`[vitehub] Sandbox file does not exist: ${path}`);
|
|
1009
|
-
return new TextDecoder().decode(contents);
|
|
1010
|
-
},
|
|
1011
|
-
async writeFile(path, contents) {
|
|
1012
|
-
await session.files.write(path, new TextEncoder().encode(contents));
|
|
1013
|
-
}
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
//#endregion
|
|
1017
|
-
//#region src/internal/shared/provider-detection.ts
|
|
1018
|
-
function createProviderDetector(rules) {
|
|
1019
|
-
return () => {
|
|
1020
|
-
for (const rule of rules) if (rule.when()) return rule.provider;
|
|
1021
|
-
};
|
|
1022
|
-
}
|
|
1023
|
-
function getRuntimeEnv() {
|
|
1024
|
-
return typeof process !== "undefined" ? process.env : {};
|
|
1025
|
-
}
|
|
1026
|
-
const isCloudflare = () => {
|
|
1027
|
-
const env = getRuntimeEnv();
|
|
1028
|
-
return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
|
|
1029
|
-
};
|
|
1030
|
-
const isVercel = () => {
|
|
1031
|
-
const env = getRuntimeEnv();
|
|
1032
|
-
return !!(env.VERCEL || env.VERCEL_ENV);
|
|
1033
|
-
};
|
|
1034
|
-
//#endregion
|
|
1035
|
-
//#region src/runtime/provider-loader-resolver.ts
|
|
1036
|
-
async function loadSandboxProviderRuntime(provider) {
|
|
1037
|
-
return await (await import("vitehub-sandbox-provider-loader").catch(() => {
|
|
1038
|
-
return new Function("specifier", "return import(specifier)")("@vite-hub/sandbox/runtime/provider-loader");
|
|
1039
|
-
})).loadSandboxRuntimeProvider(provider);
|
|
1040
|
-
}
|
|
1041
|
-
//#endregion
|
|
1042
|
-
//#region src/runtime/provider-resolution.ts
|
|
1043
|
-
const allowedDefinitionKeys = new Set(["timeout", "env"]);
|
|
1044
|
-
const maxTimeout = 2147483647;
|
|
1045
|
-
const detectProvider = createProviderDetector([{
|
|
1046
|
-
provider: "cloudflare",
|
|
1047
|
-
when: isCloudflare
|
|
1048
|
-
}, {
|
|
1049
|
-
provider: "vercel",
|
|
1050
|
-
when: isVercel
|
|
1051
|
-
}]);
|
|
1052
|
-
function detectSandbox() {
|
|
1053
|
-
const env = typeof process !== "undefined" ? process.env : {};
|
|
1054
|
-
const type = detectProvider() || "none";
|
|
1055
|
-
if (type === "cloudflare") return {
|
|
1056
|
-
type,
|
|
1057
|
-
details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
|
|
1058
|
-
};
|
|
1059
|
-
if (type === "vercel") return {
|
|
1060
|
-
type,
|
|
1061
|
-
details: { env: env.VERCEL_ENV }
|
|
1062
|
-
};
|
|
1063
|
-
return { type };
|
|
1064
|
-
}
|
|
1065
|
-
function hashCloudflareSandboxName(name) {
|
|
1066
|
-
let hash = 2166136261;
|
|
1067
|
-
for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
|
|
1068
|
-
return (hash >>> 0).toString(36);
|
|
1069
|
-
}
|
|
1070
|
-
function createCloudflareExecutionSandboxId(name, sandboxId) {
|
|
1071
|
-
if (sandboxId) return sandboxId;
|
|
1072
|
-
const prefix = "vitehub-";
|
|
1073
|
-
const suffix = `-${hashCloudflareSandboxName(name)}-${crypto.randomUUID()}`;
|
|
1074
|
-
return `${prefix}${encodeURIComponent(name).slice(0, 55 - suffix.length)}${suffix}`;
|
|
1075
|
-
}
|
|
1076
|
-
function resolveRuntimeProvider(provider, event) {
|
|
1077
|
-
if (provider?.provider) return provider.provider;
|
|
1078
|
-
const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
|
|
1079
|
-
if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
|
|
1080
|
-
if (getCloudflareEnv(event)) return "cloudflare";
|
|
1081
|
-
const detected = detectSandbox();
|
|
1082
|
-
if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
|
|
1083
|
-
throw sandboxError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_PROVIDER_REQUIRED" });
|
|
1084
|
-
}
|
|
1085
|
-
function assertSandboxDefinitionOptions(local) {
|
|
1086
|
-
const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
|
|
1087
|
-
if (invalidKeys.length > 0) throw new TypeError(`[vitehub] Sandbox definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}`);
|
|
1088
|
-
if (local.timeout !== void 0 && (!Number.isInteger(local.timeout) || local.timeout <= 0 || local.timeout > maxTimeout)) throw new TypeError(`[vitehub] Sandbox definition timeout must be a positive integer no greater than ${maxTimeout}.`);
|
|
1089
|
-
}
|
|
1090
|
-
async function resolveSandboxBox(provider, providerOptions, local, context) {
|
|
1091
|
-
return await (await loadSandboxProviderRuntime(provider)).resolveSandboxBox({
|
|
1092
|
-
local,
|
|
1093
|
-
provider: providerOptions
|
|
1094
|
-
}, context);
|
|
1095
|
-
}
|
|
1096
|
-
function withSandboxProvider(provider, options) {
|
|
1097
|
-
return {
|
|
1098
|
-
...options,
|
|
1099
|
-
provider
|
|
1100
|
-
};
|
|
1101
|
-
}
|
|
1102
|
-
//#endregion
|
|
1103
|
-
//#region src/runtime/result.ts
|
|
1104
|
-
function ok(value) {
|
|
1105
|
-
return [null, value];
|
|
1106
|
-
}
|
|
1107
|
-
function err(error) {
|
|
1108
|
-
return [error, void 0];
|
|
1109
|
-
}
|
|
1110
|
-
//#endregion
|
|
1111
|
-
//#region src/runtime/runtime.ts
|
|
1112
|
-
const cloudflareRunQueues = /* @__PURE__ */ new Map();
|
|
1113
|
-
async function serializeCloudflareRun(id, run) {
|
|
1114
|
-
if (!id) return await run();
|
|
1115
|
-
const previous = cloudflareRunQueues.get(id) ?? Promise.resolve();
|
|
1116
|
-
let release;
|
|
1117
|
-
const current = new Promise((resolve) => {
|
|
1118
|
-
release = resolve;
|
|
1119
|
-
});
|
|
1120
|
-
cloudflareRunQueues.set(id, current);
|
|
1121
|
-
await previous;
|
|
243
|
+
function isUint8ArrayValue(value) {
|
|
244
|
+
if (!ArrayBuffer.isView(value)) return false;
|
|
1122
245
|
try {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
246
|
+
const elementType = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
|
|
247
|
+
return !!elementType && Reflect.apply(elementType, value, []) === "Uint8Array";
|
|
248
|
+
} catch {
|
|
249
|
+
return false;
|
|
1127
250
|
}
|
|
1128
251
|
}
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
if (
|
|
1134
|
-
if (
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
const config = getSandboxFeatureProvider(context.config);
|
|
1157
|
-
const provider = resolveRuntimeProvider(config, context.event);
|
|
1158
|
-
return await resolveSandboxBox(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event });
|
|
1159
|
-
},
|
|
1160
|
-
async create(provider, context) {
|
|
1161
|
-
const packageManager = context.definition.bundle.project?.install.command;
|
|
1162
|
-
const box = await provider.resolveBox(["node", ...packageManager ? [packageManager] : []]);
|
|
252
|
+
function validateFileTargets(files, label) {
|
|
253
|
+
for (let index = 0; index < files.length; index++) for (let other = index + 1; other < files.length; other++) if (files[index] === files[other] || isDescendant(files[index], files[other]) || isDescendant(files[other], files[index])) throw sandboxErrorDiagnostics.SANDBOX_R0050({ message: `[vitehub] Sandbox ${label} targets conflict: ${files[index]} and ${files[other]}` });
|
|
254
|
+
}
|
|
255
|
+
function validateTargets(files, state) {
|
|
256
|
+
for (let index = 0; index < state.length; index++) for (let other = index + 1; other < state.length; other++) if (isDescendant(state[index], state[other]) || isDescendant(state[other], state[index])) throw sandboxErrorDiagnostics.SANDBOX_R0051({ message: `[vitehub] Sandbox state targets overlap: ${state[index]} and ${state[other]}` });
|
|
257
|
+
for (const file of files) for (const directory of state) if (file === directory || isDescendant(directory, file)) throw sandboxErrorDiagnostics.SANDBOX_R0052({ message: `[vitehub] Sandbox file and state targets conflict: ${file} and ${directory}` });
|
|
258
|
+
}
|
|
259
|
+
function isDescendant(path, parent) {
|
|
260
|
+
return path.startsWith(`${parent}/`);
|
|
261
|
+
}
|
|
262
|
+
function optionalRecord(value, label) {
|
|
263
|
+
if (value === void 0) return {};
|
|
264
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw sandboxErrorDiagnostics.SANDBOX_R0053({ message: `[vitehub] Sandbox ${label} must be an object.` });
|
|
265
|
+
return value;
|
|
266
|
+
}
|
|
267
|
+
function relativePath(value, label) {
|
|
268
|
+
if (typeof value !== "string" || !value || value.includes("\0") || value.includes("\\") || isAbsolute(value)) throw sandboxErrorDiagnostics.SANDBOX_R0054({ message: `[vitehub] Sandbox ${label} must be a non-empty relative POSIX path.` });
|
|
269
|
+
const normalized = posix.normalize(value);
|
|
270
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../") || normalized !== value) throw sandboxErrorDiagnostics.SANDBOX_R0055({ message: `[vitehub] Sandbox ${label} must be a non-empty relative POSIX path.` });
|
|
271
|
+
return normalized;
|
|
272
|
+
}
|
|
273
|
+
function normalizeRequirements(input) {
|
|
274
|
+
const requirements = input.map((value) => {
|
|
275
|
+
if (typeof value === "string") {
|
|
276
|
+
if (!value.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0056({ message: "[vitehub] Sandbox requirements must be non-empty commands." });
|
|
277
|
+
const command = value.trim();
|
|
278
|
+
if (command.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0057({ message: "[vitehub] Sandbox requirement commands and arguments cannot contain NUL." });
|
|
1163
279
|
return {
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(context.name, options.sandboxId || provider.sandboxId) : void 0;
|
|
1168
|
-
const attempts = provider.provider === "cloudflare" ? CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length + 1 : 1;
|
|
1169
|
-
return await serializeCloudflareRun(cloudflareSandboxId, async () => {
|
|
1170
|
-
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
1171
|
-
let sandbox;
|
|
1172
|
-
let handlerMayHaveStarted = false;
|
|
1173
|
-
let runError;
|
|
1174
|
-
try {
|
|
1175
|
-
sandbox = createSandboxExecutionBox(await box.open({ id: cloudflareSandboxId }), provider.provider);
|
|
1176
|
-
return await executeSandboxDefinition(sandbox, context.name, context.definition.options, context.definition.bundle, payload, options.context, { onHandlerStart() {
|
|
1177
|
-
handlerMayHaveStarted = true;
|
|
1178
|
-
} });
|
|
1179
|
-
} catch (error) {
|
|
1180
|
-
const sandboxError = toSandboxError(error);
|
|
1181
|
-
runError = sandboxError;
|
|
1182
|
-
if (!(!handlerMayHaveStarted && provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
|
|
1183
|
-
await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
|
|
1184
|
-
} finally {
|
|
1185
|
-
if (provider.closeAfterRun !== false || provider.provider === "cloudflare" && !options.sandboxId && !provider.sandboxId) try {
|
|
1186
|
-
await sandbox?.close();
|
|
1187
|
-
} catch (cleanupError) {
|
|
1188
|
-
if (runError) throw new AggregateError([runError, cleanupError], `${runError.message} Cleanup failed: ${toSandboxError(cleanupError).message}`);
|
|
1189
|
-
throw toSandboxError(cleanupError);
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
throw sandboxError("Cloudflare sandbox retries exhausted.", {
|
|
1194
|
-
code: "SANDBOX_RUNTIME_ERROR",
|
|
1195
|
-
provider: provider.provider
|
|
1196
|
-
});
|
|
1197
|
-
});
|
|
1198
|
-
}
|
|
280
|
+
args: [],
|
|
281
|
+
command,
|
|
282
|
+
name: command
|
|
1199
283
|
};
|
|
1200
284
|
}
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
285
|
+
if (!value || typeof value !== "object" || typeof value.command !== "string" || !value.command.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0058({ message: "[vitehub] Sandbox requirements must be commands or direct command checks." });
|
|
286
|
+
const rawArgs = value.args;
|
|
287
|
+
if (rawArgs !== void 0 && !Array.isArray(rawArgs)) throw sandboxErrorDiagnostics.SANDBOX_R0059({ message: "[vitehub] Sandbox requirement arguments must be an array of strings." });
|
|
288
|
+
const args = rawArgs === void 0 ? [] : [...rawArgs];
|
|
289
|
+
if (args.some((argument) => typeof argument !== "string")) throw sandboxErrorDiagnostics.SANDBOX_R0059({ message: "[vitehub] Sandbox requirement arguments must be strings." });
|
|
290
|
+
const command = value.command.trim();
|
|
291
|
+
if (command.includes("\0") || args.some((argument) => argument.includes("\0"))) throw sandboxErrorDiagnostics.SANDBOX_R0060({ message: "[vitehub] Sandbox requirement commands and arguments cannot contain NUL." });
|
|
292
|
+
const name = value.name?.trim() || [command, ...args].join(" ");
|
|
293
|
+
const timeout = value.timeout;
|
|
294
|
+
if (timeout !== void 0 && (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2 ** 31 - 1)) throw sandboxErrorDiagnostics.SANDBOX_R0061({ message: "[vitehub] Sandbox requirement timeout must be a positive integer no greater than 2147483647ms." });
|
|
295
|
+
return {
|
|
296
|
+
args,
|
|
297
|
+
command,
|
|
298
|
+
name,
|
|
299
|
+
...timeout === void 0 ? {} : { timeout }
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
return [...new Map(requirements.map((value) => [JSON.stringify(value), value])).values()];
|
|
1205
303
|
}
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
return err(toSandboxError(error));
|
|
1211
|
-
}
|
|
304
|
+
function resolveString(value, label) {
|
|
305
|
+
if (typeof value !== "string" || !value) throw sandboxErrorDiagnostics.SANDBOX_R0062({ message: `[vitehub] Sandbox ${label} must resolve to a non-empty string.` });
|
|
306
|
+
if (value.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0063({ message: `[vitehub] Sandbox ${label} cannot contain NUL.` });
|
|
307
|
+
return value;
|
|
1212
308
|
}
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
return
|
|
309
|
+
function resolveSha(value) {
|
|
310
|
+
const sha = resolveString(value, "checkout sha").toLowerCase();
|
|
311
|
+
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(sha)) throw sandboxErrorDiagnostics.SANDBOX_R0064({ message: "[vitehub] Sandbox checkout sha must be a full Git object id." });
|
|
312
|
+
return sha;
|
|
313
|
+
}
|
|
314
|
+
async function resolveValue(value, context) {
|
|
315
|
+
return typeof value === "function" ? await value(context) : value;
|
|
1217
316
|
}
|
|
1218
317
|
//#endregion
|
|
1219
|
-
export {
|
|
318
|
+
export { resolveSandbox };
|