@cloudflare/sandbox 0.0.0-4bedc3a → 0.0.0-50bc24c

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/Dockerfile +104 -65
  3. package/README.md +87 -772
  4. package/dist/index.d.ts +1907 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +3159 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +16 -8
  9. package/src/clients/base-client.ts +280 -0
  10. package/src/clients/command-client.ts +115 -0
  11. package/src/clients/file-client.ts +295 -0
  12. package/src/clients/git-client.ts +92 -0
  13. package/src/clients/index.ts +64 -0
  14. package/src/{jupyter-client.ts → clients/interpreter-client.ts} +148 -168
  15. package/src/clients/port-client.ts +105 -0
  16. package/src/clients/process-client.ts +177 -0
  17. package/src/clients/sandbox-client.ts +41 -0
  18. package/src/clients/types.ts +84 -0
  19. package/src/clients/utility-client.ts +119 -0
  20. package/src/errors/adapter.ts +180 -0
  21. package/src/errors/classes.ts +469 -0
  22. package/src/errors/index.ts +105 -0
  23. package/src/file-stream.ts +164 -0
  24. package/src/index.ts +83 -54
  25. package/src/interpreter.ts +22 -13
  26. package/src/request-handler.ts +80 -44
  27. package/src/sandbox.ts +883 -530
  28. package/src/security.ts +14 -23
  29. package/src/sse-parser.ts +4 -8
  30. package/src/version.ts +6 -0
  31. package/startup.sh +3 -0
  32. package/tests/base-client.test.ts +328 -0
  33. package/tests/command-client.test.ts +407 -0
  34. package/tests/file-client.test.ts +719 -0
  35. package/tests/file-stream.test.ts +306 -0
  36. package/tests/get-sandbox.test.ts +149 -0
  37. package/tests/git-client.test.ts +328 -0
  38. package/tests/port-client.test.ts +301 -0
  39. package/tests/process-client.test.ts +658 -0
  40. package/tests/request-handler.test.ts +240 -0
  41. package/tests/sandbox.test.ts +641 -0
  42. package/tests/sse-parser.test.ts +290 -0
  43. package/tests/utility-client.test.ts +332 -0
  44. package/tests/version.test.ts +16 -0
  45. package/tests/wrangler.jsonc +35 -0
  46. package/tsconfig.json +9 -1
  47. package/tsdown.config.ts +12 -0
  48. package/vitest.config.ts +31 -0
  49. package/container_src/bun.lock +0 -122
  50. package/container_src/circuit-breaker.ts +0 -121
  51. package/container_src/control-process.ts +0 -784
  52. package/container_src/handler/exec.ts +0 -185
  53. package/container_src/handler/file.ts +0 -406
  54. package/container_src/handler/git.ts +0 -130
  55. package/container_src/handler/ports.ts +0 -314
  56. package/container_src/handler/process.ts +0 -568
  57. package/container_src/handler/session.ts +0 -92
  58. package/container_src/index.ts +0 -601
  59. package/container_src/isolation.ts +0 -1039
  60. package/container_src/jupyter-server.ts +0 -579
  61. package/container_src/jupyter-service.ts +0 -461
  62. package/container_src/jupyter_config.py +0 -48
  63. package/container_src/mime-processor.ts +0 -255
  64. package/container_src/package.json +0 -18
  65. package/container_src/shell-escape.ts +0 -42
  66. package/container_src/startup.sh +0 -84
  67. package/container_src/types.ts +0 -131
  68. package/src/client.ts +0 -1009
  69. package/src/errors.ts +0 -218
  70. package/src/interpreter-types.ts +0 -383
  71. package/src/types.ts +0 -502
