@vite-hub/sandbox 0.5.0 → 0.6.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 (57) hide show
  1. package/README.md +20 -0
  2. package/dist/{abortable-CR01hzfi.js → abortable-DrHeTo1e.js} +1 -2
  3. package/dist/{cloudflare-DOrMY3MJ.js → cloudflare-DrNRQPeh.js} +13 -17
  4. package/dist/{cloudflare-env-lookup-DzI6Xv1Y.js → cloudflare-env-lookup-BNbNil7g.js} +1 -2
  5. package/dist/{cloudflare-failure-CFQhalfh.js → cloudflare-failure-f-3P3ul-.js} +1 -2
  6. package/dist/{container-BVb0fw3z.js → container-DOadzngt.js} +7 -9
  7. package/dist/{crabbox-BU8W1gVC.js → crabbox-C7KeIKnH.js} +7 -8
  8. package/dist/{error-diagnostics-BJtLRL9w.js → error-diagnostics-CApUyzzu.js} +1 -2
  9. package/dist/{error-diagnostics-BNQwU9yq.js → error-diagnostics-D9n0ZmdN.js} +8 -5
  10. package/dist/{file-listing-CHtRrfo1.js → file-listing-BF122soX.js} +3 -4
  11. package/dist/{file-lock-D0-XPogS.js → file-lock-CqA7b491.js} +3 -4
  12. package/dist/{index-DHl0T43e.d.ts → index-D9DogaoF.d.ts} +0 -14
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +12 -13
  15. package/dist/internal/cloudflare.d.ts +2 -5
  16. package/dist/internal/cloudflare.js +3 -4
  17. package/dist/internal/host-toolchain.d.ts +2 -4
  18. package/dist/internal/host-toolchain.js +4 -5
  19. package/dist/internal/vercel.d.ts +2 -4
  20. package/dist/internal/vercel.js +3 -4
  21. package/dist/{invariant-DolT9EEx.js → invariant-Dj2R1eMr.js} +1 -2
  22. package/dist/{module-types-B0LQ5H2S.js → module-types-CWcBHyEs.js} +1 -2
  23. package/dist/{module-types-NYnG3NGz.d.ts → module-types-DHr6oC3h.d.ts} +18 -13
  24. package/dist/{process-sweep-CMaujWE5.js → process-sweep-DVaTb2pO.js} +1 -2
  25. package/dist/{provider-loader-Cvqoz7_Z.d.ts → provider-loader-CLIIEEmR.d.ts} +2 -6
  26. package/dist/{provider-resolution-BrQfEQo0.js → provider-resolution-qvRcW1PC.js} +13 -10
  27. package/dist/{remote-fjUPBiLJ.js → remote-DlyX1drC.js} +5 -6
  28. package/dist/{rolldown-runtime-8H4AJuhK.js → rolldown-runtime-BJohB4LM.js} +1 -2
  29. package/dist/{runtime-DHp6ImeP.js → runtime-EtWFVKud.js} +1 -2
  30. package/dist/{runtime-type-Deo4qzxN.js → runtime-type-Dk-rJXlr.js} +1 -2
  31. package/dist/{session-e0lyzjJ3.js → session-DmUiyj4O.js} +5 -8
  32. package/dist/{shell-quote-Q3u3plif.js → shell-quote-MrD49m3N.js} +1 -2
  33. package/dist/ssh.d.ts +1 -3
  34. package/dist/ssh.js +5 -7
  35. package/dist/task/index.d.ts +2 -16
  36. package/dist/task/index.js +345 -142
  37. package/dist/task/runtime/empty-registry.d.ts +0 -2
  38. package/dist/task/runtime/empty-registry.js +1 -2
  39. package/dist/task/runtime/provider-loader.d.ts +1 -1
  40. package/dist/task/runtime/provider-loader.js +2 -3
  41. package/dist/task/runtime/providers/cloudflare.d.ts +3 -4
  42. package/dist/task/runtime/providers/cloudflare.js +3 -4
  43. package/dist/task/runtime/providers/local.d.ts +2 -4
  44. package/dist/task/runtime/providers/local.js +3 -4
  45. package/dist/task/runtime/providers/vercel.d.ts +3 -4
  46. package/dist/task/runtime/providers/vercel.js +6 -8
  47. package/dist/task/runtime/state.d.ts +3 -4
  48. package/dist/task/runtime/state.js +2 -3
  49. package/dist/task/vite.d.ts +23 -24
  50. package/dist/task/vite.js +63 -74
  51. package/dist/{toolchain-DF9eutyQ.js → toolchain-DFFxmw3N.js} +6 -7
  52. package/dist/transfer-options-LTUzbHDw.js +18 -0
  53. package/dist/{trusted-host-DLYiKP8a.js → trusted-host-CwMs64h1.js} +8 -9
  54. package/dist/{trusted-host-environment-CWKJ7DD_.js → trusted-host-environment-BJE5hGtQ.js} +1 -2
  55. package/dist/{vercel-qyDr7NvU.js → vercel-DT74kDyI.js} +9 -13
  56. package/dist/{vercel-credentials-BNTh2X-Y.js → vercel-credentials-BH5lPJxs.js} +3 -5
  57. package/package.json +10 -10
@@ -1,15 +1,15 @@
1
- import { n as cloudflareRetryDelays, r as readCloudflareFailure, t as canRetryCloudflareRequest } from "../cloudflare-failure-CFQhalfh.js";
2
- import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-BNQwU9yq.js";
3
- import { a as resolveTaskSandbox, c as isSandboxTaskError, i as resolveRuntimeProvider, l as sandboxTaskError, n as assertSandboxTaskDefinitionOptions, o as unsupportedHostedSandboxTaskProviderError, r as createCloudflareExecutionSandboxId, s as withSandboxTaskProvider } from "../provider-resolution-BrQfEQo0.js";
4
- import { t as isTrustedHostReservedCommandEnvironmentKey } from "../trusted-host-environment-CWKJ7DD_.js";
1
+ import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-D9n0ZmdN.js";
2
+ import { a as resolveTaskSandbox, c as isSandboxTaskError, i as resolveRuntimeProvider, l as sandboxTaskError, n as assertSandboxTaskDefinitionOptions, o as unsupportedHostedSandboxTaskProviderError, r as createCloudflareExecutionSandboxId, s as withSandboxTaskProvider } from "../provider-resolution-qvRcW1PC.js";
3
+ import { n as cloudflareRetryDelays, r as readCloudflareFailure, t as canRetryCloudflareRequest } from "../cloudflare-failure-f-3P3ul-.js";
4
+ import { t as isTrustedHostReservedCommandEnvironmentKey } from "../trusted-host-environment-BJE5hGtQ.js";
5
5
  import { getSandboxTaskRuntimeConfig, getSandboxTaskRuntimeLocalProvider, getSandboxTaskRuntimeRegistry } from "./runtime/state.js";
