fileserver/tools/apigen.ts
2022-08-17 21:59:51 +02:00

63 lines
1.7 KiB
TypeScript

import {
AST_NODE_TYPES,
createProgram,
parse
} from '@typescript-eslint/typescript-estree';
import * as fs from 'fs';
import {
Decorator,
ExportDefaultDeclaration,
FunctionExpression,
Literal
} from '@typescript-eslint/types/dist/generated/ast-spec';
const program = createProgram('tsconfig.json');
const ast = parse(fs.readFileSync('src/controller/filesystem.ts').toString(), {
programs: [program]
});
function parseDecorators(decs: Decorator[]): object[] | null {
try {
return decs.map((dec) => {
if (dec.expression.type !== AST_NODE_TYPES.CallExpression)
throw null;
if (dec.expression.callee.type != AST_NODE_TYPES.Identifier)
throw null;
const name = dec.expression.callee.name;
if (name === 'Request') throw null;
const prop = (
dec.expression.arguments
.filter((arg) => arg.type === AST_NODE_TYPES.Literal)
.pop() as Literal
).value;
return { name: name, prop: prop };
});
} catch (e) {
return null;
}
}
function parseFunction(name: string, func: FunctionExpression) {
const decs = func.params
.map((p) => p.decorators)
.map(parseDecorators)
.filter((d) => d !== null);
console.log(name, decs);
}
ast.body
.filter((body) => body.type == AST_NODE_TYPES.ExportDefaultDeclaration)
.forEach((body: ExportDefaultDeclaration) => {
if (body.declaration.type !== AST_NODE_TYPES.ClassDeclaration) return;
if (body.declaration.body.type !== AST_NODE_TYPES.ClassBody) return;
body.declaration.body.body.forEach((def) => {
if (
def.type === AST_NODE_TYPES.MethodDefinition &&
'name' in def.key &&
def.key.name !== 'constructor' &&
def.value.type === AST_NODE_TYPES.FunctionExpression
)
parseFunction(def.key.name, def.value);
});
});