config-loader.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import * as fs from "fs";
  2. import {
  3. SandboxRuntimeConfigSchema,
  4. type SandboxRuntimeConfig,
  5. } from "../sandbox/sandbox-config.js";
  6. /**
  7. * Parse and validate sandbox configuration from a string
  8. * Used for parsing config from control fd (JSON lines protocol)
  9. */
  10. export function loadConfigFromString(
  11. content: string,
  12. ): SandboxRuntimeConfig | null {
  13. if (!content.trim()) {
  14. return null;
  15. }
  16. try {
  17. const parsed = JSON.parse(content);
  18. const result = SandboxRuntimeConfigSchema.safeParse(parsed);
  19. if (!result.success) {
  20. return null;
  21. }
  22. return result.data;
  23. } catch {
  24. return null;
  25. }
  26. }
  27. /**
  28. * Load and validate sandbox configuration from a file
  29. */
  30. export function loadConfig(filePath: string): SandboxRuntimeConfig | null {
  31. try {
  32. if (!fs.existsSync(filePath)) {
  33. return null;
  34. }
  35. const content = fs.readFileSync(filePath, "utf-8");
  36. if (content.trim() === "") {
  37. return null;
  38. }
  39. // Parse JSON
  40. const parsed = JSON.parse(content);
  41. // Validate with zod schema
  42. const result = SandboxRuntimeConfigSchema.safeParse(parsed);
  43. if (!result.success) {
  44. console.error(`Invalid configuration in ${filePath}:`);
  45. result.error.issues.forEach((issue) => {
  46. const path = issue.path.join(".");
  47. console.error(` - ${path}: ${issue.message}`);
  48. });
  49. return null;
  50. }
  51. return result.data;
  52. } catch (error) {
  53. // Log parse errors to help users debug invalid config files
  54. if (error instanceof SyntaxError) {
  55. console.error(
  56. `Invalid JSON in config file ${filePath}: ${error.message}`,
  57. );
  58. } else {
  59. console.error(`Failed to load config from ${filePath}: ${error}`);
  60. }
  61. return null;
  62. }
  63. }