import { parseAsync , transformFromAstAsync } from '@babel/core' ; import generate from '@babel/generator' ; import type { PluginOptions } from '@compiled/babel-plugin' ; import { Transformer } from '@parcel/plugin' ; import SourceMap from '@parcel/source-map' ; type UserlandOpts = Omit < PluginOptions , 'cache' | 'onIncludedFiles' > ; const configFiles = [ '.compiledcssrc' , '.compiledcssrc.json' , 'compiledcss.js' , 'compiledcss.config.js' , ] ; /**
 * Compiled parcel transformer.
 */ export default new Transformer < UserlandOpts > ( { async loadConfig ( { config } ) { const conf = await config . getConfig ( configFiles , { packageKey : '@compiled/parcel-transformer' , } ) ; const contents = { } ; if ( conf ) { config . invalidateOnStartup ( ) ; Object . assign ( contents , conf . contents ) ; } return contents ; } , canReuseAST ( ) { return false ; } , async parse ( { asset } ) { if ( ! asset . isSource ) { return undefined ; } const code = await asset . getCode ( ) ; if ( code . indexOf ( '@compiled/react' ) === - 1 ) { return undefined ; } const program = await parseAsync ( code , { filename : asset . filePath , caller : { name : 'compiled' } , rootMode : 'upward-optional' , } ) ; return { type : 'babel' , version : '7.0.0' , program , } ; } , async transform ( { asset , config } ) { const ast = await asset . getAST ( ) ; if ( ! asset . isSource || ! ast ) { return [ asset ] ; } const includedFiles = [ ] ; const code = asset . isASTDirty ( ) ? undefined : await asset . getCode ( ) ; const result = await transformFromAstAsync ( ast . program , code , { code : false , ast : true , filename : asset . filePath , babelrc : false , configFile : false , sourceMaps : true , plugins : [ [ '@compiled/babel-plugin' , { ... config , onIncludedFiles : ( files ) => includedFiles . push ( ... files ) , cache : 'single-pass' , } , ] , ] , caller : { name : 'compiled' , } , } ) ; includedFiles . forEach ( ( file ) => { asset . invalidateOnFileChange ( file ) ; } ) ; if ( result ?. ast ) { asset . setAST ( { type : 'compiled' , version : '0.0.0' , program : result . ast , } ) ; } return [ asset ] ; } , async generate ( { asset , ast } ) { const { code , map : babelMap } = generate ( ast . program , { filename : asset . filePath , sourceMaps : true , sourceFileName : asset . filePath , } ) ; return { content : code , map : babelMap ? new SourceMap ( ) . addVLQMap ( babelMap ) : null , } ; } , } ) ;