@cloudflare/sandbox 0.0.0-af082ab → 0.0.0-b61841c

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 (105) hide show
  1. package/CHANGELOG.md +63 -6
  2. package/Dockerfile +91 -51
  3. package/README.md +88 -825
  4. package/dist/chunk-BFVUNTP4.js +104 -0
  5. package/dist/chunk-BFVUNTP4.js.map +1 -0
  6. package/dist/chunk-EKSWCBCA.js +86 -0
  7. package/dist/chunk-EKSWCBCA.js.map +1 -0
  8. package/dist/chunk-JXZMAU2C.js +559 -0
  9. package/dist/chunk-JXZMAU2C.js.map +1 -0
  10. package/dist/chunk-QHRFHK6X.js +7 -0
  11. package/dist/chunk-QHRFHK6X.js.map +1 -0
  12. package/dist/chunk-SFCV5YTY.js +2456 -0
  13. package/dist/chunk-SFCV5YTY.js.map +1 -0
  14. package/dist/chunk-Z532A7QC.js +78 -0
  15. package/dist/chunk-Z532A7QC.js.map +1 -0
  16. package/dist/file-stream.d.ts +43 -0
  17. package/dist/file-stream.js +9 -0
  18. package/dist/file-stream.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.js +67 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/interpreter.d.ts +33 -0
  23. package/dist/interpreter.js +8 -0
  24. package/dist/interpreter.js.map +1 -0
  25. package/dist/request-handler.d.ts +18 -0
  26. package/dist/request-handler.js +13 -0
  27. package/dist/request-handler.js.map +1 -0
  28. package/dist/sandbox-DWQVgVTY.d.ts +603 -0
  29. package/dist/sandbox.d.ts +4 -0
  30. package/dist/sandbox.js +13 -0
  31. package/dist/sandbox.js.map +1 -0
  32. package/dist/security.d.ts +31 -0
  33. package/dist/security.js +13 -0
  34. package/dist/security.js.map +1 -0
  35. package/dist/sse-parser.d.ts +28 -0
  36. package/dist/sse-parser.js +11 -0
  37. package/dist/sse-parser.js.map +1 -0
  38. package/dist/version.d.ts +8 -0
  39. package/dist/version.js +7 -0
  40. package/dist/version.js.map +1 -0
  41. package/package.json +12 -4
  42. package/src/clients/base-client.ts +280 -0
  43. package/src/clients/command-client.ts +115 -0
  44. package/src/clients/file-client.ts +295 -0
  45. package/src/clients/git-client.ts +92 -0
  46. package/src/clients/index.ts +64 -0
  47. package/src/{interpreter-client.ts → clients/interpreter-client.ts} +148 -171
  48. package/src/clients/port-client.ts +105 -0
  49. package/src/clients/process-client.ts +177 -0
  50. package/src/clients/sandbox-client.ts +41 -0
  51. package/src/clients/types.ts +84 -0
  52. package/src/clients/utility-client.ts +119 -0
  53. package/src/errors/adapter.ts +180 -0
  54. package/src/errors/classes.ts +469 -0
  55. package/src/errors/index.ts +105 -0
  56. package/src/file-stream.ts +119 -117
  57. package/src/index.ts +81 -69
  58. package/src/interpreter.ts +17 -8
  59. package/src/request-handler.ts +80 -44
  60. package/src/sandbox.ts +794 -537
  61. package/src/security.ts +14 -23
  62. package/src/sse-parser.ts +4 -8
  63. package/src/version.ts +6 -0
  64. package/startup.sh +3 -0
  65. package/tests/base-client.test.ts +328 -0
  66. package/tests/command-client.test.ts +407 -0
  67. package/tests/file-client.test.ts +719 -0
  68. package/tests/file-stream.test.ts +306 -0
  69. package/tests/get-sandbox.test.ts +110 -0
  70. package/tests/git-client.test.ts +328 -0
  71. package/tests/port-client.test.ts +301 -0
  72. package/tests/process-client.test.ts +658 -0
  73. package/tests/request-handler.test.ts +240 -0
  74. package/tests/sandbox.test.ts +554 -0
  75. package/tests/sse-parser.test.ts +290 -0
  76. package/tests/utility-client.test.ts +332 -0
  77. package/tests/version.test.ts +16 -0
  78. package/tests/wrangler.jsonc +35 -0
  79. package/tsconfig.json +9 -1
  80. package/vitest.config.ts +31 -0
  81. package/container_src/bun.lock +0 -76
  82. package/container_src/circuit-breaker.ts +0 -121
  83. package/container_src/control-process.ts +0 -784
  84. package/container_src/handler/exec.ts +0 -185
  85. package/container_src/handler/file.ts +0 -457
  86. package/container_src/handler/git.ts +0 -130
  87. package/container_src/handler/ports.ts +0 -314
  88. package/container_src/handler/process.ts +0 -568
  89. package/container_src/handler/session.ts +0 -92
  90. package/container_src/index.ts +0 -601
  91. package/container_src/interpreter-service.ts +0 -276
  92. package/container_src/isolation.ts +0 -1213
  93. package/container_src/mime-processor.ts +0 -255
  94. package/container_src/package.json +0 -18
  95. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  96. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  97. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  98. package/container_src/runtime/process-pool.ts +0 -464
  99. package/container_src/shell-escape.ts +0 -42
  100. package/container_src/startup.sh +0 -11
  101. package/container_src/types.ts +0 -131
  102. package/src/client.ts +0 -1048
  103. package/src/errors.ts +0 -219
  104. package/src/interpreter-types.ts +0 -390
  105. package/src/types.ts +0 -571
