Skip to content

Commit

Permalink
chore: handle process exit differently
Browse files Browse the repository at this point in the history
for proper library logging
  • Loading branch information
chrisbbreuer committed Dec 13, 2024
1 parent b7d896a commit ca2b087
Showing 1 changed file with 35 additions and 13 deletions.
48 changes: 35 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,46 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
let domains: string[] | undefined
let proxyUrl: string | undefined
let originalConsole: typeof console
let cleanupPromise: Promise<void> | null = null

const debug = (...args: any[]) => {
if (verbose)
originalConsole.log('[vite-plugin-local]', ...args)
}

// Override the library's process.exit
const originalExit = process.exit
process.exit = ((code?: number) => {
if (cleanupPromise) {
cleanupPromise.finally(() => {
process.exit = originalExit
process.exit(code)
})
return undefined as never
}
return originalExit(code)
}) as (code?: number) => never

// Add cleanup handler for process exit
const exitHandler = async () => {
if (domains?.length) {
debug('Cleaning up...')
cleanupPromise = cleanup({
domains,
etcHostsCleanup,
verbose,
})
await cleanupPromise
domains = undefined
debug('Cleanup complete')
}
}

// Handle cleanup for different termination signals
process.on('SIGINT', exitHandler)
process.on('SIGTERM', exitHandler)
process.on('beforeExit', exitHandler)

return {
name: 'vite-plugin-local',
enforce: 'pre',
Expand Down Expand Up @@ -184,19 +218,7 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
}

server.httpServer?.once('close', async () => {
if (domains?.length) {
debug('Cleaning up...')

await cleanup({
domains,
etcHostsCleanup,
verbose,
})

domains = undefined

debug('Cleanup complete')
}
await exitHandler()
})
},
}
Expand Down

0 comments on commit ca2b087

Please sign in to comment.