6
- import { t as getSandboxTaskFeatureDriver } from "../module-types-B0LQ5H2S.js";
6
+ import { t as getSandboxTaskFeatureDriver } from "../module-types-CWcBHyEs.js";
7
7
  import { defineErrors, getViteHubErrorShape } from "@vite-hub/runtime";
8
8
  import { types } from "node:util";
9
9
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
10
10
  import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
11
11
  import { dirname } from "pathe";
12
- //#region src/task/internal/shared/definition.ts
12
+ // src/task/internal/shared/definition.ts
13
13
  function assertDefinitionHandler(functionName, handler, label) {
14
14
  if (typeof handler !== "function") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0010({ message: `[vitehub] \`${functionName}()\` requires a ${label} as the first argument.` });
15
15
  }
@@ -23,8 +23,7 @@ function validateDefinitionOptions(functionName, options, config) {
23
23
  if (invalidKeys.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0012({ message: `[vitehub] \`${functionName}()\` ${config.invalidKeysMessage}. Unsupported keys: ${invalidKeys.join(", ")}.` });
24
24
  return options;
25
25
  }
26
- //#endregion
27
- //#region src/task/runtime/registry.ts
26
+ // src/task/runtime/registry.ts
28
27
  function createSandboxTaskDefinition(functionName, input) {
29
28
  if (input instanceof Object && Object.hasOwn(input, "run")) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0014({ message: `[vitehub] \`${functionName}({ run })\` was renamed. Pass the Sandbox handler as \`handler\`: \`${functionName}({ handler })\`.` });
30
29
  const validated = validateDefinitionOptions(functionName, input, {
@@ -32,9 +31,10 @@ function createSandboxTaskDefinition(functionName, input) {
32
31
  "handler",
33
32
  "timeout",
34
33
  "env",
34
+ "transfer",
35
35
  "project"
36
36
  ],
37
- invalidKeysMessage: "supports only portable Sandbox options (handler, timeout, env, project)"
37
+ invalidKeysMessage: "supports only portable Sandbox options (handler, timeout, env, transfer, project)"
38
38
  });
39
39
  if (!validated) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0072({ message: `[vitehub] \`${functionName}()\` requires an options object.` });
40
40
  if (typeof validated.project !== "undefined" && typeof validated.project !== "boolean") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0073({ message: `[vitehub] \`${functionName}()\` project must be a boolean.` });
@@ -48,14 +48,12 @@ function createSandboxTaskDefinition(functionName, input) {
48
48
  function defineSandboxTask(input) {
49
49
  return createSandboxTaskDefinition("defineSandboxTask", input);
50
50
  }
51
- //#endregion
52
- //#region src/task/internal/shared/request-payload.ts
51
+ // src/task/internal/shared/request-payload.ts
53
52
  /** Read the JSON body of the request in the event's Standard Context, or `fallback` when the body is not JSON. */
54
53
  async function readRequestPayload(event, fallback = {}) {
55
54
  return await getStandardContext(event).req.json().catch(() => fallback);
56
55
  }
57
- //#endregion
58
- //#region src/task/internal/shared/validation.ts
56
+ // src/task/internal/shared/validation.ts
59
57
  const VALIDATION_FAILED = "Validation failed";
60
58
  function isObject(value) {
61
59
  return !!value && typeof value === "object";
@@ -148,8 +146,7 @@ async function readValidatedPayload(payload, validate, options) {
148
146
  throw createValidationError(error);
149
147
  }
150
148
  }
151
- //#endregion
152
- //#region src/task/internal/shared/utils.ts
149
+ // src/task/internal/shared/utils.ts
153
150
  async function sleep(ms, signal) {
154
151
  if (signal?.aborted) throw signal.reason;
155
152
  await new Promise((resolve, reject) => {
@@ -165,8 +162,7 @@ async function sleep(ms, signal) {
165
162
  signal?.addEventListener("abort", onAbort, { once: true });
166
163
  });
167
164
  }
168
- //#endregion
169
- //#region src/task/runtime/binary-sidecars.ts
165
+ // src/task/runtime/binary-sidecars.ts
170
166
  const SANDBOX_VALUE_MARKER = "vitehub:sandbox-task:value";
171
167
  function isPlainObject(value) {
172
168
  if (!value || typeof value !== "object") return false;
@@ -177,6 +173,14 @@ function isObjectRecord(value) {
177
173
  return !!value && typeof value === "object";
178
174
  }
179
175
  const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
176
+ const blobSizeGetter = typeof Blob === "undefined" ? void 0 : Object.getOwnPropertyDescriptor(Blob.prototype, "size")?.get;
177
+ const blobArrayBuffer = typeof Blob === "undefined" ? void 0 : Blob.prototype.arrayBuffer;
178
+ function readBlobSize(blob) {
179
+ return blobSizeGetter ? Reflect.apply(blobSizeGetter, blob, []) : blob.size;
180
+ }
181
+ async function readBlobBytes(blob) {
182
+ return new Uint8Array(await (blobArrayBuffer ? Reflect.apply(blobArrayBuffer, blob, []) : blob.arrayBuffer()));
183
+ }
180
184
  function isUint8Array(value) {
181
185
  if (!ArrayBuffer.isView(value) || !typedArrayTag) return false;
182
186
  try {
@@ -213,8 +217,38 @@ function serializationError(message, details, cause) {
213
217
  details
214
218
  });
215
219
  }
216
- async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
217
- const state = { nextId: 0 };
220
+ const DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS = {
221
+ maxDepth: 32,
222
+ maxSidecars: 64,
223
+ maxSidecarBytes: 67108864
224
+ };
225
+ const DEFAULT_SANDBOX_TASK_TRANSFER_BYTES = 4194304;
226
+ function transferLimitError(label, limit, value, maximum) {
227
+ return sandboxTaskError(`Sandbox ${label} exceeds its ${limit} limit (${value} > ${maximum}).`, {
228
+ code: "SANDBOX_TASK_TRANSFER_LIMIT",
229
+ details: {
230
+ label,
231
+ limit,
232
+ value,
233
+ maximum
234
+ }
235
+ });
236
+ }
237
+ function isSandboxTaskTransferLimitError(error) {
238
+ return isSandboxTaskError(error) && error.code === "SANDBOX_TASK_TRANSFER_LIMIT";
239
+ }
240
+ /** Rejects a JSON envelope whose UTF-8 size is above `maximum` bytes. */
241
+ function assertSandboxTaskTransferBytes(json, label, limit, maximum) {
242
+ const bytes = new TextEncoder().encode(json).byteLength;
243
+ if (bytes > maximum) throw transferLimitError(label, limit, bytes, maximum);
244
+ }
245
+ /** Encodes a value and holds its binary sidecars in memory. `writeSidecars()` writes them to the Sandbox. */
246
+ async function encodeSandboxTaskValueStaged(sandbox, value, assetsDir, label, signal, limits = DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS, rootDepth = 0) {
247
+ const state = {
248
+ nextId: 0,
249
+ sidecarBytes: 0,
250
+ pendingWrites: []
251
+ };
218
252
  const throwIfAborted = () => signal?.throwIfAborted();
219
253
  const abortable = async (operation) => {
220
254
  try {
@@ -224,38 +258,51 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
224
258
  throw error;
225
259
  }
226
260
  };
227
- async function encode(entry, ancestors, key = "", applyToJSON = true) {
228
- const blob = typeof Blob !== "undefined" && entry instanceof Blob;
229
- const buffer = typeof Buffer !== "undefined" && Buffer.isBuffer(entry);
230
- if (blob || isUint8Array(entry)) {
231
- throwIfAborted();
232
- const id = state.nextId++;
233
- state.directory ||= abortable(sandbox.files.mkdir(assetsDir, {
234
- recursive: true,
235
- signal
236
- }));
237
- await state.directory;
238
- const bytes = blob ? new Uint8Array(await entry.arrayBuffer()) : entry;
239
- throwIfAborted();
240
- await abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }));
241
- return tagged({
242
- id,
243
- kind: blob ? "blob" : buffer ? "buffer" : "uint8array",
244
- ...blob && entry.type ? { type: entry.type } : {},
245
- tag: "binary"
246
- });
261
+ async function stage(descriptor, byteLength, read) {
262
+ throwIfAborted();
263
+ if (state.nextId + 1 > limits.maxSidecars) throw transferLimitError(label, "maxSidecars", state.nextId + 1, limits.maxSidecars);
264
+ if (state.sidecarBytes + byteLength > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", state.sidecarBytes + byteLength, limits.maxSidecarBytes);
265
+ const bytes = await read();
266
+ throwIfAborted();
267
+ const sidecarBytes = state.sidecarBytes + bytes.byteLength;
268
+ if (sidecarBytes > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", sidecarBytes, limits.maxSidecarBytes);
269
+ state.sidecarBytes = sidecarBytes;
270
+ const id = state.nextId++;
271
+ state.pendingWrites.push({
272
+ id,
273
+ bytes
274
+ });
275
+ return tagged({
276
+ id,
277
+ ...descriptor,
278
+ tag: "binary"
279
+ });
280
+ }
281
+ async function encode(entry, ancestors, key = "", applyToJSON = true, depth = 0) {
282
+ if (typeof Blob !== "undefined" && entry instanceof Blob) {
283
+ const prototype = Object.getPrototypeOf(entry);
284
+ if (prototype !== Blob.prototype && (typeof File === "undefined" || prototype !== File.prototype)) throw serializationError(`Sandbox ${label} Blob subclasses are not supported.`, { label });
285
+ if (Object.hasOwn(entry, "arrayBuffer")) throw serializationError(`Sandbox ${label} Blob arrayBuffer overrides are not supported.`, { label });
286
+ return await stage({
287
+ kind: "blob",
288
+ ...entry.type ? { type: entry.type } : {}
289
+ }, readBlobSize(entry), () => readBlobBytes(entry));
247
290
  }
291
+ if (isUint8Array(entry)) return await stage({ kind: typeof Buffer !== "undefined" && Buffer.isBuffer(entry) ? "buffer" : "uint8array" }, entry.byteLength, () => entry);
248
292
  if (isObjectRecord(entry) && applyToJSON) try {
249
293
  const toJSON = entry.toJSON;
250
- if (typeof toJSON === "function") return await encode(Reflect.apply(toJSON, entry, [key]), ancestors, key, false);
294
+ if (typeof toJSON === "function") return await encode(Reflect.apply(toJSON, entry, [key]), ancestors, key, false, depth);
251
295
  } catch (error) {
252
296
  if (isSandboxTaskError(error)) throw error;
253
297
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
254
298
  }
255
299
  if (Array.isArray(entry)) {
300
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
256
301
  if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
257
302
  const nextAncestors = new Set(ancestors).add(entry);
258
- return await Promise.all(entry.map((item, index) => encode(item, nextAncestors, String(index))));
303
+ const items = [];
304
+ for (const [index, item] of entry.entries()) items.push(await encode(item, nextAncestors, String(index), true, depth + 1));
305
+ return items;
259
306
  }
260
307
  if (!isObjectRecord(entry)) return entry;
261
308
  let boxed;
@@ -264,7 +311,8 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
264
311
  } catch (error) {
265
312
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
266
313
  }
267
- if (boxed) return await encode(boxed.value, ancestors, key, false);
314
+ if (boxed) return await encode(boxed.value, ancestors, key, false, depth);
315
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
268
316
  if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
269
317
  const nextAncestors = new Set(ancestors).add(entry);
270
318
  let sourceEntries;
@@ -273,38 +321,83 @@ async function encodeSandboxTaskValue(sandbox, value, assetsDir, label, signal)
273
321
  } catch (error) {
274
322
  throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
275
323
  }
276
- const entries = await Promise.all(sourceEntries.map(async ([entryKey, item]) => [entryKey, await encode(item, nextAncestors, entryKey)]));
324
+ const entries = [];
325
+ for (const [entryKey, item] of sourceEntries) entries.push([entryKey, await encode(item, nextAncestors, entryKey, true, depth + 1)]);
277
326
  return hasMarker(entry) ? tagged({
278
327
  entries,
279
328
  tag: "object"
280
329
  }) : Object.fromEntries(entries);
281
330
  }
282
- return await encode(value, /* @__PURE__ */ new Set());
283
- }
284
- async function decodeSandboxTaskValue(sandbox, value, assetsDir, label, signal) {
285
- if (Array.isArray(value)) return await Promise.all(value.map((entry) => decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)));
286
- if (!isPlainObject(value)) return value;
287
- if (!hasMarker(value)) return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
288
- const descriptor = value[SANDBOX_VALUE_MARKER];
289
- if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
290
- if (descriptor.tag === "response") {
291
- if (!isSerializedResponse(descriptor.value)) throw serializationError(`Sandbox ${label} contains an invalid response descriptor.`, { label });
292
- return deserializeResponse(descriptor.value);
293
- }
294
- if (descriptor.tag === "object") {
295
- 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 });
296
- return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [key, await decodeSandboxTaskValue(sandbox, entry, assetsDir, label, signal)])));
331
+ return {
332
+ value: await encode(value, /* @__PURE__ */ new Set(), "", true, rootDepth),
333
+ async writeSidecars() {
334
+ if (!state.pendingWrites.length) return;
335
+ await abortable(sandbox.files.mkdir(assetsDir, {
336
+ recursive: true,
337
+ signal
338
+ }));
339
+ await Promise.all(state.pendingWrites.map(({ id, bytes }) => abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }))));
340
+ }
341
+ };
342
+ }
343
+ async function decodeSandboxTaskValue(sandbox, value, assetsDir, label, signal, limits = DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS) {
344
+ const state = {
345
+ sidecars: 0,
346
+ sidecarBytes: 0
347
+ };
348
+ const readSidecar = async (path) => {
349
+ try {
350
+ return await sandbox.files.read(path, { signal });
351
+ } catch (error) {
352
+ signal?.throwIfAborted();
353
+ throw error;
354
+ }
355
+ };
356
+ async function decode(entry, depth) {
357
+ const assertContainerDepth = () => {
358
+ if (depth >= limits.maxDepth) throw transferLimitError(label, "maxDepth", depth + 1, limits.maxDepth);
359
+ };
360
+ if (Array.isArray(entry)) {
361
+ assertContainerDepth();
362
+ const items = [];
363
+ for (const item of entry) items.push(await decode(item, depth + 1));
364
+ return items;
365
+ }
366
+ if (!isPlainObject(entry)) return entry;
367
+ if (!hasMarker(entry)) {
368
+ assertContainerDepth();
369
+ const entries = [];
370
+ for (const [key, item] of Object.entries(entry)) entries.push([key, await decode(item, depth + 1)]);
371
+ return Object.fromEntries(entries);
372
+ }
373
+ const descriptor = entry[SANDBOX_VALUE_MARKER];
374
+ if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
375
+ if (descriptor.tag === "response") {
376
+ if (!isSerializedResponse(descriptor.value)) throw serializationError(`Sandbox ${label} contains an invalid response descriptor.`, { label });
377
+ return deserializeResponse(descriptor.value);
378
+ }
379
+ if (descriptor.tag === "object") {
380
+ assertContainerDepth();
381
+ if (!Array.isArray(descriptor.entries) || !descriptor.entries.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string")) throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
382
+ const entries = [];
383
+ for (const [key, item] of descriptor.entries) entries.push([key, await decode(item, depth + 1)]);
384
+ return Object.fromEntries(entries);
385
+ }
386
+ 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 });
387
+ if (state.sidecars + 1 > limits.maxSidecars) throw transferLimitError(label, "maxSidecars", state.sidecars + 1, limits.maxSidecars);
388
+ const bytes = await readSidecar(`${assetsDir}/${descriptor.id}`);
389
+ if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
390
+ id: descriptor.id,
391
+ label
392
+ });
393
+ if (state.sidecarBytes + bytes.byteLength > limits.maxSidecarBytes) throw transferLimitError(label, "maxSidecarBytes", state.sidecarBytes + bytes.byteLength, limits.maxSidecarBytes);
394
+ state.sidecars++;
395
+ state.sidecarBytes += bytes.byteLength;
396
+ return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
297
397
  }
