All files / dist/helpers classes.js

85.71% Statements 108/126
77.27% Branches 85/110
100% Functions 9/9
92.79% Lines 103/111
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    1x     1x 1x   1x   1x   1x   1x   1x   1x   1x   1x   2x   2x                 38x       38x 38x 38x 38x   38x 38x 38x 38x 38x 38x 38x 38x     38x   38x 73x 10x       38x 128x   128x   128x 90x   90x 5x   85x 85x 85x   85x 5x     80x 13x 13x   13x 1x       79x   79x     38x 38x   10x 28x 6x     6x     22x   22x                 22x 13x   9x                   38x 38x   38x   38x   38x 38x 38x   38x 1x           1x 1x     38x 1x       2x       38x     7x 13x         14x   7x   1x   6x 6x 6x       38x           38x                                     38x 36x 11x 11x       44x         44x 44x 44x                 44x   44x   44x   44x 44x       44x   44x   44x 1x     44x        
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.convertClassToUI5Extend = convertClassToUI5Extend;
exports.getClassInfo = getClassInfo;
 
require("source-map-support/register");
 
var _core = require("@babel/core");
 
var th = _interopRequireWildcard(require("./templates"));
 
var _path = _interopRequireDefault(require("path"));
 
var _objectAssignDefined = _interopRequireDefault(require("object-assign-defined"));
 
var ast = _interopRequireWildcard(require("./ast"));
 
var _jsdoc = require("./jsdoc");
 
var _decorators = require("./decorators");
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
 
/**
 * Converts an ES6 class to a UI5 extend.
 * Any static methods or properties will be moved outside the class body.
 * The path will be updated with the new AST.
 */
function convertClassToUI5Extend(path, node, classInfo, extraStaticProps, opts) {
  // eslint-disable-line no-unused-vars
  Iif (!(_core.types.isClassDeclaration(node) || _core.types.isClassExpression(node))) {
    return node;
  }
 
  const staticMembers = [];
  const classNameIdentifier = node.id;
  const className = classNameIdentifier.name;
  const superClass = node.superClass; // Identifier
 
  const superClassName = node.superClass.name;
  const isController = className.includes("Controller") || !!classInfo.controller;
  const moveControllerPropsToOnInit = isController && !!opts.moveControllerPropsToOnInit;
  const moveStaticStaticPropsToExtend = isController && !!opts.addControllerStaticPropsToExtend;
  const extendProps = [];
  const boundProps = [];
  const CONSTRUCTOR = "constructor";
  const propsByName = {};
  let constructor;
  let constructorComments;
  const staticPropsToAdd = moveStaticStaticPropsToExtend ? Object.keys(extraStaticProps) : ["metadata", "renderer"];
 
  for (const propName of staticPropsToAdd) {
    if (extraStaticProps[propName]) {
      extendProps.push(_core.types.objectProperty(_core.types.identifier(propName), extraStaticProps[propName]));
    }
  }
 
  for (const member of node.body.body) {
    const memberName = member.key.name;
 
    const memberExpression = member.static && _core.types.memberExpression(classNameIdentifier, member.key);
 
    if (_core.types.isClassMethod(member)) {
      const func = _core.types.functionExpression(member.key, member.params, member.body, member.generator, member.async);
 
      if (member.static) {
        staticMembers.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", memberExpression, func)));
      } else {
        propsByName[memberName] = func;
        func.generator = member.generator;
        func.async = member.async;
 
        if (member.kind === "get" || member.kind === "set") {
          extendProps.push(_core.types.objectMethod(member.kind, member.key, member.params, member.body, member.computed));
        } else {
          // method
          if (memberName === CONSTRUCTOR) {
            constructorComments = member.leadingComments;
            constructor = func;
 
            if (moveControllerPropsToOnInit) {
              continue; // don't push to props yet
            }
          }
 
          func.id = path.scope.generateUidIdentifier(func.id.name); // Give the function a unique name
 
          extendProps.push(_core.types.objectProperty(member.key, func));
        }
      }
    } else Eif (_core.types.isClassProperty(member)) {
      if (memberName === "metadata" || memberName === "renderer") {
        // Special handling for TypeScript limitation where metadata and renderer must be properties.
        extendProps.unshift(_core.types.objectProperty(member.key, member.value));
      } else if (member.static) {
        Iif (moveStaticStaticPropsToExtend) {
          extendProps.unshift(_core.types.objectProperty(member.key, member.value));
        } else {
          staticMembers.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", memberExpression, member.value)));
        }
      } else {
        propsByName[memberName] = member.value;
 
        Iif (memberName === "constructor") {
          constructorComments = member.leadingComments;
          constructor = member.value;
 
          if (moveControllerPropsToOnInit) {
            continue; // don't push to props yet
          }
        }
 
        if (_core.types.isArrowFunctionExpression(member.value) || ast.isThisExpressionUsed(member.value)) {
          boundProps.push(member);
        } else {
          extendProps.push(_core.types.objectProperty(member.key, member.value));
        }
      }
    }
  } // Arrow function properties need to get moved to the constructor so that
  // they're bound properly to the class instance, to align with the spec.
  // For controllers, use onInit rather than constructor, since controller constructors don't work.
  // Also move the constructor's statements to the onInit.
 
 
  const bindToConstructor = !moveControllerPropsToOnInit;
  const bindToMethodName = moveControllerPropsToOnInit ? "onInit" : "constructor";
 
  const bindToId = _core.types.identifier(bindToMethodName);
 
  let bindMethod = moveControllerPropsToOnInit ? propsByName[bindToMethodName] : constructor; // avoid getting a prop named constructor as it may return {}'s
 
  const constructorJsdoc = (0, _jsdoc.getTags)(constructorComments);
  const keepConstructor = classInfo.keepConstructor || constructorJsdoc.keep;
  const needsBindingMethod = boundProps.length || moveControllerPropsToOnInit && constructor && !keepConstructor; // See if we need to inject the 'constructor' or 'onInit' method, depending which one we'll bind to.
 
  if (needsBindingMethod && !bindMethod) {
    const bindMethodDeclaration = bindToConstructor ? th.buildInheritingConstructor({
      SUPER: _core.types.identifier(superClassName)
    }) : th.buildInheritingFunction({
      NAME: bindToId,
      SUPER: _core.types.identifier(superClassName)
    });
    bindMethod = ast.convertFunctionDeclarationToExpression(bindMethodDeclaration);
    extendProps.unshift(_core.types.objectProperty(bindToId, bindMethod));
  }
 
  if (moveControllerPropsToOnInit && constructor) {
    Iif (keepConstructor) {
      extendProps.unshift(_core.types.objectProperty(_core.types.identifier(CONSTRUCTOR), constructor));
    } else {
      // Copy all except the super call from the constructor to the bindMethod (i.e. onInit)
      bindMethod.body.body.unshift(...constructor.body.body.filter(node => !ast.isSuperCallExpression(node.expression)));
    }
  }
 
  if (boundProps.length) {
    // We need to inject the bound props into the bind method (constructor or onInit),
    // but not until after the super call (if applicable)
    const mappedProps = boundProps.map(prop => {
      return th.buildThisAssignment({
        NAME: prop.key,
        VALUE: prop.value
      });
    });
    const superIndex = bindMethod.body.body.findIndex(node => ast.isSuperCallExpression(node.expression) || ast.isSuperPrototypeCallOf(node.expression, superClassName, bindToMethodName));
 
    if (superIndex === -1) {
      // If there's no super, just add the bound props at the start
      bindMethod.body.body.unshift(...mappedProps);
    } else {
      const upToSuper = bindMethod.body.body.slice(0, superIndex + 1);
      const afterSuper = bindMethod.body.body.slice(superIndex + 1);
      bindMethod.body.body = [...upToSuper, ...mappedProps, ...afterSuper];
    }
  }
 
  const extendAssign = th.buildExtendAssign({
    NAME: classNameIdentifier,
    SUPERNAME: superClass,
    FQN: _core.types.stringLiteral(getFullyQualifiedName(classInfo)),
    OBJECT: _core.types.objectExpression(extendProps)
  });
  return [extendAssign, ...staticMembers];
}
/**
 * Sees if a class prop references 'this'.
 * The logic is a bit limited, as it currently only looks at the
 * @param {*} classPropValue
 */
