@boxfab/code-interpreter 0.0.1-placeholder.1 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,718 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ let boxfab = require("boxfab");
6
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
7
+ function _typeof(o) {
8
+ "@babel/helpers - typeof";
9
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
10
+ return typeof o;
11
+ } : function(o) {
12
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
13
+ }, _typeof(o);
14
+ }
15
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPrimitive.js
16
+ function toPrimitive(t, r) {
17
+ if ("object" != _typeof(t) || !t) return t;
18
+ var e = t[Symbol.toPrimitive];
19
+ if (void 0 !== e) {
20
+ var i = e.call(t, r || "default");
21
+ if ("object" != _typeof(i)) return i;
22
+ throw new TypeError("@@toPrimitive must return a primitive value.");
23
+ }
24
+ return ("string" === r ? String : Number)(t);
25
+ }
26
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPropertyKey.js
27
+ function toPropertyKey(t) {
28
+ var i = toPrimitive(t, "string");
29
+ return "symbol" == _typeof(i) ? i : i + "";
30
+ }
31
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/defineProperty.js
32
+ function _defineProperty(e, r, t) {
33
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
34
+ value: t,
35
+ enumerable: !0,
36
+ configurable: !0,
37
+ writable: !0
38
+ }) : e[r] = t, e;
39
+ }
40
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/objectSpread2.js
41
+ function ownKeys(e, r) {
42
+ var t = Object.keys(e);
43
+ if (Object.getOwnPropertySymbols) {
44
+ var o = Object.getOwnPropertySymbols(e);
45
+ r && (o = o.filter(function(r) {
46
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
47
+ })), t.push.apply(t, o);
48
+ }
49
+ return t;
50
+ }
51
+ function _objectSpread2(e) {
52
+ for (var r = 1; r < arguments.length; r++) {
53
+ var t = null != arguments[r] ? arguments[r] : {};
54
+ r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
55
+ _defineProperty(e, r, t[r]);
56
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
57
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
58
+ });
59
+ }
60
+ return e;
61
+ }
62
+ // src/messaging.ts
63
+ async function extractError(res) {
64
+ if (res.ok) return;
65
+ switch (res.status) {
66
+ case 502: return new boxfab.TimeoutError(`${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.`);
67
+ case 404: return new boxfab.NotFoundError(await res.text());
68
+ default: {
69
+ const body = (await res.text()).trim();
70
+ return new boxfab.SandboxError(`${res.status} ${res.statusText}${body ? `: ${body}` : ""}`);
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Represents an error that occurred during the execution of a cell.
76
+ * The error contains the name of the error, the value of the error, and the traceback.
77
+ */
78
+ var ExecutionError = class {
79
+ constructor(name, value, traceback) {
80
+ this.name = name;
81
+ this.value = value;
82
+ this.traceback = traceback;
83
+ }
84
+ };
85
+ /**
86
+ * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.
87
+ * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics
88
+ *
89
+ *
90
+ * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented
91
+ * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,
92
+ * for the actual result the representation is always present for the result, the other representations are always optional.
93
+ */
94
+ var Result = class {
95
+ constructor(rawData, isMainResult) {
96
+ this.isMainResult = isMainResult;
97
+ _defineProperty(this, "text", void 0);
98
+ _defineProperty(this, "html", void 0);
99
+ _defineProperty(this, "markdown", void 0);
100
+ _defineProperty(this, "svg", void 0);
101
+ _defineProperty(this, "png", void 0);
102
+ _defineProperty(this, "jpeg", void 0);
103
+ _defineProperty(this, "pdf", void 0);
104
+ _defineProperty(this, "latex", void 0);
105
+ _defineProperty(this, "json", void 0);
106
+ _defineProperty(this, "javascript", void 0);
107
+ _defineProperty(this, "data", void 0);
108
+ _defineProperty(this, "chart", void 0);
109
+ _defineProperty(this, "extra", void 0);
110
+ _defineProperty(this, "raw", void 0);
111
+ const data = _objectSpread2({}, rawData);
112
+ delete data["type"];
113
+ delete data["is_main_result"];
114
+ this.text = data["text"];
115
+ this.html = data["html"];
116
+ this.markdown = data["markdown"];
117
+ this.svg = data["svg"];
118
+ this.png = data["png"];
119
+ this.jpeg = data["jpeg"];
120
+ this.pdf = data["pdf"];
121
+ this.latex = data["latex"];
122
+ this.json = data["json"];
123
+ this.javascript = data["javascript"];
124
+ this.isMainResult = isMainResult;
125
+ this.raw = data;
126
+ this.data = data["data"];
127
+ this.chart = data["chart"];
128
+ this.extra = {};
129
+ for (const key of Object.keys(data)) if (![
130
+ "plain",
131
+ "html",
132
+ "markdown",
133
+ "svg",
134
+ "png",
135
+ "jpeg",
136
+ "pdf",
137
+ "latex",
138
+ "json",
139
+ "javascript",
140
+ "data",
141
+ "chart",
142
+ "extra",
143
+ "text"
144
+ ].includes(key)) this.extra[key] = data[key];
145
+ }
146
+ /**
147
+ * Returns all the formats available for the result.
148
+ *
149
+ * @returns Array of strings representing the formats available for the result.
150
+ */
151
+ formats() {
152
+ const formats = [];
153
+ if (this.html) formats.push("html");
154
+ if (this.markdown) formats.push("markdown");
155
+ if (this.svg) formats.push("svg");
156
+ if (this.png) formats.push("png");
157
+ if (this.jpeg) formats.push("jpeg");
158
+ if (this.pdf) formats.push("pdf");
159
+ if (this.latex) formats.push("latex");
160
+ if (this.json) formats.push("json");
161
+ if (this.javascript) formats.push("javascript");
162
+ if (this.data) formats.push("data");
163
+ for (const key of Object.keys(this.extra)) formats.push(key);
164
+ return formats;
165
+ }
166
+ /**
167
+ * Returns the serializable representation of the result.
168
+ */
169
+ toJSON() {
170
+ return _objectSpread2({
171
+ text: this.text,
172
+ html: this.html,
173
+ markdown: this.markdown,
174
+ svg: this.svg,
175
+ png: this.png,
176
+ jpeg: this.jpeg,
177
+ pdf: this.pdf,
178
+ latex: this.latex,
179
+ json: this.json,
180
+ javascript: this.javascript
181
+ }, Object.keys(this.extra).length > 0 ? { extra: this.extra } : {});
182
+ }
183
+ };
184
+ /**
185
+ * Represents the result of a cell execution.
186
+ */
187
+ var Execution = class {
188
+ constructor(results = [], logs = {
189
+ stdout: [],
190
+ stderr: []
191
+ }, error, executionCount) {
192
+ this.results = results;
193
+ this.logs = logs;
194
+ this.error = error;
195
+ this.executionCount = executionCount;
196
+ }
197
+ /**
198
+ * Returns the text representation of the main result of the cell.
199
+ */
200
+ get text() {
201
+ for (const data of this.results) if (data.isMainResult) return data.text;
202
+ }
203
+ /**
204
+ * Returns the serializable representation of the execution result.
205
+ */
206
+ toJSON() {
207
+ return {
208
+ results: this.results,
209
+ logs: this.logs,
210
+ error: this.error
211
+ };
212
+ }
213
+ };
214
+ async function parseOutput(execution, line, onStdout, onStderr, onResult, onError) {
215
+ const msg = JSON.parse(line);
216
+ switch (msg.type) {
217
+ case "result": {
218
+ const result = new Result(_objectSpread2(_objectSpread2({}, msg), {}, {
219
+ type: void 0,
220
+ is_main_result: void 0
221
+ }), msg.is_main_result);
222
+ execution.results.push(result);
223
+ if (onResult) await onResult(result);
224
+ break;
225
+ }
226
+ case "stdout":
227
+ execution.logs.stdout.push(msg.text);
228
+ if (onStdout) await onStdout({
229
+ error: false,
230
+ line: msg.text,
231
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
232
+ });
233
+ break;
234
+ case "stderr":
235
+ execution.logs.stderr.push(msg.text);
236
+ if (onStderr) await onStderr({
237
+ error: true,
238
+ line: msg.text,
239
+ timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3
240
+ });
241
+ break;
242
+ case "error":
243
+ execution.error = new ExecutionError(msg.name, msg.value, msg.traceback);
244
+ if (onError) await onError(execution.error);
245
+ break;
246
+ case "number_of_executions": execution.executionCount = msg.execution_count;
247
+ }
248
+ }
249
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/OverloadYield.js
250
+ function _OverloadYield(e, d) {
251
+ this.v = e, this.k = d;
252
+ }
253
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/awaitAsyncGenerator.js
254
+ function _awaitAsyncGenerator(e) {
255
+ return new _OverloadYield(e, 0);
256
+ }
257
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/wrapAsyncGenerator.js
258
+ function _wrapAsyncGenerator(e) {
259
+ return function() {
260
+ return new AsyncGenerator(e.apply(this, arguments));
261
+ };
262
+ }
263
+ function AsyncGenerator(e) {
264
+ var r, t;
265
+ function resume(r, t) {
266
+ try {
267
+ var n = e[r](t), o = n.value, u = o instanceof _OverloadYield;
268
+ Promise.resolve(u ? o.v : o).then(function(t) {
269
+ if (u) {
270
+ var i = "return" === r ? "return" : "next";
271
+ if (!o.k || t.done) return resume(i, t);
272
+ t = e[i](t).value;
273
+ }
274
+ settle(n.done ? "return" : "normal", t);
275
+ }, function(e) {
276
+ resume("throw", e);
277
+ });
278
+ } catch (e) {
279
+ settle("throw", e);
280
+ }
281
+ }
282
+ function settle(e, n) {
283
+ switch (e) {
284
+ case "return":
285
+ r.resolve({
286
+ value: n,
287
+ done: !0
288
+ });
289
+ break;
290
+ case "throw":
291
+ r.reject(n);
292
+ break;
293
+ default: r.resolve({
294
+ value: n,
295
+ done: !1
296
+ });
297
+ }
298
+ (r = r.next) ? resume(r.key, r.arg) : t = null;
299
+ }
300
+ this._invoke = function(e, n) {
301
+ return new Promise(function(o, u) {
302
+ var i = {
303
+ key: e,
304
+ arg: n,
305
+ resolve: o,
306
+ reject: u,
307
+ next: null
308
+ };
309
+ t ? t = t.next = i : (r = t = i, resume(e, n));
310
+ });
311
+ }, "function" != typeof e["return"] && (this["return"] = void 0);
312
+ }
313
+ AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
314
+ return this;
315
+ }, AsyncGenerator.prototype.next = function(e) {
316
+ return this._invoke("next", e);
317
+ }, AsyncGenerator.prototype["throw"] = function(e) {
318
+ return this._invoke("throw", e);
319
+ }, AsyncGenerator.prototype["return"] = function(e) {
320
+ return this._invoke("return", e);
321
+ };
322
+ // src/utils.ts
323
+ function formatRequestTimeoutError(error) {
324
+ if (error instanceof Error && error.name === "AbortError") return new boxfab.TimeoutError("Request timed out — the 'requestTimeoutMs' option can be used to increase this timeout");
325
+ return error;
326
+ }
327
+ function formatExecutionTimeoutError(error) {
328
+ if (error instanceof Error && error.name === "AbortError") return new boxfab.TimeoutError("Execution timed out — the 'timeoutMs' option can be used to increase this timeout");
329
+ return error;
330
+ }
331
+ const CONNECTION_CLOSED_CODES = [
332
+ "ECONNRESET",
333
+ "EPIPE",
334
+ "UND_ERR_SOCKET"
335
+ ];
336
+ const CONNECTION_CLOSED_MESSAGES = [
337
+ "error reading a body from connection",
338
+ "connection closed before message completed",
339
+ "connection reset by peer",
340
+ "network connection lost"
341
+ ];
342
+ /**
343
+ * Checks if the error means the connection was closed/reset while the request
344
+ * was in flight. The shape of this error is runtime-specific — Bun sets a
345
+ * `code` directly, Node's fetch (undici) wraps the socket error in the `cause`
346
+ * of a generic `TypeError`, and Deno and workerd only set a message.
347
+ */
348
+ function isConnectionClosedError(error) {
349
+ if (!(error instanceof Error)) return false;
350
+ const code = error.code;
351
+ if (typeof code === "string" && CONNECTION_CLOSED_CODES.includes(code)) return true;
352
+ if (error.name === "ConnectionReset" || error.name === "ConnectionClosed") return true;
353
+ const message = error.message.toLowerCase();
354
+ if (CONNECTION_CLOSED_MESSAGES.some((m) => message.includes(m))) return true;
355
+ if (error.cause) return isConnectionClosedError(error.cause);
356
+ return false;
357
+ }
358
+ function readLines(_x) {
359
+ return _readLines.apply(this, arguments);
360
+ }
361
+ function _readLines() {
362
+ _readLines = _wrapAsyncGenerator(function* (stream) {
363
+ const reader = stream.getReader();
364
+ const decoder = new TextDecoder();
365
+ let buffer = "";
366
+ try {
367
+ while (true) {
368
+ const { done, value } = yield _awaitAsyncGenerator(reader.read());
369
+ if (value !== void 0) buffer += decoder.decode(value, { stream: true });
370
+ if (done) {
371
+ buffer += decoder.decode();
372
+ if (buffer.length > 0) yield buffer;
373
+ break;
374
+ }
375
+ let newlineIdx = -1;
376
+ do {
377
+ newlineIdx = buffer.indexOf("\n");
378
+ if (newlineIdx !== -1) {
379
+ yield buffer.slice(0, newlineIdx);
380
+ buffer = buffer.slice(newlineIdx + 1);
381
+ }
382
+ } while (newlineIdx !== -1);
383
+ }
384
+ } finally {
385
+ reader.releaseLock();
386
+ }
387
+ });
388
+ return _readLines.apply(this, arguments);
389
+ }
390
+ // src/consts.ts
391
+ const DEFAULT_TIMEOUT_MS = 6e4;
392
+ const JUPYTER_PORT = 49999;
393
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/asyncIterator.js
394
+ function _asyncIterator(r) {
395
+ var n, t, o, e = 2;
396
+ for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
397
+ if (t && null != (n = r[t])) return n.call(r);
398
+ if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
399
+ t = "@@asyncIterator", o = "@@iterator";
400
+ }
401
+ throw new TypeError("Object is not async iterable");
402
+ }
403
+ function AsyncFromSyncIterator(r) {
404
+ function AsyncFromSyncIteratorContinuation(r) {
405
+ if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
406
+ var n = r.done;
407
+ return Promise.resolve(r.value).then(function(r) {
408
+ return {
409
+ value: r,
410
+ done: n
411
+ };
412
+ });
413
+ }
414
+ return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
415
+ this.s = r, this.n = r.next;
416
+ }, AsyncFromSyncIterator.prototype = {
417
+ s: null,
418
+ n: null,
419
+ next: function next() {
420
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
421
+ },
422
+ "return": function _return(r) {
423
+ var n = this.s["return"];
424
+ return void 0 === n ? Promise.resolve({
425
+ value: r,
426
+ done: !0
427
+ }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
428
+ },
429
+ "throw": function _throw(r) {
430
+ var n = this.s["throw"];
431
+ return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
432
+ }
433
+ }, new AsyncFromSyncIterator(r);
434
+ }
435
+ // src/sandbox.ts
436
+ /**
437
+ * BoxFab cloud sandbox is a secure and isolated cloud environment.
438
+ *
439
+ * The sandbox allows you to:
440
+ * - Access Linux OS
441
+ * - Create, list, and delete files and directories
442
+ * - Run commands
443
+ * - Run isolated code
444
+ * - Access the internet
445
+ *
446
+ * Check docs [here](https://boxfab.io/docs).
447
+ *
448
+ * Use {@link Sandbox.create} to create a new sandbox.
449
+ *
450
+ * @example
451
+ * ```ts
452
+ * import { Sandbox } from '@boxfab/code-interpreter'
453
+ *
454
+ * const sandbox = await Sandbox.create()
455
+ * ```
456
+ */
457
+ var Sandbox = class extends boxfab.Sandbox {
458
+ get jupyterUrl() {
459
+ return this.connectionConfig.getSandboxUrl(this.sandboxId, {
460
+ sandboxDomain: this.sandboxDomain,
461
+ envdPort: JUPYTER_PORT
462
+ });
463
+ }
464
+ async runCode(code, opts) {
465
+ var _opts$requestTimeoutM;
466
+ if ((opts === null || opts === void 0 ? void 0 : opts.context) && (opts === null || opts === void 0 ? void 0 : opts.language)) throw new boxfab.InvalidArgumentError("You can provide context or language, but not both at the same time.");
467
+ const controller = new AbortController();
468
+ const requestTimeout = (_opts$requestTimeoutM = opts === null || opts === void 0 ? void 0 : opts.requestTimeoutMs) !== null && _opts$requestTimeoutM !== void 0 ? _opts$requestTimeoutM : this.connectionConfig.requestTimeoutMs;
469
+ const reqTimer = requestTimeout ? setTimeout(() => {
470
+ controller.abort();
471
+ }, requestTimeout) : void 0;
472
+ const headers = {
473
+ "Content-Type": "application/json",
474
+ "E2b-Sandbox-Id": this.sandboxId,
475
+ "E2b-Sandbox-Port": JUPYTER_PORT.toString()
476
+ };
477
+ if (this.trafficAccessToken) headers["E2B-Traffic-Access-Token"] = this.trafficAccessToken;
478
+ if (this.envdAccessToken) headers["X-Access-Token"] = this.envdAccessToken;
479
+ try {
480
+ var _opts$context, _opts$timeoutMs;
481
+ const res = await fetch(`${this.jupyterUrl}/execute`, {
482
+ method: "POST",
483
+ headers,
484
+ body: JSON.stringify({
485
+ code,
486
+ context_id: opts === null || opts === void 0 || (_opts$context = opts.context) === null || _opts$context === void 0 ? void 0 : _opts$context.id,
487
+ language: opts === null || opts === void 0 ? void 0 : opts.language,
488
+ env_vars: opts === null || opts === void 0 ? void 0 : opts.envs
489
+ }),
490
+ signal: controller.signal,
491
+ keepalive: true
492
+ });
493
+ const error = await extractError(res);
494
+ if (error) throw error;
495
+ if (!res.body) throw new Error(`No response body: ${res.statusText} ${await (res === null || res === void 0 ? void 0 : res.text())}`);
496
+ clearTimeout(reqTimer);
497
+ const bodyTimeout = (_opts$timeoutMs = opts === null || opts === void 0 ? void 0 : opts.timeoutMs) !== null && _opts$timeoutMs !== void 0 ? _opts$timeoutMs : DEFAULT_TIMEOUT_MS;
498
+ const bodyTimer = bodyTimeout ? setTimeout(() => {
499
+ controller.abort();
500
+ }, bodyTimeout) : void 0;
501
+ const execution = new Execution();
502
+ try {
503
+ var _iteratorAbruptCompletion = false;
504
+ var _didIteratorError = false;
505
+ var _iteratorError;
506
+ try {
507
+ for (var _iterator = _asyncIterator(readLines(res.body)), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
508
+ const chunk = _step.value;
509
+ await parseOutput(execution, chunk, opts === null || opts === void 0 ? void 0 : opts.onStdout, opts === null || opts === void 0 ? void 0 : opts.onStderr, opts === null || opts === void 0 ? void 0 : opts.onResult, opts === null || opts === void 0 ? void 0 : opts.onError);
510
+ }
511
+ } catch (err) {
512
+ _didIteratorError = true;
513
+ _iteratorError = err;
514
+ } finally {
515
+ try {
516
+ if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
517
+ } finally {
518
+ if (_didIteratorError) throw _iteratorError;
519
+ }
520
+ }
521
+ } catch (error) {
522
+ throw formatExecutionTimeoutError(error);
523
+ } finally {
524
+ clearTimeout(bodyTimer);
525
+ }
526
+ return execution;
527
+ } catch (error) {
528
+ throw await this.handleRequestError(error);
529
+ }
530
+ }
531
+ /**
532
+ * Creates a new context to run code in.
533
+ *
534
+ * @param opts options for creating the context.
535
+ *
536
+ * @returns context object.
537
+ */
538
+ async createCodeContext(opts) {
539
+ try {
540
+ const headers = {
541
+ "Content-Type": "application/json",
542
+ "E2b-Sandbox-Id": this.sandboxId,
543
+ "E2b-Sandbox-Port": JUPYTER_PORT.toString()
544
+ };
545
+ if (this.trafficAccessToken) headers["E2B-Traffic-Access-Token"] = this.trafficAccessToken;
546
+ const res = await fetch(`${this.jupyterUrl}/contexts`, {
547
+ method: "POST",
548
+ headers,
549
+ body: JSON.stringify({
550
+ language: opts === null || opts === void 0 ? void 0 : opts.language,
551
+ cwd: opts === null || opts === void 0 ? void 0 : opts.cwd
552
+ }),
553
+ keepalive: true,
554
+ signal: this.connectionConfig.getSignal(opts === null || opts === void 0 ? void 0 : opts.requestTimeoutMs)
555
+ });
556
+ const error = await extractError(res);
557
+ if (error) throw error;
558
+ return await res.json();
559
+ } catch (error) {
560
+ throw await this.handleRequestError(error);
561
+ }
562
+ }
563
+ /**
564
+ * Removes a context.
565
+ *
566
+ * @param context context to remove.
567
+ *
568
+ * @returns void.
569
+ */
570
+ async removeCodeContext(context) {
571
+ try {
572
+ const id = typeof context === "string" ? context : context.id;
573
+ const headers = {
574
+ "Content-Type": "application/json",
575
+ "E2b-Sandbox-Id": this.sandboxId,
576
+ "E2b-Sandbox-Port": JUPYTER_PORT.toString()
577
+ };
578
+ if (this.trafficAccessToken) headers["E2B-Traffic-Access-Token"] = this.trafficAccessToken;
579
+ const error = await extractError(await fetch(`${this.jupyterUrl}/contexts/${id}`, {
580
+ method: "DELETE",
581
+ headers,
582
+ keepalive: true,
583
+ signal: this.connectionConfig.getSignal(this.connectionConfig.requestTimeoutMs)
584
+ }));
585
+ if (error) throw error;
586
+ } catch (error) {
587
+ throw await this.handleRequestError(error);
588
+ }
589
+ }
590
+ /**
591
+ * List all contexts.
592
+ *
593
+ * @returns list of contexts.
594
+ */
595
+ async listCodeContexts() {
596
+ try {
597
+ const headers = {
598
+ "Content-Type": "application/json",
599
+ "E2b-Sandbox-Id": this.sandboxId,
600
+ "E2b-Sandbox-Port": JUPYTER_PORT.toString()
601
+ };
602
+ if (this.trafficAccessToken) headers["E2B-Traffic-Access-Token"] = this.trafficAccessToken;
603
+ const res = await fetch(`${this.jupyterUrl}/contexts`, {
604
+ method: "GET",
605
+ headers,
606
+ keepalive: true,
607
+ signal: this.connectionConfig.getSignal(this.connectionConfig.requestTimeoutMs)
608
+ });
609
+ const error = await extractError(res);
610
+ if (error) throw error;
611
+ return await res.json();
612
+ } catch (error) {
613
+ throw await this.handleRequestError(error);
614
+ }
615
+ }
616
+ /**
617
+ * Restart a context.
618
+ *
619
+ * @param context context to restart.
620
+ *
621
+ * @returns void.
622
+ */
623
+ async restartCodeContext(context) {
624
+ try {
625
+ const id = typeof context === "string" ? context : context.id;
626
+ const headers = {
627
+ "Content-Type": "application/json",
628
+ "E2b-Sandbox-Id": this.sandboxId,
629
+ "E2b-Sandbox-Port": JUPYTER_PORT.toString()
630
+ };
631
+ if (this.trafficAccessToken) headers["E2B-Traffic-Access-Token"] = this.trafficAccessToken;
632
+ const error = await extractError(await fetch(`${this.jupyterUrl}/contexts/${id}/restart`, {
633
+ method: "POST",
634
+ headers,
635
+ keepalive: true,
636
+ signal: this.connectionConfig.getSignal(this.connectionConfig.requestTimeoutMs)
637
+ }));
638
+ if (error) throw error;
639
+ } catch (error) {
640
+ throw await this.handleRequestError(error);
641
+ }
642
+ }
643
+ /**
644
+ * Returns the error to throw for a failed request. If the connection was
645
+ * closed because the sandbox was killed mid-request, returns a descriptive
646
+ * `TimeoutError`. Otherwise falls back to formatting request timeouts and
647
+ * re-throwing the original error.
648
+ */
649
+ async handleRequestError(error) {
650
+ if (isConnectionClosedError(error) && await this.isRunning().catch(() => true) === false) return new boxfab.TimeoutError("The sandbox was killed while the request was in progress. This can happen when the sandbox times out or is killed manually. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.");
651
+ return formatRequestTimeoutError(error);
652
+ }
653
+ };
654
+ _defineProperty(Sandbox, "defaultTemplate", "code-interpreter-v1");
655
+ // src/client.ts
656
+ /**
657
+ * BoxFab client with an explicitly bound connection configuration.
658
+ *
659
+ * The resources exposed by the client ({@link BoxFab.Sandbox},
660
+ * {@link BoxFab.Volume}, {@link BoxFab.Template}, {@link BoxFab.Secret}) behave exactly
661
+ * like the top-level `Sandbox` / `Volume` / `Template` / `Secret` exports,
662
+ * except the options passed to the client are used as the defaults instead of
663
+ * the environment variables.
664
+ * Per-call options still take precedence over the client's options.
665
+ *
666
+ * Multiple clients are fully isolated from each other and from the top-level
667
+ * env-configured exports.
668
+ *
669
+ * @example
670
+ * ```ts
671
+ * import { BoxFab } from '@boxfab/code-interpreter'
672
+ *
673
+ * const client = new BoxFab({ apiKey: 'e2b_...', domain: 'us-west.boxfab.dev' })
674
+ *
675
+ * const sandbox = await client.Sandbox.create()
676
+ * const execution = await sandbox.runCode('x = 1; x += 1; x')
677
+ * ```
678
+ */
679
+ var BoxFab = class {
680
+ /**
681
+ * Create a new client with the connection options bound to it.
682
+ *
683
+ * @param opts connection options used as the defaults for every call made
684
+ * through this client's resource classes.
685
+ */
686
+ constructor(opts) {
687
+ var _Class;
688
+ _defineProperty(this, "Sandbox", void 0);
689
+ _defineProperty(this, "Volume", void 0);
690
+ _defineProperty(this, "Template", void 0);
691
+ _defineProperty(this, "Secret", void 0);
692
+ const boundOpts = _objectSpread2({}, opts !== null && opts !== void 0 ? opts : {});
693
+ delete boundOpts.signal;
694
+ if (boundOpts.headers) boundOpts.headers = _objectSpread2({}, boundOpts.headers);
695
+ if (boundOpts.apiHeaders) boundOpts.apiHeaders = _objectSpread2({}, boundOpts.apiHeaders);
696
+ this.Sandbox = (_Class = class extends Sandbox {}, _defineProperty(_Class, "boundOpts", boundOpts), _Class);
697
+ const core = new boxfab.BoxFab(boundOpts);
698
+ this.Volume = core.Volume;
699
+ this.Template = core.Template;
700
+ this.Secret = core.Secret;
701
+ }
702
+ };
703
+ // src/index.ts
704
+ var src_default = Sandbox;
705
+ exports.BoxFab = BoxFab;
706
+ exports.E2B = BoxFab;
707
+ exports.Sandbox = Sandbox;
708
+ exports.default = src_default;
709
+ Object.keys(boxfab).forEach(function(k) {
710
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
711
+ enumerable: true,
712
+ get: function() {
713
+ return boxfab[k];
714
+ }
715
+ });
716
+ });
717
+
718
+ //# sourceMappingURL=index.js.map