@cloudflare/sandbox 0.0.0-871f813 → 0.0.0-89632aa

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