import { getOrAdd } from '../common/collectionUtils' ; import { FileSystem } from '../common/fileSystem' ; import { ensureTrailingDirectorySeparator , normalizePath , normalizePathCase } from '../common/pathUtils' ; import { ImportResult } from './importResult' ; export type ImportPath = { importPath : string | undefined ; } ; type CacheEntry = { importResult : ImportResult ; path : string ; importName : string ; } ; export class ParentDirectoryCache { private readonly _importChecked = new Map < string , Map < string , ImportPath > > ( ) ; private readonly _cachedResults = new Map < string , Map < string , ImportResult > > ( ) ; private _libPathCache : string [ ] | undefined = undefined ; constructor ( private _importRootGetter ) { } getImportResult ( path , importName , importResult ) { const result = this . _cachedResults . get ( importName ) ?. get ( path ) ; if ( result ) { return result ?? importResult ; } const checked = this . _importChecked . get ( importName ) ?. get ( path ) ; if ( checked ) { if ( ! checked . importPath ) { return importResult ; } return this . _cachedResults . get ( importName ) ?. get ( checked . importPath ) ?? importResult ; } return undefined ; } checkValidPath ( fs , sourceFilePath , root ) { if ( ! sourceFilePath . startsWith ( root ) ) { return false ; } this . _libPathCache = this . _libPathCache ?? this . _importRootGetter ( ) . map ( ( r ) => ensureTrailingDirectorySeparator ( normalizePathCase ( fs , normalizePath ( r ) ) ) ) . filter ( ( r ) => r !== root ) . filter ( ( r ) => r . startsWith ( root ) ) ; if ( this . _libPathCache . some ( ( p ) => sourceFilePath . startsWith ( p ) ) ) { return false ; } return true ; } checked ( path , importName , importPath ) { getOrAdd ( this . _importChecked , importName , ( ) => new Map < string , ImportPath > ( ) ) . set ( path , importPath ) ; } add ( result ) { getOrAdd ( this . _cachedResults , result . importName , ( ) => new Map < string , ImportResult > ( ) ) . set ( result . path , result . importResult ) ; } reset ( ) { this . _importChecked . clear ( ) ; this . _cachedResults . clear ( ) ; this . _libPathCache = undefined ; } }