@vercel/sandbox 2.0.0-beta.11 → 2.0.0-beta.13

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 (196) hide show
  1. package/README.md +8 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/api-client/api-client.cjs +456 -0
  4. package/dist/api-client/api-client.cjs.map +1 -0
  5. package/dist/api-client/api-client.d.cts +790 -0
  6. package/dist/api-client/api-client.d.ts +784 -777
  7. package/dist/api-client/api-client.js +445 -471
  8. package/dist/api-client/api-client.js.map +1 -1
  9. package/dist/api-client/api-error.cjs +32 -0
  10. package/dist/api-client/api-error.cjs.map +1 -0
  11. package/dist/api-client/api-error.d.cts +29 -0
  12. package/dist/api-client/api-error.d.ts +21 -18
  13. package/dist/api-client/api-error.js +28 -33
  14. package/dist/api-client/api-error.js.map +1 -1
  15. package/dist/api-client/base-client.cjs +125 -0
  16. package/dist/api-client/base-client.cjs.map +1 -0
  17. package/dist/api-client/base-client.d.cts +38 -0
  18. package/dist/api-client/base-client.d.ts +31 -36
  19. package/dist/api-client/base-client.js +110 -130
  20. package/dist/api-client/base-client.js.map +1 -1
  21. package/dist/api-client/file-writer.cjs +62 -0
  22. package/dist/api-client/file-writer.cjs.map +1 -0
  23. package/dist/api-client/file-writer.d.cts +66 -0
  24. package/dist/api-client/file-writer.d.ts +56 -52
  25. package/dist/api-client/file-writer.js +57 -61
  26. package/dist/api-client/file-writer.js.map +1 -1
  27. package/dist/api-client/index.cjs +2 -0
  28. package/dist/api-client/index.d.ts +2 -2
  29. package/dist/api-client/index.js +4 -21
  30. package/dist/api-client/validators.cjs +182 -0
  31. package/dist/api-client/validators.cjs.map +1 -0
  32. package/dist/api-client/validators.d.cts +1469 -0
  33. package/dist/api-client/validators.d.ts +1282 -3699
  34. package/dist/api-client/validators.js +155 -170
  35. package/dist/api-client/validators.js.map +1 -1
  36. package/dist/api-client/with-retry.cjs +89 -0
  37. package/dist/api-client/with-retry.cjs.map +1 -0
  38. package/dist/api-client/with-retry.d.cts +10 -0
  39. package/dist/api-client/with-retry.d.ts +9 -13
  40. package/dist/api-client/with-retry.js +81 -102
  41. package/dist/api-client/with-retry.js.map +1 -1
  42. package/dist/auth/api.cjs +29 -0
  43. package/dist/auth/api.cjs.map +1 -0
  44. package/dist/auth/api.js +26 -25
  45. package/dist/auth/api.js.map +1 -1
  46. package/dist/auth/error.cjs +13 -0
  47. package/dist/auth/error.cjs.map +1 -0
  48. package/dist/auth/error.js +11 -11
  49. package/dist/auth/error.js.map +1 -1
  50. package/dist/auth/file.cjs +64 -0
  51. package/dist/auth/file.cjs.map +1 -0
  52. package/dist/auth/file.d.cts +26 -0
  53. package/dist/auth/file.d.ts +19 -15
  54. package/dist/auth/file.js +49 -64
  55. package/dist/auth/file.js.map +1 -1
  56. package/dist/auth/index.cjs +12 -0
  57. package/dist/auth/index.d.cts +5 -0
  58. package/dist/auth/index.d.ts +5 -6
  59. package/dist/auth/index.js +6 -27
  60. package/dist/auth/linked-project.cjs +38 -0
  61. package/dist/auth/linked-project.cjs.map +1 -0
  62. package/dist/auth/linked-project.js +30 -64
  63. package/dist/auth/linked-project.js.map +1 -1
  64. package/dist/auth/oauth.cjs +205 -0
  65. package/dist/auth/oauth.cjs.map +1 -0
  66. package/dist/auth/oauth.d.cts +135 -0
  67. package/dist/auth/oauth.d.ts +113 -109
  68. package/dist/auth/oauth.js +185 -252
  69. package/dist/auth/oauth.js.map +1 -1
  70. package/dist/auth/poll-for-token.cjs +82 -0
  71. package/dist/auth/poll-for-token.cjs.map +1 -0
  72. package/dist/auth/poll-for-token.d.cts +28 -0
  73. package/dist/auth/poll-for-token.d.ts +23 -15
  74. package/dist/auth/poll-for-token.js +79 -64
  75. package/dist/auth/poll-for-token.js.map +1 -1
  76. package/dist/auth/project.cjs +80 -0
  77. package/dist/auth/project.cjs.map +1 -0
  78. package/dist/auth/project.d.cts +44 -0
  79. package/dist/auth/project.d.ts +12 -8
  80. package/dist/auth/project.js +70 -72
  81. package/dist/auth/project.js.map +1 -1
  82. package/dist/auth/zod.cjs +22 -0
  83. package/dist/auth/zod.cjs.map +1 -0
  84. package/dist/auth/zod.js +18 -17
  85. package/dist/auth/zod.js.map +1 -1
  86. package/dist/command.cjs +328 -0
  87. package/dist/command.cjs.map +1 -0
  88. package/dist/command.d.cts +289 -0
  89. package/dist/command.d.ts +265 -171
  90. package/dist/command.js +323 -226
  91. package/dist/command.js.map +1 -1
  92. package/dist/constants.d.cts +5 -0
  93. package/dist/constants.d.ts +5 -1
  94. package/dist/index.cjs +13 -0
  95. package/dist/index.d.cts +7 -0
  96. package/dist/index.d.ts +7 -6
  97. package/dist/index.js +7 -17
  98. package/dist/network-policy.d.cts +100 -0
  99. package/dist/network-policy.d.ts +32 -28
  100. package/dist/sandbox.cjs +694 -0
  101. package/dist/sandbox.cjs.map +1 -0
  102. package/dist/sandbox.d.cts +796 -0
  103. package/dist/sandbox.d.ts +783 -711
  104. package/dist/sandbox.js +684 -615
  105. package/dist/sandbox.js.map +1 -1
  106. package/dist/session.cjs +520 -0
  107. package/dist/session.cjs.map +1 -0
  108. package/dist/session.d.cts +406 -0
  109. package/dist/session.d.ts +398 -367
  110. package/dist/session.js +517 -505
  111. package/dist/session.js.map +1 -1
  112. package/dist/snapshot.cjs +116 -0
  113. package/dist/snapshot.cjs.map +1 -0
  114. package/dist/snapshot.d.cts +107 -0
  115. package/dist/snapshot.d.ts +98 -91
  116. package/dist/snapshot.js +114 -115
  117. package/dist/snapshot.js.map +1 -1
  118. package/dist/utils/array.cjs +17 -0
  119. package/dist/utils/array.cjs.map +1 -0
  120. package/dist/utils/array.js +12 -15
  121. package/dist/utils/array.js.map +1 -1
  122. package/dist/utils/consume-readable.cjs +18 -0
  123. package/dist/utils/consume-readable.cjs.map +1 -0
  124. package/dist/utils/consume-readable.js +13 -12
  125. package/dist/utils/consume-readable.js.map +1 -1
  126. package/dist/utils/decode-base64-url.cjs +15 -0
  127. package/dist/utils/decode-base64-url.cjs.map +1 -0
  128. package/dist/utils/decode-base64-url.js +10 -9
  129. package/dist/utils/decode-base64-url.js.map +1 -1
  130. package/dist/utils/dev-credentials.cjs +142 -0
  131. package/dist/utils/dev-credentials.cjs.map +1 -0
  132. package/dist/utils/dev-credentials.js +126 -184
  133. package/dist/utils/dev-credentials.js.map +1 -1
  134. package/dist/utils/get-credentials.cjs +123 -0
  135. package/dist/utils/get-credentials.cjs.map +1 -0
  136. package/dist/utils/get-credentials.d.cts +21 -0
  137. package/dist/utils/get-credentials.d.ts +19 -61
  138. package/dist/utils/get-credentials.js +106 -140
  139. package/dist/utils/get-credentials.js.map +1 -1
  140. package/dist/utils/log.cjs +25 -0
  141. package/dist/utils/log.cjs.map +1 -0
  142. package/dist/utils/log.js +15 -17
  143. package/dist/utils/log.js.map +1 -1
  144. package/dist/utils/network-policy.cjs +65 -0
  145. package/dist/utils/network-policy.cjs.map +1 -0
  146. package/dist/utils/network-policy.js +58 -77
  147. package/dist/utils/network-policy.js.map +1 -1
  148. package/dist/utils/normalizePath.cjs +27 -0
  149. package/dist/utils/normalizePath.cjs.map +1 -0
  150. package/dist/utils/normalizePath.js +21 -28
  151. package/dist/utils/normalizePath.js.map +1 -1
  152. package/dist/utils/resolveSignal.cjs +20 -0
  153. package/dist/utils/resolveSignal.cjs.map +1 -0
  154. package/dist/utils/resolveSignal.d.cts +15 -0
  155. package/dist/utils/resolveSignal.d.ts +12 -10
  156. package/dist/utils/resolveSignal.js +14 -17
  157. package/dist/utils/resolveSignal.js.map +1 -1
  158. package/dist/utils/sandbox-snapshot.cjs +14 -0
  159. package/dist/utils/sandbox-snapshot.cjs.map +1 -0
  160. package/dist/utils/sandbox-snapshot.d.cts +10 -0
  161. package/dist/utils/sandbox-snapshot.d.ts +11 -0
  162. package/dist/utils/sandbox-snapshot.js +14 -0
  163. package/dist/utils/sandbox-snapshot.js.map +1 -0
  164. package/dist/utils/types.cjs +13 -0
  165. package/dist/utils/types.cjs.map +1 -0
  166. package/dist/utils/types.d.cts +11 -0
  167. package/dist/utils/types.d.ts +5 -7
  168. package/dist/utils/types.js +8 -8
  169. package/dist/utils/types.js.map +1 -1
  170. package/dist/version.cjs +7 -0
  171. package/dist/version.cjs.map +1 -0
  172. package/dist/version.js +5 -5
  173. package/dist/version.js.map +1 -1
  174. package/package.json +23 -3
  175. package/dist/api-client/index.js.map +0 -1
  176. package/dist/auth/api.d.ts +0 -6
  177. package/dist/auth/error.d.ts +0 -11
  178. package/dist/auth/index.js.map +0 -1
  179. package/dist/auth/linked-project.d.ts +0 -10
  180. package/dist/auth/zod.d.ts +0 -5
  181. package/dist/constants.js +0 -3
  182. package/dist/constants.js.map +0 -1
  183. package/dist/index.js.map +0 -1
  184. package/dist/network-policy.js +0 -3
  185. package/dist/network-policy.js.map +0 -1
  186. package/dist/utils/array.d.ts +0 -9
  187. package/dist/utils/consume-readable.d.ts +0 -5
  188. package/dist/utils/convert-sandbox.d.ts +0 -6
  189. package/dist/utils/convert-sandbox.js +0 -14
  190. package/dist/utils/convert-sandbox.js.map +0 -1
  191. package/dist/utils/decode-base64-url.d.ts +0 -7
  192. package/dist/utils/dev-credentials.d.ts +0 -37
  193. package/dist/utils/log.d.ts +0 -2
  194. package/dist/utils/network-policy.d.ts +0 -7
  195. package/dist/utils/normalizePath.d.ts +0 -17
  196. package/dist/version.d.ts +0 -1
