@daytonaio/sdk 0.16.0-alpha.0 → 0.16.0-alpha.2

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/dist/Daytona.d.ts CHANGED
@@ -1,18 +1,6 @@
1
- import { CreateWorkspaceTargetEnum as SandboxTargetRegion, WorkspaceVolume } from '@daytonaio/api-client';
1
+ import { CreateWorkspaceTargetEnum as SandboxTargetRegion } from '@daytonaio/api-client';
2
+ import { Image } from './Image';
2
3
  import { Sandbox, Sandbox as Workspace } from './Sandbox';
3
- import { VolumeService } from './Volume';
4
- /**
5
- * Represents a volume mount for a Sandbox.
6
- *
7
- * @interface
8
- * @property {string} volumeId - ID of the Volume to mount
9
- * @property {string} mountPath - Path on the Sandbox to mount the Volume
10
- * @extends {WorkspaceVolume}
11
- */
12
- export interface VolumeMount extends WorkspaceVolume {
13
- volumeId: string;
14
- mountPath: string;
15
- }
16
4
  /**
17
5
  * Configuration options for initializing the Daytona client.
18
6
  *
@@ -89,7 +77,7 @@ export interface SandboxResources {
89
77
  * Parameters for creating a new Sandbox.
90
78
  *
91
79
  * @interface
92
- * @property {string} [image] - Optional Docker image to use for the Sandbox
80
+ * @property {string | Image} [image] - Optional Docker image to use for the Sandbox or an Image instance
93
81
  * @property {string} [user] - Optional os user to use for the Sandbox
94
82
  * @property {CodeLanguage | string} [language] - Programming language for direct code execution
95
83
  * @property {Record<string, string>} [envVars] - Optional environment variables to set in the Sandbox
@@ -114,8 +102,8 @@ export interface SandboxResources {
114
102
  * const sandbox = await daytona.create(params, 50);
115
103
  */
116
104
  export type CreateSandboxParams = {
117
- /** Optional Docker image to use for the Sandbox */
118
- image?: string;
105
+ /** Optional Docker image to use for the Sandbox or an Image instance */
106
+ image?: string | Image;
119
107
  /** Optional os user to use for the Sandbox */
120
108
  user?: string;
121
109
  /** Programming language for direct code execution */
@@ -139,8 +127,6 @@ export type CreateSandboxParams = {
139
127
  timeout?: number;
140
128
  /** Auto-stop interval in minutes (0 means disabled) (must be a non-negative integer) */
141
129
  autoStopInterval?: number;
142
- /** List of volumes to mount in the Sandbox */
143
- volumes?: VolumeMount[];
144
130
  };
145
131
  /**
146
132
  * Filter for Sandboxes.
@@ -155,10 +141,10 @@ export type SandboxFilter = {
155
141
  };
156
142
  /**
157
143
  * Main class for interacting with the Daytona API.
144
+ *
158
145
  * Provides methods for creating, managing, and interacting with Daytona Sandboxes.
159
146
  * Can be initialized either with explicit configuration or using environment variables.
160
147
  *
161
- * @property {VolumeService} volume - Service for managing Daytona Volumes
162
148
  *
163
149
  * @example
164
150
  * // Using environment variables
@@ -180,12 +166,13 @@ export type SandboxFilter = {
180
166
  export declare class Daytona {
181
167
  private readonly sandboxApi;
182
168
  private readonly toolboxApi;
169
+ private readonly imagesApi;
170
+ private readonly objectStorageApi;
183
171
  private readonly target;
184
172
  private readonly apiKey?;
185
173
  private readonly jwtToken?;
186
174
  private readonly organizationId?;
187
175
  private readonly apiUrl;
188
- readonly volume: VolumeService;
189
176
  /**
190
177
  * Creates a new Daytona client instance.
191
178
  *
@@ -316,6 +303,24 @@ export declare class Daytona {
316
303
  * console.log(`Current sandbox state: ${sandbox.instance.state}`);
317
304
  */
318
305
  getCurrentSandbox(sandboxId: string): Promise<Sandbox>;
306
+ /**
307
+ * Creates and registers a new image from the given Image definition.
308
+ *
309
+ * @param {string} name - The name of the image to create.
310
+ * @param {Image} image - The Image instance.
311
+ * @param {object} options - Options for the create operation.
312
+ * @param {boolean} options.verbose - Default is false. Whether to log progress information upon each state change of the image.
313
+ * @param {number} options.timeout - Default is no timeout. Timeout in seconds (0 means no timeout).
314
+ * @returns {Promise<void>}
315
+ *
316
+ * @example
317
+ * const image = Image.debianSlim('3.12').pipInstall('numpy');
318
+ * await daytona.createImage('my-python-image', image);
319
+ */
320
+ createImage(name: string, image: Image, options?: {
321
+ verbose?: boolean;
322
+ timeout?: number;
323
+ }): Promise<void>;
319
324
  /**
320
325
  * Gets the appropriate code toolbox based on language.
321
326
  *
@@ -325,4 +330,12 @@ export declare class Daytona {
325
330
  * @throws {DaytonaError} - `DaytonaError` - When an unsupported language is specified
326
331
  */
327
332
  private getCodeToolbox;
333
+ /**
334
+ * Processes the image contexts by uploading them to object storage
335
+ *
336
+ * @private
337
+ * @param {Image} image - The Image instance.
338
+ * @returns {Promise<string[]>} The list of context hashes stored in object storage.
339
+ */
340
+ private processImageContext;
328
341
  }
