@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.
Files changed (58) hide show
  1. package/README.md +327 -34
  2. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  3. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  4. package/dist/crabbox-BFCdf41h.js +1106 -0
  5. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  6. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  7. package/dist/file-listing-DECFTdSl.js +26 -0
  8. package/dist/file-lock-CxyVl4Cv.js +73 -0
  9. package/dist/index-CXej1Bt0.d.ts +519 -0
  10. package/dist/index.d.ts +2 -69
  11. package/dist/index.js +277 -1183
  12. package/dist/internal/cloudflare.d.ts +4 -0
  13. package/dist/internal/cloudflare.js +16 -0
  14. package/dist/internal/host-toolchain.d.ts +22 -0
  15. package/dist/internal/host-toolchain.js +97 -0
  16. package/dist/internal/vercel.d.ts +4 -0
  17. package/dist/internal/vercel.js +16 -0
  18. package/dist/module-types-BfyRBaiP.js +7 -0
  19. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  20. package/dist/remote-1Jz2oUMK.js +247 -0
  21. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  22. package/dist/runtime-DHp6ImeP.js +32 -0
  23. package/dist/runtime-type-DrmrW5m5.js +42 -0
  24. package/dist/session-DD0S1PDC.js +337 -0
  25. package/dist/shell-quote-Q3u3plif.js +6 -0
  26. package/dist/ssh.d.ts +55 -0
  27. package/dist/ssh.js +219 -0
  28. package/dist/task/index.d.ts +67 -0
  29. package/dist/task/index.js +1523 -0
  30. package/dist/task/runtime/empty-registry.d.ts +6 -0
  31. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  32. package/dist/task/runtime/provider-loader.d.ts +20 -0
  33. package/dist/task/runtime/provider-loader.js +19 -0
  34. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  35. package/dist/task/runtime/providers/cloudflare.js +26 -0
  36. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  37. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  38. package/dist/task/runtime/state.d.ts +24 -0
  39. package/dist/task/runtime/state.js +73 -0
  40. package/dist/task/vite.d.ts +360 -0
  41. package/dist/{vite.js → task/vite.js} +964 -645
  42. package/dist/toolchain-BUVXtQ2m.js +527 -0
  43. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  44. package/dist/vercel-Jtxa9TJx.js +279 -0
  45. package/package.json +99 -48
  46. package/dist/cloudflare-env-QQV4uzCT.js +0 -14
  47. package/dist/module-types-DKYItiOu.d.ts +0 -93
  48. package/dist/module-types-Dj1MFmHT.js +0 -7
  49. package/dist/provider-loader-D0UihePq.d.ts +0 -21
  50. package/dist/runtime/empty-registry.d.ts +0 -6
  51. package/dist/runtime/provider-loader.d.ts +0 -2
  52. package/dist/runtime/provider-loader.js +0 -15
  53. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  54. package/dist/runtime/providers/cloudflare.js +0 -25
  55. package/dist/runtime/providers/vercel.d.ts +0 -121
  56. package/dist/runtime/state.d.ts +0 -26
  57. package/dist/runtime/state.js +0 -72
  58. package/dist/vite.d.ts +0 -48
