@vercel/sandbox 2.0.0-beta.19 → 2.0.0-beta.20

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.
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":["params: RunCommandParams","command","path"],"sources":["../src/session.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { type SessionMetaData, type SandboxRouteData, type SandboxMetaData, type SnapshotMetadata, APIClient } from \"./api-client/index.js\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { toSandboxSnapshot, type SandboxSnapshot } from \"./utils/sandbox-snapshot.js\";\nimport { getCredentials } from \"./utils/get-credentials.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/**\n * Serialized representation of a Session for @workflow/serde.\n */\nexport interface SerializedSession {\n session: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\nexport interface 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 * A Session represents a running VM instance within a {@link Sandbox}.\n *\n * Obtain a session via {@link Sandbox.currentSession}.\n */\nexport class Session {\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 * Internal metadata about the current session.\n */\n private session: SandboxSnapshot;\n\n private get client(): APIClient {\n if (!this._client) throw new Error(\"API client not initialized\");\n return this._client;\n }\n\n /** @internal */\n get _sessionSnapshot(): SandboxSnapshot {\n return this.session;\n }\n\n /**\n * Unique ID of this session.\n */\n public get sessionId(): string {\n return this.session.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.session.interactivePort ?? undefined;\n }\n\n /**\n * The status of this session.\n */\n public get status(): SessionMetaData[\"status\"] {\n return this.session.status;\n }\n\n /**\n * The creation date of this session.\n */\n public get createdAt(): Date {\n return new Date(this.session.createdAt);\n }\n\n /**\n * The timeout of this session in milliseconds.\n */\n public get timeout(): number {\n return this.session.timeout;\n }\n\n /**\n * The network policy of this session.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.session.networkPolicy;\n }\n\n /**\n * If the session was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.session.sourceSnapshotId;\n }\n\n /**\n * Memory allocated to this session in MB.\n */\n public get memory(): number {\n return this.session.memory;\n }\n\n /**\n * Number of vCPUs allocated to this session.\n */\n public get vcpus(): number {\n return this.session.vcpus;\n }\n\n /**\n * The region where this session is hosted.\n */\n public get region(): string {\n return this.session.region;\n }\n\n /**\n * Runtime identifier (e.g. \"node24\", \"python3.13\").\n */\n public get runtime(): string {\n return this.session.runtime;\n }\n\n /**\n * The working directory of this session.\n */\n public get cwd(): string {\n return this.session.cwd;\n }\n\n /**\n * When this session was requested.\n */\n public get requestedAt(): Date {\n return new Date(this.session.requestedAt);\n }\n\n /**\n * When this session started running.\n */\n public get startedAt(): Date | undefined {\n return this.session.startedAt != null\n ? new Date(this.session.startedAt)\n : undefined;\n }\n\n /**\n * When this session was requested to stop.\n */\n public get requestedStopAt(): Date | undefined {\n return this.session.requestedStopAt != null\n ? new Date(this.session.requestedStopAt)\n : undefined;\n }\n\n /**\n * When this session was stopped.\n */\n public get stoppedAt(): Date | undefined {\n return this.session.stoppedAt != null\n ? new Date(this.session.stoppedAt)\n : undefined;\n }\n\n /**\n * When this session was aborted.\n */\n public get abortedAt(): Date | undefined {\n return this.session.abortedAt != null\n ? new Date(this.session.abortedAt)\n : undefined;\n }\n\n /**\n * The wall-clock duration of this session in milliseconds.\n */\n public get duration(): number | undefined {\n return this.session.duration;\n }\n\n /**\n * When a snapshot was requested for this session.\n */\n public get snapshottedAt(): Date | undefined {\n return this.session.snapshottedAt != null\n ? new Date(this.session.snapshottedAt)\n : undefined;\n }\n\n /**\n * When this session was last updated.\n */\n public get updatedAt(): Date {\n return new Date(this.session.updatedAt);\n }\n\n /**\n * The amount of active CPU used by the session. Only reported once the VM is\n * stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.session.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the session. Only reported once the VM\n * is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.session.networkTransfer;\n }\n\n /**\n * Serialize a Session instance to plain data for @workflow/serde.\n *\n * Although Sandbox handles top-level serialization, Session needs these\n * methods so the Workflow SWC compiler can resolve the class by name.\n * The `new Session(...)` self-reference in WORKFLOW_DESERIALIZE forces\n * rolldown to preserve the class name in the compiled output.\n */\n static [WORKFLOW_SERIALIZE](instance: Session): SerializedSession {\n return {\n session: instance.session,\n routes: instance.routes,\n };\n }\n\n static [WORKFLOW_DESERIALIZE](data: SerializedSession): Session {\n return new Session({ routes: data.routes, snapshot: data.session });\n }\n\n constructor(params: {\n client: APIClient;\n routes: SandboxRouteData[];\n session: SessionMetaData;\n } | {\n /** @internal – used during deserialization with an already-converted snapshot */\n routes: SandboxRouteData[];\n snapshot: SandboxSnapshot;\n }) {\n this.routes = params.routes;\n if (\"snapshot\" in params) {\n this.session = params.snapshot;\n } else {\n this._client = params.client;\n this.session = toSandboxSnapshot(params.session);\n }\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 sessionId: this.session.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sessionId: this.session.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this session.\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 session.\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 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 sessionId: this.session.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 sessionId: this.session.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 sessionId: this.session.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sessionId: this.session.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 sessionId: this.session.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 session.\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 sessionId: this.session.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this session 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 sessionId: this.session.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 session 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 sessionId: this.session.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 session to the local filesystem.\n *\n * @param src - Source file on the session, 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 sessionId: this.session.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 session.\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 and stream/buffer contents\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 async writeFiles(\n files: { path: string; content: string | Uint8Array; mode?: number }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sessionId: this.session.id,\n cwd: this.session.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this session.\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 this session.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The final session state and optional sandbox metadata.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n }): Promise<{ session: SandboxSnapshot; sandbox?: SandboxMetaData; snapshot?: SnapshotMetadata }> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSession({\n sessionId: this.session.id,\n signal: opts?.signal,\n });\n this.session = toSandboxSnapshot(response.json.session);\n return { session: this.session, sandbox: response.json.sandbox, snapshot: response.json.snapshot };\n }\n\n /**\n * Update the current session's settings.\n *\n * @param params - Fields to update.\n * @param params.networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n *\n * @example\n * // Restrict to specific domains\n * await session.update({\n * networkPolicy: {\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * }\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await session.update({\n * networkPolicy: {\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await session.update({ networkPolicy: \"deny-all\" });\n */\n async update(\n params: {\n networkPolicy?: NetworkPolicy;\n },\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n if (params.networkPolicy !== undefined) {\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sessionId: this.session.id,\n networkPolicy: params.networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal session with the new network policy\n this.session = toSandboxSnapshot(response.json.session);\n }\n }\n\n /**\n * Extend the timeout of the session by the specified duration.\n *\n * This allows you to extend the lifetime of a session 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 * const session = sandbox.currentSession();\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await session.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 sessionId: this.session.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.session = toSandboxSnapshot(response.json.session);\n }\n\n /**\n * Create a snapshot from this currently running session. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.create}.\n *\n * Note: this session 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 sessionId: this.session.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.session = toSandboxSnapshot(response.json.session);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyEA,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;;CAcd,IAAY,SAAoB;AAC9B,MAAI,CAAC,KAAK,QAAS,OAAM,IAAI,MAAM,6BAA6B;AAChE,SAAO,KAAK;;;CAId,IAAI,mBAAoC;AACtC,SAAO,KAAK;;;;;CAMd,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,SAAiB;AAC1B,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,QAAgB;AACzB,SAAO,KAAK,QAAQ;;;;;CAMtB,IAAW,SAAiB;AAC1B,SAAO,KAAK,QAAQ;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCpG,MAAM,OACJ,QAGA,MACe;AACf;AACA,MAAI,OAAO,kBAAkB,OAS3B,MAAK,UAAU,mBAPE,OADF,MAAM,KAAK,cAAc,EACV,oBAAoB;GAChD,WAAW,KAAK,QAAQ;GACxB,eAAe,OAAO;GACtB,QAAQ,MAAM;GACf,CAAC,EAGwC,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;CAqB3D,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"}
1
+ {"version":3,"file":"session.js","names":["params: RunCommandParams","command","path"],"sources":["../src/session.ts"],"sourcesContent":["import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\nimport { type SessionMetaData, type SandboxRouteData, type SandboxMetaData, type SnapshotMetadata, APIClient } from \"./api-client/index.js\";\nimport type { Writable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, resolve } from \"path\";\nimport { Command, CommandFinished } from \"./command.js\";\nimport { Snapshot } from \"./snapshot.js\";\nimport { consumeReadable } from \"./utils/consume-readable.js\";\nimport type {\n NetworkPolicy,\n NetworkPolicyRule,\n NetworkTransformer,\n} from \"./network-policy.js\";\nimport { toSandboxSnapshot, type SandboxSnapshot } from \"./utils/sandbox-snapshot.js\";\nimport { getCredentials } from \"./utils/get-credentials.js\";\n\nexport type { NetworkPolicy, NetworkPolicyRule, NetworkTransformer };\n\n/**\n * Serialized representation of a Session for @workflow/serde.\n */\nexport interface SerializedSession {\n session: SandboxSnapshot;\n routes: SandboxRouteData[];\n}\n\n/** @inline */\nexport interface 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 * A Session represents a running VM instance within a {@link Sandbox}.\n *\n * Obtain a session via {@link Sandbox.currentSession}.\n */\nexport class Session {\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 * Internal metadata about the current session.\n */\n private session: SandboxSnapshot;\n\n private get client(): APIClient {\n if (!this._client) throw new Error(\"API client not initialized\");\n return this._client;\n }\n\n /** @internal */\n get _sessionSnapshot(): SandboxSnapshot {\n return this.session;\n }\n\n /**\n * Unique ID of this session.\n */\n public get sessionId(): string {\n return this.session.id;\n }\n\n public get interactivePort(): number | undefined {\n return this.session.interactivePort ?? undefined;\n }\n\n /**\n * The status of this session.\n */\n public get status(): SessionMetaData[\"status\"] {\n return this.session.status;\n }\n\n /**\n * The creation date of this session.\n */\n public get createdAt(): Date {\n return new Date(this.session.createdAt);\n }\n\n /**\n * The timeout of this session in milliseconds.\n */\n public get timeout(): number {\n return this.session.timeout;\n }\n\n /**\n * The network policy of this session.\n */\n public get networkPolicy(): NetworkPolicy | undefined {\n return this.session.networkPolicy;\n }\n\n /**\n * If the session was created from a snapshot, the ID of that snapshot.\n */\n public get sourceSnapshotId(): string | undefined {\n return this.session.sourceSnapshotId;\n }\n\n /**\n * Memory allocated to this session in MB.\n */\n public get memory(): number {\n return this.session.memory;\n }\n\n /**\n * Number of vCPUs allocated to this session.\n */\n public get vcpus(): number {\n return this.session.vcpus;\n }\n\n /**\n * The region where this session is hosted.\n */\n public get region(): string {\n return this.session.region;\n }\n\n /**\n * Runtime identifier (e.g. \"node24\", \"python3.13\").\n */\n public get runtime(): string {\n return this.session.runtime;\n }\n\n /**\n * The working directory of this session.\n */\n public get cwd(): string {\n return this.session.cwd;\n }\n\n /**\n * When this session was requested.\n */\n public get requestedAt(): Date {\n return new Date(this.session.requestedAt);\n }\n\n /**\n * When this session started running.\n */\n public get startedAt(): Date | undefined {\n return this.session.startedAt != null\n ? new Date(this.session.startedAt)\n : undefined;\n }\n\n /**\n * When this session was requested to stop.\n */\n public get requestedStopAt(): Date | undefined {\n return this.session.requestedStopAt != null\n ? new Date(this.session.requestedStopAt)\n : undefined;\n }\n\n /**\n * When this session was stopped.\n */\n public get stoppedAt(): Date | undefined {\n return this.session.stoppedAt != null\n ? new Date(this.session.stoppedAt)\n : undefined;\n }\n\n /**\n * When this session was aborted.\n */\n public get abortedAt(): Date | undefined {\n return this.session.abortedAt != null\n ? new Date(this.session.abortedAt)\n : undefined;\n }\n\n /**\n * The wall-clock duration of this session in milliseconds.\n */\n public get duration(): number | undefined {\n return this.session.duration;\n }\n\n /**\n * When a snapshot was requested for this session.\n */\n public get snapshottedAt(): Date | undefined {\n return this.session.snapshottedAt != null\n ? new Date(this.session.snapshottedAt)\n : undefined;\n }\n\n /**\n * When this session was last updated.\n */\n public get updatedAt(): Date {\n return new Date(this.session.updatedAt);\n }\n\n /**\n * The amount of active CPU used by the session. Only reported once the VM is\n * stopped.\n */\n public get activeCpuUsageMs(): number | undefined {\n return this.session.activeCpuDurationMs;\n }\n\n /**\n * The amount of network data used by the session. Only reported once the VM\n * is stopped.\n */\n public get networkTransfer():\n | { ingress: number; egress: number }\n | undefined {\n return this.session.networkTransfer;\n }\n\n /**\n * Serialize a Session instance to plain data for @workflow/serde.\n *\n * Although Sandbox handles top-level serialization, Session needs these\n * methods so the Workflow SWC compiler can resolve the class by name.\n * The `new Session(...)` self-reference in WORKFLOW_DESERIALIZE forces\n * rolldown to preserve the class name in the compiled output.\n */\n static [WORKFLOW_SERIALIZE](instance: Session): SerializedSession {\n return {\n session: instance.session,\n routes: instance.routes,\n };\n }\n\n static [WORKFLOW_DESERIALIZE](data: SerializedSession): Session {\n return new Session({ routes: data.routes, snapshot: data.session });\n }\n\n constructor(params: {\n client: APIClient;\n routes: SandboxRouteData[];\n session: SessionMetaData;\n } | {\n /** @internal – used during deserialization with an already-converted snapshot */\n routes: SandboxRouteData[];\n snapshot: SandboxSnapshot;\n }) {\n this.routes = params.routes;\n if (\"snapshot\" in params) {\n this.session = params.snapshot;\n } else {\n this._client = params.client;\n this.session = toSandboxSnapshot(params.session);\n }\n }\n\n /** @internal */\n updateRoutes(routes: SandboxRouteData[]): void {\n (this as { routes: SandboxRouteData[] }).routes = routes;\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 sessionId: this.session.id,\n cmdId,\n signal: opts?.signal,\n });\n\n return new Command({\n client,\n sessionId: this.session.id,\n cmd: command.json.command,\n });\n }\n\n /**\n * Start executing a command in this session.\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 session.\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 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 sessionId: this.session.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 sessionId: this.session.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 sessionId: this.session.id,\n cmd: finished,\n exitCode: finished.exitCode ?? 0,\n });\n }\n\n const commandResponse = await client.runCommand({\n sessionId: this.session.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 sessionId: this.session.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 session.\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 sessionId: this.session.id,\n path: path,\n signal: opts?.signal,\n });\n }\n\n /**\n * Read a file from the filesystem of this session 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 sessionId: this.session.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 session 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 sessionId: this.session.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 session to the local filesystem.\n *\n * @param src - Source file on the session, 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 sessionId: this.session.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 session.\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 and stream/buffer contents\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 async writeFiles(\n files: { path: string; content: string | Uint8Array; mode?: number }[],\n opts?: { signal?: AbortSignal },\n ) {\n \"use step\";\n const client = await this.ensureClient();\n return client.writeFiles({\n sessionId: this.session.id,\n cwd: this.session.cwd,\n extractDir: \"/\",\n files: files,\n signal: opts?.signal,\n });\n }\n\n /**\n * Get the public domain of a port of this session.\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 this session.\n *\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n * @returns The final session state and optional sandbox metadata.\n */\n async stop(opts?: {\n signal?: AbortSignal;\n }): Promise<{ session: SandboxSnapshot; sandbox?: SandboxMetaData; snapshot?: SnapshotMetadata }> {\n \"use step\";\n const client = await this.ensureClient();\n const response = await client.stopSession({\n sessionId: this.session.id,\n signal: opts?.signal,\n });\n this.session = toSandboxSnapshot(response.json.session);\n return { session: this.session, sandbox: response.json.sandbox, snapshot: response.json.snapshot };\n }\n\n /**\n * Update the current session's settings.\n *\n * @param params - Fields to update.\n * @param params.networkPolicy - The new network policy to apply.\n * @param opts - Optional parameters.\n * @param opts.signal - An AbortSignal to cancel the operation.\n *\n * @example\n * // Restrict to specific domains\n * await session.update({\n * networkPolicy: {\n * allow: [\"*.npmjs.org\", \"github.com\"],\n * }\n * });\n *\n * @example\n * // Inject credentials with per-domain transformers\n * await session.update({\n * networkPolicy: {\n * allow: {\n * \"ai-gateway.vercel.sh\": [{\n * transform: [{\n * headers: { authorization: \"Bearer ...\" }\n * }]\n * }],\n * \"*\": []\n * }\n * }\n * });\n *\n * @example\n * // Deny all network access\n * await session.update({ networkPolicy: \"deny-all\" });\n */\n async update(\n params: {\n networkPolicy?: NetworkPolicy;\n },\n opts?: { signal?: AbortSignal },\n ): Promise<void> {\n \"use step\";\n if (params.networkPolicy !== undefined) {\n const client = await this.ensureClient();\n const response = await client.updateNetworkPolicy({\n sessionId: this.session.id,\n networkPolicy: params.networkPolicy,\n signal: opts?.signal,\n });\n\n // Update the internal session with the new network policy\n this.session = toSandboxSnapshot(response.json.session);\n }\n }\n\n /**\n * Extend the timeout of the session by the specified duration.\n *\n * This allows you to extend the lifetime of a session 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 * const session = sandbox.currentSession();\n * // Extends timeout by 5 minutes, to a total of 15 minutes.\n * await session.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 sessionId: this.session.id,\n duration,\n signal: opts?.signal,\n });\n\n // Update the internal sandbox metadata with the new timeout value\n this.session = toSandboxSnapshot(response.json.session);\n }\n\n /**\n * Create a snapshot from this currently running session. New sandboxes can\n * then be created from this snapshot using {@link Sandbox.create}.\n *\n * Note: this session 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 sessionId: this.session.id,\n expiration: opts?.expiration,\n signal: opts?.signal,\n });\n\n this.session = toSandboxSnapshot(response.json.session);\n\n return new Snapshot({\n client,\n snapshot: response.json.snapshot,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyEA,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;A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;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"}
package/dist/snapshot.cjs CHANGED
@@ -128,6 +128,41 @@ var Snapshot = class Snapshot {
128
128
  });
