utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. const path = require( 'path' );
  7. const gulp = require( 'gulp' );
  8. const rename = require( 'gulp-rename' );
  9. const replace = require( 'gulp-replace' );
  10. const gulpBabel = require( 'gulp-babel' );
  11. const gutil = require( 'gulp-util' );
  12. const gulpFilter = require( 'gulp-filter' );
  13. const multipipe = require( 'multipipe' );
  14. const PassThrough = require( 'stream' ).PassThrough;
  15. const through = require( 'through2' );
  16. const fs = require( 'fs' );
  17. const sass = require( 'node-sass' );
  18. const del = require( 'del' );
  19. const minimist = require( 'minimist' );
  20. const sprite = require( 'gulp-svg-sprite' );
  21. const pipe = require( 'multipipe' );
  22. const filter = require( 'gulp-filter' );
  23. const utils = {
  24. /**
  25. * Code which can be appended to a transpiled (into AMD) test files in order to
  26. * load the 'tests' module and defer launching Bender until it's ready.
  27. *
  28. * Note: This code will not be transpiled so keep it in ES5.
  29. */
  30. benderLauncherCode:
  31. `
  32. var defer = bender.defer();
  33. require( [ 'tests', '/tests/engine/_utils/view.js', '/tests/engine/_utils/model.js' ],
  34. function( tests, view, model ) {
  35. bender.view = view;
  36. bender.model = model;
  37. defer();
  38. },
  39. function( err ) {
  40. // The problem with Require.JS is that there are no stacktraces if we won't log this.
  41. console.error( err );
  42. console.log( err.stack );
  43. } );
  44. `,
  45. /**
  46. * Module formats supported by the builder.
  47. */
  48. SUPPORTED_FORMATS: [ 'esnext', 'amd', 'cjs' ],
  49. /**
  50. * Creates a simple duplex stream.
  51. *
  52. * @param {Function} [callback] A callback which will be executed with each chunk.
  53. * @returns {Stream}
  54. */
  55. noop( callback ) {
  56. if ( !callback ) {
  57. return new PassThrough( { objectMode: true } );
  58. }
  59. return through( { objectMode: true }, ( file, encoding, throughCallback ) => {
  60. callback( file );
  61. throughCallback( null, file );
  62. } );
  63. },
  64. /**
  65. * Saves the files piped into this stream to the `build/` directory.
  66. *
  67. * @param {String} buildDir The `build/` directory path.
  68. * @param {String} format The format of the buildribution (`esnext`, `amd`, or `cjs`).
  69. * @returns {Stream}
  70. */
  71. destBuild( buildDir, format ) {
  72. const destDir = path.join( buildDir, format );
  73. return gulp.dest( destDir );
  74. },
  75. /**
  76. * Creates a function generating convertion streams.
  77. * Used to generate `formats.reduce()` callback where `formats` is an array of formats that should be generated.
  78. *
  79. * @param {String} buildDir The `build/` directory path.
  80. * @returns {Function}
  81. */
  82. getConversionStreamGenerator( buildDir ) {
  83. return ( pipes, format ) => {
  84. const conversionPipes = [];
  85. conversionPipes.push( utils.pickVersionedFile( format ) );
  86. if ( format != 'esnext' ) {
  87. // Convert src files.
  88. const filterSource = gulpFilter( ( file ) => {
  89. return utils.isSourceFile( file ) && utils.isJSFile( file );
  90. }, { restore: true } );
  91. const transpileSource = utils.transpile( format, utils.getBabelOptionsForSource( format ) );
  92. conversionPipes.push(
  93. filterSource,
  94. transpileSource,
  95. utils.fixCoverage(),
  96. filterSource.restore
  97. );
  98. // Convert test files.
  99. const filterTests = gulpFilter( ( file ) => {
  100. return utils.isTestFile( file ) && utils.isJSFile( file );
  101. }, { restore: true } );
  102. const transpileTests = utils.transpile( format, utils.getBabelOptionsForTests( format ) );
  103. conversionPipes.push(
  104. filterTests,
  105. transpileTests,
  106. format === 'amd' ? utils.appendBenderLauncher() : utils.noop(),
  107. filterTests.restore
  108. );
  109. }
  110. conversionPipes.push(
  111. utils.destBuild( buildDir, format ),
  112. utils.noop( ( file ) => {
  113. gutil.log( `Finished writing '${ gutil.colors.cyan( file.path ) }'` );
  114. } )
  115. );
  116. pipes.push( multipipe.apply( null, conversionPipes ) );
  117. return pipes;
  118. };
  119. },
  120. /**
  121. * Transpiles files piped into this stream to the given format (`amd` or `cjs`).
  122. *
  123. * @param {String} format
  124. * @returns {Stream}
  125. */
  126. transpile( format, options ) {
  127. return gulpBabel( options )
  128. .on( 'error', function( err ) {
  129. gutil.log( gutil.colors.red( `Error (Babel:${ format })` ) );
  130. gutil.log( gutil.colors.red( err.message ) );
  131. console.log( '\n' + err.codeFrame + '\n' );
  132. } );
  133. },
  134. /**
  135. * Adds istanbul ignore to the code created by babel.
  136. *
  137. * @returns {Stream}
  138. */
  139. fixCoverage() {
  140. return replace(
  141. 'return obj && obj.__esModule ? obj :',
  142. '/* istanbul ignore next */\n\t\t' +
  143. 'return obj && obj.__esModule ? obj :' );
  144. },
  145. /**
  146. * Returns an object with Babel options for the source code.
  147. *
  148. * @param {String} format
  149. * @returns {Object} options
  150. */
  151. getBabelOptionsForSource( format ) {
  152. return {
  153. plugins: utils.getBabelPlugins( format ),
  154. // Ensure that all paths ends with '.js' because Require.JS (unlike Common.JS/System.JS)
  155. // will not add it to module names which look like paths.
  156. resolveModuleSource: format == 'cjs' ? utils.resolveModuleSource : utils.appendModuleExtension
  157. };
  158. },
  159. /**
  160. * Returns an object with Babel options for the test code.
  161. *
  162. * @param {String} format
  163. * @returns {Object} options
  164. */
  165. getBabelOptionsForTests( format ) {
  166. return {
  167. plugins: utils.getBabelPlugins( format ),
  168. resolveModuleSource: format == 'cjs' ? utils.resolveModuleSource : utils.appendModuleExtension,
  169. moduleIds: true,
  170. moduleId: 'tests'
  171. };
  172. },
  173. /**
  174. * Returns an array of Babel plugins to use.
  175. *
  176. * @param {String} format
  177. * @returns {Array}
  178. */
  179. getBabelPlugins( format ) {
  180. const babelModuleTranspilers = {
  181. amd: 'amd',
  182. cjs: 'commonjs'
  183. };
  184. const babelModuleTranspiler = babelModuleTranspilers[ format ];
  185. if ( !babelModuleTranspiler ) {
  186. throw new Error( `Incorrect format: ${ format }` );
  187. }
  188. const plugins = [
  189. // Note: When plugin is specified by its name, Babel loads it from a context of a
  190. // currently transpiled file (in our case - e.g. from ckeditor5-core/src/foo.js).
  191. // Obviously that fails, since we have all the plugins installed only in ckeditor5/
  192. // and we want to have them only there to avoid installing them dozens of times.
  193. //
  194. // Anyway, I haven't found in the docs that you can also pass a plugin instance here,
  195. // but it works... so let's hope it will.
  196. require( `babel-plugin-transform-es2015-modules-${ babelModuleTranspiler }` )
  197. ];
  198. // Add additional plugins for Node.js environment.
  199. if ( format == 'cjs' ) {
  200. plugins.push( require( 'babel-plugin-transform-es2015-parameters' ) );
  201. }
  202. return plugins;
  203. },
  204. /**
  205. * Appends the {@link #benderLauncherCode} at the end of the file.
  206. *
  207. * @returns {Stream}
  208. */
  209. appendBenderLauncher() {
  210. return through( { objectMode: true }, ( file, encoding, callback ) => {
  211. if ( !file.isNull() ) {
  212. file.contents = new Buffer( file.contents.toString() + utils.benderLauncherCode );
  213. }
  214. callback( null, file );
  215. } );
  216. },
  217. /**
  218. * Allows us to pick one of files suffixed with the format (`__esnext`, `__amd`, or `__cjs`) and removes
  219. * files with other suffixes from the stream.
  220. *
  221. * For example: we have `load__esnext.js`, `load__amd.js` and `load__cjs.js`. After applying this
  222. * transformation when compiling code for a specific format the proper file will be renamed to `load.js`.
  223. * Files not matching a specified format will be removed.
  224. *
  225. * @param {String} format
  226. * @returns {Stream}
  227. */
  228. pickVersionedFile( format ) {
  229. const rejectedFormats = utils.SUPPORTED_FORMATS
  230. .filter( ( item ) => item !== format );
  231. const pickRegexp = new RegExp( `__${ format }$` );
  232. const rejectRegexp = new RegExp( `__(${ rejectedFormats.join( '|' ) }).js$` );
  233. const pick = rename( ( path ) => {
  234. path.basename = path.basename.replace( pickRegexp, '' );
  235. } );
  236. const remove = gulpFilter( ( file ) => !rejectRegexp.test( file.path ) );
  237. return multipipe( pick, remove );
  238. },
  239. /**
  240. * Processes paths of files inside CKEditor5 packages.
  241. *
  242. * * `ckeditor5-xxx/src/foo/bar.js` -> `ckeditor5/xxx/foo/bar.js`
  243. * * `ckeditor5-xxx/tests/foo/bar.js` -> `tests/xxx/foo/bar.js`
  244. *
  245. * @returns {Stream}
  246. */
  247. renamePackageFiles() {
  248. return rename( ( file ) => {
  249. const dirFrags = file.dirname.split( path.sep );
  250. // Validate the input for the clear conscious.
  251. if ( dirFrags[ 0 ].indexOf( 'ckeditor5-' ) !== 0 ) {
  252. throw new Error( 'Path should start with "ckeditor5-".' );
  253. }
  254. dirFrags[ 0 ] = dirFrags[ 0 ].replace( /^ckeditor5-/, '' );
  255. const firstFrag = dirFrags[ 1 ];
  256. if ( firstFrag == 'src' ) {
  257. // Remove 'src/'.
  258. dirFrags.splice( 1, 1 );
  259. // Temporary implementation of the UI lib option. See #88.
  260. if ( dirFrags[ 0 ] == 'ui-default' ) {
  261. dirFrags[ 0 ] = 'ui';
  262. }
  263. // And prepend 'ckeditor5/'.
  264. dirFrags.unshift( 'ckeditor5' );
  265. } else if ( firstFrag == 'tests' ) {
  266. // Remove 'tests/' from the package dir.
  267. dirFrags.splice( 1, 1 );
  268. // And prepend 'tests/'.
  269. dirFrags.unshift( 'tests' );
  270. } else {
  271. throw new Error( 'Path should start with "ckeditor5-*/(src|tests|theme)".' );
  272. }
  273. file.dirname = path.join.apply( null, dirFrags );
  274. } );
  275. },
  276. /**
  277. * Processes paths of files inside the main CKEditor5 package.
  278. *
  279. * * `src/foo/bar.js` -> `ckeditor5/foo/bar.js`
  280. * * `tests/foo/bar.js` -> `tests/ckeditor5/foo/bar.js`
  281. *
  282. * @returns {Stream}
  283. */
  284. renameCKEditor5Files() {
  285. return rename( ( file ) => {
  286. const dirFrags = file.dirname.split( path.sep );
  287. const firstFrag = dirFrags[ 0 ];
  288. if ( firstFrag == 'src' ) {
  289. // Replace 'src/' with 'ckeditor5/'.
  290. // src/path.js -> ckeditor5/path.js
  291. dirFrags.splice( 0, 1, 'ckeditor5' );
  292. } else if ( firstFrag == 'tests' ) {
  293. // Insert 'ckeditor5/' after 'tests/'.
  294. // tests/foo.js -> tests/ckeditor5/foo.js
  295. dirFrags.splice( 1, 0, 'ckeditor5' );
  296. } else {
  297. throw new Error( 'Path should start with "src" or "tests".' );
  298. }
  299. file.dirname = path.join.apply( null, dirFrags );
  300. } );
  301. },
  302. /**
  303. * Appends file extension to file URLs. Tries to not touch named modules.
  304. *
  305. * @param {String} source
  306. * @returns {String}
  307. */
  308. appendModuleExtension( source ) {
  309. if ( /^https?:|\.[\/\\]/.test( source ) && !/\.js$/.test( source ) ) {
  310. return source + '.js';
  311. }
  312. return source;
  313. },
  314. /**
  315. * Checks whether a file is a test file.
  316. *
  317. * @param {Vinyl} file
  318. * @returns {Boolean}
  319. */
  320. isTestFile( file ) {
  321. // TODO this should be based on bender configuration (config.tests.*.paths).
  322. if ( !file.relative.startsWith( 'tests' + path.sep ) ) {
  323. return false;
  324. }
  325. const dirFrags = file.relative.split( path.sep );
  326. return !dirFrags.some( dirFrag => {
  327. return dirFrag.startsWith( '_' ) && dirFrag != '_utils-tests';
  328. } );
  329. },
  330. /**
  331. * Checks whether a file is a source file.
  332. *
  333. * @param {Vinyl} file
  334. * @returns {Boolean}
  335. */
  336. isSourceFile( file ) {
  337. return !utils.isTestFile( file );
  338. },
  339. /**
  340. * Checks whether a file is a JS file.
  341. *
  342. * @param {Vinyl} file
  343. * @returns {Boolean}
  344. */
  345. isJSFile( file ) {
  346. return file.path.endsWith( '.js' );
  347. },
  348. /**
  349. * Finds all CKEditor5 package directories in "node_modules" folder.
  350. *
  351. * @param {String} rootDir A root directory containing "node_modules" folder.
  352. * @returns {Array} Array of ckeditor5-* package directory paths.
  353. */
  354. getPackages( rootDir ) {
  355. // Find all CKEditor5 package directories. Resolve symlinks so we watch real directories
  356. // in order to workaround https://github.com/paulmillr/chokidar/issues/419.
  357. return fs.readdirSync( path.join( rootDir, 'node_modules' ) )
  358. // Look for ckeditor5-* directories.
  359. .filter( fileName => {
  360. return fileName.indexOf( 'ckeditor5-' ) === 0;
  361. } )
  362. // Resolve symlinks and keep only directories.
  363. .map( fileName => {
  364. let filePath = path.join( rootDir, 'node_modules', fileName );
  365. let stat = fs.lstatSync( filePath );
  366. if ( stat.isSymbolicLink() ) {
  367. filePath = fs.realpathSync( filePath );
  368. stat = fs.lstatSync( filePath );
  369. }
  370. if ( stat.isDirectory() ) {
  371. return filePath;
  372. }
  373. // Filter...
  374. return false;
  375. } )
  376. // ...those out.
  377. .filter( filePath => filePath );
  378. },
  379. /**
  380. * Filters theme entry points only from a stream of SCSS files.
  381. *
  382. * @returns {Stream}
  383. */
  384. filterThemeEntryPoints() {
  385. return filter( '**/theme.scss' );
  386. },
  387. /**
  388. * Given the input stream of theme entry-point files (theme.scss), this method:
  389. * 1. Collects paths to entry-point.
  390. * 2. Builds the output CSS theme file using aggregated entry-points.
  391. * 3. Returns a stream containing built CSS theme file.
  392. *
  393. * @param {String} fileName The name of the output CSS theme file.
  394. * @returns {Stream}
  395. */
  396. compileThemes( fileName ) {
  397. const paths = [];
  398. const stream = through.obj( collectThemeEntryPoint, renderThemeFromEntryPoints );
  399. function collectThemeEntryPoint( file, enc, callback ) {
  400. paths.push( file.path );
  401. callback();
  402. }
  403. function renderThemeFromEntryPoints( callback ) {
  404. gutil.log( `Compiling '${ gutil.colors.cyan( fileName ) }' from ${ gutil.colors.cyan( paths.length ) } entry points...` );
  405. // Note: Make sure windows\\style\\paths are preserved.
  406. const dataToRender = paths.map( p => `@import "${ p.replace( /\\/g, '\\\\' ) }";` )
  407. .join( '\n' );
  408. try {
  409. const rendered = sass.renderSync( utils.getSassOptions( dataToRender ) );
  410. stream.push( new gutil.File( {
  411. path: fileName,
  412. contents: new Buffer( rendered.css )
  413. } ) );
  414. callback();
  415. } catch ( err ) {
  416. callback( err );
  417. }
  418. }
  419. return stream;
  420. },
  421. /**
  422. * Parses command line arguments and returns them as a user-friendly hash.
  423. *
  424. * @param {String} dataToRender
  425. * @returns {Object}
  426. */
  427. getSassOptions( dataToRender ) {
  428. return {
  429. data: dataToRender,
  430. sourceMap: true,
  431. sourceMapEmbed: true,
  432. outputStyle: 'expanded',
  433. sourceComments: true
  434. };
  435. },
  436. /**
  437. * Removes files and directories specified by `glob` starting from `rootDir`
  438. * and gently informs about deletion.
  439. *
  440. * @param {String} rootDir The path to the root directory (i.e. "dist/").
  441. * @param {String} glob Glob specifying what to clean.
  442. * @returns {Promise}
  443. */
  444. clean( rootDir, glob ) {
  445. return del( path.join( rootDir, glob ) ).then( paths => {
  446. paths.forEach( p => {
  447. gutil.log( `Deleted file '${ gutil.colors.cyan( p ) }'.` );
  448. } );
  449. } );
  450. },
  451. /**
  452. * Parses command line arguments and returns them as a user-friendly hash.
  453. *
  454. * @returns {Object} options
  455. * @returns {Array} [options.formats] Array of specified output formats ("esnext" or "amd").
  456. * @returns {Boolean} [options.watch] A flag which enables watch mode.
  457. */
  458. parseArguments() {
  459. const options = minimist( process.argv.slice( 2 ), {
  460. string: [
  461. 'formats'
  462. ],
  463. boolean: [
  464. 'watch'
  465. ],
  466. default: {
  467. formats: 'amd',
  468. watch: false
  469. }
  470. } );
  471. options.formats = options.formats.split( ',' );
  472. return options;
  473. },
  474. /**
  475. * Given a stream of .svg files it returns a stream containing JavaScript
  476. * icon sprite file.
  477. *
  478. * @returns {Stream}
  479. */
  480. compileIconSprite() {
  481. return sprite( utils.getIconSpriteOptions() );
  482. },
  483. /**
  484. * Returns svg-sprite util options to generate <symbol>-based, JavaScript
  485. * sprite file.
  486. *
  487. * @returns {Object}
  488. */
  489. getIconSpriteOptions() {
  490. return {
  491. shape: {
  492. id: {
  493. // Note: Consider unix/style/paths and windows\\style\\paths.
  494. generator: name => `ck-icon-${ name.match( /([^\/\\]*)\.svg$/ )[ 1 ] }`
  495. },
  496. },
  497. svg: {
  498. xmlDeclaration: false,
  499. doctypeDeclaration: false,
  500. },
  501. mode: {
  502. symbol: {
  503. dest: './', // Flatten symbol/ folder.
  504. inline: true,
  505. render: {
  506. js: {
  507. template: path.join( __dirname, 'iconmanagermodel.tpl' ),
  508. dest: 'iconmanagermodel.js',
  509. }
  510. }
  511. }
  512. }
  513. };
  514. },
  515. /**
  516. * Given a stream of files it returns an array of gulp-mirror streams outputting
  517. * files to `build/[formats]/theme/` directories for each of desired output formats (cjs, amd, etc.).
  518. *
  519. * @param {String} buildDir A path to /build directory.
  520. * @param {Array} formats An array of desired output formats.
  521. * @param {Function} [transformationStream] A stream used to transform files before they're saved to
  522. * desired `build/[formats]/theme` directories. Useful for transpilation.
  523. * @returns {Stream[]} An array of streams.
  524. */
  525. getThemeFormatDestStreams( buildDir, formats, transformationStream ) {
  526. return formats.map( f => {
  527. return pipe(
  528. transformationStream ? transformationStream( f ) : utils.noop(),
  529. gulp.dest( path.join( buildDir, f, 'theme' ) ),
  530. utils.noop( file => {
  531. gutil.log( `Output for ${ gutil.colors.cyan( f ) } is '${ gutil.colors.cyan( file.path ) }'.` );
  532. } )
  533. );
  534. } );
  535. },
  536. /**
  537. * Resolves CommonJS module source path.
  538. *
  539. * @param {String} source Module path passed to require() method.
  540. * @param {String} file Path to a file where require() method is called.
  541. * @returns {String} Fixed module path.
  542. */
  543. resolveModuleSource( source, file ) {
  544. // If path is relative - leave it as is.
  545. if ( !path.isAbsolute( source ) ) {
  546. return source;
  547. }
  548. // Find relative path of test file from cwd directory.
  549. let testFile = path.relative( process.cwd(), file );
  550. // Append `/` as all files uses it as root inside transpiled versions.
  551. testFile = path.join( path.sep, testFile );
  552. // Find relative path from test file to source.
  553. let relativePath = path.relative( path.dirname( testFile ), path.dirname( source ) );
  554. relativePath = path.join( relativePath, path.basename( source ) );
  555. // Convert windows path to posix.
  556. relativePath = relativePath.replace( /\\/g, '/' );
  557. return utils.appendModuleExtension( ( relativePath.startsWith( '../' ) ? '' : './' ) + relativePath );
  558. }
  559. };
  560. module.exports = utils;