@e2b/code-interpreter 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -427,6 +427,7 @@ interface CreateCodeContextOpts {
427
427
  */
428
428
  declare class Sandbox extends Sandbox$1 {
429
429
  protected static readonly defaultTemplate: string;
430
+ protected get jupyterUrl(): string;
430
431
  /**
431
432
  * Run the code as Python.
432
433
  *
@@ -494,7 +495,6 @@ declare class Sandbox extends Sandbox$1 {
494
495
  * @returns context object.
495
496
  */
496
497
  createCodeContext(opts?: CreateCodeContextOpts): Promise<Context>;
497
- protected get jupyterUrl(): string;
498
498
  }
499
499
 
500
500
  export { type BarChart, type BarData, type BoxAndWhiskerChart, type BoxAndWhiskerData, type Chart, ChartType, type ChartTypes, type Context, type CreateCodeContextOpts, Execution, ExecutionError, type LineChart, type Logs, type MIMEType, OutputMessage, type PieChart, type PieData, type PointData, type RawData, Result, type RunCodeOpts, Sandbox, ScaleType, type ScatterChart, type SuperChart, Sandbox as default };
package/dist/index.d.ts CHANGED
@@ -427,6 +427,7 @@ interface CreateCodeContextOpts {
427
427
  */
428
428
  declare class Sandbox extends Sandbox$1 {
429
429
  protected static readonly defaultTemplate: string;
430
+ protected get jupyterUrl(): string;
430
431
  /**
431
432
  * Run the code as Python.
432
433
  *
@@ -494,7 +495,6 @@ declare class Sandbox extends Sandbox$1 {
494
495
  * @returns context object.
495
496
  */
496
497
  createCodeContext(opts?: CreateCodeContextOpts): Promise<Context>;
497
- protected get jupyterUrl(): string;
498
498
  }
499
499
 
500
500
  export { type BarChart, type BarData, type BoxAndWhiskerChart, type BoxAndWhiskerData, type Chart, ChartType, type ChartTypes, type Context, type CreateCodeContextOpts, Execution, ExecutionError, type LineChart, type Logs, type MIMEType, OutputMessage, type PieChart, type PieData, type PointData, type RawData, Result, type RunCodeOpts, Sandbox, ScaleType, type ScatterChart, type SuperChart, Sandbox as default };
package/dist/index.js CHANGED
@@ -221,7 +221,7 @@ var Execution = class {
221
221
  async function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
222
222
  const msg = JSON.parse(line);
223
223
  switch (msg.type) {
224
- case "result":
224
+ case "result": {
225
225
  const result = new Result(
226
226
  __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
227
227
  msg.is_main_result
@@ -231,6 +231,7 @@ async function parseOutput(execution, line, onStdout, onStderr, onResult, onErro
231
231
  await onResult(result);
232
232
  }
233
233
  break;
234
+ }
234
235
  case "stdout":
235
236
  execution.logs.stdout.push(msg.text);
236
237
  if (onStdout) {
@@ -267,13 +268,17 @@ async function parseOutput(execution, line, onStdout, onStderr, onResult, onErro
267
268
  var import_e2b2 = require("e2b");
268
269
  function formatRequestTimeoutError(error) {
269
270
  if (error instanceof Error && error.name === "AbortError") {
270
- return new import_e2b2.TimeoutError("Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout");
271
+ return new import_e2b2.TimeoutError(
272
+ "Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout"
273
+ );
271
274
  }
272
275
  return error;
273
276
  }
274
277
  function formatExecutionTimeoutError(error) {
275
278
  if (error instanceof Error && error.name === "AbortError") {
276
- return new import_e2b2.TimeoutError("Execution timed out \u2014 the 'timeoutMs' option can be used to increase this timeout");
279
+ return new import_e2b2.TimeoutError(
280
+ "Execution timed out \u2014 the 'timeoutMs' option can be used to increase this timeout"
281
+ );
277
282
  }
278
283
  return error;
279
284
  }
@@ -314,6 +319,11 @@ var JUPYTER_PORT = 49999;
314
319
 
315
320
  // src/sandbox.ts
316
321
  var Sandbox = class extends import_e2b3.Sandbox {
322
+ get jupyterUrl() {
323
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
324
+ JUPYTER_PORT
325
+ )}`;
326
+ }
317
327
  async runCode(code, opts) {
318
328
  var _a, _b, _c;
319
329
  if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
@@ -423,11 +433,6 @@ var Sandbox = class extends import_e2b3.Sandbox {
423
433
  throw formatRequestTimeoutError(error);
424
434
  }
425
435
  }
426
- get jupyterUrl() {
427
- return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
428
- JUPYTER_PORT
429
- )}`;
430
- }
431
436
  };
432
437
  Sandbox.defaultTemplate = "code-interpreter-v1";
433
438
 
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 {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} 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 =\n '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(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\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(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\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 ...this.connectionConfig.headers,\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(\n JUPYTER_PORT\n )}`\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,aAAO,IAAI,yBAAc,MAAM,IAAI,KAAK,CAAC;AAAA,IAC3C;AACE,aAAO,IAAI,wBAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,EAC7D;AACF;AA8BO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,WACP;AATO;AAIA;AAIA;AAAA,EACL;AACN;AA6BO,IAAM,SAAN,MAAa;AAAA,EAwDlB,YAAY,SAAkC,cAAuB;AAAvB;AAC5C,UAAM,OAAO,mBAAK;AAClB,WAAO,KAAK,MAAM;AAClB,WAAO,KAAK,gBAAgB;AAE5B,SAAK,OAAO,KAAK,MAAM;AACvB,SAA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,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;AAAA,MACjE;AAAA,IACF,CAAC;AAAA,EACH;AACF;AA1Ma,QACwB,kBACjC;;;AD3FJ,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 {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} 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 =\n 'code-interpreter-v1'\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(\n JUPYTER_PORT\n )}`\n }\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(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\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(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\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 ...this.connectionConfig.headers,\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","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\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 }\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(\n \"Request timed out — the 'requestTimeoutMs' option can be used to increase this timeout\"\n )\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError(\n \"Execution timed out — the 'timeoutMs' option can be used to increase this timeout\"\n )\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,aAAO,IAAI,yBAAc,MAAM,IAAI,KAAK,CAAC;AAAA,IAC3C;AACE,aAAO,IAAI,wBAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,EAC7D;AACF;A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A,QAAO;AACd,cAAM,4BAA4BA,MAAK;AAAA,MACzC,UAAE;AACA,qBAAa,SAAS;AAAA,MACxB;AAEA,aAAO;AAAA,IACT,SAASA,QAAO;AACd,YAAM,0BAA0BA,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,WACb,KAAK,iBAAiB;AAAA,QAE3B,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;AACF;AA1Ma,QACwB,kBACjC;;;AD3FJ,IAAO,cAAQ;","names":["import_e2b","import_e2b","BaseSandbox","error"]}
package/dist/index.mjs CHANGED
@@ -198,7 +198,7 @@ var Execution = class {
198
198
  async function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
199
199
  const msg = JSON.parse(line);
200
200
  switch (msg.type) {
201
- case "result":
201
+ case "result": {
202
202
  const result = new Result(
203
203
  __spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }),
204
204
  msg.is_main_result
@@ -208,6 +208,7 @@ async function parseOutput(execution, line, onStdout, onStderr, onResult, onErro
208
208
  await onResult(result);
209
209
  }
210
210
  break;
211
+ }
211
212
  case "stdout":
212
213
  execution.logs.stdout.push(msg.text);
213
214
  if (onStdout) {
@@ -244,13 +245,17 @@ async function parseOutput(execution, line, onStdout, onStderr, onResult, onErro
244
245
  import { TimeoutError as TimeoutError2 } from "e2b";
245
246
  function formatRequestTimeoutError(error) {
246
247
  if (error instanceof Error && error.name === "AbortError") {
247
- return new TimeoutError2("Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout");
248
+ return new TimeoutError2(
249
+ "Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout"
250
+ );
248
251
  }
249
252
  return error;
250
253
  }
251
254
  function formatExecutionTimeoutError(error) {
252
255
  if (error instanceof Error && error.name === "AbortError") {
253
- return new TimeoutError2("Execution timed out \u2014 the 'timeoutMs' option can be used to increase this timeout");
256
+ return new TimeoutError2(
257
+ "Execution timed out \u2014 the 'timeoutMs' option can be used to increase this timeout"
258
+ );
254
259
  }
255
260
  return error;
256
261
  }
@@ -291,6 +296,11 @@ var JUPYTER_PORT = 49999;
291
296
 
292
297
  // src/sandbox.ts
293
298
  var Sandbox = class extends BaseSandbox {
299
+ get jupyterUrl() {
300
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
301
+ JUPYTER_PORT
302
+ )}`;
303
+ }
294
304
  async runCode(code, opts) {
295
305
  var _a, _b, _c;
296
306
  if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
@@ -400,11 +410,6 @@ var Sandbox = class extends BaseSandbox {
400
410
  throw formatRequestTimeoutError(error);
401
411
  }
402
412
  }
403
- get jupyterUrl() {
404
- return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
405
- JUPYTER_PORT
406
- )}`;
407
- }
408
413
  };
409
414
  Sandbox.defaultTemplate = "code-interpreter-v1";
410
415
 
@@ -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 {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} 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 =\n '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(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\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(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\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 ...this.connectionConfig.headers,\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(\n JUPYTER_PORT\n )}`\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 = 49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ACjC;;;AD3FJ,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","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 {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} 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 =\n 'code-interpreter-v1'\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(\n JUPYTER_PORT\n )}`\n }\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(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\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(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\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 ...this.connectionConfig.headers,\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","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\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 }\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(\n \"Request timed out — the 'requestTimeoutMs' option can be used to increase this timeout\"\n )\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError(\n \"Execution timed out — the 'timeoutMs' option can be used to increase this timeout\"\n )\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,cAAc;;;ACAd,SAAS,WAAW,aAAa,4BAA4B;;;ACA7D,SAAS,eAAe,cAAc,oBAAoB;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,aAAO,IAAI,cAAc,MAAM,IAAI,KAAK,CAAC;AAAA,IAC3C;AACE,aAAO,IAAI,aAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,EAC7D;AACF;AA8BO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,WACP;AATO;AAIA;AAIA;AAAA,EACN;AACL;AA4BO,IAAM,SAAN,MAAa;AAAA,EAwDlB,YAAY,SAAkC,cAAuB;AAAvB;AAC5C,UAAM,OAAO,mBAAK;AAClB,WAAO,KAAK,MAAM;AAClB,WAAO,KAAK,gBAAgB;AAE5B,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,WAAW,KAAK,UAAU;AAC/B,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,QAAQ,KAAK,OAAO;AACzB,SAAK,OAAO,KAAK,MAAM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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;AACF;AA1Ma,QACwB,kBACjC;;;AD3FJ,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/code-interpreter",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "E2B Code Interpreter - Stateful code execution",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  "module": "dist/index.mjs",
24
24
  "types": "dist/index.d.ts",
25
25
  "devDependencies": {
26
- "@types/node": "^18.18.6",
26
+ "@types/node": "^20.19.19",
27
27
  "dotenv": "^16.4.5",
28
28
  "knip": "^5.25.1",
29
29
  "npm-check-updates": "^17.1.14",
@@ -51,15 +51,15 @@
51
51
  "runtime",
52
52
  "vm"
53
53
  ],
54
- "dependencies": {
55
- "e2b": "^2.0.1"
56
- },
57
54
  "engines": {
58
- "node": ">=18"
55
+ "node": ">=20"
59
56
  },
60
57
  "browserslist": [
61
58
  "defaults"
62
59
  ],
60
+ "dependencies": {
61
+ "e2b": "^2.2.1"
62
+ },
63
63
  "scripts": {
64
64
  "build": "tsc --noEmit && tsup",
65
65
  "dev": "tsup --watch",
@@ -70,6 +70,8 @@
70
70
  "example": "npx tsx example.mts",
71
71
  "test:bun": "bun test tests/runtimes/bun --env-file=.env",
72
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"
73
+ "generate-ref": "./scripts/generate_sdk_ref.sh",
74
+ "lint": "eslint src/ tests/",
75
+ "format": "prettier --write src/ tests/ example.mts"
74
76
  }
75
77
  }