import * as fs from "fs"; import * as path from "path"; import { RJLog } from "../log/RJLog"; import { Files } from "../files/Files"; import { PathReference } from "../files/PathReference"; export class TemplatesInfo { templates:string[] = []; } export class TemplatesIndexBuilder { inputDir:string; outputDir:string; constructor( source:string, build:string ) { this.inputDir = source; this.outputDir = build; } filterFiles( fileName:string ) { if ( fileName.startsWith( "__" ) ) { return false; } return fileName.endsWith( ".html" ); } apply( compiler:any ) { compiler.hooks.afterCompile.tapAsync( "TemplatesIndexBuilder", async ( compilation:any, callback:any ) => { await Files.forAllIn( this.inputDir, null, async ( p:PathReference ) => { if ( await p.isDirectory() ) { return Promise.resolve(); } let fileName = p.fileName; if ( ! this.filterFiles( fileName ) ) { return Promise.resolve(); } compilation.fileDependencies.add( p.absolutePath ); return Promise.resolve(); } ); callback(); } ); compiler.hooks.emit.tapAsync( "TemplatesIndexBuilder", async ( compilation:any, callback:any ) => { let templates = new TemplatesInfo(); let templatesPathReference = new PathReference( path.resolve( this.inputDir ) ); // RJLog.log( templatesPathReference.absolutePath ); await Files.forAllIn( templatesPathReference.absolutePath, null, async ( p:PathReference ) => { if ( await p.isDirectory() ) { return Promise.resolve(); } let fileName = p.fileName; if ( ! this.filterFiles( fileName ) ) { return Promise.resolve(); } let absoluteFilePath = p.absolutePath; let inputRelativePath = templatesPathReference.createRelativeFromAbsolute( absoluteFilePath, true ); // RJLog.log( "Abs to Rel", absoluteFilePath, inputRelativePath.relativePath ); let outputFileName = path.join( this.outputDir, inputRelativePath.relativePath ); templates.templates.push( inputRelativePath.relativePath ); let content = fs.readFileSync( p.absolutePath, "utf-8" ); // RJLog.log( "Adding", p.absolutePath, outputFileName ); compilation.assets[ outputFileName ] = { source: () => content, size: () => content.length, }; return Promise.resolve(); } ); let templatesPath = path.join( this.outputDir, "index.json" ); let templatesJSON = JSON.stringify( templates, null, " " ); compilation.assets[ templatesPath ] = { source: () => templatesJSON, size: () => templatesJSON.length, }; callback(); return Promise.resolve(); } ); } }