11import path from "path" ;
22
3- async function _tryImport ( path :string ) {
3+ let diagnostics : Error [ ] = [ ]
4+
5+ async function _tryImport ( path : string ) : Promise < false | Record < string , unknown > > {
46 try {
57 return await import ( path ) ;
6- } catch ( err ) {
7- console . error ( err )
8- return false ;
8+ } catch ( err ) {
9+ if ( err instanceof Error ) {
10+ diagnostics . push ( err )
11+ }
12+ return false
913 }
1014}
1115
1216function _tryRequire ( path : string ) {
1317 try {
1418 return require ( path ) ;
15- } catch ( err ) {
16- console . error ( err )
19+ } catch ( err ) {
20+ if ( err instanceof Error ) {
21+ diagnostics . push ( err )
22+ }
1723 return false ;
1824 }
1925}
@@ -26,11 +32,14 @@ export async function load(taskRoot: string, originalHandler: string) {
2632 const functionName = pathDetails . ext . slice ( 1 ) ;
2733
2834 const functionPath = path . resolve ( taskRoot , pathDetails . dir , pathDetails . name ) ;
29-
30- const lambda = await _tryImport ( functionPath + '.js' ) || await _tryImport ( functionPath + '.mjs' ) || _tryRequire ( functionPath + '.js' ) || _tryRequire ( functionPath + '.cjs' )
3135
32- if ( ! lambda ) {
33- throw Error ( `Could not load ${ functionPath } .js or ${ functionPath } .mjs` ) ;
36+ const lambda = await _tryImport ( functionPath + '.js' ) || await _tryImport ( functionPath + '.mjs' ) ;
37+
38+ if ( lambda === false ) {
39+ if ( process . env . BASELIME_DEBUG && diagnostics . length > 0 ) {
40+ process . stdout . write ( `Diagnostics for ${ originalHandler } \n${ diagnostics . map ( d => JSON . stringify ( { name : d . name , message : d . message , stack : d . stack } ) ) . join ( '\n' ) } \n` )
41+ }
42+ throw Error ( `Could not load ${ originalHandler } ` ) ;
3443 }
3544 return lambda [ functionName ] ;
3645}
@@ -44,11 +53,14 @@ export function loadSync(taskRoot: string, originalHandler: string) {
4453 const functionName = pathDetails . ext . slice ( 1 ) ;
4554
4655 const functionPath = path . resolve ( taskRoot , pathDetails . dir , pathDetails . name ) ;
47-
48- const lambda = _tryRequire ( functionPath + '.js' ) || _tryRequire ( functionPath + '.cjs' )
56+
57+ const lambda = _tryRequire ( functionPath + '.js' ) || _tryRequire ( functionPath + '.cjs' )
4958
5059 if ( ! lambda ) {
51- throw Error ( `Could not load ${ functionPath } .js or ${ functionPath } .cjs` ) ;
60+ if ( process . env . BASELIME_DEBUG && diagnostics . length > 0 ) {
61+ process . stdout . write ( `Diagnostics for ${ originalHandler } \n${ diagnostics . map ( d => JSON . stringify ( { name : d . name , message : d . message , stack : d . stack } ) ) . join ( '\n' ) } \n` )
62+ }
63+ throw Error ( `Could not load ${ originalHandler } ` ) ;
5264 }
5365 return lambda [ functionName ] ;
5466}
0 commit comments