|
| 1 | +import ts from "typescript"; |
| 2 | +import * as path from "path"; |
| 3 | + |
| 4 | +function extractConstructorParams( |
| 5 | + sourceFile: string, |
| 6 | + className: string |
| 7 | +): { type: string; fields: string[] } | null { |
| 8 | + const absolutePath = path.resolve(sourceFile); |
| 9 | + const program = ts.createProgram([absolutePath], { |
| 10 | + target: ts.ScriptTarget.ES2015, |
| 11 | + module: ts.ModuleKind.CommonJS, |
| 12 | + }); |
| 13 | + const source = program.getSourceFile(absolutePath); |
| 14 | + const typeChecker = program.getTypeChecker(); |
| 15 | + |
| 16 | + if (!source) { |
| 17 | + console.error(`Could not find source file: ${absolutePath}`); |
| 18 | + return null; |
| 19 | + } |
| 20 | + |
| 21 | + let result: { type: string; fields: string[] } | null = null; |
| 22 | + |
| 23 | + function visit(node: ts.Node) { |
| 24 | + if (ts.isClassDeclaration(node) && node.name?.text === className) { |
| 25 | + node.members.forEach((member) => { |
| 26 | + if ( |
| 27 | + ts.isConstructorDeclaration(member) && |
| 28 | + member.parameters.length > 0 |
| 29 | + ) { |
| 30 | + const firstParam = member.parameters[0]; |
| 31 | + const type = typeChecker.getTypeAtLocation(firstParam); |
| 32 | + const typeString = typeChecker.typeToString(type); |
| 33 | + |
| 34 | + // Get properties of the type |
| 35 | + const fields: string[] = []; |
| 36 | + type.getProperties().forEach((prop) => { |
| 37 | + // Get the type of the property |
| 38 | + const propType = typeChecker.getTypeOfSymbolAtLocation( |
| 39 | + prop, |
| 40 | + firstParam |
| 41 | + ); |
| 42 | + // Only include non-function properties that don't start with __ |
| 43 | + if ( |
| 44 | + !prop.getName().startsWith("__") && |
| 45 | + prop.getName() !== "callbackManager" && |
| 46 | + !(propType.getCallSignatures().length > 0) |
| 47 | + ) { |
| 48 | + fields.push(prop.getName()); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + result = { |
| 53 | + type: typeString, |
| 54 | + fields, |
| 55 | + }; |
| 56 | + } |
| 57 | + }); |
| 58 | + } |
| 59 | + ts.forEachChild(node, visit); |
| 60 | + } |
| 61 | + |
| 62 | + visit(source); |
| 63 | + return result; |
| 64 | +} |
| 65 | +const filepath = process.argv[2]; |
| 66 | +const className = process.argv[3]; |
| 67 | + |
| 68 | +if (!filepath || !className) { |
| 69 | + console.error( |
| 70 | + "Usage: node extract_serializable_fields.ts <filepath> <className>" |
| 71 | + ); |
| 72 | + process.exit(1); |
| 73 | +} |
| 74 | + |
| 75 | +const results = extractConstructorParams(filepath, className); |
| 76 | + |
| 77 | +if (results?.fields?.length) { |
| 78 | + console.log(JSON.stringify(results?.fields, null, 2)); |
| 79 | +} else { |
| 80 | + console.error("No constructor parameters found"); |
| 81 | +} |
0 commit comments