2023-12-19 02:24:19 +03:00
|
|
|
// roughly based on https://github.com/sindresorhus/exit-hook/blob/main/index.js, MIT license
|
|
|
|
|
|
|
|
let installed = false
|
|
|
|
let handled = false
|
|
|
|
|
|
|
|
const callbacks = new Set<() => void>()
|
2024-07-01 01:50:43 +03:00
|
|
|
// eslint-disable-next-line func-call-spacing
|
|
|
|
const myHandlers = new Map<string, () => void>()
|
2023-12-19 02:24:19 +03:00
|
|
|
|
2024-07-01 01:50:43 +03:00
|
|
|
function register(shouldManuallyExit: boolean, signal: number, event: string) {
|
|
|
|
function eventHandler() {
|
2023-12-19 02:24:19 +03:00
|
|
|
if (handled) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
handled = true
|
|
|
|
|
|
|
|
for (const callback of callbacks) {
|
|
|
|
callback()
|
|
|
|
}
|
|
|
|
|
2024-07-01 01:50:43 +03:00
|
|
|
for (const [event, handler] of myHandlers) {
|
|
|
|
process.off(event, handler)
|
|
|
|
}
|
2023-12-19 02:24:19 +03:00
|
|
|
|
2024-07-01 01:50:43 +03:00
|
|
|
if (shouldManuallyExit) {
|
|
|
|
// send the signal again and let node handle it
|
|
|
|
process.kill(process.pid, signal)
|
2023-12-19 02:24:19 +03:00
|
|
|
}
|
|
|
|
}
|
2024-07-01 01:50:43 +03:00
|
|
|
|
|
|
|
process.on(event, eventHandler)
|
|
|
|
myHandlers.set(event, eventHandler)
|
2023-12-19 02:24:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
export function beforeExit(fn: () => void): () => void {
|
|
|
|
// unsupported platform
|
|
|
|
if (typeof process === 'undefined') return () => {}
|
|
|
|
|
|
|
|
if (!installed) {
|
|
|
|
installed = true
|
|
|
|
|
2024-07-01 01:50:43 +03:00
|
|
|
register(true, 0, 'beforeExit')
|
|
|
|
register(true, 2, 'SIGINT')
|
|
|
|
register(true, 15, 'SIGTERM')
|
|
|
|
register(false, 15, 'exit')
|
2023-12-19 02:24:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
callbacks.add(fn)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
callbacks.delete(fn)
|
|
|
|
}
|
|
|
|
}
|