129
129
  }
130
130
  /**
131
+ * Resolve the current snapshot ID of an existing sandbox by name.
132
+ *
133
+ * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without
134
+ * having to first look up the sandbox yourself.
135
+ *
136
+ * @param name - The name of the source sandbox.
137
+ * @param opts - Optional credentials, fetch override, and abort signal.
138
+ * @returns The current snapshot ID of the named sandbox.
139
+ * @throws If the sandbox has no current snapshot.
140
+ *
141
+ * @example
142
+ * const sandbox = await Sandbox.create({
143
+ * source: {
144
+ * type: "snapshot",
145
+ * snapshotId: await Snapshot.fromSandbox("my-sandbox"),
146
+ * },
147
+ * });
148
+ */
149
+ static async fromSandbox(name, opts) {
150
+ "use step";
151
+ const credentials = await require_get_credentials.getCredentials(opts);
152
+ const snapshotId = (await new require_api_client.APIClient({
153
+ teamId: credentials.teamId,
154
+ token: credentials.token,
155
+ fetch: opts?.fetch
156
+ }).getSandbox({
157
+ name,
158
+ projectId: credentials.projectId,
159
+ resume: false,
160
+ signal: opts?.signal
161
+ })).json.sandbox.currentSnapshotId;
162
+ if (!snapshotId) throw new Error(`Sandbox "${name}" has no current snapshot.`);
163
+ return snapshotId;
164
+ }
165
+ /**
131
166
  * Retrieve an existing snapshot.
132
167
  *
133
168
  * @param params - Get parameters and optional credentials.
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot.cjs","names":["getCredentials","APIClient","WORKFLOW_SERIALIZE","WORKFLOW_DESERIALIZE","attachPaginator"],"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\";\nimport { attachPaginator } from \"./utils/paginator.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 of the session from which this snapshot was created.\n */\n public get sourceSessionId(): string {\n return this.snapshot.sourceSessionId;\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 * The returned object is async-iterable to auto-paginate through all pages:\n *\n * ```ts\n * const result = await Snapshot.list({ name: \"my-sandbox\" });\n * for await (const snapshot of result) { ... }\n * // or: await result.toArray();\n * // or: for await (const page of result.pages()) { ... }\n * ```\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 const fetchPage = async (cursor?: string) => {\n const response = await client.listSnapshots({\n ...credentials,\n ...params,\n ...(cursor !== undefined && { cursor }),\n });\n return response.json;\n };\n const firstPage = await fetchPage(params?.cursor);\n return attachPaginator(firstPage, {\n itemsKey: \"snapshots\",\n fetchNext: fetchPage,\n signal: params?.signal,\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":";;;;;;;;;;;;;;AA6BA,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;;;;;;;;;;;;;;;;CAiBlB,aAAa,KACX,QAGA;AACA;EACA,MAAM,cAAc,MAAMH,uCAAe,OAAO;EAChD,MAAM,SAAS,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,QAAQ;GAChB,CAAC;EACF,MAAM,YAAY,OAAO,WAAoB;AAM3C,WALiB,MAAM,OAAO,cAAc;IAC1C,GAAG;IACH,GAAG;IACH,GAAI,WAAW,UAAa,EAAE,QAAQ;IACvC,CAAC,EACc;;AAGlB,SAAOG,kCADW,MAAM,UAAU,QAAQ,OAAO,EACf;GAChC,UAAU;GACV,WAAW;GACX,QAAQ,QAAQ;GACjB,CAAC;;;;;;;;CASJ,aAAa,IACX,QACmB;AACnB;EACA,MAAM,cAAc,MAAMJ,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"}
1
+ {"version":3,"file":"snapshot.cjs","names":["getCredentials","APIClient","WORKFLOW_SERIALIZE","WORKFLOW_DESERIALIZE","attachPaginator"],"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\";\nimport { attachPaginator } from \"./utils/paginator.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 of the session from which this snapshot was created.\n */\n public get sourceSessionId(): string {\n return this.snapshot.sourceSessionId;\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 * The returned object is async-iterable to auto-paginate through all pages:\n *\n * ```ts\n * const result = await Snapshot.list({ name: \"my-sandbox\" });\n * for await (const snapshot of result) { ... }\n * // or: await result.toArray();\n * // or: for await (const page of result.pages()) { ... }\n * ```\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 const fetchPage = async (cursor?: string) => {\n const response = await client.listSnapshots({\n ...credentials,\n ...params,\n ...(cursor !== undefined && { cursor }),\n });\n return response.json;\n };\n const firstPage = await fetchPage(params?.cursor);\n return attachPaginator(firstPage, {\n itemsKey: \"snapshots\",\n fetchNext: fetchPage,\n signal: params?.signal,\n });\n }\n\n /**\n * Resolve the current snapshot ID of an existing sandbox by name.\n *\n * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without\n * having to first look up the sandbox yourself.\n *\n * @param name - The name of the source sandbox.\n * @param opts - Optional credentials, fetch override, and abort signal.\n * @returns The current snapshot ID of the named sandbox.\n * @throws If the sandbox has no current snapshot.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * source: {\n * type: \"snapshot\",\n * snapshotId: await Snapshot.fromSandbox(\"my-sandbox\"),\n * },\n * });\n */\n static async fromSandbox(\n name: string,\n opts?: Partial<Credentials> & WithFetchOptions & { signal?: AbortSignal },\n ): Promise<string> {\n \"use step\";\n const credentials = await getCredentials(opts);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: opts?.fetch,\n });\n\n const response = await client.getSandbox({\n name,\n projectId: credentials.projectId,\n resume: false,\n signal: opts?.signal,\n });\n\n const snapshotId = response.json.sandbox.currentSnapshotId;\n if (!snapshotId) {\n throw new Error(`Sandbox \"${name}\" has no current snapshot.`);\n }\n return snapshotId;\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":";;;;;;;;;;;;;;AA6BA,I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EACf;GAChC,UAAU;GACV,WAAW;GACX,QAAQ,QAAQ;GACjB,CAAC;;;;;;;;;;;;;;;;;;;;;CAsBJ,aAAa,YACX,MACA,MACiB;AACjB;EACA,MAAM,cAAc,MAAMJ,uCAAe,KAAK;EAc9C,MAAM,cAPW,MANF,IAAIC,6BAAU;GAC3B,QAAQ,YAAY;GACpB,OAAO,YAAY;GACnB,OAAO,MAAM;GACd,CAAC,CAE4B,WAAW;GACvC;GACA,WAAW,YAAY;GACvB,QAAQ;GACR,QAAQ,MAAM;GACf,CAAC,EAE0B,KAAK,QAAQ;AACzC,MAAI,CAAC,WACH,OAAM,IAAI,MAAM,YAAY,KAAK,4BAA4B;AAE/D,SAAO;;;;;;;;CAST,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"}
@@ -116,6 +116,28 @@ declare class Snapshot {
116
116
  expiresAt?: number | undefined;
117
117
  }[];
118
118
  }, "snapshots">>;
119
+ /**
120
+ * Resolve the current snapshot ID of an existing sandbox by name.
121
+ *
122
+ * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without
123
+ * having to first look up the sandbox yourself.
124
+ *
125
+ * @param name - The name of the source sandbox.
126
+ * @param opts - Optional credentials, fetch override, and abort signal.
127
+ * @returns The current snapshot ID of the named sandbox.
128
+ * @throws If the sandbox has no current snapshot.
129
+ *
130
+ * @example
131
+ * const sandbox = await Sandbox.create({
132
+ * source: {
133
+ * type: "snapshot",
134
+ * snapshotId: await Snapshot.fromSandbox("my-sandbox"),
135
+ * },
136
+ * });
137
+ */
138
+ static fromSandbox(name: string, opts?: Partial<Credentials> & WithFetchOptions & {
139
+ signal?: AbortSignal;
140
+ }): Promise<string>;
119
141
  /**
120
142
  * Retrieve an existing snapshot.
121
143
  *
@@ -117,6 +117,28 @@ declare class Snapshot {
117
117
  expiresAt?: number | undefined;
118
118
  }[];
119
119
  }, "snapshots">>;
120
+ /**
121
+ * Resolve the current snapshot ID of an existing sandbox by name.
122
+ *
123
+ * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without
124
+ * having to first look up the sandbox yourself.
125
+ *
126
+ * @param name - The name of the source sandbox.
127
+ * @param opts - Optional credentials, fetch override, and abort signal.
128
+ * @returns The current snapshot ID of the named sandbox.
129
+ * @throws If the sandbox has no current snapshot.
130
+ *
131
+ * @example
132
+ * const sandbox = await Sandbox.create({
133
+ * source: {
134
+ * type: "snapshot",
135
+ * snapshotId: await Snapshot.fromSandbox("my-sandbox"),
136
+ * },
137
+ * });
138
+ */
139
+ static fromSandbox(name: string, opts?: Partial<Credentials> & WithFetchOptions & {
140
+ signal?: AbortSignal;
141
+ }): Promise<string>;
120
142
  /**
121
143
  * Retrieve an existing snapshot.
122
144
  *
package/dist/snapshot.js CHANGED
@@ -127,6 +127,41 @@ var Snapshot = class Snapshot {
127
127
  });
128
128
  }
129
129
  /**
130
+ * Resolve the current snapshot ID of an existing sandbox by name.
131
+ *
132
+ * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without
133
+ * having to first look up the sandbox yourself.
134
+ *
135
+ * @param name - The name of the source sandbox.
136
+ * @param opts - Optional credentials, fetch override, and abort signal.
137
+ * @returns The current snapshot ID of the named sandbox.
138
+ * @throws If the sandbox has no current snapshot.
139
+ *
140
+ * @example
141
+ * const sandbox = await Sandbox.create({
142
+ * source: {
143
+ * type: "snapshot",
144
+ * snapshotId: await Snapshot.fromSandbox("my-sandbox"),
145
+ * },
146
+ * });
147
+ */
148
+ static async fromSandbox(name, opts) {
149
+ "use step";
150
+ const credentials = await getCredentials(opts);
151
+ const snapshotId = (await new APIClient({
152
+ teamId: credentials.teamId,
153
+ token: credentials.token,
154
+ fetch: opts?.fetch
155
+ }).getSandbox({
156
+ name,
157
+ projectId: credentials.projectId,
158
+ resume: false,
159
+ signal: opts?.signal
160
+ })).json.sandbox.currentSnapshotId;
161
+ if (!snapshotId) throw new Error(`Sandbox "${name}" has no current snapshot.`);
162
+ return snapshotId;
163
+ }
164
+ /**
130
165
  * Retrieve an existing snapshot.
131
166
  *
132
167
  * @param params - Get parameters and optional credentials.
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot.js","names":[],"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\";\nimport { attachPaginator } from \"./utils/paginator.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 of the session from which this snapshot was created.\n */\n public get sourceSessionId(): string {\n return this.snapshot.sourceSessionId;\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 * The returned object is async-iterable to auto-paginate through all pages:\n *\n * ```ts\n * const result = await Snapshot.list({ name: \"my-sandbox\" });\n * for await (const snapshot of result) { ... }\n * // or: await result.toArray();\n * // or: for await (const page of result.pages()) { ... }\n * ```\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 const fetchPage = async (cursor?: string) => {\n const response = await client.listSnapshots({\n ...credentials,\n ...params,\n ...(cursor !== undefined && { cursor }),\n });\n return response.json;\n };\n const firstPage = await fetchPage(params?.cursor);\n return attachPaginator(firstPage, {\n itemsKey: \"snapshots\",\n fetchNext: fetchPage,\n signal: params?.signal,\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":";;;;;;;;;;;;;AA6BA,IAAa,WAAb,MAAa,SAAS;;;;;;;CASpB,MAAc,eAAmC;AAC/C;AACA,MAAI,KAAK,QAAS,QAAO,KAAK;EAC9B,MAAM,cAAc,MAAM,gBAAgB;AAC1C,OAAK,UAAU,IAAI,UAAU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3B,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"}
1
+ {"version":3,"file":"snapshot.js","names":[],"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\";\nimport { attachPaginator } from \"./utils/paginator.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 of the session from which this snapshot was created.\n */\n public get sourceSessionId(): string {\n return this.snapshot.sourceSessionId;\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 * The returned object is async-iterable to auto-paginate through all pages:\n *\n * ```ts\n * const result = await Snapshot.list({ name: \"my-sandbox\" });\n * for await (const snapshot of result) { ... }\n * // or: await result.toArray();\n * // or: for await (const page of result.pages()) { ... }\n * ```\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 const fetchPage = async (cursor?: string) => {\n const response = await client.listSnapshots({\n ...credentials,\n ...params,\n ...(cursor !== undefined && { cursor }),\n });\n return response.json;\n };\n const firstPage = await fetchPage(params?.cursor);\n return attachPaginator(firstPage, {\n itemsKey: \"snapshots\",\n fetchNext: fetchPage,\n signal: params?.signal,\n });\n }\n\n /**\n * Resolve the current snapshot ID of an existing sandbox by name.\n *\n * Useful to feed into {@link Sandbox.create} as `source.snapshotId` without\n * having to first look up the sandbox yourself.\n *\n * @param name - The name of the source sandbox.\n * @param opts - Optional credentials, fetch override, and abort signal.\n * @returns The current snapshot ID of the named sandbox.\n * @throws If the sandbox has no current snapshot.\n *\n * @example\n * const sandbox = await Sandbox.create({\n * source: {\n * type: \"snapshot\",\n * snapshotId: await Snapshot.fromSandbox(\"my-sandbox\"),\n * },\n * });\n */\n static async fromSandbox(\n name: string,\n opts?: Partial<Credentials> & WithFetchOptions & { signal?: AbortSignal },\n ): Promise<string> {\n \"use step\";\n const credentials = await getCredentials(opts);\n const client = new APIClient({\n teamId: credentials.teamId,\n token: credentials.token,\n fetch: opts?.fetch,\n });\n\n const response = await client.getSandbox({\n name,\n projectId: credentials.projectId,\n resume: false,\n signal: opts?.signal,\n });\n\n const snapshotId = response.json.sandbox.currentSnapshotId;\n if (!snapshotId) {\n throw new Error(`Sandbox \"${name}\" has no current snapshot.`);\n }\n return snapshotId;\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":";;;;;;;;;;;;;AA6BA,IAAa,WAAb,MAAa,SAAS;;;;;;;CASpB,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;;;;;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,QAAQ,oBAAoB,UAAwC;AAClE,SAAO,EACL,UAAU,SAAS,UACpB;;;;;;;;;;;CAYH,QAAQ,sBAAsB,MAAoC;AAChE,SAAO,IAAI,SAAS,EAClB,UAAU,KAAK,UAChB,CAAC;;CAGJ,YAAY,EACV,QACA,YAIC;OAvGK,UAA4B;AAwGlC,OAAK,UAA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1B,QAAQ,MAAM;GACf,CAAC,EAEuB,KAAK"}
package/dist/version.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  //#region src/version.ts
3
- const VERSION = "2.0.0-beta.19";
3
+ const VERSION = "2.0.0-beta.20";
4
4
 
5
5
  //#endregion
6
6
  exports.VERSION = VERSION;
@@ -1 +1 @@
1
- {"version":3,"file":"version.cjs","names":[],"sources":["../src/version.ts"],"sourcesContent":["// Autogenerated by inject-version.ts\nexport const VERSION = \"2.0.0-beta.19\";\n"],"mappings":";;AACA,MAAa,UAAU"}
1
+ {"version":3,"file":"version.cjs","names":[],"sources":["../src/version.ts"],"sourcesContent":["// Autogenerated by inject-version.ts\nexport const VERSION = \"2.0.0-beta.20\";\n"],"mappings":";;AACA,MAAa,UAAU"}
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region src/version.ts
2
- const VERSION = "2.0.0-beta.19";
2
+ const VERSION = "2.0.0-beta.20";
3
3
 
4
4
  //#endregion
5
5
  export { VERSION };
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["// Autogenerated by inject-version.ts\nexport const VERSION = \"2.0.0-beta.19\";\n"],"mappings":";AACA,MAAa,UAAU"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["// Autogenerated by inject-version.ts\nexport const VERSION = \"2.0.0-beta.20\";\n"],"mappings":";AACA,MAAa,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/sandbox",
3
- "version": "2.0.0-beta.19",
3
+ "version": "2.0.0-beta.20",
4
4
  "description": "Software Development Kit for Vercel Sandbox",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",