package/dist/sandbox.js CHANGED
@@ -1,624 +1,693 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Sandbox = void 0;
4
- const api_client_1 = require("./api-client");
5
- const api_error_1 = require("./api-client/api-error");
6
- const get_credentials_1 = require("./utils/get-credentials");
7
- const types_1 = require("./utils/types");
8
- const session_1 = require("./session");
9
- const network_policy_1 = require("./utils/network-policy");
10
- const promises_1 = require("node:timers/promises");
1
+ import { APIError } from "./api-client/api-error.js";
2
+ import { fromAPINetworkPolicy } from "./utils/network-policy.js";
3
+ import { getPrivateParams } from "./utils/types.js";
4
+ import { APIClient } from "./api-client/api-client.js";
5
+ import "./api-client/index.js";
6
+ import { getCredentials } from "./utils/get-credentials.js";
7
+ import { Session } from "./session.js";
8
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
9
+ import { setTimeout } from "node:timers/promises";
10
+
11
+ //#region src/sandbox.ts
11
12
  function isSandboxStoppedError(err) {
12
- return err instanceof api_error_1.APIError && err.response.status === 410;
13
+ return err instanceof APIError && err.response.status === 410;
13
14
  }
14
15
  function isSandboxStoppingError(err) {
15
- return (err instanceof api_error_1.APIError &&
16
- err.response.status === 422 &&
17
- err.json?.error?.code === "sandbox_stopping");
16
+ return err instanceof APIError && err.response.status === 422 && err.json?.error?.code === "sandbox_stopping";
18
17
  }
19
18
  function isSandboxSnapshottingError(err) {
20
- return (err instanceof api_error_1.APIError &&
21
- err.response.status === 422 &&
22
- err.json?.error?.code === "sandbox_snapshotting");
19
+ return err instanceof APIError && err.response.status === 422 && err.json?.error?.code === "sandbox_snapshotting";
23
20
  }
