@cloudflare/sandbox 0.0.0-444d2da → 0.0.0-4572082

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 (79) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/Dockerfile +130 -9
  3. package/README.md +149 -50
  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-EXQOIRZI.js +2351 -0
  9. package/dist/chunk-EXQOIRZI.js.map +1 -0
  10. package/dist/chunk-JXZMAU2C.js +559 -0
  11. package/dist/chunk-JXZMAU2C.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +66 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +31 -0
  31. package/dist/security.js +13 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +14 -8
  37. package/src/clients/base-client.ts +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/clients/interpreter-client.ts +329 -0
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +83 -119
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +170 -0
  55. package/src/sandbox.ts +916 -0
  56. package/src/security.ts +104 -0
  57. package/src/sse-parser.ts +143 -0
  58. package/startup.sh +3 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +290 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/index.ts +0 -2900
  73. package/container_src/package.json +0 -9
  74. package/src/client.ts +0 -1929
  75. package/tests/client.example.ts +0 -308
  76. package/tests/connection-test.ts +0 -81
  77. package/tests/simple-test.ts +0 -81
  78. package/tests/test1.ts +0 -281
  79. package/tests/test2.ts +0 -929
package/src/client.ts DELETED
@@ -1,1929 +0,0 @@
1
- import type { DurableObject } from "cloudflare:workers";
2
- import type { Sandbox } from "./index";
3
-
4
- interface ExecuteRequest {
5
- command: string;
6
- args?: string[];
7
- }
8
-
9
- export interface ExecuteResponse {
10
- success: boolean;
11
- stdout: string;
12
- stderr: string;
13
- exitCode: number;
14
- command: string;
15
- args: string[];
16
- timestamp: string;
17
- }
18
-
19
- interface SessionResponse {
20
- sessionId: string;
21
- message: string;
22
- timestamp: string;
23
- }
24
-
25
- interface SessionListResponse {
26
- sessions: Array<{
27
- sessionId: string;
28
- hasActiveProcess: boolean;
29
- createdAt: string;
30
- }>;
31
- count: number;
32
- timestamp: string;
33
- }
34
-
35
- interface CommandsResponse {
36
- availableCommands: string[];
37
- timestamp: string;
38
- }
39
-
40
- interface GitCheckoutRequest {
41
- repoUrl: string;
42
- branch?: string;
43
- targetDir?: string;
44
- sessionId?: string;
45
- }
46
-
47
- export interface GitCheckoutResponse {
48
- success: boolean;
49
- stdout: string;
50
- stderr: string;
51
- exitCode: number;
52
- repoUrl: string;
53
- branch: string;
54
- targetDir: string;
55
- timestamp: string;
56
- }
57
-
58
- interface MkdirRequest {
59
- path: string;
60
- recursive?: boolean;
61
- sessionId?: string;
62
- }
63
-
64
- export interface MkdirResponse {
65
- success: boolean;
66
- stdout: string;
67
- stderr: string;
68
- exitCode: number;
69
- path: string;
70
- recursive: boolean;
71
- timestamp: string;
72
- }
73
-
74
- interface WriteFileRequest {
75
- path: string;
76
- content: string;
77
- encoding?: string;
78
- sessionId?: string;
79
- }
80
-
81
- export interface WriteFileResponse {
82
- success: boolean;
83
- exitCode: number;
84
- path: string;
85
- timestamp: string;
86
- }
87
-
88
- interface ReadFileRequest {
89
- path: string;
90
- encoding?: string;
91
- sessionId?: string;
92
- }
93
-
94
- export interface ReadFileResponse {
95
- success: boolean;
96
- exitCode: number;
97
- path: string;
98
- content: string;
99
- timestamp: string;
100
- }
101
-
102
- interface DeleteFileRequest {
103
- path: string;
104
- sessionId?: string;
105
- }
106
-
107
- export interface DeleteFileResponse {
108
- success: boolean;
109
- exitCode: number;
110
- path: string;
111
- timestamp: string;
112
- }
113
-
114
- interface RenameFileRequest {
115
- oldPath: string;
116
- newPath: string;
117
- sessionId?: string;
118
- }
119
-
120
- export interface RenameFileResponse {
121
- success: boolean;
122
- exitCode: number;
123
- oldPath: string;
124
- newPath: string;
125
- timestamp: string;
126
- }
127
-
128
- interface MoveFileRequest {
129
- sourcePath: string;
130
- destinationPath: string;
131
- sessionId?: string;
132
- }
133
-
134
- export interface MoveFileResponse {
135
- success: boolean;
136
- exitCode: number;
137
- sourcePath: string;
138
- destinationPath: string;
139
- timestamp: string;
140
- }
141
-
142
- interface PingResponse {
143
- message: string;
144
- timestamp: string;
145
- }
146
-
147
- interface StreamEvent {
148
- type: "command_start" | "output" | "command_complete" | "error";
149
- command?: string;
150
- args?: string[];
151
- stream?: "stdout" | "stderr";
152
- data?: string;
153
- message?: string;
154
- path?: string;
155
- oldPath?: string;
156
- newPath?: string;
157
- sourcePath?: string;
158
- destinationPath?: string;
159
- content?: string;
160
- success?: boolean;
161
- exitCode?: number;
162
- stdout?: string;
163
- stderr?: string;
164
- error?: string;
165
- timestamp?: string;
166
- }
167
-
168
- interface HttpClientOptions {
169
- stub?: Sandbox;
170
- baseUrl?: string;
171
- port?: number;
172
- onCommandStart?: (command: string, args: string[]) => void;
173
- onOutput?: (
174
- stream: "stdout" | "stderr",
175
- data: string,
176
- command: string
177
- ) => void;
178
- onCommandComplete?: (
179
- success: boolean,
180
- exitCode: number,
181
- stdout: string,
182
- stderr: string,
183
- command: string,
184
- args: string[]
185
- ) => void;
186
- onError?: (error: string, command?: string, args?: string[]) => void;
187
- onStreamEvent?: (event: StreamEvent) => void;
188
- }
189
-
190
- export class HttpClient {
191
- private baseUrl: string;
192
- private options: HttpClientOptions;
193
- private sessionId: string | null = null;
194
-
195
- constructor(options: HttpClientOptions = {}) {
196
- this.options = {
197
- ...options,
198
- };
199
- this.baseUrl = this.options.baseUrl!;
200
- }
201
-
202
- private async doFetch(
203
- path: string,
204
- options?: RequestInit
205
- ): Promise<Response> {
206
- if (this.options.stub) {
207
- return this.options.stub.containerFetch(path, options, this.options.port);
208
- }
209
- return fetch(this.baseUrl + path, options);
210
- }
211
- // Public methods to set event handlers
212
- setOnOutput(
213
- handler: (
214
- stream: "stdout" | "stderr",
215
- data: string,
216
- command: string
217
- ) => void
218
- ): void {
219
- this.options.onOutput = handler;
220
- }
221
-
222
- setOnCommandComplete(
223
- handler: (
224
- success: boolean,
225
- exitCode: number,
226
- stdout: string,
227
- stderr: string,
228
- command: string,
229
- args: string[]
230
- ) => void
231
- ): void {
232
- this.options.onCommandComplete = handler;
233
- }
234
-
235
- setOnStreamEvent(handler: (event: StreamEvent) => void): void {
236
- this.options.onStreamEvent = handler;
237
- }
238
-
239
- // Public getter methods
240
- getOnOutput():
241
- | ((stream: "stdout" | "stderr", data: string, command: string) => void)
242
- | undefined {
243
- return this.options.onOutput;
244
- }
245
-
246
- getOnCommandComplete():
247
- | ((
248
- success: boolean,
249
- exitCode: number,
250
- stdout: string,
251
- stderr: string,
252
- command: string,
253
- args: string[]
254
- ) => void)
255
- | undefined {
256
- return this.options.onCommandComplete;
257
- }
258
-
259
- getOnStreamEvent(): ((event: StreamEvent) => void) | undefined {
260
- return this.options.onStreamEvent;
261
- }
262
-
263
- async createSession(): Promise<string> {
264
- try {
265
- const response = await this.doFetch(`/api/session/create`, {
266
- headers: {
267
- "Content-Type": "application/json",
268
- },
269
- method: "POST",
270
- });
271
-
272
- if (!response.ok) {
273
- throw new Error(`HTTP error! status: ${response.status}`);
274
- }
275
-
276
- const data: SessionResponse = await response.json();
277
- this.sessionId = data.sessionId;
278
- console.log(`[HTTP Client] Created session: ${this.sessionId}`);
279
- return this.sessionId;
280
- } catch (error) {
281
- console.error("[HTTP Client] Error creating session:", error);
282
- throw error;
283
- }
284
- }
285
-
286
- async listSessions(): Promise<SessionListResponse> {
287
- try {
288
- const response = await this.doFetch(`/api/session/list`, {
289
- headers: {
290
- "Content-Type": "application/json",
291
- },
292
- method: "GET",
293
- });
294
-
295
- if (!response.ok) {
296
- throw new Error(`HTTP error! status: ${response.status}`);
297
- }
298
-
299
- const data: SessionListResponse = await response.json();
300
- console.log(`[HTTP Client] Listed ${data.count} sessions`);
301
- return data;
302
- } catch (error) {
303
- console.error("[HTTP Client] Error listing sessions:", error);
304
- throw error;
305
- }
306
- }
307
-
308
- async execute(
309
- command: string,
310
- args: string[] = [],
311
- sessionId?: string
312
- ): Promise<ExecuteResponse> {
313
- try {
314
- const targetSessionId = sessionId || this.sessionId;
315
-
316
- const response = await this.doFetch(`/api/execute`, {
317
- body: JSON.stringify({
318
- args,
319
- command,
320
- sessionId: targetSessionId,
321
- }),
322
- headers: {
323
- "Content-Type": "application/json",
324
- },
325
- method: "POST",
326
- });
327
-
328
- if (!response.ok) {
329
- const errorData = (await response.json().catch(() => ({}))) as {
330
- error?: string;
331
- };
332
- throw new Error(
333
- errorData.error || `HTTP error! status: ${response.status}`
334
- );
335
- }
336
-
337
- const data: ExecuteResponse = await response.json();
338
- console.log(
339
- `[HTTP Client] Command executed: ${command}, Success: ${data.success}`
340
- );
341
-
342
- // Call the callback if provided
343
- this.options.onCommandComplete?.(
344
- data.success,
345
- data.exitCode,
346
- data.stdout,
347
- data.stderr,
348
- data.command,
349
- data.args
350
- );
351
-
352
- return data;
353
- } catch (error) {
354
- console.error("[HTTP Client] Error executing command:", error);
355
- this.options.onError?.(
356
- error instanceof Error ? error.message : "Unknown error",
357
- command,
358
- args
359
- );
360
- throw error;
361
- }
362
- }
363
-
364
- async executeStream(
365
- command: string,
366
- args: string[] = [],
367
- sessionId?: string
368
- ): Promise<void> {
369
- try {
370
- const targetSessionId = sessionId || this.sessionId;
371
-
372
- const response = await this.doFetch(`/api/execute/stream`, {
373
- body: JSON.stringify({
374
- args,
375
- command,
376
- sessionId: targetSessionId,
377
- }),
378
- headers: {
379
- "Content-Type": "application/json",
380
- },
381
- method: "POST",
382
- });
383
-
384
- if (!response.ok) {
385
- const errorData = (await response.json().catch(() => ({}))) as {
386
- error?: string;
387
- };
388
- throw new Error(
389
- errorData.error || `HTTP error! status: ${response.status}`
390
- );
391
- }
392
-
393
- if (!response.body) {
394
- throw new Error("No response body for streaming request");
395
- }
396
-
397
- const reader = response.body.getReader();
398
- const decoder = new TextDecoder();
399
-
400
- try {
401
- while (true) {
402
- const { done, value } = await reader.read();
403
-
404
- if (done) {
405
- break;
406
- }
407
-
408
- const chunk = decoder.decode(value, { stream: true });
409
- const lines = chunk.split("\n");
410
-
411
- for (const line of lines) {
412
- if (line.startsWith("data: ")) {
413
- try {
414
- const eventData = line.slice(6); // Remove 'data: ' prefix
415
- const event: StreamEvent = JSON.parse(eventData);
416
-
417
- console.log(`[HTTP Client] Stream event: ${event.type}`);
418
- this.options.onStreamEvent?.(event);
419
-
420
- switch (event.type) {
421
- case "command_start":
422
- console.log(
423
- `[HTTP Client] Command started: ${
424
- event.command
425
- } ${event.args?.join(" ")}`
426
- );
427
- this.options.onCommandStart?.(
428
- event.command!,
429
- event.args || []
430
- );
431
- break;
432
-
433
- case "output":
434
- console.log(`[${event.stream}] ${event.data}`);
435
- this.options.onOutput?.(
436
- event.stream!,
437
- event.data!,
438
- event.command!
439
- );
440
- break;
441
-
442
- case "command_complete":
443
- console.log(
444
- `[HTTP Client] Command completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
445
- );
446
- this.options.onCommandComplete?.(
447
- event.success!,
448
- event.exitCode!,
449
- event.stdout!,
450
- event.stderr!,
451
- event.command!,
452
- event.args || []
453
- );
454
- break;
455
-
456
- case "error":
457
- console.error(
458
- `[HTTP Client] Command error: ${event.error}`
459
- );
460
- this.options.onError?.(
461
- event.error!,
462
- event.command,
463
- event.args
464
- );
465
- break;
466
- }
467
- } catch (parseError) {
468
- console.warn(
469
- "[HTTP Client] Failed to parse stream event:",
470
- parseError
471
- );
472
- }
473
- }
474
- }
475
- }
476
- } finally {
477
- reader.releaseLock();
478
- }
479
- } catch (error) {
480
- console.error("[HTTP Client] Error in streaming execution:", error);
481
- this.options.onError?.(
482
- error instanceof Error ? error.message : "Unknown error",
483
- command,
484
- args
485
- );
486
- throw error;
487
- }
488
- }
489
-
490
- async gitCheckout(
491
- repoUrl: string,
492
- branch: string = "main",
493
- targetDir?: string,
494
- sessionId?: string
495
- ): Promise<GitCheckoutResponse> {
496
- try {
497
- const targetSessionId = sessionId || this.sessionId;
498
-
499
- const response = await this.doFetch(`/api/git/checkout`, {
500
- body: JSON.stringify({
501
- branch,
502
- repoUrl,
503
- sessionId: targetSessionId,
504
- targetDir,
505
- }),
506
- headers: {
507
- "Content-Type": "application/json",
508
- },
509
- method: "POST",
510
- });
511
-
512
- if (!response.ok) {
513
- const errorData = (await response.json().catch(() => ({}))) as {
514
- error?: string;
515
- };
516
- throw new Error(
517
- errorData.error || `HTTP error! status: ${response.status}`
518
- );
519
- }
520
-
521
- const data: GitCheckoutResponse = await response.json();
522
- console.log(
523
- `[HTTP Client] Git checkout completed: ${repoUrl}, Success: ${data.success}, Target: ${data.targetDir}`
524
- );
525
-
526
- return data;
527
- } catch (error) {
528
- console.error("[HTTP Client] Error in git checkout:", error);
529
- throw error;
530
- }
531
- }
532
-
533
- async gitCheckoutStream(
534
- repoUrl: string,
535
- branch: string = "main",
536
- targetDir?: string,
537
- sessionId?: string
538
- ): Promise<void> {
539
- try {
540
- const targetSessionId = sessionId || this.sessionId;
541
-
542
- const response = await this.doFetch(`/api/git/checkout/stream`, {
543
- body: JSON.stringify({
544
- branch,
545
- repoUrl,
546
- sessionId: targetSessionId,
547
- targetDir,
548
- }),
549
- headers: {
550
- "Content-Type": "application/json",
551
- },
552
- method: "POST",
553
- });
554
-
555
- if (!response.ok) {
556
- const errorData = (await response.json().catch(() => ({}))) as {
557
- error?: string;
558
- };
559
- throw new Error(
560
- errorData.error || `HTTP error! status: ${response.status}`
561
- );
562
- }
563
-
564
- if (!response.body) {
565
- throw new Error("No response body for streaming request");
566
- }
567
-
568
- const reader = response.body.getReader();
569
- const decoder = new TextDecoder();
570
-
571
- try {
572
- while (true) {
573
- const { done, value } = await reader.read();
574
-
575
- if (done) {
576
- break;
577
- }
578
-
579
- const chunk = decoder.decode(value, { stream: true });
580
- const lines = chunk.split("\n");
581
-
582
- for (const line of lines) {
583
- if (line.startsWith("data: ")) {
584
- try {
585
- const eventData = line.slice(6); // Remove 'data: ' prefix
586
- const event: StreamEvent = JSON.parse(eventData);
587
-
588
- console.log(
589
- `[HTTP Client] Git checkout stream event: ${event.type}`
590
- );
591
- this.options.onStreamEvent?.(event);
592
-
593
- switch (event.type) {
594
- case "command_start":
595
- console.log(
596
- `[HTTP Client] Git checkout started: ${
597
- event.command
598
- } ${event.args?.join(" ")}`
599
- );
600
- this.options.onCommandStart?.(
601
- event.command!,
602
- event.args || []
603
- );
604
- break;
605
-
606
- case "output":
607
- console.log(`[${event.stream}] ${event.data}`);
608
- this.options.onOutput?.(
609
- event.stream!,
610
- event.data!,
611
- event.command!
612
- );
613
- break;
614
-
615
- case "command_complete":
616
- console.log(
617
- `[HTTP Client] Git checkout completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
618
- );
619
- this.options.onCommandComplete?.(
620
- event.success!,
621
- event.exitCode!,
622
- event.stdout!,
623
- event.stderr!,
624
- event.command!,
625
- event.args || []
626
- );
627
- break;
628
-
629
- case "error":
630
- console.error(
631
- `[HTTP Client] Git checkout error: ${event.error}`
632
- );
633
- this.options.onError?.(
634
- event.error!,
635
- event.command,
636
- event.args
637
- );
638
- break;
639
- }
640
- } catch (parseError) {
641
- console.warn(
642
- "[HTTP Client] Failed to parse git checkout stream event:",
643
- parseError
644
- );
645
- }
646
- }
647
- }
648
- }
649
- } finally {
650
- reader.releaseLock();
651
- }
652
- } catch (error) {
653
- console.error("[HTTP Client] Error in streaming git checkout:", error);
654
- this.options.onError?.(
655
- error instanceof Error ? error.message : "Unknown error",
656
- "git clone",
657
- [branch, repoUrl, targetDir || ""]
658
- );
659
- throw error;
660
- }
661
- }
662
-
663
- async mkdir(
664
- path: string,
665
- recursive: boolean = false,
666
- sessionId?: string
667
- ): Promise<MkdirResponse> {
668
- try {
669
- const targetSessionId = sessionId || this.sessionId;
670
-
671
- const response = await this.doFetch(`/api/mkdir`, {
672
- body: JSON.stringify({
673
- path,
674
- recursive,
675
- sessionId: targetSessionId,
676
- }),
677
- headers: {
678
- "Content-Type": "application/json",
679
- },
680
- method: "POST",
681
- });
682
-
683
- if (!response.ok) {
684
- const errorData = (await response.json().catch(() => ({}))) as {
685
- error?: string;
686
- };
687
- throw new Error(
688
- errorData.error || `HTTP error! status: ${response.status}`
689
- );
690
- }
691
-
692
- const data: MkdirResponse = await response.json();
693
- console.log(
694
- `[HTTP Client] Directory created: ${path}, Success: ${data.success}, Recursive: ${data.recursive}`
695
- );
696
-
697
- return data;
698
- } catch (error) {
699
- console.error("[HTTP Client] Error creating directory:", error);
700
- throw error;
701
- }
702
- }
703
-
704
- async mkdirStream(
705
- path: string,
706
- recursive: boolean = false,
707
- sessionId?: string
708
- ): Promise<void> {
709
- try {
710
- const targetSessionId = sessionId || this.sessionId;
711
-
712
- const response = await this.doFetch(`/api/mkdir/stream`, {
713
- body: JSON.stringify({
714
- path,
715
- recursive,
716
- sessionId: targetSessionId,
717
- }),
718
- headers: {
719
- "Content-Type": "application/json",
720
- },
721
- method: "POST",
722
- });
723
-
724
- if (!response.ok) {
725
- const errorData = (await response.json().catch(() => ({}))) as {
726
- error?: string;
727
- };
728
- throw new Error(
729
- errorData.error || `HTTP error! status: ${response.status}`
730
- );
731
- }
732
-
733
- if (!response.body) {
734
- throw new Error("No response body for streaming request");
735
- }
736
-
737
- const reader = response.body.getReader();
738
- const decoder = new TextDecoder();
739
-
740
- try {
741
- while (true) {
742
- const { done, value } = await reader.read();
743
-
744
- if (done) {
745
- break;
746
- }
747
-
748
- const chunk = decoder.decode(value, { stream: true });
749
- const lines = chunk.split("\n");
750
-
751
- for (const line of lines) {
752
- if (line.startsWith("data: ")) {
753
- try {
754
- const eventData = line.slice(6); // Remove 'data: ' prefix
755
- const event: StreamEvent = JSON.parse(eventData);
756
-
757
- console.log(`[HTTP Client] Mkdir stream event: ${event.type}`);
758
- this.options.onStreamEvent?.(event);
759
-
760
- switch (event.type) {
761
- case "command_start":
762
- console.log(
763
- `[HTTP Client] Mkdir started: ${
764
- event.command
765
- } ${event.args?.join(" ")}`
766
- );
767
- this.options.onCommandStart?.(
768
- event.command!,
769
- event.args || []
770
- );
771
- break;
772
-
773
- case "output":
774
- console.log(`[${event.stream}] ${event.data}`);
775
- this.options.onOutput?.(
776
- event.stream!,
777
- event.data!,
778
- event.command!
779
- );
780
- break;
781
-
782
- case "command_complete":
783
- console.log(
784
- `[HTTP Client] Mkdir completed: ${event.command}, Success: ${event.success}, Exit code: ${event.exitCode}`
785
- );
786
- this.options.onCommandComplete?.(
787
- event.success!,
788
- event.exitCode!,
789
- event.stdout!,
790
- event.stderr!,
791
- event.command!,
792
- event.args || []
793
- );
794
- break;
795
-
796
- case "error":
797
- console.error(`[HTTP Client] Mkdir error: ${event.error}`);
798
- this.options.onError?.(
799
- event.error!,
800
- event.command,
801
- event.args
802
- );
803
- break;
804
- }
805
- } catch (parseError) {
806
- console.warn(
807
- "[HTTP Client] Failed to parse mkdir stream event:",
808
- parseError
809
- );
810
- }
811
- }
812
- }
813
- }
814
- } finally {
815
- reader.releaseLock();
816
- }
817
- } catch (error) {
818
- console.error("[HTTP Client] Error in streaming mkdir:", error);
819
- this.options.onError?.(
820
- error instanceof Error ? error.message : "Unknown error",
821
- "mkdir",
822
- recursive ? ["-p", path] : [path]
823
- );
824
- throw error;
825
- }
826
- }
827
-
828
- async writeFile(
829
- path: string,
830
- content: string,
831
- encoding: string = "utf-8",
832
- sessionId?: string
833
- ): Promise<WriteFileResponse> {
834
- try {
835
- const targetSessionId = sessionId || this.sessionId;
836
-
837
- const response = await this.doFetch(`/api/write`, {
838
- body: JSON.stringify({
839
- content,
840
- encoding,
841
- path,
842
- sessionId: targetSessionId,
843
- }),
844
- headers: {
845
- "Content-Type": "application/json",
846
- },
847
- method: "POST",
848
- });
849
-
850
- if (!response.ok) {
851
- const errorData = (await response.json().catch(() => ({}))) as {
852
- error?: string;
853
- };
854
- throw new Error(
855
- errorData.error || `HTTP error! status: ${response.status}`
856
- );
857
- }
858
-
859
- const data: WriteFileResponse = await response.json();
860
- console.log(
861
- `[HTTP Client] File written: ${path}, Success: ${data.success}`
862
- );
863
-
864
- return data;
865
- } catch (error) {
866
- console.error("[HTTP Client] Error writing file:", error);
867
- throw error;
868
- }
869
- }
870
-
871
- async writeFileStream(
872
- path: string,
873
- content: string,
874
- encoding: string = "utf-8",
875
- sessionId?: string
876
- ): Promise<void> {
877
- try {
878
- const targetSessionId = sessionId || this.sessionId;
879
-
880
- const response = await this.doFetch(`/api/write/stream`, {
881
- body: JSON.stringify({
882
- content,
883
- encoding,
884
- path,
885
- sessionId: targetSessionId,
886
- }),
887
- headers: {
888
- "Content-Type": "application/json",
889
- },
890
- method: "POST",
891
- });
892
-
893
- if (!response.ok) {
894
- const errorData = (await response.json().catch(() => ({}))) as {
895
- error?: string;
896
- };
897
- throw new Error(
898
- errorData.error || `HTTP error! status: ${response.status}`
899
- );
900
- }
901
-
902
- if (!response.body) {
903
- throw new Error("No response body for streaming request");
904
- }
905
-
906
- const reader = response.body.getReader();
907
- const decoder = new TextDecoder();
908
-
909
- try {
910
- while (true) {
911
- const { done, value } = await reader.read();
912
-
913
- if (done) {
914
- break;
915
- }
916
-
917
- const chunk = decoder.decode(value, { stream: true });
918
- const lines = chunk.split("\n");
919
-
920
- for (const line of lines) {
921
- if (line.startsWith("data: ")) {
922
- try {
923
- const eventData = line.slice(6); // Remove 'data: ' prefix
924
- const event: StreamEvent = JSON.parse(eventData);
925
-
926
- console.log(
927
- `[HTTP Client] Write file stream event: ${event.type}`
928
- );
929
- this.options.onStreamEvent?.(event);
930
-
931
- switch (event.type) {
932
- case "command_start":
933
- console.log(
934
- `[HTTP Client] Write file started: ${event.path}`
935
- );
936
- this.options.onCommandStart?.("write", [
937
- path,
938
- content,
939
- encoding,
940
- ]);
941
- break;
942
-
943
- case "output":
944
- console.log(`[output] ${event.message}`);
945
- this.options.onOutput?.("stdout", event.message!, "write");
946
- break;
947
-
948
- case "command_complete":
949
- console.log(
950
- `[HTTP Client] Write file completed: ${event.path}, Success: ${event.success}`
951
- );
952
- this.options.onCommandComplete?.(
953
- event.success!,
954
- 0,
955
- "",
956
- "",
957
- "write",
958
- [path, content, encoding]
959
- );
960
- break;
961
-
962
- case "error":
963
- console.error(
964
- `[HTTP Client] Write file error: ${event.error}`
965
- );
966
- this.options.onError?.(event.error!, "write", [
967
- path,
968
- content,
969
- encoding,
970
- ]);
971
- break;
972
- }
973
- } catch (parseError) {
974
- console.warn(
975
- "[HTTP Client] Failed to parse write file stream event:",
976
- parseError
977
- );
978
- }
979
- }
980
- }
981
- }
982
- } finally {
983
- reader.releaseLock();
984
- }
985
- } catch (error) {
986
- console.error("[HTTP Client] Error in streaming write file:", error);
987
- this.options.onError?.(
988
- error instanceof Error ? error.message : "Unknown error",
989
- "write",
990
- [path, content, encoding]
991
- );
992
- throw error;
993
- }
994
- }
995
-
996
- async readFile(
997
- path: string,
998
- encoding: string = "utf-8",
999
- sessionId?: string
1000
- ): Promise<ReadFileResponse> {
1001
- try {
1002
- const targetSessionId = sessionId || this.sessionId;
1003
-
1004
- const response = await this.doFetch(`/api/read`, {
1005
- body: JSON.stringify({
1006
- encoding,
1007
- path,
1008
- sessionId: targetSessionId,
1009
- }),
1010
- headers: {
1011
- "Content-Type": "application/json",
1012
- },
1013
- method: "POST",
1014
- });
1015
-
1016
- if (!response.ok) {
1017
- const errorData = (await response.json().catch(() => ({}))) as {
1018
- error?: string;
1019
- };
1020
- throw new Error(
1021
- errorData.error || `HTTP error! status: ${response.status}`
1022
- );
1023
- }
1024
-
1025
- const data: ReadFileResponse = await response.json();
1026
- console.log(
1027
- `[HTTP Client] File read: ${path}, Success: ${data.success}, Content length: ${data.content.length}`
1028
- );
1029
-
1030
- return data;
1031
- } catch (error) {
1032
- console.error("[HTTP Client] Error reading file:", error);
1033
- throw error;
1034
- }
1035
- }
1036
-
1037
- async readFileStream(
1038
- path: string,
1039
- encoding: string = "utf-8",
1040
- sessionId?: string
1041
- ): Promise<void> {
1042
- try {
1043
- const targetSessionId = sessionId || this.sessionId;
1044
-
1045
- const response = await this.doFetch(`/api/read/stream`, {
1046
- body: JSON.stringify({
1047
- encoding,
1048
- path,
1049
- sessionId: targetSessionId,
1050
- }),
1051
- headers: {
1052
- "Content-Type": "application/json",
1053
- },
1054
- method: "POST",
1055
- });
1056
-
1057
- if (!response.ok) {
1058
- const errorData = (await response.json().catch(() => ({}))) as {
1059
- error?: string;
1060
- };
1061
- throw new Error(
1062
- errorData.error || `HTTP error! status: ${response.status}`
1063
- );
1064
- }
1065
-
1066
- if (!response.body) {
1067
- throw new Error("No response body for streaming request");
1068
- }
1069
-
1070
- const reader = response.body.getReader();
1071
- const decoder = new TextDecoder();
1072
-
1073
- try {
1074
- while (true) {
1075
- const { done, value } = await reader.read();
1076
-
1077
- if (done) {
1078
- break;
1079
- }
1080
-
1081
- const chunk = decoder.decode(value, { stream: true });
1082
- const lines = chunk.split("\n");
1083
-
1084
- for (const line of lines) {
1085
- if (line.startsWith("data: ")) {
1086
- try {
1087
- const eventData = line.slice(6); // Remove 'data: ' prefix
1088
- const event: StreamEvent = JSON.parse(eventData);
1089
-
1090
- console.log(
1091
- `[HTTP Client] Read file stream event: ${event.type}`
1092
- );
1093
- this.options.onStreamEvent?.(event);
1094
-
1095
- switch (event.type) {
1096
- case "command_start":
1097
- console.log(
1098
- `[HTTP Client] Read file started: ${event.path}`
1099
- );
1100
- this.options.onCommandStart?.("read", [path, encoding]);
1101
- break;
1102
-
1103
- case "command_complete":
1104
- console.log(
1105
- `[HTTP Client] Read file completed: ${
1106
- event.path
1107
- }, Success: ${event.success}, Content length: ${
1108
- event.content?.length || 0
1109
- }`
1110
- );
1111
- this.options.onCommandComplete?.(
1112
- event.success!,
1113
- 0,
1114
- event.content || "",
1115
- "",
1116
- "read",
1117
- [path, encoding]
1118
- );
1119
- break;
1120
-
1121
- case "error":
1122
- console.error(
1123
- `[HTTP Client] Read file error: ${event.error}`
1124
- );
1125
- this.options.onError?.(event.error!, "read", [
1126
- path,
1127
- encoding,
1128
- ]);
1129
- break;
1130
- }
1131
- } catch (parseError) {
1132
- console.warn(
1133
- "[HTTP Client] Failed to parse read file stream event:",
1134
- parseError
1135
- );
1136
- }
1137
- }
1138
- }
1139
- }
1140
- } finally {
1141
- reader.releaseLock();
1142
- }
1143
- } catch (error) {
1144
- console.error("[HTTP Client] Error in streaming read file:", error);
1145
- this.options.onError?.(
1146
- error instanceof Error ? error.message : "Unknown error",
1147
- "read",
1148
- [path, encoding]
1149
- );
1150
- throw error;
1151
- }
1152
- }
1153
-
1154
- async deleteFile(
1155
- path: string,
1156
- sessionId?: string
1157
- ): Promise<DeleteFileResponse> {
1158
- try {
1159
- const targetSessionId = sessionId || this.sessionId;
1160
-
1161
- const response = await this.doFetch(`/api/delete`, {
1162
- body: JSON.stringify({
1163
- path,
1164
- sessionId: targetSessionId,
1165
- }),
1166
- headers: {
1167
- "Content-Type": "application/json",
1168
- },
1169
- method: "POST",
1170
- });
1171
-
1172
- if (!response.ok) {
1173
- const errorData = (await response.json().catch(() => ({}))) as {
1174
- error?: string;
1175
- };
1176
- throw new Error(
1177
- errorData.error || `HTTP error! status: ${response.status}`
1178
- );
1179
- }
1180
-
1181
- const data: DeleteFileResponse = await response.json();
1182
- console.log(
1183
- `[HTTP Client] File deleted: ${path}, Success: ${data.success}`
1184
- );
1185
-
1186
- return data;
1187
- } catch (error) {
1188
- console.error("[HTTP Client] Error deleting file:", error);
1189
- throw error;
1190
- }
1191
- }
1192
-
1193
- async deleteFileStream(path: string, sessionId?: string): Promise<void> {
1194
- try {
1195
- const targetSessionId = sessionId || this.sessionId;
1196
-
1197
- const response = await this.doFetch(`/api/delete/stream`, {
1198
- body: JSON.stringify({
1199
- path,
1200
- sessionId: targetSessionId,
1201
- }),
1202
- headers: {
1203
- "Content-Type": "application/json",
1204
- },
1205
- method: "POST",
1206
- });
1207
-
1208
- if (!response.ok) {
1209
- const errorData = (await response.json().catch(() => ({}))) as {
1210
- error?: string;
1211
- };
1212
- throw new Error(
1213
- errorData.error || `HTTP error! status: ${response.status}`
1214
- );
1215
- }
1216
-
1217
- if (!response.body) {
1218
- throw new Error("No response body for streaming request");
1219
- }
1220
-
1221
- const reader = response.body.getReader();
1222
- const decoder = new TextDecoder();
1223
-
1224
- try {
1225
- while (true) {
1226
- const { done, value } = await reader.read();
1227
-
1228
- if (done) {
1229
- break;
1230
- }
1231
-
1232
- const chunk = decoder.decode(value, { stream: true });
1233
- const lines = chunk.split("\n");
1234
-
1235
- for (const line of lines) {
1236
- if (line.startsWith("data: ")) {
1237
- try {
1238
- const eventData = line.slice(6); // Remove 'data: ' prefix
1239
- const event: StreamEvent = JSON.parse(eventData);
1240
-
1241
- console.log(
1242
- `[HTTP Client] Delete file stream event: ${event.type}`
1243
- );
1244
- this.options.onStreamEvent?.(event);
1245
-
1246
- switch (event.type) {
1247
- case "command_start":
1248
- console.log(
1249
- `[HTTP Client] Delete file started: ${event.path}`
1250
- );
1251
- this.options.onCommandStart?.("delete", [path]);
1252
- break;
1253
-
1254
- case "command_complete":
1255
- console.log(
1256
- `[HTTP Client] Delete file completed: ${event.path}, Success: ${event.success}`
1257
- );
1258
- this.options.onCommandComplete?.(
1259
- event.success!,
1260
- 0,
1261
- "",
1262
- "",
1263
- "delete",
1264
- [path]
1265
- );
1266
- break;
1267
-
1268
- case "error":
1269
- console.error(
1270
- `[HTTP Client] Delete file error: ${event.error}`
1271
- );
1272
- this.options.onError?.(event.error!, "delete", [path]);
1273
- break;
1274
- }
1275
- } catch (parseError) {
1276
- console.warn(
1277
- "[HTTP Client] Failed to parse delete file stream event:",
1278
- parseError
1279
- );
1280
- }
1281
- }
1282
- }
1283
- }
1284
- } finally {
1285
- reader.releaseLock();
1286
- }
1287
- } catch (error) {
1288
- console.error("[HTTP Client] Error in streaming delete file:", error);
1289
- this.options.onError?.(
1290
- error instanceof Error ? error.message : "Unknown error",
1291
- "delete",
1292
- [path]
1293
- );
1294
- throw error;
1295
- }
1296
- }
1297
-
1298
- async renameFile(
1299
- oldPath: string,
1300
- newPath: string,
1301
- sessionId?: string
1302
- ): Promise<RenameFileResponse> {
1303
- try {
1304
- const targetSessionId = sessionId || this.sessionId;
1305
-
1306
- const response = await this.doFetch(`/api/rename`, {
1307
- body: JSON.stringify({
1308
- newPath,
1309
- oldPath,
1310
- sessionId: targetSessionId,
1311
- }),
1312
- headers: {
1313
- "Content-Type": "application/json",
1314
- },
1315
- method: "POST",
1316
- });
1317
-
1318
- if (!response.ok) {
1319
- const errorData = (await response.json().catch(() => ({}))) as {
1320
- error?: string;
1321
- };
1322
- throw new Error(
1323
- errorData.error || `HTTP error! status: ${response.status}`
1324
- );
1325
- }
1326
-
1327
- const data: RenameFileResponse = await response.json();
1328
- console.log(
1329
- `[HTTP Client] File renamed: ${oldPath} -> ${newPath}, Success: ${data.success}`
1330
- );
1331
-
1332
- return data;
1333
- } catch (error) {
1334
- console.error("[HTTP Client] Error renaming file:", error);
1335
- throw error;
1336
- }
1337
- }
1338
-
1339
- async renameFileStream(
1340
- oldPath: string,
1341
- newPath: string,
1342
- sessionId?: string
1343
- ): Promise<void> {
1344
- try {
1345
- const targetSessionId = sessionId || this.sessionId;
1346
-
1347
- const response = await this.doFetch(`/api/rename/stream`, {
1348
- body: JSON.stringify({
1349
- newPath,
1350
- oldPath,
1351
- sessionId: targetSessionId,
1352
- }),
1353
- headers: {
1354
- "Content-Type": "application/json",
1355
- },
1356
- method: "POST",
1357
- });
1358
-
1359
- if (!response.ok) {
1360
- const errorData = (await response.json().catch(() => ({}))) as {
1361
- error?: string;
1362
- };
1363
- throw new Error(
1364
- errorData.error || `HTTP error! status: ${response.status}`
1365
- );
1366
- }
1367
-
1368
- if (!response.body) {
1369
- throw new Error("No response body for streaming request");
1370
- }
1371
-
1372
- const reader = response.body.getReader();
1373
- const decoder = new TextDecoder();
1374
-
1375
- try {
1376
- while (true) {
1377
- const { done, value } = await reader.read();
1378
-
1379
- if (done) {
1380
- break;
1381
- }
1382
-
1383
- const chunk = decoder.decode(value, { stream: true });
1384
- const lines = chunk.split("\n");
1385
-
1386
- for (const line of lines) {
1387
- if (line.startsWith("data: ")) {
1388
- try {
1389
- const eventData = line.slice(6); // Remove 'data: ' prefix
1390
- const event: StreamEvent = JSON.parse(eventData);
1391
-
1392
- console.log(
1393
- `[HTTP Client] Rename file stream event: ${event.type}`
1394
- );
1395
- this.options.onStreamEvent?.(event);
1396
-
1397
- switch (event.type) {
1398
- case "command_start":
1399
- console.log(
1400
- `[HTTP Client] Rename file started: ${event.oldPath} -> ${event.newPath}`
1401
- );
1402
- this.options.onCommandStart?.("rename", [oldPath, newPath]);
1403
- break;
1404
-
1405
- case "command_complete":
1406
- console.log(
1407
- `[HTTP Client] Rename file completed: ${event.oldPath} -> ${event.newPath}, Success: ${event.success}`
1408
- );
1409
- this.options.onCommandComplete?.(
1410
- event.success!,
1411
- 0,
1412
- "",
1413
- "",
1414
- "rename",
1415
- [oldPath, newPath]
1416
- );
1417
- break;
1418
-
1419
- case "error":
1420
- console.error(
1421
- `[HTTP Client] Rename file error: ${event.error}`
1422
- );
1423
- this.options.onError?.(event.error!, "rename", [
1424
- oldPath,
1425
- newPath,
1426
- ]);
1427
- break;
1428
- }
1429
- } catch (parseError) {
1430
- console.warn(
1431
- "[HTTP Client] Failed to parse rename file stream event:",
1432
- parseError
1433
- );
1434
- }
1435
- }
1436
- }
1437
- }
1438
- } finally {
1439
- reader.releaseLock();
1440
- }
1441
- } catch (error) {
1442
- console.error("[HTTP Client] Error in streaming rename file:", error);
1443
- this.options.onError?.(
1444
- error instanceof Error ? error.message : "Unknown error",
1445
- "rename",
1446
- [oldPath, newPath]
1447
- );
1448
- throw error;
1449
- }
1450
- }
1451
-
1452
- async moveFile(
1453
- sourcePath: string,
1454
- destinationPath: string,
1455
- sessionId?: string
1456
- ): Promise<MoveFileResponse> {
1457
- try {
1458
- const targetSessionId = sessionId || this.sessionId;
1459
-
1460
- const response = await this.doFetch(`/api/move`, {
1461
- body: JSON.stringify({
1462
- destinationPath,
1463
- sessionId: targetSessionId,
1464
- sourcePath,
1465
- }),
1466
- headers: {
1467
- "Content-Type": "application/json",
1468
- },
1469
- method: "POST",
1470
- });
1471
-
1472
- if (!response.ok) {
1473
- const errorData = (await response.json().catch(() => ({}))) as {
1474
- error?: string;
1475
- };
1476
- throw new Error(
1477
- errorData.error || `HTTP error! status: ${response.status}`
1478
- );
1479
- }
1480
-
1481
- const data: MoveFileResponse = await response.json();
1482
- console.log(
1483
- `[HTTP Client] File moved: ${sourcePath} -> ${destinationPath}, Success: ${data.success}`
1484
- );
1485
-
1486
- return data;
1487
- } catch (error) {
1488
- console.error("[HTTP Client] Error moving file:", error);
1489
- throw error;
1490
- }
1491
- }
1492
-
1493
- async moveFileStream(
1494
- sourcePath: string,
1495
- destinationPath: string,
1496
- sessionId?: string
1497
- ): Promise<void> {
1498
- try {
1499
- const targetSessionId = sessionId || this.sessionId;
1500
-
1501
- const response = await this.doFetch(`/api/move/stream`, {
1502
- body: JSON.stringify({
1503
- destinationPath,
1504
- sessionId: targetSessionId,
1505
- sourcePath,
1506
- }),
1507
- headers: {
1508
- "Content-Type": "application/json",
1509
- },
1510
- method: "POST",
1511
- });
1512
-
1513
- if (!response.ok) {
1514
- const errorData = (await response.json().catch(() => ({}))) as {
1515
- error?: string;
1516
- };
1517
- throw new Error(
1518
- errorData.error || `HTTP error! status: ${response.status}`
1519
- );
1520
- }
1521
-
1522
- if (!response.body) {
1523
- throw new Error("No response body for streaming request");
1524
- }
1525
-
1526
- const reader = response.body.getReader();
1527
- const decoder = new TextDecoder();
1528
-
1529
- try {
1530
- while (true) {
1531
- const { done, value } = await reader.read();
1532
-
1533
- if (done) {
1534
- break;
1535
- }
1536
-
1537
- const chunk = decoder.decode(value, { stream: true });
1538
- const lines = chunk.split("\n");
1539
-
1540
- for (const line of lines) {
1541
- if (line.startsWith("data: ")) {
1542
- try {
1543
- const eventData = line.slice(6); // Remove 'data: ' prefix
1544
- const event: StreamEvent = JSON.parse(eventData);
1545
-
1546
- console.log(
1547
- `[HTTP Client] Move file stream event: ${event.type}`
1548
- );
1549
- this.options.onStreamEvent?.(event);
1550
-
1551
- switch (event.type) {
1552
- case "command_start":
1553
- console.log(
1554
- `[HTTP Client] Move file started: ${event.sourcePath} -> ${event.destinationPath}`
1555
- );
1556
- this.options.onCommandStart?.("move", [
1557
- sourcePath,
1558
- destinationPath,
1559
- ]);
1560
- break;
1561
-
1562
- case "command_complete":
1563
- console.log(
1564
- `[HTTP Client] Move file completed: ${event.sourcePath} -> ${event.destinationPath}, Success: ${event.success}`
1565
- );
1566
- this.options.onCommandComplete?.(
1567
- event.success!,
1568
- 0,
1569
- "",
1570
- "",
1571
- "move",
1572
- [sourcePath, destinationPath]
1573
- );
1574
- break;
1575
-
1576
- case "error":
1577
- console.error(
1578
- `[HTTP Client] Move file error: ${event.error}`
1579
- );
1580
- this.options.onError?.(event.error!, "move", [
1581
- sourcePath,
1582
- destinationPath,
1583
- ]);
1584
- break;
1585
- }
1586
- } catch (parseError) {
1587
- console.warn(
1588
- "[HTTP Client] Failed to parse move file stream event:",
1589
- parseError
1590
- );
1591
- }
1592
- }
1593
- }
1594
- }
1595
- } finally {
1596
- reader.releaseLock();
1597
- }
1598
- } catch (error) {
1599
- console.error("[HTTP Client] Error in streaming move file:", error);
1600
- this.options.onError?.(
1601
- error instanceof Error ? error.message : "Unknown error",
1602
- "move",
1603
- [sourcePath, destinationPath]
1604
- );
1605
- throw error;
1606
- }
1607
- }
1608
-
1609
- async ping(): Promise<string> {
1610
- try {
1611
- const response = await this.doFetch(`/api/ping`, {
1612
- headers: {
1613
- "Content-Type": "application/json",
1614
- },
1615
- method: "GET",
1616
- });
1617
-
1618
- if (!response.ok) {
1619
- throw new Error(`HTTP error! status: ${response.status}`);
1620
- }
1621
-
1622
- const data: PingResponse = await response.json();
1623
- console.log(`[HTTP Client] Ping response: ${data.message}`);
1624
- return data.timestamp;
1625
- } catch (error) {
1626
- console.error("[HTTP Client] Error pinging server:", error);
1627
- throw error;
1628
- }
1629
- }
1630
-
1631
- async getCommands(): Promise<string[]> {
1632
- try {
1633
- const response = await fetch(`${this.baseUrl}/api/commands`, {
1634
- headers: {
1635
- "Content-Type": "application/json",
1636
- },
1637
- method: "GET",
1638
- });
1639
-
1640
- if (!response.ok) {
1641
- throw new Error(`HTTP error! status: ${response.status}`);
1642
- }
1643
-
1644
- const data: CommandsResponse = await response.json();
1645
- console.log(
1646
- `[HTTP Client] Available commands: ${data.availableCommands.length}`
1647
- );
1648
- return data.availableCommands;
1649
- } catch (error) {
1650
- console.error("[HTTP Client] Error getting commands:", error);
1651
- throw error;
1652
- }
1653
- }
1654
-
1655
- getSessionId(): string | null {
1656
- return this.sessionId;
1657
- }
1658
-
1659
- setSessionId(sessionId: string): void {
1660
- this.sessionId = sessionId;
1661
- }
1662
-
1663
- clearSession(): void {
1664
- this.sessionId = null;
1665
- }
1666
- }
1667
-
1668
- // Example usage and utility functions
1669
- export function createClient(options?: HttpClientOptions): HttpClient {
1670
- return new HttpClient(options);
1671
- }
1672
-
1673
- // Convenience function for quick command execution
1674
- export async function quickExecute(
1675
- command: string,
1676
- args: string[] = [],
1677
- options?: HttpClientOptions
1678
- ): Promise<ExecuteResponse> {
1679
- const client = createClient(options);
1680
- await client.createSession();
1681
-
1682
- try {
1683
- return await client.execute(command, args);
1684
- } finally {
1685
- client.clearSession();
1686
- }
1687
- }
1688
-
1689
- // Convenience function for quick streaming command execution
1690
- export async function quickExecuteStream(
1691
- command: string,
1692
- args: string[] = [],
1693
- options?: HttpClientOptions
1694
- ): Promise<void> {
1695
- const client = createClient(options);
1696
- await client.createSession();
1697
-
1698
- try {
1699
- await client.executeStream(command, args);
1700
- } finally {
1701
- client.clearSession();
1702
- }
1703
- }
1704
-
1705
- // Convenience function for quick git checkout
1706
- export async function quickGitCheckout(
1707
- repoUrl: string,
1708
- branch: string = "main",
1709
- targetDir?: string,
1710
- options?: HttpClientOptions
1711
- ): Promise<GitCheckoutResponse> {
1712
- const client = createClient(options);
1713
- await client.createSession();
1714
-
1715
- try {
1716
- return await client.gitCheckout(repoUrl, branch, targetDir);
1717
- } finally {
1718
- client.clearSession();
1719
- }
1720
- }
1721
-
1722
- // Convenience function for quick directory creation
1723
- export async function quickMkdir(
1724
- path: string,
1725
- recursive: boolean = false,
1726
- options?: HttpClientOptions
1727
- ): Promise<MkdirResponse> {
1728
- const client = createClient(options);
1729
- await client.createSession();
1730
-
1731
- try {
1732
- return await client.mkdir(path, recursive);
1733
- } finally {
1734
- client.clearSession();
1735
- }
1736
- }
1737
-
1738
- // Convenience function for quick streaming git checkout
1739
- export async function quickGitCheckoutStream(
1740
- repoUrl: string,
1741
- branch: string = "main",
1742
- targetDir?: string,
1743
- options?: HttpClientOptions
1744
- ): Promise<void> {
1745
- const client = createClient(options);
1746
- await client.createSession();
1747
-
1748
- try {
1749
- await client.gitCheckoutStream(repoUrl, branch, targetDir);
1750
- } finally {
1751
- client.clearSession();
1752
- }
1753
- }
1754
-
1755
- // Convenience function for quick streaming directory creation
1756
- export async function quickMkdirStream(
1757
- path: string,
1758
- recursive: boolean = false,
1759
- options?: HttpClientOptions
1760
- ): Promise<void> {
1761
- const client = createClient(options);
1762
- await client.createSession();
1763
-
1764
- try {
1765
- await client.mkdirStream(path, recursive);
1766
- } finally {
1767
- client.clearSession();
1768
- }
1769
- }
1770
-
1771
- // Convenience function for quick file writing
1772
- export async function quickWriteFile(
1773
- path: string,
1774
- content: string,
1775
- encoding: string = "utf-8",
1776
- options?: HttpClientOptions
1777
- ): Promise<WriteFileResponse> {
1778
- const client = createClient(options);
1779
- await client.createSession();
1780
-
1781
- try {
1782
- return await client.writeFile(path, content, encoding);
1783
- } finally {
1784
- client.clearSession();
1785
- }
1786
- }
1787
-
1788
- // Convenience function for quick streaming file writing
1789
- export async function quickWriteFileStream(
1790
- path: string,
1791
- content: string,
1792
- encoding: string = "utf-8",
1793
- options?: HttpClientOptions
1794
- ): Promise<void> {
1795
- const client = createClient(options);
1796
- await client.createSession();
1797
-
1798
- try {
1799
- await client.writeFileStream(path, content, encoding);
1800
- } finally {
1801
- client.clearSession();
1802
- }
1803
- }
1804
-
1805
- // Convenience function for quick file reading
1806
- export async function quickReadFile(
1807
- path: string,
1808
- encoding: string = "utf-8",
1809
- options?: HttpClientOptions
1810
- ): Promise<ReadFileResponse> {
1811
- const client = createClient(options);
1812
- await client.createSession();
1813
-
1814
- try {
1815
- return await client.readFile(path, encoding);
1816
- } finally {
1817
- client.clearSession();
1818
- }
1819
- }
1820
-
1821
- // Convenience function for quick streaming file reading
1822
- export async function quickReadFileStream(
1823
- path: string,
1824
- encoding: string = "utf-8",
1825
- options?: HttpClientOptions
1826
- ): Promise<void> {
1827
- const client = createClient(options);
1828
- await client.createSession();
1829
-
1830
- try {
1831
- await client.readFileStream(path, encoding);
1832
- } finally {
1833
- client.clearSession();
1834
- }
1835
- }
1836
-
1837
- // Convenience function for quick file deletion
1838
- export async function quickDeleteFile(
1839
- path: string,
1840
- options?: HttpClientOptions
1841
- ): Promise<DeleteFileResponse> {
1842
- const client = createClient(options);
1843
- await client.createSession();
1844
-
1845
- try {
1846
- return await client.deleteFile(path);
1847
- } finally {
1848
- client.clearSession();
1849
- }
1850
- }
1851
-
1852
- // Convenience function for quick streaming file deletion
1853
- export async function quickDeleteFileStream(
1854
- path: string,
1855
- options?: HttpClientOptions
1856
- ): Promise<void> {
1857
- const client = createClient(options);
1858
- await client.createSession();
1859
-
1860
- try {
1861
- await client.deleteFileStream(path);
1862
- } finally {
1863
- client.clearSession();
1864
- }
1865
- }
1866
-
1867
- // Convenience function for quick file renaming
1868
- export async function quickRenameFile(
1869
- oldPath: string,
1870
- newPath: string,
1871
- options?: HttpClientOptions
1872
- ): Promise<RenameFileResponse> {
1873
- const client = createClient(options);
1874
- await client.createSession();
1875
-
1876
- try {
1877
- return await client.renameFile(oldPath, newPath);
1878
- } finally {
1879
- client.clearSession();
1880
- }
1881
- }
1882
-
1883
- // Convenience function for quick streaming file renaming
1884
- export async function quickRenameFileStream(
1885
- oldPath: string,
1886
- newPath: string,
1887
- options?: HttpClientOptions
1888
- ): Promise<void> {
1889
- const client = createClient(options);
1890
- await client.createSession();
1891
-
1892
- try {
1893
- await client.renameFileStream(oldPath, newPath);
1894
- } finally {
1895
- client.clearSession();
1896
- }
1897
- }
1898
-
1899
- // Convenience function for quick file moving
1900
- export async function quickMoveFile(
1901
- sourcePath: string,
1902
- destinationPath: string,
1903
- options?: HttpClientOptions
1904
- ): Promise<MoveFileResponse> {
1905
- const client = createClient(options);
1906
- await client.createSession();
1907
-
1908
- try {
1909
- return await client.moveFile(sourcePath, destinationPath);
1910
- } finally {
1911
- client.clearSession();
1912
- }
1913
- }
1914
-
1915
- // Convenience function for quick streaming file moving
1916
- export async function quickMoveFileStream(
1917
- sourcePath: string,
1918
- destinationPath: string,
1919
- options?: HttpClientOptions
1920
- ): Promise<void> {
1921
- const client = createClient(options);
1922
- await client.createSession();
1923
-
1924
- try {
1925
- await client.moveFileStream(sourcePath, destinationPath);
1926
- } finally {
1927
- client.clearSession();
1928
- }
1929
- }