/* Most of the work this module does is putting an HTML-oriented facade around Webpack. That is, we want both the input and output to be primarily HTML files with proper spec semantics, and we use webpack to optimize the assets referred to by those files. While there are webpack plugins for handling HTML, none of them handle multiple HTML entrypoints and apply correct HTML semantics (for example, getting script vs module context correct). */ import type { BundleSummary, Packager, PackagerConstructor, Variant, ResolverOptions } from '@embroider/core'; import { HTMLEntrypoint, getPackagerCacheDir, getOrCreate } from '@embroider/core'; import { locateEmbroiderWorkingDir, RewrittenPackageCache, tmpdir } from '@embroider/shared-internals'; import type { Configuration, RuleSetUseItem, WebpackPluginInstance } from 'webpack'; import webpack from 'webpack'; import type { Stats } from 'fs-extra'; import { readFileSync, outputFileSync, copySync, statSync, readJSONSync } from 'fs-extra'; import { join, dirname, relative, sep } from 'path'; import isEqual from 'lodash/isEqual'; import mergeWith from 'lodash/mergeWith'; import flatMap from 'lodash/flatMap'; import MiniCssExtractPlugin from 'mini-css-extract-plugin'; import makeDebug from 'debug'; import { format } from 'util'; import { warmup as threadLoaderWarmup } from 'thread-loader'; import type { Options, BabelLoaderOptions } from './options'; import crypto from 'crypto'; import semverSatisfies from 'semver/functions/satisfies'; import supportsColor from 'supports-color'; import type { Options as HbsLoaderOptions } from '@embroider/hbs-loader'; import type { Options as EmbroiderPluginOptions } from './webpack-resolver-plugin'; import { EmbroiderPlugin } from './webpack-resolver-plugin'; import type Terser from 'terser'; const debug = makeDebug('embroider:debug'); interface AppInfo { entrypoints: HTMLEntrypoint[]; otherAssets: string[]; rootURL: string; publicAssetURL: string; resolverConfig: ResolverOptions; packageName: string; } // AppInfos are equal if they result in the same webpack config. function equalAppInfo(left: AppInfo, right: AppInfo): boolean { return ( left.entrypoints.length === right.entrypoints.length && left.entrypoints.every((e, index) => isEqual(e.modules, right.entrypoints[index].modules)) ); } type BeginFn = (total: number) => void; type IncrementFn = () => Promise; function createBarrier(): [BeginFn, IncrementFn] { const barriers: Array<[() => void, (e: unknown) => void]> = []; let done = true; let limit = 0; return [begin, increment]; function begin(newLimit: number) { if (!done) flush(new Error('begin called before limit reached')); done = false; limit = newLimit; } async function increment() { if (done) { throw new Error('increment after limit reach'); } const promise = new Promise((resolve, reject) => { barriers.push([resolve, reject]); }); if (barriers.length === limit) { flush(); } await promise; } function flush(err?: Error) { for (const [resolve, reject] of barriers) { if (err) reject(err); else resolve(); } barriers.length = 0; done = true; } } // we want to ensure that not only does our instance conform to // PackagerInstance, but our constructor conforms to Packager. So instead of // just exporting our class directly, we export a const constructor of the // correct type. const Webpack: PackagerConstructor = class Webpack implements Packager { static annotation = '@embroider/webpack'; private pathToVanillaApp: string; private extraConfig: Configuration | undefined; private passthroughCache: Map = new Map(); private publicAssetURL: string | undefined; private extraThreadLoaderOptions: object | false | undefined; private extraBabelLoaderOptions: BabelLoaderOptions | undefined; private extraCssLoaderOptions: object | undefined; private extraCssPluginOptions: object | undefined; private extraStyleLoaderOptions: object | undefined; private _bundleSummary: BundleSummary | undefined; private beginBarrier: BeginFn; private incrementBarrier: IncrementFn; constructor( private appRoot: string, private outputPath: string, private variants: Variant[], private consoleWrite: (msg: string) => void, options?: Options ) { if (!semverSatisfies(webpack.version, '^5.0.0')) { throw new Error(`@embroider/webpack requires webpack@^5.0.0, but found version ${webpack.version}`); } let packageCache = RewrittenPackageCache.shared('embroider', appRoot); this.pathToVanillaApp = packageCache.maybeMoved(packageCache.get(appRoot)).root; this.extraConfig = options?.webpackConfig; this.publicAssetURL = options?.publicAssetURL; this.extraThreadLoaderOptions = options?.threadLoaderOptions; this.extraBabelLoaderOptions = options?.babelLoaderOptions; this.extraCssLoaderOptions = options?.cssLoaderOptions; this.extraCssPluginOptions = options?.cssPluginOptions; this.extraStyleLoaderOptions = options?.styleLoaderOptions; [this.beginBarrier, this.incrementBarrier] = createBarrier(); warmUp(this.extraThreadLoaderOptions); } get bundleSummary(): BundleSummary { let bundleSummary = this._bundleSummary; if (bundleSummary === undefined) { this._bundleSummary = bundleSummary = { entrypoints: new Map(), lazyBundles: new Map(), variants: this.variants, }; } return bundleSummary; } async build(): Promise { this._bundleSummary = undefined; this.beginBarrier(this.variants.length); let appInfo = this.examineApp(); let webpack = this.getWebpack(appInfo); await this.runWebpack(webpack); } private examineApp(): AppInfo { // @ts-expect-error webpack is not updated to work on @embroider/core 4.x let meta = getAppMeta(this.pathToVanillaApp); let rootURL = meta['ember-addon']['root-url']; let entrypoints = []; let otherAssets = []; let publicAssetURL = this.publicAssetURL || rootURL; for (let relativePath of meta['ember-addon'].assets) { if (/\.html/i.test(relativePath)) { entrypoints.push(new HTMLEntrypoint(this.pathToVanillaApp, rootURL, publicAssetURL, relativePath)); } else { otherAssets.push(relativePath); } } let resolverConfig: EmbroiderPluginOptions = readJSONSync( join(locateEmbroiderWorkingDir(this.appRoot), 'resolver.json') ); return { entrypoints, otherAssets, rootURL, resolverConfig, publicAssetURL, packageName: meta.name }; } private configureWebpack(appInfo: AppInfo, variant: Variant, variantIndex: number): Configuration { const { entrypoints, publicAssetURL, packageName, resolverConfig } = appInfo; let entry: { [name: string]: string } = {}; for (let entrypoint of entrypoints) { for (let moduleName of entrypoint.modules) { entry[moduleName] = './' + moduleName; } } let { plugins: stylePlugins, loaders: styleLoaders } = this.setupStyleConfig(variant); let babelLoaderOptions = makeBabelLoaderOptions( variant, join(this.appRoot, 'babel.config.cjs'), this.extraBabelLoaderOptions ); let babelLoaderPrefix = `babel-loader-9?${JSON.stringify(babelLoaderOptions.options)}!`; return { mode: variant.optimizeForProduction ? 'production' : 'development', context: this.pathToVanillaApp, entry, performance: { hints: false, }, plugins: [ ...stylePlugins, new EmbroiderPlugin(resolverConfig, babelLoaderPrefix), compiler => { compiler.hooks.done.tapPromise('EmbroiderPlugin', async stats => { this.summarizeStats(stats, variant, variantIndex); await this.writeFiles(this.bundleSummary, this.lastAppInfo!, variantIndex); }); }, ], node: false, module: { rules: [ { test: /\.hbs$/, use: nonNullArray([ maybeThreadLoader(this.extraThreadLoaderOptions), babelLoaderOptions, { loader: require.resolve('@embroider/hbs-loader'), options: (() => { let options: HbsLoaderOptions = { compatModuleNaming: { rootDir: this.pathToVanillaApp, modulePrefix: packageName, }, }; return options; })(), }, ]), }, { use: nonNullArray([ maybeThreadLoader(this.extraThreadLoaderOptions), makeBabelLoaderOptions(variant, join(this.appRoot, 'babel.config.cjs'), this.extraBabelLoaderOptions), ]), }, { test: isCSS, use: styleLoaders, }, ], }, output: { path: join(this.outputPath), filename: `assets/chunk.[chunkhash].js`, chunkFilename: `assets/chunk.[chunkhash].js`, publicPath: publicAssetURL, }, optimization: { splitChunks: { chunks: 'all', }, }, resolve: { extensions: resolverConfig.resolvableExtensions, }, resolveLoader: { alias: { // these loaders are our dependencies, not the app's dependencies. I'm // not overriding the default loader resolution rules in case the app also // wants to control those. 'thread-loader': require.resolve('thread-loader'), 'babel-loader-9': require.resolve('@embroider/babel-loader-9'), 'css-loader': require.resolve('css-loader'), 'style-loader': require.resolve('style-loader'), }, }, experiments: { // this is needed because fasboot-only modules need to use await import() topLevelAwait: true, }, }; } private lastAppInfo: AppInfo | undefined; private lastWebpack: webpack.MultiCompiler | undefined; private getWebpack(appInfo: AppInfo) { if (this.lastWebpack && this.lastAppInfo && equalAppInfo(appInfo, this.lastAppInfo)) { debug(`reusing webpack config`); // the appInfos result in equal webpack configs so we don't need to // reconfigure webpack. But they may contain other changes (like HTML // content changes that don't alter the webpack config) so we still want // lastAppInfo to update so that the latest one will be seen in the // webpack post-build. this.lastAppInfo = appInfo; return this.lastWebpack; } debug(`configuring webpack`); let config = this.variants.map((variant, variantIndex) => mergeWith({}, this.configureWebpack(appInfo, variant, variantIndex), this.extraConfig, appendArrays) ); this.lastAppInfo = appInfo; return (this.lastWebpack = webpack(config as any)! as any); } private async writeScript(script: string, written: Set, variant: Variant) { if (!variant.optimizeForProduction) { this.copyThrough(script); return script; } // loading these lazily here so they never load in non-production builds. // The node cache will ensures we only load them once. const [Terser, srcURL] = await Promise.all([import('terser'), import('source-map-url')]); let inCode = readFileSync(join(this.pathToVanillaApp, script), 'utf8'); let terserOpts: Terser.MinifyOptions = {}; let fileRelativeSourceMapURL; let appRelativeSourceMapURL; if (srcURL.default.existsIn(inCode)) { fileRelativeSourceMapURL = srcURL.default.getFrom(inCode)!; appRelativeSourceMapURL = join(dirname(script), fileRelativeSourceMapURL); let content; try { content = readJSONSync(join(this.pathToVanillaApp, appRelativeSourceMapURL)); } catch { // the script refers to a sourcemap that doesn't exist, so we just leave // the map out. } if (content) { terserOpts.sourceMap = { content, url: fileRelativeSourceMapURL }; } } let { code: outCode, map: outMap } = await Terser.minify(inCode, terserOpts); let finalFilename = this.getFingerprintedFilename(script, outCode!); outputFileSync(join(this.outputPath, finalFilename), outCode!); written.add(script); if (appRelativeSourceMapURL && outMap) { outputFileSync(join(this.outputPath, appRelativeSourceMapURL), outMap); written.add(appRelativeSourceMapURL); } return finalFilename; } private async writeStyle(style: string, written: Set, variant: Variant) { if (!variant.optimizeForProduction) { this.copyThrough(style); written.add(style); return style; } const csso = await import('csso'); const cssContent = readFileSync(join(this.pathToVanillaApp, style), 'utf8'); const minifiedCss = csso.minify(cssContent).css; let finalFilename = this.getFingerprintedFilename(style, minifiedCss); outputFileSync(join(this.outputPath, finalFilename), minifiedCss); written.add(style); return finalFilename; } private async provideErrorContext(message: string, messageParams: any[], fn: () => Promise) { try { return await fn(); } catch (err) { let context = format(message, ...messageParams); err.message = context + ': ' + err.message; throw err; } } private async writeFiles(stats: BundleSummary, { entrypoints, otherAssets }: AppInfo, variantIndex: number) { // we're doing this ourselves because I haven't seen a webpack 4 HTML plugin // that handles multiple HTML entrypoints correctly. let written: Set = new Set(); // scripts (as opposed to modules) and stylesheets (as opposed to CSS // modules that are imported from JS modules) get passed through without // going through webpack. for (let entrypoint of entrypoints) { await this.provideErrorContext('needed by %s', [entrypoint.filename], async () => { for (let script of entrypoint.scripts) { if (!stats.entrypoints.has(script)) { const mapping = [] as string[]; try { // zero here means we always attribute passthrough scripts to the // first build variant stats.entrypoints.set(script, new Map([[0, mapping]])); mapping.push(await this.writeScript(script, written, this.variants[0])); } catch (err) { if (err.code === 'ENOENT' && err.path === join(this.pathToVanillaApp, script)) { this.consoleWrite( `warning: in ${entrypoint.filename}