24
21
  /**
25
- * A Sandbox is a persistent, isolated Linux MicroVMs to run commands in.
26
- * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.
27
- * @hideconstructor
28
- */
29
- class Sandbox {
30
- /**
31
- * The name of this sandbox.
32
- */
33
- get name() {
34
- return this.sandbox.name;
35
- }
36
- /**
37
- * Routes from ports to subdomains.
38
- * @hidden
39
- */
40
- get routes() {
41
- return this.session.routes;
42
- }
43
- /**
44
- * Whether the sandbox persists the state.
45
- */
46
- get persistent() {
47
- return this.sandbox.persistent;
48
- }
49
- /**
50
- * The region this sandbox runs in.
51
- */
52
- get region() {
53
- return this.sandbox.region;
54
- }
55
- /**
56
- * Number of virtual CPUs allocated.
57
- */
58
- get vcpus() {
59
- return this.sandbox.vcpus;
60
- }
61
- /**
62
- * Memory allocated in MB.
63
- */
64
- get memory() {
65
- return this.sandbox.memory;
66
- }
67
- /** Runtime identifier (e.g. "node24", "python3.13"). */
68
- get runtime() {
69
- return this.sandbox.runtime;
70
- }
71
- /**
72
- * Cumulative egress bytes across all sessions.
73
- */
74
- get totalEgressBytes() {
75
- return this.sandbox.totalEgressBytes;
76
- }
77
- /**
78
- * Cumulative ingress bytes across all sessions.
79
- */
80
- get totalIngressBytes() {
81
- return this.sandbox.totalIngressBytes;
82
- }
83
- /**
84
- * Cumulative active CPU duration in milliseconds across all sessions.
85
- */
86
- get totalActiveCpuDurationMs() {
87
- return this.sandbox.totalActiveCpuDurationMs;
88
- }
89
- /**
90
- * Cumulative wall-clock duration in milliseconds across all sessions.
91
- */
92
- get totalDurationMs() {
93
- return this.sandbox.totalDurationMs;
94
- }
95
- /**
96
- * When this sandbox was last updated.
97
- */
98
- get updatedAt() {
99
- return new Date(this.sandbox.updatedAt);
100
- }
101
- /**
102
- * When the sandbox status was last updated.
103
- */
104
- get statusUpdatedAt() {
105
- return this.sandbox.statusUpdatedAt
106
- ? new Date(this.sandbox.statusUpdatedAt)
107
- : undefined;
108
- }
109
- /**
110
- * When this sandbox was created.
111
- */
112
- get createdAt() {
113
- return new Date(this.sandbox.createdAt);
114
- }
115
- /**
116
- * Interactive port.
117
- */
118
- get interactivePort() {
119
- return this.session.interactivePort;
120
- }
121
- /**
122
- * The status of the current session.
123
- */
124
- get status() {
125
- return this.session.status;
126
- }
127
- /**
128
- * The default timeout of this sandbox in milliseconds.
129
- */
130
- get timeout() {
131
- return this.sandbox.timeout;
132
- }
133
- /**
134
- * Key-value tags attached to the sandbox.
135
- */
136
- get tags() {
137
- return this.sandbox.tags;
138
- }
139
- /**
140
- * The default network policy of this sandbox.
141
- */
142
- get networkPolicy() {
143
- return this.sandbox.networkPolicy
144
- ? (0, network_policy_1.fromAPINetworkPolicy)(this.sandbox.networkPolicy)
145
- : undefined;
146
- }
147
- /**
148
- * If the session was created from a snapshot, the ID of that snapshot.
149
- */
150
- get sourceSnapshotId() {
151
- return this.session.sourceSnapshotId;
152
- }
153
- /**
154
- * The current snapshot ID of this sandbox, if any.
155
- */
156
- get currentSnapshotId() {
157
- return this.sandbox.currentSnapshotId;
158
- }
159
- /**
160
- * The default snapshot expiration in milliseconds, if set.
161
- */
162
- get snapshotExpiration() {
163
- return this.sandbox.snapshotExpiration;
164
- }
165
- /**
166
- * The amount of CPU used by the session. Only reported once the VM is stopped.
167
- */
168
- get activeCpuUsageMs() {
169
- return this.session.activeCpuUsageMs;
170
- }
171
- /**
172
- * The amount of network data used by the session. Only reported once the VM is stopped.
173
- */
174
- get networkTransfer() {
175
- return this.session.networkTransfer;
176
- }
177
- /**
178
- * Allow to get a list of sandboxes for a team narrowed to the given params.
179
- * It returns both the sandboxes and the pagination metadata to allow getting
180
- * the next page of results.
181
- */
182
- static async list(params) {
183
- const credentials = await (0, get_credentials_1.getCredentials)(params);
184
- const client = new api_client_1.APIClient({
185
- teamId: credentials.teamId,
186
- token: credentials.token,
187
- fetch: params?.fetch,
188
- });
189
- const response = await client.listSandboxes({
190
- ...credentials,
191
- ...params,
192
- });
193
- return response.json;
194
- }
195
- /**
196
- * Create a new sandbox.
197
- *
198
- * @param params - Creation parameters and optional credentials.
199
- * @returns A promise resolving to the created {@link Sandbox}.
200
- * @example
201
- * <caption>Create a sandbox and drop it in the end of the block</caption>
202
- * async function fn() {
203
- * await using const sandbox = await Sandbox.create();
204
- * // Sandbox automatically stopped at the end of the lexical scope
205
- * }
206
- */
207
- static async create(params) {
208
- const credentials = await (0, get_credentials_1.getCredentials)(params);
209
- const client = new api_client_1.APIClient({
210
- teamId: credentials.teamId,
211
- token: credentials.token,
212
- fetch: params?.fetch,
213
- });
214
- const privateParams = (0, types_1.getPrivateParams)(params);
215
- const response = await client.createSandbox({
216
- source: params?.source,
217
- projectId: credentials.projectId,
218
- ports: params?.ports ?? [],
219
- timeout: params?.timeout,
220
- resources: params?.resources,
221
- runtime: params && "runtime" in params ? params?.runtime : undefined,
222
- networkPolicy: params?.networkPolicy,
223
- env: params?.env,
224
- tags: params?.tags,
225
- snapshotExpiration: params?.snapshotExpiration,
226
- signal: params?.signal,
227
- name: params?.name,
228
- persistent: params?.persistent,
229
- ...privateParams,
230
- });
231
- return new DisposableSandbox({
232
- client,
233
- session: response.json.session,
234
- sandbox: response.json.sandbox,
235
- routes: response.json.routes,
236
- projectId: credentials.projectId,
237
- });
238
- }
239
- /**
240
- * Retrieve an existing sandbox and resume its session.
241
- *
242
- * @param params - Get parameters and optional credentials.
243
- * @returns A promise resolving to the {@link Sandbox}.
244
- */
245
- static async get(params) {
246
- const credentials = await (0, get_credentials_1.getCredentials)(params);
247
- const client = new api_client_1.APIClient({
248
- teamId: credentials.teamId,
249
- token: credentials.token,
250
- fetch: params.fetch,
251
- });
252
- const privateParams = (0, types_1.getPrivateParams)(params);
253
- const response = await client.getSandbox({
254
- name: params.name,
255
- projectId: credentials.projectId,
256
- resume: params.resume,
257
- signal: params.signal,
258
- ...privateParams,
259
- });
260
- return new Sandbox({
261
- client,
262
- session: response.json.session,
263
- sandbox: response.json.sandbox,
264
- routes: response.json.routes,
265
- projectId: credentials.projectId,
266
- });
267
- }
268
- constructor({ client, routes, session, sandbox, projectId, }) {
269
- /**
270
- * In-flight resume promise, used to deduplicate concurrent resume calls.
271
- */
272
- this.resumePromise = null;
273
- this.client = client;
274
- this.session = new session_1.Session({ client, routes, session });
275
- this.sandbox = sandbox;
276
- this.projectId = projectId;
277
- }
278
- /**
279
- * Get the current session (the running VM) for this sandbox.
280
- *
281
- * @returns The {@link Session} instance.
282
- */
283
- currentSession() {
284
- return this.session;
285
- }
286
- /**
287
- * Resume this sandbox by creating a new session via `getSandbox`.
288
- */
289
- async resume(signal) {
290
- if (!this.resumePromise) {
291
- this.resumePromise = this.doResume(signal).finally(() => {
292
- this.resumePromise = null;
293
- });
294
- }
295
- return this.resumePromise;
296
- }
297
- async doResume(signal) {
298
- const response = await this.client.getSandbox({
299
- name: this.sandbox.name,
300
- projectId: this.projectId,
301
- resume: true,
302
- signal,
303
- });
304
- this.session = new session_1.Session({
305
- client: this.client,
306
- routes: response.json.routes,
307
- session: response.json.session,
308
- });
309
- }
310
- /**
311
- * Poll until the current session reaches a terminal state, then resume.
312
- */
313
- async waitForStopAndResume(signal) {
314
- const pollingInterval = 500;
315
- let status = this.session.status;
316
- while (status === "stopping" || status === "snapshotting") {
317
- await (0, promises_1.setTimeout)(pollingInterval, undefined, { signal });
318
- const poll = await this.client.getSession({
319
- sessionId: this.session.sessionId,
320
- signal,
321
- });
322
- this.session = new session_1.Session({
323
- client: this.client,
324
- routes: poll.json.routes,
325
- session: poll.json.session,
326
- });
327
- status = poll.json.session.status;
328
- }
329
- await this.resume(signal);
330
- }
331
- /**
332
- * Execute `fn`, and if the session is stopped/stopping/snapshotting, resume and retry.
333
- */
334
- async withResume(fn, signal) {
335
- try {
336
- return await fn();
337
- }
338
- catch (err) {
339
- if (isSandboxStoppedError(err)) {
340
- await this.resume(signal);
341
- return fn();
342
- }
343
- if (isSandboxStoppingError(err) || isSandboxSnapshottingError(err)) {
344
- await this.waitForStopAndResume(signal);
345
- return fn();
346
- }
347
- throw err;
348
- }
349
- }
350
- async runCommand(commandOrParams, args, opts) {
351
- const signal = typeof commandOrParams === "string"
352
- ? opts?.signal
353
- : commandOrParams.signal;
354
- return this.withResume(() => this.session.runCommand(commandOrParams, args, opts), signal);
355
- }
356
- /**
357
- * Internal helper to start a command in the sandbox.
358
- *
359
- * @param params - Command execution parameters.
360
- * @returns A {@link Command} or {@link CommandFinished}, depending on `detached`.
361
- * @internal
362
- */
363
- async getCommand(cmdId, opts) {
364
- return this.withResume(() => this.session.getCommand(cmdId, opts), opts?.signal);
365
- }
366
- /**
367
- * Create a directory in the filesystem of this sandbox.
368
- *
369
- * @param path - Path of the directory to create
370
- * @param opts - Optional parameters.
371
- * @param opts.signal - An AbortSignal to cancel the operation.
372
- */
373
- async mkDir(path, opts) {
374
- return this.withResume(() => this.session.mkDir(path, opts), opts?.signal);
375
- }
376
- /**
377
- * Read a file from the filesystem of this sandbox as a stream.
378
- *
379
- * @param file - File to read, with path and optional cwd
380
- * @param opts - Optional parameters.
381
- * @param opts.signal - An AbortSignal to cancel the operation.
382
- * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found
383
- */
384
- async readFile(file, opts) {
385
- return this.withResume(() => this.session.readFile(file, opts), opts?.signal);
386
- }
387
- /**
388
- * Read a file from the filesystem of this sandbox as a Buffer.
389
- *
390
- * @param file - File to read, with path and optional cwd
391
- * @param opts - Optional parameters.
392
- * @param opts.signal - An AbortSignal to cancel the operation.
393
- * @returns A promise that resolves to the file contents as a Buffer, or null if file not found
394
- */
395
- async readFileToBuffer(file, opts) {
396
- return this.withResume(() => this.session.readFileToBuffer(file, opts), opts?.signal);
397
- }
398
- /**
399
- * Download a file from the sandbox to the local filesystem.
400
- *
401
- * @param src - Source file on the sandbox, with path and optional cwd
402
- * @param dst - Destination file on the local machine, with path and optional cwd
403
- * @param opts - Optional parameters.
404
- * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.
405
- * @param opts.signal - An AbortSignal to cancel the operation.
406
- * @returns The absolute path to the written file, or null if the source file was not found
407
- */
408
- async downloadFile(src, dst, opts) {
409
- return this.withResume(() => this.session.downloadFile(src, dst, opts), opts?.signal);
410
- }
411
- /**
412
- * Write files to the filesystem of this sandbox.
413
- * Defaults to writing to /vercel/sandbox unless an absolute path is specified.
414
- * Writes files using the `vercel-sandbox` user.
415
- *
416
- * @param files - Array of files with path, content, and optional mode (permissions)
417
- * @param opts - Optional parameters.
418
- * @param opts.signal - An AbortSignal to cancel the operation.
419
- * @returns A promise that resolves when the files are written
420
- *
421
- * @example
422
- * // Write an executable script
423
- * await sandbox.writeFiles([
424
- * { path: "/usr/local/bin/myscript", content: Buffer.from("#!/bin/bash\necho hello"), mode: 0o755 }
425
- * ]);
426
- */
427
- async writeFiles(files, opts) {
428
- return this.withResume(() => this.session.writeFiles(files, opts), opts?.signal);
429
- }
430
- /**
431
- * Get the public domain of a port of this sandbox.
432
- *
433
- * @param p - Port number to resolve
434
- * @returns A full domain (e.g. `https://subdomain.vercel.run`)
435
- * @throws If the port has no associated route
436
- */
437
- domain(p) {
438
- return this.session.domain(p);
439
- }
440
- /**
441
- * Stop the sandbox.
442
- *
443
- * @param opts - Optional parameters.
444
- * @param opts.signal - An AbortSignal to cancel the operation.
445
- * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.
446
- * @returns The sandbox at the time the stop was acknowledged, or after fully stopped if `blocking` is true.
447
- */
448
- async stop(opts) {
449
- return this.session.stop(opts);
450
- }
451
- /**
452
- * Update the network policy for this sandbox.
453
- *
454
- * @deprecated Use {@link Sandbox.update} instead.
455
- *
456
- * @param networkPolicy - The new network policy to apply.
457
- * @param opts - Optional parameters.
458
- * @param opts.signal - An AbortSignal to cancel the operation.
459
- * @returns A promise that resolves when the network policy is updated.
460
- *
461
- * @example
462
- * // Restrict to specific domains
463
- * await sandbox.updateNetworkPolicy({
464
- * allow: ["*.npmjs.org", "github.com"],
465
- * });
466
- *
467
- * @example
468
- * // Inject credentials with per-domain transformers
469
- * await sandbox.updateNetworkPolicy({
470
- * allow: {
471
- * "ai-gateway.vercel.sh": [{
472
- * transform: [{
473
- * headers: { authorization: "Bearer ..." }
474
- * }]
475
- * }],
476
- * "*": []
477
- * }
478
- * });
479
- *
480
- * @example
481
- * // Deny all network access
482
- * await sandbox.updateNetworkPolicy("deny-all");
483
- */
484
- async updateNetworkPolicy(networkPolicy, opts) {
485
- await this.withResume(() => this.session.update({ networkPolicy: networkPolicy }, opts), opts?.signal);
486
- return this.session.networkPolicy;
487
- }
488
- /**
489
- * Extend the timeout of the sandbox by the specified duration.
490
- *
491
- * This allows you to extend the lifetime of a sandbox up until the maximum
492
- * execution timeout for your plan.
493
- *
494
- * @param duration - The duration in milliseconds to extend the timeout by
495
- * @param opts - Optional parameters.
496
- * @param opts.signal - An AbortSignal to cancel the operation.
497
- * @returns A promise that resolves when the timeout is extended
498
- *
499
- * @example
500
- * const sandbox = await Sandbox.create({ timeout: ms('10m') });
501
- * // Extends timeout by 5 minutes, to a total of 15 minutes.
502
- * await sandbox.extendTimeout(ms('5m'));
503
- */
504
- async extendTimeout(duration, opts) {
505
- return this.withResume(() => this.session.extendTimeout(duration, opts), opts?.signal);
506
- }
507
- /**
508
- * Create a snapshot from this currently running sandbox. New sandboxes can
509
- * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.
510
- *
511
- * Note: this sandbox will be stopped as part of the snapshot creation process.
512
- *
513
- * @param opts - Optional parameters.
514
- * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.
515
- * @param opts.signal - An AbortSignal to cancel the operation.
516
- * @returns A promise that resolves to the Snapshot instance
517
- */
518
- async snapshot(opts) {
519
- return this.withResume(() => this.session.snapshot(opts), opts?.signal);
520
- }
521
- /**
522
- * Update the sandbox configuration.
523
- *
524
- * @param params - Fields to update.
525
- * @param opts - Optional abort signal.
526
- */
527
- async update(params, opts) {
528
- let resources;
529
- if (params.resources?.vcpus) {
530
- resources = {
531
- vcpus: params.resources.vcpus,
532
- memory: params.resources.vcpus * 2048,
533
- };
534
- }
535
- // Update the sandbox config. This config will be used on the next session.
536
- const response = await this.client.updateSandbox({
537
- name: this.sandbox.name,
538
- projectId: this.projectId,
539
- persistent: params.persistent,
540
- resources,
541
- timeout: params.timeout,
542
- networkPolicy: params.networkPolicy,
543
- tags: params.tags,
544
- snapshotExpiration: params.snapshotExpiration,
545
- signal: opts?.signal,
546
- });
547
- this.sandbox = response.json.sandbox;
548
- // Update the current session config. This only applies to network policy.
549
- if (params.networkPolicy) {
550
- try {
551
- return await this.session.update({ networkPolicy: params.networkPolicy }, opts);
552
- }
553
- catch (err) {
554
- if (isSandboxStoppedError(err) || isSandboxStoppingError(err)) {
555
- return;
556
- }
557
- throw err;
558
- }
559
- }
560
- }
561
- /**
562
- * Delete this sandbox.
563
- *
564
- * After deletion the instance becomes inert all further API calls will
565
- * throw immediately.
566
- */
567
- async delete(opts) {
568
- await this.client.deleteSandbox({
569
- name: this.sandbox.name,
570
- projectId: this.projectId,
571
- signal: opts?.signal,
572
- });
573
- }
574
- /**
575
- * List sessions (VMs) that have been created for this sandbox.
576
- *
577
- * @param params - Optional pagination parameters.
578
- * @returns The list of sessions and pagination metadata.
579
- */
580
- async listSessions(params) {
581
- const response = await this.client.listSessions({
582
- projectId: this.projectId,
583
- name: this.sandbox.name,
584
- limit: params?.limit,
585
- cursor: params?.cursor,
586
- sortOrder: params?.sortOrder,
587
- signal: params?.signal,
588
- });
589
- return response.json;
590
- }
591
- /**
592
- * List snapshots that belong to this sandbox.
593
- *
594
- * @param params - Optional pagination parameters.
595
- * @returns The list of snapshots and pagination metadata.
596
- */
597
- async listSnapshots(params) {
598
- const response = await this.client.listSnapshots({
599
- projectId: this.projectId,
600
- name: this.sandbox.name,
601
- limit: params?.limit,
602
- cursor: params?.cursor,
603
- sortOrder: params?.sortOrder,
604
- signal: params?.signal,
605
- });
606
- return response.json;
607
- }
608
- }
609
- exports.Sandbox = Sandbox;
22
+ * A Sandbox is a persistent, isolated Linux MicroVMs to run commands in.
23
+ * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.
24
+ * @hideconstructor
25
+ */
26
+ var Sandbox = class Sandbox {
27
+ /**
28
+ * Lazily resolve credentials and construct an API client.
29
+ * @internal
30
+ */
31
+ async ensureClient() {
32
+ "use step";
33
+ if (this._client) return this._client;
34
+ const credentials = await getCredentials();
35
+ this._client = new APIClient({
36
+ teamId: credentials.teamId,
37
+ token: credentials.token
38
+ });
39
+ return this._client;
40
+ }
41
+ /**
42
+ * The name of this sandbox.
43
+ */
44
+ get name() {
45
+ return this.sandbox.name;
46
+ }
47
+ /**
48
+ * Routes from ports to subdomains.
49
+ * @hidden
50
+ */
51
+ get routes() {
52
+ return this.currentSession().routes;
53
+ }
54
+ /**
55
+ * Whether the sandbox persists the state.
56
+ */
57
+ get persistent() {
58
+ return this.sandbox.persistent;
59
+ }
60
+ /**
61
+ * The region this sandbox runs in.
62
+ */
63
+ get region() {
64
+ return this.sandbox.region;
65
+ }
66
+ /**
67
+ * Number of virtual CPUs allocated.
68
+ */
69
+ get vcpus() {
70
+ return this.sandbox.vcpus;
71
+ }
72
+ /**
73
+ * Memory allocated in MB.
74
+ */
75
+ get memory() {
76
+ return this.sandbox.memory;
77
+ }
78
+ /** Runtime identifier (e.g. "node24", "python3.13"). */
79
+ get runtime() {
80
+ return this.sandbox.runtime;
81
+ }
82
+ /**
83
+ * Cumulative egress bytes across all sessions.
84
+ */
85
+ get totalEgressBytes() {
86
+ return this.sandbox.totalEgressBytes;
87
+ }
88
+ /**
89
+ * Cumulative ingress bytes across all sessions.
90
+ */
91
+ get totalIngressBytes() {
92
+ return this.sandbox.totalIngressBytes;
93
+ }
94
+ /**
95
+ * Cumulative active CPU duration in milliseconds across all sessions.
96
+ */
97
+ get totalActiveCpuDurationMs() {
98
+ return this.sandbox.totalActiveCpuDurationMs;
99
+ }
100
+ /**
101
+ * Cumulative wall-clock duration in milliseconds across all sessions.
102
+ */
103
+ get totalDurationMs() {
104
+ return this.sandbox.totalDurationMs;
105
+ }
106
+ /**
107
+ * When this sandbox was last updated.
108
+ */
109
+ get updatedAt() {
110
+ return new Date(this.sandbox.updatedAt);
111
+ }
112
+ /**
113
+ * When the sandbox status was last updated.
114
+ */
115
+ get statusUpdatedAt() {
116
+ return this.sandbox.statusUpdatedAt ? new Date(this.sandbox.statusUpdatedAt) : void 0;
117
+ }
118
+ /**
119
+ * When this sandbox was created.
120
+ */
121
+ get createdAt() {
122
+ return new Date(this.sandbox.createdAt);
123
+ }
124
+ /**
125
+ * Interactive port.
126
+ */
127
+ get interactivePort() {
128
+ return this.currentSession().interactivePort;
129
+ }
130
+ /**
131
+ * The status of the current session.
132
+ */
133
+ get status() {
134
+ return this.currentSession().status;
135
+ }
136
+ /**
137
+ * The default timeout of this sandbox in milliseconds.
138
+ */
139
+ get timeout() {
140
+ return this.sandbox.timeout;
141
+ }
142
+ /**
143
+ * Key-value tags attached to the sandbox.
144
+ */
145
+ get tags() {
146
+ return this.sandbox.tags;
147
+ }
148
+ /**
149
+ * The default network policy of this sandbox.
150
+ */
151
+ get networkPolicy() {
152
+ return this.sandbox.networkPolicy ? fromAPINetworkPolicy(this.sandbox.networkPolicy) : void 0;
153
+ }
154
+ /**
155
+ * If the session was created from a snapshot, the ID of that snapshot.
156
+ */
157
+ get sourceSnapshotId() {
158
+ return this.currentSession().sourceSnapshotId;
159
+ }
160
+ /**
161
+ * The current snapshot ID of this sandbox, if any.
162
+ */
163
+ get currentSnapshotId() {
164
+ return this.sandbox.currentSnapshotId;
165
+ }
166
+ /**
167
+ * The default snapshot expiration in milliseconds, if set.
168
+ */
169
+ get snapshotExpiration() {
170
+ return this.sandbox.snapshotExpiration;
171
+ }
172
+ /**
173
+ * The amount of CPU used by the session. Only reported once the VM is stopped.
174
+ */
175
+ get activeCpuUsageMs() {
176
+ return this.currentSession().activeCpuUsageMs;
177
+ }
178
+ /**
179
+ * The amount of network data used by the session. Only reported once the VM is stopped.
180
+ */
181
+ get networkTransfer() {
182
+ return this.currentSession().networkTransfer;
183
+ }
184
+ /**
185
+ * Allow to get a list of sandboxes for a team narrowed to the given params.
186
+ * It returns both the sandboxes and the pagination metadata to allow getting
187
+ * the next page of results.
188
+ */
189
+ static async list(params) {
190
+ "use step";
191
+ const credentials = await getCredentials(params);
192
+ return (await new APIClient({
193
+ teamId: credentials.teamId,
194
+ token: credentials.token,
195
+ fetch: params?.fetch
196
+ }).listSandboxes({
197
+ ...credentials,
198
+ ...params
199
+ })).json;
200
+ }
201
+ /**
202
+ * Serialize a Sandbox instance to plain data for @workflow/serde.
203
+ *
204
+ * @param instance - The Sandbox instance to serialize
205
+ * @returns A plain object containing sandbox metadata and routes
206
+ */
207
+ static [WORKFLOW_SERIALIZE](instance) {
208
+ return {
209
+ metadata: instance.session?._sessionSnapshot,
210
+ routes: instance.session?.routes ?? [],
211
+ sandboxMetadata: instance.sandbox,
212
+ projectId: instance.projectId
213
+ };
214
+ }
215
+ /**
216
+ * Deserialize a Sandbox from serialized snapshot data.
217
+ *
218
+ * The deserialized instance uses the serialized metadata synchronously and
219
+ * lazily creates an API client only when methods perform API requests.
220
+ *
221
+ * @param data - The serialized sandbox data
222
+ * @returns The reconstructed Sandbox instance
223
+ */
224
+ static [WORKFLOW_DESERIALIZE](data) {
225
+ const sandbox = new Sandbox({
226
+ sandbox: data.sandboxMetadata,
227
+ routes: data.routes,
228
+ projectId: data.projectId
229
+ });
230
+ if (data.metadata) sandbox.session = new Session({
231
+ routes: data.routes,
232
+ snapshot: data.metadata
233
+ });
234
+ return sandbox;
235
+ }
236
+ /**
237
+ * Create a new sandbox.
238
+ *
239
+ * @param params - Creation parameters and optional credentials.
240
+ * @returns A promise resolving to the created {@link Sandbox}.
241
+ * @example
242
+ * <caption>Create a sandbox with default options</caption>
243
+ * const sandbox = await Sandbox.create();
244
+ *
245
+ * @example
246
+ * <caption>Create a sandbox and drop it in the end of the block</caption>
247
+ * async function fn() {
248
+ * await using const sandbox = await Sandbox.create();
249
+ * // Sandbox automatically stopped at the end of the lexical scope
250
+ * }
251
+ */
252
+ static async create(params) {
253
+ "use step";
254
+ const credentials = await getCredentials(params);
255
+ const client = new APIClient({
256
+ teamId: credentials.teamId,
257
+ token: credentials.token,
258
+ fetch: params?.fetch
259
+ });
260
+ const privateParams = getPrivateParams(params);
261
+ const response = await client.createSandbox({
262
+ source: params?.source,
263
+ projectId: credentials.projectId,
264
+ ports: params?.ports ?? [],
265
+ timeout: params?.timeout,
266
+ resources: params?.resources,
267
+ runtime: params && "runtime" in params ? params?.runtime : void 0,
268
+ networkPolicy: params?.networkPolicy,
269
+ env: params?.env,
270
+ tags: params?.tags,
271
+ snapshotExpiration: params?.snapshotExpiration,
272
+ signal: params?.signal,
273
+ name: params?.name,
274
+ persistent: params?.persistent,
275
+ ...privateParams
276
+ });
277
+ return new DisposableSandbox({
278
+ client,
279
+ session: response.json.session,
280
+ sandbox: response.json.sandbox,
281
+ routes: response.json.routes,
282
+ projectId: credentials.projectId,
283
+ onResume: params?.onResume
284
+ });
285
+ }
286
+ /**
287
+ * Retrieve an existing sandbox and resume its session.
288
+ *
289
+ * @param params - Get parameters and optional credentials.
290
+ * @returns A promise resolving to the {@link Sandbox}.
291
+ */
292
+ static async get(params) {
293
+ "use step";
294
+ const credentials = await getCredentials(params);
295
+ const client = new APIClient({
296
+ teamId: credentials.teamId,
297
+ token: credentials.token,
298
+ fetch: params.fetch
299
+ });
300
+ const privateParams = getPrivateParams(params);
301
+ const response = await client.getSandbox({
302
+ name: params.name,
303
+ projectId: credentials.projectId,
304
+ resume: params.resume,
305
+ signal: params.signal,
306
+ ...privateParams
307
+ });
308
+ const sandbox = new Sandbox({
309
+ client,
310
+ session: response.json.session,
311
+ sandbox: response.json.sandbox,
312
+ routes: response.json.routes,
313
+ projectId: credentials.projectId,
314
+ onResume: params.onResume
315
+ });
316
+ if (response.json.resumed && params.onResume) await params.onResume(sandbox);
317
+ return sandbox;
318
+ }
319
+ /**
320
+ * Create a new Sandbox instance.
321
+ *
322
+ * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.
323
+ * @param params.routes - Port-to-subdomain mappings for exposed ports
324
+ * @param params.sandbox - Sandbox snapshot metadata
325
+ */
326
+ constructor({ client, routes, session, sandbox, projectId, onResume }) {
327
+ this._client = null;
328
+ this.resumePromise = null;
329
+ this._client = client ?? null;
330
+ if (session) this.session = new Session({
331
+ client,
332
+ routes,
333
+ session
334
+ });
335
+ this.sandbox = sandbox;
336
+ this.projectId = projectId ?? "";
337
+ this.onResume = onResume;
338
+ }
339
+ /**
340
+ * Get the current session (the running VM) for this sandbox.
341
+ *
342
+ * @returns The {@link Session} instance.
343
+ */
344
+ currentSession() {
345
+ if (!this.session) throw new Error("No active session. Run a command or call resume first.");
346
+ return this.session;
347
+ }
348
+ /**
349
+ * Resume this sandbox by creating a new session via `getSandbox`.
350
+ */
351
+ async resume(signal) {
352
+ if (!this.resumePromise) this.resumePromise = this.doResume(signal).finally(() => {
353
+ this.resumePromise = null;
354
+ });
355
+ return this.resumePromise;
356
+ }
357
+ async doResume(signal) {
358
+ const client = await this.ensureClient();
359
+ const response = await client.getSandbox({
360
+ name: this.sandbox.name,
361
+ projectId: this.projectId,
362
+ resume: true,
363
+ signal
364
+ });
365
+ this.session = new Session({
366
+ client,
367
+ routes: response.json.routes,
368
+ session: response.json.session
369
+ });
370
+ if (this.onResume && response.json.resumed) await this.onResume(this);
371
+ }
372
+ /**
373
+ * Poll until the current session reaches a terminal state, then resume.
374
+ */
375
+ async waitForStopAndResume(signal) {
376
+ "use step";
377
+ const client = await this.ensureClient();
378
+ const pollingInterval = 500;
379
+ let status = this.session.status;
380
+ while (status === "stopping" || status === "snapshotting") {
381
+ await setTimeout(pollingInterval, void 0, { signal });
382
+ const poll = await client.getSession({
383
+ sessionId: this.session.sessionId,
384
+ signal
385
+ });
386
+ this.session = new Session({
387
+ client,
388
+ routes: poll.json.routes,
389
+ session: poll.json.session
390
+ });
391
+ status = poll.json.session.status;
392
+ }
393
+ await this.resume(signal);
394
+ }
395
+ /**
396
+ * Execute `fn`, and if the session is stopped/stopping/snapshotting, resume and retry.
397
+ */
398
+ async withResume(fn, signal) {
399
+ if (!this.session) await this.resume(signal);
400
+ try {
401
+ return await fn();
402
+ } catch (err) {
403
+ if (isSandboxStoppedError(err)) {
404
+ await this.resume(signal);
405
+ return fn();
406
+ }
407
+ if (isSandboxStoppingError(err) || isSandboxSnapshottingError(err)) {
408
+ await this.waitForStopAndResume(signal);
409
+ return fn();
410
+ }
411
+ throw err;
412
+ }
413
+ }
414
+ async runCommand(commandOrParams, args, opts) {
415
+ "use step";
416
+ const signal = typeof commandOrParams === "string" ? opts?.signal : commandOrParams.signal;
417
+ return this.withResume(() => this.session.runCommand(commandOrParams, args, opts), signal);
418
+ }
419
+ /**
420
+ * Internal helper to start a command in the sandbox.
421
+ *
422
+ * @param params - Command execution parameters.
423
+ * @returns A {@link Command} or {@link CommandFinished}, depending on `detached`.
424
+ * @internal
425
+ */
426
+ async getCommand(cmdId, opts) {
427
+ "use step";
428
+ return this.withResume(() => this.session.getCommand(cmdId, opts), opts?.signal);
429
+ }
430
+ /**
431
+ * Create a directory in the filesystem of this sandbox.
432
+ *
433
+ * @param path - Path of the directory to create
434
+ * @param opts - Optional parameters.
435
+ * @param opts.signal - An AbortSignal to cancel the operation.
436
+ */
437
+ async mkDir(path, opts) {
438
+ "use step";
439
+ return this.withResume(() => this.session.mkDir(path, opts), opts?.signal);
440
+ }
441
+ /**
442
+ * Read a file from the filesystem of this sandbox as a stream.
443
+ *
444
+ * @param file - File to read, with path and optional cwd
445
+ * @param opts - Optional parameters.
446
+ * @param opts.signal - An AbortSignal to cancel the operation.
447
+ * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found
448
+ */
449
+ async readFile(file, opts) {
450
+ "use step";
451
+ return this.withResume(() => this.session.readFile(file, opts), opts?.signal);
452
+ }
453
+ /**
454
+ * Read a file from the filesystem of this sandbox as a Buffer.
455
+ *
456
+ * @param file - File to read, with path and optional cwd
457
+ * @param opts - Optional parameters.
458
+ * @param opts.signal - An AbortSignal to cancel the operation.
459
+ * @returns A promise that resolves to the file contents as a Buffer, or null if file not found
460
+ */
461
+ async readFileToBuffer(file, opts) {
462
+ "use step";
463
+ return this.withResume(() => this.session.readFileToBuffer(file, opts), opts?.signal);
464
+ }
465
+ /**
466
+ * Download a file from the sandbox to the local filesystem.
467
+ *
468
+ * @param src - Source file on the sandbox, with path and optional cwd
469
+ * @param dst - Destination file on the local machine, with path and optional cwd
470
+ * @param opts - Optional parameters.
471
+ * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.
472
+ * @param opts.signal - An AbortSignal to cancel the operation.
473
+ * @returns The absolute path to the written file, or null if the source file was not found
474
+ */
475
+ async downloadFile(src, dst, opts) {
476
+ "use step";
477
+ return this.withResume(() => this.session.downloadFile(src, dst, opts), opts?.signal);
478
+ }
479
+ /**
480
+ * Write files to the filesystem of this sandbox.
481
+ * Defaults to writing to /vercel/sandbox unless an absolute path is specified.
482
+ * Writes files using the `vercel-sandbox` user.
483
+ *
484
+ * @param files - Array of files with path, content, and optional mode (permissions)
485
+ * @param opts - Optional parameters.
486
+ * @param opts.signal - An AbortSignal to cancel the operation.
487
+ * @returns A promise that resolves when the files are written
488
+ *
489
+ * @example
490
+ * // Write an executable script
491
+ * await sandbox.writeFiles([
492
+ * { path: "/usr/local/bin/myscript", content: "#!/bin/bash\necho hello", mode: 0o755 }
493
+ * ]);
494
+ */
495
+ async writeFiles(files, opts) {
496
+ "use step";
497
+ return this.withResume(() => this.session.writeFiles(files, opts), opts?.signal);
498
+ }
499
+ /**
500
+ * Get the public domain of a port of this sandbox.
501
+ *
502
+ * @param p - Port number to resolve
503
+ * @returns A full domain (e.g. `https://subdomain.vercel.run`)
504
+ * @throws If the port has no associated route
505
+ */
506
+ domain(p) {
507
+ return this.currentSession().domain(p);
508
+ }
509
+ /**
510
+ * Stop the sandbox.
511
+ *
512
+ * @param opts - Optional parameters.
513
+ * @param opts.signal - An AbortSignal to cancel the operation.
514
+ * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.
515
+ * @returns The sandbox at the time the stop was acknowledged, or after fully stopped if `blocking` is true.
516
+ */
517
+ async stop(opts) {
518
+ "use step";
519
+ if (!this.session) throw new Error("No active session to stop.");
520
+ return this.session.stop(opts);
521
+ }
522
+ /**
523
+ * Update the network policy for this sandbox.
524
+ *
525
+ * @deprecated Use {@link Sandbox.update} instead.
526
+ *
527
+ * @param networkPolicy - The new network policy to apply.
528
+ * @param opts - Optional parameters.
529
+ * @param opts.signal - An AbortSignal to cancel the operation.
530
+ * @returns A promise that resolves when the network policy is updated.
531
+ *
532
+ * @example
533
+ * // Restrict to specific domains
534
+ * await sandbox.updateNetworkPolicy({
535
+ * allow: ["*.npmjs.org", "github.com"],
536
+ * });
537
+ *
538
+ * @example
539
+ * // Inject credentials with per-domain transformers
540
+ * await sandbox.updateNetworkPolicy({
541
+ * allow: {
542
+ * "ai-gateway.vercel.sh": [{
543
+ * transform: [{
544
+ * headers: { authorization: "Bearer ..." }
545
+ * }]
546
+ * }],
547
+ * "*": []
548
+ * }
549
+ * });
550
+ *
551
+ * @example
552
+ * // Deny all network access
553
+ * await sandbox.updateNetworkPolicy("deny-all");
554
+ */
555
+ async updateNetworkPolicy(networkPolicy, opts) {
556
+ "use step";
557
+ await this.withResume(() => this.session.update({ networkPolicy }, opts), opts?.signal);
558
+ return this.session.networkPolicy;
559
+ }
560
+ /**
561
+ * Extend the timeout of the sandbox by the specified duration.
562
+ *
563
+ * This allows you to extend the lifetime of a sandbox up until the maximum
564
+ * execution timeout for your plan.
565
+ *
566
+ * @param duration - The duration in milliseconds to extend the timeout by
567
+ * @param opts - Optional parameters.
568
+ * @param opts.signal - An AbortSignal to cancel the operation.
569
+ * @returns A promise that resolves when the timeout is extended
570
+ *
571
+ * @example
572
+ * const sandbox = await Sandbox.create({ timeout: ms('10m') });
573
+ * // Extends timeout by 5 minutes, to a total of 15 minutes.
574
+ * await sandbox.extendTimeout(ms('5m'));
575
+ */
576
+ async extendTimeout(duration, opts) {
577
+ "use step";
578
+ return this.withResume(() => this.session.extendTimeout(duration, opts), opts?.signal);
579
+ }
580
+ /**
581
+ * Create a snapshot from this currently running sandbox. New sandboxes can
582
+ * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.
583
+ *
584
+ * Note: this sandbox will be stopped as part of the snapshot creation process.
585
+ *
586
+ * @param opts - Optional parameters.
587
+ * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.
588
+ * @param opts.signal - An AbortSignal to cancel the operation.
589
+ * @returns A promise that resolves to the Snapshot instance
590
+ */
591
+ async snapshot(opts) {
592
+ "use step";
593
+ return this.withResume(() => this.session.snapshot(opts), opts?.signal);
594
+ }
595
+ /**
596
+ * Update the sandbox configuration.
597
+ *
598
+ * @param params - Fields to update.
599
+ * @param opts - Optional abort signal.
600
+ */
601
+ async update(params, opts) {
602
+ "use step";
603
+ const client = await this.ensureClient();
604
+ let resources;
605
+ if (params.resources?.vcpus) resources = {
606
+ vcpus: params.resources.vcpus,
607
+ memory: params.resources.vcpus * 2048
608
+ };
609
+ this.sandbox = (await client.updateSandbox({
610
+ name: this.sandbox.name,
611
+ projectId: this.projectId,
612
+ persistent: params.persistent,
613
+ resources,
614
+ timeout: params.timeout,
615
+ networkPolicy: params.networkPolicy,
616
+ tags: params.tags,
617
+ snapshotExpiration: params.snapshotExpiration,
618
+ signal: opts?.signal
619
+ })).json.sandbox;
620
+ if (params.networkPolicy) try {
621
+ return await this.session?.update({ networkPolicy: params.networkPolicy }, opts);
622
+ } catch (err) {
623
+ if (isSandboxStoppedError(err) || isSandboxStoppingError(err)) return;
624
+ throw err;
625
+ }
626
+ }
627
+ /**
628
+ * Delete this sandbox.
629
+ *
630
+ * After deletion the instance becomes inert — all further API calls will
631
+ * throw immediately.
632
+ */
633
+ async delete(opts) {
634
+ "use step";
635
+ await (await this.ensureClient()).deleteSandbox({
636
+ name: this.sandbox.name,
637
+ projectId: this.projectId,
638
+ signal: opts?.signal
639
+ });
640
+ }
641
+ /**
642
+ * List sessions (VMs) that have been created for this sandbox.
643
+ *
644
+ * @param params - Optional pagination parameters.
645
+ * @returns The list of sessions and pagination metadata.
646
+ */
647
+ async listSessions(params) {
648
+ "use step";
649
+ return (await (await this.ensureClient()).listSessions({
650
+ projectId: this.projectId,
651
+ name: this.sandbox.name,
652
+ limit: params?.limit,
653
+ cursor: params?.cursor,
654
+ sortOrder: params?.sortOrder,
655
+ signal: params?.signal
656
+ })).json;
657
+ }
658
+ /**
659
+ * List snapshots that belong to this sandbox.
660
+ *
661
+ * @param params - Optional pagination parameters.
662
+ * @returns The list of snapshots and pagination metadata.
663
+ */
664
+ async listSnapshots(params) {
665
+ "use step";
666
+ return (await (await this.ensureClient()).listSnapshots({
667
+ projectId: this.projectId,
668
+ name: this.sandbox.name,
669
+ limit: params?.limit,
670
+ cursor: params?.cursor,
671
+ sortOrder: params?.sortOrder,
672
+ signal: params?.signal
673
+ })).json;
674
+ }
675
+ };
610
676
  /**
611
- * A {@link Sandbox} that can automatically be disposed using a `await using` statement.
612
- *
613
- * @example
614
- * {
615
- * await using const sandbox = await Sandbox.create();
616
- * }
617
- * // Sandbox is automatically stopped here
618
- */
619
- class DisposableSandbox extends Sandbox {
620
- async [Symbol.asyncDispose]() {
621
- await this.stop();
622
- }
623
- }
677
+ * A {@link Sandbox} that can automatically be disposed using a `await using` statement.
678
+ *
679
+ * @example
680
+ * {
681
+ * await using const sandbox = await Sandbox.create();
682
+ * }
683
+ * // Sandbox is automatically stopped here
684
+ */
685
+ var DisposableSandbox = class extends Sandbox {
686
+ async [Symbol.asyncDispose]() {
687
+ await this.stop();
688
+ }
689
+ };
690
+
691
+ //#endregion
692
+ export { Sandbox };
624
693
  //# sourceMappingURL=sandbox.js.map