8
0

snippetadapter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. snippetHTML = snippetHTML.replace( /%BASE_PATH%/g, snippetData.basePath );
  131. snippetHTML = `<div class="live-snippet">${ snippetHTML }</div>`;
  132. content = content.replace( getSnippetPlaceholder( snippetData.snippetName ), snippetHTML );
  133. jsFiles.push( path.join( snippetData.basePath, 'assets', 'snippet.js' ) );
  134. jsFiles.push( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.js' ) );
  135. cssFiles.push( path.join( snippetData.basePath, 'assets', 'snippet-styles.css' ) );
  136. if ( wasCSSGenerated ) {
  137. cssFiles.unshift( path.join( snippetData.relativeOutputPath, snippetData.snippetName, 'snippet.css' ) );
  138. }
  139. }
  140. const cssImportsHTML = getHTMLImports( cssFiles, importPath => {
  141. return ` <link rel="stylesheet" href="${ importPath }" type="text/css">`;
  142. } );
  143. const jsImportsHTML = getHTMLImports( jsFiles, importPath => {
  144. return ` <script src="${ importPath }"></script>`;
  145. } );
  146. content = content.replace( '<!--UMBERTO: SNIPPET: CSS-->', cssImportsHTML );
  147. content = content.replace( '<!--UMBERTO: SNIPPET: JS-->', jsImportsHTML );
  148. fs.writeFileSync( destinationPath, content );
  149. }
  150. } )
  151. .then( () => {
  152. console.log( `Finished building ${ snippets.size } snippets.` );
  153. } );
  154. };
  155. /**
  156. * Removes snippets that names do not match to patterns specified in `whitelistedSnippets` array.
  157. *
  158. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  159. * @param {Array.<String>|undefined} whitelistedSnippets Snippet patterns that should be built.
  160. */
  161. function filterWhitelistedSnippets( snippets, whitelistedSnippets ) {
  162. if ( !whitelistedSnippets.length ) {
  163. return;
  164. }
  165. const snippetsToBuild = new Set();
  166. // Find all snippets that matched to specified criteria.
  167. for ( const snippetData of snippets ) {
  168. const matchToPatterns = whitelistedSnippets.some( pattern => minimatch( snippetData.snippetName, pattern ) );
  169. // Snippet should be built.
  170. if ( matchToPatterns ) {
  171. snippetsToBuild.add( snippetData );
  172. }
  173. }
  174. // Find all dependencies that are required for whitelisted snippets.
  175. for ( const snippetData of snippets ) {
  176. if ( snippetsToBuild.has( snippetData ) ) {
  177. continue;
  178. }
  179. if ( snippetData.requiredFor && snippetsToBuild.has( snippetData.requiredFor ) ) {
  180. snippetsToBuild.add( snippetData );
  181. }
  182. }
  183. // Remove snippets that won't be built and aren't dependencies of other snippets.
  184. for ( const snippetData of snippets ) {
  185. if ( !snippetsToBuild.has( snippetData ) ) {
  186. snippets.delete( snippetData );
  187. }
  188. }
  189. }
  190. /**
  191. * Prepares configuration for Webpack.
  192. *
  193. * @param {Set.<Snippet>} snippets Snippet collection extracted from documentation files.
  194. * @param {Object} config
  195. * @param {String} config.language Language for the build.
  196. * @param {Boolean} config.production Whether to build for production.
  197. * @param {Object} config.definitions
  198. * @returns {Object}
  199. */
  200. function getWebpackConfig( snippets, config ) {
  201. // Stringify all definitions values. The `DefinePlugin` injects definition values as they are so we need to stringify them,
  202. // so they will become real strings in the generated code. See https://webpack.js.org/plugins/define-plugin/ for more information.
  203. const definitions = {};
  204. for ( const definitionKey in config.definitions ) {
  205. definitions[ definitionKey ] = JSON.stringify( config.definitions[ definitionKey ] );
  206. }
  207. const webpackConfig = {
  208. mode: config.production ? 'production' : 'development',
  209. devtool: 'source-map',
  210. entry: {},
  211. output: {
  212. filename: '[name]/snippet.js'
  213. },
  214. optimization: {
  215. minimizer: [
  216. new UglifyJsWebpackPlugin( {
  217. sourceMap: true,
  218. uglifyOptions: {
  219. output: {
  220. // Preserve license comments starting with an exclamation mark.
  221. comments: /^!/
  222. }
  223. }
  224. } )
  225. ]
  226. },
  227. plugins: [
  228. new MiniCssExtractPlugin( { filename: '[name]/snippet.css' } ),
  229. new CKEditorWebpackPlugin( {
  230. language: config.language
  231. } ),
  232. new webpack.BannerPlugin( {
  233. banner: bundler.getLicenseBanner(),
  234. raw: true
  235. } ),
  236. new webpack.DefinePlugin( definitions ),
  237. new ProgressBarPlugin( {
  238. format: `Building snippets for language "${ config.language }": :percent (:msg)`,
  239. } )
  240. ],
  241. // Configure the paths so building CKEditor 5 snippets work even if the script
  242. // is triggered from a directory outside ckeditor5 (e.g. multi-project case).
  243. resolve: {
  244. modules: getModuleResolvePaths()
  245. },
  246. resolveLoader: {
  247. modules: getModuleResolvePaths()
  248. },
  249. module: {
  250. rules: [
  251. {
  252. test: /\.svg$/,
  253. use: [ 'raw-loader' ]
  254. },
  255. {
  256. test: /\.css$/,
  257. use: [
  258. MiniCssExtractPlugin.loader,
  259. 'css-loader',
  260. {
  261. loader: 'postcss-loader',
  262. options: styles.getPostCssConfig( {
  263. themeImporter: {
  264. themePath: require.resolve( '@ckeditor/ckeditor5-theme-lark' )
  265. },
  266. minify: config.production
  267. } )
  268. }
  269. ]
  270. }
  271. ]
  272. }
  273. };
  274. for ( const snippetData of snippets ) {
  275. if ( !webpackConfig.output.path ) {
  276. webpackConfig.output.path = snippetData.outputPath;
  277. }
  278. if ( webpackConfig.entry[ snippetData.snippetName ] ) {
  279. continue;
  280. }
  281. webpackConfig.entry[ snippetData.snippetName ] = snippetData.snippetSources.js;
  282. }
  283. return webpackConfig;
  284. }
  285. /**
  286. * Builds snippets.
  287. *
  288. * @param {Object} webpackConfig
  289. * @returns {Promise}
  290. */
  291. function runWebpack( webpackConfig ) {
  292. return new Promise( ( resolve, reject ) => {
  293. webpack( webpackConfig, ( err, stats ) => {
  294. if ( err ) {
  295. reject( err );
  296. } else if ( stats.hasErrors() ) {
  297. reject( new Error( stats.toString() ) );
  298. } else {
  299. resolve();
  300. }
  301. } );
  302. } );
  303. }
  304. /**
  305. * @returns {Array.<String>}
  306. */
  307. function getModuleResolvePaths() {
  308. return [
  309. path.resolve( __dirname, '..', '..', 'node_modules' ),
  310. 'node_modules'
  311. ];
  312. }
  313. /**
  314. * Reads the snippet's configuration.
  315. *
  316. * @param {String} snippetSourcePath An absolute path to the file.
  317. * @returns {Object}
  318. */
  319. function readSnippetConfig( snippetSourcePath ) {
  320. const snippetSource = fs.readFileSync( snippetSourcePath ).toString();
  321. const configSourceMatch = snippetSource.match( /\n\/\* config ([\s\S]+?)\*\// );
  322. if ( !configSourceMatch ) {
  323. return {};
  324. }
  325. return JSON.parse( configSourceMatch[ 1 ] );
  326. }
  327. /**
  328. * Removes duplicated entries specified in `files` array and map those entires using `mapFunction`.
  329. *
  330. * @param {Array.<String>} files Paths collection.
  331. * @param {Function} mapFunction Function that should return a string.
  332. * @returns {String}
  333. */
  334. function getHTMLImports( files, mapFunction ) {
  335. return [ ...new Set( files ) ]
  336. .map( mapFunction )
  337. .join( '\n' )
  338. .replace( /^\s+/, '' );
  339. }
  340. /**
  341. * @typedef {Object} Snippet
  342. *
  343. * @property {SnippetSource} snippetSources Sources of the snippet.
  344. *
  345. * @property {String} snippetName Name of the snippet. Defined directly after `@snippet` tag.
  346. *
  347. * @property {String} outputPath An absolute path where to write file produced by the `snippetAdapter`.
  348. *
  349. * @property {String} destinationPath An absolute path to the file where the snippet is being used.
  350. *
  351. * @property {SnippetConfiguration} snippetConfig={} Additional configuration of the snippet. It's being read from the snippet's source.
  352. *
  353. * @property {String} [basePath] Relative path from the processed file to the root of the documentation.
  354. *
  355. * @property {String} [relativeOutputPath] The same like `basePath` but for the output path (where processed file will be saved).
  356. *
  357. * @property {Snippet|undefined} [requiredFor] If the value is instance of `Snippet`, current snippet requires
  358. * the snippet defined as `requiredFor` to work.
  359. */
  360. /**
  361. * @typedef {Object} SnippetSource
  362. *
  363. * @property {String} html An absolute path to the HTML sample.
  364. *
  365. * @property {String} css An absolute path to the CSS sample.
  366. *
  367. * @property {String} js An absolute path to the JS sample.
  368. */
  369. /**
  370. * @typedef {Object} SnippetConfiguration
  371. *
  372. * @property {String} [language] A language that will be used for building the editor.
  373. *
  374. * @property {Array.<String>} [dependencies] Names of samples that are required to working.
  375. */