@@ -0,0 +1,1523 @@
1
+ import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-dGQqfgLt.js";
2
+ import { t as getCloudflareEnv } from "../cloudflare-env-BBJaBbuQ.js";
3
+ import { getSandboxTaskRuntimeConfig, getSandboxTaskRuntimeRegistry } from "./runtime/state.js";
4
+ import { t as getSandboxTaskFeatureProvider } from "../module-types-BfyRBaiP.js";
5
+ import { unsupportedHostedSandboxTaskProviderError } from "./runtime/provider-loader.js";
6
+ import { ViteHubError, deserializeResponse, getViteHubErrorShape, isSerializedResponse, toResponse } from "@vite-hub/runtime";
7
+ import { types } from "node:util";
8
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
9
+ import { dirname } from "pathe";
10
+ //#region src/task/internal/shared/definition.ts
11
+ function assertDefinitionHandler(functionName, handler, label) {
12
+ if (typeof handler !== "function") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0010({ message: `[vitehub] \`${functionName}()\` requires a ${label} as the first argument.` });
13
+ }
14
+ function validateDefinitionOptions(functionName, options, config) {
15
+ if (typeof options === "undefined") return void 0;
16
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0011({ message: `[vitehub] \`${functionName}()\` accepts one options object.` });
17
+ const invalidKeys = Object.keys(options).filter((key) => {
18
+ if (config.allowedKeys) return !config.allowedKeys.includes(key);
19
+ return config.disallowedKeys?.includes(key);
20
+ });
21
+ if (invalidKeys.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0012({ message: `[vitehub] \`${functionName}()\` ${config.invalidKeysMessage}. Unsupported keys: ${invalidKeys.join(", ")}.` });
22
+ return options;
23
+ }
24
+ //#endregion
25
+ //#region src/task/runtime/registry.ts
26
+ function createSandboxTaskDefinition(functionName, input) {
27
+ const validated = validateDefinitionOptions(functionName, input, {
28
+ allowedKeys: [
29
+ "run",
30
+ "timeout",
31
+ "env",
32
+ "project"
33
+ ],
34
+ invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env, project)"
35
+ });
36
+ if (!validated) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0072({ message: `[vitehub] \`${functionName}()\` requires an options object.` });
37
+ if (typeof validated.project !== "undefined" && typeof validated.project !== "boolean") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0073({ message: `[vitehub] \`${functionName}()\` project must be a boolean.` });
38
+ const { project: _project, run, ...options } = validated;
39
+ assertDefinitionHandler(functionName, run, "Sandbox handler in `run`");
40
+ return {
41
+ run,
42
+ options: Object.keys(options).length ? options : void 0
43
+ };
44
+ }
45
+ function defineSandboxTask(input) {
46
+ return createSandboxTaskDefinition("defineSandboxTask", input);
47
+ }
48
+ //#endregion
49
+ //#region src/task/internal/shared/request-payload.ts
50
+ async function readRequestPayload(event, fallback = {}) {
51
+ return await event.req.json().catch(() => fallback);
52
+ }
53
+ //#endregion
54
+ //#region src/task/sandbox-task/errors.ts
55
+ function sanitizeSandboxTaskDetail(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
56
+ if (value === null || typeof value === "boolean") return value;
57
+ if (typeof value === "string") return value.slice(0, 16384);
58
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
59
+ if (!value || typeof value !== "object" || depth >= 8 || seen.has(value)) return void 0;
60
+ seen.add(value);
61
+ try {
62
+ if (Array.isArray(value)) return value.slice(0, 128).flatMap((item) => {
63
+ const sanitized = sanitizeSandboxTaskDetail(item, depth + 1, seen);
64
+ return sanitized === void 0 ? [] : [sanitized];
65
+ });
66
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return void 0;
67
+ const result = {};
68
+ for (const [key, item] of Object.entries(value).slice(0, 128)) {
69
+ if (!key || key.length > 128) continue;
70
+ result[key] = sanitizeSandboxTaskDetail(item, depth + 1, seen);
71
+ }
72
+ return result;
73
+ } catch {
74
+ return;
75
+ } finally {
76
+ seen.delete(value);
77
+ }
78
+ }
79
+ function sanitizeSandboxTaskDetails(details) {
80
+ const sanitized = sanitizeSandboxTaskDetail(details);
81
+ return sanitized && !Array.isArray(sanitized) && typeof sanitized === "object" ? sanitized : void 0;
82
+ }
83
+ function sandboxTaskError(message, metadata = {}) {
84
+ const { cause, code = "SANDBOX_TASK_RUNTIME_ERROR", details, httpStatus, method, provider } = metadata;
85
+ return new ViteHubError(code, message.slice(0, 16384) || "Sandbox execution failed.", {
86
+ cause,
87
+ details: sanitizeSandboxTaskDetails({
88
+ ...provider === void 0 ? {} : { provider },
89
+ ...method === void 0 ? {} : { method },
90
+ ...httpStatus === void 0 ? {} : { httpStatus },
91
+ ...sanitizeSandboxTaskDetails(details)
92
+ })
93
+ });
94
+ }
95
+ function isSandboxTaskError(value) {
96
+ return getViteHubErrorShape(value)?.code.startsWith("SANDBOX_TASK_") === true;
97
+ }
98
+ //#endregion
99
+ //#region src/task/internal/shared/validation.ts
100
+ const VALIDATION_FAILED = "Validation failed";
101
+ function isObject(value) {
102
+ return !!value && typeof value === "object";
103
+ }
104
+ function hasStandardValidator(value) {
105
+ if (!isObject(value)) return false;
106
+ const standard = value["~standard"];
107
+ return Object.hasOwn(value, "~standard") && isObject(standard) && typeof standard.validate === "function";
108
+ }
109
+ function isErrorWithHttpMetadata(error) {
110
+ if (!(error instanceof Error)) return false;
111
+ const e = error;
112
+ return typeof e.status === "number" || typeof e.statusCode === "number" || typeof e.statusText === "string" || typeof e.statusMessage === "string";
113
+ }
114
+ function readIssues(value) {
115
+ if (!isObject(value)) return void 0;
116
+ if (Array.isArray(value.issues)) return value.issues;
117
+ if (isObject(value.data) && Array.isArray(value.data.issues)) return value.data.issues;
118
+ }
119
+ function readStatusCode(value) {
120
+ if (!isObject(value)) return 400;
121
+ if (typeof value.statusCode === "number") return value.statusCode;
122
+ if (typeof value.status === "number") return value.status;
123
+ return 400;
124
+ }
125
+ function readStatusText(value) {
126
+ if (!isObject(value)) return VALIDATION_FAILED;
127
+ if (typeof value.statusMessage === "string" && value.statusMessage) return value.statusMessage;
128
+ if (typeof value.statusText === "string" && value.statusText) return value.statusText;
129
+ return VALIDATION_FAILED;
130
+ }
131
+ function readMessage(value) {
132
+ if (value instanceof Error) return value.message || VALIDATION_FAILED;
133
+ if (isObject(value) && typeof value.message === "string" && value.message) return value.message;
134
+ return VALIDATION_FAILED;
135
+ }
136
+ function readData(value, issues) {
137
+ const base = isObject(value) && isObject(value.data) ? { ...value.data } : {};
138
+ const message = value instanceof Error ? VALIDATION_FAILED : typeof base.message === "string" && base.message || readMessage(value);
139
+ return {
140
+ ...base,
141
+ message,
142
+ ...issues ? { issues } : {}
143
+ };
144
+ }
145
+ function createValidationError(cause) {
146
+ if (isErrorWithHttpMetadata(cause)) return cause;
147
+ const statusCode = readStatusCode(cause);
148
+ const statusText = readStatusText(cause);
149
+ const data = readData(cause, readIssues(cause));
150
+ return Object.assign(sandboxTaskError(readMessage(cause), {
151
+ cause,
152
+ code: "SANDBOX_TASK_VALIDATION_ERROR",
153
+ details: data,
154
+ httpStatus: statusCode
155
+ }), {
156
+ status: statusCode,
157
+ statusCode,
158
+ statusText,
159
+ statusMessage: statusText,
160
+ data
161
+ });
162
+ }
163
+ async function readValidatedPayload(payload, validate, options) {
164
+ if (hasStandardValidator(validate)) {
165
+ let result;
166
+ try {
167
+ result = await validate["~standard"].validate(payload);
168
+ } catch (error) {
169
+ throw createValidationError(error);
170
+ }
171
+ if (result.issues !== void 0) throw createValidationError(options?.onError?.({
172
+ issues: result.issues,
173
+ value: payload
174
+ }) || {
175
+ issues: result.issues,
176
+ message: VALIDATION_FAILED
177
+ });
178
+ return result.value;
179
+ }
180
+ try {
181
+ const result = await validate(payload);
182
+ if (result === false) throw createValidationError(options?.onError?.({
183
+ issues: [{ message: VALIDATION_FAILED }],
184
+ value: payload
185
+ }) || { message: VALIDATION_FAILED });
186
+ if (result === true || result == null) return payload;
187
+ return result;
188
+ } catch (error) {
189
+ throw createValidationError(error);
190
+ }
191
+ }
192
+ //#endregion
193
+ //#region src/task/internal/shared/cloudflare-retry.ts
194
+ const CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS = [
195
+ 1e3,
196
+ 2e3,
197
+ 5e3,
198
+ 1e4,
199
+ 15e3
200
+ ];
201
+ 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 sandbox [a-z][a-z0-9]* timed out after \d+ms/i;
202
+ function collectErrorMessages(error) {
203
+ try {
204
+ if (types.isNativeError(error)) {
205
+ const message = error.message;
206
+ const cause = error.cause;
207
+ return [message, types.isNativeError(cause) ? cause.message : ""].filter(Boolean).join("\n");
208
+ }
209
+ } catch {}
210
+ try {
211
+ return String(error);
212
+ } catch {
213
+ return "";
214
+ }
215
+ }
216
+ function collectCloudflareErrorMessages(error, ...extraMessages) {
217
+ return [collectErrorMessages(error), ...extraMessages].filter(Boolean).join("\n");
218
+ }
219
+ //#endregion
220
+ //#region src/task/internal/shared/utils.ts
221
+ async function sleep(ms, signal) {
222
+ if (signal?.aborted) throw signal.reason;
223
+ await new Promise((resolve, reject) => {
224
+ const onAbort = () => {
225
+ clearTimeout(timer);
226
+ signal?.removeEventListener("abort", onAbort);
227
+ reject(signal?.reason);
228
+ };
229
+ const timer = setTimeout(() => {
230
+ signal?.removeEventListener("abort", onAbort);
231
+ resolve();
232
+ }, ms);
233
+ signal?.addEventListener("abort", onAbort, { once: true });
234
+ });
235
+ }
236
+ //#endregion
237
+ //#region src/task/runtime/binary-sidecars.ts
238
+ const SANDBOX_VALUE_MARKER = "vitehub:sandbox-task:value";
239
+ function isPlainObject(value) {
240
+ if (!value || typeof value !== "object") return false;
241
+ const prototype = Object.getPrototypeOf(value);
242
+ return prototype === Object.prototype || prototype === null;
243
+ }
244
+ function isObjectRecord(value) {
245
+ return !!value && typeof value === "object";
246
+ }
247
+ const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
248
+ function isUint8Array(value) {
249
+ if (!ArrayBuffer.isView(value) || !typedArrayTag) return false;
250
+ try {
251
+ return typedArrayTag.call(value) === "Uint8Array";
252
+ } catch {
253
+ return false;
254
+ }
255
+ }
256
+ function unboxJsonPrimitive(value) {
257
+ for (const unbox of [
258
+ Boolean.prototype.valueOf,
259
+ Number.prototype.valueOf,
260
+ String.prototype.valueOf,
261
+ BigInt.prototype.valueOf
262
+ ]) {
263
+ try {
264
+ Reflect.apply(unbox, value, []);
265
+ } catch {
266
+ continue;
267
+ }
268
+ return { value: Reflect.apply(value.valueOf, value, []) };
269
+ }
270
+ }
271
+ function hasMarker(value) {
272
+ return Object.prototype.hasOwnProperty.call(value, SANDBOX_VALUE_MARKER);
273
+ }
274
+ function tagged(value) {
275
+ return { [SANDBOX_VALUE_MARKER]: value };
276
+ }
277
+ function serializationError(message, details, cause) {
278
+ return sandboxTaskError(message, {
279
+ code: "SANDBOX_TASK_SERIALIZATION_ERROR",
280
+ cause,
281
+ details
282
+ });
283
+ }
284
+ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
285
+ const state = { nextId: 0 };
286
+ const throwIfAborted = () => signal?.throwIfAborted();
287
+ const abortable = async (operation) => {
288
+ try {
289
+ return await operation;
290
+ } catch (error) {
291
+ throwIfAborted();
292
+ throw error;
293
+ }
294
+ };
295
+ async function encode(entry, ancestors, key = "", applyToJSON = true) {
296
+ const blob = typeof Blob !== "undefined" && entry instanceof Blob;
297
+ const buffer = typeof Buffer !== "undefined" && Buffer.isBuffer(entry);
298
+ if (blob || isUint8Array(entry)) {
299
+ throwIfAborted();
300
+ const id = state.nextId++;
301
+ state.directory ||= abortable(sandbox.files.mkdir(assetsDir, {
302
+ recursive: true,
303
+ signal
304
+ }));
305
+ await state.directory;
306
+ const bytes = blob ? new Uint8Array(await entry.arrayBuffer()) : entry;
307
+ throwIfAborted();
308
+ await abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }));
309
+ return tagged({
310
+ id,
311
+ kind: blob ? "blob" : buffer ? "buffer" : "uint8array",
312
+ ...blob && entry.type ? { type: entry.type } : {},
313
+ tag: "binary"
314
+ });
315
+ }
316
+ if (isObjectRecord(entry) && applyToJSON) try {
317
+ const toJSON = entry.toJSON;
318
+ if (typeof toJSON === "function") return await encode(Reflect.apply(toJSON, entry, [key]), ancestors, key, false);
319
+ } catch (error) {
320
+ if (isSandboxTaskError(error)) throw error;
321
+ throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
322
+ }
323
+ if (Array.isArray(entry)) {
324
+ if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
325
+ const nextAncestors = new Set(ancestors).add(entry);
326
+ return await Promise.all(entry.map((item, index) => encode(item, nextAncestors, String(index))));
327
+ }
328
+ if (!isObjectRecord(entry)) return entry;
329
+ let boxed;
330
+ try {
331
+ boxed = unboxJsonPrimitive(entry);
332
+ } catch (error) {
333
+ throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
334
+ }
335
+ if (boxed) return await encode(boxed.value, ancestors, key, false);
336
+ if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
337
+ const nextAncestors = new Set(ancestors).add(entry);
338
+ let sourceEntries;
339
+ try {
340
+ sourceEntries = Object.entries(entry).filter(([entryKey, item]) => applyToJSON || entryKey !== "toJSON" || typeof item !== "function");
341
+ } catch (error) {
342
+ throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
343
+ }
344
+ const entries = await Promise.all(sourceEntries.map(async ([entryKey, item]) => [entryKey, await encode(item, nextAncestors, entryKey)]));
345
+ return hasMarker(entry) ? tagged({
346
+ entries,
347
+ tag: "object"
348
+ }) : Object.fromEntries(entries);
349
+ }
350
+ return await encode(value, /* @__PURE__ */ new Set());
351
+ }
352
+ async function decodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
353
+ if (Array.isArray(value)) return await Promise.all(value.map((entry) => decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)));
354
+ if (!isPlainObject(value)) return value;
355
+ if (!hasMarker(value)) return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
356
+ const descriptor = value[SANDBOX_VALUE_MARKER];
357
+ if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
358
+ if (descriptor.tag === "response") {
359
+ if (!isSerializedResponse(descriptor.value)) throw serializationError(`Sandbox ${label} contains an invalid response descriptor.`, { label });
360
+ return deserializeResponse(descriptor.value);
361
+ }
362
+ if (descriptor.tag === "object") {
363
+ 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 });
364
+ return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
365
+ }
366
+ if (descriptor.tag !== "binary" || !Number.isSafeInteger(descriptor.id) || Object.is(descriptor.id, -0) || descriptor.id < 0 || descriptor.kind !== "blob" && descriptor.kind !== "buffer" && descriptor.kind !== "uint8array" || typeof descriptor.type !== "undefined" && typeof descriptor.type !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
367
+ const bytes = await sandbox.files.read(`${assetsDir}/${descriptor.id}`, { signal });
368
+ if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
369
+ id: descriptor.id,
370
+ label
371
+ });
372
+ return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
373
+ }
374
+ //#endregion
375
+ //#region src/task/runtime/error-normalization.ts
376
+ function readSandboxTaskErrorMetadata(error) {
377
+ if (!error || typeof error !== "object") return void 0;
378
+ const metadata = error;
379
+ const shape = getViteHubErrorShape(error);
380
+ return {
381
+ code: shape?.code || (typeof metadata.code === "string" ? metadata.code : void 0),
382
+ provider: typeof shape?.details?.provider === "string" ? shape.details.provider : typeof metadata.provider === "string" ? metadata.provider : void 0,
383
+ cause: metadata.cause,
384
+ details: shape?.details || (typeof metadata.details === "object" && metadata.details !== null ? metadata.details : void 0)
385
+ };
386
+ }
387
+ function toSandboxTaskError(error) {
388
+ if (isSandboxTaskError(error)) return error;
389
+ const metadata = readSandboxTaskErrorMetadata(error);
390
+ if (isErrorValue(error)) {
391
+ const message = readErrorMessage(error);
392
+ return sandboxTaskError(message ? message : "Sandbox execution failed.", {
393
+ code: sandboxTaskCode(metadata?.code),
394
+ provider: metadata?.provider,
395
+ details: metadata?.details,
396
+ cause: error
397
+ });
398
+ }
399
+ return sandboxTaskError(String(error) || "Sandbox execution failed.", {
400
+ code: sandboxTaskCode(metadata?.code),
401
+ provider: metadata?.provider,
402
+ details: metadata?.details,
403
+ cause: error
404
+ });
405
+ }
406
+ function combineSandboxTaskErrors(error, cleanupError) {
407
+ const primary = toSandboxTaskError(error);
408
+ return sandboxTaskError(primary.message, {
409
+ code: primary.code,
410
+ details: primary.details,
411
+ cause: new AggregateError([error, cleanupError], "Sandbox execution and cleanup failed.")
412
+ });
413
+ }
414
+ function isErrorValue(value) {
415
+ if (value instanceof Error) return true;
416
+ try {
417
+ return types.isNativeError(value);
418
+ } catch {
419
+ return false;
420
+ }
421
+ }
422
+ function readErrorMessage(error) {
423
+ try {
424
+ const message = error.message;
425
+ return hasRuntimeType(message, "string") && message.length > 0 ? message : void 0;
426
+ } catch {
427
+ return;
428
+ }
429
+ }
430
+ function sandboxTaskCode(code) {
431
+ return code?.startsWith("SANDBOX_TASK_") ? code : "SANDBOX_TASK_RUNTIME_ERROR";
432
+ }
433
+ //#endregion
434
+ //#region src/task/runtime/entry-script.ts
435
+ const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
436
+ function createEntrySource(definitionPath, execution = "definition") {
437
+ const invocation = execution === "module" ? [
438
+ ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
439
+ ` const exported = await mod.default`,
440
+ ` if (typeof exported !== 'function')`,
441
+ ` throw new TypeError('Sandbox package entrypoint must default-export a function.')`,
442
+ ` const result = await exported(input.payload, input.context)`
443
+ ] : [
444
+ ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
445
+ ` const definition = mod?.default`,
446
+ ` if (!definition || typeof definition.run !== 'function')`,
447
+ ` throw new Error('Sandbox Task Definition must default-export defineSandboxTask({ run }).')`,
448
+ ` const result = await definition.run(input.payload, input.context)`
449
+ ];
450
+ return [
451
+ `import { mkdir, readFile, writeFile } from 'node:fs/promises'`,
452
+ `import { Buffer } from 'node:buffer'`,
453
+ `import { pathToFileURL } from 'node:url'`,
454
+ `const serializationErrors = new WeakSet()`,
455
+ ``,
456
+ `function serializationError(message, cause) {`,
457
+ ` const error = new TypeError(message, { cause })`,
458
+ ` serializationErrors.add(error)`,
459
+ ` return error`,
460
+ `}`,
461
+ ``,
462
+ `function normalizeError(error) {`,
463
+ ` if (error instanceof Error) {`,
464
+ ` return {`,
465
+ ` code: serializationErrors.has(error) ? 'SANDBOX_TASK_SERIALIZATION_ERROR' : undefined,`,
466
+ ` name: error.name,`,
467
+ ` message: error.message,`,
468
+ ` stack: error.stack,`,
469
+ ` cause: error.cause ? String(error.cause) : undefined,`,
470
+ ` }`,
471
+ ` }`,
472
+ ` return {`,
473
+ ` code: undefined,`,
474
+ ` name: 'Error',`,
475
+ ` message: String(error),`,
476
+ ` }`,
477
+ `}`,
478
+ ``,
479
+ `const valueMarker = ${JSON.stringify("vitehub:sandbox-task:value")}`,
480
+ `const nativeResponseClone = typeof Response !== 'undefined' ? Response.prototype.clone : undefined`,
481
+ `const nativeResponseBody = typeof Response !== 'undefined' ? Object.getOwnPropertyDescriptor(Response.prototype, 'body')?.get : undefined`,
482
+ ``,
483
+ `function isPlainObject(value) {`,
484
+ ` if (!value || typeof value !== 'object') return false`,
485
+ ` const prototype = Object.getPrototypeOf(value)`,
486
+ ` return prototype === Object.prototype || prototype === null`,
487
+ `}`,
488
+ ``,
489
+ `function hasMarker(value) {`,
490
+ ` return Object.prototype.hasOwnProperty.call(value, valueMarker)`,
491
+ `}`,
492
+ ``,
493
+ `const typedArrayTagGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get`,
494
+ ``,
495
+ `function isUint8Array(value) {`,
496
+ ` return ArrayBuffer.isView(value) && typedArrayTagGetter?.call(value) === 'Uint8Array'`,
497
+ `}`,
498
+ ``,
499
+ `function unboxJsonPrimitive(value) {`,
500
+ ` for (const unbox of [Boolean.prototype.valueOf, Number.prototype.valueOf, String.prototype.valueOf, BigInt.prototype.valueOf]) {`,
501
+ ` try { Reflect.apply(unbox, value, []) }`,
502
+ ` catch { continue }`,
503
+ ` return { value: Reflect.apply(value.valueOf, value, []) }`,
504
+ ` }`,
505
+ ` return undefined`,
506
+ `}`,
507
+ ``,
508
+ `function hasEnumerableProperties(value) {`,
509
+ ` if (Object.keys(value).length > 0) return true`,
510
+ ` const enumerableSymbols = Object.getOwnPropertySymbols(value).filter(symbol => Object.prototype.propertyIsEnumerable.call(value, symbol))`,
511
+ ` if (enumerableSymbols.length === 0) return false`,
512
+ ` return true`,
513
+ `}`,
514
+ ``,
515
+ `function isResponse(value) {`,
516
+ ` if (!value || typeof value !== 'object') return false`,
517
+ ` try {`,
518
+ ` let clone = nativeResponseClone`,
519
+ ` let cloneSucceeded = false`,
520
+ ` let cloneResult`,
521
+ ` let bodySucceeded = false`,
522
+ ` if (typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
523
+ ` if (!cloneSucceeded && typeof nativeResponseBody === 'function') { try { nativeResponseBody.call(value); bodySucceeded = true } catch {} }`,
524
+ ` if (cloneSucceeded || bodySucceeded) {`,
525
+ ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
526
+ ` && typeof value.statusText === 'string'`,
527
+ ` && typeof value.arrayBuffer === 'function'`,
528
+ ` && value.headers && typeof value.headers.get === 'function'`,
529
+ ` && typeof value.headers[Symbol.iterator] === 'function'`,
530
+ ` }`,
531
+ ` clone = undefined`,
532
+ ` let foreignCloneDescriptor`,
533
+ ` let foreignBodyDescriptor`,
534
+ ` let foreignConstructorDescriptor`,
535
+ ` let foreignClonePrototype`,
536
+ ` let foreignBodyPrototype`,
537
+ ` let foreignConstructorPrototype`,
538
+ ` let prototype = Object.getPrototypeOf(value)`,
539
+ ` while (prototype) {`,
540
+ ` if (typeof clone !== 'function') {`,
541
+ ` const cloneDescriptor = Object.getOwnPropertyDescriptor(prototype, 'clone')`,
542
+ ` if (typeof cloneDescriptor?.value === 'function') {`,
543
+ ` clone = cloneDescriptor.value`,
544
+ ` foreignCloneDescriptor = cloneDescriptor`,
545
+ ` foreignClonePrototype = prototype`,
546
+ ` }`,
547
+ ` }`,
548
+ ` if (!bodySucceeded) {`,
549
+ ` const bodyDescriptor = Object.getOwnPropertyDescriptor(prototype, 'body')`,
550
+ ` if (typeof bodyDescriptor?.get === 'function') {`,
551
+ ` foreignBodyDescriptor = bodyDescriptor`,
552
+ ` foreignBodyPrototype = prototype`,
553
+ ` try { bodyDescriptor.get.call(value); bodySucceeded = true } catch {}`,
554
+ ` }`,
555
+ ` }`,
556
+ ` if (!foreignConstructorDescriptor) {`,
557
+ ` const constructorDescriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')`,
558
+ ` if (typeof constructorDescriptor?.value === 'function') { foreignConstructorDescriptor = constructorDescriptor; foreignConstructorPrototype = prototype }`,
559
+ ` }`,
560
+ ` prototype = Object.getPrototypeOf(prototype)`,
561
+ ` }`,
562
+ ` if (!cloneSucceeded && typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
563
+ ` // Consumed or locked foreign Responses reject clone(), but their branded body getter still succeeds.`,
564
+ ` if (!bodySucceeded || typeof clone !== 'function') return false`,
565
+ ` let cloneResultBodySucceeded = false`,
566
+ ` if (cloneResult && cloneResult !== value && foreignBodyDescriptor) {`,
567
+ ` try {`,
568
+ ` const cloneResultBody = foreignBodyDescriptor.get.call(cloneResult)`,
569
+ ` cloneResultBodySucceeded = cloneResultBody === null || (cloneResultBody && typeof cloneResultBody.getReader === 'function')`,
570
+ ` } catch {}`,
571
+ ` }`,
572
+ ` const cloneResultLooksLikeResponse = Boolean(cloneResult && Number.isInteger(cloneResult.status) && cloneResult.status >= 0 && cloneResult.status <= 599 && typeof cloneResult.statusText === 'string' && typeof cloneResult.arrayBuffer === 'function' && cloneResult.headers && typeof cloneResult.headers.get === 'function' && typeof cloneResult.headers[Symbol.iterator] === 'function')`,
573
+ ` const hasOwnConstructor = Object.prototype.hasOwnProperty.call(value, 'constructor')`,
574
+ ` const foreignConstructor = hasOwnConstructor ? undefined : value.constructor`,
575
+ ` const foreignPrototype = typeof foreignConstructor === 'function' ? foreignConstructor.prototype : undefined`,
576
+ ` const hasForeignPrototype = Boolean(foreignPrototype && foreignPrototype !== Object.prototype && foreignPrototype.isPrototypeOf(value) && foreignPrototype.isPrototypeOf(cloneResult))`,
577
+ ` let foreignConstructorSource = ''`,
578
+ ` try { foreignConstructorSource = Function.prototype.toString.call(foreignConstructor) } catch {}`,
579
+ ` // Independently branded implementations expose a class Response constructor;`,
580
+ ` // rejecting callable/user-defined constructors keeps prototype-chain spoofs ordinary.`,
581
+ ` const trustedForeignConstructor = ( /^class\\s+Response\\b/.test(foreignConstructorSource) || foreignConstructorSource.includes('[native code]') )`,
582
+ ` && Object.prototype.hasOwnProperty.call(foreignConstructor, 'error') && Object.prototype.hasOwnProperty.call(foreignConstructor, 'json') && Object.prototype.hasOwnProperty.call(foreignConstructor, 'redirect')`,
583
+ ` && typeof foreignConstructor.error === 'function' && typeof foreignConstructor.json === 'function' && typeof foreignConstructor.redirect === 'function'`,
584
+ ` const constructorSharesResponsePrototype = foreignConstructorPrototype === foreignClonePrototype && foreignConstructorPrototype === foreignBodyPrototype`,
585
+ ` // Prototype and constructor relationships are observable and can be forged by ordinary values.`,
586
+ ` // Without a realm-local brand proof, keep enumerable values on the ordinary-object path.`,
587
+ ` const enumerableSymbols = Object.getOwnPropertySymbols(value).filter(symbol => Object.prototype.propertyIsEnumerable.call(value, symbol))`,
588
+ ` const undiciStateSymbol = enumerableSymbols.find(symbol => symbol.description === 'state')`,
589
+ ` const undiciHeadersSymbol = enumerableSymbols.find(symbol => symbol.description === 'headers')`,
590
+ ` const undiciState = undiciStateSymbol && value[undiciStateSymbol]`,
591
+ ` const undiciHeaders = undiciHeadersSymbol && value[undiciHeadersSymbol]`,
592
+ ` const cloneSymbols = cloneResult && Object.getOwnPropertySymbols(cloneResult).filter(symbol => Object.prototype.propertyIsEnumerable.call(cloneResult, symbol))`,
593
+ ` const cloneStateSymbol = cloneSymbols?.find(symbol => symbol.description === 'state')`,
594
+ ` const cloneHeadersSymbol = cloneSymbols?.find(symbol => symbol.description === 'headers')`,
595
+ ` const cloneState = cloneStateSymbol && cloneResult[cloneStateSymbol]`,
596
+ ` const cloneHeaders = cloneHeadersSymbol && cloneResult[cloneHeadersSymbol]`,
597
+ ` const undiciInternals = enumerableSymbols.length === 2 && undiciState && typeof undiciState === 'object' && Number.isInteger(undiciState.status) && 'body' in undiciState && 'headersList' in undiciState && undiciHeaders && typeof undiciHeaders === 'object' && undiciHeaders === value.headers && typeof undiciHeaders.get === 'function' && cloneSymbols?.length === 2 && cloneState && typeof cloneState === 'object' && 'headersList' in cloneState && cloneHeaders && typeof cloneHeaders === 'object' && cloneHeaders === cloneResult.headers && typeof cloneHeaders.get === 'function'`,
598
+ ` if (Object.keys(value).length > 0) return false`,
599
+ ` if (hasEnumerableProperties(value) && !undiciInternals) return false`,
600
+ ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
601
+ ` && typeof value.statusText === 'string'`,
602
+ ` && typeof value.arrayBuffer === 'function'`,
603
+ ` && value.headers && typeof value.headers.get === 'function'`,
604
+ ` && typeof value.headers[Symbol.iterator] === 'function'`,
605
+ ` }`,
606
+ ` catch { return false }`,
607
+ `}`,
608
+ ``,
609
+ `function invalidDescriptor(label) {`,
610
+ ` return new TypeError('Sandbox ' + label + ' contains an invalid binary sidecar descriptor.')`,
611
+ `}`,
612
+ ``,
613
+ `async function reviveValue(value, assetsDir, label) {`,
614
+ ` if (Array.isArray(value))`,
615
+ ` return await Promise.all(value.map(entry => reviveValue(entry, assetsDir, label)))`,
616
+ ` if (!value || typeof value !== 'object') return value`,
617
+ ` if (!hasMarker(value)) {`,
618
+ ` return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [`,
619
+ ` key,`,
620
+ ` await reviveValue(entry, assetsDir, label),`,
621
+ ` ])))`,
622
+ ` }`,
623
+ ` const descriptor = value[valueMarker]`,
624
+ ` if (!isPlainObject(descriptor) || typeof descriptor.tag !== 'string')`,
625
+ ` throw invalidDescriptor(label)`,
626
+ ` if (descriptor.tag === 'object') {`,
627
+ ` if (!Array.isArray(descriptor.entries) || !descriptor.entries.every(entry => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'))`,
628
+ ` throw invalidDescriptor(label)`,
629
+ ` return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [`,
630
+ ` key,`,
631
+ ` await reviveValue(entry, assetsDir, label),`,
632
+ ` ])))`,
633
+ ` }`,
634
+ ` if (descriptor.tag !== 'binary'`,
635
+ ` || !Number.isSafeInteger(descriptor.id)`,
636
+ ` || Object.is(descriptor.id, -0)`,
637
+ ` || descriptor.id < 0`,
638
+ ` || (descriptor.kind !== 'blob' && descriptor.kind !== 'buffer' && descriptor.kind !== 'uint8array')`,
639
+ ` || (typeof descriptor.type !== 'undefined' && typeof descriptor.type !== 'string'))`,
640
+ ` throw invalidDescriptor(label)`,
641
+ ` const bytes = new Uint8Array(await readFile(assetsDir + '/' + descriptor.id))`,
642
+ ` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
643
+ `}`,
644
+ ``,
645
+ `async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
646
+ ` if (isResponse(value)) {`,
647
+ ` return { [valueMarker]: { tag: 'response', value: {`,
648
+ ` body: { isNull: value.body === null, data: Buffer.from(await value.arrayBuffer()).toString('base64'), encoding: 'base64', mediaType: value.headers.get('content-type') || 'application/octet-stream' },`,
649
+ ` headers: Array.from(value.headers),`,
650
+ ` status: value.status,`,
651
+ ` statusText: value.statusText,`,
652
+ ` ...(value.type === 'opaqueredirect' ? { url: value.url } : {}),`,
653
+ ` ...(['error', 'opaque', 'opaqueredirect'].includes(value.type) ? { type: value.type } : {}),`,
654
+ ` } } }`,
655
+ ` }`,
656
+ ` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
657
+ ` const buffer = Buffer.isBuffer(value)`,
658
+ ` if (blob || isUint8Array(value)) {`,
659
+ ` const id = state.nextId++`,
660
+ ` state.directory ||= mkdir(assetsDir, { recursive: true })`,
661
+ ` await state.directory`,
662
+ ` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
663
+ ` await writeFile(assetsDir + '/' + id, bytes)`,
664
+ ` return { [valueMarker]: {`,
665
+ ` id,`,
666
+ ` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
667
+ ` ...(blob && value.type ? { type: value.type } : {}),`,
668
+ ` tag: 'binary',`,
669
+ ` } }`,
670
+ ` }`,
671
+ ` if (value && typeof value === 'object' && applyToJSON) {`,
672
+ ` const toJSON = value.toJSON`,
673
+ ` if (typeof toJSON === 'function')`,
674
+ ` return await extractValue(Reflect.apply(toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
675
+ ` }`,
676
+ ` if (Array.isArray(value)) {`,
677
+ ` if (ancestors.has(value))`,
678
+ ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
679
+ ` const nextAncestors = new Set(ancestors).add(value)`,
680
+ ` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
681
+ ` }`,
682
+ ` if (!value || typeof value !== 'object') return value`,
683
+ ` const boxed = unboxJsonPrimitive(value)`,
684
+ ` if (boxed) return await extractValue(boxed.value, assetsDir, state, ancestors, key, false)`,
685
+ ` if (ancestors.has(value))`,
686
+ ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
687
+ ` const nextAncestors = new Set(ancestors).add(value)`,
688
+ ` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
689
+ ` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
690
+ ` entryKey,`,
691
+ ` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
692
+ ` ]))`,
693
+ ` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
694
+ `}`,
695
+ ``,
696
+ `async function serializeSuccess(result, assetsDir) {`,
697
+ ` try {`,
698
+ ` const encoded = await extractValue(result, assetsDir)`,
699
+ ` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
700
+ ` const type = typeof value`,
701
+ ` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
702
+ ` throw serializationError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
703
+ ` if (type === 'number' && !Number.isFinite(value))`,
704
+ ` throw serializationError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
705
+ ` return value`,
706
+ ` })`,
707
+ ` }`,
708
+ ` catch (error) {`,
709
+ ` if (serializationErrors.has(error))`,
710
+ ` throw error`,
711
+ ` throw serializationError('Sandbox result must be JSON-serializable.', error)`,
712
+ ` }`,
713
+ `}`,
714
+ ``,
715
+ `export async function main(argv = process.argv.slice(2)) {`,
716
+ ` const [inputPath, outputPath] = argv`,
717
+ ` try {`,
718
+ ` const raw = await readFile(inputPath, 'utf8')`,
719
+ ` const input = await reviveValue(JSON.parse(raw || '{}'), inputPath + '.files', 'input')`,
720
+ ...invocation,
721
+ ` const output = await serializeSuccess(result, outputPath + '.files')`,
722
+ ` await writeFile(outputPath, output)`,
723
+ ` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
724
+ ` }`,
725
+ ` catch (error) {`,
726
+ ` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
727
+ ` await writeFile(outputPath, output)`,
728
+ ` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
729
+ ` process.exitCode = 1`,
730
+ ` }`,
731
+ `}`,
732
+ ``,
733
+ `await main()`,
734
+ ``
735
+ ].join("\n");
736
+ }
737
+ //#endregion
738
+ //#region src/task/runtime/execution-files.ts
739
+ const DEFAULT_DEFINITION_ENTRY = "definition.js";
740
+ function normalizeSandboxTaskDefinitionBundle(source) {
741
+ if (typeof source === "string") return {
742
+ entry: DEFAULT_DEFINITION_ENTRY,
743
+ modules: { [DEFAULT_DEFINITION_ENTRY]: source }
744
+ };
745
+ return source;
746
+ }
747
+ function createExecutionFiles(definitionName) {
748
+ const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
749
+ const baseDir = `/tmp/vitehub-sandbox-task/${definitionName.replace(/[^a-z0-9/_-]/gi, "_")}-${nonce}`;
750
+ return {
751
+ baseDir,
752
+ entryPath: `${baseDir}/entry.mjs`,
753
+ inputAssetsDir: `${baseDir}/input.json.files`,
754
+ inputPath: `${baseDir}/input.json`,
755
+ outputAssetsDir: `${baseDir}/output.json.files`,
756
+ outputPath: `${baseDir}/output.json`
757
+ };
758
+ }
759
+ function resolveSandboxTaskModulePath(baseDir, modulePath) {
760
+ const normalizedPath = modulePath.replaceAll("\\", "/");
761
+ if (normalizedPath === ".") return baseDir;
762
+ return `${baseDir}/${normalizedPath}`;
763
+ }
764
+ function normalizeSandboxTaskBundlePath(path) {
765
+ const slashPath = path.replace(/\\/g, "/");
766
+ const normalized = slashPath.replace(/^\/+|\/+$/g, "");
767
+ const parts = normalized.split("/").filter(Boolean);
768
+ if (!normalized || slashPath.startsWith("/") || /^[A-Za-z]:\//.test(slashPath) || parts.some((part) => part === "." || part === "..")) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0067({ message: `[vitehub] Sandbox bundle path must stay inside the project: ${path}.` });
769
+ return parts.join("/");
770
+ }
771
+ async function writeSandboxTaskDefinitionBundle(sandbox, baseDir, bundle, signal) {
772
+ const files = Object.entries({
773
+ ...bundle.project ? Object.fromEntries(Object.entries(bundle.project.files).map(([path, file]) => [path, Uint8Array.from(Buffer.from(file.contents, file.encoding))])) : {},
774
+ ...bundle.modules
775
+ }).map(([path, source]) => ({
776
+ path: normalizeSandboxTaskBundlePath(path),
777
+ source
778
+ }));
779
+ const modes = Object.entries(bundle.project?.files || {}).filter(([, file]) => Boolean(file.mode)).map(([path, file]) => ({
780
+ mode: file.mode,
781
+ path: normalizeSandboxTaskBundlePath(path)
782
+ }));
783
+ await sandbox.files.remove(baseDir, {
784
+ recursive: true,
785
+ signal
786
+ });
787
+ await sandbox.files.mkdir(baseDir, {
788
+ recursive: true,
789
+ signal
790
+ });
791
+ await Promise.all(files.map(async ({ path, source }) => {
792
+ const parent = dirname(path);
793
+ if (parent !== ".") await sandbox.files.mkdir(`${baseDir}/${parent}`, {
794
+ recursive: true,
795
+ signal
796
+ });
797
+ await sandbox.files.write(`${baseDir}/${path}`, typeof source === "string" ? new TextEncoder().encode(source) : source, { signal });
798
+ }));
799
+ await Promise.all(modes.map(async ({ mode, path }) => {
800
+ if (signal) await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`], { signal });
801
+ else await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`]);
802
+ }));
803
+ }
804
+ //#endregion
805
+ //#region src/task/runtime/definition-preparation.ts
806
+ const projectPreparations = /* @__PURE__ */ new Map();
807
+ async function prepareSandboxTaskDefinition(sandbox, bundle, baseDir, options) {
808
+ const project = bundle.project;
809
+ if (!project) {
810
+ await writeSandboxTaskDefinitionBundle(sandbox, baseDir, bundle, options.signal);
811
+ return {
812
+ directory: baseDir,
813
+ cwd: baseDir
814
+ };
815
+ }
816
+ const projectDir = `/tmp/vitehub-sandbox-task/projects/${project.digest}`;
817
+ const marker = `${projectDir}/.vitehub/prepared`;
818
+ const prepared = {
819
+ directory: projectDir,
820
+ cwd: resolveSandboxTaskModulePath(projectDir, project.packagePath)
821
+ };
822
+ await sandbox.mkdir("/tmp/vitehub-sandbox-task/projects", {
823
+ recursive: true,
824
+ signal: options.signal
825
+ });
826
+ if (await sandbox.exists(marker, { signal: options.signal })) return prepared;
827
+ const preparationKey = `${sandbox.id}:${project.digest}`;
828
+ while (!await sandbox.exists(marker, { signal: options.signal })) {
829
+ let preparation = projectPreparations.get(preparationKey);
830
+ let owned = false;
831
+ if (!preparation) {
832
+ owned = true;
833
+ preparation = prepareSandboxTaskProjectAtomically(sandbox, {
834
+ ...bundle,
835
+ project
836
+ }, projectDir, marker, options);
837
+ projectPreparations.set(preparationKey, preparation);
838
+ preparation.finally(() => {
839
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
840
+ }).catch(() => {});
841
+ }
842
+ try {
843
+ await preparation;
844
+ } catch (error) {
845
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
846
+ if (owned || options.signal?.aborted) throw error;
847
+ continue;
848
+ }
849
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
850
+ }
851
+ return prepared;
852
+ }
853
+ async function prepareSandboxTaskProjectAtomically(sandbox, bundle, projectDir, marker, options) {
854
+ if (await sandbox.exists(marker, { signal: options.signal })) return;
855
+ const staging = `${projectDir}.staging-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
856
+ try {
857
+ await sandbox.mkdir(staging, {
858
+ recursive: true,
859
+ signal: options.signal
860
+ });
861
+ await writeSandboxTaskDefinitionBundle(sandbox, staging, bundle, options.signal);
862
+ const result = await sandbox.exec(bundle.project.install.command, bundle.project.install.args, {
863
+ signal: options.signal,
864
+ timeout: options.timeout,
865
+ cwd: resolveSandboxTaskModulePath(staging, bundle.project.install.cwd)
866
+ });
867
+ if (!result.ok) throw sandboxTaskError("Sandbox package preparation failed.", {
868
+ code: "SANDBOX_TASK_EXECUTION_ERROR",
869
+ details: {
870
+ command: bundle.project.install.command,
871
+ exitCode: result.code,
872
+ stderr: result.stderr
873
+ }
874
+ });
875
+ await sandbox.mkdir(`${staging}/.vitehub`, {
876
+ recursive: true,
877
+ signal: options.signal
878
+ });
879
+ await sandbox.writeFile(`${staging}/.vitehub/prepared`, bundle.project.digest, { signal: options.signal });
880
+ const published = await sandbox.exec("node", [
881
+ "-e",
882
+ "import(\"node:fs/promises\").then(({ rename }) => rename(process.argv[1], process.argv[2]))",
883
+ staging,
884
+ projectDir
885
+ ], { signal: options.signal });
886
+ if (!published.ok && !await sandbox.exists(marker, { signal: options.signal })) throw sandboxTaskError("Sandbox package preparation could not publish its project.", {
887
+ code: "SANDBOX_TASK_EXECUTION_ERROR",
888
+ details: {
889
+ exitCode: published.code,
890
+ stderr: published.stderr
891
+ }
892
+ });
893
+ } finally {
894
+ await sandbox.exec("rm", [
895
+ "-rf",
896
+ "--",
897
+ staging
898
+ ]).catch(() => {});
899
+ }
900
+ }
901
+ //#endregion
902
+ //#region src/task/runtime/output-recovery.ts
903
+ const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
904
+ const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
905
+ const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
906
+ const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
907
+ const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
908
+ const HANDLER_DIAGNOSTIC_LENGTH = 16384;
909
+ function getErrorMessage(error) {
910
+ if (error instanceof Error) return error.message;
911
+ if (error && typeof error === "object") {
912
+ const candidate = error;
913
+ if (typeof candidate.message === "string" && candidate.message) return candidate.message;
914
+ if (typeof candidate.stderr === "string" && candidate.stderr) return candidate.stderr;
915
+ if (typeof candidate.stdout === "string" && candidate.stdout) return candidate.stdout;
916
+ }
917
+ if (error === void 0) return void 0;
918
+ return String(error);
919
+ }
920
+ function isRecoverableCloudflareExecError(error) {
921
+ const metadata = readSandboxTaskErrorMetadata(error);
922
+ if (metadata?.provider && metadata.provider !== "cloudflare") return false;
923
+ if (metadata?.code === "SANDBOX_TASK_TIMEOUT" || metadata?.code === "SANDBOX_TASK_TRANSPORT_ERROR") return true;
924
+ return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
925
+ }
926
+ function createHandlerError(message, provider, details) {
927
+ const publicDetails = {};
928
+ for (const [key, value] of Object.entries(details || {})) if (typeof value === "string") publicDetails[key] = value.slice(0, HANDLER_DIAGNOSTIC_LENGTH);
929
+ else if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) publicDetails[key] = value;
930
+ return sandboxTaskError(message.slice(0, HANDLER_DIAGNOSTIC_LENGTH) || "Sandbox handler failed.", {
931
+ code: "SANDBOX_TASK_HANDLER_ERROR",
932
+ provider,
933
+ details: Object.keys(publicDetails).length ? publicDetails : void 0
934
+ });
935
+ }
936
+ function createTimeoutError(provider, timeout) {
937
+ return sandboxTaskError(`Sandbox Task Definition timed out after ${timeout}ms.`, {
938
+ code: "SANDBOX_TASK_TIMEOUT",
939
+ provider,
940
+ details: { timeout }
941
+ });
942
+ }
943
+ function tryParseSandboxTaskOutput(outputRaw) {
944
+ if (!outputRaw.trim()) return null;
945
+ try {
946
+ const output = JSON.parse(outputRaw);
947
+ if (!hasRuntimeType(output, "object") || output === null || Array.isArray(output) || !hasRuntimeType(Reflect.get(output, "ok"), "boolean")) return null;
948
+ return output;
949
+ } catch {
950
+ return null;
951
+ }
952
+ }
953
+ function isCompleteSandboxTaskOutput(outputRaw) {
954
+ if (!outputRaw.trim()) return false;
955
+ try {
956
+ JSON.parse(outputRaw);
957
+ return true;
958
+ } catch {
959
+ return false;
960
+ }
961
+ }
962
+ function extractSandboxTaskOutputFromExecution(execution) {
963
+ const streams = [execution?.stdout, execution?.stderr].filter(Boolean);
964
+ for (const stream of streams) {
965
+ const markerOffset = stream.lastIndexOf(EXEC_STDIO_OUTPUT_MARKER);
966
+ if (markerOffset < 0) continue;
967
+ const lineStart = stream.lastIndexOf("\n", markerOffset) + 1;
968
+ const lineEnd = stream.indexOf("\n", markerOffset);
969
+ const markerIndex = stream.indexOf(EXEC_STDIO_OUTPUT_MARKER, lineStart);
970
+ return stream.slice(markerIndex + 18, lineEnd < 0 ? stream.length : lineEnd);
971
+ }
972
+ return null;
973
+ }
974
+ function previewExecutionStream(stream) {
975
+ if (!stream) return void 0;
976
+ return stream.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH);
977
+ }
978
+ function getExecutionDiagnostics(execution) {
979
+ return {
980
+ args: Array.isArray(execution?.meta?.args) ? execution?.meta?.args : void 0,
981
+ command: typeof execution?.meta?.command === "string" ? execution.meta.command : void 0,
982
+ cwd: typeof execution?.meta?.cwd === "string" ? execution.meta.cwd : void 0,
983
+ exitCode: typeof execution?.code === "undefined" ? void 0 : execution.code,
984
+ stderrPreview: previewExecutionStream(execution?.stderr),
985
+ stdoutPreview: previewExecutionStream(execution?.stdout)
986
+ };
987
+ }
988
+ function getErrorDiagnostics(error) {
989
+ if (!error || typeof error !== "object" || !("details" in error)) return {};
990
+ const details = error.details;
991
+ if (!details || typeof details !== "object") return {};
992
+ return {
993
+ args: Array.isArray(details.args) ? details.args : void 0,
994
+ command: typeof details.command === "string" ? details.command : void 0,
995
+ cwd: typeof details.cwd === "string" ? details.cwd : void 0,
996
+ exitCode: typeof details.exitCode === "number" || details.exitCode === null ? details.exitCode : void 0,
997
+ spawnErrorCode: typeof details.spawnErrorCode === "string" ? details.spawnErrorCode : void 0,
998
+ spawnErrorMessage: typeof details.spawnErrorMessage === "string" ? details.spawnErrorMessage : void 0,
999
+ stderrPreview: typeof details.stderrPreview === "string" ? details.stderrPreview : void 0,
1000
+ stdoutPreview: typeof details.stdoutPreview === "string" ? details.stdoutPreview : void 0
1001
+ };
1002
+ }
1003
+ function resolveExecOutputRecoveryTimeout(timeout) {
1004
+ if (!timeout || timeout <= 0) return DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS;
1005
+ return Math.min(MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.max(MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.floor(timeout * .1)));
1006
+ }
1007
+ function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, details) {
1008
+ return createHandlerError("Sandbox Task Definition execution failed before producing an output file.", sandbox.provider, {
1009
+ outputPath,
1010
+ cause: getErrorMessage(error),
1011
+ recoveryTimeout,
1012
+ ...details,
1013
+ ...getErrorDiagnostics(error),
1014
+ ...getExecutionDiagnostics(execution)
1015
+ });
1016
+ }
1017
+ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1018
+ const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
1019
+ const deadline = Date.now() + recoveryTimeout;
1020
+ let lastError = error;
1021
+ let lastOutput = "";
1022
+ while (Date.now() < deadline) {
1023
+ signal?.throwIfAborted();
1024
+ try {
1025
+ const output = await sandbox.readFile(outputPath, { signal });
1026
+ lastOutput = output;
1027
+ if (isCompleteSandboxTaskOutput(output)) return output;
1028
+ } catch (readError) {
1029
+ if (signal?.aborted) throw signal.reason;
1030
+ lastError = readError;
1031
+ }
1032
+ const remaining = deadline - Date.now();
1033
+ if (remaining > 0) await sleep(Math.min(EXEC_OUTPUT_RECOVERY_POLL_MS, remaining), signal);
1034
+ }
1035
+ signal?.throwIfAborted();
1036
+ throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, {
1037
+ lastReadError: getErrorMessage(lastError),
1038
+ outputPreview: lastOutput.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH) || void 0
1039
+ });
1040
+ }
1041
+ async function recoverExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1042
+ if (sandbox.provider !== "cloudflare" || !isRecoverableCloudflareExecError(error)) return null;
1043
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1044
+ }
1045
+ async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal) {
1046
+ const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
1047
+ signal?.throwIfAborted();
1048
+ if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
1049
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1050
+ }
1051
+ async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution, signal) {
1052
+ const executionOutput = extractSandboxTaskOutputFromExecution(execution) || extractSandboxTaskOutputFromExecution(error);
1053
+ if (executionOutput) return executionOutput;
1054
+ try {
1055
+ const output = await sandbox.readFile(outputPath, { signal });
1056
+ if (isCompleteSandboxTaskOutput(output)) return output;
1057
+ } catch {
1058
+ signal?.throwIfAborted();
1059
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1060
+ }
1061
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1062
+ }
1063
+ //#endregion
1064
+ //#region src/task/runtime/execute.ts
1065
+ const SANDBOX_CLEANUP_GRACE_MS = 1e3;
1066
+ function toJson(value, label) {
1067
+ try {
1068
+ return JSON.stringify(value);
1069
+ } catch (error) {
1070
+ throw sandboxTaskError(`Sandbox ${label} must be JSON-serializable.`, {
1071
+ code: "SANDBOX_TASK_SERIALIZATION_ERROR",
1072
+ details: { label },
1073
+ cause: error
1074
+ });
1075
+ }
1076
+ }
1077
+ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, lifecycle, deadline) {
1078
+ const bundle = normalizeSandboxTaskDefinitionBundle(source);
1079
+ const files = createExecutionFiles(definitionName);
1080
+ let failure;
1081
+ const throwIfAborted = () => {
1082
+ if (signal?.aborted) throw signal.reason ?? new DOMException("The Sandbox invocation was aborted.", "AbortError");
1083
+ };
1084
+ try {
1085
+ await sandbox.mkdir(files.baseDir, {
1086
+ recursive: true,
1087
+ signal
1088
+ });
1089
+ throwIfAborted();
1090
+ let inputJson = bundle.project ? toJson(await encodeSandboxTaskValue(sandbox, {
1091
+ payload,
1092
+ context
1093
+ }, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
1094
+ const prepared = await prepareSandboxTaskDefinition(sandbox, bundle, files.baseDir, {
1095
+ signal,
1096
+ timeout: definitionOptions?.timeout
1097
+ });
1098
+ inputJson ||= toJson(await encodeSandboxTaskValue(sandbox, {
1099
+ payload,
1100
+ context
1101
+ }, files.inputAssetsDir, "payload/context", signal), "payload/context");
1102
+ const definitionPath = resolveSandboxTaskModulePath(prepared.directory, bundle.entry);
1103
+ throwIfAborted();
1104
+ await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution), { signal }), sandbox.writeFile(files.inputPath, inputJson, { signal })]);
1105
+ throwIfAborted();
1106
+ const execArgs = [
1107
+ "-e",
1108
+ "import(process.argv[1])",
1109
+ files.entryPath,
1110
+ files.inputPath,
1111
+ files.outputPath
1112
+ ];
1113
+ let outputRaw = "";
1114
+ let execution;
1115
+ try {
1116
+ lifecycle?.onHandlerStart?.();
1117
+ execution = await sandbox.exec("node", execArgs, {
1118
+ cwd: prepared.cwd,
1119
+ env: definitionOptions?.env,
1120
+ signal,
1121
+ timeout: definitionOptions?.timeout
1122
+ });
1123
+ outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution, signal);
1124
+ } catch (error) {
1125
+ throwIfAborted();
1126
+ if (readSandboxTaskErrorMetadata(error)?.details?.operation === "createSession") throw error;
1127
+ if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1128
+ else {
1129
+ const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1130
+ if (recoveredOutput == null) throw error;
1131
+ outputRaw = recoveredOutput;
1132
+ }
1133
+ }
1134
+ const output = tryParseSandboxTaskOutput(outputRaw) || tryParseSandboxTaskOutput(extractSandboxTaskOutputFromExecution(execution) || "");
1135
+ if (!output) throw createHandlerError("Sandbox Task Definition output is not valid JSON.", sandbox.provider, {
1136
+ output: outputRaw,
1137
+ cause: "Output file was empty or contained incomplete JSON."
1138
+ });
1139
+ if (output.ok) return await decodeSandboxTaskValue(sandbox, output.result, files.outputAssetsDir, "result", signal);
1140
+ if (output.error?.code === "SANDBOX_TASK_SERIALIZATION_ERROR") throw sandboxTaskError(output.error.message || "Sandbox result must be JSON-serializable.", {
1141
+ code: "SANDBOX_TASK_SERIALIZATION_ERROR",
1142
+ provider: sandbox.provider,
1143
+ cause: output.error.cause
1144
+ });
1145
+ throw createHandlerError(output.error?.message || "Sandbox Task Definition failed.", sandbox.provider, {
1146
+ name: output.error?.name,
1147
+ stack: output.error?.stack,
1148
+ cause: output.error?.cause,
1149
+ stdout: execution?.stdout,
1150
+ stderr: execution?.stderr,
1151
+ exitCode: execution?.code
1152
+ });
1153
+ } catch (error) {
1154
+ failure = { error };
1155
+ throw error;
1156
+ } finally {
1157
+ if (sandbox.provider === "cloudflare") {
1158
+ const cleanupTimeout = deadline === void 0 ? void 0 : SANDBOX_CLEANUP_GRACE_MS;
1159
+ const cleanupOptions = cleanupTimeout === void 0 ? void 0 : { timeout: cleanupTimeout };
1160
+ try {
1161
+ const cleanup = await sandbox.exec("rm", [
1162
+ "-rf",
1163
+ "--",
1164
+ files.baseDir
1165
+ ], cleanupOptions).catch((error) => {
1166
+ throw sandboxTaskError("Sandbox invocation cleanup failed.", {
1167
+ provider: sandbox.provider,
1168
+ cause: error
1169
+ });
1170
+ });
1171
+ if (!cleanup.ok || cleanup.code !== 0) throw sandboxTaskError("Sandbox invocation cleanup failed.", {
1172
+ provider: sandbox.provider,
1173
+ details: {
1174
+ operation: "cleanup",
1175
+ exitCode: cleanup.code
1176
+ },
1177
+ cause: cleanup
1178
+ });
1179
+ } catch (cleanupError) {
1180
+ if (failure) throw combineSandboxTaskErrors(failure.error, cleanupError);
1181
+ throw cleanupError;
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ async function executeSandboxTaskDefinition(sandbox, definitionName, definitionOptions, source, payload, context, lifecycle, externalSignal) {
1187
+ const timeout = definitionOptions?.timeout;
1188
+ const execute = (signal) => {
1189
+ const execution = executeSandboxTaskDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, lifecycle);
1190
+ lifecycle?.onExecution?.(execution);
1191
+ return execution;
1192
+ };
1193
+ if ((timeout === void 0 || timeout <= 0) && !externalSignal) return await execute();
1194
+ externalSignal?.throwIfAborted();
1195
+ let timeoutId;
1196
+ const abortController = new AbortController();
1197
+ const deadline = timeout === void 0 || timeout <= 0 ? void 0 : Date.now() + timeout;
1198
+ let timedOut = false;
1199
+ let timeoutError;
1200
+ const signal = timeout === void 0 || timeout <= 0 ? externalSignal : externalSignal ? AbortSignal.any([externalSignal, abortController.signal]) : abortController.signal;
1201
+ let externalAbort;
1202
+ let execution;
1203
+ try {
1204
+ const currentExecution = execution = executeSandboxTaskDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, lifecycle, deadline);
1205
+ lifecycle?.onExecution?.(currentExecution);
1206
+ const races = [currentExecution];
1207
+ if (externalSignal) races.push(new Promise((_, reject) => {
1208
+ externalAbort = () => reject(externalSignal.reason ?? new DOMException("The Sandbox invocation was aborted.", "AbortError"));
1209
+ externalSignal.addEventListener("abort", externalAbort, { once: true });
1210
+ }));
1211
+ if (timeout !== void 0 && timeout > 0) races.push(new Promise((_, reject) => {
1212
+ timeoutId = setTimeout(() => {
1213
+ timeoutError = createTimeoutError(sandbox.provider, timeout);
1214
+ timedOut = true;
1215
+ abortController.abort(timeoutError);
1216
+ reject(timeoutError);
1217
+ }, timeout);
1218
+ }));
1219
+ return await Promise.race(races);
1220
+ } catch (error) {
1221
+ if (timedOut) {
1222
+ await execution.catch((executionError) => {
1223
+ if (executionError !== timeoutError) throw sandboxTaskError(timeoutError.message, {
1224
+ code: "SANDBOX_TASK_TIMEOUT",
1225
+ details: timeoutError.details,
1226
+ cause: executionError
1227
+ });
1228
+ });
1229
+ throw timeoutError ?? error;
1230
+ }
1231
+ throw error;
1232
+ } finally {
1233
+ if (timeoutId) clearTimeout(timeoutId);
1234
+ if (externalAbort) externalSignal?.removeEventListener("abort", externalAbort);
1235
+ }
1236
+ }
1237
+ //#endregion
1238
+ //#region src/task/runtime/task-sandbox.ts
1239
+ function createTaskSandbox(session, provider) {
1240
+ return {
1241
+ executionAuthority: session.executionAuthority,
1242
+ id: session.id,
1243
+ files: session.files,
1244
+ provider,
1245
+ async close() {
1246
+ await session.close();
1247
+ },
1248
+ async exec(command, args, options) {
1249
+ return await session.exec(command, args, options);
1250
+ },
1251
+ async exists(path, options) {
1252
+ return await session.files.exists(path, options);
1253
+ },
1254
+ async mkdir(path, options) {
1255
+ await session.files.mkdir(path, options);
1256
+ },
1257
+ async readFile(path, options) {
1258
+ const contents = await session.files.read(path, options);
1259
+ if (!contents) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0066({ message: `[vitehub] Sandbox file does not exist: ${path}` });
1260
+ return new TextDecoder().decode(contents);
1261
+ },
1262
+ async writeFile(path, contents, options) {
1263
+ await session.files.write(path, new TextEncoder().encode(contents), options);
1264
+ }
1265
+ };
1266
+ }
1267
+ //#endregion
1268
+ //#region src/task/internal/shared/provider-detection.ts
1269
+ function createProviderDetector(rules) {
1270
+ return () => {
1271
+ for (const rule of rules) if (rule.when()) return rule.provider;
1272
+ };
1273
+ }
1274
+ function getRuntimeEnv() {
1275
+ return typeof process !== "undefined" ? process.env : {};
1276
+ }
1277
+ const isCloudflare = () => {
1278
+ const env = getRuntimeEnv();
1279
+ return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
1280
+ };
1281
+ const isVercel = () => {
1282
+ const env = getRuntimeEnv();
1283
+ return !!(env.VERCEL || env.VERCEL_ENV);
1284
+ };
1285
+ //#endregion
1286
+ //#region src/task/runtime/provider-resolution.ts
1287
+ const allowedDefinitionKeys = /* @__PURE__ */ new Set(["timeout", "env"]);
1288
+ const maxTimeout = 2147483647;
1289
+ const detectProvider = createProviderDetector([{
1290
+ provider: "cloudflare",
1291
+ when: isCloudflare
1292
+ }, {
1293
+ provider: "vercel",
1294
+ when: isVercel
1295
+ }]);
1296
+ function detectSandbox() {
1297
+ const env = typeof process !== "undefined" ? process.env : {};
1298
+ const type = detectProvider() || "none";
1299
+ if (type === "cloudflare") return {
1300
+ type,
1301
+ details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
1302
+ };
1303
+ if (type === "vercel") return {
1304
+ type,
1305
+ details: { env: env.VERCEL_ENV }
1306
+ };
1307
+ return { type };
1308
+ }
1309
+ function hashCloudflareSandboxName(name) {
1310
+ let hash = 2166136261;
1311
+ for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
1312
+ return (hash >>> 0).toString(36);
1313
+ }
1314
+ function createCloudflareExecutionSandboxId(name, sandboxId) {
1315
+ if (sandboxId) return sandboxId;
1316
+ const prefix = "vitehub-";
1317
+ const suffix = `-${hashCloudflareSandboxName(name)}-${crypto.randomUUID()}`;
1318
+ return `${prefix}${encodeURIComponent(name).slice(0, 55 - suffix.length)}${suffix}`;
1319
+ }
1320
+ function resolveRuntimeProvider(provider, event) {
1321
+ if (provider?.provider) return provider.provider;
1322
+ const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
1323
+ if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
1324
+ if (getCloudflareEnv(event)) return "cloudflare";
1325
+ const detected = detectSandbox();
1326
+ if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
1327
+ throw sandboxTaskError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_TASK_PROVIDER_REQUIRED" });
1328
+ }
1329
+ function assertSandboxTaskDefinitionOptions(local) {
1330
+ const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
1331
+ if (invalidKeys.length > 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0069({ message: `[vitehub] Sandbox Task Definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}` });
1332
+ if (local.timeout !== void 0 && (!Number.isInteger(local.timeout) || local.timeout <= 0 || local.timeout > maxTimeout)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0070({ message: `[vitehub] Sandbox Task Definition timeout must be a positive integer no greater than ${maxTimeout}.` });
1333
+ }
1334
+ async function resolveTaskSandbox(provider, providerOptions, local, context) {
1335
+ return await (await (await import("vitehub-sandbox-task-provider-loader").catch(() => {
1336
+ return new Function("specifier", "return import(specifier)")("@vite-hub/sandbox/task/runtime/provider-loader");
1337
+ })).loadSandboxTaskRuntimeProvider(provider)).resolveTaskSandbox({
1338
+ local,
1339
+ provider: providerOptions
1340
+ }, context);
1341
+ }
1342
+ function withSandboxTaskProvider(provider, options) {
1343
+ return {
1344
+ ...options,
1345
+ provider
1346
+ };
1347
+ }
1348
+ //#endregion
1349
+ //#region src/task/runtime/result.ts
1350
+ /** Convert a sandbox value to the native Web Response contract. */
1351
+ async function ok(value) {
1352
+ return toResponse(value);
1353
+ }
1354
+ function statusFor(error) {
1355
+ const status = error.details?.httpStatus;
1356
+ if (Number.isInteger(status) && Number(status) >= 400 && Number(status) <= 599) return Number(status);
1357
+ if (error.code.includes("TIMEOUT")) return 504;
1358
+ if (error.code.includes("NOT_FOUND")) return 404;
1359
+ if (error.code.includes("VALIDATION")) return 400;
1360
+ return 500;
1361
+ }
1362
+ function err(error) {
1363
+ const body = JSON.stringify({ error: {
1364
+ code: error.code,
1365
+ message: error.message,
1366
+ details: error.details
1367
+ } });
1368
+ return new Response(body, {
1369
+ status: statusFor(error),
1370
+ headers: { "content-type": "application/json; charset=utf-8" }
1371
+ });
1372
+ }
1373
+ //#endregion
1374
+ //#region src/task/runtime/runtime.ts
1375
+ const cloudflareRunQueues = /* @__PURE__ */ new Map();
1376
+ async function awaitWithAbort(promise, signal) {
1377
+ if (!signal) return await promise;
1378
+ if (signal.aborted) {
1379
+ promise.catch(() => {});
1380
+ throw signal.reason;
1381
+ }
1382
+ return await new Promise((resolve, reject) => {
1383
+ const onAbort = () => {
1384
+ signal.removeEventListener("abort", onAbort);
1385
+ reject(signal.reason);
1386
+ };
1387
+ signal.addEventListener("abort", onAbort, { once: true });
1388
+ promise.then((value) => {
1389
+ signal.removeEventListener("abort", onAbort);
1390
+ resolve(value);
1391
+ }, (error) => {
1392
+ signal.removeEventListener("abort", onAbort);
1393
+ reject(error);
1394
+ });
1395
+ });
1396
+ }
1397
+ async function serializeCloudflareRun(id, run, signal) {
1398
+ if (!id) return await run();
1399
+ const previous = cloudflareRunQueues.get(id) ?? Promise.resolve();
1400
+ let release;
1401
+ const current = new Promise((resolve) => {
1402
+ release = resolve;
1403
+ });
1404
+ cloudflareRunQueues.set(id, current);
1405
+ let started = false;
1406
+ const releaseAfterPrevious = () => {
1407
+ release();
1408
+ if (cloudflareRunQueues.get(id) === current) cloudflareRunQueues.delete(id);
1409
+ };
1410
+ try {
1411
+ await awaitWithAbort(previous, signal);
1412
+ signal?.throwIfAborted();
1413
+ started = true;
1414
+ return await run();
1415
+ } finally {
1416
+ if (started) releaseAfterPrevious();
1417
+ else previous.then(releaseAfterPrevious, releaseAfterPrevious);
1418
+ }
1419
+ }
1420
+ function isRetriableCloudflareSandboxError(error) {
1421
+ if (isSandboxTaskError(error) && error.cause instanceof AggregateError) error = error.cause.errors[0];
1422
+ const metadata = readSandboxTaskErrorMetadata(error);
1423
+ const provider = metadata?.provider;
1424
+ if (provider && provider !== "cloudflare") return false;
1425
+ if (metadata?.code === "SANDBOX_TASK_TIMEOUT") return false;
1426
+ const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
1427
+ return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
1428
+ }
1429
+ async function loadSandboxTaskDefinition(name) {
1430
+ const registry = getSandboxTaskRuntimeRegistry() ?? {};
1431
+ const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
1432
+ if (!entry) return void 0;
1433
+ return typeof entry === "function" ? (await entry()).default : entry;
1434
+ }
1435
+ function hasValidSandboxTaskBundle(definition) {
1436
+ return !!definition.bundle && typeof definition.bundle === "object" && typeof definition.bundle.entry === "string" && definition.bundle.entry.length > 0 && !!definition.bundle.modules && typeof definition.bundle.modules === "object" && (Object.hasOwn(definition.bundle.modules, definition.bundle.entry) || !!definition.bundle.project?.files && typeof definition.bundle.project.files === "object" && Object.hasOwn(definition.bundle.project.files, definition.bundle.entry));
1437
+ }
1438
+ async function resolveSandboxTaskProvider(sandboxTaskConfig, definition) {
1439
+ assertSandboxTaskDefinitionOptions(definition.options ?? {});
1440
+ const config = getSandboxTaskFeatureProvider(sandboxTaskConfig);
1441
+ const provider = resolveRuntimeProvider(config);
1442
+ return await resolveTaskSandbox(provider, withSandboxTaskProvider(provider, config), definition.options ?? {}, {});
1443
+ }
1444
+ async function createSandboxTaskRunner(name, definition, provider) {
1445
+ const packageManager = definition.bundle.project?.install.command;
1446
+ const sandbox = await provider.resolveSandbox(["node", ...packageManager ? [packageManager] : []]);
1447
+ return {
1448
+ executionAuthority: sandbox.plan.executionAuthority,
1449
+ name,
1450
+ async run(payload, options = {}) {
1451
+ const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(name, options.sandboxId || provider.sandboxId) : void 0;
1452
+ const attempts = provider.provider === "cloudflare" ? CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length + 1 : 1;
1453
+ options.signal?.throwIfAborted();
1454
+ return await awaitWithAbort(serializeCloudflareRun(cloudflareSandboxId, async () => {
1455
+ for (let attempt = 0; attempt < attempts; attempt++) {
1456
+ let taskSandbox;
1457
+ let handlerMayHaveStarted = false;
1458
+ let runError;
1459
+ let executionSettled;
1460
+ try {
1461
+ taskSandbox = createTaskSandbox(options.signal ? await sandbox.open({
1462
+ id: cloudflareSandboxId,
1463
+ signal: options.signal
1464
+ }) : await sandbox.open({ id: cloudflareSandboxId }), provider.provider);
1465
+ const lifecycle = {
1466
+ onExecution(execution) {
1467
+ executionSettled = execution.then(() => void 0, () => void 0);
1468
+ },
1469
+ onHandlerStart() {
1470
+ handlerMayHaveStarted = true;
1471
+ }
1472
+ };
1473
+ return options.signal ? await executeSandboxTaskDefinition(taskSandbox, name, definition.options, definition.bundle, payload, options.context, lifecycle, options.signal) : await executeSandboxTaskDefinition(taskSandbox, name, definition.options, definition.bundle, payload, options.context, lifecycle);
1474
+ } catch (error) {
1475
+ if (options.signal?.aborted) throw options.signal.reason ?? error;
1476
+ const sandboxTaskError = toSandboxTaskError(error);
1477
+ runError = sandboxTaskError;
1478
+ if (!(!handlerMayHaveStarted && provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(error))) throw sandboxTaskError;
1479
+ if (options.signal) await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt], options.signal);
1480
+ else await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
1481
+ } finally {
1482
+ await executionSettled;
1483
+ if (options.signal?.aborted || readSandboxTaskErrorMetadata(runError)?.code === "SANDBOX_TASK_TIMEOUT" || provider.closeAfterRun !== false || provider.provider === "cloudflare" && !options.sandboxId && !provider.sandboxId) try {
1484
+ await taskSandbox?.close();
1485
+ } catch (cleanupError) {
1486
+ if (options.signal?.aborted) throw options.signal.reason ?? cleanupError;
1487
+ if (runError) throw combineSandboxTaskErrors(runError, cleanupError);
1488
+ throw toSandboxTaskError(cleanupError);
1489
+ }
1490
+ }
1491
+ }
1492
+ throw sandboxTaskError("Cloudflare sandbox retries exhausted.", {
1493
+ code: "SANDBOX_TASK_RUNTIME_ERROR",
1494
+ provider: provider.provider
1495
+ });
1496
+ }, options.signal), options.signal);
1497
+ }
1498
+ };
1499
+ }
1500
+ async function resolveSandboxTaskRunner(name) {
1501
+ if (!name) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0052({ message: "[vitehub] Sandbox name is required. An explicit name is required." });
1502
+ const config = getSandboxTaskRuntimeConfig();
1503
+ const definition = await loadSandboxTaskDefinition(name);
1504
+ if (!definition) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0053({ message: `[vitehub] Unknown Sandbox Task "${name}".` });
1505
+ if (!hasValidSandboxTaskBundle(definition)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0054({ message: `[vitehub] Sandbox "${name}" is invalid.` });
1506
+ return await createSandboxTaskRunner(name, definition, await resolveSandboxTaskProvider(config, definition));
1507
+ }
1508
+ async function runSandboxTaskRuntime(name, payload, options) {
1509
+ try {
1510
+ options?.signal?.throwIfAborted();
1511
+ return await ok(await (await resolveSandboxTaskRunner(name)).run(payload, options));
1512
+ } catch (error) {
1513
+ if (options?.signal?.aborted) throw options.signal.reason ?? error;
1514
+ return err(toSandboxTaskError(error));
1515
+ }
1516
+ }
1517
+ //#endregion
1518
+ //#region src/task/runtime/public.ts
1519
+ async function runSandboxTask(name, payload, options) {
1520
+ return await runSandboxTaskRuntime(name, payload, options);
1521
+ }
1522
+ //#endregion
1523
+ export { defineSandboxTask, readRequestPayload, readValidatedPayload, resolveSandboxTaskRunner, runSandboxTask, unsupportedHostedSandboxTaskProviderError };