@cloudflare/sandbox 0.0.0-af082ab → 0.0.0-b4913fb

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 (75) hide show
  1. package/CHANGELOG.md +156 -21
  2. package/Dockerfile +157 -70
  3. package/LICENSE +176 -0
  4. package/README.md +92 -822
  5. package/dist/index.d.ts +1953 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +3280 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +16 -8
  10. package/src/clients/base-client.ts +295 -0
  11. package/src/clients/command-client.ts +115 -0
  12. package/src/clients/file-client.ts +300 -0
  13. package/src/clients/git-client.ts +98 -0
  14. package/src/clients/index.ts +64 -0
  15. package/src/clients/interpreter-client.ts +333 -0
  16. package/src/clients/port-client.ts +105 -0
  17. package/src/clients/process-client.ts +180 -0
  18. package/src/clients/sandbox-client.ts +39 -0
  19. package/src/clients/types.ts +88 -0
  20. package/src/clients/utility-client.ts +156 -0
  21. package/src/errors/adapter.ts +238 -0
  22. package/src/errors/classes.ts +594 -0
  23. package/src/errors/index.ts +109 -0
  24. package/src/file-stream.ts +123 -116
  25. package/src/index.ts +89 -66
  26. package/src/interpreter.ts +58 -40
  27. package/src/request-handler.ts +94 -55
  28. package/src/sandbox.ts +1009 -497
  29. package/src/security.ts +34 -28
  30. package/src/sse-parser.ts +8 -11
  31. package/src/version.ts +6 -0
  32. package/startup.sh +3 -0
  33. package/tests/base-client.test.ts +364 -0
  34. package/tests/command-client.test.ts +444 -0
  35. package/tests/file-client.test.ts +831 -0
  36. package/tests/file-stream.test.ts +310 -0
  37. package/tests/get-sandbox.test.ts +149 -0
  38. package/tests/git-client.test.ts +487 -0
  39. package/tests/port-client.test.ts +293 -0
  40. package/tests/process-client.test.ts +683 -0
  41. package/tests/request-handler.test.ts +292 -0
  42. package/tests/sandbox.test.ts +739 -0
  43. package/tests/sse-parser.test.ts +291 -0
  44. package/tests/utility-client.test.ts +339 -0
  45. package/tests/version.test.ts +16 -0
  46. package/tests/wrangler.jsonc +35 -0
  47. package/tsconfig.json +9 -1
  48. package/tsdown.config.ts +12 -0
  49. package/vitest.config.ts +31 -0
  50. package/container_src/bun.lock +0 -76
  51. package/container_src/circuit-breaker.ts +0 -121
  52. package/container_src/control-process.ts +0 -784
  53. package/container_src/handler/exec.ts +0 -185
  54. package/container_src/handler/file.ts +0 -457
  55. package/container_src/handler/git.ts +0 -130
  56. package/container_src/handler/ports.ts +0 -314
  57. package/container_src/handler/process.ts +0 -568
  58. package/container_src/handler/session.ts +0 -92
  59. package/container_src/index.ts +0 -601
  60. package/container_src/interpreter-service.ts +0 -276
  61. package/container_src/isolation.ts +0 -1213
  62. package/container_src/mime-processor.ts +0 -255
  63. package/container_src/package.json +0 -18
  64. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  65. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  66. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  67. package/container_src/runtime/process-pool.ts +0 -464
  68. package/container_src/shell-escape.ts +0 -42
  69. package/container_src/startup.sh +0 -11
  70. package/container_src/types.ts +0 -131
  71. package/src/client.ts +0 -1048
  72. package/src/errors.ts +0 -219
  73. package/src/interpreter-client.ts +0 -352
  74. package/src/interpreter-types.ts +0 -390
  75. package/src/types.ts +0 -571
