import { Block , ResolvedConfiguration , StyleMapping , resolveConfiguration , } from "@css-blocks/core" ; import * as debugGenerator from "debug" ; import * as loaderUtils from "loader-utils" ; const debug = debugGenerator ( "css-blocks:webpack:loader" ) ; import { LoaderContext } from "./context" ; import { PendingResult , TmpType } from "./Plugin" ; /**
 * The css-blocks loader makes css-blocks available to webpack modules.
 */ function trackBlockDependencies ( loaderContext , block , options ) { let sourceFile = options . importer . filesystemPath ( block . identifier , options ) ; if ( sourceFile !== null ) { loaderContext . dependency ( sourceFile ) ; } block . dependencies . forEach ( dep => { loaderContext . dependency ( dep ) ; } ) ; block . transitiveBlockDependencies ( ) . forEach ( blockDep => { trackBlockDependencies ( loaderContext , blockDep , options ) ; } ) ; } export function CSSBlocksWebpackAdapter ( this , source , map ) { let callback = this . async ( ) ! ; if ( ! callback ) { throw new Error ( "Cannot initialize CSS Blocks async Webpack loader." ) ; } let thisLoader = this . loaders [ this . loaderIndex ] ; let path = this . resourcePath ; let options ; if ( thisLoader . options ) { options = thisLoader . options ; } else { options = loaderUtils . getOptions ( this ) || { } ; } if ( ! options . rewriter ) { callback ( new Error ( "No rewriter" ) ) ; return ; } let rewriter = options . rewriter || { } ; rewriter . blocks = rewriter . blocks || { } ; this . dependency ( path ) ; let cssFileNames = Object . keys ( this . cssBlocks . mappings ) ; let cssBlockOpts = resolveConfiguration ( this . cssBlocks . compilationOptions ) ; let metaMappingPromises = [ ] ; cssFileNames . forEach ( filename => { metaMappingPromises . push ( this . cssBlocks . mappings [ filename ] ) ; } ) ; debug ( `Waiting for ${ metaMappingPromises . length } block compilations to complete...` ) ; Promise . all ( metaMappingPromises ) . then ( ( mappings ) => { debug ( `Completed ${ metaMappingPromises . length } block compilations!` ) ; mappings . forEach ( ( mapping ) => { debug ( `StyleMapping has ${ mapping && mapping . blocks . size || 0 } blocks` ) ; if ( ! mapping ) { return ; } let styleMapping = mapping && mapping . analyses && mapping . analyses . find ( a => a . template . identifier === path ) && mapping ; if ( ! styleMapping ) { return ; } for ( let key in styleMapping . blocks ) { let block = styleMapping . blocks [ key ] ; trackBlockDependencies ( this , block , cssBlockOpts ) ; } rewriter . blocks [ path ] = styleMapping ; } ) ; callback ( null , source , map ) ; } ) . catch ( ( err ) => { debug ( `${ metaMappingPromises . length } block compilations failed with:\n\n ${ err }` ) ; callback ( err ) ; } ) ; } export const LOADER = __filename ; export default CSSBlocksWebpackAdapter ;