You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

775 lines
20 KiB

3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
2 years ago
5 years ago
5 years ago
5 years ago
2 years ago
5 years ago
5 years ago
5 years ago
5 years ago
2 years ago
2 years ago
2 years ago
2 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. //@ts-check
  2. /** @typedef {import('webpack').Configuration} WebpackConfig **/
  3. const { spawnSync } = require('child_process');
  4. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  5. const CircularDependencyPlugin = require('circular-dependency-plugin');
  6. const { CleanWebpackPlugin: CleanPlugin } = require('clean-webpack-plugin');
  7. const CopyPlugin = require('copy-webpack-plugin');
  8. const CspHtmlPlugin = require('csp-html-webpack-plugin');
  9. const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
  10. const esbuild = require('esbuild');
  11. const { EsbuildPlugin } = require('esbuild-loader');
  12. const { generateFonts } = require('fantasticon');
  13. const ForkTsCheckerPlugin = require('fork-ts-checker-webpack-plugin');
  14. const fs = require('fs');
  15. const HtmlPlugin = require('html-webpack-plugin');
  16. const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
  17. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  18. const path = require('path');
  19. const { validate } = require('schema-utils');
  20. const TerserPlugin = require('terser-webpack-plugin');
  21. const { WebpackError, optimize, webpack } = require('webpack');
  22. const WebpackRequireFromPlugin = require('webpack-require-from');
  23. module.exports =
  24. /**
  25. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; esbuildMinify?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  26. * @param {{ mode: 'production' | 'development' | 'none' | undefined }} argv
  27. * @returns { WebpackConfig[] }
  28. */
  29. function (env, argv) {
  30. const mode = argv.mode || 'none';
  31. env = {
  32. analyzeBundle: false,
  33. analyzeDeps: false,
  34. esbuild: true,
  35. esbuildMinify: false,
  36. useSharpForImageOptimization: true,
  37. ...env,
  38. };
  39. return [
  40. getExtensionConfig('node', mode, env),
  41. getExtensionConfig('webworker', mode, env),
  42. getWebviewsConfig(mode, env),
  43. ];
  44. };
  45. /**
  46. * @param { 'node' | 'webworker' } target
  47. * @param { 'production' | 'development' | 'none' } mode
  48. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; esbuildMinify?: boolean; useSharpForImageOptimization?: boolean }} env
  49. * @returns { WebpackConfig }
  50. */
  51. function getExtensionConfig(target, mode, env) {
  52. /**
  53. * @type WebpackConfig['plugins'] | any
  54. */
  55. const plugins = [
  56. new CleanPlugin({ cleanOnceBeforeBuildPatterns: ['!dist/webviews/**'] }),
  57. new ForkTsCheckerPlugin({
  58. async: false,
  59. eslint: {
  60. enabled: true,
  61. files: 'src/**/*.ts?(x)',
  62. options: {
  63. cache: true,
  64. cacheLocation: path.join(__dirname, '.eslintcache/', target === 'webworker' ? 'browser/' : ''),
  65. cacheStrategy: 'content',
  66. fix: mode !== 'production',
  67. overrideConfigFile: path.join(
  68. __dirname,
  69. target === 'webworker' ? '.eslintrc.browser.json' : '.eslintrc.json',
  70. ),
  71. },
  72. },
  73. formatter: 'basic',
  74. typescript: {
  75. configFile: path.join(__dirname, target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json'),
  76. },
  77. }),
  78. ];
  79. if (target === 'webworker') {
  80. plugins.push(new optimize.LimitChunkCountPlugin({ maxChunks: 1 }));
  81. } else {
  82. // Ensure that the dist folder exists otherwise the FantasticonPlugin will fail
  83. const dist = path.join(__dirname, 'dist');
  84. if (!fs.existsSync(dist)) {
  85. fs.mkdirSync(dist);
  86. }
  87. plugins.push(
  88. new FantasticonPlugin({
  89. configPath: '.fantasticonrc.js',
  90. onBefore: () =>
  91. spawnSync('yarn', ['run', 'icons:svgo'], {
  92. cwd: __dirname,
  93. encoding: 'utf8',
  94. shell: true,
  95. }),
  96. onComplete: () =>
  97. spawnSync('yarn', ['run', 'icons:apply'], {
  98. cwd: __dirname,
  99. encoding: 'utf8',
  100. shell: true,
  101. }),
  102. }),
  103. );
  104. }
  105. if (env.analyzeDeps) {
  106. plugins.push(
  107. new CircularDependencyPlugin({
  108. cwd: __dirname,
  109. exclude: /node_modules/,
  110. failOnError: false,
  111. onDetected: function ({ module: _webpackModuleRecord, paths, compilation }) {
  112. if (paths.some(p => p.includes('container.ts'))) return;
  113. // @ts-ignore
  114. compilation.warnings.push(new WebpackError(paths.join(' -> ')));
  115. },
  116. }),
  117. );
  118. }
  119. if (env.analyzeBundle) {
  120. plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 'auto' }));
  121. }
  122. return {
  123. name: `extension:${target}`,
  124. entry: {
  125. extension: './src/extension.ts',
  126. },
  127. mode: mode,
  128. target: target,
  129. devtool: mode === 'production' ? false : 'source-map',
  130. output: {
  131. chunkFilename: 'feature-[name].js',
  132. filename: 'gitlens.js',
  133. libraryTarget: 'commonjs2',
  134. path: target === 'webworker' ? path.join(__dirname, 'dist', 'browser') : path.join(__dirname, 'dist'),
  135. },
  136. optimization: {
  137. minimizer: [
  138. env.esbuildMinify
  139. ? new EsbuildPlugin({
  140. drop: ['debugger'],
  141. format: 'cjs',
  142. // Keep the class names otherwise @log won't provide a useful name
  143. keepNames: true,
  144. legalComments: 'none',
  145. minify: true,
  146. target: 'es2022',
  147. treeShaking: true,
  148. })
  149. : new TerserPlugin({
  150. extractComments: false,
  151. parallel: true,
  152. terserOptions: {
  153. compress: {
  154. drop_debugger: true,
  155. ecma: 2020,
  156. module: true,
  157. },
  158. ecma: 2020,
  159. format: {
  160. comments: false,
  161. ecma: 2020,
  162. },
  163. // Keep the class names otherwise @log won't provide a useful name
  164. keep_classnames: true,
  165. module: true,
  166. },
  167. }),
  168. ],
  169. splitChunks:
  170. target === 'webworker'
  171. ? false
  172. : {
  173. // Disable all non-async code splitting
  174. chunks: () => false,
  175. cacheGroups: {
  176. default: false,
  177. vendors: false,
  178. },
  179. },
  180. },
  181. externals: {
  182. vscode: 'commonjs vscode',
  183. },
  184. module: {
  185. rules: [
  186. {
  187. exclude: /\.d\.ts$/,
  188. include: path.join(__dirname, 'src'),
  189. test: /\.tsx?$/,
  190. use: env.esbuild
  191. ? {
  192. loader: 'esbuild-loader',
  193. options: {
  194. format: 'esm',
  195. implementation: esbuild,
  196. target: ['es2022', 'chrome102', 'node16.14.2'],
  197. tsconfig: path.join(
  198. __dirname,
  199. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  200. ),
  201. },
  202. }
  203. : {
  204. loader: 'ts-loader',
  205. options: {
  206. configFile: path.join(
  207. __dirname,
  208. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  209. ),
  210. experimentalWatchApi: true,
  211. transpileOnly: true,
  212. },
  213. },
  214. },
  215. ],
  216. },
  217. resolve: {
  218. alias: {
  219. '@env': path.resolve(__dirname, 'src', 'env', target === 'webworker' ? 'browser' : target),
  220. // This dependency is very large, and isn't needed for our use-case
  221. tr46: path.resolve(__dirname, 'patches', 'tr46.js'),
  222. // Stupid dependency that is used by `http-proxy-agent`
  223. debug:
  224. target === 'webworker'
  225. ? path.resolve(__dirname, 'node_modules', 'debug', 'src', 'browser.js')
  226. : path.resolve(__dirname, 'node_modules', 'debug', 'src', 'node.js'),
  227. },
  228. fallback:
  229. target === 'webworker'
  230. ? { path: require.resolve('path-browserify'), os: require.resolve('os-browserify/browser') }
  231. : undefined,
  232. mainFields: target === 'webworker' ? ['browser', 'module', 'main'] : ['module', 'main'],
  233. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  234. },
  235. plugins: plugins,
  236. infrastructureLogging:
  237. mode === 'production'
  238. ? undefined
  239. : {
  240. level: 'log', // enables logging required for problem matchers
  241. },
  242. stats: {
  243. preset: 'errors-warnings',
  244. assets: true,
  245. assetsSort: 'name',
  246. assetsSpace: 100,
  247. colors: true,
  248. env: true,
  249. errorsCount: true,
  250. warningsCount: true,
  251. timings: true,
  252. },
  253. };
  254. }
  255. /**
  256. * @param { 'production' | 'development' | 'none' } mode
  257. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; esbuildMinify?: boolean; useSharpForImageOptimization?: boolean }} env
  258. * @returns { WebpackConfig }
  259. */
  260. function getWebviewsConfig(mode, env) {
  261. const basePath = path.join(__dirname, 'src', 'webviews', 'apps');
  262. /** @type WebpackConfig['plugins'] | any */
  263. const plugins = [
  264. new CleanPlugin(
  265. mode === 'production'
  266. ? {
  267. cleanOnceBeforeBuildPatterns: [
  268. path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews', 'media', '**'),
  269. ],
  270. dangerouslyAllowCleanPatternsOutsideProject: true,
  271. dry: false,
  272. }
  273. : undefined,
  274. ),
  275. new ForkTsCheckerPlugin({
  276. async: false,
  277. eslint: {
  278. enabled: true,
  279. files: path.join(basePath, '**', '*.ts?(x)'),
  280. options: {
  281. cache: true,
  282. cacheLocation: path.join(__dirname, '.eslintcache', 'webviews/'),
  283. cacheStrategy: 'content',
  284. fix: mode !== 'production',
  285. },
  286. },
  287. formatter: 'basic',
  288. typescript: {
  289. configFile: path.join(basePath, 'tsconfig.json'),
  290. },
  291. }),
  292. new WebpackRequireFromPlugin({
  293. variableName: 'webpackResourceBasePath',
  294. }),
  295. new MiniCssExtractPlugin({ filename: '[name].css' }),
  296. getHtmlPlugin('commitDetails', false, mode, env),
  297. getHtmlPlugin('graph', true, mode, env),
  298. getHtmlPlugin('home', false, mode, env),
  299. getHtmlPlugin('rebase', false, mode, env),
  300. getHtmlPlugin('settings', false, mode, env),
  301. getHtmlPlugin('timeline', true, mode, env),
  302. getHtmlPlugin('welcome', false, mode, env),
  303. getCspHtmlPlugin(mode, env),
  304. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  305. new CopyPlugin({
  306. patterns: [
  307. {
  308. from: path.posix.join(basePath.replace(/\\/g, '/'), 'media', '*.*'),
  309. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  310. },
  311. {
  312. from: path.posix.join(
  313. __dirname.replace(/\\/g, '/'),
  314. 'node_modules',
  315. '@vscode',
  316. 'codicons',
  317. 'dist',
  318. 'codicon.ttf',
  319. ),
  320. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  321. },
  322. ],
  323. }),
  324. ];
  325. const imageGeneratorConfig = getImageMinimizerConfig(mode, env);
  326. if (mode !== 'production') {
  327. plugins.push(
  328. new ImageMinimizerPlugin({
  329. deleteOriginalAssets: true,
  330. generator: [imageGeneratorConfig],
  331. }),
  332. );
  333. }
  334. if (env.analyzeBundle) {
  335. plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 'auto' }));
  336. }
  337. return {
  338. name: 'webviews',
  339. context: basePath,
  340. entry: {
  341. commitDetails: './commitDetails/commitDetails.ts',
  342. graph: './plus/graph/graph.tsx',
  343. home: './home/home.ts',
  344. rebase: './rebase/rebase.ts',
  345. settings: './settings/settings.ts',
  346. timeline: './plus/timeline/timeline.ts',
  347. welcome: './welcome/welcome.ts',
  348. },
  349. mode: mode,
  350. target: 'web',
  351. devtool: mode === 'production' ? false : 'source-map',
  352. output: {
  353. chunkFilename: 'feature-[name].js',
  354. filename: '[name].js',
  355. libraryTarget: 'module',
  356. path: path.join(__dirname, 'dist', 'webviews'),
  357. publicPath: '#{root}/dist/webviews/',
  358. },
  359. experiments: {
  360. outputModule: true,
  361. },
  362. optimization: {
  363. minimizer:
  364. mode === 'production'
  365. ? [
  366. env.esbuildMinify
  367. ? new EsbuildPlugin({
  368. css: true,
  369. drop: ['debugger', 'console'],
  370. format: 'esm',
  371. // Keep the class names otherwise @log won't provide a useful name
  372. // keepNames: true,
  373. legalComments: 'none',
  374. minify: true,
  375. target: 'es2022',
  376. treeShaking: true,
  377. })
  378. : new TerserPlugin({
  379. extractComments: false,
  380. parallel: true,
  381. terserOptions: {
  382. compress: {
  383. drop_debugger: true,
  384. drop_console: true,
  385. ecma: 2020,
  386. module: true,
  387. },
  388. ecma: 2020,
  389. format: {
  390. comments: false,
  391. ecma: 2020,
  392. },
  393. // // Keep the class names otherwise @log won't provide a useful name
  394. // keep_classnames: true,
  395. module: true,
  396. },
  397. }),
  398. new ImageMinimizerPlugin({
  399. deleteOriginalAssets: true,
  400. generator: [imageGeneratorConfig],
  401. }),
  402. new CssMinimizerPlugin({
  403. minimizerOptions: {
  404. preset: [
  405. 'cssnano-preset-advanced',
  406. { discardUnused: false, mergeIdents: false, reduceIdents: false },
  407. ],
  408. },
  409. }),
  410. ]
  411. : [],
  412. splitChunks: {
  413. // Disable all non-async code splitting
  414. // chunks: () => false,
  415. cacheGroups: {
  416. default: false,
  417. vendors: false,
  418. },
  419. },
  420. },
  421. module: {
  422. rules: [
  423. {
  424. test: /\.m?js/,
  425. resolve: { fullySpecified: false },
  426. },
  427. {
  428. exclude: /\.d\.ts$/,
  429. include: path.join(__dirname, 'src'),
  430. test: /\.tsx?$/,
  431. use: env.esbuild
  432. ? {
  433. loader: 'esbuild-loader',
  434. options: {
  435. format: 'esm',
  436. implementation: esbuild,
  437. target: 'es2021',
  438. tsconfig: path.join(basePath, 'tsconfig.json'),
  439. },
  440. }
  441. : {
  442. loader: 'ts-loader',
  443. options: {
  444. configFile: path.join(basePath, 'tsconfig.json'),
  445. experimentalWatchApi: true,
  446. transpileOnly: true,
  447. },
  448. },
  449. },
  450. {
  451. test: /\.scss$/,
  452. use: [
  453. {
  454. loader: MiniCssExtractPlugin.loader,
  455. },
  456. {
  457. loader: 'css-loader',
  458. options: {
  459. sourceMap: mode !== 'production',
  460. url: false,
  461. },
  462. },
  463. {
  464. loader: 'sass-loader',
  465. options: {
  466. sourceMap: mode !== 'production',
  467. },
  468. },
  469. ],
  470. exclude: /node_modules/,
  471. },
  472. ],
  473. },
  474. resolve: {
  475. alias: {
  476. '@env': path.resolve(__dirname, 'src', 'env', 'browser'),
  477. '@microsoft/fast-foundation': path.resolve(
  478. __dirname,
  479. 'node_modules/@microsoft/fast-foundation/dist/esm/index.js',
  480. ),
  481. '@microsoft/fast-react-wrapper': path.resolve(
  482. __dirname,
  483. 'node_modules/@microsoft/fast-react-wrapper/dist/esm/index.js',
  484. ),
  485. react: path.resolve(__dirname, 'node_modules', 'react'),
  486. 'react-dom': path.resolve(__dirname, 'node_modules', 'react-dom'),
  487. tslib: path.resolve(__dirname, 'node_modules/tslib/tslib.es6.js'),
  488. },
  489. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  490. modules: [basePath, 'node_modules'],
  491. },
  492. plugins: plugins,
  493. infrastructureLogging:
  494. mode === 'production'
  495. ? undefined
  496. : {
  497. level: 'log', // enables logging required for problem matchers
  498. },
  499. stats: {
  500. preset: 'errors-warnings',
  501. assets: true,
  502. assetsSort: 'name',
  503. assetsSpace: 100,
  504. colors: true,
  505. env: true,
  506. errorsCount: true,
  507. excludeAssets: [/\.(ttf|webp)/],
  508. warningsCount: true,
  509. timings: true,
  510. },
  511. };
  512. }
  513. /**
  514. * @param { 'production' | 'development' | 'none' } mode
  515. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  516. * @returns { CspHtmlPlugin }
  517. */
  518. function getCspHtmlPlugin(mode, env) {
  519. const cspPlugin = new CspHtmlPlugin(
  520. {
  521. 'default-src': "'none'",
  522. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  523. 'script-src':
  524. mode !== 'production'
  525. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  526. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  527. 'style-src':
  528. mode === 'production'
  529. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  530. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  531. 'font-src': ['#{cspSource}'],
  532. },
  533. {
  534. enabled: true,
  535. hashingMethod: 'sha256',
  536. hashEnabled: {
  537. 'script-src': true,
  538. 'style-src': mode === 'production',
  539. },
  540. nonceEnabled: {
  541. 'script-src': true,
  542. 'style-src': mode === 'production',
  543. },
  544. },
  545. );
  546. // Override the nonce creation so we can dynamically generate them at runtime
  547. // @ts-ignore
  548. cspPlugin.createNonce = () => '#{cspNonce}';
  549. return cspPlugin;
  550. }
  551. /**
  552. * @param { 'production' | 'development' | 'none' } mode
  553. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  554. * @returns { ImageMinimizerPlugin.Generator<any> }
  555. */
  556. function getImageMinimizerConfig(mode, env) {
  557. /** @type ImageMinimizerPlugin.Generator<any> */
  558. // @ts-ignore
  559. return env.useSharpForImageOptimization
  560. ? {
  561. type: 'asset',
  562. implementation: ImageMinimizerPlugin.sharpGenerate,
  563. options: {
  564. encodeOptions: {
  565. webp: {
  566. lossless: true,
  567. },
  568. },
  569. },
  570. }
  571. : {
  572. type: 'asset',
  573. implementation: ImageMinimizerPlugin.imageminGenerate,
  574. options: {
  575. plugins: [
  576. [
  577. 'imagemin-webp',
  578. {
  579. lossless: true,
  580. nearLossless: 0,
  581. quality: 100,
  582. method: mode === 'production' ? 4 : 0,
  583. },
  584. ],
  585. ],
  586. },
  587. };
  588. }
  589. /**
  590. * @param { string } name
  591. * @param { boolean } plus
  592. * @param { 'production' | 'development' | 'none' } mode
  593. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  594. * @returns { HtmlPlugin }
  595. */
  596. function getHtmlPlugin(name, plus, mode, env) {
  597. return new HtmlPlugin({
  598. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  599. chunks: [name],
  600. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  601. inject: true,
  602. scriptLoading: 'module',
  603. inlineSource: mode === 'production' ? '.css$' : undefined,
  604. minify:
  605. mode === 'production'
  606. ? {
  607. removeComments: true,
  608. collapseWhitespace: true,
  609. removeRedundantAttributes: false,
  610. useShortDoctype: true,
  611. removeEmptyAttributes: true,
  612. removeStyleLinkTypeAttributes: true,
  613. keepClosingSlash: true,
  614. minifyCSS: true,
  615. }
  616. : false,
  617. });
  618. }
  619. class InlineChunkHtmlPlugin {
  620. constructor(htmlPlugin, patterns) {
  621. this.htmlPlugin = htmlPlugin;
  622. this.patterns = patterns;
  623. }
  624. getInlinedTag(publicPath, assets, tag) {
  625. if (
  626. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  627. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  628. ) {
  629. return tag;
  630. }
  631. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  632. if (publicPath) {
  633. chunkName = chunkName.replace(publicPath, '');
  634. }
  635. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  636. return tag;
  637. }
  638. const asset = assets[chunkName];
  639. if (asset == null) {
  640. return tag;
  641. }
  642. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  643. }
  644. apply(compiler) {
  645. let publicPath = compiler.options.output.publicPath || '';
  646. if (publicPath && !publicPath.endsWith('/')) {
  647. publicPath += '/';
  648. }
  649. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  650. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  651. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  652. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  653. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  654. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  655. });
  656. });
  657. }
  658. }
  659. const schema = {
  660. type: 'object',
  661. properties: {
  662. config: {
  663. type: 'object',
  664. },
  665. configPath: {
  666. type: 'string',
  667. },
  668. onBefore: {
  669. instanceof: 'Function',
  670. },
  671. onComplete: {
  672. instanceof: 'Function',
  673. },
  674. },
  675. };
  676. class FantasticonPlugin {
  677. alreadyRun = false;
  678. constructor(options = {}) {
  679. this.pluginName = 'fantasticon';
  680. this.options = options;
  681. validate(
  682. // @ts-ignore
  683. schema,
  684. options,
  685. {
  686. name: this.pluginName,
  687. baseDataPath: 'options',
  688. },
  689. );
  690. }
  691. /**
  692. * @param {import("webpack").Compiler} compiler
  693. */
  694. apply(compiler) {
  695. const {
  696. config = undefined,
  697. configPath = undefined,
  698. onBefore = undefined,
  699. onComplete = undefined,
  700. } = this.options;
  701. let loadedConfig;
  702. if (configPath) {
  703. try {
  704. loadedConfig = require(path.join(__dirname, configPath));
  705. } catch (ex) {
  706. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  707. }
  708. }
  709. if (!loadedConfig && !config) {
  710. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  711. return;
  712. }
  713. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  714. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  715. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  716. /**
  717. * @this {FantasticonPlugin}
  718. * @param {import("webpack").Compiler} compiler
  719. */
  720. async function generate(compiler) {
  721. if (compiler.watchMode) {
  722. if (this.alreadyRun) return;
  723. this.alreadyRun = true;
  724. }
  725. const logger = compiler.getInfrastructureLogger(this.pluginName);
  726. logger.log(`Generating icon font...`);
  727. await onBefore?.(fontConfig);
  728. await generateFonts(fontConfig);
  729. await onComplete?.(fontConfig);
  730. logger.log(`Generated icon font`);
  731. }
  732. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  733. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  734. }
  735. }