@cloudflare/sandbox 0.0.0-cbb7fcd → 0.0.0-cecde0a

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.
@@ -0,0 +1,337 @@
1
+ import { type SpawnOptions, spawn } from "node:child_process";
2
+ import type { ExecuteRequest, SessionData } from "../types";
3
+
4
+ function executeCommand(
5
+ sessions: Map<string, SessionData>,
6
+ command: string,
7
+ sessionId?: string,
8
+ background?: boolean
9
+ ): Promise<{
10
+ success: boolean;
11
+ stdout: string;
12
+ stderr: string;
13
+ exitCode: number;
14
+ }> {
15
+ return new Promise((resolve, reject) => {
16
+ const spawnOptions: SpawnOptions = {
17
+ shell: true,
18
+ stdio: ["pipe", "pipe", "pipe"] as const,
19
+ detached: background || false,
20
+ };
21
+
22
+ const child = spawn(command, spawnOptions);
23
+
24
+ // Store the process reference for cleanup if sessionId is provided
25
+ if (sessionId && sessions.has(sessionId)) {
26
+ const session = sessions.get(sessionId)!;
27
+ session.activeProcess = child;
28
+ }
29
+
30
+ let stdout = "";
31
+ let stderr = "";
32
+
33
+ child.stdout?.on("data", (data) => {
34
+ stdout += data.toString();
35
+ });
36
+
37
+ child.stderr?.on("data", (data) => {
38
+ stderr += data.toString();
39
+ });
40
+
41
+ if (background) {
42
+ // For background processes, unref and return quickly
43
+ child.unref();
44
+
45
+ // Collect initial output for 100ms then return
46
+ setTimeout(() => {
47
+ resolve({
48
+ exitCode: 0, // Process is still running
49
+ stderr,
50
+ stdout,
51
+ success: true,
52
+ });
53
+ }, 100);
54
+
55
+ // Still handle errors
56
+ child.on("error", (error) => {
57
+ console.error(`[Server] Background process error: ${command}`, error);
58
+ // Don't reject since we might have already resolved
59
+ });
60
+ } else {
61
+ // Normal synchronous execution
62
+ child.on("close", (code) => {
63
+ // Clear the active process reference
64
+ if (sessionId && sessions.has(sessionId)) {
65
+ const session = sessions.get(sessionId)!;
66
+ session.activeProcess = null;
67
+ }
68
+
69
+ console.log(`[Server] Command completed: ${command}, Exit code: ${code}`);
70
+
71
+ resolve({
72
+ exitCode: code || 0,
73
+ stderr,
74
+ stdout,
75
+ success: code === 0,
76
+ });
77
+ });
78
+
79
+ child.on("error", (error) => {
80
+ // Clear the active process reference
81
+ if (sessionId && sessions.has(sessionId)) {
82
+ const session = sessions.get(sessionId)!;
83
+ session.activeProcess = null;
84
+ }
85
+
86
+ reject(error);
87
+ });
88
+ }
89
+ });
90
+ }
91
+
92
+ export async function handleExecuteRequest(
93
+ sessions: Map<string, SessionData>,
94
+ req: Request,
95
+ corsHeaders: Record<string, string>
96
+ ): Promise<Response> {
97
+ try {
98
+ const body = (await req.json()) as ExecuteRequest;
99
+ const { command, sessionId, background } = body;
100
+
101
+ if (!command || typeof command !== "string") {
102
+ return new Response(
103
+ JSON.stringify({
104
+ error: "Command is required and must be a string",
105
+ }),
106
+ {
107
+ headers: {
108
+ "Content-Type": "application/json",
109
+ ...corsHeaders,
110
+ },
111
+ status: 400,
112
+ }
113
+ );
114
+ }
115
+
116
+ console.log(`[Server] Executing command: ${command}`);
117
+
118
+ const result = await executeCommand(sessions, command, sessionId, background);
119
+
120
+ return new Response(
121
+ JSON.stringify({
122
+ command,
123
+ exitCode: result.exitCode,
124
+ stderr: result.stderr,
125
+ stdout: result.stdout,
126
+ success: result.success,
127
+ timestamp: new Date().toISOString(),
128
+ }),
129
+ {
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ ...corsHeaders,
133
+ },
134
+ }
135
+ );
136
+ } catch (error) {
137
+ console.error("[Server] Error in handleExecuteRequest:", error);
138
+ return new Response(
139
+ JSON.stringify({
140
+ error: "Failed to execute command",
141
+ message: error instanceof Error ? error.message : "Unknown error",
142
+ }),
143
+ {
144
+ headers: {
145
+ "Content-Type": "application/json",
146
+ ...corsHeaders,
147
+ },
148
+ status: 500,
149
+ }
150
+ );
151
+ }
152
+ }
153
+
154
+ export async function handleStreamingExecuteRequest(
155
+ sessions: Map<string, SessionData>,
156
+ req: Request,
157
+ corsHeaders: Record<string, string>
158
+ ): Promise<Response> {
159
+ try {
160
+ const body = (await req.json()) as ExecuteRequest;
161
+ const { command, sessionId, background } = body;
162
+
163
+ if (!command || typeof command !== "string") {
164
+ return new Response(
165
+ JSON.stringify({
166
+ error: "Command is required and must be a string",
167
+ }),
168
+ {
169
+ headers: {
170
+ "Content-Type": "application/json",
171
+ ...corsHeaders,
172
+ },
173
+ status: 400,
174
+ }
175
+ );
176
+ }
177
+
178
+ console.log(
179
+ `[Server] Executing streaming command: ${command}`
180
+ );
181
+
182
+ const stream = new ReadableStream({
183
+ start(controller) {
184
+ const spawnOptions: SpawnOptions = {
185
+ shell: true,
186
+ stdio: ["pipe", "pipe", "pipe"] as const,
187
+ detached: background || false,
188
+ };
189
+
190
+ const child = spawn(command, spawnOptions);
191
+
192
+ // Store the process reference for cleanup if sessionId is provided
193
+ if (sessionId && sessions.has(sessionId)) {
194
+ const session = sessions.get(sessionId)!;
195
+ session.activeProcess = child;
196
+ }
197
+
198
+ // For background processes, unref to prevent blocking
199
+ if (background) {
200
+ child.unref();
201
+ }
202
+
203
+ let stdout = "";
204
+ let stderr = "";
205
+
206
+ // Send command start event
207
+ controller.enqueue(
208
+ new TextEncoder().encode(
209
+ `data: ${JSON.stringify({
210
+ type: "start",
211
+ timestamp: new Date().toISOString(),
212
+ command,
213
+ background: background || false,
214
+ })}\n\n`
215
+ )
216
+ );
217
+
218
+ child.stdout?.on("data", (data) => {
219
+ const output = data.toString();
220
+ stdout += output;
221
+
222
+ // Send real-time output
223
+ controller.enqueue(
224
+ new TextEncoder().encode(
225
+ `data: ${JSON.stringify({
226
+ type: "stdout",
227
+ timestamp: new Date().toISOString(),
228
+ data: output,
229
+ command,
230
+ })}\n\n`
231
+ )
232
+ );
233
+ });
234
+
235
+ child.stderr?.on("data", (data) => {
236
+ const output = data.toString();
237
+ stderr += output;
238
+
239
+ // Send real-time error output
240
+ controller.enqueue(
241
+ new TextEncoder().encode(
242
+ `data: ${JSON.stringify({
243
+ type: "stderr",
244
+ timestamp: new Date().toISOString(),
245
+ data: output,
246
+ command,
247
+ })}\n\n`
248
+ )
249
+ );
250
+ });
251
+
252
+ child.on("close", (code) => {
253
+ // Clear the active process reference
254
+ if (sessionId && sessions.has(sessionId)) {
255
+ const session = sessions.get(sessionId)!;
256
+ session.activeProcess = null;
257
+ }
258
+
259
+ console.log(
260
+ `[Server] Command completed: ${command}, Exit code: ${code}`
261
+ );
262
+
263
+ // Send command completion event
264
+ controller.enqueue(
265
+ new TextEncoder().encode(
266
+ `data: ${JSON.stringify({
267
+ type: "complete",
268
+ timestamp: new Date().toISOString(),
269
+ command,
270
+ exitCode: code,
271
+ result: {
272
+ success: code === 0,
273
+ exitCode: code,
274
+ stdout,
275
+ stderr,
276
+ command,
277
+ timestamp: new Date().toISOString(),
278
+ },
279
+ })}\n\n`
280
+ )
281
+ );
282
+
283
+ // For non-background processes, close the stream
284
+ // For background processes with streaming, the stream stays open
285
+ if (!background) {
286
+ controller.close();
287
+ }
288
+ });
289
+
290
+ child.on("error", (error) => {
291
+ // Clear the active process reference
292
+ if (sessionId && sessions.has(sessionId)) {
293
+ const session = sessions.get(sessionId)!;
294
+ session.activeProcess = null;
295
+ }
296
+
297
+ controller.enqueue(
298
+ new TextEncoder().encode(
299
+ `data: ${JSON.stringify({
300
+ type: "error",
301
+ timestamp: new Date().toISOString(),
302
+ error: error.message,
303
+ command,
304
+ })}\n\n`
305
+ )
306
+ );
307
+
308
+ controller.close();
309
+ });
310
+ },
311
+ });
312
+
313
+ return new Response(stream, {
314
+ headers: {
315
+ "Cache-Control": "no-cache",
316
+ Connection: "keep-alive",
317
+ "Content-Type": "text/event-stream",
318
+ ...corsHeaders,
319
+ },
320
+ });
321
+ } catch (error) {
322
+ console.error("[Server] Error in handleStreamingExecuteRequest:", error);
323
+ return new Response(
324
+ JSON.stringify({
325
+ error: "Failed to execute streaming command",
326
+ message: error instanceof Error ? error.message : "Unknown error",
327
+ }),
328
+ {
329
+ headers: {
330
+ "Content-Type": "application/json",
331
+ ...corsHeaders,
332
+ },
333
+ status: 500,
334
+ }
335
+ );
336
+ }
337
+ }