awesome-cordova-plugins/scripts/build/transformers/extract-injectables.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

import { unlinkSync, writeJSONSync } from 'fs-extra';
2021-09-28 02:32:20 +08:00
import { resolve } from 'path';
import { ClassDeclaration, SyntaxKind, TransformationContext, visitEachChild } from 'typescript';
2018-03-23 17:57:54 +08:00
2017-12-28 20:28:44 +08:00
import { hasDecorator, ROOT } from '../helpers';
export interface InjectableClassEntry {
file: string;
className: string;
dirName: string;
}
const injectableClasses: InjectableClassEntry[] = [];
2021-09-28 02:32:20 +08:00
export const EMIT_PATH = resolve(ROOT, 'injectable-classes.json');
2017-12-28 20:28:44 +08:00
/**
* This transformer extracts all the injectable classes
* so we can use all the names later on when we compile
* an es5 bundle.
*
* Every injectable class will end up in the
* window['IonicNative'] object.
*/
export function extractInjectables() {
return (ctx: TransformationContext) => {
2021-09-28 04:09:05 +08:00
return (tsSourceFile) => {
if (tsSourceFile.fileName.indexOf('src/@awesome-cordova-plugins/plugins') > -1) {
visitEachChild(
2018-03-23 17:57:54 +08:00
tsSourceFile,
2021-09-28 04:09:05 +08:00
(node) => {
if (node.kind !== SyntaxKind.ClassDeclaration) {
2018-03-23 17:57:54 +08:00
return node;
}
const isInjectable: boolean = hasDecorator('Injectable', node);
if (isInjectable) {
injectableClasses.push({
file: tsSourceFile.path,
className: (node as ClassDeclaration).name.text,
2020-05-16 20:40:49 +08:00
dirName: tsSourceFile.path.split(/[\\\/]+/).reverse()[1],
2018-03-23 17:57:54 +08:00
});
}
},
ctx
);
2017-12-28 20:28:44 +08:00
}
return tsSourceFile;
2018-03-23 17:57:54 +08:00
};
2017-12-28 20:28:44 +08:00
};
}
export function emitInjectableClasses() {
writeJSONSync(EMIT_PATH, injectableClasses);
2017-12-28 20:28:44 +08:00
}
export function cleanEmittedData() {
unlinkSync(EMIT_PATH);
2017-12-28 20:28:44 +08:00
}