import { Provider , ProviderConstructor } from "../core/provider" ; import { InitialAllocation , NativeClarityBinProvider } from "./clarityBin" ; export class ProviderRegistry { static availableProviders : ProviderConstructor [ ] = [ ] ; static defaultLoadCachedPromise : Promise < false | ProviderConstructor > | undefined ; static registerProvider ( providerConstructor , clearExisting = false ) { if ( clearExisting ) { this . availableProviders . length = 0 ; } this . availableProviders . push ( providerConstructor ) ; } returns static tryLoadDefaultBinProvider ( ) { if ( this . defaultLoadCachedPromise ) { return this . defaultLoadCachedPromise ; } const loadPromise = Promise . resolve < false | ProviderConstructor > ( ( async ( ) => { let nativeBinModule ; try { nativeBinModule = await import ( "@blockstack/clarity-native-bin" ) ; } catch ( e ) { if ( e . code === "MODULE_NOT_FOUND" ) { return false ; } if ( e . message ) { const importErrStrings = [ "error loading dynamically imported module" , "error resolving module specifier" , "failed to fetch dynamically imported module" , "failed to resolve module" ] ; const errMsg = ( e . message as string ) . toLowerCase ( ) ; if ( importErrStrings . some ( errStr => errMsg . includes ( errStr ) ) ) { return false ; } } throw e ; } const nativeBinFile = nativeBinModule . getDefaultBinaryFilePath ( ) ; const providerConstructor = { create : ( allocations ) => NativeClarityBinProvider . createEphemeral ( allocations , nativeBinFile ) , } ; this . defaultLoadCachedPromise = undefined ; return providerConstructor ; } ) ( ) ) ; this . defaultLoadCachedPromise = loadPromise ; return this . defaultLoadCachedPromise ; } param allocations param noWarn static async createProvider ( allocations = [ ] , noWarn = false ) { if ( this . availableProviders . length === 0 ) { const defaultProvider = await this . tryLoadDefaultBinProvider ( ) ; if ( defaultProvider === false ) { throw new Error ( "No provider is registered. Install the `@blockstack/clarity-native-bin` peer " + "dependency or register a provider manually with `registerProvider()`." ) ; } else { this . availableProviders . push ( defaultProvider ) ; } } if ( ! noWarn && this . availableProviders . length > 1 ) { console . warn ( "Multiple providers are registered. The last registered provider will be returned." ) ; } const providerConstructor = this . availableProviders [ this . availableProviders . length - 1 ] ; return providerConstructor . create ( allocations ) ; } private constructor ( ) { } }