type Tuple < T = any > = [ T ] | T [ ] ; type Await < T > = T extends Promise < infer V > ? V : never ; type Config = { lifespan ? : number ; equal ? : ( a : any , b : any ) => boolean ; } ; type Cache < Keys extends Tuple < unknown > > = { promise : Promise < unknown > ; keys : Keys ; equal ? : ( a : any , b : any ) => boolean ; error ? : any ; response ? : unknown ; } ; const globalCache = [ ] ; function shallowEqualArrays ( arrA , arrB , equal = ( a , b ) => a === b ) { if ( arrA === arrB ) return true ; if ( ! arrA || ! arrB ) return false ; const len = arrA . length ; if ( arrB . length !== len ) return false ; for ( let i = 0 ; i < len ; i ++ ) if ( ! equal ( arrA [ i ] , arrB [ i ] ) ) return false ; return true ; } function query < Keys extends Tuple < unknown > , Fn extends ( ... keys : Keys ) => Promise < unknown > > ( fn , keys , preload = false , config = { } ) { for ( const entry of globalCache ) { if ( shallowEqualArrays ( keys , entry . keys , entry . equal ) ) { if ( preload ) return undefined as unknown as Await < ReturnType < Fn > > ; if ( Object . prototype . hasOwnProperty . call ( entry , 'error' ) ) throw entry . error ; if ( Object . prototype . hasOwnProperty . call ( entry , 'response' ) ) return entry . response as Await < ReturnType < Fn > > ; if ( ! preload ) throw entry . promise ; } } const entry = { keys , equal : config . equal , promise : fn ( ... keys ) . then ( ( response ) => ( entry . response = response ) ) . then ( ( ) => { if ( config . lifespan && config . lifespan > 0 ) { setTimeout ( ( ) => { const index = globalCache . indexOf ( entry ) ; if ( index !== - 1 ) globalCache . splice ( index , 1 ) ; } , config . lifespan ) ; } } ) . catch ( ( error ) => ( entry . error = error ) ) , } ; globalCache . push ( entry ) ; if ( ! preload ) throw entry . promise ; return undefined as unknown as Await < ReturnType < Fn > > ; } const suspend = < Keys extends Tuple < unknown > , Fn extends ( ... keys : Keys ) => Promise < unknown > > ( fn , keys , config ? ) => query ( fn , keys , false , config ) ; const preload = < Keys extends Tuple < unknown > , Fn extends ( ... keys : Keys ) => Promise < unknown > > ( fn , keys , config ? ) => void query ( fn , keys , true , config ) ; const peek = < Keys extends Tuple < unknown > > ( keys ) => globalCache . find ( ( entry ) => shallowEqualArrays ( keys , entry . keys , entry . equal ) ) ?. response ; const clear = < Keys extends Tuple < unknown > > ( keys ? ) => { if ( keys === undefined || keys . length === 0 ) globalCache . splice ( 0 , globalCache . length ) ; else { const entry = globalCache . find ( ( entry ) => shallowEqualArrays ( keys , entry . keys , entry . equal ) ) ; if ( entry ) { const index = globalCache . indexOf ( entry ) ; if ( index !== - 1 ) globalCache . splice ( index , 1 ) ; } } } ; export { suspend , clear , preload , peek } ;