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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | 1x 1x 1x 1x 1x 1x 1x 1x 31x 1x 1x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 13x 46x 46x 46x 11x 11x 9x 2x 2x 44x 39x 5x 3x 3x 17x 1x 1x 1x 1x 16x 3x 3x 44x 9x 44x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 47x 33x 33x 33x 33x 33x 11x 14x 12x 2x 2x 37x 37x 37x 47x 47x 47x 47x 47x 4x 4x 4x 4x 4x 47x 10x 20x 10x 37x 37x 37x 25x 25x 12x 12x 12x 12x 37x 41x 41x 41x 41x 41x 41x 1x 41x 23x 23x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 33x 33x 32x 29x 29x 29x 5x 24x 29x 24x 24x 24x 19x 5x 5x 5x 5x 14x 186x 186x 1x 1x 185x 12x 12x 12x 173x 136x 173x 67x 7x 60x 4x 14x 14x 14x 1x 12x 24x 12x 7x 7x 4x 4x 4x 32x 32x 1x 35x 31x 44x 42x 42x 44x 186x 41x 1x | 'use strict'; require('source-map-support/register'); var _templates = require('./helpers/templates'); var th = _interopRequireWildcard(_templates); var _ast = require('./helpers/ast'); var _classes = require('./helpers/classes'); var _exports = require('./helpers/exports'); var _jsdoc = require('./helpers/jsdoc'); 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)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /* References: Babel Plugin Handbook: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md AST Spec: https://github.com/babel/babylon/blob/master/ast/spec.md Babel Types (t.*) https://github.com/babel/babel/tree/master/packages/babel-types AST Explorer: https://astexplorer.net/ */ const tempModuleName = name => `__${ name }`; // import t from 'babel-types' module.exports = ({ types: t }) => { const ProgramVisitor = { // Use a ProgramVisitor to efficiently avoid processing the same file twice if babel calls twice. // The UI5ModuleVisitor will only be used if it hasn't let ran. Program: { exit(path, { opts }) { Iif (this.ran) return; this.ran = true; let { node } = path; let { body } = node; this.defaultExport = null; this.defaultExportNode = null; this.exportGlobal = false; this.imports = []; this.namedExports = []; this.wrap = null; this.requires = []; // Opts handling this.namespacePrefix = opts.namespacePrefix; const { noImportInteroptPrefixes = ['sap/'] } = opts; this.noImportInteroptPrefixesRegexp = new RegExp(noImportInteroptPrefixes.map(p => `(^${ p }.*)`).join('|')); this.programNode = node; path.traverse(UI5ModuleVisitor, this); if (this.wrap === false) { return; } let allExportHelperAdded = false; opts.collapse = !opts.noExportCollapse; // opts.extend = !opts.noExportExtend // Before adding anything, see if the named exports can be collapsed into the default export. if (this.defaultExport && this.namedExports.length && opts.collapse) { let filteredExports = (0, _exports.collapseNamedExports)(node, this.defaultExportDeclaration, this.namedExports, opts); if (!filteredExports.length) { this.namedExports = []; } else Eif (!opts.allowUnsafeMixedExports) { throw new Error(`Unsafe mixing of default and named exports. The following named exports can't be collapsed or ignored: \n(${ (0, _ast.getPropNames)(filteredExports).join(', ') }).`); } } if (!this.namedExports.length && this.defaultExport) { body.push(t.returnStatement(this.defaultExport)); } else if (this.namedExports.length) { node.body.unshift(...[th.buildDeclareExports(), th.buildExportsModuleDeclaration()]); for (let namedExport of this.namedExports) { if (namedExport.all) { Eif (!allExportHelperAdded) { node.body.push(th.buildAllExportHelper()); allExportHelperAdded = true; } node.body.push(th.buildAllExport({ LOCAL: namedExport.value })); } else { node.body.push(th.buildNamedExport(namedExport)); } } Iif (this.defaultExport) { node.body.push(th.buildNamedExport({ key: t.identifier('default'), value: this.defaultExport })); // TODO have a flag to enable/disable export interop altogether // Add all of default's properties to the export. // if (t.isObjectExpression(this.defaultExportDeclaration) && this.defaultExportDeclaration.properties) { // for (const property of this.defaultExportDeclaration.properties) { // const { key, value } = property // const matchingNamedExport = this.namedExports.find(namedExport => namedExport.key.name === key.name) // if (!matchingNamedExport) { // No matching named export, so it's safe to add // node.body.push( // th.buildNamedExport({ // key, value // }) // ) // } // Else conflict with a named export // else if (value && key.name === value.name) { // // The value is the same as the named export. No action needed. // continue // } // else { // // TODO have a flag to enable/disable export interop // throw path.buildCodeFrameError(`Can't build interop export since default export's key '${key.name}' conflicts with named export.`) // } // } // } } body.push(t.returnStatement(t.identifier('exports'))); } // setInteroptFlag(this.imports, opts) if (this.imports.some(imp => imp.interopt)) { body.unshift(th.buildDefaultImportInterop()); } node.body = [generateDefine(body, this.imports, this.exportGlobal || opts.exportAllGlobal)]; } } }; const UI5ModuleVisitor = { /*! * Removes the ES6 import and adds the details to the import array in our state. */ ImportDeclaration(path, { opts = {} }) { this.wrap = true; const { node } = path; const { specifiers, source } = node; const src = source.value.replace(/\\/g, '/'); const noInteropt = this.noImportInteroptPrefixesRegexp.test(src); const testLibs = opts.libs || ['^sap/']; const isLibRE = testLibs.length && new RegExp(`(${ testLibs.join('|') })`); const isLib = isLibRE.test(src); const testSrc = (opts.libs || ['^sap/']).concat(opts.files || []); const isUi5SrcRE = testSrc.length && new RegExp(`(${ testSrc.join('|') })`); const isUi5Src = isUi5SrcRE.test(src); const name = src.replace(/\//g, '_').replace(/\./g, ''); // default to the src for import without named var let tmpName = noInteropt ? name : tempModuleName(name); const imp = { src, name, isLib, isUi5Src, tmpName }; const destructors = []; for (const specifier of specifiers) { if (t.isImportDefaultSpecifier(specifier)) { imp.default = true; imp.interopt = !noInteropt; // Shorten the imported as name. The default import should always come first, // so this new name will be used for destructoring the other too. imp.name = specifier.local.name; tmpName = imp.tmpName = noInteropt ? imp.name : tempModuleName(imp.name); if (!noInteropt) { destructors.push(th.buildDefaultImportDestructor({ MODULE: t.identifier(imp.tmpName), LOCAL: specifier.local })); } } else if (t.isImportSpecifier(specifier)) { destructors.push(th.buildNamedImportDestructor({ MODULE: t.identifier(imp.tmpName), LOCAL: specifier.local, IMPORTED: t.stringLiteral(specifier.imported.name) })); } else Eif (t.isImportNamespaceSpecifier(specifier)) { destructors.push(th.buildConstDeclaration({ NAME: specifier.local, VALUE: t.identifier(imp.tmpName) })); } else { throw path.buildCodeFrameError(`Unknown ImportDeclaration specifier type ${ specifier.type }`); } } path.replaceWithMultiple(destructors); imp.path = path; this.imports.push(imp); }, /** * Push all exports to an array. * The reason we don't export in place is to handle the situation * where a let or var can be defined, and the latest one should be * expored. */ ExportNamedDeclaration(path) { this.wrap = true; const { node } = path; const { specifiers, declaration, source } = node; let fromSource = ''; if (source) { // export { one, two } from 'x' const src = source.value; const name = src.replace(/\//g, '_').replace(/\./g, ''); const tmpName = tempModuleName(name); this.imports.push({ src, name, tmpName }); fromSource = tmpName + '.'; } if (specifiers && specifiers.length) { // export { one, two } for (const specifier of path.node.specifiers) { this.namedExports.push({ key: specifier.exported, value: t.identifier(`${ fromSource }${ specifier.local.name }`) }); } path.remove(); } else Eif (declaration) { // export const c = 1 | export function f() {} const name = (0, _ast.getIdName)(declaration); if (name) { // export function f() {} const id = t.identifier(declaration.id.name); this.namedExports.push({ key: id, value: id }); } else Eif (declaration.declarations) { // export const c = 1 for (const subDeclaration of declaration.declarations) { const id = t.identifier(subDeclaration.id.name); this.namedExports.push({ value: id, key: id }); } } else { throw path.buildCodeFrameError('Unknown ExportNamedDeclartion shape.'); } path.replaceWith(declaration); } else { throw path.buildCodeFrameError('Unknown ExportNamedDeclartion shape.'); } }, /*! * Replaces the ES6 export with sap.ui.define by using the state.imports array built up when * visting ImportDeclaration. * Only a single 'export default' is supported. */ ExportDefaultDeclaration(path) { this.wrap = true; const { node } = path; const { declaration } = node; this.defaultExportDeclaration = declaration; const declarationName = (0, _ast.getIdName)(declaration); if (hasGlobalExportFlag(node)) { // check for @export jsdoc this.exportGlobal = true; } if (declarationName) { // ClassDeclaration or FunctionDeclaration with name. // Leave the declaration in-line and preserve the identifier for the return statement. path.replaceWith(declaration); this.defaultExport = t.identifier(declarationName); } else { // Identifier, ObjectExpression or anonymous FunctionDeclaration // Safe to move to the end and return directly Iif (t.isFunctionDeclaration(declaration)) { const { params, body, generator, async: isAsync } = declaration; this.defaultExport = t.functionExpression(null, params, body, generator, isAsync); } else { this.defaultExport = declaration; } path.remove(); } }, ExportAllDeclaration(path) { const src = path.node.source.value; const name = src.replace(/\//g, '_').replace(/\./g, ''); const tmpName = tempModuleName(name); this.imports.push({ src, name, tmpName }); this.exportAllHelper = true; this.namedExports.push({ all: true, value: t.identifier(tmpName) }); path.remove(); }, /** * ClassDeclaration visitor. * Use both enter() and exit() to track when the visitor is inside a UI5 class, * in order to convert the super calls. * No changes for non-UI5 classes. */ Class: { enter(path, { opts = {} }) { const { node, parent, parentPath } = path; if (opts.neverConvertClass) return; if (doesClassExtendFromImport(node, [...this.imports, ...this.requires])) { const { name } = node.id; // If the super class is one of the imports, we'll assume it's a UI5 managed class, // and therefore needs to be transformed to .extend() syntax. const classInfo = (0, _classes.getClassInfo)(path, node, path.parent, opts); if (classInfo.nonUI5 || opts.onlyConvertNamedClass && !classInfo.name) { return; } this.superClassName = classInfo.superClassName; // Find the Block scoped parent (Program or Function body) and search for assigned properties within that. const blockParent = path.findParent(path => path.isBlock()).node; const staticProps = (0, _ast.groupPropertiesByName)((0, _ast.getOtherPropertiesOfIdentifier)(blockParent, name)); // TODO flag metadata and renderer for removal if applicable const ui5ExtendClass = (0, _classes.convertClassToUI5Extend)(node, classInfo, staticProps); if (path.isClassDeclaration()) { // class X {} path.replaceWithMultiple(ui5ExtendClass); } else Eif (path.isClassExpression()) { // return class X {} Eif (t.isReturnStatement(parent)) { // Add the return statement back before calling replace ui5ExtendClass.push(th.buildReturn({ ID: t.identifier(classInfo.localName) })); } parentPath.replaceWithMultiple(ui5ExtendClass); } } }, exit() { this.superClassName = null; } }, /*! * Visits function calls. */ CallExpression(path) { const node = path.node; // If state.wrap is still null, this IIFE was enconuntered before any other calls, imports or exports. if (isIIFE(node) && !this.wrap) { this.wrap = false; return; } // If the file already has SAPUIDefine, then don't wrap. Keep visiting so we can fix non-class constructor() else if ((0, _classes.isSAPUIDefineCallExpression)(node)) { this.wrap = false; this.requires = getRequiredParamsOfSAPUIDefine(path, node); return; } // If we encounter a call expression prior to a wrapping iife or sap.ui.define, // then we need to wrap with sap.ui.defined else if (this.wrap !== false) { this.wrap = true; } if (this.superClassName) { if (t.isSuper(node.callee)) { replaceConstructorSuperCall(path, node, this.superClassName); } else if (t.isSuper(node.callee.object)) { replaceObjectSuperCall(path, node, this.superClassName); } } }, /** * Convert object method constructor() to constructor: function constructor(), * since a UI5 class is not a real class. */ ObjectMethod(path) { const { node } = path; const CONSTRUCTOR = 'constructor'; if (node.key.name === CONSTRUCTOR) { // The keyword 'constructor' should not be used as a shorthand // method name in an object. It might(?) work on some objects, // but it doesn't work with X.extend(...) inheritance. path.replaceWith(t.objectProperty(t.identifier(CONSTRUCTOR), t.functionExpression(t.identifier(CONSTRUCTOR), node.params, node.body))); } } }; function getRequiredParamsOfSAPUIDefine(path, node) { const defineArgs = node.arguments; const callbackNode = defineArgs.find(argNode => argNode.type === 'ArrowFunctionExpression' || argNode.type === 'FunctionExpression'); return callbackNode.params; // Identifier } /** * Replace super() call */ function replaceConstructorSuperCall(path, node, superClassName) { node.arguments.unshift(t.identifier('this')); path.replaceWith(t.callExpression(t.identifier(`${ superClassName }.prototype.constructor.call`), node.arguments)); } /** * Replace super.method() call */ function replaceObjectSuperCall(path, node, superClassName) { node.arguments.unshift(t.identifier('this')); const callIdentifier = t.identifier(`${ superClassName }.prototype.${ node.callee.property.name }.call`); path.replaceWith(t.callExpression(callIdentifier, node.arguments)); } function doesClassExtendFromImport(node, imports) { const superClass = node.superClass; if (!superClass) { return false; } const isImported = imports.some(imported => imported.name === superClass.name); return isImported; } function generateDefine(body, imports, exportGlobal) { const defineOpts = { SOURCES: imports.map(i => t.stringLiteral(i.src)), PARAMS: imports.map(i => t.identifier(i.tmpName)), BODY: body }; return exportGlobal ? th.buildDefineGlobal(defineOpts) : th.buildDefine(defineOpts); } function isIIFE(node) { return t.isCallExpression(node) && t.isFunctionExpression(node.callee); } function hasGlobalExportFlag(node) { return (0, _jsdoc.hasJsdocGlobalExportFlag)(node); } return { visitor: ProgramVisitor }; }; |