import { FluentBundle } from "@fluent/bundle/compat" ; import { globalErrorReporter } from "../errors" ; function getMessageFromBundle < T extends { } > ( bundle , key , args ? ) { const message = bundle . getMessage ( key ) ; if ( ! message ) { if ( bundle . locales . includes ( "en-US" ) ) { globalErrorReporter . report ( `Missing English translation for "${ key }"` ) ; } else if ( process . env . NODE_ENV !== "production" ) { console . warn ( `Translation ${ key } was not found for ${ bundle . locales }` ) ; } } if ( ! message || ! message . value ) { return "" ; } const errors = [ ] ; const formatted = bundle . formatPattern ( message . value , args || { } , errors ) ; if ( errors . length > 0 ) { globalErrorReporter . report ( `Translation ${ key } encountered an error: ${ errors . map ( ( err ) => err . message ) . join ( ", " ) }` ) ; return "" ; } if ( formatted && Array . isArray ( formatted ) ) { return formatted . join ( "" ) ; } return formatted ; } export default function getMessage < T extends { } > ( bundles , key , defaultTo , args ? ) { const result = bundles . reduce ( ( val , bundle ) => ( val ? val : getMessageFromBundle < T > ( bundle , key , args ) ) , "" ) ; return result || defaultTo ; }