import { authenticate , createUser , graphSigner } from '@chaingun/sear' ; import { ChainGunSeaClient } from './ChainGunSeaClient' ; interface UserReference { readonly alias : string ; readonly pub : string ; } interface AckErr { readonly err : Error ; } interface UserCredentials { readonly priv : string ; readonly epriv : any ; readonly alias : string ; readonly pub : string ; readonly epub : string ; } type LoginCallback = ( userRef : UserReference | AckErr ) => void ; const DEFAULT_CREATE_OPTS = { } ; const DEFAULT_AUTH_OPTS = { } ; export class ChainGunUserApi { public readonly is ? : UserReference ; private readonly _gun : ChainGunSeaClient ; private readonly _signMiddleware ? : ( graph : any ) => Promise < any > ; constructor ( gun ) { this . _gun = gun ; } param alias param password param cb param opt public async create ( alias , password , cb ? , _opt = DEFAULT_CREATE_OPTS ) { try { const user = await createUser ( this . _gun , alias , password ) ; const ref = this . useCredentials ( user ) ; if ( cb ) { cb ( ref ) ; } return ref ; } catch ( err ) { if ( cb ) { cb ( { err } ) ; } throw err ; } } param alias param password param cb param opt public async auth ( alias , password , cb ? , _opt = DEFAULT_AUTH_OPTS ) { try { const user = await authenticate ( this . _gun , alias , password ) ; const ref = this . useCredentials ( user ) ; if ( cb ) { cb ( ref ) ; } return ref ; } catch ( err ) { if ( cb ) { cb ( { err } ) ; } throw err ; } } /**
     * https://gun.eco/docs/User#user-leave
     */ public leave ( ) { if ( this . _signMiddleware ) { this . _gun . graph . unuse ( this . _signMiddleware , 'write' ) ; this . _signMiddleware = undefined ; this . is = undefined ; } return this ; } public useCredentials ( credentials ) { this . leave ( ) ; this . _signMiddleware = graphSigner ( { priv : credentials . priv , pub : credentials . pub } ) ; this . _gun . graph . use ( this . _signMiddleware , 'write' ) ; return ( this . is = { alias : credentials . alias , pub : credentials . pub } ) ; } }