snippetadapter.js 18 KB

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