298
- 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 });
299
- const bytes = await sandbox.files.read(`${assetsDir}/${descriptor.id}`, { signal });
300
- if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
301
- id: descriptor.id,
302
- label
303
- });
304
- return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
398
+ return await decode(value, 0);
305
399
  }
306
- //#endregion
307
- //#region src/task/runtime/error-normalization.ts
400
+ // src/task/runtime/error-normalization.ts
308
401
  function readSandboxTaskErrorMetadata(error) {
309
402
  if (!error || typeof error !== "object") return void 0;
310
403
  const metadata = error;
@@ -362,10 +455,14 @@ function readErrorMessage(error) {
362
455
  function sandboxTaskCode(code) {
363
456
  return code?.startsWith("SANDBOX_TASK_") ? code : "SANDBOX_TASK_RUNTIME_ERROR";
364
457
  }
365
- //#endregion
366
- //#region src/task/runtime/entry-script.injected.ts
458
+ // src/task/runtime/entry-script.injected.ts
367
459
  const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
368
- function createEntrySource(definitionPath, execution = "definition", env) {
460
+ const EXEC_DIAGNOSTIC_PREFIX = "{\"ok\":false,\"error\":";
461
+ const MAX_EXEC_DIAGNOSTIC_BYTES = 131072;
462
+ function createEntrySource(definitionPath, execution = "definition", env, transferLimits = {
463
+ ...DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS,
464
+ maxOutputBytes: DEFAULT_SANDBOX_TASK_TRANSFER_BYTES
465
+ }) {
369
466
  const invocation = execution === "module" ? [
370
467
  ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
371
468
  ` const exported = await mod.default`,
@@ -384,6 +481,8 @@ function createEntrySource(definitionPath, execution = "definition", env) {
384
481
  `import { Buffer } from 'node:buffer'`,
385
482
  `import { pathToFileURL } from 'node:url'`,
386
483
  `const serializationErrors = new WeakSet()`,
484
+ `const transferLimitErrors = new WeakSet()`,
485
+ `const transferLimits = ${JSON.stringify(transferLimits)}`,
387
486
  ``,
388
487
  `function serializationError(message, cause) {`,
389
488
  ` const error = new TypeError(message, { cause })`,
@@ -391,10 +490,16 @@ function createEntrySource(definitionPath, execution = "definition", env) {
391
490
  ` return error`,
392
491
  `}`,
393
492
  ``,
493
+ `function transferLimitError(limit, value) {`,
494
+ ` const error = new Error('Sandbox result exceeds its ' + limit + ' limit (' + value + ' > ' + transferLimits[limit] + ').')`,
495
+ ` transferLimitErrors.add(error)`,
496
+ ` return error`,
497
+ `}`,
498
+ ``,
394
499
  `function normalizeError(error) {`,
395
500
  ` if (error instanceof Error) {`,
396
501
  ` return {`,
397
- ` code: serializationErrors.has(error) ? 'SANDBOX_TASK_SERIALIZATION_ERROR' : undefined,`,
502
+ ` code: serializationErrors.has(error) ? 'SANDBOX_TASK_SERIALIZATION_ERROR' : transferLimitErrors.has(error) ? 'SANDBOX_TASK_TRANSFER_LIMIT' : undefined,`,
398
503
  ` name: error.name,`,
399
504
  ` message: error.message,`,
400
505
  ` stack: error.stack,`,
@@ -408,8 +513,21 @@ function createEntrySource(definitionPath, execution = "definition", env) {
408
513
  ` }`,
409
514
  `}`,
410
515
  ``,
516
+ `function serializeFailure(error) {`,
517
+ ` const diagnostic = normalizeError(error)`,
518
+ ` const maximum = ${MAX_EXEC_DIAGNOSTIC_BYTES}`,
519
+ ` const envelope = value => ${JSON.stringify(EXEC_DIAGNOSTIC_PREFIX)} + JSON.stringify(value) + '}'`,
520
+ ` const output = envelope(Object.fromEntries(Object.entries(diagnostic).map(([key, value]) => [key, typeof value === 'string' ? value.slice(0, maximum) : value])))`,
521
+ ` if (Buffer.byteLength(output) <= maximum) return output`,
522
+ ` const fallback = { code: diagnostic.code, message: '' }`,
523
+ ` const message = String(diagnostic.message).slice(0, maximum)`,
524
+ ` const withMessage = envelope({ ...fallback, message })`,
525
+ ` if (Buffer.byteLength(withMessage) <= maximum) return withMessage`,
526
+ ` const messageBudget = maximum - Buffer.byteLength(envelope(fallback))`,
527
+ ` return envelope({ ...fallback, message: message.slice(0, Math.floor(messageBudget / 6)) })`,
528
+ `}`,
529
+ ``,
411
530
  `const valueMarker = ${JSON.stringify("vitehub:sandbox-task:value")}`,
412
- `const nativeResponseClone = typeof Response !== 'undefined' ? Response.prototype.clone : undefined`,
413
531
  `const nativeResponseBody = typeof Response !== 'undefined' ? Object.getOwnPropertyDescriptor(Response.prototype, 'body')?.get : undefined`,
414
532
  ``,
415
533
  `function isPlainObject(value) {`,
@@ -423,6 +541,8 @@ function createEntrySource(definitionPath, execution = "definition", env) {
423
541
  `}`,
424
542
  ``,
425
543
  `const typedArrayTagGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get`,
544
+ `const blobSizeGetter = typeof Blob !== 'undefined' ? Object.getOwnPropertyDescriptor(Blob.prototype, 'size')?.get : undefined`,
545
+ `const blobArrayBuffer = typeof Blob !== 'undefined' ? Blob.prototype.arrayBuffer : undefined`,
426
546
  ``,
427
547
  `function isUint8Array(value) {`,
428
548
  ` return ArrayBuffer.isView(value) && typedArrayTagGetter?.call(value) === 'Uint8Array'`,
@@ -447,20 +567,17 @@ function createEntrySource(definitionPath, execution = "definition", env) {
447
567
  `function isResponse(value) {`,
448
568
  ` if (!value || typeof value !== 'object') return false`,
449
569
  ` try {`,
450
- ` let clone = nativeResponseClone`,
451
- ` let cloneSucceeded = false`,
452
- ` let cloneResult`,
453
570
  ` let bodySucceeded = false`,
454
- ` if (typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
455
- ` if (!cloneSucceeded && typeof nativeResponseBody === 'function') { try { nativeResponseBody.call(value); bodySucceeded = true } catch {} }`,
456
- ` if (cloneSucceeded || bodySucceeded) {`,
571
+ ` if (typeof nativeResponseBody === 'function') { try { nativeResponseBody.call(value); bodySucceeded = true } catch {} }`,
572
+ ` if (bodySucceeded) {`,
457
573
  ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
458
574
  ` && typeof value.statusText === 'string'`,
459
575
  ` && typeof value.arrayBuffer === 'function'`,
460
576
  ` && value.headers && typeof value.headers.get === 'function'`,
461
577
  ` && typeof value.headers[Symbol.iterator] === 'function'`,
462
578
  ` }`,
463
- ` clone = undefined`,
579
+ ` let clone`,
580
+ ` let cloneResult`,
464
581
  ` let foreignCloneDescriptor`,
465
582
  ` let foreignBodyDescriptor`,
466
583
  ` let foreignConstructorDescriptor`,
@@ -491,7 +608,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
491
608
  ` }`,
492
609
  ` prototype = Object.getPrototypeOf(prototype)`,
493
610
  ` }`,
494
- ` if (!cloneSucceeded && typeof clone === 'function') { try { cloneResult = clone.call(value); cloneSucceeded = true } catch {} }`,
611
+ ` if (typeof clone === 'function') { try { cloneResult = clone.call(value) } catch {} }`,
495
612
  ` // Consumed or locked foreign Responses reject clone(), but their branded body getter still succeeds.`,
496
613
  ` if (!bodySucceeded || typeof clone !== 'function') return false`,
497
614
  ` let cloneResultBodySucceeded = false`,
@@ -529,6 +646,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
529
646
  ` 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'`,
530
647
  ` if (Object.keys(value).length > 0) return false`,
531
648
  ` if (hasEnumerableProperties(value) && !undiciInternals) return false`,
649
+ ` if (cloneResultBodySucceeded && cloneResult.body) void cloneResult.body.cancel().catch(() => {})`,
532
650
  ` return Number.isInteger(value.status) && value.status >= 0 && value.status <= 599`,
533
651
  ` && typeof value.statusText === 'string'`,
534
652
  ` && typeof value.arrayBuffer === 'function'`,
@@ -574,25 +692,70 @@ function createEntrySource(definitionPath, execution = "definition", env) {
574
692
  ` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
575
693
  `}`,
576
694
  ``,
577
- `async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
695
+ `async function readResponseBody(response, state, descriptorBytes) {`,
696
+ ` const baseBytes = state.responseBytes + descriptorBytes`,
697
+ ` const assertBytes = bodyBytes => {`,
698
+ ` const outputBytes = baseBytes + 4 * Math.ceil(bodyBytes / 3)`,
699
+ ` if (outputBytes > transferLimits.maxOutputBytes) throw transferLimitError('maxOutputBytes', outputBytes)`,
700
+ ` return outputBytes`,
701
+ ` }`,
702
+ ` if (!response.body) {`,
703
+ ` state.responseBytes = assertBytes(0)`,
704
+ ` return ''`,
705
+ ` }`,
706
+ ` if (response.bodyUsed) throw new TypeError('Response body has already been consumed.')`,
707
+ ` const reader = response.body.getReader()`,
708
+ ` const chunks = []`,
709
+ ` let bytes = 0`,
710
+ ` try {`,
711
+ ` assertBytes(0)`,
712
+ ` for (;;) {`,
713
+ ` const { done, value } = await reader.read()`,
714
+ ` if (done) break`,
715
+ ` if (!(value instanceof Uint8Array) && !isUint8Array(value)) throw new TypeError('Response body must contain bytes.')`,
716
+ ` bytes += value.byteLength`,
717
+ ` assertBytes(bytes)`,
718
+ ` if (value.byteLength) chunks.push(value)`,
719
+ ` }`,
720
+ ` state.responseBytes = assertBytes(bytes)`,
721
+ ` return Buffer.concat(chunks, bytes).toString('base64')`,
722
+ ` }`,
723
+ ` catch (error) {`,
724
+ ` void reader.cancel().catch(() => {})`,
725
+ ` throw error`,
726
+ ` }`,
727
+ ` finally { reader.releaseLock() }`,
728
+ `}`,
729
+ ``,
730
+ `async function extractValue(value, assetsDir, state, ancestors = new Set(), key = '', applyToJSON = true, depth = 0) {`,
578
731
  ` if (isResponse(value)) {`,
579
- ` return { [valueMarker]: { tag: 'response', value: {`,
580
- ` body: { isNull: value.body === null, data: Buffer.from(await value.arrayBuffer()).toString('base64'), encoding: 'base64', mediaType: value.headers.get('content-type') || 'application/octet-stream' },`,
732
+ ` const response = {`,
733
+ ` body: { isNull: value.body === null, data: '', encoding: 'base64', mediaType: value.headers.get('content-type') || 'application/octet-stream' },`,
581
734
  ` headers: Array.from(value.headers),`,
582
735
  ` status: value.status,`,
583
736
  ` statusText: value.statusText,`,
584
737
  ` ...(value.type === 'opaqueredirect' ? { url: value.url } : {}),`,
585
738
  ` ...(['error', 'opaque', 'opaqueredirect'].includes(value.type) ? { type: value.type } : {}),`,
586
- ` } } }`,
739
+ ` }`,
740
+ ` const descriptor = { [valueMarker]: { tag: 'response', value: response } }`,
741
+ ` response.body.data = await readResponseBody(value, state, Buffer.byteLength(JSON.stringify(descriptor)))`,
742
+ ` return descriptor`,
587
743
  ` }`,
588
744
  ` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
745
+ ` if (blob && Object.getPrototypeOf(value) !== Blob.prototype && (typeof File === 'undefined' || Object.getPrototypeOf(value) !== File.prototype))`,
746
+ ` throw serializationError('Sandbox result must be JSON-serializable; Blob subclasses are not supported.')`,
747
+ ` if (blob && Object.hasOwn(value, 'arrayBuffer'))`,
748
+ ` throw serializationError('Sandbox result must be JSON-serializable; Blob arrayBuffer overrides are not supported.')`,
589
749
  ` const buffer = Buffer.isBuffer(value)`,
590
750
  ` if (blob || isUint8Array(value)) {`,
751
+ ` if (state.nextId + 1 > transferLimits.maxSidecars) throw transferLimitError('maxSidecars', state.nextId + 1)`,
752
+ ` const byteLength = blob ? Reflect.apply(blobSizeGetter, value, []) : value.byteLength`,
753
+ ` if (state.sidecarBytes + byteLength > transferLimits.maxSidecarBytes) throw transferLimitError('maxSidecarBytes', state.sidecarBytes + byteLength)`,
754
+ ` const bytes = blob ? new Uint8Array(await Reflect.apply(blobArrayBuffer, value, [])) : value`,
755
+ ` if (state.sidecarBytes + bytes.byteLength > transferLimits.maxSidecarBytes) throw transferLimitError('maxSidecarBytes', state.sidecarBytes + bytes.byteLength)`,
756
+ ` state.sidecarBytes += bytes.byteLength`,
591
757
  ` const id = state.nextId++`,
592
- ` state.directory ||= mkdir(assetsDir, { recursive: true })`,
593
- ` await state.directory`,
594
- ` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
595
- ` await writeFile(assetsDir + '/' + id, bytes)`,
758
+ ` state.pendingWrites.push({ id, bytes })`,
596
759
  ` return { [valueMarker]: {`,
597
760
  ` id,`,
598
761
  ` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
@@ -602,33 +765,40 @@ function createEntrySource(definitionPath, execution = "definition", env) {
602
765
  ` }`,
603
766
  ` if (value && typeof value === 'object' && applyToJSON) {`,
604
767
  ` const toJSON = value.toJSON`,
605
- ` if (typeof toJSON === 'function')`,
606
- ` return await extractValue(Reflect.apply(toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
768
+ ` if (typeof toJSON === 'function') {`,
769
+ ` const replacement = Reflect.apply(toJSON, value, [key])`,
770
+ ` return await extractValue(replacement, assetsDir, state, ancestors, key, false, depth)`,
771
+ ` }`,
607
772
  ` }`,
608
773
  ` if (Array.isArray(value)) {`,
774
+ ` if (depth >= transferLimits.maxDepth) throw transferLimitError('maxDepth', depth + 1)`,
609
775
  ` if (ancestors.has(value))`,
610
776
  ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
611
777
  ` const nextAncestors = new Set(ancestors).add(value)`,
612
- ` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
778
+ ` const items = []`,
779
+ ` for (const [index, entry] of value.entries())`,
780
+ ` items.push(await extractValue(entry, assetsDir, state, nextAncestors, String(index), true, depth + 1))`,
781
+ ` return items`,
613
782
  ` }`,
614
783
  ` if (!value || typeof value !== 'object') return value`,
615
784
  ` const boxed = unboxJsonPrimitive(value)`,
616
- ` if (boxed) return await extractValue(boxed.value, assetsDir, state, ancestors, key, false)`,
785
+ ` if (boxed) return await extractValue(boxed.value, assetsDir, state, ancestors, key, false, depth)`,
786
+ ` if (depth >= transferLimits.maxDepth) throw transferLimitError('maxDepth', depth + 1)`,
617
787
  ` if (ancestors.has(value))`,
618
788
  ` throw serializationError('Sandbox result must be JSON-serializable; cyclic value.')`,
619
789
  ` const nextAncestors = new Set(ancestors).add(value)`,
620
790
  ` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
621
- ` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
622
- ` entryKey,`,
623
- ` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
624
- ` ]))`,
791
+ ` const entries = []`,
792
+ ` for (const [entryKey, entry] of sourceEntries)`,
793
+ ` entries.push([entryKey, await extractValue(entry, assetsDir, state, nextAncestors, entryKey, true, depth + 1)])`,
625
794
  ` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
626
795
  `}`,
627
796
  ``,
628
797
  `async function serializeSuccess(result, assetsDir) {`,
629
798
  ` try {`,
630
- ` const encoded = await extractValue(result, assetsDir)`,
631
- ` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
799
+ ` const state = { nextId: 0, sidecarBytes: 0, pendingWrites: [], responseBytes: '{"ok":true,"result":}'.length }`,
800
+ ` const encoded = await extractValue(result, assetsDir, state)`,
801
+ ` const output = JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
632
802
  ` const type = typeof value`,
633
803
  ` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
634
804
  ` throw serializationError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
@@ -636,9 +806,16 @@ function createEntrySource(definitionPath, execution = "definition", env) {
636
806
  ` throw serializationError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
637
807
  ` return value`,
638
808
  ` })`,
809
+ ` const outputBytes = Buffer.byteLength(output, 'utf8')`,
810
+ ` if (outputBytes > transferLimits.maxOutputBytes) throw transferLimitError('maxOutputBytes', outputBytes)`,
811
+ ` if (state.pendingWrites.length) {`,
812
+ ` await mkdir(assetsDir, { recursive: true })`,
813
+ ` await Promise.all(state.pendingWrites.map(({ id, bytes }) => writeFile(assetsDir + '/' + id, bytes)))`,
814
+ ` }`,
815
+ ` return output`,
639
816
  ` }`,
640
817
  ` catch (error) {`,
641
- ` if (serializationErrors.has(error))`,
818
+ ` if (serializationErrors.has(error) || transferLimitErrors.has(error))`,
642
819
  ` throw error`,
643
820
  ` throw serializationError('Sandbox result must be JSON-serializable.', error)`,
644
821
  ` }`,
@@ -657,7 +834,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
657
834
  ` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
658
835
  ` }`,
659
836
  ` catch (error) {`,
660
- ` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
837
+ ` const output = serializeFailure(error)`,
661
838
  ` await writeFile(outputPath, output)`,
662
839
  ` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
663
840
  ` process.exitCode = 1`,
@@ -668,8 +845,7 @@ function createEntrySource(definitionPath, execution = "definition", env) {
668
845
  ``
669
846
  ].join("\n");
670
847
  }
671
- //#endregion
672
- //#region src/task/runtime/execution-files.ts
848
+ // src/task/runtime/execution-files.ts
673
849
  const DEFAULT_DEFINITION_ENTRY = "definition.js";
674
850
  function normalizeSandboxTaskDefinitionBundle(source) {
675
851
  if (typeof source === "string") return {
@@ -735,8 +911,7 @@ async function writeSandboxTaskDefinitionBundle(sandbox, baseDir, bundle, signal
735
911
  else await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`]);
736
912
  }));
737
913
  }
738
- //#endregion
739
- //#region src/task/runtime/definition-preparation.ts
914
+ // src/task/runtime/definition-preparation.ts
740
915
  const projectPreparations = /* @__PURE__ */ new Map();
741
916
  async function prepareSandboxTaskDefinition(sandbox, bundle, baseDir, options) {
742
917
  const project = bundle.project;
@@ -834,14 +1009,20 @@ async function prepareSandboxTaskProjectAtomically(sandbox, bundle, projectDir,
834
1009
  ]).catch(() => {});
835
1010
  }
836
1011
  }
837
- //#endregion
838
- //#region src/task/runtime/output-recovery.ts
1012
+ // src/task/runtime/output-recovery.ts
839
1013
  const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
840
1014
  const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
841
1015
  const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
842
1016
  const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
843
1017
  const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
844
1018
  const HANDLER_DIAGNOSTIC_LENGTH = 16384;
1019
+ function assertOutputBytes(output, maxOutputBytes) {
1020
+ if (output.startsWith("{\"ok\":false,\"error\":") || "{\"ok\":false,\"error\":".startsWith(output)) {
1021
+ assertSandboxTaskTransferBytes(output, "diagnostic", "maxDiagnosticBytes", MAX_EXEC_DIAGNOSTIC_BYTES);
1022
+ if (tryParseSandboxTaskOutput(output)?.ok !== true) return;
1023
+ }
1024
+ if (maxOutputBytes !== void 0) assertSandboxTaskTransferBytes(output, "result", "maxOutputBytes", maxOutputBytes);
1025
+ }
845
1026
  function getErrorMessage(error) {
846
1027
  if (error instanceof Error) return error.message;
847
1028
  if (error && typeof error === "object") {
@@ -952,7 +1133,7 @@ function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, ex
952
1133
  ...getExecutionDiagnostics(execution)
953
1134
  });
954
1135
  }
955
- async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1136
+ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
956
1137
  const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
957
1138
  const deadline = Date.now() + recoveryTimeout;
958
1139
  let lastError = error;
@@ -961,10 +1142,12 @@ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution,
961
1142
  signal?.throwIfAborted();
962
1143
  try {
963
1144
  const output = await sandbox.readFile(outputPath, { signal });
1145
+ assertOutputBytes(output, maxOutputBytes);
964
1146
  lastOutput = output;
965
1147
  if (isCompleteSandboxTaskOutput(output)) return output;
966
1148
  } catch (readError) {
967
1149
  if (signal?.aborted) throw signal.reason;
1150
+ if (isSandboxTaskTransferLimitError(readError)) throw readError;
968
1151
  lastError = readError;
969
1152
  }
970
1153
  const remaining = deadline - Date.now();
@@ -976,35 +1159,42 @@ async function waitForExecOutput(sandbox, outputPath, error, timeout, execution,
976
1159
  outputPreview: lastOutput.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH) || void 0
977
1160
  });
978
1161
  }
