@vercel/sandbox 1.9.3 → 1.10.1

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 (45) hide show
  1. package/dist/api-client/base-client.cjs +2 -1
  2. package/dist/api-client/base-client.cjs.map +1 -1
  3. package/dist/api-client/base-client.js +2 -1
  4. package/dist/api-client/base-client.js.map +1 -1
  5. package/dist/auth/api.cjs +1 -1
  6. package/dist/auth/api.cjs.map +1 -1
  7. package/dist/auth/api.js +1 -1
  8. package/dist/auth/api.js.map +1 -1
  9. package/dist/auth/index.cjs +0 -1
  10. package/dist/auth/index.d.cts +2 -2
  11. package/dist/auth/index.d.ts +2 -2
  12. package/dist/auth/index.js +2 -2
  13. package/dist/auth/project.cjs +124 -26
  14. package/dist/auth/project.cjs.map +1 -1
  15. package/dist/auth/project.d.cts +9 -13
  16. package/dist/auth/project.d.ts +9 -13
  17. package/dist/auth/project.js +125 -26
  18. package/dist/auth/project.js.map +1 -1
  19. package/dist/filesystem.cjs +499 -0
  20. package/dist/filesystem.cjs.map +1 -0
  21. package/dist/filesystem.d.cts +258 -0
  22. package/dist/filesystem.d.ts +258 -0
  23. package/dist/filesystem.js +497 -0
  24. package/dist/filesystem.js.map +1 -0
  25. package/dist/index.cjs +2 -0
  26. package/dist/index.d.cts +3 -2
  27. package/dist/index.d.ts +3 -2
  28. package/dist/index.js +2 -1
  29. package/dist/sandbox.cjs +2 -0
  30. package/dist/sandbox.cjs.map +1 -1
  31. package/dist/sandbox.d.cts +11 -0
  32. package/dist/sandbox.d.ts +11 -0
  33. package/dist/sandbox.js +2 -0
  34. package/dist/sandbox.js.map +1 -1
  35. package/dist/snapshot.cjs +39 -5
  36. package/dist/snapshot.cjs.map +1 -1
  37. package/dist/snapshot.d.cts +28 -6
  38. package/dist/snapshot.d.ts +28 -6
  39. package/dist/snapshot.js +38 -5
  40. package/dist/snapshot.js.map +1 -1
  41. package/dist/version.cjs +1 -1
  42. package/dist/version.cjs.map +1 -1
  43. package/dist/version.js +1 -1
  44. package/dist/version.js.map +1 -1
  45. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.cjs","names":["getCredentials","APIClient","WORKFLOW_SERIALIZE","WORKFLOW_DESERIALIZE","getPrivateParams","toSandboxSnapshot","Command","params: RunCommandParams","command","CommandFinished","path","consumeReadable","Snapshot"],"sources":["../src/sandbox.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SandboxMetaData, SandboxRouteData } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport type { RUNTIMES } from \"./constants.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\nimport {\n type SandboxSnapshot,\n toSandboxSnapshot,\n} from \"./utils/sandbox-snapshot.js\";\nimport { getPrivateParams, type WithPrivate } from \"./utils/types.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/** @inline */\nexport interface BaseCreateSandboxParams {\n /**\n * The source of the sandbox.\n *\n * Omit this parameter start a sandbox without a source.\n *\n * For git sources:\n * - `depth`: Creates shallow clones with limited commit history (minimum: 1)\n * - `revision`: Clones and checks out a specific commit, branch, or tag\n */\n source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n }\n | {\n type: \"git\";\n url: string;\n username: string;\n password: string;\n depth?: number;\n revision?: string;\n }\n | { type: \"tarball\"; url: string };\n /**\n * Array of port numbers to expose from the sandbox. Sandboxes can\n * expose up to 4 ports.\n */\n ports?: number[];\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n */\n timeout?: number;\n /**\n * Resources to allocate to the sandbox.\n *\n * Your sandbox will get the amount of vCPUs you specify here and\n * 2048 MB of memory per vCPU.\n */\n resources?: { vcpus: number };\n\n /**\n * The runtime of the sandbox, currently only `node24`, `node22` and `python3.13` are supported.\n * If not specified, the default runtime `node24` will be used.\n */\n runtime?: RUNTIMES | (string & {});\n\n /**\n * Network policy to define network restrictions for the sandbox.\n * Defaults to full internet access if not specified.\n */\n networkPolicy?: NetworkPolicy;\n\n /**\n * Default environment variables for the sandbox.\n * These are inherited by all commands unless overridden with\n * the `env` option in `runCommand`.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * env: { NODE_ENV: \"production\", API_KEY: \"secret\" },\n * });\n * // All commands will have NODE_ENV and API_KEY set\n * await sandbox.runCommand(\"node\", [\"app.js\"]);\n */\n env?: Record<string, string>;\n\n /**\n * An AbortSignal to cancel sandbox creation.\n */\n signal?: AbortSignal;\n}\n\nexport type CreateSandboxParams =\n | BaseCreateSandboxParams\n | (Omit<BaseCreateSandboxParams, \"runtime\" | \"source\"> & {\n source: { type: \"snapshot\"; snapshotId: string };\n });\n\n/** @inline */\ninterface GetSandboxParams {\n /**\n * Unique identifier of the sandbox.\n */\n sandboxId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Serialized representation of a Sandbox for @workflow/serde.\n */\nexport interface SerializedSandbox {\n metadata: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\ninterface RunCommandParams {\n /**\n * The command to execute\n */\n cmd: string;\n /**\n * Arguments to pass to the command\n */\n args?: string[];\n /**\n * Working directory to execute the command in\n */\n cwd?: string;\n /**\n * Environment variables to set for this command\n */\n env?: Record<string, string>;\n /**\n * If true, execute this command with root privileges. Defaults to false.\n */\n sudo?: boolean;\n /**\n * If true, the command will return without waiting for `exitCode`\n */\n detached?: boolean;\n /**\n * A `Writable` stream where `stdout` from the command will be piped\n */\n stdout?: Writable;\n /**\n * A `Writable` stream where `stderr` from the command will be piped\n */\n stderr?: Writable;\n /**\n * An AbortSignal to cancel the command execution\n */\n signal?: AbortSignal;\n}\n\n// ============================================================================\n// Sandbox class\n// ============================================================================\n\n/**\n * A Sandbox is an isolated Linux MicroVM to run commands in.\n *\n * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.\n * @hideconstructor\n */\nexport class Sandbox {\n private _client: APIClient | null = null;\n\n /**\n * Lazily resolve credentials and construct an API client.\n * This is used in step contexts where the Sandbox was deserialized\n * without a client (e.g. when crossing workflow/step boundaries).\n * Uses getCredentials() which resolves from OIDC or env vars.\n * @internal\n */\n private async ensureClient(): Promise<APIClient> {\n \"use step\";\n if (this._client) return this._client;\n const credentials = await getCredentials();\n this._client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n return this._client;\n }\n\n /**\n * Routes from ports to subdomains.\n /* @hidden\n */\n public readonly routes: SandboxRouteData[];\n\n /**\n * Unique ID of this sandbox.\n */\n public get sandboxId(): string {\n return this.sandbox.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.sandbox.interactivePort ?? undefined;\n }\n\n /**\n * The status of the sandbox.\n */\n public get status(): SandboxMetaData[\"status\"] {\n return this.sandbox.status;\n }\n\n /**\n * The creation date of the sandbox.\n */\n public get createdAt(): Date {\n return new Date(this.sandbox.createdAt);\n }\n\n /**\n * The timeout of the sandbox in milliseconds.\n */\n public get timeout(): number {\n return this.sandbox.timeout;\n }\n\n /**\n * The network policy of the sandbox.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.sandbox.networkPolicy;\n }\n\n /**\n * If the sandbox was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.sandbox.sourceSnapshotId;\n }\n\n /**\n * The amount of CPU used by the sandbox. Only reported once the VM is stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.sandbox.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the sandbox. Only reported once the VM is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.sandbox.networkTransfer;\n }\n\n /**\n * Internal metadata about this sandbox.\n */\n private sandbox: SandboxSnapshot;\n\n /**\n * Allow to get a list of sandboxes for a team narrowed to the given params.\n * It returns both the sandboxes and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSandboxes\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSandboxes({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Serialize a Sandbox instance to plain data for @workflow/serde.\n *\n * @param instance - The Sandbox instance to serialize\n * @returns A plain object containing sandbox metadata and routes\n */\n static [WORKFLOW_SERIALIZE](instance: Sandbox): SerializedSandbox {\n return {\n metadata: instance.sandbox,\n routes: instance.routes,\n };\n }\n\n /**\n * Deserialize a Sandbox from serialized snapshot data.\n *\n * The deserialized instance uses the serialized metadata synchronously and\n * lazily creates an API client only when methods perform API requests.\n *\n * @param data - The serialized sandbox data\n * @returns The reconstructed Sandbox instance\n */\n static [WORKFLOW_DESERIALIZE](data: SerializedSandbox): Sandbox {\n return new Sandbox({\n sandbox: data.metadata,\n routes: data.routes,\n });\n }\n\n /**\n * Create a new sandbox.\n *\n * @param params - Creation parameters and optional credentials.\n * @returns A promise resolving to the created {@link Sandbox}.\n * @example\n * <caption>Create a sandbox and drop it in the end of the block</caption>\n * async function fn() {\n * await using const sandbox = await Sandbox.create();\n * // Sandbox automatically stopped at the end of the lexical scope\n * }\n */\n static async create(\n params?: WithPrivate<\n CreateSandboxParams | (CreateSandboxParams & Credentials)\n > &\n WithFetchOptions,\n ): Promise<Sandbox & AsyncDisposable> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.createSandbox({\n source: params?.source,\n projectId: credentials.projectId,\n ports: params?.ports ?? [],\n timeout: params?.timeout,\n resources: params?.resources,\n runtime: params && \"runtime\" in params ? params?.runtime : undefined,\n networkPolicy: params?.networkPolicy,\n env: params?.env,\n signal: params?.signal,\n ...privateParams,\n });\n\n return new DisposableSandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Retrieve an existing sandbox.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: WithPrivate<GetSandboxParams | (GetSandboxParams & Credentials)> &\n WithFetchOptions,\n ): Promise<Sandbox> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.getSandbox({\n sandboxId: params.sandboxId,\n signal: params.signal,\n ...privateParams,\n });\n\n return new Sandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Create a new Sandbox instance.\n *\n * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.\n * @param params.routes - Port-to-subdomain mappings for exposed ports\n * @param params.sandbox - Sandbox snapshot metadata\n */\n constructor({\n client,\n routes,\n sandbox,\n }: {\n client?: APIClient;\n routes: SandboxRouteData[];\n sandbox: SandboxSnapshot;\n }) {\n this._client = client ?? null;\n this.routes = routes;\n this.sandbox = sandbox;\n }\n\n /**\n * Get a previously run command by its ID.\n *\n * @param cmdId - ID of the command to retrieve\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A {@link Command} instance representing the command\n */\n async getCommand(\n cmdId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<Command> {\n \"use step\";\n const client = await this.ensureClient();\n const command = await client.getCommand({\n sandboxId: this.sandbox.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param command - The command to execute.\n * @param args - Arguments to pass to the command.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the command execution.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(\n command: string,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<CommandFinished>;\n\n /**\n * Start executing a command in detached mode.\n *\n * @param params - The command parameters.\n * @returns A {@link Command} instance for the running command.\n */\n async runCommand(\n params: RunCommandParams & { detached: true },\n ): Promise<Command>;\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param params - The command parameters.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(params: RunCommandParams): Promise<CommandFinished>;\n\n async runCommand(\n commandOrParams: string | RunCommandParams,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<Command | CommandFinished> {\n \"use step\";\n const client = await this.ensureClient();\n const params: RunCommandParams =\n typeof commandOrParams === \"string\"\n ? { cmd: commandOrParams, args, signal: opts?.signal }\n : commandOrParams;\n\n const wait = params.detached ? false : true;\n const pipeLogs = async (command: Command): Promise<void> => {\n if (!params.stdout && !params.stderr) {\n return;\n }\n\n try {\n for await (const log of command.logs({ signal: params.signal })) {\n if (log.stream === \"stdout\") {\n params.stdout?.write(log.data);\n } else if (log.stream === \"stderr\") {\n params.stderr?.write(log.data);\n }\n }\n } catch (err) {\n if (params.signal?.aborted) {\n return;\n }\n throw err;\n }\n };\n\n if (wait) {\n const commandStream = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n wait: true,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandStream.command,\n });\n\n const [finished] = await Promise.all([\n commandStream.finished,\n pipeLogs(command),\n ]);\n return new CommandFinished({\n client,\n sandboxId: this.sandbox.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandResponse.json.command,\n });\n\n void pipeLogs(command).catch((err) => {\n if (params.signal?.aborted) {\n return;\n }\n (params.stderr ?? params.stdout)?.emit(\"error\", err);\n });\n\n return command;\n }\n\n /**\n * Create a directory in the filesystem of this sandbox.\n *\n * @param path - Path of the directory to create\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n */\n async mkDir(path: string, opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n await client.mkDir({\n sandboxId: this.sandbox.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a stream.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found\n */\n async readFile(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<NodeJS.ReadableStream | null> {\n \"use step\";\n const client = await this.ensureClient();\n return client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a Buffer.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the file contents as a Buffer, or null if file not found\n */\n async readFileToBuffer(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<Buffer | null> {\n \"use step\";\n const client = await this.ensureClient();\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n return consumeReadable(stream);\n }\n\n /**\n * Download a file from the sandbox to the local filesystem.\n *\n * @param src - Source file on the sandbox, with path and optional cwd\n * @param dst - Destination file on the local machine, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The absolute path to the written file, or null if the source file was not found\n */\n async downloadFile(\n src: { path: string; cwd?: string },\n dst: { path: string; cwd?: string },\n opts?: { mkdirRecursive?: boolean; signal?: AbortSignal },\n ): Promise<string | null> {\n \"use step\";\n const client = await this.ensureClient();\n if (!src?.path) {\n throw new Error(\"downloadFile: source path is required\");\n }\n\n if (!dst?.path) {\n throw new Error(\"downloadFile: destination path is required\");\n }\n\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: src.path,\n cwd: src.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n try {\n const dstPath = resolve(dst.cwd ?? \"\", dst.path);\n if (opts?.mkdirRecursive) {\n await mkdir(dirname(dstPath), { recursive: true });\n }\n await pipeline(stream, createWriteStream(dstPath), {\n signal: opts?.signal,\n });\n return dstPath;\n } finally {\n stream.destroy();\n }\n }\n\n /**\n * Write files to the filesystem of this sandbox.\n * Defaults to writing to /vercel/sandbox unless an absolute path is specified.\n * Writes files using the `vercel-sandbox` user.\n *\n * @param files - Array of files with path, content, and optional mode (permissions)\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the files are written\n *\n * @example\n * // Write an executable script\n * await sandbox.writeFiles([\n * { path: \"/usr/local/bin/myscript\", content: \"#!/bin/bash\\necho hello\", mode: 0o755 }\n * ]);\n */\n async writeFiles(\n files: {\n path: string;\n content: string | Uint8Array;\n mode?: number;\n }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sandboxId: this.sandbox.id,\n cwd: this.sandbox.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this sandbox.\n *\n * @param p - Port number to resolve\n * @returns A full domain (e.g. `https://subdomain.vercel.run`)\n * @throws If the port has no associated route\n */\n domain(p: number): string {\n const route = this.routes.find(({ port }) => port == p);\n if (route) {\n return `https://${route.subdomain}.vercel.run`;\n } else {\n throw new Error(`No route for port ${p}`);\n }\n }\n\n /**\n * Stop the sandbox.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.\n * @returns The sandbox metadata at the time the stop was acknowledged, or after fully stopped if `blocking` is true.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n blocking?: boolean;\n }): Promise<SandboxSnapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSandbox({\n sandboxId: this.sandbox.id,\n signal: opts?.signal,\n blocking: opts?.blocking,\n });\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox;\n }\n\n /**\n * Update the network policy for this sandbox.\n *\n * @param networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the network policy is updated.\n *\n * @example\n * // Restrict to specific domains\n * await sandbox.updateNetworkPolicy({\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await sandbox.updateNetworkPolicy({\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await sandbox.updateNetworkPolicy(\"deny-all\");\n */\n async updateNetworkPolicy(\n networkPolicy: NetworkPolicy,\n opts?: { signal?: AbortSignal },\n ): Promise<NetworkPolicy> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sandboxId: this.sandbox.id,\n networkPolicy: networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox.networkPolicy!;\n }\n\n /**\n * Extend the timeout of the sandbox by the specified duration.\n *\n * This allows you to extend the lifetime of a sandbox up until the maximum\n * execution timeout for your plan.\n *\n * @param duration - The duration in milliseconds to extend the timeout by\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the timeout is extended\n *\n * @example\n * const sandbox = await Sandbox.create({ timeout: ms('10m') });\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await sandbox.extendTimeout(ms('5m'));\n */\n async extendTimeout(\n duration: number,\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.extendTimeout({\n sandboxId: this.sandbox.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n }\n\n /**\n * Create a snapshot from this currently running sandbox. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.\n *\n * Note: this sandbox will be stopped as part of the snapshot creation process.\n *\n * @param opts - Optional parameters.\n * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the Snapshot instance\n */\n async snapshot(opts?: {\n expiration?: number;\n signal?: AbortSignal;\n }): Promise<Snapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.createSnapshot({\n sandboxId: this.sandbox.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n\n/**\n * A {@link Sandbox} that can automatically be disposed using a `await using` statement.\n *\n * @example\n * {\n * await using const sandbox = await Sandbox.create();\n * }\n * // Sandbox is automatically stopped here\n */\nclass DisposableSandbox extends Sandbox implements AsyncDisposable {\n async [Symbol.asyncDispose]() {\n await this.stop();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmLA,IAAa,UAAb,MAAa,QAAQ;;;;;;;;CAUnB,MAAc,eAAmC;AAC/C;AACA,MAAI,KAAK,QAAS,QAAO,KAAK;EAC9B,MAAM,cAAc,MAAMA,wCAAgB;AAC1C,OAAK,UAAU,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AACF,SAAO,KAAK;;;;;CAYd,IAAW,YAAoB;AAC7B,SAAO,KAAK,QAAQ;;CAGtB,IAAW,kBAAsC;AAC/C,SAAO,KAAK,QAAQ,mBAAmB;;;;;CAMzC,IAAW,SAAoC;AAC7C,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,YAAkB;AAC3B,SAAO,IAAI,KAAK,KAAK,QAAQ,UAAU;;;;;CAMzC,IAAW,UAAkB;AAC3B,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,gBAA2C;AACpD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,kBAEG;AACZ,SAAO,KAAK,QAAQ;;;;;;;CAatB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAMD,uCAAe,OAAO;AAMhD,SALe,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC,CACY,cAAc;GAC1B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,QAAQ;AACvD,SAAO,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCd,MAAM,oBACJ,eACA,MACwB;AACxB;AASA,OAAK,UAAUA,4CAPE,OADF,MAAM,KAAK,cAAc,EACV,oBAAoB;GAChD,WAAW,KAAK,QAAQ;GACT;GACf,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;AACvD,SAAO,KAAK,QAAQ;;;;;;;;;;;;;;;;;;CAmBtB,MAAM,cACJ,UACA,MACe;AACf;AASA,OAAK,UAAUA,4CAPE,OADF,MAAM,KAAK,cAAc,EACV,cAAc;GAC1C,WAAW,KAAK,QAAQ;GACxB;GACA,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;;;;;;;;;;;;;CAczD,MAAM,SAAS,MAGO;AACpB;EACA,MAAM,SAAS,MAAM,KAAK,cAAc;EACxC,MAAM,WAAW,MAAM,OAAO,eAAe;GAC3C,WAAW,KAAK,QAAQ;GACxB,YAAY,MAAM;GAClB,QAAQ,MAAM;GACf,CAAC;AAEF,OAAK,UAAUA,2CAAkB,SAAS,KAAK,QAAQ;AAEvD,SAAO,IAAIO,0BAAS;GAClB;GACA,UAAU,SAAS,KAAK;GACzB,CAAC;;;;;;;;;;;;AAaN,IAAM,oBAAN,cAAgC,QAAmC;CACjE,OAAO,OAAO,gBAAgB;AAC5B,QAAM,KAAK,MAAM"}
