@cloudflare/sandbox 0.0.0-d55b0f4 → 0.0.0-d670ba2

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.
package/src/errors.ts ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Standard error response from the sandbox API
3
+ */
4
+ export interface SandboxErrorResponse {
5
+ error?: string;
6
+ status?: string;
7
+ progress?: number;
8
+ }
9
+
10
+ /**
11
+ * Base error class for all Sandbox-related errors
12
+ */
13
+ export class SandboxError extends Error {
14
+ constructor(message: string) {
15
+ super(message);
16
+ this.name = this.constructor.name;
17
+
18
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
19
+ if (Error.captureStackTrace) {
20
+ Error.captureStackTrace(this, this.constructor);
21
+ }
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Error thrown when interpreter functionality is requested but the service is still initializing.
27
+ *
28
+ * Note: With the current implementation, requests wait for interpreter to be ready.
29
+ * This error is only thrown when:
30
+ * 1. The request times out waiting for interpreter (default: 30 seconds)
31
+ * 2. interpreter initialization actually fails
32
+ *
33
+ * Most requests will succeed after a delay, not throw this error.
34
+ */
35
+ export class InterpreterNotReadyError extends SandboxError {
36
+ public readonly code = "INTERPRETER_NOT_READY";
37
+ public readonly retryAfter: number;
38
+ public readonly progress?: number;
39
+
40
+ constructor(
41
+ message?: string,
42
+ options?: { retryAfter?: number; progress?: number }
43
+ ) {
44
+ super(
45
+ message ||
46
+ "Interpreter is still initializing. Please retry in a few seconds."
47
+ );
48
+ this.retryAfter = options?.retryAfter || 5;
49
+ this.progress = options?.progress;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Error thrown when a context is not found
55
+ */
56
+ export class ContextNotFoundError extends SandboxError {
57
+ public readonly code = "CONTEXT_NOT_FOUND";
58
+ public readonly contextId: string;
59
+
60
+ constructor(contextId: string) {
61
+ super(`Context ${contextId} not found`);
62
+ this.contextId = contextId;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Error thrown when code execution fails
68
+ */
69
+ export class CodeExecutionError extends SandboxError {
70
+ public readonly code = "CODE_EXECUTION_ERROR";
71
+ public readonly executionError?: {
72
+ ename?: string;
73
+ evalue?: string;
74
+ traceback?: string[];
75
+ };
76
+
77
+ constructor(message: string, executionError?: any) {
78
+ super(message);
79
+ this.executionError = executionError;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Error thrown when the sandbox container is not ready
85
+ */
86
+ export class ContainerNotReadyError extends SandboxError {
87
+ public readonly code = "CONTAINER_NOT_READY";
88
+
89
+ constructor(message?: string) {
90
+ super(
91
+ message ||
92
+ "Container is not ready. Please wait for initialization to complete."
93
+ );
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Error thrown when a network request to the sandbox fails
99
+ */
100
+ export class SandboxNetworkError extends SandboxError {
101
+ public readonly code = "NETWORK_ERROR";
102
+ public readonly statusCode?: number;
103
+ public readonly statusText?: string;
104
+
105
+ constructor(message: string, statusCode?: number, statusText?: string) {
106
+ super(message);
107
+ this.statusCode = statusCode;
108
+ this.statusText = statusText;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Error thrown when service is temporarily unavailable (e.g., circuit breaker open)
114
+ */
115
+ export class ServiceUnavailableError extends SandboxError {
116
+ public readonly code = "SERVICE_UNAVAILABLE";
117
+ public readonly retryAfter?: number;
118
+
119
+ constructor(message?: string, retryAfter?: number) {
120
+ // Simple, user-friendly message without implementation details
121
+ super(message || "Service temporarily unavailable");
122
+ this.retryAfter = retryAfter;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Type guard to check if an error is a InterpreterNotReadyError
128
+ */
129
+ export function isInterpreterNotReadyError(
130
+ error: unknown
131
+ ): error is InterpreterNotReadyError {
132
+ return error instanceof InterpreterNotReadyError;
133
+ }
134
+
135
+ /**
136
+ * Type guard to check if an error is any SandboxError
137
+ */
138
+ export function isSandboxError(error: unknown): error is SandboxError {
139
+ return error instanceof SandboxError;
140
+ }
141
+
142
+ /**
143
+ * Helper to determine if an error is retryable
144
+ */
145
+ export function isRetryableError(error: unknown): boolean {
146
+ if (
147
+ error instanceof InterpreterNotReadyError ||
148
+ error instanceof ContainerNotReadyError ||
149
+ error instanceof ServiceUnavailableError
150
+ ) {
151
+ return true;
152
+ }
153
+
154
+ if (error instanceof SandboxNetworkError) {
155
+ // Retry on 502, 503, 504 (gateway/service unavailable errors)
156
+ return error.statusCode
157
+ ? [502, 503, 504].includes(error.statusCode)
158
+ : false;
159
+ }
160
+
161
+ return false;
162
+ }
163
+
164
+ /**
165
+ * Parse error response from the sandbox API and return appropriate error instance
166
+ */
167
+ export async function parseErrorResponse(
168
+ response: Response
169
+ ): Promise<SandboxError> {
170
+ let data: SandboxErrorResponse;
171
+
172
+ try {
173
+ data = (await response.json()) as SandboxErrorResponse;
174
+ } catch {
175
+ // If JSON parsing fails, return a generic network error
176
+ return new SandboxNetworkError(
177
+ `Request failed with status ${response.status}`,
178
+ response.status,
179
+ response.statusText
180
+ );
181
+ }
182
+
183
+ // Check for specific error types based on response
184
+ if (response.status === 503) {
185
+ // Circuit breaker error
186
+ if (data.status === "circuit_open") {
187
+ return new ServiceUnavailableError(
188
+ "Service temporarily unavailable",
189
+ parseInt(response.headers.get("Retry-After") || "30")
190
+ );
191
+ }
192
+
193
+ // Interpreter initialization error
194
+ if (data.status === "initializing") {
195
+ return new InterpreterNotReadyError(data.error, {
196
+ retryAfter: parseInt(response.headers.get("Retry-After") || "5"),
197
+ progress: data.progress,
198
+ });
199
+ }
200
+ }
201
+
202
+ // Check for context not found
203
+ if (
204
+ response.status === 404 &&
205
+ data.error?.includes("Context") &&
206
+ data.error?.includes("not found")
207
+ ) {
208
+ const contextId =
209
+ data.error.match(/Context (\S+) not found/)?.[1] || "unknown";
210
+ return new ContextNotFoundError(contextId);
211
+ }
212
+
213
+ // Default network error
214
+ return new SandboxNetworkError(
215
+ data.error || `Request failed with status ${response.status}`,
216
+ response.status,
217
+ response.statusText
218
+ );
219
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * File streaming utilities for reading binary and text files
3
+ * Provides simple AsyncIterable API over SSE stream with automatic base64 decoding
4
+ */
5
+
6
+ import { parseSSEStream } from './sse-parser';
7
+ import type { FileChunk, FileMetadata, FileStreamEvent } from './types';
8
+
9
+ /**
10
+ * Convert ReadableStream of SSE file events to AsyncIterable of file chunks
11
+ * Automatically decodes base64 for binary files and provides metadata
12
+ *
13
+ * @param stream - The SSE ReadableStream from readFileStream()
14
+ * @param signal - Optional AbortSignal for cancellation
15
+ * @returns AsyncIterable that yields file chunks (string for text, Uint8Array for binary)
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const stream = await sandbox.readFileStream('/path/to/file.png');
20
+ *
21
+ * for await (const chunk of streamFile(stream)) {
22
+ * if (chunk instanceof Uint8Array) {
23
+ * // Binary chunk - already decoded from base64
24
+ * console.log('Binary chunk:', chunk.byteLength, 'bytes');
25
+ * } else {
26
+ * // Text chunk
27
+ * console.log('Text chunk:', chunk);
28
+ * }
29
+ * }
30
+ *
31
+ * // Access metadata
32
+ * const iter = streamFile(stream);
33
+ * for await (const chunk of iter) {
34
+ * console.log('MIME type:', iter.metadata?.mimeType);
35
+ * // process chunk...
36
+ * }
37
+ * ```
38
+ */
39
+ export async function* streamFile(
40
+ stream: ReadableStream<Uint8Array>,
41
+ signal?: AbortSignal
42
+ ): AsyncGenerator<FileChunk, void, undefined> {
43
+ let metadata: FileMetadata | undefined;
44
+
45
+ try {
46
+ for await (const event of parseSSEStream<FileStreamEvent>(stream, signal)) {
47
+ switch (event.type) {
48
+ case 'metadata':
49
+ // Store metadata for access via iterator
50
+ metadata = {
51
+ mimeType: event.mimeType,
52
+ size: event.size,
53
+ isBinary: event.isBinary,
54
+ encoding: event.encoding,
55
+ };
56
+ // Store on generator function for external access
57
+ (streamFile as any).metadata = metadata;
58
+ break;
59
+
60
+ case 'chunk':
61
+ // Auto-decode base64 for binary files
62
+ if (metadata?.isBinary && metadata?.encoding === 'base64') {
63
+ // Decode base64 to Uint8Array
64
+ const binaryString = atob(event.data);
65
+ const bytes = new Uint8Array(binaryString.length);
66
+ for (let i = 0; i < binaryString.length; i++) {
67
+ bytes[i] = binaryString.charCodeAt(i);
68
+ }
69
+ yield bytes;
70
+ } else {
71
+ // Text file - yield as-is
72
+ yield event.data;
73
+ }
74
+ break;
75
+
76
+ case 'complete':
77
+ // Stream completed successfully
78
+ console.log(`[streamFile] File streaming complete: ${event.bytesRead} bytes read`);
79
+ return;
80
+
81
+ case 'error':
82
+ // Stream error
83
+ throw new Error(`File streaming error: ${event.error}`);
84
+ }
85
+ }
86
+ } catch (error) {
87
+ console.error('[streamFile] Error streaming file:', error);
88
+ throw error;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Helper to collect entire file from stream into memory
94
+ * Useful for smaller files where you want the complete content at once
95
+ *
96
+ * @param stream - The SSE ReadableStream from readFileStream()
97
+ * @param signal - Optional AbortSignal for cancellation
98
+ * @returns Object with content (string or Uint8Array) and metadata
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const stream = await sandbox.readFileStream('/path/to/image.png');
103
+ * const { content, metadata } = await collectFile(stream);
104
+ *
105
+ * if (content instanceof Uint8Array) {
106
+ * console.log('Binary file:', metadata.mimeType, content.byteLength, 'bytes');
107
+ * } else {
108
+ * console.log('Text file:', metadata.mimeType, content.length, 'chars');
109
+ * }
110
+ * ```
111
+ */
112
+ export async function collectFile(
113
+ stream: ReadableStream<Uint8Array>,
114
+ signal?: AbortSignal
115
+ ): Promise<{ content: string | Uint8Array; metadata: FileMetadata }> {
116
+ let metadata: FileMetadata | undefined;
117
+ const chunks: FileChunk[] = [];
118
+
119
+ for await (const chunk of streamFile(stream, signal)) {
120
+ chunks.push(chunk);
121
+ // Capture metadata from first iteration
122
+ if (!metadata && (streamFile as any).metadata) {
123
+ metadata = (streamFile as any).metadata;
124
+ }
125
+ }
126
+
127
+ if (!metadata) {
128
+ throw new Error('No metadata received from file stream');
129
+ }
130
+
131
+ // Combine chunks based on type
132
+ if (chunks.length === 0) {
133
+ // Empty file
134
+ return {
135
+ content: metadata.isBinary ? new Uint8Array(0) : '',
136
+ metadata,
137
+ };
138
+ }
139
+
140
+ // Check if binary or text based on first chunk
141
+ if (chunks[0] instanceof Uint8Array) {
142
+ // Binary file - concatenate Uint8Arrays
143
+ const totalLength = chunks.reduce((sum, chunk) => {
144
+ return sum + (chunk as Uint8Array).byteLength;
145
+ }, 0);
146
+
147
+ const result = new Uint8Array(totalLength);
148
+ let offset = 0;
149
+ for (const chunk of chunks) {
150
+ result.set(chunk as Uint8Array, offset);
151
+ offset += (chunk as Uint8Array).byteLength;
152
+ }
153
+
154
+ return { content: result, metadata };
155
+ } else {
156
+ // Text file - concatenate strings
157
+ return {
158
+ content: chunks.join(''),
159
+ metadata,
160
+ };
161
+ }
162
+ }
package/src/index.ts CHANGED
@@ -1,20 +1,81 @@
1
- // Export types from client
2
- export type {
3
- DeleteFileResponse, ExecuteResponse,
4
- GitCheckoutResponse,
5
- MkdirResponse, MoveFileResponse,
6
- ReadFileResponse, RenameFileResponse, WriteFileResponse
7
- } from "./client";
1
+ // biome-ignore-start assist/source/organizeImports: Need separate exports for deprecation warnings to work properly
2
+ /**
3
+ * @deprecated Use `InterpreterNotReadyError` instead. Will be removed in a future version.
4
+ */
5
+ export { InterpreterNotReadyError as JupyterNotReadyError } from "./errors";
8
6
 
9
- // Re-export request handler utilities
7
+ /**
8
+ * @deprecated Use `isInterpreterNotReadyError` instead. Will be removed in a future version.
9
+ */
10
+ export { isInterpreterNotReadyError as isJupyterNotReadyError } from "./errors";
11
+ // biome-ignore-end assist/source/organizeImports: Need separate exports for deprecation warnings to work properly
12
+
13
+ // Export API response types
10
14
  export {
11
- proxyToSandbox, type RouteInfo, type SandboxEnv
12
- } from './request-handler';
15
+ CodeExecutionError,
16
+ ContainerNotReadyError,
17
+ ContextNotFoundError,
18
+ InterpreterNotReadyError,
19
+ isInterpreterNotReadyError,
20
+ isRetryableError,
21
+ isSandboxError,
22
+ parseErrorResponse,
23
+ SandboxError,
24
+ type SandboxErrorResponse,
25
+ SandboxNetworkError,
26
+ ServiceUnavailableError,
27
+ } from "./errors";
13
28
 
29
+ // Export code interpreter types
30
+ export type {
31
+ ChartData,
32
+ CodeContext,
33
+ CreateContextOptions,
34
+ Execution,
35
+ ExecutionError,
36
+ OutputMessage,
37
+ Result,
38
+ RunCodeOptions,
39
+ } from "./interpreter-types";
40
+ // Export the implementations
41
+ export { ResultImpl } from "./interpreter-types";
42
+ // Re-export request handler utilities
43
+ export {
44
+ proxyToSandbox,
45
+ type RouteInfo,
46
+ type SandboxEnv,
47
+ } from "./request-handler";
14
48
  export { getSandbox, Sandbox } from "./sandbox";
15
-
16
49
  // Export SSE parser for converting ReadableStream to AsyncIterable
17
- export { asyncIterableToSSEStream, parseSSEStream, responseToAsyncIterable } from "./sse-parser";
18
-
19
- // Export event types for streaming
20
- export type { ExecEvent, LogEvent } from "./types";
50
+ export {
51
+ asyncIterableToSSEStream,
52
+ parseSSEStream,
53
+ responseToAsyncIterable,
54
+ } from "./sse-parser";
55
+ // Export file streaming utilities
56
+ export { streamFile, collectFile } from "./file-stream";
57
+ export type {
58
+ DeleteFileResponse,
59
+ ExecEvent,
60
+ ExecOptions,
61
+ ExecResult,
62
+ ExecuteResponse,
63
+ ExecutionSession,
64
+ FileChunk,
65
+ FileMetadata,
66
+ FileStream,
67
+ FileStreamEvent,
68
+ GitCheckoutResponse,
69
+ ISandbox,
70
+ ListFilesResponse,
71
+ LogEvent,
72
+ MkdirResponse,
73
+ MoveFileResponse,
74
+ Process,
75
+ ProcessOptions,
76
+ ProcessStatus,
77
+ ReadFileResponse,
78
+ RenameFileResponse,
79
+ StreamOptions,
80
+ WriteFileResponse,
81
+ } from "./types";