import Fs from 'fs' ; import Path from 'path' ; import webpack from 'webpack' ; import { RawSource } from 'webpack-sources' ; export interface State { optimizerCacheKey ? : unknown ; cacheKey ? : unknown ; moduleCount ? : number ; workUnits ? : number ; files ? : string [ ] ; bundleRefExportIds ? : string [ ] ; } const DEFAULT_STATE = { } ; const DEFAULT_STATE_JSON = JSON . stringify ( DEFAULT_STATE ) ; const CACHE_FILENAME = '.kbn-optimizer-cache' ; /**
 * Helper to read and update metadata for bundles.
 */ export class BundleCache { private state : State | undefined = undefined ; private readonly path : string | false ; constructor ( outputDir ) { this . path = outputDir === false ? false : Path . resolve ( outputDir , CACHE_FILENAME ) ; } refresh ( ) { this . state = undefined ; } get ( ) { if ( ! this . state ) { let json ; try { if ( this . path ) { json = Fs . readFileSync ( this . path , 'utf8' ) ; } } catch ( error ) { if ( error . code !== 'ENOENT' ) { throw error ; } } let partialCache ; try { partialCache = JSON . parse ( json || DEFAULT_STATE_JSON ) ; } catch ( error ) { partialCache = { } ; } this . state = { ... DEFAULT_STATE , ... partialCache , } ; } return this . state ; } set ( updated ) { this . state = updated ; if ( this . path ) { const directory = Path . dirname ( this . path ) ; Fs . mkdirSync ( directory , { recursive : true } ) ; Fs . writeFileSync ( this . path , JSON . stringify ( this . state , null , 2 ) ) ; } } public getModuleCount ( ) { return this . get ( ) . moduleCount ; } public getReferencedFiles ( ) { return this . get ( ) . files ; } public getBundleRefExportIds ( ) { return this . get ( ) . bundleRefExportIds ; } public getCacheKey ( ) { return this . get ( ) . cacheKey ; } public getWorkUnits ( ) { return this . get ( ) . workUnits ; } public getOptimizerCacheKey ( ) { return this . get ( ) . optimizerCacheKey ; } public clear ( ) { this . state = undefined ; if ( this . path ) { try { Fs . unlinkSync ( this . path ) ; } catch ( error ) { if ( error . code !== 'ENOENT' ) { throw error ; } } } } public writeWebpackAsset ( compilation ) { if ( ! this . path ) { return ; } const source = new RawSource ( JSON . stringify ( this . state , null , 2 ) ) ; compilation . emitAsset ( CACHE_FILENAME , source ) ; } }