8
0

snippetadapter.js 15 KB

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