1
+ {"version":3,"file":"sandbox.cjs","names":["getCredentials","APIClient","WORKFLOW_SERIALIZE","WORKFLOW_DESERIALIZE","getPrivateParams","toSandboxSnapshot","FileSystem","Command","params: RunCommandParams","command","CommandFinished","path","consumeReadable","Snapshot"],"sources":["../src/sandbox.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SandboxMetaData, SandboxRouteData } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport type { RUNTIMES } from \"./constants.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\nimport {\n type SandboxSnapshot,\n toSandboxSnapshot,\n} from \"./utils/sandbox-snapshot.js\";\nimport { getPrivateParams, type WithPrivate } from \"./utils/types.js\";\nimport { FileSystem } from \"./filesystem.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/** @inline */\nexport interface BaseCreateSandboxParams {\n /**\n * The source of the sandbox.\n *\n * Omit this parameter start a sandbox without a source.\n *\n * For git sources:\n * - `depth`: Creates shallow clones with limited commit history (minimum: 1)\n * - `revision`: Clones and checks out a specific commit, branch, or tag\n */\n source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n }\n | {\n type: \"git\";\n url: string;\n username: string;\n password: string;\n depth?: number;\n revision?: string;\n }\n | { type: \"tarball\"; url: string };\n /**\n * Array of port numbers to expose from the sandbox. Sandboxes can\n * expose up to 4 ports.\n */\n ports?: number[];\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n */\n timeout?: number;\n /**\n * Resources to allocate to the sandbox.\n *\n * Your sandbox will get the amount of vCPUs you specify here and\n * 2048 MB of memory per vCPU.\n */\n resources?: { vcpus: number };\n\n /**\n * The runtime of the sandbox, currently only `node24`, `node22` and `python3.13` are supported.\n * If not specified, the default runtime `node24` will be used.\n */\n runtime?: RUNTIMES | (string & {});\n\n /**\n * Network policy to define network restrictions for the sandbox.\n * Defaults to full internet access if not specified.\n */\n networkPolicy?: NetworkPolicy;\n\n /**\n * Default environment variables for the sandbox.\n * These are inherited by all commands unless overridden with\n * the `env` option in `runCommand`.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * env: { NODE_ENV: \"production\", API_KEY: \"secret\" },\n * });\n * // All commands will have NODE_ENV and API_KEY set\n * await sandbox.runCommand(\"node\", [\"app.js\"]);\n */\n env?: Record<string, string>;\n\n /**\n * An AbortSignal to cancel sandbox creation.\n */\n signal?: AbortSignal;\n}\n\nexport type CreateSandboxParams =\n | BaseCreateSandboxParams\n | (Omit<BaseCreateSandboxParams, \"runtime\" | \"source\"> & {\n source: { type: \"snapshot\"; snapshotId: string };\n });\n\n/** @inline */\ninterface GetSandboxParams {\n /**\n * Unique identifier of the sandbox.\n */\n sandboxId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Serialized representation of a Sandbox for @workflow/serde.\n */\nexport interface SerializedSandbox {\n metadata: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\ninterface RunCommandParams {\n /**\n * The command to execute\n */\n cmd: string;\n /**\n * Arguments to pass to the command\n */\n args?: string[];\n /**\n * Working directory to execute the command in\n */\n cwd?: string;\n /**\n * Environment variables to set for this command\n */\n env?: Record<string, string>;\n /**\n * If true, execute this command with root privileges. Defaults to false.\n */\n sudo?: boolean;\n /**\n * If true, the command will return without waiting for `exitCode`\n */\n detached?: boolean;\n /**\n * A `Writable` stream where `stdout` from the command will be piped\n */\n stdout?: Writable;\n /**\n * A `Writable` stream where `stderr` from the command will be piped\n */\n stderr?: Writable;\n /**\n * An AbortSignal to cancel the command execution\n */\n signal?: AbortSignal;\n}\n\n// ============================================================================\n// Sandbox class\n// ============================================================================\n\n/**\n * A Sandbox is an isolated Linux MicroVM to run commands in.\n *\n * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.\n * @hideconstructor\n */\nexport class Sandbox {\n private _client: APIClient | null = null;\n\n /**\n * Lazily resolve credentials and construct an API client.\n * This is used in step contexts where the Sandbox was deserialized\n * without a client (e.g. when crossing workflow/step boundaries).\n * Uses getCredentials() which resolves from OIDC or env vars.\n * @internal\n */\n private async ensureClient(): Promise<APIClient> {\n \"use step\";\n if (this._client) return this._client;\n const credentials = await getCredentials();\n this._client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n return this._client;\n }\n\n /**\n * Routes from ports to subdomains.\n /* @hidden\n */\n public readonly routes: SandboxRouteData[];\n\n /**\n * A `node:fs/promises`-compatible API for interacting with the sandbox filesystem.\n *\n * @example\n * const content = await sandbox.fs.readFile('/etc/hostname', 'utf8');\n * await sandbox.fs.writeFile('/tmp/hello.txt', 'Hello, world!');\n * const files = await sandbox.fs.readdir('/tmp');\n * const stats = await sandbox.fs.stat('/tmp/hello.txt');\n */\n public readonly fs: FileSystem;\n\n /**\n * Unique ID of this sandbox.\n */\n public get sandboxId(): string {\n return this.sandbox.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.sandbox.interactivePort ?? undefined;\n }\n\n /**\n * The status of the sandbox.\n */\n public get status(): SandboxMetaData[\"status\"] {\n return this.sandbox.status;\n }\n\n /**\n * The creation date of the sandbox.\n */\n public get createdAt(): Date {\n return new Date(this.sandbox.createdAt);\n }\n\n /**\n * The timeout of the sandbox in milliseconds.\n */\n public get timeout(): number {\n return this.sandbox.timeout;\n }\n\n /**\n * The network policy of the sandbox.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.sandbox.networkPolicy;\n }\n\n /**\n * If the sandbox was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.sandbox.sourceSnapshotId;\n }\n\n /**\n * The amount of CPU used by the sandbox. Only reported once the VM is stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.sandbox.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the sandbox. Only reported once the VM is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.sandbox.networkTransfer;\n }\n\n /**\n * Internal metadata about this sandbox.\n */\n private sandbox: SandboxSnapshot;\n\n /**\n * Allow to get a list of sandboxes for a team narrowed to the given params.\n * It returns both the sandboxes and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSandboxes\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSandboxes({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Serialize a Sandbox instance to plain data for @workflow/serde.\n *\n * @param instance - The Sandbox instance to serialize\n * @returns A plain object containing sandbox metadata and routes\n */\n static [WORKFLOW_SERIALIZE](instance: Sandbox): SerializedSandbox {\n return {\n metadata: instance.sandbox,\n routes: instance.routes,\n };\n }\n\n /**\n * Deserialize a Sandbox from serialized snapshot data.\n *\n * The deserialized instance uses the serialized metadata synchronously and\n * lazily creates an API client only when methods perform API requests.\n *\n * @param data - The serialized sandbox data\n * @returns The reconstructed Sandbox instance\n */\n static [WORKFLOW_DESERIALIZE](data: SerializedSandbox): Sandbox {\n return new Sandbox({\n sandbox: data.metadata,\n routes: data.routes,\n });\n }\n\n /**\n * Create a new sandbox.\n *\n * @param params - Creation parameters and optional credentials.\n * @returns A promise resolving to the created {@link Sandbox}.\n * @example\n * <caption>Create a sandbox and drop it in the end of the block</caption>\n * async function fn() {\n * await using const sandbox = await Sandbox.create();\n * // Sandbox automatically stopped at the end of the lexical scope\n * }\n */\n static async create(\n params?: WithPrivate<\n CreateSandboxParams | (CreateSandboxParams & Credentials)\n > &\n WithFetchOptions,\n ): Promise<Sandbox & AsyncDisposable> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.createSandbox({\n source: params?.source,\n projectId: credentials.projectId,\n ports: params?.ports ?? [],\n timeout: params?.timeout,\n resources: params?.resources,\n runtime: params && \"runtime\" in params ? params?.runtime : undefined,\n networkPolicy: params?.networkPolicy,\n env: params?.env,\n signal: params?.signal,\n ...privateParams,\n });\n\n return new DisposableSandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Retrieve an existing sandbox.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: WithPrivate<GetSandboxParams | (GetSandboxParams & Credentials)> &\n WithFetchOptions,\n ): Promise<Sandbox> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.getSandbox({\n sandboxId: params.sandboxId,\n signal: params.signal,\n ...privateParams,\n });\n\n return new Sandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Create a new Sandbox instance.\n *\n * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.\n * @param params.routes - Port-to-subdomain mappings for exposed ports\n * @param params.sandbox - Sandbox snapshot metadata\n */\n constructor({\n client,\n routes,\n sandbox,\n }: {\n client?: APIClient;\n routes: SandboxRouteData[];\n sandbox: SandboxSnapshot;\n }) {\n this._client = client ?? null;\n this.routes = routes;\n this.sandbox = sandbox;\n this.fs = new FileSystem(this);\n }\n\n /**\n * Get a previously run command by its ID.\n *\n * @param cmdId - ID of the command to retrieve\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A {@link Command} instance representing the command\n */\n async getCommand(\n cmdId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<Command> {\n \"use step\";\n const client = await this.ensureClient();\n const command = await client.getCommand({\n sandboxId: this.sandbox.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param command - The command to execute.\n * @param args - Arguments to pass to the command.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the command execution.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(\n command: string,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<CommandFinished>;\n\n /**\n * Start executing a command in detached mode.\n *\n * @param params - The command parameters.\n * @returns A {@link Command} instance for the running command.\n */\n async runCommand(\n params: RunCommandParams & { detached: true },\n ): Promise<Command>;\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param params - The command parameters.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(params: RunCommandParams): Promise<CommandFinished>;\n\n async runCommand(\n commandOrParams: string | RunCommandParams,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<Command | CommandFinished> {\n \"use step\";\n const client = await this.ensureClient();\n const params: RunCommandParams =\n typeof commandOrParams === \"string\"\n ? { cmd: commandOrParams, args, signal: opts?.signal }\n : commandOrParams;\n\n const wait = params.detached ? false : true;\n const pipeLogs = async (command: Command): Promise<void> => {\n if (!params.stdout && !params.stderr) {\n return;\n }\n\n try {\n for await (const log of command.logs({ signal: params.signal })) {\n if (log.stream === \"stdout\") {\n params.stdout?.write(log.data);\n } else if (log.stream === \"stderr\") {\n params.stderr?.write(log.data);\n }\n }\n } catch (err) {\n if (params.signal?.aborted) {\n return;\n }\n throw err;\n }\n };\n\n if (wait) {\n const commandStream = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n wait: true,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandStream.command,\n });\n\n const [finished] = await Promise.all([\n commandStream.finished,\n pipeLogs(command),\n ]);\n return new CommandFinished({\n client,\n sandboxId: this.sandbox.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandResponse.json.command,\n });\n\n void pipeLogs(command).catch((err) => {\n if (params.signal?.aborted) {\n return;\n }\n (params.stderr ?? params.stdout)?.emit(\"error\", err);\n });\n\n return command;\n }\n\n /**\n * Create a directory in the filesystem of this sandbox.\n *\n * @param path - Path of the directory to create\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n */\n async mkDir(path: string, opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n await client.mkDir({\n sandboxId: this.sandbox.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a stream.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found\n */\n async readFile(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<NodeJS.ReadableStream | null> {\n \"use step\";\n const client = await this.ensureClient();\n return client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a Buffer.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the file contents as a Buffer, or null if file not found\n */\n async readFileToBuffer(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<Buffer | null> {\n \"use step\";\n const client = await this.ensureClient();\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n return consumeReadable(stream);\n }\n\n /**\n * Download a file from the sandbox to the local filesystem.\n *\n * @param src - Source file on the sandbox, with path and optional cwd\n * @param dst - Destination file on the local machine, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The absolute path to the written file, or null if the source file was not found\n */\n async downloadFile(\n src: { path: string; cwd?: string },\n dst: { path: string; cwd?: string },\n opts?: { mkdirRecursive?: boolean; signal?: AbortSignal },\n ): Promise<string | null> {\n \"use step\";\n const client = await this.ensureClient();\n if (!src?.path) {\n throw new Error(\"downloadFile: source path is required\");\n }\n\n if (!dst?.path) {\n throw new Error(\"downloadFile: destination path is required\");\n }\n\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: src.path,\n cwd: src.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n try {\n const dstPath = resolve(dst.cwd ?? \"\", dst.path);\n if (opts?.mkdirRecursive) {\n await mkdir(dirname(dstPath), { recursive: true });\n }\n await pipeline(stream, createWriteStream(dstPath), {\n signal: opts?.signal,\n });\n return dstPath;\n } finally {\n stream.destroy();\n }\n }\n\n /**\n * Write files to the filesystem of this sandbox.\n * Defaults to writing to /vercel/sandbox unless an absolute path is specified.\n * Writes files using the `vercel-sandbox` user.\n *\n * @param files - Array of files with path, content, and optional mode (permissions)\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the files are written\n *\n * @example\n * // Write an executable script\n * await sandbox.writeFiles([\n * { path: \"/usr/local/bin/myscript\", content: \"#!/bin/bash\\necho hello\", mode: 0o755 }\n * ]);\n */\n async writeFiles(\n files: {\n path: string;\n content: string | Uint8Array;\n mode?: number;\n }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sandboxId: this.sandbox.id,\n cwd: this.sandbox.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this sandbox.\n *\n * @param p - Port number to resolve\n * @returns A full domain (e.g. `https://subdomain.vercel.run`)\n * @throws If the port has no associated route\n */\n domain(p: number): string {\n const route = this.routes.find(({ port }) => port == p);\n if (route) {\n return `https://${route.subdomain}.vercel.run`;\n } else {\n throw new Error(`No route for port ${p}`);\n }\n }\n\n /**\n * Stop the sandbox.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.\n * @returns The sandbox metadata at the time the stop was acknowledged, or after fully stopped if `blocking` is true.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n blocking?: boolean;\n }): Promise<SandboxSnapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSandbox({\n sandboxId: this.sandbox.id,\n signal: opts?.signal,\n blocking: opts?.blocking,\n });\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox;\n }\n\n /**\n * Update the network policy for this sandbox.\n *\n * @param networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the network policy is updated.\n *\n * @example\n * // Restrict to specific domains\n * await sandbox.updateNetworkPolicy({\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await sandbox.updateNetworkPolicy({\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await sandbox.updateNetworkPolicy(\"deny-all\");\n */\n async updateNetworkPolicy(\n networkPolicy: NetworkPolicy,\n opts?: { signal?: AbortSignal },\n ): Promise<NetworkPolicy> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sandboxId: this.sandbox.id,\n networkPolicy: networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox.networkPolicy!;\n }\n\n /**\n * Extend the timeout of the sandbox by the specified duration.\n *\n * This allows you to extend the lifetime of a sandbox up until the maximum\n * execution timeout for your plan.\n *\n * @param duration - The duration in milliseconds to extend the timeout by\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the timeout is extended\n *\n * @example\n * const sandbox = await Sandbox.create({ timeout: ms('10m') });\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await sandbox.extendTimeout(ms('5m'));\n */\n async extendTimeout(\n duration: number,\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.extendTimeout({\n sandboxId: this.sandbox.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n }\n\n /**\n * Create a snapshot from this currently running sandbox. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.\n *\n * Note: this sandbox will be stopped as part of the snapshot creation process.\n *\n * @param opts - Optional parameters.\n * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the Snapshot instance\n */\n async snapshot(opts?: {\n expiration?: number;\n signal?: AbortSignal;\n }): Promise<Snapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.createSnapshot({\n sandboxId: this.sandbox.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n\n/**\n * A {@link Sandbox} that can automatically be disposed using a `await using` statement.\n *\n * @example\n * {\n * await using const sandbox = await Sandbox.create();\n * }\n * // Sandbox is automatically stopped here\n */\nclass DisposableSandbox extends Sandbox implements AsyncDisposable {\n async [Symbol.asyncDispose]() {\n await this.stop();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoLA,IAAa,UAAb,MAAa,QAAQ;;;;;;;;CAUnB,MAAc,eAAmC;AAC/C;AACA,MAAI,KAAK,QAAS,QAAO,KAAK;EAC9B,MAAM,cAAc,MAAMA,wCAAgB;AAC1C,OAAK,UAAU,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AACF,SAAO,KAAK;;;;;CAuBd,IAAW,YAAoB;AAC7B,SAAO,KAAK,QAAQ;;CAGtB,IAAW,kBAAsC;AAC/C,SAAO,KAAK,QAAQ,mBAAmB;;;;;CAMzC,IAAW,SAAoC;AAC7C,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,YAAkB;AAC3B,SAAO,IAAI,KAAK,KAAK,QAAQ,UAAU;;;;;CAMzC,IAAW,UAAkB;AAC3B,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,gBAA2C;AACpD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,kBAEG;AACZ,SAAO,KAAK,QAAQ;;;;;;;CAatB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAMD,uCAAe,OAAO;AAMhD,SALe,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC,CACY,cAAc;GAC1B,GAAG;GACH,GAAG;GACJ,CAAC;;;;;;;;CASJ,QAAQC,qCAAoB,UAAsC;AAChE,SAAO;GACL,UAAU,SAAS;GACnB,QAAQ,SAAS;GAClB;;;;;;;;;;;CAYH,QAAQC,uCAAsB,MAAk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APE,OADF,MAAM,KAAK,cAAc,EACV,oBAAoB;GAChD,WAAW,KAAK,QAAQ;GACT;GACf,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;AACvD,SAAO,KAAK,QAAQ;;;;;;;;;;;;;;;;;;CAmBtB,MAAM,cACJ,UACA,MACe;AACf;AASA,OAAK,UAAUA,4CAPE,OADF,MAAM,KAAK,cAAc,EACV,cAAc;GAC1C,WAAW,KAAK,QAAQ;GACxB;GACA,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;;;;;;;;;;;;;CAczD,MAAM,SAAS,MAGO;AACpB;EACA,MAAM,SAAS,MAAM,KAAK,cAAc;EACxC,MAAM,WAAW,MAAM,OAAO,eAAe;GAC3C,WAAW,KAAK,QAAQ;GACxB,YAAY,MAAM;GAClB,QAAQ,MAAM;GACf,CAAC;AAEF,OAAK,UAAUA,2CAAkB,SAAS,KAAK,QAAQ;AAEvD,SAAO,IAAIQ,0BAAS;GAClB;GACA,UAAU,SAAS,KAAK;GACzB,CAAC;;;;;;;;;;;;AAaN,IAAM,oBAAN,cAAgC,QAAmC;CACjE,OAAO,OAAO,gBAAgB;AAC5B,QAAM,KAAK,MAAM"}
@@ -8,6 +8,7 @@ import { Command, CommandFinished } from "./command.cjs";
8
8
  import { Credentials } from "./utils/get-credentials.cjs";
9
9
  import { Snapshot } from "./snapshot.cjs";
10
10
  import { SandboxSnapshot } from "./utils/sandbox-snapshot.cjs";
11
+ import { FileSystem } from "./filesystem.cjs";
11
12
  import * as zod0 from "zod";
12
13
  import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
13
14
  import { Writable } from "stream";
@@ -170,6 +171,16 @@ declare class Sandbox {
170
171
  /* @hidden
171
172
  */
172
173
  readonly routes: SandboxRouteData[];
174
+ /**
175
+ * A `node:fs/promises`-compatible API for interacting with the sandbox filesystem.
176
+ *
177
+ * @example
178
+ * const content = await sandbox.fs.readFile('/etc/hostname', 'utf8');
179
+ * await sandbox.fs.writeFile('/tmp/hello.txt', 'Hello, world!');
180
+ * const files = await sandbox.fs.readdir('/tmp');
181
+ * const stats = await sandbox.fs.stat('/tmp/hello.txt');
182
+ */
183
+ readonly fs: FileSystem;
173
184
  /**
174
185
  * Unique ID of this sandbox.
175
186
  */
package/dist/sandbox.d.ts CHANGED
@@ -9,6 +9,7 @@ import { Command, CommandFinished } from "./command.js";
9
9
  import { Credentials } from "./utils/get-credentials.js";
10
10
  import { Snapshot } from "./snapshot.js";
11
11
  import { SandboxSnapshot } from "./utils/sandbox-snapshot.js";
12
+ import { FileSystem } from "./filesystem.js";
12
13
  import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
13
14
  import * as zod0 from "zod";
14
15
  import { Writable } from "stream";
@@ -171,6 +172,16 @@ declare class Sandbox {
171
172
  /* @hidden
172
173
  */
173
174
  readonly routes: SandboxRouteData[];
175
+ /**
176
+ * A `node:fs/promises`-compatible API for interacting with the sandbox filesystem.
177
+ *
178
+ * @example
179
+ * const content = await sandbox.fs.readFile('/etc/hostname', 'utf8');
180
+ * await sandbox.fs.writeFile('/tmp/hello.txt', 'Hello, world!');
181
+ * const files = await sandbox.fs.readdir('/tmp');
182
+ * const stats = await sandbox.fs.stat('/tmp/hello.txt');
183
+ */
184
+ readonly fs: FileSystem;
174
185
  /**
175
186
  * Unique ID of this sandbox.
176
187
  */
package/dist/sandbox.js CHANGED
@@ -6,6 +6,7 @@ import { getCredentials } from "./utils/get-credentials.js";
6
6
  import { Command, CommandFinished } from "./command.js";
7
7
  import { Snapshot } from "./snapshot.js";
8
8
  import { toSandboxSnapshot } from "./utils/sandbox-snapshot.js";
9
+ import { FileSystem } from "./filesystem.js";
9
10
  import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
10
11
  import { createWriteStream } from "fs";
11
12
  import { mkdir } from "fs/promises";
@@ -209,6 +210,7 @@ var Sandbox = class Sandbox {
209
210
  this._client = client ?? null;
210
211
  this.routes = routes;
211
212
  this.sandbox = sandbox;
213
+ this.fs = new FileSystem(this);
212
214
  }
213
215
  /**
214
216
  * Get a previously run command by its ID.
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.js","names":["params: RunCommandParams","command","path"],"sources":["../src/sandbox.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SandboxMetaData, SandboxRouteData } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport type { RUNTIMES } from \"./constants.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\nimport {\n type SandboxSnapshot,\n toSandboxSnapshot,\n} from \"./utils/sandbox-snapshot.js\";\nimport { getPrivateParams, type WithPrivate } from \"./utils/types.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/** @inline */\nexport interface BaseCreateSandboxParams {\n /**\n * The source of the sandbox.\n *\n * Omit this parameter start a sandbox without a source.\n *\n * For git sources:\n * - `depth`: Creates shallow clones with limited commit history (minimum: 1)\n * - `revision`: Clones and checks out a specific commit, branch, or tag\n */\n source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n }\n | {\n type: \"git\";\n url: string;\n username: string;\n password: string;\n depth?: number;\n revision?: string;\n }\n | { type: \"tarball\"; url: string };\n /**\n * Array of port numbers to expose from the sandbox. Sandboxes can\n * expose up to 4 ports.\n */\n ports?: number[];\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n */\n timeout?: number;\n /**\n * Resources to allocate to the sandbox.\n *\n * Your sandbox will get the amount of vCPUs you specify here and\n * 2048 MB of memory per vCPU.\n */\n resources?: { vcpus: number };\n\n /**\n * The runtime of the sandbox, currently only `node24`, `node22` and `python3.13` are supported.\n * If not specified, the default runtime `node24` will be used.\n */\n runtime?: RUNTIMES | (string & {});\n\n /**\n * Network policy to define network restrictions for the sandbox.\n * Defaults to full internet access if not specified.\n */\n networkPolicy?: NetworkPolicy;\n\n /**\n * Default environment variables for the sandbox.\n * These are inherited by all commands unless overridden with\n * the `env` option in `runCommand`.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * env: { NODE_ENV: \"production\", API_KEY: \"secret\" },\n * });\n * // All commands will have NODE_ENV and API_KEY set\n * await sandbox.runCommand(\"node\", [\"app.js\"]);\n */\n env?: Record<string, string>;\n\n /**\n * An AbortSignal to cancel sandbox creation.\n */\n signal?: AbortSignal;\n}\n\nexport type CreateSandboxParams =\n | BaseCreateSandboxParams\n | (Omit<BaseCreateSandboxParams, \"runtime\" | \"source\"> & {\n source: { type: \"snapshot\"; snapshotId: string };\n });\n\n/** @inline */\ninterface GetSandboxParams {\n /**\n * Unique identifier of the sandbox.\n */\n sandboxId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Serialized representation of a Sandbox for @workflow/serde.\n */\nexport interface SerializedSandbox {\n metadata: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\ninterface RunCommandParams {\n /**\n * The command to execute\n */\n cmd: string;\n /**\n * Arguments to pass to the command\n */\n args?: string[];\n /**\n * Working directory to execute the command in\n */\n cwd?: string;\n /**\n * Environment variables to set for this command\n */\n env?: Record<string, string>;\n /**\n * If true, execute this command with root privileges. Defaults to false.\n */\n sudo?: boolean;\n /**\n * If true, the command will return without waiting for `exitCode`\n */\n detached?: boolean;\n /**\n * A `Writable` stream where `stdout` from the command will be piped\n */\n stdout?: Writable;\n /**\n * A `Writable` stream where `stderr` from the command will be piped\n */\n stderr?: Writable;\n /**\n * An AbortSignal to cancel the command execution\n */\n signal?: AbortSignal;\n}\n\n// ============================================================================\n// Sandbox class\n// ============================================================================\n\n/**\n * A Sandbox is an isolated Linux MicroVM to run commands in.\n *\n * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.\n * @hideconstructor\n */\nexport class Sandbox {\n private _client: APIClient | null = null;\n\n /**\n * Lazily resolve credentials and construct an API client.\n * This is used in step contexts where the Sandbox was deserialized\n * without a client (e.g. when crossing workflow/step boundaries).\n * Uses getCredentials() which resolves from OIDC or env vars.\n * @internal\n */\n private async ensureClient(): Promise<APIClient> {\n \"use step\";\n if (this._client) return this._client;\n const credentials = await getCredentials();\n this._client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n return this._client;\n }\n\n /**\n * Routes from ports to subdomains.\n /* @hidden\n */\n public readonly routes: SandboxRouteData[];\n\n /**\n * Unique ID of this sandbox.\n */\n public get sandboxId(): string {\n return this.sandbox.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.sandbox.interactivePort ?? undefined;\n }\n\n /**\n * The status of the sandbox.\n */\n public get status(): SandboxMetaData[\"status\"] {\n return this.sandbox.status;\n }\n\n /**\n * The creation date of the sandbox.\n */\n public get createdAt(): Date {\n return new Date(this.sandbox.createdAt);\n }\n\n /**\n * The timeout of the sandbox in milliseconds.\n */\n public get timeout(): number {\n return this.sandbox.timeout;\n }\n\n /**\n * The network policy of the sandbox.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.sandbox.networkPolicy;\n }\n\n /**\n * If the sandbox was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.sandbox.sourceSnapshotId;\n }\n\n /**\n * The amount of CPU used by the sandbox. Only reported once the VM is stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.sandbox.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the sandbox. Only reported once the VM is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.sandbox.networkTransfer;\n }\n\n /**\n * Internal metadata about this sandbox.\n */\n private sandbox: SandboxSnapshot;\n\n /**\n * Allow to get a list of sandboxes for a team narrowed to the given params.\n * It returns both the sandboxes and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSandboxes\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSandboxes({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Serialize a Sandbox instance to plain data for @workflow/serde.\n *\n * @param instance - The Sandbox instance to serialize\n * @returns A plain object containing sandbox metadata and routes\n */\n static [WORKFLOW_SERIALIZE](instance: Sandbox): SerializedSandbox {\n return {\n metadata: instance.sandbox,\n routes: instance.routes,\n };\n }\n\n /**\n * Deserialize a Sandbox from serialized snapshot data.\n *\n * The deserialized instance uses the serialized metadata synchronously and\n * lazily creates an API client only when methods perform API requests.\n *\n * @param data - The serialized sandbox data\n * @returns The reconstructed Sandbox instance\n */\n static [WORKFLOW_DESERIALIZE](data: SerializedSandbox): Sandbox {\n return new Sandbox({\n sandbox: data.metadata,\n routes: data.routes,\n });\n }\n\n /**\n * Create a new sandbox.\n *\n * @param params - Creation parameters and optional credentials.\n * @returns A promise resolving to the created {@link Sandbox}.\n * @example\n * <caption>Create a sandbox and drop it in the end of the block</caption>\n * async function fn() {\n * await using const sandbox = await Sandbox.create();\n * // Sandbox automatically stopped at the end of the lexical scope\n * }\n */\n static async create(\n params?: WithPrivate<\n CreateSandboxParams | (CreateSandboxParams & Credentials)\n > &\n WithFetchOptions,\n ): Promise<Sandbox & AsyncDisposable> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.createSandbox({\n source: params?.source,\n projectId: credentials.projectId,\n ports: params?.ports ?? [],\n timeout: params?.timeout,\n resources: params?.resources,\n runtime: params && \"runtime\" in params ? params?.runtime : undefined,\n networkPolicy: params?.networkPolicy,\n env: params?.env,\n signal: params?.signal,\n ...privateParams,\n });\n\n return new DisposableSandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Retrieve an existing sandbox.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: WithPrivate<GetSandboxParams | (GetSandboxParams & Credentials)> &\n WithFetchOptions,\n ): Promise<Sandbox> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.getSandbox({\n sandboxId: params.sandboxId,\n signal: params.signal,\n ...privateParams,\n });\n\n return new Sandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Create a new Sandbox instance.\n *\n * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.\n * @param params.routes - Port-to-subdomain mappings for exposed ports\n * @param params.sandbox - Sandbox snapshot metadata\n */\n constructor({\n client,\n routes,\n sandbox,\n }: {\n client?: APIClient;\n routes: SandboxRouteData[];\n sandbox: SandboxSnapshot;\n }) {\n this._client = client ?? null;\n this.routes = routes;\n this.sandbox = sandbox;\n }\n\n /**\n * Get a previously run command by its ID.\n *\n * @param cmdId - ID of the command to retrieve\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A {@link Command} instance representing the command\n */\n async getCommand(\n cmdId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<Command> {\n \"use step\";\n const client = await this.ensureClient();\n const command = await client.getCommand({\n sandboxId: this.sandbox.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param command - The command to execute.\n * @param args - Arguments to pass to the command.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the command execution.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(\n command: string,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<CommandFinished>;\n\n /**\n * Start executing a command in detached mode.\n *\n * @param params - The command parameters.\n * @returns A {@link Command} instance for the running command.\n */\n async runCommand(\n params: RunCommandParams & { detached: true },\n ): Promise<Command>;\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param params - The command parameters.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(params: RunCommandParams): Promise<CommandFinished>;\n\n async runCommand(\n commandOrParams: string | RunCommandParams,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<Command | CommandFinished> {\n \"use step\";\n const client = await this.ensureClient();\n const params: RunCommandParams =\n typeof commandOrParams === \"string\"\n ? { cmd: commandOrParams, args, signal: opts?.signal }\n : commandOrParams;\n\n const wait = params.detached ? false : true;\n const pipeLogs = async (command: Command): Promise<void> => {\n if (!params.stdout && !params.stderr) {\n return;\n }\n\n try {\n for await (const log of command.logs({ signal: params.signal })) {\n if (log.stream === \"stdout\") {\n params.stdout?.write(log.data);\n } else if (log.stream === \"stderr\") {\n params.stderr?.write(log.data);\n }\n }\n } catch (err) {\n if (params.signal?.aborted) {\n return;\n }\n throw err;\n }\n };\n\n if (wait) {\n const commandStream = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n wait: true,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandStream.command,\n });\n\n const [finished] = await Promise.all([\n commandStream.finished,\n pipeLogs(command),\n ]);\n return new CommandFinished({\n client,\n sandboxId: this.sandbox.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandResponse.json.command,\n });\n\n void pipeLogs(command).catch((err) => {\n if (params.signal?.aborted) {\n return;\n }\n (params.stderr ?? params.stdout)?.emit(\"error\", err);\n });\n\n return command;\n }\n\n /**\n * Create a directory in the filesystem of this sandbox.\n *\n * @param path - Path of the directory to create\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n */\n async mkDir(path: string, opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n await client.mkDir({\n sandboxId: this.sandbox.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a stream.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found\n */\n async readFile(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<NodeJS.ReadableStream | null> {\n \"use step\";\n const client = await this.ensureClient();\n return client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a Buffer.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the file contents as a Buffer, or null if file not found\n */\n async readFileToBuffer(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<Buffer | null> {\n \"use step\";\n const client = await this.ensureClient();\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n return consumeReadable(stream);\n }\n\n /**\n * Download a file from the sandbox to the local filesystem.\n *\n * @param src - Source file on the sandbox, with path and optional cwd\n * @param dst - Destination file on the local machine, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The absolute path to the written file, or null if the source file was not found\n */\n async downloadFile(\n src: { path: string; cwd?: string },\n dst: { path: string; cwd?: string },\n opts?: { mkdirRecursive?: boolean; signal?: AbortSignal },\n ): Promise<string | null> {\n \"use step\";\n const client = await this.ensureClient();\n if (!src?.path) {\n throw new Error(\"downloadFile: source path is required\");\n }\n\n if (!dst?.path) {\n throw new Error(\"downloadFile: destination path is required\");\n }\n\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: src.path,\n cwd: src.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n try {\n const dstPath = resolve(dst.cwd ?? \"\", dst.path);\n if (opts?.mkdirRecursive) {\n await mkdir(dirname(dstPath), { recursive: true });\n }\n await pipeline(stream, createWriteStream(dstPath), {\n signal: opts?.signal,\n });\n return dstPath;\n } finally {\n stream.destroy();\n }\n }\n\n /**\n * Write files to the filesystem of this sandbox.\n * Defaults to writing to /vercel/sandbox unless an absolute path is specified.\n * Writes files using the `vercel-sandbox` user.\n *\n * @param files - Array of files with path, content, and optional mode (permissions)\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the files are written\n *\n * @example\n * // Write an executable script\n * await sandbox.writeFiles([\n * { path: \"/usr/local/bin/myscript\", content: \"#!/bin/bash\\necho hello\", mode: 0o755 }\n * ]);\n */\n async writeFiles(\n files: {\n path: string;\n content: string | Uint8Array;\n mode?: number;\n }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sandboxId: this.sandbox.id,\n cwd: this.sandbox.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this sandbox.\n *\n * @param p - Port number to resolve\n * @returns A full domain (e.g. `https://subdomain.vercel.run`)\n * @throws If the port has no associated route\n */\n domain(p: number): string {\n const route = this.routes.find(({ port }) => port == p);\n if (route) {\n return `https://${route.subdomain}.vercel.run`;\n } else {\n throw new Error(`No route for port ${p}`);\n }\n }\n\n /**\n * Stop the sandbox.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.\n * @returns The sandbox metadata at the time the stop was acknowledged, or after fully stopped if `blocking` is true.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n blocking?: boolean;\n }): Promise<SandboxSnapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSandbox({\n sandboxId: this.sandbox.id,\n signal: opts?.signal,\n blocking: opts?.blocking,\n });\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox;\n }\n\n /**\n * Update the network policy for this sandbox.\n *\n * @param networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the network policy is updated.\n *\n * @example\n * // Restrict to specific domains\n * await sandbox.updateNetworkPolicy({\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await sandbox.updateNetworkPolicy({\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await sandbox.updateNetworkPolicy(\"deny-all\");\n */\n async updateNetworkPolicy(\n networkPolicy: NetworkPolicy,\n opts?: { signal?: AbortSignal },\n ): Promise<NetworkPolicy> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sandboxId: this.sandbox.id,\n networkPolicy: networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox.networkPolicy!;\n }\n\n /**\n * Extend the timeout of the sandbox by the specified duration.\n *\n * This allows you to extend the lifetime of a sandbox up until the maximum\n * execution timeout for your plan.\n *\n * @param duration - The duration in milliseconds to extend the timeout by\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the timeout is extended\n *\n * @example\n * const sandbox = await Sandbox.create({ timeout: ms('10m') });\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await sandbox.extendTimeout(ms('5m'));\n */\n async extendTimeout(\n duration: number,\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.extendTimeout({\n sandboxId: this.sandbox.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n }\n\n /**\n * Create a snapshot from this currently running sandbox. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.\n *\n * Note: this sandbox will be stopped as part of the snapshot creation process.\n *\n * @param opts - Optional parameters.\n * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the Snapshot instance\n */\n async snapshot(opts?: {\n expiration?: number;\n signal?: AbortSignal;\n }): Promise<Snapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.createSnapshot({\n sandboxId: this.sandbox.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n\n/**\n * A {@link Sandbox} that can automatically be disposed using a `await using` statement.\n *\n * @example\n * {\n * await using const sandbox = await Sandbox.create();\n * }\n * // Sandbox is automatically stopped here\n */\nclass DisposableSandbox extends Sandbox implements AsyncDisposable {\n async [Symbol.asyncDispose]() {\n await this.stop();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmLA,IAAa,UAAb,MAAa,QAAQ;;;;;;;;CAUnB,MAAc,eAAmC;AAC/C;AACA,MAAI,KAAK,QAAS,QAAO,KAAK;EAC9B,MAAM,cAAc,MAAM,gBAAgB;AAC1C,OAAK,UAAU,IAAI,UAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AACF,SAAO,KAAK;;;;;CAYd,IAAW,YAAoB;AAC7B,SAAO,KAAK,QAAQ;;CAGtB,IAAW,kBAAsC;AAC/C,SAAO,KAAK,QAAQ,mBAAmB;;;;;CAMzC,IAAW,SAAoC;AAC7C,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,YAAkB;AAC3B,SAAO,IAAI,KAAK,KAAK,QAAQ,UAAU;;;;;CAMzC,IAAW,UAAkB;AAC3B,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,gBAA2C;AACpD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,mBAAuC;AAChD,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,kBAEG;AACZ,SAAO,KAAK,QAAQ;;;;;;;CAatB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAM,eAAe,OAAO;AAMhD,SALe,IAAI,UAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC,CACY,cAAc;GAC1B,GAAG;GACH,GAAG;GACJ,CAAC;;;;;;;;CASJ,QAAQ,oBAAoB,UAAsC;AAChE,S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Cd,MAAM,oBACJ,eACA,MACwB;AACxB;AASA,OAAK,UAAU,mBAPE,OADF,MAAM,KAAK,cAAc,EACV,oBAAoB;GAChD,WAAW,KAAK,QAAQ;GACT;GACf,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;AACvD,SAAO,KAAK,QAAQ;;;;;;;;;;;;;;;;;;CAmBtB,MAAM,cACJ,UACA,MACe;AACf;AASA,OAAK,UAAU,mBAPE,OADF,MAAM,KAAK,cAAc,EACV,cAAc;GAC1C,WAAW,KAAK,QAAQ;GACxB;GACA,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;;;;;;;;;;;;;CAczD,MAAM,SAAS,MAGO;AACpB;EACA,MAAM,SAAS,MAAM,KAAK,cAAc;EACxC,MAAM,WAAW,MAAM,OAAO,eAAe;GAC3C,WAAW,KAAK,QAAQ;GACxB,YAAY,MAAM;GAClB,QAAQ,MAAM;GACf,CAAC;AAEF,OAAK,UAAU,kBAAkB,SAAS,KAAK,QAAQ;AAEvD,SAAO,IAAI,SAAS;GAClB;GACA,UAAU,SAAS,KAAK;GACzB,CAAC;;;;;;;;;;;;AAaN,IAAM,oBAAN,cAAgC,QAAmC;CACjE,OAAO,OAAO,gBAAgB;AAC5B,QAAM,KAAK,MAAM"}
1
+ {"version":3,"file":"sandbox.js","names":["params: RunCommandParams","command","path"],"sources":["../src/sandbox.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SandboxMetaData, SandboxRouteData } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport type { RUNTIMES } from \"./constants.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\nimport {\n type SandboxSnapshot,\n toSandboxSnapshot,\n} from \"./utils/sandbox-snapshot.js\";\nimport { getPrivateParams, type WithPrivate } from \"./utils/types.js\";\nimport { FileSystem } from \"./filesystem.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/** @inline */\nexport interface BaseCreateSandboxParams {\n /**\n * The source of the sandbox.\n *\n * Omit this parameter start a sandbox without a source.\n *\n * For git sources:\n * - `depth`: Creates shallow clones with limited commit history (minimum: 1)\n * - `revision`: Clones and checks out a specific commit, branch, or tag\n */\n source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n }\n | {\n type: \"git\";\n url: string;\n username: string;\n password: string;\n depth?: number;\n revision?: string;\n }\n | { type: \"tarball\"; url: string };\n /**\n * Array of port numbers to expose from the sandbox. Sandboxes can\n * expose up to 4 ports.\n */\n ports?: number[];\n /**\n * Timeout in milliseconds before the sandbox auto-terminates.\n */\n timeout?: number;\n /**\n * Resources to allocate to the sandbox.\n *\n * Your sandbox will get the amount of vCPUs you specify here and\n * 2048 MB of memory per vCPU.\n */\n resources?: { vcpus: number };\n\n /**\n * The runtime of the sandbox, currently only `node24`, `node22` and `python3.13` are supported.\n * If not specified, the default runtime `node24` will be used.\n */\n runtime?: RUNTIMES | (string & {});\n\n /**\n * Network policy to define network restrictions for the sandbox.\n * Defaults to full internet access if not specified.\n */\n networkPolicy?: NetworkPolicy;\n\n /**\n * Default environment variables for the sandbox.\n * These are inherited by all commands unless overridden with\n * the `env` option in `runCommand`.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * env: { NODE_ENV: \"production\", API_KEY: \"secret\" },\n * });\n * // All commands will have NODE_ENV and API_KEY set\n * await sandbox.runCommand(\"node\", [\"app.js\"]);\n */\n env?: Record<string, string>;\n\n /**\n * An AbortSignal to cancel sandbox creation.\n */\n signal?: AbortSignal;\n}\n\nexport type CreateSandboxParams =\n | BaseCreateSandboxParams\n | (Omit<BaseCreateSandboxParams, \"runtime\" | \"source\"> & {\n source: { type: \"snapshot\"; snapshotId: string };\n });\n\n/** @inline */\ninterface GetSandboxParams {\n /**\n * Unique identifier of the sandbox.\n */\n sandboxId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Serialized representation of a Sandbox for @workflow/serde.\n */\nexport interface SerializedSandbox {\n metadata: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\ninterface RunCommandParams {\n /**\n * The command to execute\n */\n cmd: string;\n /**\n * Arguments to pass to the command\n */\n args?: string[];\n /**\n * Working directory to execute the command in\n */\n cwd?: string;\n /**\n * Environment variables to set for this command\n */\n env?: Record<string, string>;\n /**\n * If true, execute this command with root privileges. Defaults to false.\n */\n sudo?: boolean;\n /**\n * If true, the command will return without waiting for `exitCode`\n */\n detached?: boolean;\n /**\n * A `Writable` stream where `stdout` from the command will be piped\n */\n stdout?: Writable;\n /**\n * A `Writable` stream where `stderr` from the command will be piped\n */\n stderr?: Writable;\n /**\n * An AbortSignal to cancel the command execution\n */\n signal?: AbortSignal;\n}\n\n// ============================================================================\n// Sandbox class\n// ============================================================================\n\n/**\n * A Sandbox is an isolated Linux MicroVM to run commands in.\n *\n * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.\n * @hideconstructor\n */\nexport class Sandbox {\n private _client: APIClient | null = null;\n\n /**\n * Lazily resolve credentials and construct an API client.\n * This is used in step contexts where the Sandbox was deserialized\n * without a client (e.g. when crossing workflow/step boundaries).\n * Uses getCredentials() which resolves from OIDC or env vars.\n * @internal\n */\n private async ensureClient(): Promise<APIClient> {\n \"use step\";\n if (this._client) return this._client;\n const credentials = await getCredentials();\n this._client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n return this._client;\n }\n\n /**\n * Routes from ports to subdomains.\n /* @hidden\n */\n public readonly routes: SandboxRouteData[];\n\n /**\n * A `node:fs/promises`-compatible API for interacting with the sandbox filesystem.\n *\n * @example\n * const content = await sandbox.fs.readFile('/etc/hostname', 'utf8');\n * await sandbox.fs.writeFile('/tmp/hello.txt', 'Hello, world!');\n * const files = await sandbox.fs.readdir('/tmp');\n * const stats = await sandbox.fs.stat('/tmp/hello.txt');\n */\n public readonly fs: FileSystem;\n\n /**\n * Unique ID of this sandbox.\n */\n public get sandboxId(): string {\n return this.sandbox.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.sandbox.interactivePort ?? undefined;\n }\n\n /**\n * The status of the sandbox.\n */\n public get status(): SandboxMetaData[\"status\"] {\n return this.sandbox.status;\n }\n\n /**\n * The creation date of the sandbox.\n */\n public get createdAt(): Date {\n return new Date(this.sandbox.createdAt);\n }\n\n /**\n * The timeout of the sandbox in milliseconds.\n */\n public get timeout(): number {\n return this.sandbox.timeout;\n }\n\n /**\n * The network policy of the sandbox.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.sandbox.networkPolicy;\n }\n\n /**\n * If the sandbox was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.sandbox.sourceSnapshotId;\n }\n\n /**\n * The amount of CPU used by the sandbox. Only reported once the VM is stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.sandbox.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the sandbox. Only reported once the VM is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.sandbox.networkTransfer;\n }\n\n /**\n * Internal metadata about this sandbox.\n */\n private sandbox: SandboxSnapshot;\n\n /**\n * Allow to get a list of sandboxes for a team narrowed to the given params.\n * It returns both the sandboxes and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSandboxes\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSandboxes({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Serialize a Sandbox instance to plain data for @workflow/serde.\n *\n * @param instance - The Sandbox instance to serialize\n * @returns A plain object containing sandbox metadata and routes\n */\n static [WORKFLOW_SERIALIZE](instance: Sandbox): SerializedSandbox {\n return {\n metadata: instance.sandbox,\n routes: instance.routes,\n };\n }\n\n /**\n * Deserialize a Sandbox from serialized snapshot data.\n *\n * The deserialized instance uses the serialized metadata synchronously and\n * lazily creates an API client only when methods perform API requests.\n *\n * @param data - The serialized sandbox data\n * @returns The reconstructed Sandbox instance\n */\n static [WORKFLOW_DESERIALIZE](data: SerializedSandbox): Sandbox {\n return new Sandbox({\n sandbox: data.metadata,\n routes: data.routes,\n });\n }\n\n /**\n * Create a new sandbox.\n *\n * @param params - Creation parameters and optional credentials.\n * @returns A promise resolving to the created {@link Sandbox}.\n * @example\n * <caption>Create a sandbox and drop it in the end of the block</caption>\n * async function fn() {\n * await using const sandbox = await Sandbox.create();\n * // Sandbox automatically stopped at the end of the lexical scope\n * }\n */\n static async create(\n params?: WithPrivate<\n CreateSandboxParams | (CreateSandboxParams & Credentials)\n > &\n WithFetchOptions,\n ): Promise<Sandbox & AsyncDisposable> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.createSandbox({\n source: params?.source,\n projectId: credentials.projectId,\n ports: params?.ports ?? [],\n timeout: params?.timeout,\n resources: params?.resources,\n runtime: params && \"runtime\" in params ? params?.runtime : undefined,\n networkPolicy: params?.networkPolicy,\n env: params?.env,\n signal: params?.signal,\n ...privateParams,\n });\n\n return new DisposableSandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Retrieve an existing sandbox.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: WithPrivate<GetSandboxParams | (GetSandboxParams & Credentials)> &\n WithFetchOptions,\n ): Promise<Sandbox> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params.fetch,\n });\n\n const privateParams = getPrivateParams(params);\n const sandbox = await client.getSandbox({\n sandboxId: params.sandboxId,\n signal: params.signal,\n ...privateParams,\n });\n\n return new Sandbox({\n client,\n sandbox: toSandboxSnapshot(sandbox.json.sandbox),\n routes: sandbox.json.routes,\n });\n }\n\n /**\n * Create a new Sandbox instance.\n *\n * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.\n * @param params.routes - Port-to-subdomain mappings for exposed ports\n * @param params.sandbox - Sandbox snapshot metadata\n */\n constructor({\n client,\n routes,\n sandbox,\n }: {\n client?: APIClient;\n routes: SandboxRouteData[];\n sandbox: SandboxSnapshot;\n }) {\n this._client = client ?? null;\n this.routes = routes;\n this.sandbox = sandbox;\n this.fs = new FileSystem(this);\n }\n\n /**\n * Get a previously run command by its ID.\n *\n * @param cmdId - ID of the command to retrieve\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A {@link Command} instance representing the command\n */\n async getCommand(\n cmdId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<Command> {\n \"use step\";\n const client = await this.ensureClient();\n const command = await client.getCommand({\n sandboxId: this.sandbox.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param command - The command to execute.\n * @param args - Arguments to pass to the command.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the command execution.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(\n command: string,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<CommandFinished>;\n\n /**\n * Start executing a command in detached mode.\n *\n * @param params - The command parameters.\n * @returns A {@link Command} instance for the running command.\n */\n async runCommand(\n params: RunCommandParams & { detached: true },\n ): Promise<Command>;\n\n /**\n * Start executing a command in this sandbox.\n *\n * @param params - The command parameters.\n * @returns A {@link CommandFinished} result once execution is done.\n */\n async runCommand(params: RunCommandParams): Promise<CommandFinished>;\n\n async runCommand(\n commandOrParams: string | RunCommandParams,\n args?: string[],\n opts?: { signal?: AbortSignal },\n ): Promise<Command | CommandFinished> {\n \"use step\";\n const client = await this.ensureClient();\n const params: RunCommandParams =\n typeof commandOrParams === \"string\"\n ? { cmd: commandOrParams, args, signal: opts?.signal }\n : commandOrParams;\n\n const wait = params.detached ? false : true;\n const pipeLogs = async (command: Command): Promise<void> => {\n if (!params.stdout && !params.stderr) {\n return;\n }\n\n try {\n for await (const log of command.logs({ signal: params.signal })) {\n if (log.stream === \"stdout\") {\n params.stdout?.write(log.data);\n } else if (log.stream === \"stderr\") {\n params.stderr?.write(log.data);\n }\n }\n } catch (err) {\n if (params.signal?.aborted) {\n return;\n }\n throw err;\n }\n };\n\n if (wait) {\n const commandStream = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n wait: true,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandStream.command,\n });\n\n const [finished] = await Promise.all([\n commandStream.finished,\n pipeLogs(command),\n ]);\n return new CommandFinished({\n client,\n sandboxId: this.sandbox.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sandboxId: this.sandbox.id,\n command: params.cmd,\n args: params.args ?? [],\n cwd: params.cwd,\n env: params.env ?? {},\n sudo: params.sudo ?? false,\n signal: params.signal,\n });\n\n const command = new Command({\n client,\n sandboxId: this.sandbox.id,\n cmd: commandResponse.json.command,\n });\n\n void pipeLogs(command).catch((err) => {\n if (params.signal?.aborted) {\n return;\n }\n (params.stderr ?? params.stdout)?.emit(\"error\", err);\n });\n\n return command;\n }\n\n /**\n * Create a directory in the filesystem of this sandbox.\n *\n * @param path - Path of the directory to create\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n */\n async mkDir(path: string, opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n await client.mkDir({\n sandboxId: this.sandbox.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a stream.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found\n */\n async readFile(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<NodeJS.ReadableStream | null> {\n \"use step\";\n const client = await this.ensureClient();\n return client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this sandbox as a Buffer.\n *\n * @param file - File to read, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the file contents as a Buffer, or null if file not found\n */\n async readFileToBuffer(\n file: { path: string; cwd?: string },\n opts?: { signal?: AbortSignal },\n ): Promise<Buffer | null> {\n \"use step\";\n const client = await this.ensureClient();\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: file.path,\n cwd: file.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n return consumeReadable(stream);\n }\n\n /**\n * Download a file from the sandbox to the local filesystem.\n *\n * @param src - Source file on the sandbox, with path and optional cwd\n * @param dst - Destination file on the local machine, with path and optional cwd\n * @param opts - Optional parameters.\n * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The absolute path to the written file, or null if the source file was not found\n */\n async downloadFile(\n src: { path: string; cwd?: string },\n dst: { path: string; cwd?: string },\n opts?: { mkdirRecursive?: boolean; signal?: AbortSignal },\n ): Promise<string | null> {\n \"use step\";\n const client = await this.ensureClient();\n if (!src?.path) {\n throw new Error(\"downloadFile: source path is required\");\n }\n\n if (!dst?.path) {\n throw new Error(\"downloadFile: destination path is required\");\n }\n\n const stream = await client.readFile({\n sandboxId: this.sandbox.id,\n path: src.path,\n cwd: src.cwd,\n signal: opts?.signal,\n });\n\n if (stream === null) {\n return null;\n }\n\n try {\n const dstPath = resolve(dst.cwd ?? \"\", dst.path);\n if (opts?.mkdirRecursive) {\n await mkdir(dirname(dstPath), { recursive: true });\n }\n await pipeline(stream, createWriteStream(dstPath), {\n signal: opts?.signal,\n });\n return dstPath;\n } finally {\n stream.destroy();\n }\n }\n\n /**\n * Write files to the filesystem of this sandbox.\n * Defaults to writing to /vercel/sandbox unless an absolute path is specified.\n * Writes files using the `vercel-sandbox` user.\n *\n * @param files - Array of files with path, content, and optional mode (permissions)\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the files are written\n *\n * @example\n * // Write an executable script\n * await sandbox.writeFiles([\n * { path: \"/usr/local/bin/myscript\", content: \"#!/bin/bash\\necho hello\", mode: 0o755 }\n * ]);\n */\n async writeFiles(\n files: {\n path: string;\n content: string | Uint8Array;\n mode?: number;\n }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sandboxId: this.sandbox.id,\n cwd: this.sandbox.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this sandbox.\n *\n * @param p - Port number to resolve\n * @returns A full domain (e.g. `https://subdomain.vercel.run`)\n * @throws If the port has no associated route\n */\n domain(p: number): string {\n const route = this.routes.find(({ port }) => port == p);\n if (route) {\n return `https://${route.subdomain}.vercel.run`;\n } else {\n throw new Error(`No route for port ${p}`);\n }\n }\n\n /**\n * Stop the sandbox.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.\n * @returns The sandbox metadata at the time the stop was acknowledged, or after fully stopped if `blocking` is true.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n blocking?: boolean;\n }): Promise<SandboxSnapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSandbox({\n sandboxId: this.sandbox.id,\n signal: opts?.signal,\n blocking: opts?.blocking,\n });\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox;\n }\n\n /**\n * Update the network policy for this sandbox.\n *\n * @param networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the network policy is updated.\n *\n * @example\n * // Restrict to specific domains\n * await sandbox.updateNetworkPolicy({\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await sandbox.updateNetworkPolicy({\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await sandbox.updateNetworkPolicy(\"deny-all\");\n */\n async updateNetworkPolicy(\n networkPolicy: NetworkPolicy,\n opts?: { signal?: AbortSignal },\n ): Promise<NetworkPolicy> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sandboxId: this.sandbox.id,\n networkPolicy: networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n return this.sandbox.networkPolicy!;\n }\n\n /**\n * Extend the timeout of the sandbox by the specified duration.\n *\n * This allows you to extend the lifetime of a sandbox up until the maximum\n * execution timeout for your plan.\n *\n * @param duration - The duration in milliseconds to extend the timeout by\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves when the timeout is extended\n *\n * @example\n * const sandbox = await Sandbox.create({ timeout: ms('10m') });\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await sandbox.extendTimeout(ms('5m'));\n */\n async extendTimeout(\n duration: number,\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.extendTimeout({\n sandboxId: this.sandbox.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n }\n\n /**\n * Create a snapshot from this currently running sandbox. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.\n *\n * Note: this sandbox will be stopped as part of the snapshot creation process.\n *\n * @param opts - Optional parameters.\n * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves to the Snapshot instance\n */\n async snapshot(opts?: {\n expiration?: number;\n signal?: AbortSignal;\n }): Promise<Snapshot> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.createSnapshot({\n sandboxId: this.sandbox.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.sandbox = toSandboxSnapshot(response.json.sandbox);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n\n/**\n * A {@link Sandbox} that can automatically be disposed using a `await using` statement.\n *\n * @example\n * {\n * await using const sandbox = await Sandbox.create();\n * }\n * // Sandbox is automatically stopped here\n */\nclass DisposableSandbox extends Sandbox implements AsyncDisposable {\n async [Symbol.asyncDispose]() {\n await this.stop();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoLA,IAAa,UAAb,MAAa,QAAQ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;AACf;AASA,OAAK,UAAU,mBAPE,OADF,MAAM,KAAK,cAAc,EACV,cAAc;GAC1C,WAAW,KAAK,QAAQ;GACxB;GACA,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;;;;;;;;;;;;;CAczD,MAAM,SAAS,MAGO;AACpB;EACA,MAAM,SAAS,MAAM,KAAK,cAAc;EACxC,MAAM,WAAW,MAAM,OAAO,eAAe;GAC3C,WAAW,KAAK,QAAQ;GACxB,YAAY,MAAM;GAClB,QAAQ,MAAM;GACf,CAAC;AAEF,OAAK,UAAU,kBAAkB,SAAS,KAAK,QAAQ;AAEvD,SAAO,IAAI,SAAS;GAClB;GACA,UAAU,SAAS,KAAK;GACzB,CAAC;;;;;;;;;;;;AAaN,IAAM,oBAAN,cAAgC,QAAmC;CACjE,OAAO,OAAO,gBAAgB;AAC5B,QAAM,KAAK,MAAM"}
package/dist/snapshot.cjs CHANGED
@@ -1,6 +1,8 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
1
2
  const require_api_client = require('./api-client/api-client.cjs');
2
3
  require('./api-client/index.cjs');
3
4
  const require_get_credentials = require('./utils/get-credentials.cjs');
5
+ let __workflow_serde = require("@workflow/serde");
4
6
 
5
7
  //#region src/snapshot.ts
6
8
  /**
@@ -10,6 +12,22 @@ const require_get_credentials = require('./utils/get-credentials.cjs');
10
12
  * @hideconstructor
11
13
  */
12
14
  var Snapshot = class Snapshot {
15
+ /**
16
+ * Lazily resolve credentials and construct an API client.
17
+ * This is used in step contexts where the Snapshot was deserialized
18
+ * without a client (e.g. when crossing workflow/step boundaries).
19
+ * @internal
20
+ */
21
+ async ensureClient() {
22
+ "use step";
23
+ if (this._client) return this._client;
24
+ const credentials = await require_get_credentials.getCredentials();
25
+ this._client = new require_api_client.APIClient({
26
+ teamId: credentials.teamId,
27
+ token: credentials.token
28
+ });
29
+ return this._client;
30
+ }
13
31
  /**
14
32
  * Unique ID of this snapshot.
15
33
  */
@@ -48,13 +66,29 @@ var Snapshot = class Snapshot {
48
66
  return new Date(this.snapshot.expiresAt);
49
67
  }
50
68
  /**
51
- * Create a new Snapshot instance.
69
+ * Serialize a Snapshot instance to plain data for @workflow/serde.
52
70
  *
53
- * @param client - API client used to communicate with the backend
54
- * @param snapshot - Snapshot metadata
71
+ * @param instance - The Snapshot instance to serialize
72
+ * @returns A plain object containing snapshot metadata
55
73
  */
74
+ static [__workflow_serde.WORKFLOW_SERIALIZE](instance) {
75
+ return { snapshot: instance.snapshot };
76
+ }
77
+ /**
78
+ * Deserialize a Snapshot from serialized data.
79
+ *
80
+ * The deserialized instance uses the serialized metadata synchronously and
81
+ * lazily creates an API client only when methods perform API requests.
82
+ *
83
+ * @param data - The serialized snapshot data
84
+ * @returns The reconstructed Snapshot instance
85
+ */
86
+ static [__workflow_serde.WORKFLOW_DESERIALIZE](data) {
87
+ return new Snapshot({ snapshot: data.snapshot });
88
+ }
56
89
  constructor({ client, snapshot }) {
57
- this.client = client;
90
+ this._client = null;
91
+ this._client = client ?? null;
58
92
  this.snapshot = snapshot;
59
93
  }
60
94
  /**
@@ -104,7 +138,7 @@ var Snapshot = class Snapshot {
104
138
  */
105
139
  async delete(opts) {
106
140
  "use step";
107
- this.snapshot = (await this.client.deleteSnapshot({
141
+ this.snapshot = (await (await this.ensureClient()).deleteSnapshot({
108
142
  snapshotId: this.snapshot.id,
109
143
  signal: opts?.signal
110
144
  })).json.snapshot;
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot.cjs","names":["getCredentials","APIClient"],"sources":["../src/snapshot.ts"],"sourcesContent":["import type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SnapshotMetadata } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\n\n/** @inline */\ninterface GetSnapshotParams {\n /**\n * Unique identifier of the snapshot.\n */\n snapshotId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * A Snapshot is a saved state of a Sandbox that can be used to create new Sandboxes\n *\n * Use {@link Sandbox.snapshot} or {@link Snapshot.get} to construct.\n * @hideconstructor\n */\nexport class Snapshot {\n private readonly client: APIClient;\n\n /**\n * Unique ID of this snapshot.\n */\n public get snapshotId(): string {\n return this.snapshot.id;\n }\n\n /**\n * The ID the sandbox from which this snapshot was created.\n */\n public get sourceSandboxId(): string {\n return this.snapshot.sourceSandboxId;\n }\n\n /**\n * The status of the snapshot.\n */\n public get status(): SnapshotMetadata[\"status\"] {\n return this.snapshot.status;\n }\n\n /**\n * The size of the snapshot in bytes, or null if not available.\n */\n public get sizeBytes(): number {\n return this.snapshot.sizeBytes;\n }\n\n /**\n * The creation date of this snapshot.\n */\n public get createdAt(): Date {\n return new Date(this.snapshot.createdAt);\n }\n\n /**\n * The expiration date of this snapshot, or undefined if it does not expire.\n */\n public get expiresAt(): Date | undefined {\n if (this.snapshot.expiresAt === undefined) {\n return undefined;\n }\n\n return new Date(this.snapshot.expiresAt);\n }\n\n /**\n * Internal metadata about this snapshot.\n */\n private snapshot: SnapshotMetadata;\n\n /**\n * Create a new Snapshot instance.\n *\n * @param client - API client used to communicate with the backend\n * @param snapshot - Snapshot metadata\n */\n constructor({\n client,\n snapshot,\n }: {\n client: APIClient;\n snapshot: SnapshotMetadata;\n }) {\n this.client = client;\n this.snapshot = snapshot;\n }\n\n /**\n * Allow to get a list of snapshots for a team narrowed to the given params.\n * It returns both the snapshots and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSnapshots\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSnapshots({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Retrieve an existing snapshot.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: GetSnapshotParams | (GetSnapshotParams & Credentials),\n ): Promise<Snapshot> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n\n const sandbox = await client.getSnapshot({\n snapshotId: params.snapshotId,\n signal: params.signal,\n });\n\n return new Snapshot({\n client,\n snapshot: sandbox.json.snapshot,\n });\n }\n\n /**\n * Delete this snapshot.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves once the snapshot has been deleted.\n */\n async delete(opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const response = await this.client!.deleteSnapshot({\n snapshotId: this.snapshot.id,\n signal: opts?.signal,\n });\n\n this.snapshot = response.json.snapshot;\n }\n}\n"],"mappings":";;;;;;;;;;;AAuBA,IAAa,WAAb,MAAa,SAAS;;;;CAMpB,IAAW,aAAqB;AAC9B,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,kBAA0B;AACnC,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,SAAqC;AAC9C,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,YAAoB;AAC7B,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,YAAkB;AAC3B,SAAO,IAAI,KAAK,KAAK,SAAS,UAAU;;;;;CAM1C,IAAW,YAA8B;AACvC,MAAI,KAAK,SAAS,cAAc,OAC9B;AAGF,SAAO,IAAI,KAAK,KAAK,SAAS,UAAU;;;;;;;;CAc1C,YAAY,EACV,QACA,YAIC;AACD,OAAK,SAAS;AACd,OAAK,WAAW;;;;;;;CAQlB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAMA,uCAAe,OAAO;AAMhD,SALe,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC,CACY,cAAc;GAC1B,GAAG;GACH,GAAG;GACJ,CAAC;;;;;;;;CASJ,aAAa,IACX,QACmB;AACnB;EACA,MAAM,cAAc,MAAMD,uCAAe,OAAO;EAChD,MAAM,SAAS,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AAOF,SAAO,IAAI,SAAS;GAClB;GACA,WAPc,MAAM,OAAO,YAAY;IACvC,YAAY,OAAO;IACnB,QAAQ,OAAO;IAChB,CAAC,EAIkB,KAAK;GACxB,CAAC;;;;;;;;;CAUJ,MAAM,OAAO,MAAgD;AAC3D;AAMA,OAAK,YALY,MAAM,KAAK,OAAQ,eAAe;GACjD,YAAY,KAAK,SAAS;GAC1B,QAAQ,MAAM;GACf,CAAC,EAEuB,KAAK"}
1
+ {"version":3,"file":"snapshot.cjs","names":["getCredentials","APIClient","WORKFLOW_SERIALIZE","WORKFLOW_DESERIALIZE"],"sources":["../src/snapshot.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport type { WithFetchOptions } from \"./api-client/api-client.js\";\nimport type { SnapshotMetadata } from \"./api-client/index.js\";\nimport { APIClient } from \"./api-client/index.js\";\nimport { type Credentials, getCredentials } from \"./utils/get-credentials.js\";\n\nexport interface SerializedSnapshot {\n snapshot: SnapshotMetadata;\n}\n\n/** @inline */\ninterface GetSnapshotParams {\n /**\n * Unique identifier of the snapshot.\n */\n snapshotId: string;\n /**\n * An AbortSignal to cancel the operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * A Snapshot is a saved state of a Sandbox that can be used to create new Sandboxes\n *\n * Use {@link Sandbox.snapshot} or {@link Snapshot.get} to construct.\n * @hideconstructor\n */\nexport class Snapshot {\n private _client: APIClient | null = null;\n\n /**\n * Lazily resolve credentials and construct an API client.\n * This is used in step contexts where the Snapshot was deserialized\n * without a client (e.g. when crossing workflow/step boundaries).\n * @internal\n */\n private async ensureClient(): Promise<APIClient> {\n \"use step\";\n if (this._client) return this._client;\n const credentials = await getCredentials();\n this._client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n return this._client;\n }\n\n /**\n * Unique ID of this snapshot.\n */\n public get snapshotId(): string {\n return this.snapshot.id;\n }\n\n /**\n * The ID the sandbox from which this snapshot was created.\n */\n public get sourceSandboxId(): string {\n return this.snapshot.sourceSandboxId;\n }\n\n /**\n * The status of the snapshot.\n */\n public get status(): SnapshotMetadata[\"status\"] {\n return this.snapshot.status;\n }\n\n /**\n * The size of the snapshot in bytes, or null if not available.\n */\n public get sizeBytes(): number {\n return this.snapshot.sizeBytes;\n }\n\n /**\n * The creation date of this snapshot.\n */\n public get createdAt(): Date {\n return new Date(this.snapshot.createdAt);\n }\n\n /**\n * The expiration date of this snapshot, or undefined if it does not expire.\n */\n public get expiresAt(): Date | undefined {\n if (this.snapshot.expiresAt === undefined) {\n return undefined;\n }\n\n return new Date(this.snapshot.expiresAt);\n }\n\n /**\n * Internal metadata about this snapshot.\n */\n private snapshot: SnapshotMetadata;\n\n /**\n * Serialize a Snapshot instance to plain data for @workflow/serde.\n *\n * @param instance - The Snapshot instance to serialize\n * @returns A plain object containing snapshot metadata\n */\n static [WORKFLOW_SERIALIZE](instance: Snapshot): SerializedSnapshot {\n return {\n snapshot: instance.snapshot,\n };\n }\n\n /**\n * Deserialize a Snapshot from serialized data.\n *\n * The deserialized instance uses the serialized metadata synchronously and\n * lazily creates an API client only when methods perform API requests.\n *\n * @param data - The serialized snapshot data\n * @returns The reconstructed Snapshot instance\n */\n static [WORKFLOW_DESERIALIZE](data: SerializedSnapshot): Snapshot {\n return new Snapshot({\n snapshot: data.snapshot,\n });\n }\n\n constructor({\n client,\n snapshot,\n }: {\n client?: APIClient;\n snapshot: SnapshotMetadata;\n }) {\n this._client = client ?? null;\n this.snapshot = snapshot;\n }\n\n /**\n * Allow to get a list of snapshots for a team narrowed to the given params.\n * It returns both the snapshots and the pagination metadata to allow getting\n * the next page of results.\n */\n static async list(\n params?: Partial<Parameters<APIClient[\"listSnapshots\"]>[0]> &\n Partial<Credentials> &\n WithFetchOptions,\n ) {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: params?.fetch,\n });\n return client.listSnapshots({\n ...credentials,\n ...params,\n });\n }\n\n /**\n * Retrieve an existing snapshot.\n *\n * @param params - Get parameters and optional credentials.\n * @returns A promise resolving to the {@link Sandbox}.\n */\n static async get(\n params: GetSnapshotParams | (GetSnapshotParams & Credentials),\n ): Promise<Snapshot> {\n \"use step\";\n const credentials = await getCredentials(params);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n });\n\n const sandbox = await client.getSnapshot({\n snapshotId: params.snapshotId,\n signal: params.signal,\n });\n\n return new Snapshot({\n client,\n snapshot: sandbox.json.snapshot,\n });\n }\n\n /**\n * Delete this snapshot.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns A promise that resolves once the snapshot has been deleted.\n */\n async delete(opts?: { signal?: AbortSignal }): Promise<void> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.deleteSnapshot({\n snapshotId: this.snapshot.id,\n signal: opts?.signal,\n });\n\n this.snapshot = response.json.snapshot;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA4BA,IAAa,WAAb,MAAa,SAAS;;;;;;;CASpB,MAAc,eAAmC;AAC/C;AACA,MAAI,KAAK,QAAS,QAAO,KAAK;EAC9B,MAAM,cAAc,MAAMA,wCAAgB;AAC1C,OAAK,UAAU,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AACF,SAAO,KAAK;;;;;CAMd,IAAW,aAAqB;AAC9B,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,kBAA0B;AACnC,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,SAAqC;AAC9C,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,YAAoB;AAC7B,SAAO,KAAK,SAAS;;;;;CAMvB,IAAW,YAAkB;AAC3B,SAAO,IAAI,KAAK,KAAK,SAAS,UAAU;;;;;CAM1C,IAAW,YAA8B;AACvC,MAAI,KAAK,SAAS,cAAc,OAC9B;AAGF,SAAO,IAAI,KAAK,KAAK,SAAS,UAAU;;;;;;;;CAc1C,QAAQC,qCAAoB,UAAwC;AAClE,SAAO,EACL,UAAU,SAAS,UACpB;;;;;;;;;;;CAYH,QAAQC,uCAAsB,MAAoC;AAChE,SAAO,IAAI,SAAS,EAClB,UAAU,KAAK,UAChB,CAAC;;CAGJ,YAAY,EACV,QACA,YAIC;OAvGK,UAA4B;AAwGlC,OAAK,UAAU,UAAU;AACzB,OAAK,WAAW;;;;;;;CAQlB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAMH,uCAAe,OAAO;AAMhD,SALe,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC,CACY,cAAc;GAC1B,GAAG;GACH,GAAG;GACJ,CAAC;;;;;;;;CASJ,aAAa,IACX,QACmB;AACnB;EACA,MAAM,cAAc,MAAMD,uCAAe,OAAO;EAChD,MAAM,SAAS,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACpB,CAAC;AAOF,SAAO,IAAI,SAAS;GAClB;GACA,WAPc,MAAM,OAAO,YAAY;IACvC,YAAY,OAAO;IACnB,QAAQ,OAAO;IAChB,CAAC,EAIkB,KAAK;GACxB,CAAC;;;;;;;;;CAUJ,MAAM,OAAO,MAAgD;AAC3D;AAOA,OAAK,YALY,OADF,MAAM,KAAK,cAAc,EACV,eAAe;GAC3C,YAAY,KAAK,SAAS;GAC1B,QAAQ,MAAM;GACf,CAAC,EAEuB,KAAK"}
@@ -2,8 +2,12 @@ import { Parsed } from "./api-client/base-client.cjs";
2
2
  import { SnapshotMetadata } from "./api-client/validators.cjs";
3
3
  import { APIClient, WithFetchOptions } from "./api-client/api-client.cjs";
4
4
  import { Credentials } from "./utils/get-credentials.cjs";
5
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
5
6
 
6
7
  //#region src/snapshot.d.ts
8
+ interface SerializedSnapshot {
9
+ snapshot: SnapshotMetadata;
10
+ }
7
11
  /** @inline */
8
12
  interface GetSnapshotParams {
9
13
  /**
@@ -22,7 +26,14 @@ interface GetSnapshotParams {
22
26
  * @hideconstructor
23
27
  */
24
28
  declare class Snapshot {
25
- private readonly client;
29
+ private _client;
30
+ /**
31
+ * Lazily resolve credentials and construct an API client.
32
+ * This is used in step contexts where the Snapshot was deserialized
33
+ * without a client (e.g. when crossing workflow/step boundaries).
34
+ * @internal
35
+ */
36
+ private ensureClient;
26
37
  /**
27
38
  * Unique ID of this snapshot.
28
39
  */
@@ -52,16 +63,27 @@ declare class Snapshot {
52
63
  */
53
64
  private snapshot;
54
65
  /**
55
- * Create a new Snapshot instance.
66
+ * Serialize a Snapshot instance to plain data for @workflow/serde.
67
+ *
68
+ * @param instance - The Snapshot instance to serialize
69
+ * @returns A plain object containing snapshot metadata
70
+ */
71
+ static [WORKFLOW_SERIALIZE](instance: Snapshot): SerializedSnapshot;
72
+ /**
73
+ * Deserialize a Snapshot from serialized data.
74
+ *
75
+ * The deserialized instance uses the serialized metadata synchronously and
76
+ * lazily creates an API client only when methods perform API requests.
56
77
  *
57
- * @param client - API client used to communicate with the backend
58
- * @param snapshot - Snapshot metadata
78
+ * @param data - The serialized snapshot data
79
+ * @returns The reconstructed Snapshot instance
59
80
  */
81
+ static [WORKFLOW_DESERIALIZE](data: SerializedSnapshot): Snapshot;
60
82
  constructor({
61
83
  client,
62
84
  snapshot
63
85
  }: {
64
- client: APIClient;
86
+ client?: APIClient;
65
87
  snapshot: SnapshotMetadata;
66
88
  });
67
89
  /**
@@ -105,5 +127,5 @@ declare class Snapshot {
105
127
  }): Promise<void>;
106
128
  }
107
129
  //#endregion
108
- export { Snapshot };
130
+ export { SerializedSnapshot, Snapshot };
109
131
  //# sourceMappingURL=snapshot.d.cts.map