Skip to content
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

[WIP] Work on using external modules #158

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
- [x] SDL should extend type for external types - I guess marking types in SDL
- [x] can't generate graphql-js stuff, don't want to do it for externs - don't support graphql-js for this?
- [x] all imported types (so support interfaces etc)
- [x] Read SDL to actually do validation
- [x] reenable global validations
- [x] "modular" mode? like no full schema, but parts of schema but with full validation by resolving it?
- [?] treat query/mutation/subscription as "import" type and extend it
- [ ] all tests to add fixtures for metadata/resolver map
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm onboard with this. Happy to have this as a separate PR if you want to merge that first.

- [ ] pluggable module resolution - too many variables there, use filepath by default, let users customize it
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory we only need this path in order to perform validation (is that right?). I wonder if there is a TypeScript API which will let us use the same (or most of) TypeScript's implementation of module resolution. I would need to avoid expecting the file to have a .js/.ts/.mjs/etc extension, but maybe something like that is exposed? I suspect that would be sufficient we could find something like that.

I did see this: https://github.com/microsoft/TypeScript/blob/6a00bd2422ffa46c13ac8ff81d7b4b1157e60ba7/src/server/project.ts#L484

Which could be a good place to start looking.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure any non-ts files are included in how the typescript resolves it. There is also the whole story of "lib" in package.json and stuff like this. Ultimately there is no "well-known" spot for the GraphQL files, so it feels like it all might just break weirdly. I will experiment on this ofc, but I feel that there might not be an easy solution.

- [ ] first try ts project resolution
- [ ] how to handle overimporting? Improting whole SDL module "infects" the schema with types that might not be requested.
- [ ] another check on error handling - I think eg enums and scalars accept stuff they shouldn't accept?
18 changes: 18 additions & 0 deletions src/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
SPECIFIED_BY_TAG,
CONTEXT_TAG,
INFO_TAG,
EXTERNAL_TAG,
AllTags,
} from "./Extractor";

export const ISSUE_URL = "https://github.com/captbaritone/grats/issues";
Expand Down Expand Up @@ -153,6 +155,10 @@ export function typeTagOnAliasOfNonObjectOrUnknown() {
return `Expected \`@${TYPE_TAG}\` type to be an object type literal (\`{ }\`) or \`unknown\`. For example: \`type Foo = { bar: string }\` or \`type Query = unknown\`.`;
}

export function nonExternalTypeAlias(tag: AllTags) {
return `Expected \`@${tag}\` to be a type alias only if used with \`@${EXTERNAL_TAG}\``;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The constraint here is just that it not be a runtime construct. Can we expand this to also support interfaces?

}

