import { statSync } from 'fs' ; import { join , resolve } from 'pathe' ; export interface FindNearestFileOptions { default startingFrom ? : string ; default rootPattern ? : RegExp ; default test ? : ( filePath : string ) => boolean | null | Promise < boolean | null > ; } const defaultFindOptions = { startingFrom : '.' , rootPattern : /^node_modules$/ , test : ( filePath ) => { try { if ( statSync ( filePath ) . isFile ( ) ) { return true ; } } catch { } return null ; } } ; export async function findNearestFile ( filename , _options = { } ) { const options = { ... defaultFindOptions , ... _options } ; const basePath = resolve ( options . startingFrom ) ; const leadingSlash = basePath [ 0 ] === '/' ; const segments = basePath . split ( '/' ) . filter ( Boolean ) ; if ( leadingSlash ) { segments [ 0 ] = '/' + segments [ 0 ] ; } let root = segments . findIndex ( r => r . match ( options . rootPattern ) ) ; if ( root === - 1 ) root = 0 ; for ( let i = segments . length ; i > root ; i -- ) { const filePath = join ( ... segments . slice ( 0 , i ) , filename ) ; if ( await options . test ( filePath ) ) { return filePath ; } } throw new Error ( `Cannot find matching ${ filename } in ${ options . startingFrom } or parent directories` ) ; }