wbxsandbox 0.1.2 → 0.2.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.
package/src/index.ts CHANGED
@@ -26,6 +26,8 @@ export {
26
26
  Metrics,
27
27
  Computer,
28
28
  type SandboxCreateParams,
29
+ type CloneParams,
30
+ type CloneResult,
29
31
  type RunOptions,
30
32
  type RunCodeOptions,
31
33
  type FileData,
@@ -46,6 +48,7 @@ export {
46
48
  type WasmOptions,
47
49
  type WaitOptions,
48
50
  } from "./jobs.js";
51
+ export { Snapshot, Snapshots } from "./snapshots.js";
49
52
  export { Templates, BudgetResource, Compute, Webhooks, verifyWebhook } from "./account.js";
50
53
  export { Page } from "./pagination.js";
51
54
  export { SSEParser, readNDJSON, readSSE, type SSEEvent, type SSEParserOptions, type NDJSONOptions } from "./streams.js";
package/src/sandbox.ts CHANGED
@@ -10,12 +10,16 @@ import {
10
10
  NotFoundError,
11
11
  StreamLimitError,
12
12
  WBXError,
13
+ errorFromResponse,
13
14
  isAbortLike,
14
15
  } from "./errors.js";
15
16
  import type { RequestOptions, Transport } from "./http.js";
16
17
  import { backoffMs } from "./http.js";
17
18
  import { SSEParser, readNDJSON, readSSE } from "./streams.js";
19
+ import { Snapshot } from "./snapshots.js";
18
20
  import type {
21
+ CloneError,
22
+ CloneResponse,
19
23
  ComputerAction,
20
24
  ComputerActionResultEntry,
21
25
  ComputerActionsResult,
@@ -37,6 +41,7 @@ import type {
37
41
  SandboxMetrics,
38
42
  SandboxState,
39
43
  Screenshot,
44
+ SnapshotInfo,
40
45
  Signal,
41
46
  WatchEvent,
42
47
  WriteResult,
@@ -53,6 +58,12 @@ const DEFAULT_COMMAND_TIMEOUT_MS = 60_000;
53
58
  */
54
59
  const COMPUTER_ACTIONS_TIMEOUT_MS = 300_000;
55
60
  const EXEC_GRACE_MS = 30_000;
61
+ /** A snapshot without a reflink-capable disk copies the whole disk – allow up to 10 minutes. */
62
+ const SNAPSHOT_TIMEOUT_MS = 630_000;
63
+ /** A sandbox from a snapshot copies the snapshot's disk and restarts once with a new identity – allow 5 minutes. */
64
+ const FROM_SNAPSHOT_TIMEOUT_MS = 300_000;
65
+ // klon: snapshot (server ≤ ~620 s) + souběžné kopie (≤ ~230 s) + úklid ≈ 910 s
66
+ const CLONE_TIMEOUT_MS = 930_000;
56
67
 
57
68
  /** Options of {@link Sandboxes.create}. */
58
69
  export interface SandboxCreateParams {
@@ -89,6 +100,57 @@ export interface SandboxCreateParams {
89
100
  dependencyCache?: boolean;
90
101
  /** Network policy (only stricter than your team's policy) and IP version. */
91
102
  network?: NetworkOptions;
103
+ /**
104
+ * Start from the disk of one of your snapshots (`snap_…`, feature `snapshots`) instead of a
105
+ * fresh template disk. The sandbox gets the snapshot's template (leave `template` out), a new
106
+ * ID and network; env and settings come from these params, never from the snapshot.
107
+ */
108
+ fromSnapshot?: string;
109
+ }
110
+
111
+ /**
112
+ * Options of {@link Sandbox.clone}: the create options (without template) plus the count. Lifetime
113
+ * options, `computeClass` and `network` left out are taken from the source sandbox.
114
+ */
115
+ export interface CloneParams extends Omit<SandboxCreateParams, "template" | "fromSnapshot"> {
116
+ /** How many copies, 1–10 (default 1). */
117
+ count?: number;
118
+ /** Keep the snapshot the copies were started from (default: it is deleted afterwards). */
119
+ keepSnapshot?: boolean;
120
+ /** Name of the snapshot (same rules as a sandbox name); useful with `keepSnapshot`. */
121
+ snapshotName?: string;
122
+ }
123
+
124
+ /** Result of {@link Sandbox.clone}. */
125
+ export interface CloneResult {
126
+ /** The snapshot the copies were started from (deleted again unless `keepSnapshot`). */
127
+ snapshotId: string | undefined;
128
+ /** Whether the snapshot was kept (`keepSnapshot`); otherwise it has been deleted. */
129
+ snapshotKept: boolean;
130
+ /** The new sandboxes. */
131
+ sandboxes: Sandbox[];
132
+ /** One entry per copy that could not be created (`index` 0…count-1, `name`, `status`, `code`, `error`). */
133
+ errors: CloneError[];
134
+ }
135
+
136
+ /** @internal REST body of a create (also of a clone) from camelCase params. */
137
+ function createBody(params: Omit<SandboxCreateParams, "template" | "fromSnapshot">): Record<string, unknown> {
138
+ return compact({
139
+ timeout_s: params.timeoutSeconds,
140
+ name: params.name,
141
+ on_timeout: params.onTimeout,
142
+ idle_timeout_s: params.idleTimeoutSeconds,
143
+ keep_days: params.keepDays,
144
+ metadata: params.metadata,
145
+ env: params.env,
146
+ vcpu: params.vcpu,
147
+ mem_mb: params.memMb,
148
+ compute_class: params.computeClass,
149
+ optimize_for: params.optimizeFor,
150
+ placement: params.placement,
151
+ dependency_cache: params.dependencyCache,
152
+ network: params.network,
153
+ });
92
154
  }
93
155
 
94
156
  /** Options of {@link Commands.run} and {@link Commands.stream}. */
@@ -1032,6 +1094,63 @@ export class Sandbox {
1032
1094
  return (await this.t.json<KeepResult>({ method: "PUT", path: this.path("/keep"), json: { keep_days: Math.floor(days) }, options })).data;
1033
1095
  }
1034
1096
 
1097
+ /**
1098
+ * Saves a copy of the sandbox disk as a snapshot (feature `snapshots`). Works for a running,
1099
+ * paused or sleeping sandbox; a running one is paused only for a moment and keeps running.
1100
+ * The snapshot holds files only – no memory, no running programs, no env. An archived
1101
+ * sandbox must be woken up first (`ConflictError`, code `sandbox_archived`); the number of
1102
+ * snapshots is limited by your plan (`RateLimitError`, code `snapshot_limit`).
1103
+ *
1104
+ * ```ts
1105
+ * const snap = await sandbox.snapshot({ name: "after-setup" });
1106
+ * const copy = await snap.createSandbox({ timeoutSeconds: 600 });
1107
+ * ```
1108
+ */
1109
+ async snapshot(params: { name?: string } = {}, options?: RequestOptions): Promise<Snapshot> {
1110
+ const { data } = await this.t.json<SnapshotInfo>({
1111
+ method: "POST",
1112
+ path: this.path("/snapshots"),
1113
+ json: compact({ name: params.name }),
1114
+ defaultTimeoutMs: SNAPSHOT_TIMEOUT_MS,
1115
+ options,
1116
+ });
1117
+ return new Snapshot(this.t, data);
1118
+ }
1119
+
1120
+ /**
1121
+ * Creates `count` (1–10) new sandboxes with a copy of this sandbox's disk (features
1122
+ * `snapshots` and `clones`): a snapshot plus N creates on the same server. Each copy has its
1123
+ * own ID, IP addresses and identity (new machine-id, no SSH host keys of the source). Memory and
1124
+ * running programs are not copied.
1125
+ *
1126
+ * Copies keep the source sandbox's lifetime and network settings unless you pass them: without
1127
+ * `timeoutSeconds`, `onTimeout`, `idleTimeoutSeconds`, `keepDays` or `computeClass` they get the
1128
+ * source's values, and its network access (no internet, allowed destinations, IP version).
1129
+ * A `network` passed here can only narrow the source's access, never widen it. `env` is not
1130
+ * inherited – pass what the copies need.
1131
+ *
1132
+ * When some copies fail, they are listed in `errors`; when none could be created, the error
1133
+ * of the first one is thrown. The copies count towards your concurrent-sandbox limits.
1134
+ */
1135
+ async clone(params: CloneParams = {}, options?: RequestOptions): Promise<CloneResult> {
1136
+ const { count = 1, keepSnapshot, snapshotName, ...create } = params;
1137
+ if (!Number.isInteger(count) || count < 1 || count > 10) throw new WBXError("count must be an integer between 1 and 10");
1138
+ const { data, status, headers } = await this.t.json<CloneResponse>({
1139
+ method: "POST",
1140
+ path: this.path("/clone"),
1141
+ json: compact({ ...createBody(create), count, keep_snapshot: keepSnapshot || undefined, snapshot_name: snapshotName || undefined }),
1142
+ defaultTimeoutMs: CLONE_TIMEOUT_MS,
1143
+ options,
1144
+ });
1145
+ const sandboxes = (data?.sandboxes ?? []).map((d) => new Sandbox(this.t, d));
1146
+ const errors = data?.errors ?? [];
1147
+ const first = errors[0];
1148
+ if (sandboxes.length === 0 && first) {
1149
+ throw errorFromResponse(first.status ?? (status >= 400 ? status : 500), first, headers, "POST", this.path("/clone"));
1150
+ }
1151
+ return { snapshotId: data?.snapshot_id, snapshotKept: data?.snapshot_kept ?? !!keepSnapshot, sandboxes, errors };
1152
+ }
1153
+
1035
1154
  /**
1036
1155
  * Public HTTPS address of a TCP port in the sandbox (a web app or API you started there).
1037
1156
  * The app must listen on `0.0.0.0`. Open `url_with_token` in a browser or send the header
@@ -1082,29 +1201,14 @@ export class Sandboxes {
1082
1201
  * without a name is never retried automatically.
1083
1202
  */
1084
1203
  async create(params: SandboxCreateParams = {}, options?: RequestOptions): Promise<Sandbox> {
1085
- const body = compact({
1086
- template: params.template,
1087
- timeout_s: params.timeoutSeconds,
1088
- name: params.name,
1089
- on_timeout: params.onTimeout,
1090
- idle_timeout_s: params.idleTimeoutSeconds,
1091
- keep_days: params.keepDays,
1092
- metadata: params.metadata,
1093
- env: params.env,
1094
- vcpu: params.vcpu,
1095
- mem_mb: params.memMb,
1096
- compute_class: params.computeClass,
1097
- optimize_for: params.optimizeFor,
1098
- placement: params.placement,
1099
- dependency_cache: params.dependencyCache,
1100
- network: params.network,
1101
- });
1204
+ const body = compact({ template: params.template, ...createBody(params), from_snapshot: params.fromSnapshot });
1102
1205
  const { data, headers } = await this.t.json<SandboxInfo>({
1103
1206
  method: "POST",
1104
1207
  path: "/v1/sandboxes",
1105
1208
  json: body,
1106
1209
  idempotent: !!params.name,
1107
- defaultTimeoutMs: CREATE_TIMEOUT_MS,
1210
+ // from a snapshot the disk is copied first – longer limit (like the portal)
1211
+ defaultTimeoutMs: params.fromSnapshot ? FROM_SNAPSHOT_TIMEOUT_MS : CREATE_TIMEOUT_MS,
1108
1212
  options,
1109
1213
  });
1110
1214
  return new Sandbox(this.t, data, headers.get("x-wbx-existing") === "1");
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Snapshots of sandbox disks (feature `snapshots`).
3
+ * @module
4
+ */
5
+
6
+ import { NotFoundError } from "./errors.js";
7
+ import type { RequestOptions, Transport } from "./http.js";
8
+ import { Sandboxes, type Sandbox, type SandboxCreateParams } from "./sandbox.js";
9
+ import type { SnapshotInfo } from "./types.js";
10
+
11
+ /**
12
+ * A saved copy of a sandbox disk – files only (no memory, no running programs, no env).
13
+ * Obtain one from `sandbox.snapshot()`, `wbx.snapshots.list()` or `wbx.snapshots.get(id)`.
14
+ * It stays until you delete it (deleting the source sandbox does not delete it); its size is
15
+ * billed as storage, like a sleeping sandbox.
16
+ */
17
+ export class Snapshot {
18
+ /** Snapshot ID (`snap_…`). */
19
+ readonly id: string;
20
+ /** The API record (snake_case fields). */
21
+ info: SnapshotInfo;
22
+ private readonly t: Transport;
23
+
24
+ /** Not meant to be called directly – use the {@link WBX} client. */
25
+ constructor(t: Transport, info: SnapshotInfo) {
26
+ this.t = t;
27
+ this.id = info.id;
28
+ this.info = info;
29
+ }
30
+
31
+ /** Name given when the snapshot was taken. */
32
+ get name(): string | undefined {
33
+ return this.info.name || undefined;
34
+ }
35
+
36
+ /** ID of the sandbox the snapshot was taken from. */
37
+ get sourceSandbox(): string | undefined {
38
+ return this.info.source_sandbox || undefined;
39
+ }
40
+
41
+ /** Template of the source sandbox (a sandbox from this snapshot gets it too). */
42
+ get template(): string {
43
+ return this.info.template;
44
+ }
45
+
46
+ /** Space the snapshot takes in bytes (billed as storage). */
47
+ get sizeBytes(): number {
48
+ return this.info.size_bytes ?? 0;
49
+ }
50
+
51
+ /** When the snapshot was taken. */
52
+ get createdAt(): Date | undefined {
53
+ return this.info.created_at ? new Date(this.info.created_at) : undefined;
54
+ }
55
+
56
+ /** Starts a new sandbox from this snapshot (same options as `wbx.sandboxes.create()`). */
57
+ createSandbox(params: Omit<SandboxCreateParams, "fromSnapshot" | "template"> = {}, options?: RequestOptions): Promise<Sandbox> {
58
+ return new Sandboxes(this.t).create({ ...params, fromSnapshot: this.id }, options);
59
+ }
60
+
61
+ /** Deletes the snapshot. No error when it is already gone; sandboxes created from it are not affected. */
62
+ async delete(options?: RequestOptions): Promise<void> {
63
+ await new Snapshots(this.t).delete(this.id, options);
64
+ }
65
+
66
+ /** @internal */
67
+ toJSON(): SnapshotInfo {
68
+ return this.info;
69
+ }
70
+ }
71
+
72
+ /** `wbx.snapshots` */
73
+ export class Snapshots {
74
+ /** Not meant to be called directly – use the {@link WBX} client. */
75
+ constructor(private readonly t: Transport) {}
76
+
77
+ /** Your snapshots (all at once, no pages). */
78
+ async list(options?: RequestOptions): Promise<Snapshot[]> {
79
+ const { data } = await this.t.json<SnapshotInfo[] | { snapshots?: SnapshotInfo[] }>({ method: "GET", path: "/v1/snapshots", options });
80
+ const rows = Array.isArray(data) ? data : (data?.snapshots ?? []);
81
+ return rows.map((d) => new Snapshot(this.t, d));
82
+ }
83
+
84
+ /** One snapshot by its ID (`NotFoundError` when it does not exist or is not yours). */
85
+ async get(id: string, options?: RequestOptions): Promise<Snapshot> {
86
+ const { data } = await this.t.json<SnapshotInfo>({ method: "GET", path: `/v1/snapshots/${encodeURIComponent(id)}`, options });
87
+ return new Snapshot(this.t, data);
88
+ }
89
+
90
+ /** Deletes a snapshot by ID. No error when it is already gone. */
91
+ async delete(id: string, options?: RequestOptions): Promise<void> {
92
+ try {
93
+ await this.t.json({ method: "DELETE", path: `/v1/snapshots/${encodeURIComponent(id)}`, options });
94
+ } catch (e) {
95
+ if (!(e instanceof NotFoundError)) throw e;
96
+ }
97
+ }
98
+ }
package/src/types.ts CHANGED
@@ -68,6 +68,45 @@ export interface SandboxInfo {
68
68
  delete_reason?: string;
69
69
  }
70
70
 
71
+ /** A snapshot of a sandbox disk (`GET /v1/snapshots/{id}`). Files only – never env or memory. */
72
+ export interface SnapshotInfo {
73
+ /** Snapshot ID (`snap_…`). */
74
+ id: string;
75
+ name?: string;
76
+ /** ID of the sandbox the snapshot was taken from (it may no longer exist). */
77
+ source_sandbox?: string;
78
+ template: string;
79
+ vcpu?: number;
80
+ mem_mb?: number;
81
+ /** Size of the disk in MB (the size a sandbox from this snapshot gets). */
82
+ disk_mb?: number;
83
+ /** Space the snapshot takes – billed as storage. */
84
+ size_bytes?: number;
85
+ created_at?: string;
86
+ }
87
+
88
+ /** One copy of a clone that could not be created. */
89
+ export interface CloneError {
90
+ /** Position of the copy, 0 … count-1. */
91
+ index?: number;
92
+ /** Name of the copy (`<name>-N` for several copies), empty without `name`. */
93
+ name?: string;
94
+ error?: string;
95
+ code?: string;
96
+ /** HTTP status of the failed create, when the server sent it. */
97
+ status?: number;
98
+ [key: string]: unknown;
99
+ }
100
+
101
+ /** Response of `POST /v1/sandboxes/{id}/clone`. */
102
+ export interface CloneResponse {
103
+ snapshot_id?: string;
104
+ /** Whether the snapshot was kept (`keep_snapshot`). */
105
+ snapshot_kept?: boolean;
106
+ sandboxes?: SandboxInfo[];
107
+ errors?: CloneError[];
108
+ }
109
+
71
110
  /** Result of `PUT /v1/sandboxes/{id}/keep`. */
72
111
  export interface KeepResult {
73
112
  id: string;
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** Version of this SDK (kept equal to `version` in package.json – checked by the tests). */
2
- export const VERSION = "0.1.2";
2
+ export const VERSION = "0.2.1";