import type { Plugin } from 'esbuild' ; import { getRequest } from '../util/cache' ; import { inferLoader } from '../util/loader' ; export async function fetchPkg ( url ) { let response = await getRequest ( url ) ; return { url : response . url , content : new Uint8Array ( await response . arrayBuffer ( ) ) , } ; } export const HTTP_NAMESPACE = 'http-url' ; export const HTTP = ( ) : Plugin => { return { name : HTTP_NAMESPACE , setup ( build ) { build . onResolve ( { filter : /^https?:\/\// } , args => { let resolveDir = args . resolveDir . replace ( /^\// , '' ) ; return { path : resolveDir . length > 0 ? new URL ( args . path , resolveDir ) . toString ( ) : args . path , namespace : HTTP_NAMESPACE , } ; } ) ; build . onResolve ( { filter : /.*/ , namespace : HTTP_NAMESPACE } , args => { let importer = args . importer ; let pathUrl = args . path . replace ( /\/$/ , "/index" ) ; return { path : new URL ( pathUrl , importer ) . toString ( ) , namespace : HTTP_NAMESPACE , } ; } ) ; build . onLoad ( { filter : /.*/ , namespace : HTTP_NAMESPACE } , async ( args ) => { const { content , url } = await fetchPkg ( args . path ) ; return { contents : content , loader : inferLoader ( url ) , resolveDir : `/${ url }` , } ; } ) ; } , } ; } ;