979
- async function recoverExecOutput(sandbox, outputPath, error, timeout, execution, signal) {
1162
+ async function recoverExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
980
1163
  if (sandbox.provider !== "cloudflare" || !mayHaveRunCloudflareExec(error)) return null;
981
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1164
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
982
1165
  }
983
- async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal) {
1166
+ async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
984
1167
  const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
985
1168
  signal?.throwIfAborted();
986
1169
  if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
987
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, signal);
1170
+ return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
988
1171
  }
989
- async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution, signal) {
1172
+ async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal) {
990
1173
  const executionOutput = extractSandboxTaskOutputFromExecution(execution) || extractSandboxTaskOutputFromExecution(error);
991
- if (executionOutput) return executionOutput;
1174
+ if (executionOutput) {
1175
+ assertOutputBytes(executionOutput, maxOutputBytes);
1176
+ return executionOutput;
1177
+ }
992
1178
  try {
993
1179
  const output = await sandbox.readFile(outputPath, { signal });
1180
+ assertOutputBytes(output, maxOutputBytes);
994
1181
  if (isCompleteSandboxTaskOutput(output)) return output;
995
- } catch {
1182
+ } catch (readError) {
1183
+ if (isSandboxTaskTransferLimitError(readError)) throw readError;
996
1184
  signal?.throwIfAborted();
997
- return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1185
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
998
1186
  }
999
- return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, signal);
1187
+ return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution, maxOutputBytes, signal);
1000
1188
  }
