All files / src/cli signals.ts

89.47% Statements 17/19
83.33% Branches 10/12
50% Functions 2/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 391x                           3x 3x 3x 3x 3x   3x 5x 5x 1x     4x   4x 1x 1x     3x 3x 3x      
const DEFAULT_DUPLICATE_SIGINT_WINDOW_MS = 750;
 
interface SigintHandlerOptions {
  abortController: AbortController;
  interrupted: { value: boolean };
  now?: () => number;
  exit?: (code: number) => void;
  duplicateWindowMs?: number;
}
 
/**
 * Create the CLI SIGINT handler.
 */
export function createSigintHandler(options: SigintHandlerOptions): () => void {
  const duplicateWindowMs = options.duplicateWindowMs ?? DEFAULT_DUPLICATE_SIGINT_WINDOW_MS;
  const now = options.now ?? (() => Date.now());
  const exit = options.exit ?? ((code) => process.exit(code));
  let gracefulInterruptSeen = false;
  let lastSigintAt = 0;
 
  return () => {
    const sigintAt = now();
    if (gracefulInterruptSeen && sigintAt - lastSigintAt < duplicateWindowMs) {
      return;
    }
 
    lastSigintAt = sigintAt;
 
    if (gracefulInterruptSeen) {
      exit(130);
      return;
    }
 
    gracefulInterruptSeen = true;
    options.abortController.abort();
    options.interrupted.value = true;
  };
}