@e2b/code-interpreter 1.2.5-autopause.1 → 1.5.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.js CHANGED
@@ -35,26 +35,6 @@ var __copyProps = (to, from, except, desc) => {
35
35
  };
36
36
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
37
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
- var __async = (__this, __arguments, generator) => {
39
- return new Promise((resolve, reject) => {
40
- var fulfilled = (value) => {
41
- try {
42
- step(generator.next(value));
43
- } catch (e) {
44
- reject(e);
45
- }
46
- };
47
- var rejected = (value) => {
48
- try {
49
- step(generator.throw(value));
50
- } catch (e) {
51
- reject(e);
52
- }
53
- };
54
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
55
- step((generator = generator.apply(__this, __arguments)).next());
56
- });
57
- };
58
38
  var __await = function(promise, isYieldStar) {
59
39
  this[0] = promise;
60
40
  this[1] = isYieldStar;
@@ -86,22 +66,20 @@ var import_e2b3 = require("e2b");
86
66
 
87
67
  // src/messaging.ts
88
68
  var import_e2b = require("e2b");
89
- function extractError(res) {
90
- return __async(this, null, function* () {
91
- if (res.ok) {
92
- return;
93
- }
94
- switch (res.status) {
95
- case 502:
96
- return new import_e2b.TimeoutError(
97
- `${yield res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`
98
- );
99
- case 404:
100
- return new import_e2b.NotFoundError(yield res.text());
101
- default:
102
- return new import_e2b.SandboxError(`${res.status} ${res.statusText}`);
103
- }
104
- });
69
+ async function extractError(res) {
70
+ if (res.ok) {
71
+ return;
72
+ }
73
+ switch (res.status) {
74
+ case 502:
75
+ return new import_e2b.TimeoutError(
76
+ `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`
77
+ );
78
+ case 404:
79
+ return new import_e2b.NotFoundError(await res.text());
80
+ default:
81
+ return new import_e2b.SandboxError(`${res.status} ${res.statusText}`);
82
+ }
105
83
  }
106
84
  var ExecutionError = class {
107
85
  constructor(name, value, traceback) {
@@ -240,51 +218,49 @@ var Execution = class {
240
218
  };
241
219
  }
242
220
  };
243
- function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
244
- return __async(this, null, function* () {
245
- const msg = JSON.parse(line);
246
- switch (msg.type) {
247
- case "result":
248
- const result = new Result(
249
- __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
250
- msg.is_main_result
251
- );
252
- execution.results.push(result);
253
- if (onResult) {
254
- yield onResult(result);
255
- }
256
- break;
257
- case "stdout":
258
- execution.logs.stdout.push(msg.text);
259
- if (onStdout) {
260
- yield onStdout({
261
- error: false,
262
- line: msg.text,
263
- timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
264
- });
265
- }
266
- break;
267
- case "stderr":
268
- execution.logs.stderr.push(msg.text);
269
- if (onStderr) {
270
- yield onStderr({
271
- error: true,
272
- line: msg.text,
273
- timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
274
- });
275
- }
276
- break;
277
- case "error":
278
- execution.error = new ExecutionError(msg.name, msg.value, msg.traceback);
279
- if (onError) {
280
- yield onError(execution.error);
281
- }
282
- break;
283
- case "number_of_executions":
284
- execution.executionCount = msg.execution_count;
285
- break;
286
- }
287
- });
221
+ async function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
222
+ const msg = JSON.parse(line);
223
+ switch (msg.type) {
224
+ case "result":
225
+ const result = new Result(
226
+ __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
227
+ msg.is_main_result
228
+ );
229
+ execution.results.push(result);
230
+ if (onResult) {
231
+ await onResult(result);
232
+ }
233
+ break;
234
+ case "stdout":
235
+ execution.logs.stdout.push(msg.text);
236
+ if (onStdout) {
237
+ await onStdout({
238
+ error: false,
239
+ line: msg.text,
240
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
241
+ });
242
+ }
243
+ break;
244
+ case "stderr":
245
+ execution.logs.stderr.push(msg.text);
246
+ if (onStderr) {
247
+ await onStderr({
248
+ error: true,
249
+ line: msg.text,
250
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
251
+ });
252
+ }
253
+ break;
254
+ case "error":
255
+ execution.error = new ExecutionError(msg.name, msg.value, msg.traceback);
256
+ if (onError) {
257
+ await onError(execution.error);
258
+ }
259
+ break;
260
+ case "number_of_executions":
261
+ execution.executionCount = msg.execution_count;
262
+ break;
263
+ }
288
264
  }
289
265
 
290
266
  // src/utils.ts
@@ -338,71 +314,69 @@ var JUPYTER_PORT = 49999;
338
314
 
339
315
  // src/sandbox.ts
340
316
  var Sandbox = class extends import_e2b3.Sandbox {
341
- runCode(code, opts) {
342
- return __async(this, null, function* () {
343
- var _a, _b, _c;
344
- if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
345
- throw new import_e2b3.InvalidArgumentError("You can provide context or language, but not both at the same time.");
317
+ async runCode(code, opts) {
318
+ var _a, _b, _c;
319
+ if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
320
+ throw new import_e2b3.InvalidArgumentError("You can provide context or language, but not both at the same time.");
321
+ }
322
+ const controller = new AbortController();
323
+ const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
324
+ const reqTimer = requestTimeout ? setTimeout(() => {
325
+ controller.abort();
326
+ }, requestTimeout) : void 0;
327
+ try {
328
+ const res = await fetch(`${this.jupyterUrl}/execute`, {
329
+ method: "POST",
330
+ headers: {
331
+ "Content-Type": "application/json"
332
+ },
333
+ body: JSON.stringify({
334
+ code,
335
+ context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
336
+ language: opts == null ? void 0 : opts.language,
337
+ env_vars: opts == null ? void 0 : opts.envs
338
+ }),
339
+ signal: controller.signal,
340
+ keepalive: true
341
+ });
342
+ const error2 = await extractError(res);
343
+ if (error2) {
344
+ throw error2;
345
+ }
346
+ if (!res.body) {
347
+ throw new Error(`Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`);
346
348
  }
347
- const controller = new AbortController();
348
- const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
349
- const reqTimer = requestTimeout ? setTimeout(() => {
349
+ clearTimeout(reqTimer);
350
+ const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
351
+ const bodyTimer = bodyTimeout ? setTimeout(() => {
350
352
  controller.abort();
351
- }, requestTimeout) : void 0;
353
+ }, bodyTimeout) : void 0;
354
+ const execution = new Execution();
352
355
  try {
353
- const res = yield fetch(`${this.jupyterUrl}/execute`, {
354
- method: "POST",
355
- headers: {
356
- "Content-Type": "application/json"
357
- },
358
- body: JSON.stringify({
359
- code,
360
- context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
361
- language: opts == null ? void 0 : opts.language,
362
- env_vars: opts == null ? void 0 : opts.envs
363
- }),
364
- signal: controller.signal,
365
- keepalive: true
366
- });
367
- const error2 = yield extractError(res);
368
- if (error2) {
369
- throw error2;
370
- }
371
- if (!res.body) {
372
- throw new Error(`Not response body: ${res.statusText} ${yield res == null ? void 0 : res.text()}`);
373
- }
374
- clearTimeout(reqTimer);
375
- const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
376
- const bodyTimer = bodyTimeout ? setTimeout(() => {
377
- controller.abort();
378
- }, bodyTimeout) : void 0;
379
- const execution = new Execution();
380
356
  try {
357
+ for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
358
+ const chunk = temp.value;
359
+ await parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
360
+ }
361
+ } catch (temp) {
362
+ error = [temp];
363
+ } finally {
381
364
  try {
382
- for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
383
- const chunk = temp.value;
384
- yield parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
385
- }
386
- } catch (temp) {
387
- error = [temp];
365
+ more && (temp = iter.return) && await temp.call(iter);
388
366
  } finally {
389
- try {
390
- more && (temp = iter.return) && (yield temp.call(iter));
391
- } finally {
392
- if (error)
393
- throw error[0];
394
- }
367
+ if (error)
368
+ throw error[0];
395
369
  }
396
- } catch (error3) {
397
- throw formatExecutionTimeoutError(error3);
398
- } finally {
399
- clearTimeout(bodyTimer);
400
370
  }
401
- return execution;
402
- } catch (error2) {
403
- throw formatRequestTimeoutError(error2);
371
+ } catch (error3) {
372
+ throw formatExecutionTimeoutError(error3);
373
+ } finally {
374
+ clearTimeout(bodyTimer);
404
375
  }
405
- });
376
+ return execution;
377
+ } catch (error2) {
378
+ throw formatRequestTimeoutError(error2);
379
+ }
406
380
  }
