snippetadapter.js 15 KB

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