8
0

snippetadapter.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* eslint-env node */
  6. const path = require( 'path' );
  7. const fs = require( 'fs' );
  8. const minimatch = require( 'minimatch' );
  9. const webpack = require( 'webpack' );
  10. const { bundler, styles } = require( '@ckeditor/ckeditor5-dev-utils' );
  11. const CKEditorWebpackPlugin = require( '@ckeditor/ckeditor5-dev-webpack-plugin' );
  12. const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
  13. const TerserPlugin = require( 'terser-webpack-plugin' );
  14. const ProgressBarPlugin = require( 'progress-bar-webpack-plugin' );
  15. const DEFAULT_LANGUAGE = 'en';
  16. const MULTI_LANGUAGE = 'multi-language';
  17. /**
  18. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  19. * @param {Object} options
  20. * @param {Boolean} options.production Whether to build snippets in production mode.
  21. * @param {Array.<String>|undefined} options.allowedSnippets An array that contains glob patterns.
  22. * @param {Object.<String, Function>} umbertoHelpers
  23. * @returns {Promise}
  24. */
  25. module.exports = function snippetAdapter( snippets, options, umbertoHelpers ) {
  26. const { getSnippetPlaceholder, getSnippetSourcePaths } = umbertoHelpers;
  27. const snippetsDependencies = new Map();
  28. // For each snippet, load its config. If the snippet has defined dependencies, load those as well.
  29. for ( const snippetData of snippets ) {
  30. if ( !snippetData.snippetSources.js ) {
  31. throw new Error( `Missing snippet source for "${ snippetData.snippetName }".` );
  32. }
  33. snippetData.snippetConfig = readSnippetConfig( snippetData.snippetSources.js );
  34. snippetData.snippetConfig.language = snippetData.snippetConfig.language || DEFAULT_LANGUAGE;
  35. // If, in order to work, a snippet requires another snippet to be built, and the other snippet
  36. // isn't included in any guide via `{@snippet ...}`, then that other snippet need to be marked
  37. // as a dependency of the first one. Example – bootstrap UI uses an iframe, and inside that iframe we
  38. // need a JS file. That JS file needs to be built, even though it's not a real snippet (and it's not used
  39. // via {@snippet}).
  40. if ( snippetData.snippetConfig.dependencies ) {
  41. for ( const dependencyName of snippetData.snippetConfig.dependencies ) {
  42. // Do not load the same dependency more than once.
  43. if ( snippetsDependencies.has( dependencyName ) ) {
  44. continue;
  45. }
  46. // Find a root path where to look for the snippet's sources. We just want to pass it through Webpack.
  47. const snippetBasePathRegExp = new RegExp( snippetData.snippetName.replace( /\//g, '\\/' ) + '.*$' );
  48. const snippetBasePath = snippetData.snippetSources.js.replace( snippetBasePathRegExp, '' );
  49. const dependencySnippet = {
  50. snippetSources: getSnippetSourcePaths( snippetBasePath, dependencyName ),
  51. snippetName: dependencyName,
  52. outputPath: snippetData.outputPath,
  53. destinationPath: snippetData.destinationPath,
  54. requiredFor: snippetData
  55. };
  56. if ( !dependencySnippet.snippetSources.js ) {
  57. throw new Error( `Missing snippet source for "${ dependencySnippet.snippetName }".` );
  58. }
  59. dependencySnippet.snippetConfig = readSnippetConfig( dependencySnippet.snippetSources.js );
  60. dependencySnippet.snippetConfig.language = dependencySnippet.snippetConfig.language || DEFAULT_LANGUAGE;
  61. snippetsDependencies.set( dependencyName, dependencySnippet );
  62. }
  63. }
  64. }
  65. // Add all dependencies to the snippet collection.
  66. for ( const snippetData of snippetsDependencies.values() ) {
  67. snippets.add( snippetData );
  68. }
  69. // Remove snippets that do not match to patterns specified in `options.allowedSnippets`.
  70. if ( options.allowedSnippets ) {
  71. filterAllowedSnippets( snippets, options.allowedSnippets );
  72. }
  73. console.log( `Found ${ snippets.size } "{@snippet ...}" tags...` );
  74. console.log( `Building ${ countUniqueSnippets( snippets ) } snippets...` );
  75. const groupedSnippetsByLanguage = {};
  76. // Group snippets by language. There is no way to build different languages in a single Webpack process.
  77. // Webpack must be called as many times as different languages are being used in snippets.
  78. for ( const snippetData of snippets ) {
  79. // Multi-languages editors must be built separately.
  80. if ( snippetData.snippetConfig.additionalLanguages ) {
  81. snippetData.snippetConfig.additionalLanguages.push( snippetData.snippetConfig.language );
  82. snippetData.snippetConfig.language = MULTI_LANGUAGE;
  83. }
  84. if ( !groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] ) {
  85. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ] = new Set();
  86. }
  87. groupedSnippetsByLanguage[ snippetData.snippetConfig.language ].add( snippetData );
  88. }
  89. // For each language prepare own Webpack configuration.
  90. const webpackConfigs = Object.keys( groupedSnippetsByLanguage )
  91. .map( language => {
  92. return getWebpackConfig( groupedSnippetsByLanguage[ language ], {
  93. language,
  94. production: options.production,
  95. definitions: options.definitions || {}
  96. } );
  97. } );
  98. let promise = Promise.resolve();
  99. // Nothing to build.
  100. if ( !webpackConfigs.length ) {
  101. return promise;
  102. }
  103. for ( const config of webpackConfigs ) {
  104. promise = promise.then( () => runWebpack( config ) );
  105. }
  106. return promise
  107. .then( () => {
  108. // Group snippets by destination path in order to attach required HTML code and assets (CSS and JS).
  109. const groupedSnippetsByDestinationPath = {};
  110. for ( const snippetData of snippets ) {
  111. if ( !groupedSnippetsByDestinationPath[ snippetData.destinationPath ] ) {
  112. groupedSnippetsByDestinationPath[ snippetData.destinationPath ] = new Set();
  113. }
  114. groupedSnippetsByDestinationPath[ snippetData.destinationPath ].add( snippetData );
  115. }
  116. // For every page that contains at least one snippet, we need to replace Umberto comments with HTML code.
  117. for ( const destinationPath of Object.keys( groupedSnippetsByDestinationPath ) ) {
  118. const snippetsOnPage = groupedSnippetsByDestinationPath[ destinationPath ];
  119. // Assets required for the all snippets.
  120. const cssFiles = [];
  121. const jsFiles = [];
  122. let content = fs.readFileSync( destinationPath ).toString();
  123. for ( const snippetData of snippetsOnPage ) {
  124. // CSS may not be generated by Webpack if a snippet's JS file didn't import any CSS files.
  125. const wasCSSGenerated = fs.existsSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.css' ) );
  126. // If the snippet is a dependency, append JS and CSS to HTML, save to disk and continue.
  127. if ( snippetData.requiredFor ) {
  128. let htmlFile = fs.readFileSync( snippetData.snippetSources.html ).toString();
  129. if ( wasCSSGenerated ) {
  130. htmlFile += '<link rel="stylesheet" href="snippet.css" type="text/css">';
  131. }
  132. htmlFile += '<script src="snippet.js"></script>';
  133. fs.writeFileSync( path.join( snippetData.outputPath, snippetData.snippetName, 'snippet.html' ), htmlFile );
  134. continue;
  135. }
  136. let snippetHTML = fs.readFileSync( snippetData.snippetSources.html ).toString();
  137. if ( snippetHTML.trim() ) {
  138. snippetHTML = snippetHTML.replace( /%BASE_PATH%/g, snippetData.basePath );
  139. snippetHTML = `<div class="live-snippet">${ snippetHTML }</div>`;
  140. }
  141. content = content.replace( getSnippetPlaceholder( snippetData.snippetName ), snippetHTML );
  142. jsFiles.push( path.join( snippetData.basePath, 'assets', 'snippet.js' ) );
  143. jsFiles.push( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.js' ) );
  144. cssFiles.push( path.join( snippetData.basePath, 'assets', 'snippet-styles.css' ) );
  145. if ( wasCSSGenerated ) {
  146. cssFiles.unshift( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.css' ) );
  147. }
  148. // Additional languages must be imported by the HTML code.
  149. if ( snippetData.snippetConfig.additionalLanguages ) {
  150. snippetData.snippetConfig.additionalLanguages.forEach( language => {
  151. jsFiles.push( path.join( snippetData.relativeOutputPath, 'translations', `${ language }.js` ) );
  152. } );
  153. }
  154. }
  155. const cssImportsHTML = getHTMLImports( cssFiles, importPath => {
  156. return ` <link rel="stylesheet" href="${ importPath }" type="text/css">`;
  157. } );
  158. const jsImportsHTML = getHTMLImports( jsFiles, importPath => {
  159. return ` <script src="${ importPath }"></script>`;
  160. } );
  161. content = content.replace( '<!--UMBERTO: SNIPPET: CSS-->', cssImportsHTML );
  162. content = content.replace( '<!--UMBERTO: SNIPPET: JS-->', jsImportsHTML );
  163. fs.writeFileSync( destinationPath, content );
  164. }
  165. } )
  166. .then( () => {
  167. console.log( 'Finished building snippets.' );
  168. } );
  169. };
  170. /**
  171. * Removes snippets that names do not match to patterns specified in `allowedSnippets` array.
  172. *
  173. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  174. * @param {Array.<String>|undefined} allowedSnippets Snippet patterns that should be built.
  175. */
  176. function filterAllowedSnippets( snippets, allowedSnippets ) {
  177. if ( !allowedSnippets.length ) {
  178. return;
  179. }
  180. const snippetsToBuild = new Set();
  181. // Find all snippets that matched to specified criteria.
  182. for ( const snippetData of snippets ) {
  183. const shouldBeBuilt = allowedSnippets.some( pattern => {
  184. return minimatch( snippetData.snippetName, pattern ) || snippetData.snippetName.includes( pattern );
  185. } );
  186. if ( shouldBeBuilt ) {
  187. snippetsToBuild.add( snippetData );
  188. }
  189. }
  190. // Find all dependencies that are required for whitelisted snippets.
  191. for ( const snippetData of snippets ) {
  192. if ( snippetsToBuild.has( snippetData ) ) {
  193. continue;
  194. }
  195. if ( snippetData.requiredFor && snippetsToBuild.has( snippetData.requiredFor ) ) {
  196. snippetsToBuild.add( snippetData );
  197. }
  198. }
  199. // Remove snippets that won't be built and aren't dependencies of other snippets.
  200. for ( const snippetData of snippets ) {
  201. if ( !snippetsToBuild.has( snippetData ) ) {
  202. snippets.delete( snippetData );
  203. }
  204. }
  205. }
  206. /**
  207. * Prepares configuration for Webpack.
  208. *
  209. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  210. * @param {Object} config
  211. * @param {String} config.language Language for the build.
  212. * @param {Boolean} config.production Whether to build for production.
  213. * @param {Object} config.definitions
  214. * @returns {Object}
  215. */
  216. function getWebpackConfig( snippets, config ) {
  217. // Stringify all definitions values. The `DefinePlugin` injects definition values as they are so we need to stringify them,
  218. // so they will become real strings in the generated code. See https://webpack.js.org/plugins/define-plugin/ for more information.
  219. const definitions = {};
  220. for ( const definitionKey in config.definitions ) {
  221. definitions[ definitionKey ] = JSON.stringify( config.definitions[ definitionKey ] );
  222. }
  223. const ckeditorWebpackPluginOptions = {
  224. // All translation files are added to HTML files directly later.
  225. buildAllTranslationsToSeparateFiles: true
  226. };
  227. if ( config.language === MULTI_LANGUAGE ) {
  228. const additionalLanguages = new Set();
  229. // Find all additional languages that must be built.
  230. for ( const snippetData of snippets ) {
  231. for ( const language of snippetData.snippetConfig.additionalLanguages ) {
  232. additionalLanguages.add( language );
  233. }
  234. }
  235. // Pass unique values of `additionalLanguages` to `CKEditorWebpackPlugin`.
  236. ckeditorWebpackPluginOptions.additionalLanguages = [ ...additionalLanguages ];
  237. // Also, set the default language because of the warning that comes from the plugin.
  238. ckeditorWebpackPluginOptions.language = DEFAULT_LANGUAGE;
  239. } else {
  240. ckeditorWebpackPluginOptions.language = config.language;
  241. }
  242. const webpackConfig = {
  243. mode: config.production ? 'production' : 'development',
  244. devtool: 'source-map',
  245. entry: {},
  246. output: {
  247. filename: '[name]/snippet.js'
  248. },
  249. optimization: {
  250. minimizer: [
  251. new TerserPlugin( {
  252. sourceMap: true,
  253. terserOptions: {
  254. output: {
  255. // Preserve CKEditor 5 license comments.
  256. comments: /^!/
  257. }
  258. },
  259. extractComments: false
  260. } )
  261. ]
  262. },
  263. plugins: [
  264. new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
  265. new CKEditorWebpackPlugin( ckeditorWebpackPluginOptions ),
  266. new webpack.BannerPlugin( {
  267. banner: bundler.getLicenseBanner(),
  268. raw: true
  269. } ),
  270. new webpack.DefinePlugin( definitions ),
  271. new ProgressBarPlugin( {
  272. format: `Building snippets for language "${ config.language }": :percent (:msg)`
  273. } )
  274. ],
  275. // Configure the paths so building CKEditor 5 snippets work even if the script
  276. // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
  277. resolve: {
  278. modules: getModuleResolvePaths()
  279. },
  280. resolveLoader: {
  281. modules: getModuleResolvePaths()
  282. },
  283. module: {
  284. rules: [
  285. {
  286. test: /\.svg$/,
  287. use: [ 'raw-loader' ]
  288. },
  289. {
  290. test: /\.css$/,
  291. use: [
  292. MiniCssExtractPlugin.loader,
  293. 'css-loader',
  294. {
  295. loader: 'postcss-loader',
  296. options: styles.getPostCssConfig( {
  297. themeImporter: {
  298. themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
  299. },
  300. minify: config.production
  301. } )
  302. }
  303. ]
  304. }
  305. ]
  306. }
  307. };
  308. for ( const snippetData of snippets ) {
  309. if ( !webpackConfig.output.path ) {
  310. webpackConfig.output.path = snippetData.outputPath;
  311. }
  312. if ( webpackConfig.entry[ snippetData.snippetName ] ) {
  313. continue;
  314. }
  315. webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
  316. }
  317. return webpackConfig;
  318. }
  319. /**
  320. * Builds snippets.
  321. *
  322. * @param {Object} webpackConfig
  323. * @returns {Promise}
  324. */
  325. function runWebpack( webpackConfig ) {
  326. return new Promise( ( resolve, reject ) => {
  327. webpack( webpackConfig, ( err, stats ) => {
  328. if ( err ) {
  329. reject( err );
  330. } else if ( stats.hasErrors() ) {
  331. reject( new Error( stats.toString() ) );
  332. } else {
  333. resolve();
  334. }
  335. } );
  336. } );
  337. }
  338. /**
  339. * @returns {Array.<String>}
  340. */
  341. function getModuleResolvePaths() {
  342. return [
  343. path.resolve( __dirname, '..', '..', 'node_modules' ),
  344. 'node_modules'
  345. ];
  346. }
  347. /**
  348. * Reads the snippet's configuration.
  349. *
  350. * @param {String} snippetSourcePath An absolute path to the file.
  351. * @returns {Object}
  352. */
  353. function readSnippetConfig( snippetSourcePath ) {
  354. const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
  355. const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
  356. if ( !configSourceMatch ) {
  357. return {};
  358. }
  359. return JSON.parse( configSourceMatch[ 1 ] );
  360. }
  361. /**
  362. * Removes duplicated entries specified in `files` array and map those entires using `mapFunction`.
  363. *
  364. * @param {Array.<String>} files Paths collection.
  365. * @param {Function} mapFunction Function that should return a string.
  366. * @returns {String}
  367. */
  368. function getHTMLImports( files, mapFunction ) {
  369. return [ ...new Set( files ) ]
  370. .map( mapFunction )
  371. .join( '\n' )
  372. .replace( /^\s+/, '' );
  373. }
  374. /**
  375. * Returns a number of unique snippet names that will be built.
  376. *
  377. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  378. * @returns {Number}
  379. */
  380. function countUniqueSnippets( snippets ) {
  381. const uniqueSnippetNames = new Set();
  382. for ( const snippet of snippets ) {
  383. uniqueSnippetNames.add( snippet.snippetName );
  384. }
  385. return uniqueSnippetNames.size;
  386. }
  387. /**
  388. * @typedef {Object} Snippet
  389. *
  390. * @property {SnippetSource} snippetSources Sources of the snippet.
  391. *
  392. * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
  393. *
  394. * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
  395. *
  396. * @property {String} destinationPath An absolute path to the file where the snippet is being used.
  397. *
  398. * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
  399. *
  400. * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
  401. *
  402. * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
  403. *
  404. * @property {Snippet|undefined} [requiredFor] If the value is instance of `Snippet`, current snippet requires
  405. * the snippet defined as `requiredFor` to work.
  406. */
  407. /**
  408. * @typedef {Object} SnippetSource
  409. *
  410. * @property {String} html An absolute path to the HTML sample.
  411. *
  412. * @property {String} css An absolute path to the CSS sample.
  413. *
  414. * @property {String} js An absolute path to the JS sample.
  415. */
  416. /**
  417. * @typedef {Object} SnippetConfiguration
  418. *
  419. * @property {String} [language] A language that will be used for building the editor.
  420. *
  421. * @property {Array.<String>} [dependencies] Names of samples that are required to working.
  422. *
  423. * @property {Array.<String>} [additionalLanguages] Additional languages that are required by the snippet.
  424. */