package/dist/Daytona.js CHANGED
@@ -43,8 +43,9 @@ const dotenv_1 = __importDefault(require("dotenv"));
43
43
  const SandboxPythonCodeToolbox_1 = require("./code-toolbox/SandboxPythonCodeToolbox");
44
44
  const SandboxTsCodeToolbox_1 = require("./code-toolbox/SandboxTsCodeToolbox");
45
45
  const DaytonaError_1 = require("./errors/DaytonaError");
46
+ const Image_1 = require("./Image");
47
+ const ObjectStorage_1 = require("./ObjectStorage");
46
48
  const Sandbox_1 = require("./Sandbox");
47
- const Volume_1 = require("./Volume");
48
49
  /**
49
50
  * Supported programming languages for code execution
50
51
  */
@@ -56,10 +57,10 @@ var CodeLanguage;
56
57
  })(CodeLanguage || (exports.CodeLanguage = CodeLanguage = {}));
57
58
  /**
58
59
  * Main class for interacting with the Daytona API.
60
+ *
59
61
  * Provides methods for creating, managing, and interacting with Daytona Sandboxes.
60
62
  * Can be initialized either with explicit configuration or using environment variables.
61
63
  *
62
- * @property {VolumeService} volume - Service for managing Daytona Volumes
63
64
  *
64
65
  * @example
65
66
  * // Using environment variables
@@ -150,7 +151,8 @@ class Daytona {
150
151
  });
151
152
  this.sandboxApi = new api_client_1.WorkspaceApi(configuration, '', axiosInstance);
152
153
  this.toolboxApi = new api_client_1.ToolboxApi(configuration, '', axiosInstance);
153
- this.volume = new Volume_1.VolumeService(new api_client_1.VolumesApi(configuration, '', axiosInstance));
154
+ this.imagesApi = new api_client_1.ImagesApi(configuration, '', axiosInstance);
155
+ this.objectStorageApi = new api_client_1.ObjectStorageApi(configuration, '', axiosInstance);
154
156
  }
155
157
  /**
156
158
  * Creates Sandboxes with default or custom configurations. You can specify various parameters,
@@ -182,8 +184,8 @@ class Daytona {
182
184
  * const sandbox = await daytona.create(params, 40);
183
185
  */
