awesome-cordova-plugins/scripts/build/transformers/methods.ts

79 lines
1.9 KiB
TypeScript
Raw Normal View History

import {
createBinary,
createBlock,
createCall,
createIdentifier,
createIf,
createImmediatelyInvokedArrowFunction,
createLiteral,
createMethod,
createReturn,
createThis,
createTrue,
Expression,
MethodDeclaration,
SyntaxKind,
} from 'typescript';
2017-12-29 12:15:34 +08:00
import { Logger } from '../../logger';
2020-05-16 20:40:49 +08:00
import {
convertValueToLiteral,
getDecorator,
getDecoratorArgs,
getDecoratorName,
getMethodsForDecorator,
} from '../helpers';
2017-12-28 20:28:44 +08:00
export function transformMethod(method: MethodDeclaration) {
2017-12-28 20:28:44 +08:00
if (!method) return;
const decorator = getDecorator(method),
decoratorName = getDecoratorName(decorator),
decoratorArgs = getDecoratorArgs(decorator);
try {
return createMethod(
2020-05-16 20:40:49 +08:00
undefined,
undefined,
undefined,
method.name,
undefined,
method.typeParameters,
method.parameters,
method.type,
createBlock([createReturn(getMethodBlock(method, decoratorName, decoratorArgs))])
2020-05-16 20:40:49 +08:00
);
2017-12-28 20:28:44 +08:00
} catch (e) {
2017-12-29 12:15:34 +08:00
Logger.error('Error transforming method: ' + (method.name as any).text);
Logger.error(e.message);
2017-12-28 20:28:44 +08:00
}
}
function getMethodBlock(method: MethodDeclaration, decoratorName: string, decoratorArgs: any): Expression {
2017-12-28 20:28:44 +08:00
const decoratorMethod = getMethodsForDecorator(decoratorName)[0];
switch (decoratorName) {
case 'CordovaCheck':
case 'InstanceCheck':
// TODO remove function wrapper
return createImmediatelyInvokedArrowFunction([
createIf(
createBinary(
createCall(createIdentifier(decoratorMethod), undefined, [createThis()]),
SyntaxKind.EqualsEqualsEqualsToken,
createTrue()
2020-05-16 20:40:49 +08:00
),
method.body
2017-12-28 20:28:44 +08:00
),
2020-05-16 20:40:49 +08:00
]);
2017-12-28 20:28:44 +08:00
default:
return createCall(createIdentifier(decoratorMethod), undefined, [
createThis(),
createLiteral(decoratorArgs?.methodName || (method.name as any).text),
2017-12-28 20:28:44 +08:00
convertValueToLiteral(decoratorArgs),
createIdentifier('arguments'),
2017-12-28 20:28:44 +08:00
]);
}
}