1. /**
  2. * Boots traps scripts from file contents with a timeout.
  3. * @param {string[]} scriptPaths - An array of file paths to scripts.
  4. * @param {number} timeoutMs - The timeout in milliseconds for each script.
  5. * @returns {Promise<object>} - A promise resolving to an object containing the results of each script execution.
  6. * The object's keys are the script paths and the values are either the script's output or an error object.
  7. */
  8. async function bootstrapScriptsWithTimeout(scriptPaths, timeoutMs) {
  9. const results = {};
  10. for (const scriptPath of scriptPaths) {
  11. try {
  12. const scriptContent = await fetch(scriptPath).then(response => response.text()); // Fetch script content
  13. const timeoutPromise = new Promise((_, reject) => {
  14. setTimeout(() => {
  15. reject(new Error(`Script ${scriptPath} timed out after ${timeoutMs}ms`));
  16. }, timeoutMs);
  17. });
  18. const scriptResult = await Promise.race([
  19. timeoutPromise,
  20. new Promise(resolve => {
  21. try {
  22. // Execute the script content. Consider using eval() with caution.
  23. const func = new Function(scriptContent);
  24. resolve(func());
  25. } catch (error) {
  26. reject(error); // Reject if execution fails.
  27. }
  28. })
  29. ]);
  30. results[scriptPath] = scriptResult;
  31. } catch (error) {
  32. results[scriptPath] = { error: error.message }; // Store error message
  33. }
  34. }
  35. return results;
  36. }

Add your comment