All files / packages/sds-stylelint-config/src/plugins styling-hooks-pattern.js

0% Statements 0/72
0% Branches 0/39
0% Functions 0/18
0% Lines 0/68

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                                                                                                                                                                                                                                                                                                                                                                             
const path = require('path');
const chalk = require('chalk');
const stylelint = require('stylelint');
const { report, ruleMessages, validateOptions } = stylelint.utils;
const valueParser = require('postcss-value-parser');
const metadata = require('../metadata/metadata.js');
const {
  validateNs,
  validateScope,
  validateContext,
  validateElement,
  validateVariant,
  validateCategory,
  validateProperty,
  validateAttribute,
  validateState,
  validatePsuedoState,
  removeFromArray,
  getMissingKeys,
  getContextFromString,
  storeSearchableKeys,
  isValidCustomProperty,
} = require('../utils');
 
// Plugin name
const ruleName = 'sds-stylelint-plugin/styling-hooks-pattern';
 
// Custom message for report
const messages = ruleMessages(ruleName, {
  expected: (prop, report, message) => {
    const errors = report
      .map((error, key) => {
        const expected = error.info.expected
          ? `Expected ${chalk.bold(error.group)} value(s) of "${chalk.bold(
              error.info.expected,
            )}" but received "${chalk.redBright(error.info.received)}".`
          : '';
        return `${key + 1}.) ${expected}`;
      })
      .join(' ');
    const error = `${report.length} found on ${chalk.cyan(prop)} fails naming pattern. ${errors}${
      message && message.length > 0
        ? `${chalk.redBright('[Analysis Warning]')}: ${message.map((error) => error).join(' ')}`
        : ''
    }`;
    return error;
  },
});
 
module.exports = stylelint.createPlugin(ruleName, function (primary, options) {
  return function (root, result) {
    const validOptions = validateOptions(result, ruleName, { actual: primary });
    if (!validOptions) return;
    if (options && options.valid) {
      Object.keys(options.valid).map((group) => {
        if (Object.getOwnPropertyNames(metadata.component.valid).includes(group)) {
          const merged = new Set([...metadata.component.valid[group], ...options.valid[group]]);
          const newOptions = [...Array.from(merged)];
          metadata.component.valid[group] = newOptions;
        }
      });
    }
 
    root.walkDecls((decl) => {
      const parsedValue = valueParser(decl.value);
      const privateSyntax = (options && options.privateSyntax) || metadata.privateSyntax;
 
      parsedValue.walk(async (node) => {
        const context = decl.source.input.file
          ? path.parse(decl.source.input.file).name.split('.')[0]
          : getContextFromString(decl.parent.selector);
        // console.log(context);
        if (node.type !== 'word') return;
        if (isValidCustomProperty({ value: node.value, privateSyntax })) {
          // Break words of custom prop into groups
          const groups = node.value.match(/\b[_a-z0-9-]+\b/g);
          // Store keys based on metadata
          const keys = storeSearchableKeys(groups);
          // Store remaining unused keys, this is used to determine validity of optional words
          const fuzzyKeys = new Set(removeFromArray(getMissingKeys(keys, groups.length), 2));
 
          // Kill processing if hook is not component level
          if (groups[1] !== 'c') return;
 
          // Populate pattern object to check against custom prop
          const pattern = new Promise((resolve, reject) => {
            resolve({
              prop: node.value,
              groups,
              keys,
              lastKey: groups.length - 1,
              fuzzyKeys,
              // Known validations
              validate: {
                ns: validateNs(groups[0], privateSyntax),
                scope: validateScope(groups, keys),
                context: validateContext(groups, context, keys),
              },
              customMessage: [],
            });
          });
 
          // Required validations
          pattern.then((result) => {
            result.validate.category = validateCategory(result);
          });
 
          // Optional validations
          pattern.then((result) => {
            result.validate.element = validateElement(result);
            result.validate.variant = validateVariant(result);
            result.validate.property = validateProperty(result);
            result.validate.attribute = validateAttribute(result);
            result.validate.state = validateState(result);
            result.validate.psuedoState = validatePsuedoState(result);
            // console.log(result);
            return result;
          });
 
          // console.log(await pattern);
 
          // Check validity on Promise and send back invalid items
          const onInvalid = pattern.then((result) => {
            let isValid = true;
            const invalid = Object.keys(result.validate).map((valid, index) => {
              if (result.validate[valid] && result.validate[valid].valid === false) {
                isValid = false;
                return {
                  group: valid,
                  info:
                    result.customMessage.length > 0
                      ? Object.assign(result.validate[valid], { message: result.customMessage })
                      : result.validate[valid],
                };
              }
            });
            const invalidSet = new Set(invalid);
            return isValid
              ? false
              : {
                  prop: result.prop,
                  result: [...invalidSet].filter((x) => x !== undefined),
                  message: result.customMessage,
                };
          });
 
          // Throw report if unparseable items show up
          const unparseable = pattern.then((result) => {
            const parsed = Object.keys(result.validate).map((valid) => {
              return result.validate[valid] === undefined && result.prop;
            });
            return parsed.filter((x) => x !== false).toString();
          });
          if (await unparseable) {
            console.log(
              `${chalk.black.bgWhite('Attention')} The custom property ${chalk.cyan(
                node.value,
              )} could not be parsed. Please ensure the property is formatted correctly. If you believe this to be a bug, please report this issue to the Design System Engineering team at ${chalk.underline(
                '#design-system-help',
              )}.`,
            );
          }
 
          // Throw report if invalid items show up in the onInvalid Set
          onInvalid.then((invalid) => {
            if (invalid) {
              report({
                ruleName,
                result,
                message: messages.expected(invalid.prop, invalid.result, invalid.message),
                node: decl,
              });
            }
          });
        }
      });
    });
  };
});
 
module.exports.ruleName = ruleName;
module.exports.messages = messages;