import { defaultConfigOptions } from './web-preset' ; import { IS_SERVER } from './env' ; import { UNDEFINED , mergeObjects , noop } from './helper' ; import { internalMutate } from './mutate' ; import { GlobalState , SWRGlobalState } from './global-state' ; import * as revalidateEvents from '../constants/revalidate-events' ; import { RevalidateEvent } from '../types' ; import { Cache , ScopedMutator , RevalidateCallback , ProviderConfiguration } from '../types' ; const revalidateAllKeys = ( revalidators , type ) => { for ( const key in revalidators ) { if ( revalidators [ key ] [ 0 ] ) revalidators [ key ] [ 0 ] ( type ) ; } } ; export const initCache = < Data = any > ( provider , options ? ) : [ Cache < Data > , ScopedMutator < Data > , ( ) => void ] | [ Cache < Data > , ScopedMutator < Data > ] | undefined => { if ( ! SWRGlobalState . has ( provider ) ) { const opts = mergeObjects ( defaultConfigOptions , options ) ; const EVENT_REVALIDATORS = { } ; const mutate = internalMutate . bind ( UNDEFINED , provider ) as ScopedMutator < Data > ; let unmount = noop ; SWRGlobalState . set ( provider , [ EVENT_REVALIDATORS , { } , { } , { } , mutate ] ) ; if ( ! IS_SERVER ) { const releaseFocus = opts . initFocus ( setTimeout . bind ( UNDEFINED , revalidateAllKeys . bind ( UNDEFINED , EVENT_REVALIDATORS , revalidateEvents . FOCUS_EVENT ) ) ) ; const releaseReconnect = opts . initReconnect ( setTimeout . bind ( UNDEFINED , revalidateAllKeys . bind ( UNDEFINED , EVENT_REVALIDATORS , revalidateEvents . RECONNECT_EVENT ) ) ) ; unmount = ( ) => { releaseFocus && releaseFocus ( ) ; releaseReconnect && releaseReconnect ( ) ; SWRGlobalState . delete ( provider ) ; } ; } return [ provider , mutate , unmount ] ; } return [ provider , ( SWRGlobalState . get ( provider ) as GlobalState ) [ 4 ] ] ; } ;