All files / packages/design-system/scripts/gulp/generate sanitized.js

0% Statements 0/70
0% Branches 0/6
0% Functions 0/22
0% Lines 0/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                                                                                                                                                                                                                                                                                                                                                                                                                                       
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
 
import fs from 'fs';
import I from 'immutable';
import path from 'path';
import gulp from 'gulp';
import gulpRename from 'gulp-rename';
import through from 'through2';
import discardComments from 'postcss-discard-comments';
import { toList } from '../../../shared/utils/tree';
import paths from '../../helpers/paths';
import * as gulpHelpers from '../../helpers/gulp';
import { uiJson } from '../../ui';
import { BEM_MODIFIER_REGEX, compileSanitizedComponents } from './sanitized-components';
 
const MODULE_NAME = 'salesforce-lightning-design-system';
 
/**
 * Store paths
 */
const root = path.resolve(__dirname, '../../../');
const rootPath = path.resolve.bind(path, root);
const distPath = path.resolve.bind(path, paths.dist);
 
/**
 * Regex to remove BEM -- modifier from source
 */
export const regex = BEM_MODIFIER_REGEX;
 
/**
 * Parse ui.json and return the components collection, since we're only
 * concerned about components and not utilities. Computed on demand rather than
 * at import: building ui.json loads every example and costs several seconds,
 * which every gulp task (including `build`) would otherwise pay at startup.
 * getComponents : () -> Map
 */
const getComponents = () => I.fromJS(I.Map(JSON.parse(uiJson())).get('components'));
 
/**
 * Helper function to store paths in a friendly way
 * @param {string} c - Top level component
 * @param {string} v - Component variant, if it exists
 * setPath : component, variant -> string
 */
const setPath = (c, v) => {
  const component = c.get('id');
  const variant = c.get('id') === v.get('id') ? 'base' : v.get('id');
  return `${component}/${variant}`;
};
 
/**
 * Parse and store import paths based on lwc annotations
 * @param {Map} c - Immutable Map of components
 */
const readLwcAnnotations = (c) => {
  const rollup = [];
  c.map((x) => {
    toList(x)
      .filter((item) => item.getIn(['annotations', 'lwc']))
      .map((z) => rollup.push(setPath(x, z)));
  });
  return rollup;
};
 
/**
 * Writes a new scss file into ui/components that has the imports for
 * all components with @lwc annotations
 * @param {array} packages
 * @note Will sort alphabetically
 */
export const writeSanitizedScssFile = (packages) => {
  const file = rootPath('ui/components/_index.sanitized.scss');
  let pathImports = [];
  packages.map((t) => {
    pathImports.push(`@import '${t}/index';`);
  });
  let content = [
    '// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    '// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license',
    '\n\n',
    pathImports.sort((a, b) => a.localeCompare(b)).join('\n'),
    '\n',
  ].join('');
 
  try {
    fs.writeFileSync(file, content);
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
};
 
/**
 * Writes a new css file into ui/components that has the imports for
 * all components with @lwc annotations, this file is for lwc to chunk
 * files using @import statements
 * @param {array} packages
 * @note Will sort alphabetically
 */
export const writeSanitizedCssFile = (packages) => {
  const file = distPath(`assets/styles/${MODULE_NAME}-imports.sanitized.css`);
  let pathImports = [];
  packages.map((t) => {
    pathImports.push(`@import '../../css/${t}/index.css';`);
  });
  let content = [
    '/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    'Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */',
    '\n\n',
    "@import '../../css/common/index.css';",
    '\n',
    pathImports.sort((a, b) => a.localeCompare(b)).join('\n'),
    '\n',
  ].join('');
 
  try {
    fs.writeFileSync(file, content);
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
};
 
/**
 * We need to dynamically generate a common file to be used as an import
 * @param {callback} done
 */
export const writeCommonCss = (done) => {
  const dir = rootPath(`.css/common`);
  const file = rootPath(`${dir}/index.scss`);
  let content = [
    '/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    'Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */',
    '\n\n',
    "@import 'dist/scss/init';",
    '\n',
    "@import 'dist/scss/vendor/normalize-sanitized';",
    '\n',
    '@include core($scoped: false, $globals: false);',
    '\n',
  ].join('');
  try {
    // Synchronous so the file exists by the time `done` signals the next task
    fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(file, content);
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
  if (done) done();
};
 
/**
 * Write sanitized version to assets/styles so it can be copied
 * and minified with dist script runs
 */
export const writeSanitizedCss = () =>
  gulp
    .src('ui/index-sanitized.scss')
    .pipe(gulpHelpers.writeScss({ outputStyle: 'expanded' }))
    .pipe(gulpHelpers.writePostCss([discardComments()]))
    // Need to format to ensure proper parsing
    .pipe(gulpHelpers.writePrettierCss())
    // Remove BEM -- modifiers
    .pipe(
      through.obj((file, enc, next) => {
        let newFile = file.clone();
        newFile.contents = Buffer.from(file.contents.toString().replace(regex[0], '').replace(regex[1], ''));
        return next(null, newFile);
      }),
    )
    // For cleanup
    .pipe(gulpHelpers.writePrettierCss())
    .pipe(
      gulpRename((path) => {
        path.basename = `${MODULE_NAME}.sanitized`;
        path.extname = '.css';
        return path;
      }),
    )
    .pipe(gulp.dest(distPath('assets/styles/')));
 
/**
 * Compiles sanitized version of SLDS component files, in parallel across
 * worker threads (see ./sanitized-components)
 * @returns {Promise<void>}
 */
export const writeSanitizedComponentCss = async () => {
  const srcBase = paths.rootPath('.css');
  // Equivalent to the `.css/**/{index,touch}.scss` globs (which skip dot
  // directories), but listed synchronously so the workers start right away
  // instead of waiting for the main thread to come free of generateSanitizedScss
  const srcPaths = fs
    .readdirSync(srcBase, { recursive: true })
    .filter((file) => ['index.scss', 'touch.scss'].includes(path.basename(file)))
    .filter((file) => !file.split(path.sep).some((segment) => segment.startsWith('.')))
    .map((file) => path.join(srcBase, file));
  return compileSanitizedComponents({ srcPaths, srcBase, destBase: distPath('css') });
};
 
/**
 * Export for gulp task
 * @param {callback} done
 */
export const generateSanitizedScss = (done) => {
  const rollup = readLwcAnnotations(getComponents());
  writeSanitizedScssFile(rollup);
  writeSanitizedCssFile(rollup);
  if (done) done();
};