All files babel-plugin-class-bound-components.ts

100% Statements 103/103
96.49% Branches 110/114
100% Functions 20/20
100% Lines 101/101

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374            11x                               1x     11x   13x 1x       12x 12x       12x 13x     12x 14x         12x 8x     12x 6x                     11x       53x   53x 44x           53x 48x       26x     22x         17x     17x     5x     53x 38x   38x 37x   15x         5x 5x       5x 3x   10x         1x   1x 1x                     11x       24x   24x             24x       24x 20x 20x           11x           11x         11x         4x 1x     3x             3x             11x       37x       15x 15x     22x           20x 20x           11x             11x       15x 15x   22x     3x     12x       18x 6x     6x                         11x 20x   20x       4x             4x         16x         16x     16x 46x 14x       16x     11x       20x 9x               11x 64x   56x     2x     4x         2x       11x 18x                   11x       20x 4x         16x       4x           12x           1x     11x     11x    
import { Visitor } from '@babel/traverse';
import * as t from '@babel/types';
 
type BabelTypes = typeof t;
 
export default function (babelTypes: { types: BabelTypes }) {
  return {
    name: 'class-bound-components',
    visitor: makeRootVisitor(babelTypes.types),
  };
}
 
type Options = {
  displayName?: boolean;
  elementType?: boolean;
};
 
type State = {
  classBoundSpecifier: string | null;
  extendSpecifier: string | null;
};
 
const reservedMethods = ['extend', 'withOptions', 'withVariants', 'as'];
 