184
186
  async create(params, timeout = 60) {
185
- // const startTime = Date.now();
186
187
  var _a, _b, _c, _d;
188
+ const startTime = Date.now();
187
189
  if (params == null) {
188
190
  params = { language: 'python' };
189
191
  }
@@ -202,8 +204,22 @@ class Daytona {
202
204
  }
203
205
  const codeToolbox = this.getCodeToolbox(params.language);
204
206
  try {
207
+ // Handle Image instance if provided
208
+ let imageStr;
209
+ let buildInfo;
210
+ if (typeof params.image === 'string') {
211
+ imageStr = params.image;
212
+ }
213
+ else if (params.image instanceof Image_1.Image) {
214
+ const contextHashes = await this.processImageContext(params.image);
215
+ buildInfo = {
216
+ contextHashes,
217
+ dockerfileContent: params.image.dockerfile,
218
+ };
219
+ }
205
220
  const response = await this.sandboxApi.createWorkspace({
206
- image: params.image,
221
+ image: imageStr,
222
+ buildInfo,
207
223
  user: params.user,
208
224
  env: params.envVars || {},
209
225
  labels: params.labels,
@@ -214,7 +230,6 @@ class Daytona {
214
230
  memory: (_c = params.resources) === null || _c === void 0 ? void 0 : _c.memory,
215
231
  disk: (_d = params.resources) === null || _d === void 0 ? void 0 : _d.disk,
216
232
  autoStopInterval: params.autoStopInterval,
217
- volumes: params.volumes,
218
233
  }, undefined, {
219
234
  timeout: effectiveTimeout * 1000,
220
235
  });
@@ -225,10 +240,10 @@ class Daytona {
225
240
  name: '',
226
241
  };
227
242
  const sandbox = new Sandbox_1.Sandbox(sandboxInstance.id, sandboxInstance, this.sandboxApi, this.toolboxApi, codeToolbox);
228
- // if (!params.async) {
229
- // const timeElapsed = Date.now() - startTime;
230
- // await sandbox.waitUntilStarted(effectiveTimeout ? effectiveTimeout - (timeElapsed / 1000) : 0);
231
- // }
243
+ if (!params.async && sandbox.instance.state !== 'started') {
244
+ const timeElapsed = Date.now() - startTime;
245
+ await sandbox.waitUntilStarted(effectiveTimeout ? effectiveTimeout - timeElapsed / 1000 : 0);
246
+ }
232
247
  return sandbox;
233
248
  }
234
249
  catch (error) {
@@ -371,6 +386,48 @@ class Daytona {
371
386
  async getCurrentSandbox(sandboxId) {
372
387
  return await this.get(sandboxId);
373
388
  }
389
+ /**
390
+ * Creates and registers a new image from the given Image definition.
391
+ *
392
+ * @param {string} name - The name of the image to create.
393
+ * @param {Image} image - The Image instance.
394
+ * @param {object} options - Options for the create operation.
395
+ * @param {boolean} options.verbose - Default is false. Whether to log progress information upon each state change of the image.
396
+ * @param {number} options.timeout - Default is no timeout. Timeout in seconds (0 means no timeout).
397
+ * @returns {Promise<void>}
398
+ *
399
+ * @example
400
+ * const image = Image.debianSlim('3.12').pipInstall('numpy');
401
+ * await daytona.createImage('my-python-image', image);
402
+ */
403
+ async createImage(name, image, options = {}) {
404
+ const contextHashes = await this.processImageContext(image);
405
+ let builtImage = (await this.imagesApi.buildImage({
406
+ name,
407
+ buildInfo: {
408
+ contextHashes,
409
+ dockerfileContent: image.dockerfile,
410
+ },
411
+ }, undefined, {
412
+ timeout: (options.timeout || 0) * 1000,
413
+ })).data;
414
+ let previousState = null;
415
+ while (builtImage.state !== api_client_1.ImageState.ACTIVE && builtImage.state !== api_client_1.ImageState.ERROR) {
416
+ if (options.verbose && previousState !== builtImage.state) {
417
+ console.log(`Building image ${builtImage.name} (${builtImage.state})`);
418
+ previousState = builtImage.state;
419
+ }
420
+ await new Promise((resolve) => setTimeout(resolve, 1000));
421
+ const response = await this.imagesApi.getImage(builtImage.id);
422
+ builtImage = response.data;
423
+ }
424
+ if (builtImage.state === api_client_1.ImageState.ERROR) {
425
+ throw new DaytonaError_1.DaytonaError(`Failed to build image. Image ended in the ERROR state. name: ${builtImage.name}; error reason: ${builtImage.errorReason}`);
426
+ }
427
+ if (options.verbose) {
428
+ console.log(`Built image ${builtImage.name} (${builtImage.state})`);
429
+ }
430
+ }
374
431
  /**
375
432
  * Gets the appropriate code toolbox based on language.
376
433
  *
@@ -391,5 +448,30 @@ class Daytona {
391
448
  throw new DaytonaError_1.DaytonaError(`Unsupported language: ${language}, supported languages: ${Object.values(CodeLanguage).join(', ')}`);
392
449
  }
393
450
  }
451
+ /**
452
+ * Processes the image contexts by uploading them to object storage
453
+ *
454
+ * @private
455
+ * @param {Image} image - The Image instance.
456
+ * @returns {Promise<string[]>} The list of context hashes stored in object storage.
457
+ */
458
+ async processImageContext(image) {
459
+ if (!image.contextList || !image.contextList.length) {
460
+ return [];
461
+ }
462
+ const pushAccessCreds = (await this.objectStorageApi.getPushAccess()).data;
463
+ const objectStorage = new ObjectStorage_1.ObjectStorage({
464
+ endpointUrl: pushAccessCreds.storageUrl,
465
+ accessKeyId: pushAccessCreds.accessKey,
466
+ secretAccessKey: pushAccessCreds.secret,
467
+ sessionToken: pushAccessCreds.sessionToken,
468
+ });
469
+ const contextHashes = [];
470
+ for (const context of image.contextList) {
471
+ const contextHash = await objectStorage.upload(context.sourcePath, pushAccessCreds.organizationId, context.archivePath);
472
+ contextHashes.push(contextHash);
473
+ }
474
+ return contextHashes;
475
+ }
394
476
  }
395
477
  exports.Daytona = Daytona;
@@ -0,0 +1,261 @@
1
+ declare const SUPPORTED_PYTHON_SERIES: readonly ["3.9", "3.10", "3.11", "3.12", "3.13"];
2
+ type SupportedPythonSeries = (typeof SUPPORTED_PYTHON_SERIES)[number];
3
+ /**
4
+ * Represents a context file to be added to the image.
5
+ *
6
+ * @interface
7
+ * @property {string} sourcePath - The path to the source file or directory.
8
+ * @property {string} archivePath - The path inside the archive file in object storage.
9
+ */
10
+ export interface Context {
11
+ sourcePath: string;
12
+ archivePath?: string;
13
+ }
14
+ /**
15
+ * Options for the pip install command.
16
+ *
17
+ * @interface
18
+ * @property {string[]} findLinks - The find-links to use for the pip install command.
19
+ * @property {string} indexUrl - The index URL to use for the pip install command.
20
+ * @property {string[]} extraIndexUrls - The extra index URLs to use for the pip install command.
21
+ * @property {boolean} pre - Whether to install pre-release versions.
22
+ * @property {string} extraOptions - The extra options to use for the pip install command. Given string is passed directly to the pip install command.
23
+ */
24
+ export interface PipInstallOptions {
25
+ findLinks?: string[];
26
+ indexUrl?: string;
27
+ extraIndexUrls?: string[];
28
+ pre?: boolean;
29
+ extraOptions?: string;
30
+ }
31
+ /**
32
+ * Options for the pip install command from a pyproject.toml file.
33
+ *
34
+ * @interface
35
+ * @property {string[]} optionalDependencies - The optional dependencies to install.
36
+ *
37
+ * @extends {PipInstallOptions}
38
+ */
39
+ export interface PyprojectOptions extends PipInstallOptions {
40
+ optionalDependencies?: string[];
41
+ }
42
+ /**
43
+ * Represents an image definition for a Daytona sandbox.
44
+ * Do not construct this class directly. Instead use one of its static factory methods,
45
+ * such as `Image.base()`, `Image.debianSlim()` or `Image.fromDockerfile()`.
46
+ *
47
+ * @class
48
+ * @property {string} dockerfile - The Dockerfile content.
49
+ * @property {Context[]} contextList - The list of context files to be added to the image.
50
+ */
51
+ export declare class Image {
52
+ private _dockerfile;
53
+ private _contextList;
54
+ private constructor();
55
+ get dockerfile(): string;
56
+ get contextList(): Context[];
57
+ /**
58
+ * Adds commands to install packages using pip.
59
+ *
60
+ * @param {string | string[]} packages - The packages to install.
61
+ * @param {Object} options - The options for the pip install command.
62
+ * @param {string[]} options.findLinks - The find-links to use for the pip install command.
63
+ * @returns {Image} The Image instance.
64
+ *
65
+ * @example
66
+ * const image = Image.debianSlim('3.12').pipInstall('numpy', { findLinks: ['https://pypi.org/simple'] })
67
+ */
68
+ pipInstall(packages: string | string[], options?: PipInstallOptions): Image;
69
+ /**
70
+ * Installs dependencies from a requirements.txt file.
71
+ *
72
+ * @param {string} requirementsTxt - The path to the requirements.txt file.
73
+ * @param {PipInstallOptions} options - The options for the pip install command.
74
+ * @returns {Image} The Image instance.
75
+ *
76
+ * @example
77
+ * const image = Image.debianSlim('3.12')
78
+ * image.pipInstallFromRequirements('requirements.txt', { findLinks: ['https://pypi.org/simple'] })
79
+ */
80
+ pipInstallFromRequirements(requirementsTxt: string, options?: PipInstallOptions): Image;
81
+ /**
82
+ * Installs dependencies from a pyproject.toml file.
83
+ *
84
+ * @param {string} pyprojectToml - The path to the pyproject.toml file.
85
+ * @param {PyprojectOptions} options - The options for the pip install command.
86
+ * @returns {Image} The Image instance.
87
+ *
88
+ * @example
89
+ * const image = Image.debianSlim('3.12')
90
+ * image.pipInstallFromPyproject('pyproject.toml', { optionalDependencies: ['dev'] })
91
+ */
92
+ pipInstallFromPyproject(pyprojectToml: string, options?: PyprojectOptions): Image;
93
+ /**
94
+ * Adds a local file to the image.
95
+ *
96
+ * @param {string} localPath - The path to the local file.
97
+ * @param {string} remotePath - The path of the file in the image.
98
+ * @returns {Image} The Image instance.
99
+ *
100
+ * @example
101
+ * const image = Image
102
+ * .debianSlim('3.12')
103
+ * .addLocalFile('requirements.txt', '/home/daytona/requirements.txt')
104
+ */
105
+ addLocalFile(localPath: string, remotePath: string): Image;
106
+ /**
107
+ * Adds a local directory to the image.
108
+ *
109
+ * @param {string} localPath - The path to the local directory.
110
+ * @param {string} remotePath - The path of the directory in the image.
111
+ * @returns {Image} The Image instance.
112
+ *
113
+ * @example
114
+ * const image = Image
115
+ * .debianSlim('3.12')
116
+ * .addLocalDir('src', '/home/daytona/src')
117
+ */
118
+ addLocalDir(localPath: string, remotePath: string): Image;
119
+ /**
120
+ * Runs commands in the image.
121
+ *
122
+ * @param {string | string[]} commands - The commands to run.
123
+ * @returns {Image} The Image instance.
124
+ *
125
+ * @example
126
+ * const image = Image
127
+ * .debianSlim('3.12')
128
+ * .runCommands('echo "Hello, world!"')
129
+ */
130
+ runCommands(...commands: (string | string[])[]): Image;
131
+ /**
132
+ * Sets environment variables in the image.
133
+ *
134
+ * @param {Record<string, string>} envVars - The environment variables to set.
135
+ * @returns {Image} The Image instance.
136
+ *
137
+ * @example
138
+ * const image = Image
139
+ * .debianSlim('3.12')
140
+ * .env({ FOO: 'bar' })
141
+ */
142
+ env(envVars: Record<string, string>): Image;
143
+ /**
144
+ * Sets the working directory in the image.
145
+ *
146
+ * @param {string} dirPath - The path to the working directory.
147
+ * @returns {Image} The Image instance.
148
+ *
149
+ * @example
150
+ * const image = Image
151
+ * .debianSlim('3.12')
152
+ * .workdir('/home/daytona')
153
+ */
154
+ workdir(dirPath: string): Image;
155
+ /**
156
+ * Sets the entrypoint for the image.
157
+ *
158
+ * @param {string[]} entrypointCommands - The commands to set as the entrypoint.
159
+ * @returns {Image} The Image instance.
160
+ *
161
+ * @example
162
+ * const image = Image
163
+ * .debianSlim('3.12')
164
+ * .entrypoint(['/bin/bash'])
165
+ */
166
+ entrypoint(entrypointCommands: string[]): Image;
167
+ /**
168
+ * Sets the default command for the image.
169
+ *
170
+ * @param {string[]} cmd - The command to set as the default command.
171
+ * @returns {Image} The Image instance.
172
+ *
173
+ * @example
174
+ * const image = Image
175
+ * .debianSlim('3.12')
176
+ * .cmd(['/bin/bash'])
177
+ */
178
+ cmd(cmd: string[]): Image;
179
+ /**
180
+ * Extends an image with arbitrary Dockerfile-like commands.
181
+ *
182
+ * @param {string | string[]} dockerfileCommands - The commands to add to the Dockerfile.
183
+ * @param {string} contextDir - The path to the context directory.
184
+ * @returns {Image} The Image instance.
185
+ *
186
+ * @example
187
+ * const image = Image
188
+ * .debianSlim('3.12')
189
+ * .dockerfileCommands(['RUN echo "Hello, world!"'])
190
+ */
191
+ dockerfileCommands(dockerfileCommands: (string | string[])[], contextDir?: string): Image;
192
+ /**
193
+ * Creates an Image from an existing Dockerfile.
194
+ *
195
+ * @param {string} path - The path to the Dockerfile.
196
+ * @returns {Image} The Image instance.
197
+ *
198
+ * @example
199
+ * const image = Image.fromDockerfile('Dockerfile')
200
+ */
201
+ static fromDockerfile(path: string): Image;
202
+ /**
203
+ * Creates an Image from an existing base image.
204
+ *
205
+ * @param {string} image - The base image to use.
206
+ * @returns {Image} The Image instance.
207
+ *
208
+ * @example
209
+ * const image = Image.base('python:3.12-slim-bookworm')
210
+ */
211
+ static base(image: string): Image;
212
+ /**
213
+ * Creates a Debian slim image based on the official Python Docker image.
214
+ *
215
+ * @param {string} pythonVersion - The Python version to use.
216
+ * @returns {Image} The Image instance.
217
+ *
218
+ * @example
219
+ * const image = Image.debianSlim('3.12')
220
+ */
221
+ static debianSlim(pythonVersion?: SupportedPythonSeries): Image;
222
+ /**
223
+ * Formats pip install arguments in a single string.
224
+ *
225
+ * @param {PipInstallOptions} options - The options for the pip install command.
226
+ * @returns {string} The formatted pip install arguments.
227
+ */
228
+ private formatPipInstallArgs;
229
+ /**
230
+ * Flattens a string argument.
231
+ *
232
+ * @param {string} functionName - The name of the function.
233
+ * @param {string} argName - The name of the argument.
234
+ * @param {any} args - The argument to flatten.
235
+ * @returns {string[]} The flattened argument.
236
+ */
237
+ private flattenStringArgs;
238
+ /**
239
+ * Processes the Python version.
240
+ *
241
+ * @param {string} pythonVersion - The Python version to use.
242
+ * @returns {string} The processed Python version.
243
+ */
244
+ private static processPythonVersion;
245
+ /**
246
+ * Extracts source files from COPY commands in a Dockerfile.
247
+ *
248
+ * @param {string} dockerfileContent - The content of the Dockerfile.
249
+ * @param {string} pathPrefix - The path prefix to use for the sources.
250
+ * @returns {Array<[string, string]>} The list of the actual file path and its corresponding COPY-command source path.
251
+ */
252
+ private static extractCopySources;
253
+ /**
254
+ * Parses a COPY command to extract sources and destination.
255
+ *
256
+ * @param {string} line - The line to parse.
257
+ * @returns {Object} The parsed sources and destination.
258
+ */
259
+ private static parseCopyCommand;
260
+ }
261
+ export {};