1001
- //#endregion
1002
- //#region src/task/runtime/execute.ts
1189
+ // src/task/runtime/execute.ts
1003
1190
  const SANDBOX_CLEANUP_GRACE_MS = 1e3;
1004
- function toJson(value, label) {
1191
+ function toJson(value, label, maxInputBytes) {
1005
1192
  try {
1006
- return JSON.stringify(value);
1193
+ const json = JSON.stringify(value);
1194
+ assertSandboxTaskTransferBytes(json, label, "maxInputBytes", maxInputBytes);
1195
+ return json;
1007
1196
  } catch (error) {
1197
+ if (isSandboxTaskError(error)) throw error;
1008
1198
  throw sandboxTaskError(`Sandbox ${label} must be JSON-serializable.`, {
1009
1199
  code: "SANDBOX_TASK_SERIALIZATION_ERROR",
1010
1200
  details: { label },
@@ -1015,29 +1205,40 @@ function toJson(value, label) {
1015
1205
  async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, lifecycle, deadline) {
1016
1206
  const bundle = normalizeSandboxTaskDefinitionBundle(source);
1017
1207
  const files = createExecutionFiles(definitionName, sandbox.tempDir);
1208
+ const transfer = definitionOptions?.transfer;
1209
+ const transferLimits = {
1210
+ maxDepth: transfer?.maxDepth ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxDepth,
1211
+ maxSidecars: transfer?.maxSidecars ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxSidecars,
1212
+ maxSidecarBytes: transfer?.maxSidecarBytes ?? DEFAULT_SANDBOX_TASK_TRANSFER_LIMITS.maxSidecarBytes
1213
+ };
1214
+ const maxInputBytes = transfer?.maxInputBytes ?? 4194304;
1215
+ const maxOutputBytes = transfer?.maxOutputBytes ?? 4194304;
1018
1216
  let failure;
1019
1217
  const throwIfAborted = () => {
1020
1218
  if (signal?.aborted) throw signal.reason ?? new DOMException("The Sandbox invocation was aborted.", "AbortError");
1021
1219
  };
1220
+ const encodeInput = async () => {
1221
+ const encoded = await encodeSandboxTaskValueStaged(sandbox, {
1222
+ payload,
1223
+ context
1224
+ }, files.inputAssetsDir, "payload/context", signal, transferLimits, -1);
1225
+ const json = toJson(encoded.value, "payload/context", maxInputBytes);
1226
+ await encoded.writeSidecars();
1227
+ return json;
1228
+ };
1022
1229
  try {
1023
1230
  await sandbox.mkdir(files.baseDir, {
1024
1231
  recursive: true,
1025
1232
  signal
1026
1233
  });
1027
1234
  throwIfAborted();
1028
- let inputJson = bundle.project ? toJson(await encodeSandboxTaskValue(sandbox, {
1029
- payload,
1030
- context
1031
- }, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
1235
+ let inputJson = bundle.project ? await encodeInput() : void 0;
1032
1236
  const prepared = await prepareSandboxTaskDefinition(sandbox, bundle, files.baseDir, {
1033
1237
  onCommandStart: lifecycle?.onCommandStart,
1034
1238
  signal,
1035
1239
  timeout: definitionOptions?.timeout
1036
1240
  });
1037
- inputJson ||= toJson(await encodeSandboxTaskValue(sandbox, {
1038
- payload,
1039
- context
1040
- }, files.inputAssetsDir, "payload/context", signal), "payload/context");
1241
+ inputJson ||= await encodeInput();
1041
1242
  const definitionPath = resolveSandboxTaskModulePath(prepared.directory, bundle.entry);
1042
1243
  const local = sandbox.provider === "local";
1043
1244
  let env = definitionOptions?.env;
@@ -1048,7 +1249,10 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1048
1249
  env = Object.fromEntries(entries.filter(([name]) => !isTrustedHostReservedCommandEnvironmentKey(name)));
1049
1250
  }
1050
1251
  throwIfAborted();
1051
- await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution, entryEnvironment), { signal }), sandbox.writeFile(files.inputPath, inputJson, { signal })]);
1252
+ await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution, entryEnvironment, {
1253
+ ...transferLimits,
1254
+ maxOutputBytes
1255
+ }), { signal }), sandbox.writeFile(files.inputPath, inputJson, { signal })]);
1052
1256
  throwIfAborted();
