import path from 'path' ; import { URL } from 'url' ; import type { Transformer } from '@remark-embedder/core' ; import fetch from 'make-fetch-happen' ; fetch . defaults ( { cachePath : path . join ( process . cwd ( ) , 'node_modules/.cache/@remark-embedder/transformer-oembed/fetch' ) } ) ; type Provider = { provider_name : string ; provider_url : string ; endpoints : Array < { schemes ? : string [ ] ; discovery ? : boolean ; url : string ; } > ; } ; type Providers = Array < Provider > ; declare namespace getProviders { let cache ; } async function getProviders ( ) { if ( ! getProviders . cache ) { const res = await fetch ( 'https://oembed.com/providers.json' ) ; getProviders . cache = ( await res . json ( ) ) as Providers ; } return getProviders . cache ; } async function getProviderEndpointURLForURL ( url ) { const providers = await getProviders ( ) ; for ( const provider of providers ) { for ( const endpoint of provider . endpoints ) { if ( endpoint . schemes ?. some ( scheme => new RegExp ( scheme . replace ( /\*/g , '(.*)' ) ) . test ( url ) ) ) { return { provider , endpoint : endpoint . url } ; } } } return null ; } type Config = { params ? : { [ key ] : unknown ; } ; } ; type GetConfig = ( { url , provider , } : { url : string ; provider : Provider ; } ) => Config | null | undefined ; type OEmbedData = { html : string ; } ; const transformer = { name : '@remark-embedder/transformer-oembed' , shouldTransform : async ( url ) => { const result = await getProviderEndpointURLForURL ( url ) ; return Boolean ( result ) ; } , getHTML : async ( urlString , getConfig = { } ) => { const result = await getProviderEndpointURLForURL ( urlString ) ; if ( ! result ) return null ; const { provider , endpoint } = result ; const url = new URL ( endpoint ) ; url . searchParams . set ( 'url' , urlString ) ; let config = getConfig as Config ; if ( typeof getConfig === 'function' ) { config = getConfig ( { url : urlString , provider } ) ?? { } ; } for ( const [ key , value ] of Object . entries ( config . params ?? { } ) ) { url . searchParams . set ( key , String ( value ) ) ; } url . searchParams . set ( 'format' , 'json' ) ; const res = await fetch ( url . toString ( ) ) ; const data = ( await res . json ( ) ) as OEmbedData ; return data . html ; } } ; export default transformer ; type ExportedConfig = Config | GetConfig ; export type { ExportedConfig as Config } ;