@@ -0,0 +1,444 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { ExecuteResponse } from '../src/clients';
3
+ import { CommandClient } from '../src/clients/command-client';
4
+ import {
5
+ CommandError,
6
+ CommandNotFoundError,
7
+ SandboxError
8
+ } from '../src/errors';
9
+
10
+ describe('CommandClient', () => {
11
+ let client: CommandClient;
12
+ let mockFetch: ReturnType<typeof vi.fn>;
13
+ let onCommandComplete: ReturnType<typeof vi.fn>;
14
+ let onError: ReturnType<typeof vi.fn>;
15
+
16
+ beforeEach(() => {
17
+ vi.clearAllMocks();
18
+
19
+ mockFetch = vi.fn();
20
+ global.fetch = mockFetch as unknown as typeof fetch;
21
+
22
+ onCommandComplete = vi.fn();
23
+ onError = vi.fn();
24
+
25
+ client = new CommandClient({
26
+ baseUrl: 'http://test.com',
27
+ port: 3000,
28
+ onCommandComplete,
29
+ onError
30
+ });
31
+ });
32
+
33
+ afterEach(() => {
34
+ vi.restoreAllMocks();
35
+ });
36
+
37
+ describe('execute', () => {
38
+ it('should execute simple commands successfully', async () => {
39
+ const mockResponse: ExecuteResponse = {
40
+ success: true,
41
+ stdout: 'Hello World\n',
42
+ stderr: '',
43
+ exitCode: 0,
44
+ command: 'echo "Hello World"',
45
+ timestamp: '2023-01-01T00:00:00Z'
46
+ };
47
+
48
+ mockFetch.mockResolvedValue(
49
+ new Response(JSON.stringify(mockResponse), { status: 200 })
50
+ );
51
+
52
+ const result = await client.execute('echo "Hello World"', 'session-exec');
53
+
54
+ expect(result.success).toBe(true);
55
+ expect(result.stdout).toBe('Hello World\n');
56
+ expect(result.stderr).toBe('');
57
+ expect(result.exitCode).toBe(0);
58
+ expect(result.command).toBe('echo "Hello World"');
59
+ expect(onCommandComplete).toHaveBeenCalledWith(
60
+ true,
61
+ 0,
62
+ 'Hello World\n',
63
+ '',
64
+ 'echo "Hello World"'
65
+ );
66
+ });
67
+
68
+ it('should handle command failures with proper exit codes', async () => {
69
+ const mockResponse: ExecuteResponse = {
70
+ success: false,
71
+ stdout: '',
72
+ stderr: 'command not found: nonexistent-cmd\n',
73
+ exitCode: 127,
74
+ command: 'nonexistent-cmd',
75
+ timestamp: '2023-01-01T00:00:00Z'
76
+ };
77
+
78
+ mockFetch.mockResolvedValue(
79
+ new Response(JSON.stringify(mockResponse), { status: 200 })
80
+ );
81
+
82
+ const result = await client.execute('nonexistent-cmd', 'session-exec');
83
+
84
+ expect(result.success).toBe(false);
85
+ expect(result.exitCode).toBe(127);
86
+ expect(result.stderr).toContain('command not found');
87
+ expect(result.stdout).toBe('');
88
+ expect(onCommandComplete).toHaveBeenCalledWith(
89
+ false,
90
+ 127,
91
+ '',
92
+ 'command not found: nonexistent-cmd\n',
93
+ 'nonexistent-cmd'
94
+ );
95
+ });
96
+
97
+ it('should handle container-level errors with proper error mapping', async () => {
98
+ const errorResponse = {
99
+ code: 'COMMAND_NOT_FOUND',
100
+ message: 'Command not found: invalidcmd',
101
+ context: { command: 'invalidcmd' },
102
+ httpStatus: 404,
103
+ timestamp: new Date().toISOString()
104
+ };
105
+
106
+ mockFetch.mockResolvedValue(
107
+ new Response(JSON.stringify(errorResponse), { status: 404 })
108
+ );
109
+
110
+ await expect(client.execute('invalidcmd', 'session-err')).rejects.toThrow(
111
+ CommandNotFoundError
112
+ );
113
+ expect(onError).toHaveBeenCalledWith(
114
+ expect.stringContaining('Command not found'),
115
+ 'invalidcmd'
116
+ );
117
+ });
118
+
119
+ it('should handle network failures gracefully', async () => {
120
+ mockFetch.mockRejectedValue(new Error('Network connection failed'));
121
+
122
+ await expect(client.execute('ls', 'session-err')).rejects.toThrow(
123
+ 'Network connection failed'
124
+ );
125
+ expect(onError).toHaveBeenCalledWith('Network connection failed', 'ls');
126
+ });
127
+
128
+ it('should handle server errors with proper status codes', async () => {
129
+ const scenarios = [
130
+ { status: 400, code: 'COMMAND_EXECUTION_ERROR', error: CommandError },
131
+ { status: 500, code: 'EXECUTION_ERROR', error: SandboxError }
132
+ ];
133
+
134
+ for (const scenario of scenarios) {
135
+ mockFetch.mockResolvedValueOnce(
136
+ new Response(
137
+ JSON.stringify({
138
+ code: scenario.code,
139
+ message: 'Test error',
140
+ context: {},
141
+ httpStatus: scenario.status,
142
+ timestamp: new Date().toISOString()
143
+ }),
144
+ { status: scenario.status }
145
+ )
146
+ );
147
+ await expect(
148
+ client.execute('test-command', 'session-err')
149
+ ).rejects.toThrow(scenario.error);
150
+ }
151
+ });
152
+
153
+ it('should handle commands with large output', async () => {
154
+ const largeOutput = 'line of output\n'.repeat(10000);
155
+ const mockResponse: ExecuteResponse = {
156
+ success: true,
157
+ stdout: largeOutput,
158
+ stderr: '',
159
+ exitCode: 0,
160
+ command: 'find / -type f',
161
+ timestamp: '2023-01-01T00:00:00Z'
162
+ };
163
+
164
+ mockFetch.mockResolvedValue(
165
+ new Response(JSON.stringify(mockResponse), { status: 200 })
166
+ );
167
+
168
+ const result = await client.execute('find / -type f', 'session-exec');
169
+
170
+ expect(result.success).toBe(true);
171
+ expect(result.stdout.length).toBeGreaterThan(100000);
172
+ expect(result.stdout.split('\n')).toHaveLength(10001);
173
+ expect(result.exitCode).toBe(0);
174
+ });
175
+
176
+ it('should handle concurrent command executions', async () => {
177
+ mockFetch.mockImplementation((url: string, options: RequestInit) => {
178
+ const body = JSON.parse(options.body as string);
179
+ const command = body.command;
180
+ return Promise.resolve(
181
+ new Response(
182
+ JSON.stringify({
183
+ success: true,
184
+ stdout: `output for ${command}\n`,
185
+ stderr: '',
186
+ exitCode: 0,
187
+ command: command,
188
+ timestamp: '2023-01-01T00:00:00Z'
189
+ }),
190
+ { status: 200 }
191
+ )
192
+ );
193
+ });
194
+
195
+ const commands = ['echo 1', 'echo 2', 'echo 3', 'pwd', 'ls'];
196
+ const results = await Promise.all(
197
+ commands.map((cmd) => client.execute(cmd, 'session-concurrent'))
198
+ );
199
+
200
+ expect(results).toHaveLength(5);
201
+ results.forEach((result, index) => {
202
+ expect(result.success).toBe(true);
203
+ expect(result.stdout).toBe(`output for ${commands[index]}\n`);
204
+ expect(result.exitCode).toBe(0);
205
+ });
206
+ expect(onCommandComplete).toHaveBeenCalledTimes(5);
207
+ });
208
+
209
+ it('should handle malformed server responses', async () => {
210
+ mockFetch.mockResolvedValue(
211
+ new Response('invalid json {', {
212
+ status: 200,
213
+ headers: { 'Content-Type': 'application/json' }
214
+ })
215
+ );
216
+
217
+ await expect(client.execute('ls', 'session-err')).rejects.toThrow(
218
+ SandboxError
219
+ );
220
+ expect(onError).toHaveBeenCalled();
221
+ });
222
+
223
+ it('should handle empty command input', async () => {
224
+ const errorResponse = {
225
+ code: 'INVALID_COMMAND',
226
+ message: 'Invalid command: empty command provided',
227
+ context: {},
228
+ httpStatus: 400,
229
+ timestamp: new Date().toISOString()
230
+ };
231
+
232
+ mockFetch.mockResolvedValue(
233
+ new Response(JSON.stringify(errorResponse), { status: 400 })
234
+ );
235
+
236
+ await expect(client.execute('', 'session-err')).rejects.toThrow(
237
+ CommandError
238
+ );
239
+ });
240
+
241
+ it('should handle streaming command execution', async () => {
242
+ const streamContent = [
243
+ 'data: {"type":"start","command":"tail -f app.log","timestamp":"2023-01-01T00:00:00Z"}\n\n',
244
+ 'data: {"type":"stdout","data":"log line 1\\n","timestamp":"2023-01-01T00:00:01Z"}\n\n',
245
+ 'data: {"type":"stdout","data":"log line 2\\n","timestamp":"2023-01-01T00:00:02Z"}\n\n',
246
+ 'data: {"type":"complete","exitCode":0,"timestamp":"2023-01-01T00:00:03Z"}\n\n'
247
+ ].join('');
248
+
249
+ const mockStream = new ReadableStream({
250
+ start(controller) {
251
+ controller.enqueue(new TextEncoder().encode(streamContent));
252
+ controller.close();
253
+ }
254
+ });
255
+
256
+ mockFetch.mockResolvedValue(
257
+ new Response(mockStream, {
258
+ status: 200,
259
+ headers: { 'Content-Type': 'text/event-stream' }
260
+ })
261
+ );
262
+
263
+ const stream = await client.executeStream(
264
+ 'tail -f app.log',
265
+ 'session-stream'
266
+ );
267
+ expect(stream).toBeInstanceOf(ReadableStream);
268
+
269
+ const reader = stream.getReader();
270
+ const decoder = new TextDecoder();
271
+ let content = '';
272
+
273
+ try {
274
+ while (true) {
275
+ const { done, value } = await reader.read();
276
+ if (done) break;
277
+ content += decoder.decode(value);
278
+ }
279
+ } finally {
280
+ reader.releaseLock();
281
+ }
282
+
283
+ expect(content).toContain('tail -f app.log');
284
+ expect(content).toContain('log line 1');
285
+ expect(content).toContain('log line 2');
286
+ expect(content).toContain('"type":"complete"');
287
+ });
288
+
289
+ it('should handle streaming errors gracefully', async () => {
290
+ const errorResponse = {
291
+ code: 'STREAM_START_ERROR',
292
+ message: 'Command failed to start streaming',
293
+ context: { command: 'invalid-stream-command' },
294
+ httpStatus: 400,
295
+ timestamp: new Date().toISOString()
296
+ };
297
+
298
+ mockFetch.mockResolvedValue(
299
+ new Response(JSON.stringify(errorResponse), { status: 400 })
300
+ );
301
+
302
+ await expect(
303
+ client.executeStream('invalid-stream-command', 'session-err')
304
+ ).rejects.toThrow(CommandError);
305
+ expect(onError).toHaveBeenCalledWith(
306
+ expect.stringContaining('Command failed to start streaming'),
307
+ 'invalid-stream-command'
308
+ );
309
+ });
310
+
311
+ it('should handle streaming without response body', async () => {
312
+ mockFetch.mockResolvedValue(
313
+ new Response(null, {
314
+ status: 200,
315
+ headers: { 'Content-Type': 'text/event-stream' }
316
+ })
317
+ );
318
+
319
+ await expect(
320
+ client.executeStream('test-command', 'session-err')
321
+ ).rejects.toThrow('No response body for streaming');
322
+ });
323
+
324
+ it('should handle network failures during streaming setup', async () => {
325
+ mockFetch.mockRejectedValue(
326
+ new Error('Connection lost during streaming')
327
+ );
328
+
329
+ await expect(
330
+ client.executeStream('stream-command', 'session-err')
331
+ ).rejects.toThrow('Connection lost during streaming');
332
+ expect(onError).toHaveBeenCalledWith(
333
+ 'Connection lost during streaming',
334
+ 'stream-command'
335
+ );
336
+ });
337
+ });
338
+
339
+ describe('callback integration', () => {
340
+ it('should work without any callbacks', async () => {
341
+ const clientWithoutCallbacks = new CommandClient({
342
+ baseUrl: 'http://test.com',
343
+ port: 3000
344
+ });
345
+
346
+ const mockResponse: ExecuteResponse = {
347
+ success: true,
348
+ stdout: 'test output\n',
349
+ stderr: '',
350
+ exitCode: 0,
351
+ command: 'echo test',
352
+ timestamp: '2023-01-01T00:00:00Z'
353
+ };
354
+
355
+ mockFetch.mockResolvedValue(
356
+ new Response(JSON.stringify(mockResponse), { status: 200 })
357
+ );
358
+
359
+ const result = await clientWithoutCallbacks.execute(
360
+ 'echo test',
361
+ 'session-nocb'
362
+ );
363
+
364
+ expect(result.success).toBe(true);
365
+ expect(result.stdout).toBe('test output\n');
366
+ });
367
+
368
+ it('should handle errors gracefully without callbacks', async () => {
369
+ const clientWithoutCallbacks = new CommandClient({
370
+ baseUrl: 'http://test.com',
371
+ port: 3000
372
+ });
373
+
374
+ mockFetch.mockRejectedValue(new Error('Network failed'));
375
+
376
+ await expect(
377
+ clientWithoutCallbacks.execute('test', 'session-nocb')
378
+ ).rejects.toThrow('Network failed');
379
+ });
380
+
381
+ it('should call onCommandComplete for both success and failure', async () => {
382
+ const successResponse: ExecuteResponse = {
383
+ success: true,
384
+ stdout: 'success\n',
385
+ stderr: '',
386
+ exitCode: 0,
387
+ command: 'echo success',
388
+ timestamp: '2023-01-01T00:00:00Z'
389
+ };
390
+
391
+ mockFetch.mockResolvedValueOnce(
392
+ new Response(JSON.stringify(successResponse), { status: 200 })
393
+ );
394
+
395
+ await client.execute('echo success', 'session-cb');
396
+ expect(onCommandComplete).toHaveBeenLastCalledWith(
397
+ true,
398
+ 0,
399
+ 'success\n',
400
+ '',
401
+ 'echo success'
402
+ );
403
+
404
+ const failureResponse: ExecuteResponse = {
405
+ success: false,
406
+ stdout: '',
407
+ stderr: 'error\n',
408
+ exitCode: 1,
409
+ command: 'false',
410
+ timestamp: '2023-01-01T00:00:00Z'
411
+ };
412
+
413
+ mockFetch.mockResolvedValueOnce(
414
+ new Response(JSON.stringify(failureResponse), { status: 200 })
415
+ );
416
+
417
+ await client.execute('false', 'session-cb');
418
+ expect(onCommandComplete).toHaveBeenLastCalledWith(
419
+ false,
420
+ 1,
421
+ '',
422
+ 'error\n',
423
+ 'false'
424
+ );
425
+ });
426
+ });
427
+
428
+ describe('constructor options', () => {
429
+ it('should initialize with minimal options', async () => {
430
+ const minimalClient = new CommandClient();
431
+ expect(minimalClient).toBeDefined();
432
+ });
433
+
434
+ it('should initialize with full options', async () => {
435
+ const fullOptionsClient = new CommandClient({
436
+ baseUrl: 'http://custom.com',
437
+ port: 8080,
438
+ onCommandComplete: vi.fn(),
439
+ onError: vi.fn()
440
+ });
441
+ expect(fullOptionsClient).toBeDefined();
442
+ });
443
+ });
444
+ });