Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/commands/emails/receiving/listen.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Command } from '@commander-js/extra-typings';
import pc from 'picocolors';
import type { ListReceivingEmail } from 'resend';
import { getCancelExitCode, setSigintHandler } from '../../../lib/cli-exit';
import type { GlobalOpts } from '../../../lib/client';
import { requireClient } from '../../../lib/client';
import { buildHelpText } from '../../../lib/help-text';
Expand Down Expand Up @@ -204,10 +205,10 @@ Ctrl+C exits cleanly.`,
if (!jsonMode) {
process.stderr.write('\nStopped listening.\n');
}
process.exit(0);
process.exit(getCancelExitCode());
};

process.on('SIGINT', handleSignal);
setSigintHandler(handleSignal);
process.on('SIGTERM', handleSignal);

// Keep alive
Expand Down
5 changes: 3 additions & 2 deletions src/commands/webhooks/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { Command } from '@commander-js/extra-typings';
import pc from 'picocolors';
import type { Resend, WebhookEvent } from 'resend';
import { getCancelExitCode, setSigintHandler } from '../../lib/cli-exit';
import type { GlobalOpts } from '../../lib/client';
import { requireClient } from '../../lib/client';
import { buildHelpText } from '../../lib/help-text';
Expand Down Expand Up @@ -372,10 +373,10 @@ For example, if using ngrok: ngrok http 4318`,
}
cleaningUp = true;
await cleanup(resend, webhookId, server);
process.exit(0);
process.exit(getCancelExitCode());
};

process.on('SIGINT', handleSignal);
setSigintHandler(handleSignal);
process.on('SIGTERM', handleSignal);

// Keep the process alive until signal
Expand Down
24 changes: 20 additions & 4 deletions src/lib/cli-exit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@ import { errorMessage, outputError } from './output';

const CANCEL_EXIT_CODE = 130;

function defaultSigintHandler(): void {
if (process.stderr.isTTY) {
process.stderr.write('\r\x1B[2K');
}
console.error('Cancelled.');
process.exit(CANCEL_EXIT_CODE);
}

let currentSigintHandler: (() => void) | undefined;

export function setupCliExitHandler(): void {
process.on('SIGINT', () => {
console.error('Cancelled.');
process.exit(CANCEL_EXIT_CODE);
});
currentSigintHandler = defaultSigintHandler;
process.on('SIGINT', currentSigintHandler);

process.on('uncaughtException', (err: unknown) => {
outputError(
Expand All @@ -20,6 +28,14 @@ export function setupCliExitHandler(): void {
});
}

export function setSigintHandler(handler: () => void): void {
if (currentSigintHandler) {
process.removeListener('SIGINT', currentSigintHandler);
}
currentSigintHandler = handler;
process.on('SIGINT', currentSigintHandler);
}

export function getCancelExitCode(): number {
return CANCEL_EXIT_CODE;
}
13 changes: 10 additions & 3 deletions tests/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,25 @@ export function mockSdkError(message: string, name = 'error') {
return { data: null, error: { message, name }, headers: null };
}

export async function expectExit1(fn: () => Promise<unknown>): Promise<void> {
export async function expectExitCode(
code: number,
fn: () => Promise<unknown>,
): Promise<void> {
let threw = false;
try {
await fn();
} catch (err) {
threw = true;
expect(err).toBeInstanceOf(ExitError);
expect((err as ExitError).code).toBe(1);
expect((err as ExitError).code).toBe(code);
}
if (!threw) {
throw new Error(
'Expected command to exit with code 1 but it completed successfully',
`Expected command to exit with code ${code} but it completed successfully`,
);
}
}

export async function expectExit1(fn: () => Promise<unknown>): Promise<void> {
return expectExitCode(1, fn);
}
74 changes: 74 additions & 0 deletions tests/lib/cli-exit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
getCancelExitCode,
setSigintHandler,
setupCliExitHandler,
} from '../../src/lib/cli-exit';
import { ExitError, expectExitCode, mockExitThrow } from '../helpers';

describe('cli-exit', () => {
let exitSpy: ReturnType<typeof mockExitThrow>;

beforeEach(() => {
exitSpy = mockExitThrow();
process.removeAllListeners('SIGINT');
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
process.removeAllListeners('uncaughtException');
});

afterEach(() => {
process.removeAllListeners('SIGINT');
process.removeAllListeners('uncaughtException');
vi.restoreAllMocks();
});

it('getCancelExitCode() returns 130', () => {
expect(getCancelExitCode()).toBe(130);
});

it('default SIGINT handler calls process.exit(130)', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
setupCliExitHandler();

expect(() => process.emit('SIGINT', 'SIGINT')).toThrow(ExitError);
expect(exitSpy).toHaveBeenCalledWith(130);
});

it('default SIGINT handler clears terminal line when stderr is TTY', () => {
const originalIsTTY = process.stderr.isTTY;
const stderrSpy = vi
.spyOn(process.stderr, 'write')
.mockImplementation(() => true);
vi.spyOn(console, 'error').mockImplementation(() => {});
Object.defineProperty(process.stderr, 'isTTY', {
value: true,
configurable: true,
});

setupCliExitHandler();

try {
expect(() => process.emit('SIGINT', 'SIGINT')).toThrow(ExitError);
expect(stderrSpy).toHaveBeenCalledWith('\r\x1B[2K');
} finally {
Object.defineProperty(process.stderr, 'isTTY', {
value: originalIsTTY,
configurable: true,
});
}
});

it('setSigintHandler() replaces the default handler', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
setupCliExitHandler();

const custom = vi.fn(() => {
process.exit(getCancelExitCode());
});
setSigintHandler(custom);

await expectExitCode(130, async () => {
process.emit('SIGINT', 'SIGINT');
});
expect(custom).toHaveBeenCalledOnce();
});
});