407
381
  /**
408
382
  * Creates a new context to run code in.
@@ -411,30 +385,28 @@ var Sandbox = class extends import_e2b3.Sandbox {
411
385
  *
412
386
  * @returns context object.
413
387
  */
414
- createCodeContext(opts) {
415
- return __async(this, null, function* () {
416
- try {
417
- const res = yield fetch(`${this.jupyterUrl}/contexts`, {
418
- method: "POST",
419
- headers: {
420
- "Content-Type": "application/json"
421
- },
422
- body: JSON.stringify({
423
- language: opts == null ? void 0 : opts.language,
424
- cwd: opts == null ? void 0 : opts.cwd
425
- }),
426
- keepalive: true,
427
- signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
428
- });
429
- const error = yield extractError(res);
430
- if (error) {
431
- throw error;
432
- }
433
- return yield res.json();
434
- } catch (error) {
435
- throw formatRequestTimeoutError(error);
388
+ async createCodeContext(opts) {
389
+ try {
390
+ const res = await fetch(`${this.jupyterUrl}/contexts`, {
391
+ method: "POST",
392
+ headers: {
393
+ "Content-Type": "application/json"
394
+ },
395
+ body: JSON.stringify({
396
+ language: opts == null ? void 0 : opts.language,
397
+ cwd: opts == null ? void 0 : opts.cwd
398
+ }),
399
+ keepalive: true,
400
+ signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
401
+ });
402
+ const error = await extractError(res);
403
+ if (error) {
404
+ throw error;
436
405
  }
437
- });
406
+ return await res.json();
407
+ } catch (error) {
408
+ throw formatRequestTimeoutError(error);
409
+ }
438
410
  }
439
411
  get jupyterUrl() {
440
412
  return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAA6D;;;ACA7D,iBAA0D;AAG1D,SAAsB,aAAa,KAAe;AAAA;AAChD,QAAI,IAAI,IAAI;AACV;AAAA,IACF;AAEA,YAAQ,IAAI,QAAQ;AAAA,MAClB,KAAK;AACH,eAAO,IAAI;AAAA,UACT,GAAG,MAAM,IAAI,KAAK,CAAC;AAAA,QACrB;AAAA,MACF,KAAK;AACH,eAAO,IAAI,yBAAc,MAAM,IAAI,KAAK,CAAC;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AK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASM,kBAAkB,MAAgD;AAAA;AACtE,UAAI;AACF,cAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,UACrD,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,gBAAgB;AAAA,UAClB;AAAA,UACA,MAAM,KAAK,UAAU;AAAA,YACnB,UAAU,6BAAM;AAAA,YAChB,KAAK,6BAAM;AAAA,UACb,CAAC;AAAA,UACD,WAAW;AAAA,UACX,QAAQ,KAAK,iBAAiB,UAAU,6BAAM,gBAAgB;AAAA,QAChE,CAAC;AAED,cAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,YAAI,OAAO;AACT,gBAAM;AAAA,QACR;AAEA,eAAO,MAAM,IAAI,KAAK;AAAA,MACxB,SAAS,OAAO;AACd,cAAM,0BAA0B,KAAK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAO,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC1F;AACF;AArLa,QACwB,kBAA0B;;;AD/E/D,IAAO,cAAQ;","names":["import_e2b","import_e2b","BaseSandbox","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAA6D;;;ACA7D,iBAA0D;AAG1D,eAAsB,aAAa,KAAe;AAChD,MAAI,IAAI,IAAI;AACV;AAAA,EACF;AAEA,UAAQ,IAAI,QAAQ;AAAA,IAClB,KAAK;AACH,aAAO,IAAI;AAAA,QACT,GAAG,MAAM,IAAI,KAAK,CAAC;AAAA,MACrB;AAAA,IACF,KAAK;AACH,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A,MAAK;AAAA,IACvC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,kBAAkB,MAAgD;AACtE,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,QACrD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,UAAU,6BAAM;AAAA,UAChB,KAAK,6BAAM;AAAA,QACb,CAAC;AAAA,QACD,WAAW;AAAA,QACX,QAAQ,KAAK,iBAAiB,UAAU,6BAAM,gBAAgB;AAAA,MAChE,CAAC;AAED,YAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,UAAI,OAAO;AACT,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,OAAO;AACd,YAAM,0BAA0B,KAAK;AAAA,IACvC;AAAA,EACF;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAO,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC1F;AACF;AArLa,QACwB,kBAA0B;;;AD/E/D,IAAO,cAAQ;","names":["import_e2b","import_e2b","BaseSandbox","error"]}
package/dist/index.mjs CHANGED
@@ -18,26 +18,6 @@ var __spreadValues = (a, b) => {
18
18
  return a;
19
19
  };
20
20
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
- var __async = (__this, __arguments, generator) => {
22
- return new Promise((resolve, reject) => {
23
- var fulfilled = (value) => {
24
- try {
25
- step(generator.next(value));
26
- } catch (e) {
27
- reject(e);
28
- }
29
- };
30
- var rejected = (value) => {
31
- try {
32
- step(generator.throw(value));
33
- } catch (e) {
34
- reject(e);
35
- }
36
- };
37
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
38
- step((generator = generator.apply(__this, __arguments)).next());
39
- });
40
- };
41
21
  var __await = function(promise, isYieldStar) {
42
22
  this[0] = promise;
43
23
  this[1] = isYieldStar;
@@ -63,22 +43,20 @@ import { Sandbox as BaseSandbox, InvalidArgumentError } from "e2b";
63
43
 
64
44
  // src/messaging.ts
65
45
  import { NotFoundError, SandboxError, TimeoutError } from "e2b";
66
- function extractError(res) {
67
- return __async(this, null, function* () {
68
- if (res.ok) {
69
- return;
70
- }
71
- switch (res.status) {
72
- case 502:
73
- return new TimeoutError(
74
- `${yield res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`
75
- );
76
- case 404:
77
- return new NotFoundError(yield res.text());
78
- default:
79
- return new SandboxError(`${res.status} ${res.statusText}`);
80
- }
81
- });
46
+ async function extractError(res) {
47
+ if (res.ok) {
48
+ return;
49
+ }
50
+ switch (res.status) {
51
+ case 502:
52
+ return new TimeoutError(
53
+ `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`
54
+ );
55
+ case 404:
56
+ return new NotFoundError(await res.text());
57
+ default:
58
+ return new SandboxError(`${res.status} ${res.statusText}`);
59
+ }
82
60
  }
83
61
  var ExecutionError = class {
84
62
  constructor(name, value, traceback) {
@@ -217,51 +195,49 @@ var Execution = class {
217
195
  };
218
196
  }
219
197
  };
220
- function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
221
- return __async(this, null, function* () {
222
- const msg = JSON.parse(line);
223
- switch (msg.type) {
224
- case "result":
225
- const result = new Result(
226
- __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
227
- msg.is_main_result
228
- );
229
- execution.results.push(result);
230
- if (onResult) {
231
- yield onResult(result);
232
- }
233
- break;
234
- case "stdout":
235
- execution.logs.stdout.push(msg.text);
236
- if (onStdout) {
237
- yield onStdout({
238
- error: false,
239
- line: msg.text,
240
- timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
241
- });
242
- }
243
- break;
244
- case "stderr":
245
- execution.logs.stderr.push(msg.text);
246
- if (onStderr) {
247
- yield onStderr({
248
- error: true,
249
- line: msg.text,
250
- timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
251
- });
252
- }
253
- break;
254
- case "error":
255
- execution.error = new ExecutionError(msg.name, msg.value, msg.traceback);
256
- if (onError) {
257
- yield onError(execution.error);
258
- }
259
- break;
260
- case "number_of_executions":
261
- execution.executionCount = msg.execution_count;
262
- break;
263
- }
264
- });
198
+ async function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
199
+ const msg = JSON.parse(line);
200
+ switch (msg.type) {
201
+ case "result":
202
+ const result = new Result(
203
+ __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
204
+ msg.is_main_result
205
+ );
206
+ execution.results.push(result);
207
+ if (onResult) {
208
+ await onResult(result);
209
+ }
210
+ break;
211
+ case "stdout":
212
+ execution.logs.stdout.push(msg.text);
213
+ if (onStdout) {
214
+ await onStdout({
215
+ error: false,
216
+ line: msg.text,
217
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
218
+ });
219
+ }
220
+ break;
221
+ case "stderr":
222
+ execution.logs.stderr.push(msg.text);
223
+ if (onStderr) {
224
+ await onStderr({
225
+ error: true,
226
+ line: msg.text,
227
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
228
+ });
229
+ }
230
+ break;
231
+ case "error":
232
+ execution.error = new ExecutionError(msg.name, msg.value, msg.traceback);
233
+ if (onError) {
234
+ await onError(execution.error);
235
+ }
236
+ break;
237
+ case "number_of_executions":
238
+ execution.executionCount = msg.execution_count;
239
+ break;
240
+ }
265
241
  }
266
242
 
267
243
  // src/utils.ts
@@ -315,71 +291,69 @@ var JUPYTER_PORT = 49999;
315
291
 
316
292
  // src/sandbox.ts
317
293
  var Sandbox = class extends BaseSandbox {
318
- runCode(code, opts) {
319
- return __async(this, null, function* () {
320
- var _a, _b, _c;
321
- if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
322
- throw new InvalidArgumentError("You can provide context or language, but not both at the same time.");
294
+ async runCode(code, opts) {
295
+ var _a, _b, _c;
296
+ if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
297
+ throw new InvalidArgumentError("You can provide context or language, but not both at the same time.");
298
+ }
299
+ const controller = new AbortController();
300
+ const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
301
+ const reqTimer = requestTimeout ? setTimeout(() => {
302
+ controller.abort();
303
+ }, requestTimeout) : void 0;
304
+ try {
305
+ const res = await fetch(`${this.jupyterUrl}/execute`, {
306
+ method: "POST",
307
+ headers: {
308
+ "Content-Type": "application/json"
309
+ },
310
+ body: JSON.stringify({
311
+ code,
312
+ context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
313
+ language: opts == null ? void 0 : opts.language,
314
+ env_vars: opts == null ? void 0 : opts.envs
315
+ }),
316
+ signal: controller.signal,
317
+ keepalive: true
318
+ });
319
+ const error2 = await extractError(res);
320
+ if (error2) {
321
+ throw error2;
322
+ }
323
+ if (!res.body) {
324
+ throw new Error(`Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`);
323
325
  }
324
- const controller = new AbortController();
325
- const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
326
- const reqTimer = requestTimeout ? setTimeout(() => {
326
+ clearTimeout(reqTimer);
327
+ const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
328
+ const bodyTimer = bodyTimeout ? setTimeout(() => {
327
329
  controller.abort();
328
- }, requestTimeout) : void 0;
330
+ }, bodyTimeout) : void 0;
331
+ const execution = new Execution();
329
332
  try {
330
- const res = yield fetch(`${this.jupyterUrl}/execute`, {
331
- method: "POST",
332
- headers: {
333
- "Content-Type": "application/json"
334
- },
335
- body: JSON.stringify({
336
- code,
337
- context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
338
- language: opts == null ? void 0 : opts.language,
339
- env_vars: opts == null ? void 0 : opts.envs
340
- }),
341
- signal: controller.signal,
342
- keepalive: true
343
- });
344
- const error2 = yield extractError(res);
345
- if (error2) {
346
- throw error2;
347
- }
348
- if (!res.body) {
349
- throw new Error(`Not response body: ${res.statusText} ${yield res == null ? void 0 : res.text()}`);
350
- }
351
- clearTimeout(reqTimer);
352
- const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
353
- const bodyTimer = bodyTimeout ? setTimeout(() => {
354
- controller.abort();
355
- }, bodyTimeout) : void 0;
356
- const execution = new Execution();
357
333
  try {
334
+ for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
335
+ const chunk = temp.value;
336
+ await parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
337
+ }
338
+ } catch (temp) {
339
+ error = [temp];
340
+ } finally {
358
341
  try {
359
- for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
360
- const chunk = temp.value;
361
- yield parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
362
- }
363
- } catch (temp) {
364
- error = [temp];
342
+ more && (temp = iter.return) && await temp.call(iter);
365
343
  } finally {
366
- try {
367
- more && (temp = iter.return) && (yield temp.call(iter));
368
- } finally {
369
- if (error)
370
- throw error[0];
371
- }
344
+ if (error)
345
+ throw error[0];
372
346
  }
373
- } catch (error3) {
374
- throw formatExecutionTimeoutError(error3);
375
- } finally {
376
- clearTimeout(bodyTimer);
377
347
  }
378
- return execution;
379
- } catch (error2) {
380
- throw formatRequestTimeoutError(error2);
348
+ } catch (error3) {
349
+ throw formatExecutionTimeoutError(error3);
350
+ } finally {
351
+ clearTimeout(bodyTimer);
381
352
  }
382
- });
353
+ return execution;
354
+ } catch (error2) {
355
+ throw formatRequestTimeoutError(error2);
356
+ }
383
357
  }
384
358
  /**
385
359
  * Creates a new context to run code in.
@@ -388,30 +362,28 @@ var Sandbox = class extends BaseSandbox {
388
362
  *
389
363
  * @returns context object.
390
364
  */
391
- createCodeContext(opts) {
392
- return __async(this, null, function* () {
393
- try {
394
- const res = yield fetch(`${this.jupyterUrl}/contexts`, {
395
- method: "POST",
396
- headers: {
397
- "Content-Type": "application/json"
398
- },
399
- body: JSON.stringify({
400
- language: opts == null ? void 0 : opts.language,
401
- cwd: opts == null ? void 0 : opts.cwd
402
- }),
403
- keepalive: true,
404
- signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
405
- });
406
- const error = yield extractError(res);
407
- if (error) {
408
- throw error;
409
- }
410
- return yield res.json();
411
- } catch (error) {
412
- throw formatRequestTimeoutError(error);
365
+ async createCodeContext(opts) {
366
+ try {
367
+ const res = await fetch(`${this.jupyterUrl}/contexts`, {
368
+ method: "POST",
369
+ headers: {
370
+ "Content-Type": "application/json"
371
+ },
372
+ body: JSON.stringify({
373
+ language: opts == null ? void 0 : opts.language,
374
+ cwd: opts == null ? void 0 : opts.cwd
375
+ }),
376
+ keepalive: true,
377
+ signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
378
+ });
379
+ const error = await extractError(res);
380
+ if (error) {
381
+ throw error;
413
382
  }
414
- });
383
+ return await res.json();
384
+ } catch (error) {
385
+ throw formatRequestTimeoutError(error);
386
+ }
415
387
  }
416
388
  get jupyterUrl() {
417
389
  return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_P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+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS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2b/code-interpreter",
3
- "version": "1.2.5-autopause.1",
4
- "packageManager": "pnpm@8.7.6",
3
+ "version": "1.5.0",
5
4
  "description": "E2B Code Interpreter - Stateful code execution",
6
5
  "homepage": "https://e2b.dev",
7
6
  "license": "MIT",
@@ -23,30 +22,16 @@
23
22
  "main": "dist/index.js",
24
23
  "module": "dist/index.mjs",
25
24
  "types": "dist/index.d.ts",
26
- "scripts": {
27
- "prepublishOnly": "pnpm build",
28
- "build": "tsc --noEmit && tsup",
29
- "dev": "tsup --watch",
30
- "test": "vitest run",
31
- "test:coverage": "vitest run --coverage",
32
- "check-deps": "knip",
33
- "update-deps": "ncu -u && pnpm i",
34
- "example": "npx tsx example.mts",
35
- "test:bun": "bun test tests/runtimes/bun --env-file=.env",
36
- "test:deno": "deno test tests/runtimes/deno/ --allow-net --allow-read --allow-env --unstable-sloppy-imports --trace-leaks",
37
- "generate-ref": "./scripts/generate_sdk_ref.sh"
38
- },
39
25
  "devDependencies": {
40
26
  "@types/node": "^18.18.6",
41
- "@types/ws": "^8.5.10",
42
27
  "dotenv": "^16.4.5",
43
28
  "knip": "^5.25.1",
44
- "npm-check-updates": "^16.14.20",
45
- "tsup": "^8.1.0",
46
- "typedoc": "^0.26.8",
47
- "typedoc-plugin-markdown": "^4.2.7",
29
+ "npm-check-updates": "^17.1.14",
30
+ "tsup": "^8.4.0",
31
+ "typedoc": "0.26.8",
32
+ "typedoc-plugin-markdown": "4.2.7",
48
33
  "typescript": "^5.5.3",
49
- "vitest": "^2.0.1"
34
+ "vitest": "^3.0.9"
50
35
  },
51
36
  "files": [
52
37
  "dist",
@@ -67,12 +52,24 @@
67
52
  "vm"
68
53
  ],
69
54
  "dependencies": {
70
- "e2b": "1.2.5-autopause.1"
55
+ "e2b": "^1.4.0"
71
56
  },
72
57
  "engines": {
73
58
  "node": ">=18"
74
59
  },
75
60
  "browserslist": [
76
61
  "defaults"
77
- ]
78
- }
62
+ ],
63
+ "scripts": {
64
+ "build": "tsc --noEmit && tsup",
65
+ "dev": "tsup --watch",
66
+ "test": "vitest run",
67
+ "test:coverage": "vitest run --coverage",
68
+ "check-deps": "knip",
69
+ "update-deps": "ncu -u && pnpm i",
70
+ "example": "npx tsx example.mts",
71
+ "test:bun": "bun test tests/runtimes/bun --env-file=.env",
72
+ "test:deno": "deno test tests/runtimes/deno/ --allow-net --allow-read --allow-env --unstable-sloppy-imports --trace-leaks",
73
+ "generate-ref": "./scripts/generate_sdk_ref.sh"
74
+ }
75
+ }