1
+ import { Command } from 'commander'
2
+ import { existsSync , mkdirSync } from 'fs'
3
+ import { parseAndRemoveWildcardOptions } from '~/utils'
4
+ import { StaxConfig } from '~/types'
5
+ import { registerCommands } from '~/commands'
6
+ import { version } from '../package.json'
7
+ import * as path from 'path'
8
+ import tmp from 'tmp'
9
+
10
+ function buildArgs ( ) {
11
+ let [ args , overrides ] = parseAndRemoveWildcardOptions ( process . argv , '--stax.' )
12
+ const commandSeparator = args . indexOf ( '--' )
13
+
14
+ if ( commandSeparator >= 0 ) {
15
+ const command = args . slice ( commandSeparator + 1 ) . join ( ' ' )
16
+ args = args . slice ( 0 , commandSeparator )
17
+ args . push ( command )
18
+ }
19
+
20
+ if ( args . includes ( '-v' ) || args . includes ( '--version' ) ) {
21
+ console . log ( version )
22
+ process . exit ( 0 )
23
+ }
24
+
25
+ return [ args , overrides ]
26
+ }
27
+
28
+ function init ( ) {
29
+ process . env . STAX_HOME = path . join ( process . env . HOME , '.stax' )
30
+ process . env . STAX_HOST_SERVICES = path . join ( process . env . STAX_HOME , 'host-services' )
31
+
32
+ if ( ! existsSync ( process . env . STAX_HOME ) ) mkdirSync ( process . env . STAX_HOME )
33
+ if ( ! existsSync ( process . env . STAX_HOST_SERVICES ) ) mkdirSync ( process . env . STAX_HOST_SERVICES )
34
+
35
+ process . on ( 'SIGINT' , ( ) => { tmp . setGracefulCleanup ( ) ; process . exit ( ) } )
36
+
37
+ process . on ( 'unhandledRejection' , ( reason : any , promise : Promise < any > ) => {
38
+ /*
39
+ workaround to fix what seems like an input problem with bun. triggers every time when you press
40
+ enter multiple times during a prompt.
41
+
42
+ TypeError: undefined is not an object
43
+ at <anonymous> (native)
44
+ at <anonymous> (native)
45
+ at <anonymous> (native)
46
+ at <anonymous> (native)
47
+ at <anonymous> (native)
48
+ at handleResult (native:36:41)
49
+ at handleNativeReadableStreamPromiseResult2 (native:7:60)
50
+ at processTicksAndRejections (native:7:39)
51
+ at spawnSync (unknown)
52
+ at spawnSync (node:child_process:233:22)
53
+
54
+ this work around causes some input to get ignored and you'll have to press your
55
+ keys multiple times for it to register but it's better than crashing.
56
+ */
57
+ if ( reason instanceof TypeError && reason . message === 'undefined is not an object' && reason . stack ?. includes ( 'handleResult' ) )
58
+ return
59
+
60
+ if ( reason instanceof Error ) {
61
+ console . error ( reason . stack )
62
+ process . exit ( 1 )
63
+ }
64
+ } )
65
+
66
+ tmp . setGracefulCleanup ( )
67
+ }
68
+
69
+ export function runProgram ( additionalCommands : Function [ ] = [ ] ) {
70
+ const program = new Command ( )
71
+ const [ args , overrides ] = buildArgs ( )
72
+
73
+ init ( )
74
+ registerCommands ( program , overrides as unknown as StaxConfig , additionalCommands )
75
+ program . name ( 'stax' )
76
+ program . parse ( args as string [ ] )
77
+ }
78
+
0 commit comments