import type { PluginAPI, PluginObject, PluginPass, PresetAPI, PresetObject, } from "@babel/core"; type APIPolyfillFactory = ( api: PluginAPI, ) => PluginAPI[T]; type APIPolyfills = { assertVersion: APIPolyfillFactory<"assertVersion">; targets: APIPolyfillFactory<"targets">; assumption: APIPolyfillFactory<"assumption">; }; const apiPolyfills: APIPolyfills = { // Not supported by Babel 7 and early versions of Babel 7 beta. // It's important that this is polyfilled for older Babel versions // since it's needed to report the version mismatch. assertVersion: (api: PluginAPI) => (range: number | string) => { throwVersionError(range, api.version); }, // This is supported starting from Babel 7.13 // TODO(Babel 8): Remove this polyfill targets: () => () => { return {}; }, // This is supported starting from Babel 7.13 // TODO(Babel 8): Remove this polyfill assumption: () => () => { return undefined; }, }; export function declare( builder: ( api: PluginAPI, options: Option, dirname: string, ) => PluginObject, ): ( api: PluginAPI, options: Option, dirname: string, ) => PluginObject { return (api, options: Option, dirname: string) => { let clonedApi: PluginAPI; for (const name of Object.keys( apiPolyfills, ) as (keyof typeof apiPolyfills)[]) { if (api[name]) continue; // TODO: Use ??= when flow lets us to do so clonedApi = clonedApi ?? copyApiObject(api); // @ts-expect-error The shape of API polyfill is guaranteed by APIPolyfillFactory clonedApi[name] = apiPolyfills[name](clonedApi); } // @ts-expect-error options || {} may not be assigned to Options return builder(clonedApi ?? api, options || {}, dirname); }; } export const declarePreset = declare as