function makeRootVisitor(t: BabelTypes): Visitor {
  const importClassBoundVisitor: Visitor<{ opts: Options }> = {
    ImportDeclaration(path, state) {
      if (path.node.source.value !== 'class-bound-components') {
        return;
      }
 
      // Symbol of the classBound function
      const defaultImportLocal = path.node.specifiers.find(
        (s) => s.type === 'ImportDefaultSpecifier'
      )?.local.name;
 
      // Symbol of the standalone extend function
      const extendImportLocal = path.node.specifiers.find(
        (s) => s.type === 'ImportSpecifier' && s.imported.name === 'extend'
      )?.local.name;
 
      const traverseProgramWith = (visitor: Visitor<State>) =>
        path.parentPath.traverse(visitor, {
          classBoundSpecifier: defaultImportLocal || null,
          extendSpecifier: extendImportLocal || null,
        });
 
      if (state.opts.displayName ?? true) {
        traverseProgramWith(displayNameVisitor);
      }
 
      if (state.opts.elementType ?? true) {
        traverseProgramWith(elementTypeVisitor);
      }
    },
  };
 
  /**
   * Visits all `CallExpression`s and searches for calls of the `classBound` (or as whatever
   * symbol it is imported in the current module), `classBound.extend` or `extend` functions and tries
   * to explicitly add a `displayName` argument. The display name is taken from the corresponding
   * `VariableDeclaration` if possible.
   */
  const displayNameVisitor: Visitor<State> = {
    CallExpression(path) {
      const {
        node: { callee },
      } = path;
 
      const getImplicitDisplayName = (node: t.Node): string | null => {
        return node.type === 'VariableDeclarator' &&
          node.id.type === 'Identifier'
          ? node.id.name
          : null;
      };
 
      const isClassBoundCall = () => {
        if (
          callee.type === 'Identifier' &&
          callee.name === this.classBoundSpecifier
        ) {
          return true;
        }
 
        if (
          callee.type === 'MemberExpression' &&
          callee.object.type === 'Identifier' &&
          callee.object.name === this.classBoundSpecifier
        ) {
          const propertyName = getStaticExpressionValue(
            callee.property as t.Expression
          );
          return !!propertyName && reservedMethods.indexOf(propertyName) < 0;
        }
 
        return false;
      };
 
      if (this.classBoundSpecifier && isClassBoundCall()) {
        const displayName = getImplicitDisplayName(path.parent);
 
        if (displayName) {
          addDisplayNameToClassBound(path.node, displayName);
        }
      } else if (
        callee.type === 'MemberExpression' &&
        callee.object.type === 'Identifier' &&
        callee.object.name === this.classBoundSpecifier
      ) {
        const displayName = getImplicitDisplayName(path.parent);
        const propertyName = getStaticExpressionValue(
          callee.property as t.Expression
        );
 
        if (propertyName === 'extend' && displayName) {
          addDisplayNameToExtend(path.node, displayName);
        }
      } else if (
        this.extendSpecifier &&
        callee.type === 'Identifier' &&
        callee.name === this.extendSpecifier
      ) {
        const displayName = getImplicitDisplayName(path.parent);
 
        Eif (displayName) {
          addDisplayNameToExtend(path.node, displayName);
        }
      }
    },
  };
 
  /**
   * Visits all `CallExpression`s and searches for calls of the `classBound` function (or as whatever
   * symbol it is imported in the current module) and tries to replace a proxy member access of
   * `classBound[IntrinsicElement]()` with an explicit `elementType` argument.
   */
  const elementTypeVisitor: Visitor<State> = {
    CallExpression(path) {
      const {
        node: { callee },
      } = path;
 
      Eif (
        this.classBoundSpecifier &&
        callee.type === 'MemberExpression' &&
        callee.object.type === 'Identifier' &&
        callee.object.name === this.classBoundSpecifier
      ) {
        // Try to get the property name from Identifier, StringLiteral, TemplateLiteral etc.
        const propertyValue = getStaticExpressionValue(
          callee.property as t.Expression
        );
 
        if (propertyValue && reservedMethods.indexOf(propertyValue) < 0) {
          inlineElementType(path.node, propertyValue);
          path.node.callee = t.identifier(this.classBoundSpecifier);
        }
      }
    },
  };
 
  const safeNonObjectTypes: Array<t.Expression['type']> = [
    'StringLiteral',
    'TemplateLiteral',
    'BinaryExpression',
  ];
 
  const allowedFirstArgumentTypes: Array<t.Expression['type']> = [
    ...safeNonObjectTypes,
    'ArrayExpression',
  ];
 
  const addDisplayNameToExtend = (
    call: t.CallExpression,
    displayName: string
  ) => {
    // When there's more than 3 arguments, it has to be the full signature
    if (call.arguments.length > 3) {
      return;
    }
 
    Eif (
      // Can safely add the third argument
      call.arguments.length < 3 ||
      // Third argument has to be variants
      (call.arguments.length === 3 &&
        call.arguments[2].type === 'ObjectExpression')
    ) {
      call.arguments.splice(2, 0, t.stringLiteral(displayName));
    }
  };
 
  /**
   * Given a `classBound` call expression, adds an explicit displayName argument if possible
   */
  const addDisplayNameToClassBound = (
    call: t.CallExpression,
    displayName: string | null
  ) => {
    if (
      call.arguments.length === 1 &&
      call.arguments[0].type === 'ObjectExpression'
    ) {
      transformOptionsSignature(call.arguments[0], displayName);
      return;
    }
 
    if (
      call.arguments.length > 0 &&
      (allowedFirstArgumentTypes as Array<string>).includes(
        call.arguments[0].type
      )
    ) {
      transformPositionalSignatures(call, displayName);
      return;
    }
  };
 
  const allowedObjectPropertyTypes: Array<
    t.ObjectExpression['properties'][0]['type']
  > = ['ObjectMethod', 'ObjectProperty'];
 
  /**
   * Given an object expression representing a `classBound` options object, adds a `displayName` property.
   * `displayName` is only added when it's clear that it's not already present. E.g., when spreading another
   * object into the options object, we can't be sure a `displayName` is not already provided.
   */
  const transformOptionsSignature = (
    objectExpression: t.ObjectExpression,
    displayName: string | null
  ) => {
    Eif (displayName) {
      if (
        !objectExpression.properties.every((p) =>
          allowedObjectPropertyTypes.includes(p.type)
        )
      ) {
        return;
      }
 
      const properties = objectExpression.properties as Array<
        t.ObjectMethod | t.ObjectProperty
      >;
 
      if (properties.some((p) => isStaticObjectKey(p.key, 'displayName'))) {
        return;
      }
 
      objectExpression.properties.push(
        t.objectProperty(
          t.identifier('displayName'),
          t.stringLiteral(displayName)
        )
      );
    }
  };
 
  /**
   * Given a CallExpression of `classBound[JSX.IntrinsicElement]()` tries to move the proxy method.
   * Returns a boolean indicating whether it was successfully added.
   */
  const inlineElementType = (call: t.CallExpression, elementType: string) => {
    const [optionsOrClassName] = call.arguments;
 
    if (
      call.arguments.length === 1 &&
      optionsOrClassName.type === 'ObjectExpression'
    ) {
      optionsOrClassName.properties.push(
        t.objectProperty(
          t.identifier('elementType'),
          t.stringLiteral(elementType)
        )
      );
 
      return;
    }
 
    // When the second argument is an ObjectExpression it has to be [className, variants, elementType]
    const isShortSignature =
      call.arguments.length === 2 &&
      call.arguments[1].type === 'ObjectExpression';
 
    // When it's not for sure the short signature it has to be [className, displayName, variants, elementType],
    // otherwise elementType can always be passed as the fourth argument
    const elementTypePosition = isShortSignature ? 2 : 3;
 
    // Fill with null literals
    for (let i = 0; i < elementTypePosition; ++i) {
      if (!call.arguments[i]) {
        call.arguments[i] = t.nullLiteral();
      }
    }
 
    call.arguments[elementTypePosition] = t.stringLiteral(elementType);
  };
 
  const transformPositionalSignatures = (
    call: t.CallExpression,
    displayName: string | null
  ) => {
    if (displayName && shouldInsertDisplayNameIntoPositionalSignature(call)) {
      call.arguments.splice(1, 0, t.stringLiteral(displayName));
    }
  };
 
  /**
   * Given an arbitrary expression, tries to retrieve its static value, e.g.,
   * for Identifiers, StringLiterals or TemplateLiterals with only static parts
   */
  const getStaticExpressionValue = (expression: t.Expression) => {
    switch (expression.type) {
      case 'Identifier':
        return expression.name;
 
      case 'StringLiteral':
        return expression.value;
 
      case 'TemplateLiteral':
        return expression.quasis.length === 1
          ? expression.quasis[0].value.raw
          : null;
 
      default:
        return null;
    }
  };
 
  const isStaticObjectKey = (key: t.Expression, name: string) =>
    getStaticExpressionValue(key) === name;
 
  /**
   * Given a `CallExpression` of the `classBound` function, tries to infer the signature used by the nature
   * of the arguments and decides whether it is safe to insert an explicit `displayName` as the second argument.
   * It is considered safe when it is clear that no explicit `displayName` is given in the input.
   *
   * @param   call        Call to check for arguments
   * @returns             Whether to insert an explicit `displayName`
   */
  const shouldInsertDisplayNameIntoPositionalSignature = (
    call: t.CallExpression
  ) => {
    // When there's only the className argument there cannot be a displayName
    if (call.arguments.length === 1) {
      return true;
    }
 
    // When there are multiple arguments we can be sure that the second is variants
    // when it's an object expression, so `displayName` can be added before it
    if (
      call.arguments.length > 1 &&
      call.arguments[1].type === 'ObjectExpression'
    ) {
      return true;
    }
 
    // When there are three arguments and the (className, variants, elementType) signature couldn't be
    // inferred from `variants` being an ObjectExpression, we can still be sure we have it when the last
    // one is a string (i.e. `elementType` is an intrinsic JSX element)
    if (
      call.arguments.length === 3 &&
      safeNonObjectTypes.includes(
        call.arguments[2].type as t.Expression['type']
      )
    ) {
      return true;
    }
 
    return false;
  };
 
  return importClassBoundVisitor as Visitor<any>;
}