@@ -0,0 +1,641 @@
1
+ import { Container } from '@cloudflare/containers';
2
+ import type { DurableObjectState } from '@cloudflare/workers-types';
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+ import { Sandbox, connect } from '../src/sandbox';
5
+
6
+ // Mock dependencies before imports
7
+ vi.mock('./interpreter', () => ({
8
+ CodeInterpreter: vi.fn().mockImplementation(() => ({})),
9
+ }));
10
+
11
+ vi.mock('@cloudflare/containers', () => {
12
+ const mockSwitchPort = vi.fn((request: Request, port: number) => {
13
+ // Create a new request with the port in the URL path
14
+ const url = new URL(request.url);
15
+ url.pathname = `/proxy/${port}${url.pathname}`;
16
+ return new Request(url, request);
17
+ });
18
+
19
+ const MockContainer = class Container {
20
+ ctx: any;
21
+ env: any;
22
+ constructor(ctx: any, env: any) {
23
+ this.ctx = ctx;
24
+ this.env = env;
25
+ }
26
+ async fetch(request: Request): Promise<Response> {
27
+ // Mock implementation - will be spied on in tests
28
+ const upgradeHeader = request.headers.get('Upgrade');
29
+ if (upgradeHeader?.toLowerCase() === 'websocket') {
30
+ return new Response('WebSocket Upgraded', {
31
+ status: 200,
32
+ headers: {
33
+ 'X-WebSocket-Upgraded': 'true',
34
+ 'Upgrade': 'websocket',
35
+ 'Connection': 'Upgrade',
36
+ },
37
+ });
38
+ }
39
+ return new Response('Mock Container fetch');
40
+ }
41
+ async containerFetch(request: Request, port: number): Promise<Response> {
42
+ // Mock implementation for HTTP path
43
+ return new Response('Mock Container HTTP fetch');
44
+ }
45
+ };
46
+
47
+ return {
48
+ Container: MockContainer,
49
+ getContainer: vi.fn(),
50
+ switchPort: mockSwitchPort,
51
+ };
52
+ });
53
+
54
+ describe('Sandbox - Automatic Session Management', () => {
55
+ let sandbox: Sandbox;
56
+ let mockCtx: Partial<DurableObjectState>;
57
+ let mockEnv: any;
58
+
59
+ beforeEach(async () => {
60
+ vi.clearAllMocks();
61
+
62
+ // Mock DurableObjectState
63
+ mockCtx = {
64
+ storage: {
65
+ get: vi.fn().mockResolvedValue(null),
66
+ put: vi.fn().mockResolvedValue(undefined),
67
+ delete: vi.fn().mockResolvedValue(undefined),
68
+ list: vi.fn().mockResolvedValue(new Map()),
69
+ } as any,
70
+ blockConcurrencyWhile: vi.fn().mockImplementation(<T>(callback: () => Promise<T>): Promise<T> => callback()),
71
+ id: {
72
+ toString: () => 'test-sandbox-id',
73
+ equals: vi.fn(),
74
+ name: 'test-sandbox',
75
+ } as any,
76
+ };
77
+
78
+ mockEnv = {};
79
+
80
+ // Create Sandbox instance - SandboxClient is created internally
81
+ sandbox = new Sandbox(mockCtx as DurableObjectState, mockEnv);
82
+
83
+ // Wait for blockConcurrencyWhile to complete
84
+ await vi.waitFor(() => {
85
+ expect(mockCtx.blockConcurrencyWhile).toHaveBeenCalled();
86
+ });
87
+
88
+ // Now spy on the client methods that we need for testing
89
+ vi.spyOn(sandbox.client.utils, 'createSession').mockResolvedValue({
90
+ success: true,
91
+ id: 'sandbox-default',
92
+ message: 'Created',
93
+ } as any);
94
+
95
+ vi.spyOn(sandbox.client.commands, 'execute').mockResolvedValue({
96
+ success: true,
97
+ stdout: '',
98
+ stderr: '',
99
+ exitCode: 0,
100
+ command: '',
101
+ timestamp: new Date().toISOString(),
102
+ } as any);
103
+
104
+ vi.spyOn(sandbox.client.files, 'writeFile').mockResolvedValue({
105
+ success: true,
106
+ path: '/test.txt',
107
+ timestamp: new Date().toISOString(),
108
+ } as any);
109
+ });
110
+
111
+ afterEach(() => {
112
+ vi.restoreAllMocks();
113
+ });
114
+
115
+ describe('default session management', () => {
116
+ it('should create default session on first operation', async () => {
117
+ vi.mocked(sandbox.client.commands.execute).mockResolvedValueOnce({
118
+ success: true,
119
+ stdout: 'test output',
120
+ stderr: '',
121
+ exitCode: 0,
122
+ command: 'echo test',
123
+ timestamp: new Date().toISOString(),
124
+ } as any);
125
+
126
+ await sandbox.exec('echo test');
127
+
128
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
129
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
130
+ id: expect.stringMatching(/^sandbox-/),
131
+ env: {},
132
+ cwd: '/workspace',
133
+ });
134
+
135
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith(
136
+ 'echo test',
137
+ expect.stringMatching(/^sandbox-/)
138
+ );
139
+ });
140
+
141
+ it('should reuse default session across multiple operations', async () => {
142
+ await sandbox.exec('echo test1');
143
+ await sandbox.writeFile('/test.txt', 'content');
144
+ await sandbox.exec('echo test2');
145
+
146
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
147
+
148
+ const firstSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
149
+ const fileSessionId = vi.mocked(sandbox.client.files.writeFile).mock.calls[0][2];
150
+ const secondSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
151
+
152
+ expect(firstSessionId).toBe(fileSessionId);
153
+ expect(firstSessionId).toBe(secondSessionId);
154
+ });
155
+
156
+ it('should use default session for process management', async () => {
157
+ vi.spyOn(sandbox.client.processes, 'startProcess').mockResolvedValue({
158
+ success: true,
159
+ processId: 'proc-1',
160
+ pid: 1234,
161
+ command: 'sleep 10',
162
+ timestamp: new Date().toISOString(),
163
+ } as any);
164
+
165
+ vi.spyOn(sandbox.client.processes, 'listProcesses').mockResolvedValue({
166
+ success: true,
167
+ processes: [{
168
+ id: 'proc-1',
169
+ pid: 1234,
170
+ command: 'sleep 10',
171
+ status: 'running',
172
+ startTime: new Date().toISOString(),
173
+ }],
174
+ timestamp: new Date().toISOString(),
175
+ } as any);
176
+
177
+ const process = await sandbox.startProcess('sleep 10');
178
+ const processes = await sandbox.listProcesses();
179
+
180
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
181
+
182
+ // startProcess uses sessionId (to start process in that session)
183
+ const startSessionId = vi.mocked(sandbox.client.processes.startProcess).mock.calls[0][1];
184
+ expect(startSessionId).toMatch(/^sandbox-/);
185
+
186
+ // listProcesses is sandbox-scoped - no sessionId parameter
187
+ const listProcessesCall = vi.mocked(sandbox.client.processes.listProcesses).mock.calls[0];
188
+ expect(listProcessesCall).toEqual([]);
189
+
190
+ // Verify the started process appears in the list
191
+ expect(process.id).toBe('proc-1');
192
+ expect(processes).toHaveLength(1);
193
+ expect(processes[0].id).toBe('proc-1');
194
+ });
195
+
196
+ it('should use default session for git operations', async () => {
197
+ vi.spyOn(sandbox.client.git, 'checkout').mockResolvedValue({
198
+ success: true,
199
+ stdout: 'Cloned successfully',
200
+ stderr: '',
201
+ branch: 'main',
202
+ targetDir: '/workspace/repo',
203
+ timestamp: new Date().toISOString(),
204
+ } as any);
205
+
206
+ await sandbox.gitCheckout('https://github.com/test/repo.git', { branch: 'main' });
207
+
208
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
209
+ expect(sandbox.client.git.checkout).toHaveBeenCalledWith(
210
+ 'https://github.com/test/repo.git',
211
+ expect.stringMatching(/^sandbox-/),
212
+ { branch: 'main', targetDir: undefined }
213
+ );
214
+ });
215
+
216
+ it('should initialize session with sandbox name when available', async () => {
217
+ await sandbox.setSandboxName('my-sandbox');
218
+
219
+ await sandbox.exec('pwd');
220
+
221
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
222
+ id: 'sandbox-my-sandbox',
223
+ env: {},
224
+ cwd: '/workspace',
225
+ });
226
+ });
227
+ });
228
+
229
+ describe('explicit session creation', () => {
230
+ it('should create isolated execution session', async () => {
231
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
232
+ success: true,
233
+ id: 'custom-session-123',
234
+ message: 'Created',
235
+ } as any);
236
+
237
+ const session = await sandbox.createSession({
238
+ id: 'custom-session-123',
239
+ env: { NODE_ENV: 'test' },
240
+ cwd: '/test',
241
+ });
242
+
243
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
244
+ id: 'custom-session-123',
245
+ env: { NODE_ENV: 'test' },
246
+ cwd: '/test',
247
+ });
248
+
249
+ expect(session.id).toBe('custom-session-123');
250
+ expect(session.exec).toBeInstanceOf(Function);
251
+ expect(session.startProcess).toBeInstanceOf(Function);
252
+ expect(session.writeFile).toBeInstanceOf(Function);
253
+ expect(session.gitCheckout).toBeInstanceOf(Function);
254
+ });
255
+
256
+ it('should execute operations in specific session context', async () => {
257
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
258
+ success: true,
259
+ id: 'isolated-session',
260
+ message: 'Created',
261
+ } as any);
262
+
263
+ const session = await sandbox.createSession({ id: 'isolated-session' });
264
+
265
+ await session.exec('echo test');
266
+
267
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith(
268
+ 'echo test',
269
+ 'isolated-session'
270
+ );
271
+ });
272
+
273
+ it('should isolate multiple explicit sessions', async () => {
274
+ vi.mocked(sandbox.client.utils.createSession)
275
+ .mockResolvedValueOnce({ success: true, id: 'session-1', message: 'Created' } as any)
276
+ .mockResolvedValueOnce({ success: true, id: 'session-2', message: 'Created' } as any);
277
+
278
+ const session1 = await sandbox.createSession({ id: 'session-1' });
279
+ const session2 = await sandbox.createSession({ id: 'session-2' });
280
+
281
+ await session1.exec('echo build');
282
+ await session2.exec('echo test');
283
+
284
+ const session1Id = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
285
+ const session2Id = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
286
+
287
+ expect(session1Id).toBe('session-1');
288
+ expect(session2Id).toBe('session-2');
289
+ expect(session1Id).not.toBe(session2Id);
290
+ });
291
+
292
+ it('should not interfere with default session', async () => {
293
+ vi.mocked(sandbox.client.utils.createSession)
294
+ .mockResolvedValueOnce({ success: true, id: 'sandbox-default', message: 'Created' } as any)
295
+ .mockResolvedValueOnce({ success: true, id: 'explicit-session', message: 'Created' } as any);
296
+
297
+ await sandbox.exec('echo default');
298
+
299
+ const explicitSession = await sandbox.createSession({ id: 'explicit-session' });
300
+ await explicitSession.exec('echo explicit');
301
+
302
+ await sandbox.exec('echo default-again');
303
+
304
+ const defaultSessionId1 = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
305
+ const explicitSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
306
+ const defaultSessionId2 = vi.mocked(sandbox.client.commands.execute).mock.calls[2][1];
307
+
308
+ expect(defaultSessionId1).toBe('sandbox-default');
309
+ expect(explicitSessionId).toBe('explicit-session');
310
+ expect(defaultSessionId2).toBe('sandbox-default');
311
+ expect(defaultSessionId1).toBe(defaultSessionId2);
312
+ expect(explicitSessionId).not.toBe(defaultSessionId1);
313
+ });
314
+
315
+ it('should generate session ID if not provided', async () => {
316
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
317
+ success: true,
318
+ id: 'session-generated-123',
319
+ message: 'Created',
320
+ } as any);
321
+
322
+ await sandbox.createSession();
323
+
324
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
325
+ id: expect.stringMatching(/^session-/),
326
+ env: undefined,
327
+ cwd: undefined,
328
+ });
329
+ });
330
+ });
331
+
332
+ describe('ExecutionSession operations', () => {
333
+ let session: any;
334
+
335
+ beforeEach(async () => {
336
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
337
+ success: true,
338
+ id: 'test-session',
339
+ message: 'Created',
340
+ } as any);
341
+
342
+ session = await sandbox.createSession({ id: 'test-session' });
343
+ });
344
+
345
+ it('should execute command with session context', async () => {
346
+ await session.exec('pwd');
347
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith('pwd', 'test-session');
348
+ });
349
+
350
+ it('should start process with session context', async () => {
351
+ vi.spyOn(sandbox.client.processes, 'startProcess').mockResolvedValue({
352
+ success: true,
353
+ process: {
354
+ id: 'proc-1',
355
+ pid: 1234,
356
+ command: 'sleep 10',
357
+ status: 'running',
358
+ startTime: new Date().toISOString(),
359
+ },
360
+ } as any);
361
+
362
+ await session.startProcess('sleep 10');
363
+
364
+ expect(sandbox.client.processes.startProcess).toHaveBeenCalledWith(
365
+ 'sleep 10',
366
+ 'test-session',
367
+ { processId: undefined }
368
+ );
369
+ });
370
+
371
+ it('should write file with session context', async () => {
372
+ vi.spyOn(sandbox.client.files, 'writeFile').mockResolvedValue({
373
+ success: true,
374
+ path: '/test.txt',
375
+ timestamp: new Date().toISOString(),
376
+ } as any);
377
+
378
+ await session.writeFile('/test.txt', 'content');
379
+
380
+ expect(sandbox.client.files.writeFile).toHaveBeenCalledWith(
381
+ '/test.txt',
382
+ 'content',
383
+ 'test-session',
384
+ { encoding: undefined }
385
+ );
386
+ });
387
+
388
+ it('should perform git checkout with session context', async () => {
389
+ vi.spyOn(sandbox.client.git, 'checkout').mockResolvedValue({
390
+ success: true,
391
+ stdout: 'Cloned',
392
+ stderr: '',
393
+ branch: 'main',
394
+ targetDir: '/workspace/repo',
395
+ timestamp: new Date().toISOString(),
396
+ } as any);
397
+
398
+ await session.gitCheckout('https://github.com/test/repo.git');
399
+
400
+ expect(sandbox.client.git.checkout).toHaveBeenCalledWith(
401
+ 'https://github.com/test/repo.git',
402
+ 'test-session',
403
+ { branch: undefined, targetDir: undefined }
404
+ );
405
+ });
406
+ });
407
+
408
+ describe('edge cases and error handling', () => {
409
+ it('should handle session creation errors gracefully', async () => {
410
+ vi.mocked(sandbox.client.utils.createSession).mockRejectedValueOnce(
411
+ new Error('Session creation failed')
412
+ );
413
+
414
+ await expect(sandbox.exec('echo test')).rejects.toThrow('Session creation failed');
415
+ });
416
+
417
+ it('should initialize with empty environment when not set', async () => {
418
+ await sandbox.exec('pwd');
419
+
420
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
421
+ id: expect.any(String),
422
+ env: {},
423
+ cwd: '/workspace',
424
+ });
425
+ });
426
+
427
+ it('should use updated environment after setEnvVars', async () => {
428
+ await sandbox.setEnvVars({ NODE_ENV: 'production', DEBUG: 'true' });
429
+
430
+ await sandbox.exec('env');
431
+
432
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
433
+ id: expect.any(String),
434
+ env: { NODE_ENV: 'production', DEBUG: 'true' },
435
+ cwd: '/workspace',
436
+ });
437
+ });
438
+ });
439
+
440
+ describe('port exposure - workers.dev detection', () => {
441
+ beforeEach(async () => {
442
+ await sandbox.setSandboxName('test-sandbox');
443
+ vi.spyOn(sandbox.client.ports, 'exposePort').mockResolvedValue({
444
+ success: true,
445
+ port: 8080,
446
+ name: 'test-service',
447
+ exposedAt: new Date().toISOString(),
448
+ } as any);
449
+ });
450
+
451
+ it('should reject workers.dev domains with CustomDomainRequiredError', async () => {
452
+ const hostnames = [
453
+ 'my-worker.workers.dev',
454
+ 'my-worker.my-account.workers.dev'
455
+ ];
456
+
457
+ for (const hostname of hostnames) {
458
+ try {
459
+ await sandbox.exposePort(8080, { name: 'test', hostname });
460
+ // Should not reach here
461
+ expect.fail('Should have thrown CustomDomainRequiredError');
462
+ } catch (error: any) {
463
+ expect(error.name).toBe('CustomDomainRequiredError');
464
+ expect(error.code).toBe('CUSTOM_DOMAIN_REQUIRED');
465
+ expect(error.message).toContain('workers.dev');
466
+ expect(error.message).toContain('custom domain');
467
+ }
468
+ }
469
+
470
+ // Verify client method was never called
471
+ expect(sandbox.client.ports.exposePort).not.toHaveBeenCalled();
472
+ });
473
+
474
+ it('should accept custom domains and subdomains', async () => {
475
+ const testCases = [
476
+ { hostname: 'example.com', description: 'apex domain' },
477
+ { hostname: 'sandbox.example.com', description: 'subdomain' }
478
+ ];
479
+
480
+ for (const { hostname } of testCases) {
481
+ const result = await sandbox.exposePort(8080, { name: 'test', hostname });
482
+ expect(result.url).toContain(hostname);
483
+ expect(result.port).toBe(8080);
484
+ }
485
+ });
486
+
487
+ it('should accept localhost for local development', async () => {
488
+ const result = await sandbox.exposePort(8080, {
489
+ name: 'test',
490
+ hostname: 'localhost:8787'
491
+ });
492
+
493
+ expect(result.url).toContain('localhost');
494
+ expect(sandbox.client.ports.exposePort).toHaveBeenCalled();
495
+ });
496
+ });
497
+
498
+ describe('fetch() override - WebSocket detection', () => {
499
+ let superFetchSpy: any;
500
+
501
+ beforeEach(async () => {
502
+ await sandbox.setSandboxName('test-sandbox');
503
+
504
+ // Spy on Container.prototype.fetch to verify WebSocket routing
505
+ superFetchSpy = vi.spyOn(Container.prototype, 'fetch')
506
+ .mockResolvedValue(new Response('WebSocket response'));
507
+ });
508
+
509
+ afterEach(() => {
510
+ superFetchSpy?.mockRestore();
511
+ });
512
+
513
+ it('should detect WebSocket upgrade header and route to super.fetch', async () => {
514
+ const request = new Request('https://example.com/ws', {
515
+ headers: {
516
+ 'Upgrade': 'websocket',
517
+ 'Connection': 'Upgrade',
518
+ },
519
+ });
520
+
521
+ const response = await sandbox.fetch(request);
522
+
523
+ // Should route through super.fetch() for WebSocket
524
+ expect(superFetchSpy).toHaveBeenCalledTimes(1);
525
+ expect(await response.text()).toBe('WebSocket response');
526
+ });
527
+
528
+ it('should route non-WebSocket requests through containerFetch', async () => {
529
+ // GET request
530
+ const getRequest = new Request('https://example.com/api/data');
531
+ await sandbox.fetch(getRequest);
532
+ expect(superFetchSpy).not.toHaveBeenCalled();
533
+
534
+ vi.clearAllMocks();
535
+
536
+ // POST request
537
+ const postRequest = new Request('https://example.com/api/data', {
538
+ method: 'POST',
539
+ body: JSON.stringify({ data: 'test' }),
540
+ headers: { 'Content-Type': 'application/json' },
541
+ });
542
+ await sandbox.fetch(postRequest);
543
+ expect(superFetchSpy).not.toHaveBeenCalled();
544
+
545
+ vi.clearAllMocks();
546
+
547
+ // SSE request (should not be detected as WebSocket)
548
+ const sseRequest = new Request('https://example.com/events', {
549
+ headers: { 'Accept': 'text/event-stream' },
550
+ });
551
+ await sandbox.fetch(sseRequest);
552
+ expect(superFetchSpy).not.toHaveBeenCalled();
553
+ });
554
+
555
+ it('should preserve WebSocket request unchanged when calling super.fetch()', async () => {
556
+ const request = new Request('https://example.com/ws', {
557
+ headers: {
558
+ 'Upgrade': 'websocket',
559
+ 'Connection': 'Upgrade',
560
+ 'Sec-WebSocket-Key': 'test-key-123',
561
+ 'Sec-WebSocket-Version': '13',
562
+ },
563
+ });
564
+
565
+ await sandbox.fetch(request);
566
+
567
+ expect(superFetchSpy).toHaveBeenCalledTimes(1);
568
+ const passedRequest = superFetchSpy.mock.calls[0][0] as Request;
569
+ expect(passedRequest.headers.get('Upgrade')).toBe('websocket');
570
+ expect(passedRequest.headers.get('Connection')).toBe('Upgrade');
571
+ expect(passedRequest.headers.get('Sec-WebSocket-Key')).toBe('test-key-123');
572
+ expect(passedRequest.headers.get('Sec-WebSocket-Version')).toBe('13');
573
+ });
574
+ });
575
+
576
+ describe('connect() function', () => {
577
+ it('should route WebSocket request through switchPort to sandbox.fetch', async () => {
578
+ const { switchPort } = await import('@cloudflare/containers');
579
+ const switchPortMock = vi.mocked(switchPort);
580
+
581
+ const request = new Request('http://localhost/ws/echo', {
582
+ headers: {
583
+ 'Upgrade': 'websocket',
584
+ 'Connection': 'Upgrade',
585
+ },
586
+ });
587
+
588
+ const fetchSpy = vi.spyOn(sandbox, 'fetch');
589
+ const response = await connect(sandbox, request, 8080);
590
+
591
+ // Verify switchPort was called with correct port
592
+ expect(switchPortMock).toHaveBeenCalledWith(request, 8080);
593
+
594
+ // Verify fetch was called with the switched request
595
+ expect(fetchSpy).toHaveBeenCalledOnce();
596
+
597
+ // Verify response indicates WebSocket upgrade
598
+ expect(response.status).toBe(200);
599
+ expect(response.headers.get('X-WebSocket-Upgraded')).toBe('true');
600
+ });
601
+
602
+ it('should reject invalid ports with SecurityError', async () => {
603
+ const request = new Request('http://localhost/ws/test', {
604
+ headers: { 'Upgrade': 'websocket', 'Connection': 'Upgrade' },
605
+ });
606
+
607
+ // Invalid port values
608
+ await expect(connect(sandbox, request, -1)).rejects.toThrow('Invalid or restricted port');
609
+ await expect(connect(sandbox, request, 0)).rejects.toThrow('Invalid or restricted port');
610
+ await expect(connect(sandbox, request, 70000)).rejects.toThrow('Invalid or restricted port');
611
+
612
+ // Privileged ports
613
+ await expect(connect(sandbox, request, 80)).rejects.toThrow('Invalid or restricted port');
614
+ await expect(connect(sandbox, request, 443)).rejects.toThrow('Invalid or restricted port');
615
+ });
616
+
617
+ it('should preserve request properties through routing', async () => {
618
+ const request = new Request('http://localhost/ws/test?token=abc&room=lobby', {
619
+ headers: {
620
+ 'Upgrade': 'websocket',
621
+ 'Connection': 'Upgrade',
622
+ 'X-Custom-Header': 'custom-value',
623
+ },
624
+ });
625
+
626
+ const fetchSpy = vi.spyOn(sandbox, 'fetch');
627
+ await connect(sandbox, request, 8080);
628
+
629
+ const calledRequest = fetchSpy.mock.calls[0][0];
630
+
631
+ // Verify headers are preserved
632
+ expect(calledRequest.headers.get('Upgrade')).toBe('websocket');
633
+ expect(calledRequest.headers.get('X-Custom-Header')).toBe('custom-value');
634
+
635
+ // Verify query parameters are preserved
636
+ const url = new URL(calledRequest.url);
637
+ expect(url.searchParams.get('token')).toBe('abc');
638
+ expect(url.searchParams.get('room')).toBe('lobby');
639
+ });
640
+ });
641
+ });