( packages: string[], language: "python" | "javascript" | "typescript" = "python" )
| 232 | * @returns The execution result |
| 233 | */ |
| 234 | export async function installPackages( |
| 235 | packages: string[], |
| 236 | language: "python" | "javascript" | "typescript" = "python" |
| 237 | ): Promise<ExecutionResult> { |
| 238 | const sandbox = await createSandbox(); |
| 239 | |
| 240 | try { |
| 241 | let installCommand: string; |
| 242 | |
| 243 | if (language === "python") { |
| 244 | installCommand = `!pip install ${packages.join(" ")}`; |
| 245 | } else if (language === "javascript" || language === "typescript") { |
| 246 | installCommand = `const { execSync } = require('child_process'); |
| 247 | try { |
| 248 | console.log('Installing packages: ${packages.join(", ")}'); |
| 249 | execSync('npm install ${packages.join(" ")}', { stdio: 'inherit' }); |
| 250 | console.log('Packages installed successfully'); |
| 251 | } catch (error) { |
| 252 | console.error('Failed to install packages:', error.message); |
| 253 | }`; |
| 254 | } else { |
| 255 | throw new Error(`Unsupported language: ${language}`); |
| 256 | } |
| 257 | |
| 258 | const execution = await sandbox.notebook.execCell(installCommand, { |
| 259 | onStdout: (msg: string) => console.log("[stdout]", msg), |
| 260 | onStderr: (msg: string) => console.error("[stderr]", msg) |
| 261 | }); |
| 262 | |
| 263 | // Format the result to match our ExecutionResult interface |
| 264 | const result: ExecutionResult = { |
| 265 | text: execution.text || "", |
| 266 | results: execution.results || [], |
| 267 | error: execution.error ? { |
| 268 | type: "error", |
| 269 | value: typeof execution.error === 'string' ? execution.error : |
| 270 | JSON.stringify(execution.error) |
| 271 | } : null, |
| 272 | logs: { |
| 273 | stdout: Array.isArray(execution.logs?.stdout) ? execution.logs.stdout : |
| 274 | (execution.logs?.stdout ? [execution.logs.stdout] : []), |
| 275 | stderr: Array.isArray(execution.logs?.stderr) ? execution.logs.stderr : |
| 276 | (execution.logs?.stderr ? [execution.logs.stderr] : []) |
| 277 | } |
| 278 | }; |
| 279 | |
| 280 | const isError = result.error !== null && result.error !== undefined; |
| 281 | await logMessage( |
| 282 | isError ? "error" : "info", |
| 283 | `Package installation ${isError ? "failed" : "completed"}`, |
| 284 | { |
| 285 | packages, |
| 286 | language, |
| 287 | error: isError && result.error ? result.error.value : undefined |
| 288 | } |
| 289 | ); |
| 290 | |
| 291 | return result; |
no test coverage detected