import { ResourceState , LooseApi , Family } from './interface.js' ; interface Listener { api : LooseApi ; key : string ; callback : ( ) => void ; } export class ObservableCache { private readonly listeners : Set < Listener > = new Set ( ) ; private version : number = 0 ; constructor ( private readonly cache ) { } getVersion ( ) { return this . version ; } init ( api , key , promise ) { const family = this . getFamilySafe ( api ) ! ; family . set ( key , { promise , kind : 'pending' } ) ; } set ( api , key , value ) { const family = this . getFamilySafe ( api ) ! ; family . set ( key , value ) ; this . version ++ ; this . notify ( api , key ) ; } get ( api , key ) { return this . getFamilySafe ( api ) . get ( key ) ; } has ( api , key ) { return this . cache . has ( api ) && this . cache . get ( api ) ! . has ( key ) ; } observe ( api , key , callback ) { const listener = { api , key , callback } ; this . listeners . add ( listener ) ; return ( ) => { this . listeners . delete ( listener ) ; } ; } private getFamilySafe ( api ) { if ( ! this . cache . has ( api ) ) { this . cache . set ( api , new Map ( ) ) ; } return this . cache . get ( api ) ! ; } private notify ( api , key ) { for ( const listener of this . listeners ) { if ( listener . api === api && listener . key === key ) { listener . callback ( ) ; } } } }