1053
1257
  const execArgs = local ? [
1054
1258
  files.entryPath,
@@ -1071,13 +1275,13 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1071
1275
  signal,
1072
1276
  timeout: definitionOptions?.timeout
1073
1277
  });
1074
- outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution, signal);
1278
+ outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1075
1279
  } catch (error) {
1076
1280
  throwIfAborted();
1077
1281
  if (readSandboxTaskErrorMetadata(error)?.details?.operation === "createSession") throw error;
1078
- if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1282
+ if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1079
1283
  else {
1080
- const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, signal);
1284
+ const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution, maxOutputBytes, signal);
1081
1285
  if (recoveredOutput == null) throw error;
1082
1286
  outputRaw = recoveredOutput;
1083
1287
  }
@@ -1087,7 +1291,11 @@ async function executeSandboxTaskDefinitionOnce(sandbox, definitionName, definit
1087
1291
  output: outputRaw,
1088
1292
  cause: "Output file was empty or contained incomplete JSON."
1089
1293
  });
1090
- if (output.ok) return await decodeSandboxTaskValue(sandbox, output.result, files.outputAssetsDir, "result", signal);
1294
+ if (output.ok) return await decodeSandboxTaskValue(sandbox, output.result, files.outputAssetsDir, "result", signal, transferLimits);
1295
+ if (output.error?.code === "SANDBOX_TASK_TRANSFER_LIMIT") throw sandboxTaskError(output.error.message || "Sandbox result exceeds its transfer limit.", {
1296
+ code: "SANDBOX_TASK_TRANSFER_LIMIT",
1297
+ provider: sandbox.provider
1298
+ });
1091
1299
  if (output.error?.code === "SANDBOX_TASK_SERIALIZATION_ERROR") throw sandboxTaskError(output.error.message || "Sandbox result must be JSON-serializable.", {
1092
1300
  code: "SANDBOX_TASK_SERIALIZATION_ERROR",
1093
1301
  provider: sandbox.provider,
@@ -1185,8 +1393,7 @@ async function executeSandboxTaskDefinition(sandbox, definitionName, definitionO
1185
1393
  if (externalAbort) externalSignal?.removeEventListener("abort", externalAbort);
1186
1394
  }
1187
1395
  }
1188
- //#endregion
1189
- //#region src/task/runtime/task-sandbox.ts
1396
+ // src/task/runtime/task-sandbox.ts
1190
1397
  function createTaskSandbox(session, provider, closesAfterRun) {
1191
1398
  return {
1192
1399
  executionAuthority: session.executionAuthority,
@@ -1217,8 +1424,7 @@ function createTaskSandbox(session, provider, closesAfterRun) {
1217
1424
  }
1218
1425
  };
1219
1426
  }
1220
- //#endregion
1221
- //#region src/task/runtime/result.ts
1427
+ // src/task/runtime/result.ts
1222
1428
  const sandboxTaskRunErrors = /*#__PURE__*/ defineErrors({
1223
1429
  docs: "https://vitehub.dev/docs/sandbox/diagnostics",
1224
1430
  codes: { SANDBOX_TASK_RUN_FAILED: {
@@ -1250,8 +1456,7 @@ function runFailed(name, error) {
1250
1456
  value: statusFor(error)
1251
1457
  });
1252
1458
  }
1253
- //#endregion
1254
- //#region src/task/runtime/runtime.ts
1459
+ // src/task/runtime/runtime.ts
1255
1460
  const cloudflareRunQueues = /* @__PURE__ */ new Map();
1256
1461
  async function awaitWithAbort(promise, signal) {
1257
1462
  if (!signal) return await promise;
@@ -1413,10 +1618,8 @@ async function runSandboxTaskRuntime(name, payload, options) {
1413
1618
  return [runFailed(name ?? "", toSandboxTaskError(error)), void 0];
1414
1619
  }
1415
1620
  }
1416
- //#endregion
1417
- //#region src/task/runtime/public.ts
1621
+ // src/task/runtime/public.ts
1418
1622
  async function runSandboxTask(name, payload, options) {
1419
1623
  return await runSandboxTaskRuntime(name, payload, options);
1420
1624
  }
1421
- //#endregion
1422
1625
  export { defineSandboxTask, readRequestPayload, readValidatedPayload, resolveSandboxTaskRunner, runSandboxTask, unsupportedHostedSandboxTaskProviderError };