'use strict';

const fs = require( 'fs' );
const path = require( 'path' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );

/**
 * Entry points, keyed by output name.
 *
 * Sources that are not present are skipped so that a distribution containing
 * only a subset of them still builds with `npx wp-scripts build`.
 */
const candidates = {
	admin: 'resources/admin.ts',
	frontend: 'resources/frontend.ts',
	'admin-pro__premium_only': 'resources/admin-pro__premium_only.tsx',
	'frontend-pro__premium_only': 'resources/frontend-pro__premium_only.ts',
};

const entry = Object.keys( candidates ).reduce( function ( entries, name ) {
	const source = path.resolve( __dirname, candidates[ name ] );
	if ( fs.existsSync( source ) ) {
		entries[ name ] = source;
	}
	return entries;
}, {} );

/**
 * `@wordpress/scripts` adds CleanWebpackPlugin, which empties the output
 * directory and would delete the packaged icons and asset manifest that live
 * alongside the bundles. Drop it and use webpack's own cleaning instead, so
 * only generated bundles are replaced.
 */
const plugins = ( defaultConfig.plugins || [] ).filter( function ( plugin ) {
	return plugin.constructor.name !== 'CleanWebpackPlugin';
} );

module.exports = {
	...defaultConfig,
	entry,
	plugins,
	output: {
		...defaultConfig.output,
		clean: {
			keep: function ( asset ) {
				return ! /\.(?:js|css)$|\.asset\.php$/.test( asset );
			},
		},
		filename: '[name].js',
		path: path.resolve( __dirname, 'public' ),
	},
	optimization: {
		...defaultConfig.optimization,
		runtimeChunk: false,
		splitChunks: false,
	},
	performance: {
		hints: 'warning',
		maxAssetSize: 256 * 1024,
		// The authenticated Pro editor loads its preview CSS with the editor.
		// Keep a narrow combined budget while retaining the stricter per-file cap.
		maxEntrypointSize: 288 * 1024,
		assetFilter: function ( filename ) {
			return (
				! /-rtl\.css$/.test( filename ) &&
				! /\.asset\.php$/.test( filename )
			);
		},
	},
};
