@@ -5,11 +5,12 @@ import { launchBrowsers } from './bun/launch-browser.js';
5
5
import { buildHandler } from './bun/socket-handler.js' ;
6
6
import { debug , error , print } from './utils/debug.js' ;
7
7
import { getPort } from './utils/port.js' ;
8
+ import { addCloseHandler } from './bun/watch.js' ;
8
9
9
10
/** @type {import('bun-types') } */
10
11
const isBun = typeof Bun !== 'undefined' ;
11
12
12
- export default async function launch ( config ) {
13
+ export async function launch ( config ) {
13
14
if ( isBun ) {
14
15
debug ( `Bun detected, using Bun.serve()` ) ;
15
16
@@ -34,6 +35,18 @@ export default async function launch(config) {
34
35
browsers : new Map ( ) ,
35
36
completed : 0 ,
36
37
expected : config . parallel ?? 1 ,
38
+ closeHandlers : [ ] ,
39
+ } ;
40
+ state . safeCleanup = async ( ) => {
41
+ debug ( `Running close handlers` ) ;
42
+ for ( const handler of state . closeHandlers ) {
43
+ try {
44
+ await handler ( ) ;
45
+ } catch ( e ) {
46
+ error ( `Error in close handler: ${ e ?. message ?? e } ` ) ;
47
+ }
48
+ }
49
+ debug ( `All close handlers completed` ) ;
37
50
} ;
38
51
39
52
if ( protocol === 'https' ) {
@@ -56,6 +69,16 @@ export default async function launch(config) {
56
69
} ,
57
70
websocket : buildHandler ( config , state ) ,
58
71
} ) ;
72
+
73
+ addCloseHandler ( state , ( ) => {
74
+ state . browsers ?. forEach ( ( browser ) => {
75
+ browser . proc . kill ( ) ;
76
+ browser . proc . unref ( ) ;
77
+ } ) ;
78
+ state . server . stop ( ) ;
79
+ state . server . unref ( ) ;
80
+ } ) ;
81
+
59
82
print ( chalk . magenta ( `🚀 Serving on ${ chalk . white ( protocol + '://' + hostname + ':' ) } ${ chalk . magenta ( port ) } ` ) ) ;
60
83
config . reporter . serverConfig = {
61
84
port,
@@ -66,22 +89,28 @@ export default async function launch(config) {
66
89
67
90
if ( config . setup ) {
68
91
debug ( `Running configured setup hook` ) ;
92
+
69
93
await config . setup ( {
70
94
port,
71
95
hostname,
72
96
protocol,
73
97
} ) ;
74
98
debug ( `Configured setup hook completed` ) ;
75
99
}
100
+ if ( config . cleanup ) {
101
+ addCloseHandler ( state , async ( ) => {
102
+ debug ( `Running configured cleanup hook` ) ;
103
+ await config . cleanup ( ) ;
104
+ debug ( `Configured cleanup hook completed` ) ;
105
+ } ) ;
106
+ }
76
107
77
- await launchBrowsers ( config , state ) ;
108
+ if ( ! config . noLaunch ) {
109
+ await launchBrowsers ( config , state ) ;
110
+ }
78
111
} catch ( e ) {
79
112
error ( `Error: ${ e ?. message ?? e } ` ) ;
80
- if ( config . cleanup ) {
81
- debug ( `Running configured cleanup hook` ) ;
82
- await config . cleanup ( ) ;
83
- debug ( `Configured cleanup hook completed` ) ;
84
- }
113
+ await state . safeCleanup ( ) ;
85
114
throw e ;
86
115
}
87
116
} else {
0 commit comments