-
Notifications
You must be signed in to change notification settings - Fork 132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use TS Morph to generate type predicates #1387
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { InterfaceDeclaration, MethodDeclaration, Project, SyntaxKind } from "ts-morph" | ||
|
||
// open a new project with just BrowserTypes as the only source file | ||
const project = new Project(); | ||
const sourceFile = project.addSourceFileAtPath("./src/api/BrowserTypes.ts") | ||
|
||
//get a list of all interfaces in the file | ||
const interfaces = sourceFile.getChildrenOfKind(SyntaxKind.InterfaceDeclaration); | ||
|
||
// get a list of all conversion functions in the Convert class | ||
const convert = sourceFile.getClass("Convert"); | ||
const convertFunctions = (convert?.getChildrenOfKind(SyntaxKind.MethodDeclaration) ?? []).filter(func => func.getReturnType().getText() === "string"); | ||
|
||
// generate a list of Interfaces that have an associated conversion function | ||
const matchedInterfaces = convertFunctions.map(func => { | ||
const valueParameter = func.getParameter("value"); | ||
|
||
const matchingInterface = interfaces.find(interfaceNode => { | ||
return valueParameter?.getType().getText(valueParameter) === interfaceNode.getName(); | ||
}); | ||
|
||
|
||
if(matchingInterface != null) { | ||
return {func, matchingInterface}; | ||
} | ||
|
||
return undefined; | ||
}).filter(((value => value != null) as <T>(value: T | null | undefined) => value is T)); | ||
|
||
// write a type predicate for each matched interface | ||
matchedInterfaces.forEach(matched => writePredicate(matched.matchingInterface, matched.func)); | ||
|
||
writeUnionType("RequestMessage", interfaces, "Request"); | ||
writeUnionType("ResponseMessage", interfaces, "Response"); | ||
writeUnionType("EventMessage", interfaces, "Event"); | ||
|
||
function writePredicate(matchingInterface: InterfaceDeclaration, func: MethodDeclaration): void{ | ||
const predicateName = `is${matchingInterface.getName()}`; | ||
|
||
sourceFile.addStatements(` | ||
export function ${predicateName}(value: any): value is ${matchingInterface.getName()} { | ||
try{ | ||
Convert.${func.getName()}(value); | ||
return true; | ||
} catch(e: any){ | ||
return false; | ||
} | ||
}`); | ||
} | ||
|
||
|
||
|
||
function writeUnionType(unionName: string, interfaces: InterfaceDeclaration[], nameEndsWith: string): void{ | ||
const matchingInterfaces = interfaces | ||
.map(currentInterface => currentInterface.getName()) | ||
.filter(interfaceName => interfaceName.length > nameEndsWith.length && interfaceName.indexOf(nameEndsWith) === interfaceName.length - nameEndsWith.length); | ||
|
||
sourceFile.addStatements(` | ||
export type ${unionName} = ${matchingInterfaces.join(" | ")};`); | ||
} | ||
|
||
sourceFile.formatText(); | ||
|
||
project.saveSync(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
{ | ||
// see https://www.typescriptlang.org/tsconfig to better understand tsconfigs | ||
"files": ["generate-type-predicates.ts"], | ||
"compilerOptions": { | ||
"module": "CommonJS", | ||
"lib": ["dom", "esnext"], | ||
"importHelpers": true, | ||
// output .d.ts declaration files for consumers | ||
"declaration": true, | ||
"outDir": "dist", | ||
// output .js.map sourcemap files for consumers | ||
"sourceMap": true, | ||
// match output dir to input dir. e.g. dist/index instead of dist/src/index | ||
"rootDir": "./", | ||
// stricter type-checking for stronger correctness. Recommended by TS | ||
"strict": true, | ||
// linter checks for common issues | ||
"noImplicitReturns": true, | ||
"noFallthroughCasesInSwitch": true, | ||
// noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative | ||
"noUnusedLocals": true, | ||
"noUnusedParameters": true, | ||
// use Node's module resolution algorithm, instead of the legacy TS one | ||
"moduleResolution": "node", | ||
// transpile JSX to React.createElement | ||
"jsx": "react", | ||
// interop between ESM and CJS modules. Recommended by TS | ||
"esModuleInterop": true, | ||
// significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS | ||
"skipLibCheck": true, | ||
// error out if import and file system have a casing mismatch. Recommended by TS | ||
"forceConsistentCasingInFileNames": true, | ||
// `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` | ||
"noEmit": true, | ||
} | ||
} | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,7 +27,9 @@ | |
"prepack": "npm run build", | ||
"typegen": "cd schemas && node ../s2tQuicktypeUtil.js context ../src/context/ContextTypes.ts", | ||
"typegen-browser": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json context/context.schema.json api ../src/api/BrowserTypes.ts", | ||
"typegen-bridging": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json api/broadcastRequest.schema.json api/findInstancesRequest.schema.json api/findInstancesResponse.schema.json api/findIntentRequest.schema.json api/findIntentResponse.schema.json api/findIntentsByContextRequest.schema.json api/findIntentsByContextResponse.schema.json api/getAppMetadataRequest.schema.json api/getAppMetadataResponse.schema.json api/openRequest.schema.json api/openResponse.schema.json api/raiseIntentRequest.schema.json api/raiseIntentResponse.schema.json api/raiseIntentResultResponse.schema.json context/context.schema.json bridging ../src/bridging/BridgingTypes.ts" | ||
"typegen-bridging": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json api/broadcastRequest.schema.json api/findInstancesRequest.schema.json api/findInstancesResponse.schema.json api/findIntentRequest.schema.json api/findIntentResponse.schema.json api/findIntentsByContextRequest.schema.json api/findIntentsByContextResponse.schema.json api/getAppMetadataRequest.schema.json api/getAppMetadataResponse.schema.json api/openRequest.schema.json api/openResponse.schema.json api/raiseIntentRequest.schema.json api/raiseIntentResponse.schema.json api/raiseIntentResultResponse.schema.json context/context.schema.json bridging ../src/bridging/BridgingTypes.ts", | ||
"posttypegen-browser": "npm run generate-type-predicates", | ||
"generate-type-predicates": "ts-node code-generation/generate-type-predicates.ts" | ||
Comment on lines
+31
to
+32
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Given that this is the only thing run 'post' typegen-browser you can probably combine these entries. |
||
}, | ||
"husky": { | ||
"hooks": { | ||
|
@@ -65,6 +67,8 @@ | |
"rimraf": "^5.0.5", | ||
"rollup": "4.22.4", | ||
"ts-jest": "29.1.2", | ||
"ts-morph": "^23.0.0", | ||
"ts-node": "^10.9.2", | ||
"tslib": "^2.0.1", | ||
"typescript": "^4.0.3" | ||
}, | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does this really need its own tsconfig.json, or could it use the existing one in the root? The only differences between the two tsconfig files appear to be:
"module": "CommonJS"
vs."module": "esnext"
AFAIK ts-node is quite happy to handle ESM...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am pretty sure that I would have only added this as I was getting errors without but hopefully I can get it to work without if I have another go.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The original one has an include filter that would have excluded your codegeneration directory: https://github.com/finos/FDC3/blob/1a21b027f506d9ed88d5e3a1d55be38ac03ae828/tsconfig.json#L3C25-L3C25
The only other difference is your
files
entry above - could it have been that it just wasn't applying to your file?