Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
js-sdk: run the msw-mocked suites in the browser leg (#1871)
devin-ai-integration[bot]3e5a48b00eb1
diff --git a/packages/js-sdk/tests/client.test.ts b/packages/js-sdk/tests/client.test.tsindex b277fb896..e49d481cb 100644--- a/packages/js-sdk/tests/client.test.ts+++ b/packages/js-sdk/tests/client.test.ts@@ -1,6 +1,5 @@import { afterAll, afterEach, assert, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import DefaultExport, {type ConnectionOpts,@@ -11,7 +10,9 @@ import DefaultExport, {TemplateBase,Volume,} from '../src'+import { runtime } from '../src/utils'import { TEST_API_KEY } from './setup'+import { setupMockApi } from './mockApi'const API_KEY_A = `e2b_${'a'.repeat(40)}`const API_KEY_B = `e2b_${'b'.repeat(40)}`@@ -51,7 +52,7 @@ const secretResponse = {updatedAt: new Date().toISOString(),}-const server = setupServer(+const server = setupMockApi(http.post(/\/sandboxes$/, async ({ request }) => {record(request)return HttpResponse.json(sandboxResponse)@@ -107,7 +108,7 @@ const envOverrides = {E2B_DEBUG: undefined,}-beforeAll(() => {+beforeAll(async () => {for (const [key, value] of Object.entries(envOverrides)) {envBackup[key] = process.env[key]if (value === undefined) {@@ -117,11 +118,11 @@ beforeAll(() => {}}- server.listen({ onUnhandledRequest: 'error' })+ await server.listen({ onUnhandledRequest: 'error' })})-afterAll(() => {- server.close()+afterAll(async () => {+ await server.close()for (const [key, value] of Object.entries(envBackup)) {if (value === undefined) {@@ -346,18 +347,23 @@ test('client.Template statics use the client config', async () => {assert.equal(lastRequest().apiKey, API_KEY_B)})-test('client.Template builds template instances', async () => {- const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })- const template = client.Template().fromPythonImage('3')-- assert.instanceOf(template, TemplateBase)- assert.instanceOf(template, client.Template)- assert.instanceOf(new client.Template(), client.Template)- assert.equal(- await client.Template.toDockerfile(template),- await Template.toDockerfile(Template().fromPythonImage('3'))- )-})+// The template builder is Node-only (node:path/node:fs); tests/template/** is+// excluded from the browser suite for the same reason.+test.skipIf(runtime === 'browser')(+ 'client.Template builds template instances',+ async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })+ const template = client.Template().fromPythonImage('3')++ assert.instanceOf(template, TemplateBase)+ assert.instanceOf(template, client.Template)+ assert.instanceOf(new client.Template(), client.Template)+ assert.equal(+ await client.Template.toDockerfile(template),+ await Template.toDockerfile(Template().fromPythonImage('3'))+ )+ }+)test('client.Template can be rebound to a variable', async () => {const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })diff --git a/packages/js-sdk/tests/mockApi.ts b/packages/js-sdk/tests/mockApi.tsnew file mode 100644index 000000000..2c810b0dd--- /dev/null+++ b/packages/js-sdk/tests/mockApi.ts@@ -0,0 +1,45 @@+import type { RequestHandler, SharedOptions } from 'msw'+import { setupServer, type SetupServer } from 'msw/node'++/**+ * A mocked E2B API for the unit suites that don't talk to a real backend.+ *+ * The handlers are plain msw and run everywhere; only the interception does+ * not. Node — and the runtimes with a Node compatibility layer — patch the+ * HTTP clients in-process through `msw/node`, whose entry pulls in+ * `node:http`. A browser can't load that and intercepts at the network layer+ * instead, through a Service Worker from `msw/browser`; the browser config+ * swaps in tests/runtimes/browser/mockApi.ts for this module. Both expose+ * this shape, so a suite written against it runs on every leg unchanged.+ */+export interface MockApi {+ /**+ * Starts intercepting requests. Async because a browser has to register+ * and activate the worker first; on Node it resolves immediately.+ */+ listen(options?: SharedOptions): Promise<void>+ /** Stops intercepting requests. */+ close(): Promise<void>+ /** Prepends handlers to the active list until the next `resetHandlers`. */+ use: SetupServer['use']+ /** Restores the initial handlers, or replaces them when some are given. */+ resetHandlers: SetupServer['resetHandlers']+ /** Life-cycle events, e.g. `request:start`. */+ events: SetupServer['events']+}++export function setupMockApi(...handlers: RequestHandler[]): MockApi {+ const server = setupServer(...handlers)++ return {+ async listen(options) {+ server.listen(options)+ },+ async close() {+ server.close()+ },+ use: (...next) => server.use(...next),+ resetHandlers: (...next) => server.resetHandlers(...next),+ events: server.events,+ }+}diff --git a/packages/js-sdk/tests/runtimes/browser/mockApi.ts b/packages/js-sdk/tests/runtimes/browser/mockApi.tsnew file mode 100644index 000000000..ccdf02a2e--- /dev/null+++ b/packages/js-sdk/tests/runtimes/browser/mockApi.ts@@ -0,0 +1,34 @@+import type { RequestHandler } from 'msw'+import { setupWorker } from 'msw/browser'++import type { MockApi } from '../../mockApi'++/**+ * Browser implementation of tests/mockApi.ts, served in place of it by the+ * browser config. Requests are intercepted by a Service Worker registered+ * from `/mockServiceWorker.js`, which the config serves straight out of the+ * installed `msw` package so the script can't fall out of step with the+ * library.+ *+ * The worker is shared by every test file (one registration per origin), but+ * it only intercepts for clients that have called `start()`, and vitest runs+ * each file in its own iframe — so a suite's handlers never see another+ * suite's traffic.+ */+export function setupMockApi(...handlers: RequestHandler[]): MockApi {+ const worker = setupWorker(...handlers)++ return {+ async listen(options) {+ // `quiet` drops msw's per-request console group, which vitest would+ // otherwise forward to the terminal for every mocked call.+ await worker.start({ ...options, quiet: true })+ },+ async close() {+ worker.stop()+ },+ use: (...next) => worker.use(...next),+ resetHandlers: (...next) => worker.resetHandlers(...next),+ events: worker.events,+ }+}diff --git a/packages/js-sdk/tests/runtimes/browser/vitest.config.mts b/packages/js-sdk/tests/runtimes/browser/vitest.config.mtsindex 7efe3d098..00f28616c 100644--- a/packages/js-sdk/tests/runtimes/browser/vitest.config.mts+++ b/packages/js-sdk/tests/runtimes/browser/vitest.config.mts@@ -1,6 +1,11 @@+import { createReadStream } from 'node:fs'+import { createRequire } from 'node:module'+import { dirname, join, sep } from 'node:path'+import { fileURLToPath } from 'node:url'+import { playwright } from '@vitest/browser-playwright'import { config } from 'dotenv'-import { defineConfig } from 'vitest/config'+import { defineConfig, type Plugin } from 'vitest/config'// Real env vars win over `.env`, matching dotenv's own precedence.const env = { ...config().parsed, ...process.env }@@ -12,6 +17,45 @@ const testEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith('E2B_'))) as Record<string, string>+// Vite module ids always use `/`, also on Windows.+const toModuleId = (path: string) => path.split(sep).join('/')++const testsDir = fileURLToPath(new URL('../..', import.meta.url))+const nodeMockApi = toModuleId(join(testsDir, 'mockApi.ts'))+const browserMockApi = toModuleId(+ fileURLToPath(new URL('./mockApi.ts', import.meta.url))+)+const workerScript = join(+ dirname(createRequire(import.meta.url).resolve('msw/package.json')),+ 'lib/mockServiceWorker.js'+)++// The suites that mock the API import `setupMockApi` from tests/mockApi.ts,+// which wraps `msw/node` — an entry that pulls in node:http and can't be+// served to a browser. Redirect that one module to the Service Worker-backed+// implementation, and serve msw's worker script at the URL `worker.start()`+// registers by default, straight from the installed package rather than a+// checked-in copy that would drift from the library version.+const browserMockApiPlugin: Plugin = {+ name: 'e2b:browser-mock-api',+ // Before Vite's own resolver, which would otherwise settle the import first.+ enforce: 'pre',+ async resolveId(source, importer, options) {+ if (!importer || !/\bmockApi(\.ts)?$/.test(source)) return+ const resolved = await this.resolve(source, importer, {+ ...options,+ skipSelf: true,+ })+ return resolved?.id === nodeMockApi ? browserMockApi : undefined+ },+ configureServer(server) {+ server.middlewares.use('/mockServiceWorker.js', (_req, res) => {+ res.setHeader('Content-Type', 'text/javascript')+ createReadStream(workerScript).pipe(res)+ })+ },+}+// Runs the unit + connectionConfig projects (same coverage as test:bun /// test:deno / test:cf) inside a real Chromium via Playwright, against src.// Nothing is skipped for being a browser: the suites that can't run here are@@ -20,6 +64,7 @@ const testEnv = Object.fromEntries(// (`corsHttpServerCmd` in tests/setup.ts), the way a browser app's own server// would be configured.export default defineConfig({+ plugins: [browserMockApiPlugin],test: {name: 'browser',include: [@@ -40,21 +85,6 @@ export default defineConfig({// The browser never takes that path — `createRuntimeFetch` late-binds// the global fetch outside Node — so there is nothing to cover here.'tests/undici.test.ts',- // These mock the API with msw's `setupServer`, whose `msw/node` entry- // pulls in node:http and can't be served to the browser. Porting them- // means `setupWorker` plus a service worker served from a public dir.- // Any new suite that imports `msw/node` belongs here — `grep -rl msw/node- // tests/` lists the full set (tests/template/** is already excluded).- 'tests/client.test.ts',- 'tests/sandbox/abortSignal.test.ts',- 'tests/sandbox/egressProxy.test.ts',- 'tests/sandbox/iam.test.ts',- 'tests/sandbox/lifecycleRequest.test.ts',- 'tests/sandbox/networkTransform.test.ts',- 'tests/sandbox/onResumeRequest.test.ts',- 'tests/secret/secret.test.ts',- 'tests/volume/file.test.ts',- 'tests/volume/volume.test.ts',],globals: false,testTimeout: 30_000,diff --git a/packages/js-sdk/tests/sandbox/abortSignal.test.ts b/packages/js-sdk/tests/sandbox/abortSignal.test.tsindex 2aa767ce2..54d0e8b0f 100644--- a/packages/js-sdk/tests/sandbox/abortSignal.test.ts+++ b/packages/js-sdk/tests/sandbox/abortSignal.test.ts@@ -1,9 +1,9 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { Sandbox } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'// Hold the request open until the caller aborts. If the signal is already// aborted by the time the handler runs, `addEventListener('abort', …)` would@@ -34,7 +34,7 @@ const restHandlers = [}),]-const server = setupServer(...restHandlers)+const server = setupMockApi(...restHandlers)beforeAll(() =>server.listen({diff --git a/packages/js-sdk/tests/sandbox/egressProxy.test.ts b/packages/js-sdk/tests/sandbox/egressProxy.test.tsindex a807ed34f..b54a058c0 100644--- a/packages/js-sdk/tests/sandbox/egressProxy.test.ts+++ b/packages/js-sdk/tests/sandbox/egressProxy.test.ts@@ -1,9 +1,9 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { Sandbox } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'const sandboxId = 'test-sandbox-id'@@ -11,7 +11,7 @@ let lastCreateBody: Record<string, any> | undefinedlet lastUpdateBody: Record<string, any> | undefinedlet sandboxNetwork: Record<string, any> | undefined-const server = setupServer(+const server = setupMockApi(http.post(apiUrl('/sandboxes'), async ({ request }) => {lastCreateBody = (await request.json()) as Record<string, any>return HttpResponse.json({diff --git a/packages/js-sdk/tests/sandbox/iam.test.ts b/packages/js-sdk/tests/sandbox/iam.test.tsindex 4cf768afc..d38e26293 100644--- a/packages/js-sdk/tests/sandbox/iam.test.ts+++ b/packages/js-sdk/tests/sandbox/iam.test.ts@@ -1,16 +1,16 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { InvalidArgumentError, Sandbox, Secret } from '../../src'import { iamTokenPlaceholders } from '../../src/sandbox/iam'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'const RUNTIME_PROBED_PROPS = ['toJSON', 'then', 'toString', 'valueOf']let lastCreateBody: Record<string, unknown> | undefined-const server = setupServer(+const server = setupMockApi(http.post(apiUrl('/sandboxes'), async ({ request }) => {lastCreateBody = (await request.json()) as Record<string, unknown>return HttpResponse.json({diff --git a/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.tsindex c85dbed0d..fb3636d6d 100644--- a/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts+++ b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts@@ -1,13 +1,13 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { InvalidArgumentError, Sandbox } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'let lastCreateBody: Record<string, unknown> | undefined-const server = setupServer(+const server = setupMockApi(http.post(apiUrl('/sandboxes'), async ({ request }) => {lastCreateBody = (await request.json()) as Record<string, unknown>return HttpResponse.json({diff --git a/packages/js-sdk/tests/sandbox/networkTransform.test.ts b/packages/js-sdk/tests/sandbox/networkTransform.test.tsindex 9be7b3ab4..3b6541a29 100644--- a/packages/js-sdk/tests/sandbox/networkTransform.test.ts+++ b/packages/js-sdk/tests/sandbox/networkTransform.test.ts@@ -1,16 +1,16 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { InvalidArgumentError, Sandbox, Secret } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'const sandboxId = 'test-sandbox-id'let lastCreateBody: Record<string, any> | undefinedlet lastUpdateBody: Record<string, any> | undefined-const server = setupServer(+const server = setupMockApi(http.post(apiUrl('/sandboxes'), async ({ request }) => {lastCreateBody = (await request.json()) as Record<string, any>return HttpResponse.json({diff --git a/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts b/packages/js-sdk/tests/sandbox/onResumeRequest.test.tsindex a1e82a2b8..96985ff72 100644--- a/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts+++ b/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts@@ -1,13 +1,13 @@import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'import { InvalidArgumentError, Sandbox } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'let lastConnectBody: Record<string, unknown> | undefined-const server = setupServer(+const server = setupMockApi(http.post(apiUrl('/sandboxes/:sandboxID/connect'), async ({ request }) => {lastConnectBody = (await request.json()) as Record<string, unknown>return HttpResponse.json({diff --git a/packages/js-sdk/tests/secret/secret.test.ts b/packages/js-sdk/tests/secret/secret.test.tsindex 3714ad774..455c0766e 100644--- a/packages/js-sdk/tests/secret/secret.test.ts+++ b/packages/js-sdk/tests/secret/secret.test.ts@@ -1,10 +1,9 @@import { describe, it, expect, afterAll, afterEach, beforeAll } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'-import { randomUUID } from 'node:crypto'import { InvalidArgumentError, Secret, SecretNotFoundError } from '../../src'import { apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'interface MockSecret {secretID: string@@ -34,7 +33,7 @@ const restHandlers = [}const now = new Date().toISOString()const secret: MockSecret = {- secretID: `sec_${randomUUID()}`,+ secretID: `sec_${crypto.randomUUID()}`,name: name.toLowerCase(),currentVersion: 1,metadata: metadata ?? {},@@ -110,7 +109,7 @@ const restHandlers = [),]-const server = setupServer(...restHandlers)+const server = setupMockApi(...restHandlers)beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))afterAll(() => server.close())diff --git a/packages/js-sdk/tests/volume/file.test.ts b/packages/js-sdk/tests/volume/file.test.tsindex b35efa867..91915a485 100644--- a/packages/js-sdk/tests/volume/file.test.ts+++ b/packages/js-sdk/tests/volume/file.test.ts@@ -1,5 +1,4 @@import { afterAll, beforeAll, beforeEach, describe, expect } from 'vitest'-import { setupServer } from 'msw/node'import { http, HttpResponse } from 'msw'import {@@ -9,9 +8,10 @@ import {VolumePathNotFoundError,} from '../../src'import { apiUrl, volumeTest } from '../setup'+import { setupMockApi } from '../mockApi'import { createMockVolumeApi } from './mockVolumeContent'-const server = setupServer()+const server = setupMockApi()beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))afterAll(() => server.close())diff --git a/packages/js-sdk/tests/volume/mockVolumeContent.ts b/packages/js-sdk/tests/volume/mockVolumeContent.tsindex e19ad1293..17b146a5b 100644--- a/packages/js-sdk/tests/volume/mockVolumeContent.ts+++ b/packages/js-sdk/tests/volume/mockVolumeContent.ts@@ -1,5 +1,4 @@import { http, HttpResponse } from 'msw'-import { randomUUID } from 'node:crypto'import { VolumeFileType } from '../../src'import { apiUrl } from '../setup'@@ -152,8 +151,8 @@ export function createMockVolumeApi() {// Control-plane volume CRUD used by the `volumeTest` fixture.http.post(apiUrl('/volumes'), async ({ request }) => {const { name } = (await request.clone().json()) as { name: string }- const volumeID = randomUUID()- const token = `vol-token-${randomUUID()}`+ const volumeID = crypto.randomUUID()+ const token = `vol-token-${crypto.randomUUID()}`volumes.set(volumeID, { volumeID, name, token })return HttpResponse.json({ volumeID, name, token }, { status: 201 })}),diff --git a/packages/js-sdk/tests/volume/volume.test.ts b/packages/js-sdk/tests/volume/volume.test.tsindex b0f5bed88..c4460dbb8 100644--- a/packages/js-sdk/tests/volume/volume.test.ts+++ b/packages/js-sdk/tests/volume/volume.test.ts@@ -1,7 +1,5 @@import { describe, it, expect, afterAll, afterEach, beforeAll } from 'vitest'import { http, HttpResponse } from 'msw'-import { setupServer } from 'msw/node'-import { randomUUID } from 'node:crypto'import {Volume,@@ -12,6 +10,7 @@ import {import { VolumeConnectionConfig } from '../../src/volume/client'import { runtime } from '../../src/utils'import { apiUrl } from '../setup'+import { setupMockApi } from '../mockApi'// In-memory store for mock volumesconst volumes = new Map<@@ -26,8 +25,8 @@ const restHandlers = [// POST /volumes - create (returns VolumeAndToken)http.post(apiUrl('/volumes'), async ({ request }) => {const { name } = (await request.clone().json()) as { name: string }- const volumeID = randomUUID()- const token = `vol-token-${randomUUID()}`+ const volumeID = crypto.randomUUID()+ const token = `vol-token-${crypto.randomUUID()}`volumes.set(volumeID, { volumeID, name, token })return HttpResponse.json({ volumeID, name, token }, { status: 201 })}),@@ -85,7 +84,7 @@ const restHandlers = [}),]-const server = setupServer(...restHandlers)+const server = setupMockApi(...restHandlers)beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))afterAll(() => server.close())@@ -222,8 +221,8 @@ describe('Volume BYOC domain', () => {server.use(http.post(apiUrl('/volumes'), async ({ request }) => {const { name } = (await request.clone().json()) as { name: string }- const volumeID = randomUUID()- const token = `vol-token-${randomUUID()}`+ const volumeID = crypto.randomUUID()+ const token = `vol-token-${crypto.randomUUID()}`return HttpResponse.json({ volumeID, name, token, domain: byocDomain },{ status: 201 }