Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Fix ESM timeout compatibility and update dependencies

Tomas Valenta421fbac09db6
diff --git a/.changeset/clean-bugs-mix.md b/.changeset/clean-bugs-mix.md
new file mode 100644
index 000000000..de4f606ba
--- /dev/null
+++ b/.changeset/clean-bugs-mix.md
@@ -0,0 +1,5 @@
+---
+"@e2b/sdk": patch
+---
+
+Fix ESM timeout compatibility
diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.json
index 4bf91afca..f9f340693 100644
--- a/packages/js-sdk/package.json
+++ b/packages/js-sdk/package.json
@@ -72,7 +72,6 @@
"dependencies": {
"normalize-path": "^3.0.0",
"openapi-typescript-fetch": "^1.1.3",
- "p-timeout": "^6.1.2",
"path-browserify": "^1.0.1",
"platform": "^1.3.6",
"rpc-websocket-client": "^1.1.4"
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 00830af2a..d75548010 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -1,9 +1,12 @@
-import { Fetcher, OpArgType, TypedFetch } from 'openapi-typescript-fetch'
+import * as fetcher from 'openapi-typescript-fetch'
+import type { OpArgType, TypedFetch } from 'openapi-typescript-fetch'
import { API_HOST } from '../constants'
import type { components, paths } from './schema.gen'
import { defaultHeaders } from './metadata'
+const { Fetcher } = fetcher
+
const client = Fetcher.for<paths>()
type ClientType = typeof client
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 60da7b443..d9c9f2506 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -1,10 +1,7 @@
-import { Sandbox } from './sandbox'
-
export { default as api, withAPIKey, withAccessToken } from './api'
export type { ClientType, components, paths } from './api'
export { SANDBOX_DOMAIN, API_HOST } from './constants'
-export { Sandbox } from './sandbox'
export type { SandboxOpts } from './sandbox'
export type { OpenPort } from './sandbox/codeSnippet'
export { Terminal, TerminalOutput } from './sandbox/terminal'
@@ -23,6 +20,7 @@ export { Process, ProcessMessage, ProcessOutput } from './sandbox/process'
export type { ProcessManager } from './sandbox/process'
export type { EnvVars } from './sandbox/envVars'
export { runCode, CodeRuntime } from './runCode' // Export CodeRuntime enum as value, not as type, so it can be actually used in consumer code
+import { Sandbox } from './sandbox/index'
// export { runCmd } from './runCmd'
import { DataAnalysis } from './templates/dataAnalysis'
@@ -30,4 +28,8 @@ export { DataAnalysis as CodeInterpreter }
export { Artifact, DataAnalysis } from './templates/dataAnalysis'
export type { RunPythonOpts } from './templates/dataAnalysis'
+
+export { Sandbox }
export default Sandbox
+
+// export { Sandbox }
diff --git a/packages/js-sdk/src/utils/promise.ts b/packages/js-sdk/src/utils/promise.ts
index bc9aa4832..31ed2a49a 100644
--- a/packages/js-sdk/src/utils/promise.ts
+++ b/packages/js-sdk/src/utils/promise.ts
@@ -1,4 +1,4 @@
-import pTimeout from 'p-timeout'
+import pTimeout from './timeout'
import { TIMEOUT } from '../constants'
diff --git a/packages/js-sdk/src/utils/timeout.d.ts b/packages/js-sdk/src/utils/timeout.d.ts
new file mode 100644
index 000000000..31fa4d628
--- /dev/null
+++ b/packages/js-sdk/src/utils/timeout.d.ts
@@ -0,0 +1,151 @@
+export class TimeoutError extends Error {
+ readonly name: 'TimeoutError';
+ constructor(message?: string);
+}
+
+export type ClearablePromise<T> = {
+ /**
+ Clear the timeout.
+ */
+ clear: () => void;
+} & Promise<T>;
+
+export type Options<ReturnType> = {
+ /**
+ Milliseconds before timing out.
+
+ Passing `Infinity` will cause it to never time out.
+ */
+ milliseconds: number;
+
+ /**
+ Do something other than rejecting with an error on timeout.
+
+ You could for example retry:
+
+ @example
+ ```
+ import {setTimeout} from 'node:timers/promises';
+ import pTimeout from 'p-timeout';
+
+ const delayedPromise = () => setTimeout(200);
+
+ await pTimeout(delayedPromise(), {
+ milliseconds: 50,
+ fallback: () => {
+ return pTimeout(delayedPromise(), {
+ milliseconds: 300
+ });
+ },
+ });
+ ```
+ */
+ fallback?: () => ReturnType | Promise<ReturnType>;
+
+ /**
+ Specify a custom error message or error to throw when it times out:
+
+ - `message: 'too slow'` will throw `TimeoutError('too slow')`
+ - `message: new MyCustomError('it’s over 9000')` will throw the same error instance
+ - `message: false` will make the promise resolve with `undefined` instead of rejecting
+
+ If you do a custom error, it's recommended to sub-class `TimeoutError`:
+
+ ```
+ import {TimeoutError} from 'p-timeout';
+
+ class MyCustomError extends TimeoutError {
+ name = "MyCustomError";
+ }
+ ```
+ */
+ message?: string | Error | false;
+
+ /**
+ Custom implementations for the `setTimeout` and `clearTimeout` functions.
+
+ Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
+
+ @example
+ ```
+ import pTimeout from 'p-timeout';
+ import sinon from 'sinon';
+
+ const originalSetTimeout = setTimeout;
+ const originalClearTimeout = clearTimeout;
+
+ sinon.useFakeTimers();
+
+ // Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
+ await pTimeout(doSomething(), {
+ milliseconds: 2000,
+ customTimers: {
+ setTimeout: originalSetTimeout,
+ clearTimeout: originalClearTimeout
+ }
+ });
+ ```
+ */
+ readonly customTimers?: {
+ setTimeout: typeof globalThis.setTimeout;
+ clearTimeout: typeof globalThis.clearTimeout;
+ };
+
+ /**
+ You can abort the promise using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
+
+ _Requires Node.js 16 or later._
+
+ @example
+ ```
+ import pTimeout from 'p-timeout';
+ import delay from 'delay';
+
+ const delayedPromise = delay(3000);
+
+ const abortController = new AbortController();
+
+ setTimeout(() => {
+ abortController.abort();
+ }, 100);
+
+ await pTimeout(delayedPromise, {
+ milliseconds: 2000,
+ signal: abortController.signal
+ });
+ ```
+ */
+ signal?: globalThis.AbortSignal;
+};
+
+/**
+Timeout a promise after a specified amount of time.
+
+If you pass in a cancelable promise, specifically a promise with a `.cancel()` method, that method will be called when the `pTimeout` promise times out.
+
+@param input - Promise to decorate.
+@returns A decorated `input` that times out after `milliseconds` time. It has a `.clear()` method that clears the timeout.
+
+@example
+```
+import {setTimeout} from 'node:timers/promises';
+import pTimeout from 'p-timeout';
+
+const delayedPromise = () => setTimeout(200);
+
+await pTimeout(delayedPromise(), {
+ milliseconds: 50,
+ fallback: () => {
+ return pTimeout(delayedPromise(), {milliseconds: 300});
+ }
+});
+```
+*/
+export default function pTimeout<ValueType, ReturnType = ValueType>(
+ input: PromiseLike<ValueType>,
+ options: Options<ReturnType> & {message: false}
+): ClearablePromise<ValueType | ReturnType | undefined>;
+export default function pTimeout<ValueType, ReturnType = ValueType>(
+ input: PromiseLike<ValueType>,
+ options: Options<ReturnType>
+): ClearablePromise<ValueType | ReturnType>;
\ No newline at end of file
diff --git a/packages/js-sdk/src/utils/timeout.js b/packages/js-sdk/src/utils/timeout.js
new file mode 100644
index 000000000..e07eefeb2
--- /dev/null
+++ b/packages/js-sdk/src/utils/timeout.js
@@ -0,0 +1,116 @@
+export class TimeoutError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = 'TimeoutError';
+ }
+}
+
+/**
+An error to be thrown when the request is aborted by AbortController.
+DOMException is thrown instead of this Error when DOMException is available.
+*/
+export class AbortError extends Error {
+ constructor(message) {
+ super();
+ this.name = 'AbortError';
+ this.message = message;
+ }
+}
+
+/**
+TODO: Remove AbortError and just throw DOMException when targeting Node 18.
+*/
+const getDOMException = errorMessage => globalThis.DOMException === undefined
+ ? new AbortError(errorMessage)
+ : new DOMException(errorMessage);
+
+/**
+TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
+*/
+const getAbortedReason = signal => {
+ const reason = signal.reason === undefined
+ ? getDOMException('This operation was aborted.')
+ : signal.reason;
+
+ return reason instanceof Error ? reason : getDOMException(reason);
+};
+
+export default function pTimeout(promise, options) {
+ const {
+ milliseconds,
+ fallback,
+ message,
+ customTimers = { setTimeout, clearTimeout },
+ } = options;
+
+ let timer;
+
+ const wrappedPromise = new Promise((resolve, reject) => {
+ if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
+ }
+
+ if (options.signal) {
+ const { signal } = options;
+ if (signal.aborted) {
+ reject(getAbortedReason(signal));
+ }
+
+ signal.addEventListener('abort', () => {
+ reject(getAbortedReason(signal));
+ });
+ }
+
+ if (milliseconds === Number.POSITIVE_INFINITY) {
+ promise.then(resolve, reject);
+ return;
+ }
+
+ // We create the error outside of `setTimeout` to preserve the stack trace.
+ const timeoutError = new TimeoutError();
+
+ timer = customTimers.setTimeout.call(undefined, () => {
+ if (fallback) {
+ try {
+ resolve(fallback());
+ } catch (error) {
+ reject(error);
+ }
+
+ return;
+ }
+
+ if (typeof promise.cancel === 'function') {
+ promise.cancel();
+ }
+
+ if (message === false) {
+ resolve();
+ } else if (message instanceof Error) {
+ reject(message);
+ } else {
+ timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
+ reject(timeoutError);
+ }
+ }, milliseconds);
+
+ (async () => {
+ try {
+ resolve(await promise);
+ } catch (error) {
+ reject(error);
+ }
+ })();
+ });
+
+ const cancelablePromise = wrappedPromise.finally(() => {
+ cancelablePromise.clear();
+ });
+
+ cancelablePromise.clear = () => {
+ customTimers.clearTimeout.call(undefined, timer);
+ timer = undefined;
+ };
+
+ return cancelablePromise;
+}
\ No newline at end of file
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e72de387e..7dfe901a7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -318,9 +318,6 @@ importers:
openapi-typescript-fetch:
specifier: ^1.1.3
version: 1.1.3
- p-timeout:
- specifier: ^6.1.2
- version: 6.1.2
path-browserify:
specifier: ^1.0.1
version: 1.0.1