import { Err , Result } from 'ts-results' ; export class CheckedError < T > extends Error { constructor ( private kind , private reason ) { super ( kind + '' , { cause : reason } ) ; } override toString ( ) { if ( this . reason ) return `${ this . kind }\n${ this . reason }` ; return super . toString ( ) ; } static mapErr < E > ( r ) { return ( e ) => new CheckedError ( r , e ) ; } static withErr < P extends any [ ] , T , E > ( f , o ) ; static withErr < P extends any [ ] , T , E > ( f , o ) ; static withErr < P extends any [ ] , T , E > ( f , o ) { return ( ... args ) => { const r = f ( ... args ) ; if ( 'then' in r ) return r . then ( ( r ) => r . mapErr ( CheckedError . mapErr ( o ) ) ) ; return r . mapErr ( CheckedError . mapErr ( o ) ) ; } ; } toErr ( ) { return Err ( this ) ; } }