@@ -0,0 +1,719 @@
1
+ import type {
2
+ DeleteFileResult,
3
+ FileExistsResult,
4
+ ListFilesResult,
5
+ MkdirResult,
6
+ MoveFileResult,
7
+ ReadFileResult,
8
+ RenameFileResult,
9
+ WriteFileResult
10
+ } from '@repo/shared';
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
12
+ import { FileClient } from '../src/clients/file-client';
13
+ import {
14
+ FileExistsError,
15
+ FileNotFoundError,
16
+ FileSystemError,
17
+ PermissionDeniedError,
18
+ SandboxError
19
+ } from '../src/errors';
20
+
21
+ describe('FileClient', () => {
22
+ let client: FileClient;
23
+ let mockFetch: ReturnType<typeof vi.fn>;
24
+
25
+ beforeEach(() => {
26
+ vi.clearAllMocks();
27
+
28
+ mockFetch = vi.fn();
29
+ global.fetch = mockFetch as unknown as typeof fetch;
30
+
31
+ client = new FileClient({
32
+ baseUrl: 'http://test.com',
33
+ port: 3000,
34
+ });
35
+ });
36
+
37
+ afterEach(() => {
38
+ vi.restoreAllMocks();
39
+ });
40
+
41
+ describe('mkdir', () => {
42
+ it('should create directories successfully', async () => {
43
+ const mockResponse: MkdirResult = {
44
+ success: true,
45
+ exitCode: 0,
46
+ path: '/app/new-directory',
47
+ recursive: false,
48
+ timestamp: '2023-01-01T00:00:00Z',
49
+ };
50
+
51
+ mockFetch.mockResolvedValue(new Response(
52
+ JSON.stringify(mockResponse),
53
+ { status: 200 }
54
+ ));
55
+
56
+ const result = await client.mkdir('/app/new-directory', 'session-mkdir');
57
+
58
+ expect(result.success).toBe(true);
59
+ expect(result.path).toBe('/app/new-directory');
60
+ expect(result.recursive).toBe(false);
61
+ expect(result.exitCode).toBe(0);
62
+ });
63
+
64
+ it('should create directories recursively', async () => {
65
+ const mockResponse: MkdirResult = {
66
+ success: true,
67
+ exitCode: 0,
68
+ path: '/app/deep/nested/directory',
69
+ recursive: true,
70
+ timestamp: '2023-01-01T00:00:00Z',
71
+ };
72
+
73
+ mockFetch.mockResolvedValue(new Response(
74
+ JSON.stringify(mockResponse),
75
+ { status: 200 }
76
+ ));
77
+
78
+ const result = await client.mkdir('/app/deep/nested/directory', 'session-mkdir', { recursive: true });
79
+
80
+ expect(result.success).toBe(true);
81
+ expect(result.recursive).toBe(true);
82
+ expect(result.path).toBe('/app/deep/nested/directory');
83
+ });
84
+
85
+ it('should handle permission denied errors', async () => {
86
+ const errorResponse = {
87
+ error: 'Permission denied: cannot create directory /root/secure',
88
+ code: 'PERMISSION_DENIED',
89
+ path: '/root/secure'
90
+ };
91
+
92
+ mockFetch.mockResolvedValue(new Response(
93
+ JSON.stringify(errorResponse),
94
+ { status: 403 }
95
+ ));
96
+
97
+ await expect(client.mkdir('/root/secure', 'session-mkdir'))
98
+ .rejects.toThrow(PermissionDeniedError);
99
+ });
100
+
101
+ it('should handle directory already exists errors', async () => {
102
+ const errorResponse = {
103
+ error: 'Directory already exists: /app/existing',
104
+ code: 'FILE_EXISTS',
105
+ path: '/app/existing'
106
+ };
107
+
108
+ mockFetch.mockResolvedValue(new Response(
109
+ JSON.stringify(errorResponse),
110
+ { status: 409 }
111
+ ));
112
+
113
+ await expect(client.mkdir('/app/existing', 'session-mkdir'))
114
+ .rejects.toThrow(FileExistsError);
115
+ });
116
+ });
117
+
118
+ describe('writeFile', () => {
119
+ it('should write files successfully', async () => {
120
+ const mockResponse: WriteFileResult = {
121
+ success: true,
122
+ exitCode: 0,
123
+ path: '/app/config.json',
124
+ timestamp: '2023-01-01T00:00:00Z',
125
+ };
126
+
127
+ mockFetch.mockResolvedValue(new Response(
128
+ JSON.stringify(mockResponse),
129
+ { status: 200 }
130
+ ));
131
+
132
+ const content = '{"setting": "value", "enabled": true}';
133
+ const result = await client.writeFile('/app/config.json', content, 'session-write');
134
+
135
+ expect(result.success).toBe(true);
136
+ expect(result.path).toBe('/app/config.json');
137
+ expect(result.exitCode).toBe(0);
138
+ });
139
+
140
+ it('should write files with different encodings', async () => {
141
+ const mockResponse: WriteFileResult = {
142
+ success: true,
143
+ exitCode: 0,
144
+ path: '/app/image.png',
145
+ timestamp: '2023-01-01T00:00:00Z',
146
+ };
147
+
148
+ mockFetch.mockResolvedValue(new Response(
149
+ JSON.stringify(mockResponse),
150
+ { status: 200 }
151
+ ));
152
+
153
+ const binaryData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jYlkKQAAAABJRU5ErkJggg==';
154
+ const result = await client.writeFile('/app/image.png', binaryData, 'session-write', { encoding: 'base64' });
155
+
156
+ expect(result.success).toBe(true);
157
+ expect(result.path).toBe('/app/image.png');
158
+ });
159
+
160
+ it('should handle write permission errors', async () => {
161
+ const errorResponse = {
162
+ error: 'Permission denied: cannot write to /system/readonly.txt',
163
+ code: 'PERMISSION_DENIED',
164
+ path: '/system/readonly.txt'
165
+ };
166
+
167
+ mockFetch.mockResolvedValue(new Response(
168
+ JSON.stringify(errorResponse),
169
+ { status: 403 }
170
+ ));
171
+
172
+ await expect(client.writeFile('/system/readonly.txt', 'content', 'session-err'))
173
+ .rejects.toThrow(PermissionDeniedError);
174
+ });
175
+
176
+ it('should handle disk space errors', async () => {
177
+ const errorResponse = {
178
+ error: 'No space left on device',
179
+ code: 'NO_SPACE',
180
+ path: '/app/largefile.dat'
181
+ };
182
+
183
+ mockFetch.mockResolvedValue(new Response(
184
+ JSON.stringify(errorResponse),
185
+ { status: 507 }
186
+ ));
187
+
188
+ await expect(client.writeFile('/app/largefile.dat', 'x'.repeat(1000000), 'session-err'))
189
+ .rejects.toThrow(FileSystemError);
190
+ });
191
+ });
192
+
193
+ describe('readFile', () => {
194
+ it('should read text files successfully with metadata', async () => {
195
+ const fileContent = `# Configuration File
196
+ server:
197
+ port: 3000
198
+ host: localhost
199
+ database:
200
+ url: postgresql://localhost/app`;
201
+
202
+ const mockResponse: ReadFileResult = {
203
+ success: true,
204
+ exitCode: 0,
205
+ path: '/app/config.yaml',
206
+ content: fileContent,
207
+ timestamp: '2023-01-01T00:00:00Z',
208
+ encoding: 'utf-8',
209
+ isBinary: false,
210
+ mimeType: 'text/yaml',
211
+ size: 100,
212
+ };
213
+
214
+ mockFetch.mockResolvedValue(new Response(
215
+ JSON.stringify(mockResponse),
216
+ { status: 200 }
217
+ ));
218
+
219
+ const result = await client.readFile('/app/config.yaml', 'session-read');
220
+
221
+ expect(result.success).toBe(true);
222
+ expect(result.path).toBe('/app/config.yaml');
223
+ expect(result.content).toContain('port: 3000');
224
+ expect(result.content).toContain('postgresql://localhost/app');
225
+ expect(result.exitCode).toBe(0);
226
+ expect(result.encoding).toBe('utf-8');
227
+ expect(result.isBinary).toBe(false);
228
+ expect(result.mimeType).toBe('text/yaml');
229
+ expect(result.size).toBe(100);
230
+ });
231
+
232
+ it('should read binary files with base64 encoding and metadata', async () => {
233
+ const binaryContent = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jYlkKQAAAABJRU5ErkJggg==';
234
+ const mockResponse: ReadFileResult = {
235
+ success: true,
236
+ exitCode: 0,
237
+ path: '/app/logo.png',
238
+ content: binaryContent,
239
+ timestamp: '2023-01-01T00:00:00Z',
240
+ encoding: 'base64',
241
+ isBinary: true,
242
+ mimeType: 'image/png',
243
+ size: 95,
244
+ };
245
+
246
+ mockFetch.mockResolvedValue(new Response(
247
+ JSON.stringify(mockResponse),
248
+ { status: 200 }
249
+ ));
250
+
251
+ const result = await client.readFile('/app/logo.png', 'session-read', { encoding: 'base64' });
252
+
253
+ expect(result.success).toBe(true);
254
+ expect(result.content).toBe(binaryContent);
255
+ expect(result.content.startsWith('iVBORw0K')).toBe(true);
256
+ expect(result.encoding).toBe('base64');
257
+ expect(result.isBinary).toBe(true);
258
+ expect(result.mimeType).toBe('image/png');
259
+ expect(result.size).toBe(95);
260
+ });
261
+
262
+ it('should handle file not found errors', async () => {
263
+ const errorResponse = {
264
+ error: 'File not found: /app/missing.txt',
265
+ code: 'FILE_NOT_FOUND',
266
+ path: '/app/missing.txt'
267
+ };
268
+
269
+ mockFetch.mockResolvedValue(new Response(
270
+ JSON.stringify(errorResponse),
271
+ { status: 404 }
272
+ ));
273
+
274
+ await expect(client.readFile('/app/missing.txt', 'session-read'))
275
+ .rejects.toThrow(FileNotFoundError);
276
+ });
277
+
278
+ it('should handle directory read attempts', async () => {
279
+ const errorResponse = {
280
+ error: 'Is a directory: /app/logs',
281
+ code: 'IS_DIRECTORY',
282
+ path: '/app/logs'
283
+ };
284
+
285
+ mockFetch.mockResolvedValue(new Response(
286
+ JSON.stringify(errorResponse),
287
+ { status: 400 }
288
+ ));
289
+
290
+ await expect(client.readFile('/app/logs', 'session-read'))
291
+ .rejects.toThrow(FileSystemError);
292
+ });
293
+ });
294
+
295
+ describe('readFileStream', () => {
296
+ it('should stream file successfully', async () => {
297
+ const mockStream = new ReadableStream({
298
+ start(controller) {
299
+ controller.enqueue(new TextEncoder().encode('data: {"type":"metadata","mimeType":"text/plain","size":100,"isBinary":false,"encoding":"utf-8"}\n\n'));
300
+ controller.enqueue(new TextEncoder().encode('data: {"type":"chunk","data":"Hello"}\n\n'));
301
+ controller.enqueue(new TextEncoder().encode('data: {"type":"complete","bytesRead":5}\n\n'));
302
+ controller.close();
303
+ }
304
+ });
305
+
306
+ mockFetch.mockResolvedValue(new Response(mockStream, {
307
+ status: 200,
308
+ headers: { 'Content-Type': 'text/event-stream' }
309
+ }));
310
+
311
+ const result = await client.readFileStream('/app/test.txt', 'session-stream');
312
+
313
+ expect(result).toBeInstanceOf(ReadableStream);
314
+ expect(mockFetch).toHaveBeenCalledWith(
315
+ expect.stringContaining('/api/read/stream'),
316
+ expect.objectContaining({
317
+ method: 'POST',
318
+ body: JSON.stringify({
319
+ path: '/app/test.txt',
320
+ sessionId: 'session-stream',
321
+ })
322
+ })
323
+ );
324
+ });
325
+
326
+ it('should handle binary file streams', async () => {
327
+ const mockStream = new ReadableStream({
328
+ start(controller) {
329
+ controller.enqueue(new TextEncoder().encode('data: {"type":"metadata","mimeType":"image/png","size":1024,"isBinary":true,"encoding":"base64"}\n\n'));
330
+ controller.enqueue(new TextEncoder().encode('data: {"type":"chunk","data":"iVBORw0K"}\n\n'));
331
+ controller.enqueue(new TextEncoder().encode('data: {"type":"complete","bytesRead":1024}\n\n'));
332
+ controller.close();
333
+ }
334
+ });
335
+
336
+ mockFetch.mockResolvedValue(new Response(mockStream, {
337
+ status: 200,
338
+ headers: { 'Content-Type': 'text/event-stream' }
339
+ }));
340
+
341
+ const result = await client.readFileStream('/app/image.png', 'session-stream');
342
+
343
+ expect(result).toBeInstanceOf(ReadableStream);
344
+ });
345
+
346
+ it('should handle stream errors', async () => {
347
+ const errorResponse = {
348
+ error: 'File not found: /app/missing.txt',
349
+ code: 'FILE_NOT_FOUND',
350
+ path: '/app/missing.txt'
351
+ };
352
+
353
+ mockFetch.mockResolvedValue(new Response(
354
+ JSON.stringify(errorResponse),
355
+ { status: 404 }
356
+ ));
357
+
358
+ await expect(client.readFileStream('/app/missing.txt', 'session-stream'))
359
+ .rejects.toThrow(FileNotFoundError);
360
+ });
361
+
362
+ it('should handle network errors during streaming', async () => {
363
+ mockFetch.mockRejectedValue(new Error('Network timeout'));
364
+
365
+ await expect(client.readFileStream('/app/file.txt', 'session-stream'))
366
+ .rejects.toThrow('Network timeout');
367
+ });
368
+ });
369
+
370
+ describe('deleteFile', () => {
371
+ it('should delete files successfully', async () => {
372
+ const mockResponse: DeleteFileResult = {
373
+ success: true,
374
+ exitCode: 0,
375
+ path: '/app/temp.txt',
376
+ timestamp: '2023-01-01T00:00:00Z',
377
+ };
378
+
379
+ mockFetch.mockResolvedValue(new Response(
380
+ JSON.stringify(mockResponse),
381
+ { status: 200 }
382
+ ));
383
+
384
+ const result = await client.deleteFile('/app/temp.txt', 'session-delete');
385
+
386
+ expect(result.success).toBe(true);
387
+ expect(result.path).toBe('/app/temp.txt');
388
+ expect(result.exitCode).toBe(0);
389
+ });
390
+
391
+ it('should handle delete non-existent file', async () => {
392
+ const errorResponse = {
393
+ error: 'File not found: /app/nonexistent.txt',
394
+ code: 'FILE_NOT_FOUND',
395
+ path: '/app/nonexistent.txt'
396
+ };
397
+
398
+ mockFetch.mockResolvedValue(new Response(
399
+ JSON.stringify(errorResponse),
400
+ { status: 404 }
401
+ ));
402
+
403
+ await expect(client.deleteFile('/app/nonexistent.txt', 'session-delete'))
404
+ .rejects.toThrow(FileNotFoundError);
405
+ });
406
+
407
+ it('should handle delete permission errors', async () => {
408
+ const errorResponse = {
409
+ error: 'Permission denied: cannot delete /system/important.conf',
410
+ code: 'PERMISSION_DENIED',
411
+ path: '/system/important.conf'
412
+ };
413
+
414
+ mockFetch.mockResolvedValue(new Response(
415
+ JSON.stringify(errorResponse),
416
+ { status: 403 }
417
+ ));
418
+
419
+ await expect(client.deleteFile('/system/important.conf', 'session-delete'))
420
+ .rejects.toThrow(PermissionDeniedError);
421
+ });
422
+ });
423
+
424
+ describe('renameFile', () => {
425
+ it('should rename files successfully', async () => {
426
+ const mockResponse: RenameFileResult = {
427
+ success: true,
428
+ exitCode: 0,
429
+ path: '/app/old-name.txt',
430
+ newPath: '/app/new-name.txt',
431
+ timestamp: '2023-01-01T00:00:00Z',
432
+ };
433
+
434
+ mockFetch.mockResolvedValue(new Response(
435
+ JSON.stringify(mockResponse),
436
+ { status: 200 }
437
+ ));
438
+
439
+ const result = await client.renameFile('/app/old-name.txt', '/app/new-name.txt', 'session-rename');
440
+
441
+ expect(result.success).toBe(true);
442
+ expect(result.path).toBe('/app/old-name.txt');
443
+ expect(result.newPath).toBe('/app/new-name.txt');
444
+ expect(result.exitCode).toBe(0);
445
+ });
446
+
447
+ it('should handle rename to existing file', async () => {
448
+ const errorResponse = {
449
+ error: 'Target file already exists: /app/existing.txt',
450
+ code: 'FILE_EXISTS',
451
+ path: '/app/existing.txt'
452
+ };
453
+
454
+ mockFetch.mockResolvedValue(new Response(
455
+ JSON.stringify(errorResponse),
456
+ { status: 409 }
457
+ ));
458
+
459
+ await expect(client.renameFile('/app/source.txt', '/app/existing.txt', 'session-rename'))
460
+ .rejects.toThrow(FileExistsError);
461
+ });
462
+ });
463
+
464
+ describe('moveFile', () => {
465
+ it('should move files successfully', async () => {
466
+ const mockResponse: MoveFileResult = {
467
+ success: true,
468
+ exitCode: 0,
469
+ path: '/src/document.pdf',
470
+ newPath: '/dest/document.pdf',
471
+ timestamp: '2023-01-01T00:00:00Z',
472
+ };
473
+
474
+ mockFetch.mockResolvedValue(new Response(
475
+ JSON.stringify(mockResponse),
476
+ { status: 200 }
477
+ ));
478
+
479
+ const result = await client.moveFile('/src/document.pdf', '/dest/document.pdf', 'session-move');
480
+
481
+ expect(result.success).toBe(true);
482
+ expect(result.path).toBe('/src/document.pdf');
483
+ expect(result.newPath).toBe('/dest/document.pdf');
484
+ expect(result.exitCode).toBe(0);
485
+ });
486
+
487
+ it('should handle move to non-existent directory', async () => {
488
+ const errorResponse = {
489
+ error: 'Destination directory does not exist: /nonexistent/',
490
+ code: 'NOT_DIRECTORY',
491
+ path: '/nonexistent/'
492
+ };
493
+
494
+ mockFetch.mockResolvedValue(new Response(
495
+ JSON.stringify(errorResponse),
496
+ { status: 404 }
497
+ ));
498
+
499
+ await expect(client.moveFile('/app/file.txt', '/nonexistent/file.txt', 'session-move'))
500
+ .rejects.toThrow(FileSystemError);
501
+ });
502
+ });
503
+
504
+ describe('listFiles', () => {
505
+ const createMockFile = (overrides: Partial<any> = {}) => ({
506
+ name: 'test.txt',
507
+ absolutePath: '/workspace/test.txt',
508
+ relativePath: 'test.txt',
509
+ type: 'file' as const,
510
+ size: 1024,
511
+ modifiedAt: '2023-01-01T00:00:00Z',
512
+ mode: 'rw-r--r--',
513
+ permissions: { readable: true, writable: true, executable: false },
514
+ ...overrides,
515
+ });
516
+
517
+ it('should list files with correct structure', async () => {
518
+ const mockResponse: ListFilesResult = {
519
+ success: true,
520
+ path: '/workspace',
521
+ files: [
522
+ createMockFile({ name: 'file.txt' }),
523
+ createMockFile({ name: 'dir', type: 'directory', mode: 'rwxr-xr-x' }),
524
+ ],
525
+ count: 2,
526
+ timestamp: '2023-01-01T00:00:00Z',
527
+ };
528
+
529
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
530
+
531
+ const result = await client.listFiles('/workspace', 'session-list');
532
+
533
+ expect(result.success).toBe(true);
534
+ expect(result.count).toBe(2);
535
+ expect(result.files[0].name).toBe('file.txt');
536
+ expect(result.files[1].name).toBe('dir');
537
+ expect(result.files[1].type).toBe('directory');
538
+ });
539
+
540
+ it('should pass options correctly', async () => {
541
+ const mockResponse: ListFilesResult = {
542
+ success: true,
543
+ path: '/workspace',
544
+ files: [createMockFile({ name: '.hidden', relativePath: '.hidden' })],
545
+ count: 1,
546
+ timestamp: '2023-01-01T00:00:00Z',
547
+ };
548
+
549
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
550
+
551
+ await client.listFiles('/workspace', 'session-list', { recursive: true, includeHidden: true });
552
+
553
+ expect(mockFetch).toHaveBeenCalledWith(
554
+ expect.stringContaining('/api/list-files'),
555
+ expect.objectContaining({
556
+ body: JSON.stringify({
557
+ path: '/workspace',
558
+ sessionId: 'session-list',
559
+ options: { recursive: true, includeHidden: true },
560
+ })
561
+ })
562
+ );
563
+ });
564
+
565
+ it('should handle empty directories', async () => {
566
+ mockFetch.mockResolvedValue(new Response(
567
+ JSON.stringify({ success: true, path: '/empty', files: [], count: 0, timestamp: '2023-01-01T00:00:00Z' }),
568
+ { status: 200 }
569
+ ));
570
+
571
+ const result = await client.listFiles('/empty', 'session-list');
572
+
573
+ expect(result.count).toBe(0);
574
+ expect(result.files).toHaveLength(0);
575
+ });
576
+
577
+ it('should handle error responses', async () => {
578
+ mockFetch.mockResolvedValue(new Response(
579
+ JSON.stringify({ error: 'Directory not found', code: 'FILE_NOT_FOUND' }),
580
+ { status: 404 }
581
+ ));
582
+
583
+ await expect(client.listFiles('/nonexistent', 'session-list'))
584
+ .rejects.toThrow(FileNotFoundError);
585
+ });
586
+ });
587
+
588
+ describe('exists', () => {
589
+ it('should return true when file exists', async () => {
590
+ const mockResponse: FileExistsResult = {
591
+ success: true,
592
+ path: '/workspace/test.txt',
593
+ exists: true,
594
+ timestamp: '2023-01-01T00:00:00Z',
595
+ };
596
+
597
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
598
+
599
+ const result = await client.exists('/workspace/test.txt', 'session-exists');
600
+
601
+ expect(result.success).toBe(true);
602
+ expect(result.exists).toBe(true);
603
+ expect(result.path).toBe('/workspace/test.txt');
604
+ });
605
+
606
+ it('should return false when file does not exist', async () => {
607
+ const mockResponse: FileExistsResult = {
608
+ success: true,
609
+ path: '/workspace/nonexistent.txt',
610
+ exists: false,
611
+ timestamp: '2023-01-01T00:00:00Z',
612
+ };
613
+
614
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
615
+
616
+ const result = await client.exists('/workspace/nonexistent.txt', 'session-exists');
617
+
618
+ expect(result.success).toBe(true);
619
+ expect(result.exists).toBe(false);
620
+ });
621
+
622
+ it('should return true when directory exists', async () => {
623
+ const mockResponse: FileExistsResult = {
624
+ success: true,
625
+ path: '/workspace/some-dir',
626
+ exists: true,
627
+ timestamp: '2023-01-01T00:00:00Z',
628
+ };
629
+
630
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
631
+
632
+ const result = await client.exists('/workspace/some-dir', 'session-exists');
633
+
634
+ expect(result.success).toBe(true);
635
+ expect(result.exists).toBe(true);
636
+ });
637
+
638
+ it('should send correct request payload', async () => {
639
+ const mockResponse: FileExistsResult = {
640
+ success: true,
641
+ path: '/test/path',
642
+ exists: true,
643
+ timestamp: '2023-01-01T00:00:00Z',
644
+ };
645
+
646
+ mockFetch.mockResolvedValue(new Response(JSON.stringify(mockResponse), { status: 200 }));
647
+
648
+ await client.exists('/test/path', 'session-test');
649
+
650
+ expect(mockFetch).toHaveBeenCalledWith(
651
+ expect.stringContaining('/api/exists'),
652
+ expect.objectContaining({
653
+ method: 'POST',
654
+ body: JSON.stringify({
655
+ path: '/test/path',
656
+ sessionId: 'session-test',
657
+ })
658
+ })
659
+ );
660
+ });
661
+ });
662
+
663
+ describe('error handling', () => {
664
+ it('should handle network failures gracefully', async () => {
665
+ mockFetch.mockRejectedValue(new Error('Network connection failed'));
666
+
667
+ await expect(client.readFile('/app/file.txt', 'session-read'))
668
+ .rejects.toThrow('Network connection failed');
669
+ });
670
+
671
+ it('should handle malformed server responses', async () => {
672
+ mockFetch.mockResolvedValue(new Response(
673
+ 'invalid json {',
674
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
675
+ ));
676
+
677
+ await expect(client.writeFile('/app/file.txt', 'content', 'session-err'))
678
+ .rejects.toThrow(SandboxError);
679
+ });
680
+
681
+ it('should handle server errors with proper mapping', async () => {
682
+ const serverErrorScenarios = [
683
+ { status: 400, code: 'FILESYSTEM_ERROR', error: FileSystemError },
684
+ { status: 403, code: 'PERMISSION_DENIED', error: PermissionDeniedError },
685
+ { status: 404, code: 'FILE_NOT_FOUND', error: FileNotFoundError },
686
+ { status: 409, code: 'FILE_EXISTS', error: FileExistsError },
687
+ { status: 500, code: 'INTERNAL_ERROR', error: SandboxError },
688
+ ];
689
+
690
+ for (const scenario of serverErrorScenarios) {
691
+ mockFetch.mockResolvedValueOnce(new Response(
692
+ JSON.stringify({
693
+ error: 'Test error',
694
+ code: scenario.code
695
+ }),
696
+ { status: scenario.status }
697
+ ));
698
+
699
+ await expect(client.readFile('/app/test.txt', 'session-read'))
700
+ .rejects.toThrow(scenario.error);
701
+ }
702
+ });
703
+ });
704
+
705
+ describe('constructor options', () => {
706
+ it('should initialize with minimal options', () => {
707
+ const minimalClient = new FileClient();
708
+ expect(minimalClient).toBeDefined();
709
+ });
710
+
711
+ it('should initialize with full options', () => {
712
+ const fullOptionsClient = new FileClient({
713
+ baseUrl: 'http://custom.com',
714
+ port: 8080,
715
+ });
716
+ expect(fullOptionsClient).toBeDefined();
717
+ });
718
+ });
719
+ });