11import { watch as rollupWatcher , RollupOptions , OutputOptions , RollupWatcher , RollupWatcherEvent } from 'rollup'
22import { EventEmitter } from 'events'
33
4- export const watchersOutput : Record < string , string > = { }
4+ const lastWatchersOutputEmmitedEvents : Record < string , RollupWatcherEvent > = { }
55
6- export const watchers : Record < string , RollupWatcher > = { }
6+ const watchers : Record < string , RollupWatcher > = { }
77
8- export function watch ( rollupOptions : RollupOptions , outputOptions : OutputOptions , file : EventEmitter ) : Promise < string > {
9- const watcherKey = rollupOptions . input ! . toString ( )
8+ export async function watch ( rollupOptions : RollupOptions , outputOptions : OutputOptions , file : EventEmitter ) : Promise < string > {
9+ const watcherKey = getWatcherKey ( rollupOptions )
1010
1111 const watcher = watchers [ watcherKey ] = watchers [ watcherKey ] ?? rollupWatcher ( {
1212 ...rollupOptions ,
@@ -22,11 +22,29 @@ export function watch (rollupOptions: RollupOptions, outputOptions: OutputOption
2222 } )
2323}
2424
25+ function getWatcherKey ( rollupOptions : RollupOptions ) {
26+ return rollupOptions . input ! . toString ( )
27+ }
28+
29+ export function getWatcherCachedOutput ( rollupOptions : RollupOptions ) : Promise < string > | null {
30+ const lastEvent = lastWatchersOutputEmmitedEvents [ getWatcherKey ( rollupOptions ) ]
31+
32+ if ( lastEvent ?. code === 'BUNDLE_END' ) {
33+ return Promise . resolve ( lastEvent . output [ 0 ] )
34+ }
35+
36+ if ( lastEvent ?. code === 'ERROR' ) {
37+ return Promise . reject ( lastEvent . error )
38+ }
39+
40+ return null
41+ }
42+
2543function createFileClosedListener ( watcherKey : string ) {
2644 return ( ) => {
2745 watchers [ watcherKey ] ?. close ( )
2846 delete watchers [ watcherKey ]
29- delete watchersOutput [ watcherKey ]
47+ delete lastWatchersOutputEmmitedEvents [ watcherKey ]
3048 }
3149}
3250
@@ -47,12 +65,12 @@ function createBuildFinishedListener (file: EventEmitter) {
4765function createOutputEmittedListener ( watcherKey : string , resolve : ( output : string ) => any , reject : ( reason : any ) => any ) {
4866 return ( e : RollupWatcherEvent ) => {
4967 if ( e . code === 'BUNDLE_END' ) {
50- watchersOutput [ watcherKey ] = e . output [ 0 ]
51- resolve ( watchersOutput [ watcherKey ] )
68+ lastWatchersOutputEmmitedEvents [ watcherKey ] = e
69+ resolve ( e . output [ 0 ] )
5270 }
5371
5472 if ( e . code === 'ERROR' ) {
55- delete watchersOutput [ watcherKey ]
73+ lastWatchersOutputEmmitedEvents [ watcherKey ] = e
5674 reject ( e . error )
5775 }
5876 }
0 commit comments