timeout.js 848 B

123456789101112131415161718192021
  1. import {setTimeout} from 'node:timers/promises';
  2. import {DiscardedError} from '../return/final-error.js';
  3. // Validate `timeout` option
  4. export const validateTimeout = ({timeout}) => {
  5. if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
  6. throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
  7. }
  8. };
  9. // Fails when the `timeout` option is exceeded
  10. export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined
  11. ? []
  12. : [killAfterTimeout(subprocess, timeout, context, controller)];
  13. const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {
  14. await setTimeout(timeout, undefined, {signal});
  15. context.terminationReason ??= 'timeout';
  16. subprocess.kill();
  17. throw new DiscardedError();
  18. };