// TODO: Add code action
export function typeNameNotDeclaration() {
return `Expected \`__typename\` to be a property declaration. For example: \`__typename: "MyType"\`.`;
Expand Down Expand Up @@ -607,3 +613,15 @@ export function noTypesDefined() {
export function tsConfigNotFound(cwd: string) {
return `Grats: Could not find \`tsconfig.json\` searching in ${cwd}.\n\nSee https://www.typescriptlang.org/download/ for instructors on how to add TypeScript to your project. Then run \`npx tsc --init\` to create a \`tsconfig.json\` file.`;
}

export function noModuleInGqlExternal() {
return `\`@${EXTERNAL_TAG}\` must include a module name in double quotes. For example: /** @gqlExternal "myModule" */`;
}

export function externalNotInResolverMapMode() {
return `Unexpected \`@${EXTERNAL_TAG}\` tag. \`@${EXTERNAL_TAG}\` is only supported when the \`EXPERIMENTAL__emitResolverMap\` Grats configuration option is enabled.`;
}

export function externalOnWrongNode(existingTag: string) {
return `Unexpected \`@${EXTERNAL_TAG}\` on type with \`${existingTag}\`. \`@${EXTERNAL_TAG}\` can only be used on type declarations.`;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"type declaration" here is a bit ambiguous. Does it mean a TypeScript type alias? A GraphQL object type? Maybe it would be clearer (if a bit awkward) to just enumerate the six tags which are valid?

}
162 changes: 139 additions & 23 deletions src/Extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import {
InputValueDefinitionNodeOrResolverArg,
ResolverArgument,
} from "./resolverSignature";
import path = require("path");
import { GratsConfig } from "./gratsConfig";

export const LIBRARY_IMPORT_NAME = "grats";
export const LIBRARY_NAME = "Grats";
Expand All @@ -62,6 +64,18 @@ export const INFO_TAG = "gqlInfo";
export const IMPLEMENTS_TAG_DEPRECATED = "gqlImplements";
export const KILLS_PARENT_ON_EXCEPTION_TAG = "killsParentOnException";

export const EXTERNAL_TAG = "gqlExternal";

export type AllTags =
| typeof TYPE_TAG
| typeof FIELD_TAG
| typeof SCALAR_TAG
| typeof INTERFACE_TAG
| typeof ENUM_TAG
| typeof UNION_TAG
| typeof INPUT_TAG
| typeof EXTERNAL_TAG;

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we derive this from ALL_TAGS?

const x = ["A", "B", "C"] as const;
type X = typeof x[number]

// All the tags that start with gql
export const ALL_TAGS = [
TYPE_TAG,
Expand All @@ -71,6 +85,7 @@ export const ALL_TAGS = [
ENUM_TAG,
UNION_TAG,
INPUT_TAG,
EXTERNAL_TAG,
];

const DEPRECATED_TAG = "deprecated";
Expand Down Expand Up @@ -106,8 +121,9 @@ type FieldTypeContext = {
*/
export function extract(
sourceFile: ts.SourceFile,
options: GratsConfig,
): DiagnosticsResult<ExtractionSnapshot> {
const extractor = new Extractor();
const extractor = new Extractor(options);
return extractor.extract(sourceFile);
}

Expand All @@ -123,7 +139,7 @@ class Extractor {
errors: ts.DiagnosticWithLocation[] = [];
gql: GraphQLConstructor;

constructor() {
constructor(private _options: GratsConfig) {
this.gql = new GraphQLConstructor();
}

Expand All @@ -135,12 +151,12 @@ class Extractor {
node: ts.DeclarationStatement,
name: NameNode,
kind: NameDefinition["kind"],
externalImportPath: string | null = null,
): void {
this.nameDefinitions.set(node, { name, kind });
this.nameDefinitions.set(node, { name, kind, externalImportPath });
}

// Traverse all nodes, checking each one for its JSDoc tags.
// If we find a tag we recognize, we extract the relevant information,
// Traverse all nodes, checking each one for its JSDoc tags. // If we find a tag we recognize, we extract the relevant information,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Traverse all nodes, checking each one for its JSDoc tags. // If we find a tag we recognize, we extract the relevant information,
// Traverse all nodes, checking each one for its JSDoc tags.
// If we find a tag we recognize, we extract the relevant information,

// reporting an error if it is attached to a node where that tag is not
// supported.
extract(sourceFile: ts.SourceFile): DiagnosticsResult<ExtractionSnapshot> {
Expand Down Expand Up @@ -231,6 +247,30 @@ class Extractor {
}
break;
}
case EXTERNAL_TAG:
if (!this._options.EXPERIMENTAL__emitResolverMap) {
this.report(tag.tagName, E.externalNotInResolverMapMode());
}
if (
Comment on lines +253 to +254
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the feature is not enabled, I think it's better to not report errors related to the feature.

Suggested change
}
if (
} else if (

!this.hasTag(node, TYPE_TAG) &&
!this.hasTag(node, INPUT_TAG) &&
!this.hasTag(node, INTERFACE_TAG) &&
!this.hasTag(node, UNION_TAG) &&
!this.hasTag(node, SCALAR_TAG) &&
!this.hasTag(node, ENUM_TAG)
) {
this.report(
tag.tagName,
E.externalOnWrongNode(
ts
.getJSDocTags(node)
.filter((t) => t.tagName.text !== EXTERNAL_TAG)[0].tagName
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would also report non-@gql tags, like @deprecated or other non-Grats tags.

.text,
),
);
}
break;

default:
{
const lowerCaseTag = tag.tagName.text.toLowerCase();
Expand Down Expand Up @@ -353,6 +393,8 @@ class Extractor {
extractInterface(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isInterfaceDeclaration(node)) {
this.interfaceInterfaceDeclaration(node, tag);
} else if (ts.isTypeAliasDeclaration(node)) {
this.interfaceTypeAliasDeclaration(node, tag);
} else {
this.report(tag, E.invalidInterfaceTagUsage());
}
Expand Down Expand Up @@ -426,7 +468,12 @@ class Extractor {
const name = this.entityName(node, tag);
if (name == null) return null;

if (!ts.isUnionTypeNode(node.type)) {
if (ts.isTypeReferenceNode(node)) {
if (this.hasTag(node, EXTERNAL_TAG)) {
return this.externalModule(node, name, "UNION");
}
return this.report(node, E.nonExternalTypeAlias(UNION_TAG));
} else if (!ts.isUnionTypeNode(node.type)) {
return this.report(node, E.expectedUnionTypeNode());
}

Expand Down Expand Up @@ -742,6 +789,11 @@ class Extractor {
if (name == null) return null;

const description = this.collectDescription(node);

if (this.hasTag(node, EXTERNAL_TAG)) {
return this.externalModule(node, name, "SCALAR");
}

this.recordTypeName(node, name, "SCALAR");

// TODO: Can a scalar be deprecated?
Expand All @@ -763,21 +815,29 @@ class Extractor {
if (name == null) return null;

const description = this.collectDescription(node);
this.recordTypeName(node, name, "INPUT_OBJECT");

const fields = this.collectInputFields(node);
if (
node.type.kind === ts.SyntaxKind.TypeReference &&
this.hasTag(node, EXTERNAL_TAG)
) {
return this.externalModule(node, name, "INPUT_OBJECT");
} else {
const fields = this.collectInputFields(node);

const deprecatedDirective = this.collectDeprecated(node);
const deprecatedDirective = this.collectDeprecated(node);

this.definitions.push(
this.gql.inputObjectTypeDefinition(
node,
name,
fields,
deprecatedDirective == null ? null : [deprecatedDirective],
description,
),
);
this.recordTypeName(node, name, "INPUT_OBJECT");

this.definitions.push(
this.gql.inputObjectTypeDefinition(
node,
name,
fields,
deprecatedDirective == null ? null : [deprecatedDirective],
description,
),
);
}
}

inputInterfaceDeclaration(node: ts.InterfaceDeclaration, tag: ts.JSDocTag) {
Expand Down Expand Up @@ -1070,6 +1130,11 @@ class Extractor {
// This is fine, we just don't know what it is. This should be the expected
// case for operation types such as `Query`, `Mutation`, and `Subscription`
// where there is not strong convention around.
} else if (
node.type.kind === ts.SyntaxKind.TypeReference &&
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason we can't also support external interfaces? I think you could define an interface which extends the interface from the other library.

this.hasTag(node, EXTERNAL_TAG)
) {
return this.externalModule(node, name, "TYPE");
} else {
return this.report(node.type, E.typeTagOnAliasOfNonObjectOrUnknown());
}
Expand Down Expand Up @@ -1371,6 +1436,24 @@ class Extractor {
);
}

interfaceTypeAliasDeclaration(
node: ts.TypeAliasDeclaration,
tag: ts.JSDocTag,
) {
const name = this.entityName(node, tag);
if (name == null || name.value == null) {
return;
}

if (
node.type.kind === ts.SyntaxKind.TypeReference &&
this.hasTag(node, EXTERNAL_TAG)
) {
return this.externalModule(node, name, "INTERFACE");
}
return this.report(node.type, E.nonExternalTypeAlias(INTERFACE_TAG));
}

collectFields(
members: ReadonlyArray<ts.ClassElement | ts.TypeElement>,
): Array<FieldDefinitionNode> {
Expand Down Expand Up @@ -1668,7 +1751,7 @@ class Extractor {
);
}

enumEnumDeclaration(node: ts.EnumDeclaration, tag: ts.JSDocTag): void {
enumEnumDeclaration(node: ts.EnumDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null || name.value == null) {
return;
Expand All @@ -1684,15 +1767,16 @@ class Extractor {
);
}

enumTypeAliasDeclaration(
node: ts.TypeAliasDeclaration,
tag: ts.JSDocTag,
): void {
enumTypeAliasDeclaration(node: ts.TypeAliasDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null || name.value == null) {
return;
}

if (this.hasTag(node, EXTERNAL_TAG)) {
return this.externalModule(node, name, "ENUM");
}

const values = this.enumTypeAliasVariants(node);
if (values == null) return;

Expand Down Expand Up @@ -1858,6 +1942,38 @@ class Extractor {
return this.gql.name(id, id.text);
}

externalModule(
node: ts.DeclarationStatement,
name: NameNode,
kind: NameDefinition["kind"],
) {
const tag = this.findTag(node, EXTERNAL_TAG);
if (!tag) {
return this.report(node, E.noModuleInGqlExternal());
}

let externalModule;
if (tag.comment != null) {
const commentText = ts.getTextOfJSDocComment(tag.comment);
if (commentText) {
const match = commentText.match(/^\s*"(.*)"\s*$/);

if (match && match[1]) {
externalModule = match[1];
}
}
}
if (!externalModule) {
return this.report(node, E.noModuleInGqlExternal());
}
return this.recordTypeName(
node,
name,
kind,
path.resolve(path.dirname(node.getSourceFile().fileName), externalModule),
);
}

methodDeclaration(
node: ts.MethodDeclaration | ts.MethodSignature | ts.GetAccessorDeclaration,
): FieldDefinitionNode | null {
Expand Down
Loading