// function doesClassPropUseThis(classPropValue) {
//   if (t.isCallExpression(classProperty)) {
//   }
//   else if (t.isMemberExpression(classProperty)) {
//   }
//   else {
//     return false
//   }
// }
 
 
function getFullyQualifiedName(classInfo) {
  if (classInfo.alias) return classInfo.alias;
  if (classInfo.name) return classInfo.name;
  const separator = classInfo.namespace ? "." : "";
  return `${classInfo.namespace}${separator}${classInfo.localName}`;
}
 
function getClassInfo(path, node, parent, pluginOpts) {
  const defaults = {
    localName: node.id.name,
    superClassName: node.superClass && node.superClass.name,
    namespace: getFileBaseNamespace(path, pluginOpts) || ""
  };
  const decoratorInfo = (0, _decorators.getDecoratorClassInfo)(node);
  const jsDocInfo = (0, _jsdoc.getJsDocClassInfo)(node, parent);
  return (0, _objectAssignDefined.default)( // like Object.assign, but ignoring undefined values.
  defaults, decoratorInfo, jsDocInfo);
}
/**
 * Reads the namespace from the file path, but not the name
 */
 
 
function getFileBaseNamespace(path, pluginOpts) {
  const opts = path.hub.file.opts;
 
  const filename = _path.default.resolve(opts.filename);
 
  const sourceRoot = opts.sourceRoot || process.cwd();
 
  Eif (filename.startsWith(sourceRoot)) {
    const filenameRelative = _path.default.relative(sourceRoot, filename);
 
    const {
      dir
    } = _path.default.parse(filenameRelative);
 
    const namespaceParts = dir.split(_path.default.sep);
 
    if (pluginOpts.namespacePrefix) {
      namespaceParts.unshift(pluginOpts.namespacePrefix);
    }
 
    return namespaceParts.join(".");
  } else {
    return undefined;
  }
}