1 | import type { CommonLogger } from '@naturalcycles/js-lib'
|
2 |
|
3 | export interface RunScriptOptions {
|
4 | |
5 |
|
6 |
|
7 |
|
8 |
|
9 | noExit?: boolean
|
10 |
|
11 | |
12 |
|
13 |
|
14 | logger?: CommonLogger
|
15 | }
|
16 |
|
17 | const { DEBUG_RUN_SCRIPT } = process.env
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | export function runScript(fn: (...args: any[]) => any, opt: RunScriptOptions = {}): void {
|
38 | const { logger = console, noExit } = opt
|
39 |
|
40 | process.on('uncaughtException', err => {
|
41 | logger.error('uncaughtException:', err)
|
42 | })
|
43 | process.on('unhandledRejection', err => {
|
44 | logger.error('unhandledRejection:', err)
|
45 | })
|
46 |
|
47 | if (DEBUG_RUN_SCRIPT) {
|
48 | process.on('exit', code => logger.log(`process.exit event, code=${code}`))
|
49 | process.on('beforeExit', code => logger.log(`process.beforeExit event, code=${code}`))
|
50 | }
|
51 |
|
52 |
|
53 | const timeout = setTimeout(() => {}, 10000000)
|
54 |
|
55 | void (async () => {
|
56 | try {
|
57 | await fn()
|
58 |
|
59 | if (DEBUG_RUN_SCRIPT) logger.log(`runScript promise resolved`)
|
60 |
|
61 | if (!noExit) {
|
62 | setImmediate(() => process.exit(0))
|
63 | }
|
64 | } catch (err) {
|
65 | logger.error('runScript error:', err)
|
66 | process.exitCode = 1
|
67 | if (!noExit) {
|
68 | setImmediate(() => process.exit(1))
|
69 | }
|
70 | } finally {
|
71 | clearTimeout(timeout)
|
72 | }
|
73 | })()
|
74 | }
|