New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

grats

Package Overview
Dependencies
Maintainers
1
Versions
240
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

grats - npm Package Compare versions

Comparing version 0.0.0-main-8e63ea66 to 0.0.0-main-957a70fd

dist/src/codegenHelpers.d.ts

33

dist/package.json
{
"name": "grats",
"version": "0.0.10",
"version": "0.0.25",
"main": "dist/src/index.js",

@@ -9,3 +9,4 @@ "bin": "dist/src/cli.js",

"files": [
"dist"
"dist",
"!dist/src/tests"
],

@@ -15,5 +16,5 @@ "scripts": {

"integration-tests": "node src/tests/integration.mjs",
"build": "tsc --build",
"build": "rm -rf dist/ && tsc --build",
"format": "prettier . --write",
"lint": "eslint src/**/*.ts && prettier . --check"
"lint": "eslint . && prettier . --check"
},

@@ -28,2 +29,3 @@ "dependencies": {

"@types/node": "^18.14.6",
"@types/semver": "^7.5.6",
"@typescript-eslint/eslint-plugin": "^5.55.0",

@@ -37,2 +39,3 @@ "@typescript-eslint/parser": "^5.55.0",

"process": "^0.11.10",
"semver": "^7.5.4",
"ts-node": "^10.9.1"

@@ -47,3 +50,23 @@ },

"pnpm": "^8"
}
},
"bugs": {
"url": "https://github.com/captbaritone/grats/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/captbaritone/grats.git"
},
"author": {
"name": "Jordan Eldredge",
"email": "jordan@jordaneldredge.com",
"url": "https://jordaneldredge.com"
},
"keywords": [
"graphql",
"typescript",
"resolvers",
"schema",
"code-first",
"implementation-first"
]
}

80

dist/src/cli.js

@@ -41,3 +41,2 @@ #!/usr/bin/env node

exports.formatLoc = void 0;
var graphql_1 = require("graphql");
var _1 = require("./");

@@ -52,2 +51,3 @@ var lib_1 = require("./lib");

var ts = require("typescript");
var DiagnosticError_1 = require("./utils/DiagnosticError");
var program = new commander_1.Command();

@@ -59,7 +59,13 @@ program

.option("--tsconfig <TSCONFIG>", "Path to tsconfig.json. Defaults to auto-detecting based on the current working directory")
.option("--watch", "Watch for changes and rebuild schema files as needed")
.action(function (_a) {
var tsconfig = _a.tsconfig;
var tsconfig = _a.tsconfig, watch = _a.watch;
return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_b) {
build(tsconfig);
if (watch) {
startWatchMode(tsconfig);
}
else {
runBuild(tsconfig);
}
return [2 /*return*/];

@@ -75,4 +81,9 @@ });

var tsconfig = _a.tsconfig;
var config = getTsConfig(tsconfig).config;
var schema = buildSchema(config);
var config = getTsConfigOrReportAndExit(tsconfig).config;
var schemaAndDocResult = (0, lib_1.buildSchemaAndDocResult)(config);
if (schemaAndDocResult.kind === "ERROR") {
console.error(schemaAndDocResult.err.formatDiagnosticsWithColorAndContext());
process.exit(1);
}
var schema = schemaAndDocResult.value.schema;
var loc = (0, Locate_1.locate)(schema, entity);

@@ -86,12 +97,42 @@ if (loc.kind === "ERROR") {

program.parse();
function build(tsconfig) {
var _a = getTsConfig(tsconfig), config = _a.config, configPath = _a.configPath;
var schema = buildSchema(config);
var sortedSchema = (0, graphql_1.lexicographicSortSchema)(schema);
/**
* Run the compiler in watch mode.
*/
function startWatchMode(tsconfig) {
var _a = getTsConfigOrReportAndExit(tsconfig), config = _a.config, configPath = _a.configPath;
var watchHost = ts.createWatchCompilerHost(configPath, {}, ts.sys, ts.createSemanticDiagnosticsBuilderProgram, function (diagnostic) { return reportDiagnostics([diagnostic]); }, function (diagnostic) { return reportDiagnostics([diagnostic]); });
watchHost.afterProgramCreate = function (program) {
// For now we just rebuild the schema on every change.
var schemaResult = (0, lib_1.extractSchemaAndDoc)(config, program.getProgram());
if (schemaResult.kind === "ERROR") {
reportDiagnostics(schemaResult.err);
return;
}
writeSchemaFilesAndReport(schemaResult.value, config, configPath);
};
ts.createWatchProgram(watchHost);
}
/**
* Run the compiler performing a single build.
*/
function runBuild(tsconfig) {
var _a = getTsConfigOrReportAndExit(tsconfig), config = _a.config, configPath = _a.configPath;
var schemaAndDocResult = (0, lib_1.buildSchemaAndDocResult)(config);
if (schemaAndDocResult.kind === "ERROR") {
console.error(schemaAndDocResult.err.formatDiagnosticsWithColorAndContext());
process.exit(1);
}
writeSchemaFilesAndReport(schemaAndDocResult.value, config, configPath);
}
/**
* Serializes the SDL and TypeScript schema to disk and reports to the console.
*/
function writeSchemaFilesAndReport(schemaAndDoc, config, configPath) {
var schema = schemaAndDoc.schema, doc = schemaAndDoc.doc;
var gratsOptions = config.raw.grats;
var dest = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsOptions.tsSchema);
var code = (0, printSchema_1.printExecutableSchema)(sortedSchema, gratsOptions, dest);
var code = (0, printSchema_1.printExecutableSchema)(schema, gratsOptions, dest);
(0, fs_1.writeFileSync)(dest, code);
console.error("Grats: Wrote TypeScript schema to `".concat(dest, "`."));
var schemaStr = (0, printSchema_1.printGratsSDL)(sortedSchema, gratsOptions);
var schemaStr = (0, printSchema_1.printGratsSDL)(doc, gratsOptions);
var absOutput = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsOptions.graphqlSchema);

@@ -101,4 +142,11 @@ (0, fs_1.writeFileSync)(absOutput, schemaStr);

}
/**
* Utility function to report diagnostics to the console.
*/
function reportDiagnostics(diagnostics) {
var reportable = DiagnosticError_1.ReportableDiagnostics.fromDiagnostics(diagnostics);
console.error(reportable.formatDiagnosticsWithColorAndContext());
}
// Locate and read the tsconfig.json file
function getTsConfig(tsconfig) {
function getTsConfigOrReportAndExit(tsconfig) {
var configPath = tsconfig || ts.findConfigFile(process.cwd(), ts.sys.fileExists);

@@ -115,10 +163,2 @@ if (configPath == null) {

}
function buildSchema(options) {
var schemaResult = (0, lib_1.buildSchemaResult)(options);
if (schemaResult.kind === "ERROR") {
console.error(schemaResult.err.formatDiagnosticsWithColorAndContext());
process.exit(1);
}
return schemaResult.value;
}
// Format a location for printing to the console. Tools like VS Code and iTerm

@@ -125,0 +165,0 @@ // will automatically turn this into a clickable link.

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __read = (this && this.__read) || function (o, n) {

@@ -34,2 +45,6 @@ var m = typeof Symbol === "function" && o[Symbol.iterator];

var gratsRoot_1 = require("./gratsRoot");
var publicDirectives_1 = require("./publicDirectives");
var codegenHelpers_1 = require("./codegenHelpers");
var helpers_1 = require("./utils/helpers");
var RESOLVER_ARGS = ["source", "args", "context", "info"];
var F = ts.factory;

@@ -40,4 +55,3 @@ // Given a GraphQL SDL, returns the a string of TypeScript code that generates a

var codegen = new Codegen(schema, destination);
codegen.schemaDeclaration();
codegen.schemaExport();
codegen.schemaDeclarationExport();
return codegen.print();

@@ -49,2 +63,3 @@ }

this._imports = [];
this._helpers = new Map();
this._typeDefinitions = new Set();

@@ -56,2 +71,10 @@ this._graphQLImports = new Set();

}
Codegen.prototype.createBlockWithScope = function (closure) {
var initialStatements = this._statements;
this._statements = [];
closure();
var block = F.createBlock(this._statements, true);
this._statements = initialStatements;
return block;
};
Codegen.prototype.graphQLImport = function (name) {

@@ -61,10 +84,11 @@ this._graphQLImports.add(name);

};
Codegen.prototype.schemaDeclaration = function () {
this.constDeclaration("schema", F.createNewExpression(this.graphQLImport("GraphQLSchema"), [], [this.schemaConfig()]));
Codegen.prototype.graphQLTypeImport = function (name) {
this._graphQLImports.add(name);
return F.createTypeReferenceNode(name);
};
Codegen.prototype.schemaExport = function () {
this._statements.push(F.createExportDeclaration(undefined, // [F.createModifier(ts.SyntaxKind.DefaultKeyword)],
false, F.createNamedExports([
F.createExportSpecifier(false, undefined, F.createIdentifier("schema")),
])));
Codegen.prototype.schemaDeclarationExport = function () {
var _this = this;
this.functionDeclaration("getSchema", [F.createModifier(ts.SyntaxKind.ExportKeyword)], this.graphQLTypeImport("GraphQLSchema"), this.createBlockWithScope(function () {
_this._statements.push(F.createReturnStatement(F.createNewExpression(_this.graphQLImport("GraphQLSchema"), [], [_this.schemaConfig()])));
}));
};

@@ -140,3 +164,3 @@ Codegen.prototype.schemaConfig = function () {

this.description(obj.description),
this.fields(obj),
this.fields(obj, false),
this.interfaces(obj),

@@ -147,18 +171,29 @@ ]);

var _this = this;
var args = ["source", "args", "context", "info"];
var exported = fieldDirective(field, metadataDirectives_1.EXPORTED_DIRECTIVE);
if (exported != null) {
var exportedMetadata = (0, metadataDirectives_1.parseExportedDirective)(exported);
var module_1 = exportedMetadata.tsModulePath;
var funcName = exportedMetadata.exportedFunctionName;
var argCount = exportedMetadata.argCount;
var metadataDirective = (0, helpers_1.nullThrows)(fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE));
var metadata = (0, metadataDirectives_1.parseFieldMetadataDirective)(metadataDirective);
if (metadata.tsModulePath != null) {
var module_1 = metadata.tsModulePath;
var exportName = metadata.exportName;
var argCount = (0, helpers_1.nullThrows)(metadata.argCount);
var abs = (0, gratsRoot_1.resolveRelativePath)(module_1);
var relative = stripExt(path.relative(path.dirname(this._destination), abs));
var resolverName = formatResolverFunctionVarName(parentTypeName, funcName);
this.import("./".concat(relative), [{ name: funcName, as: resolverName }]);
var usedArgs = args.slice(0, argCount);
// Note: This name is guaranteed to be unique, but for static methods, it
// means we import the same class multiple times with multiple names.
var resolverName = formatResolverFunctionVarName(parentTypeName, field.name);
var modulePath = "./".concat(normalizeRelativePathToPosix(relative));
if (exportName == null) {
this.importDefault(modulePath, resolverName);
}
else {
this.import(modulePath, [{ name: exportName, as: resolverName }]);
}
var usedArgs = RESOLVER_ARGS.slice(0, argCount);
var resolverAccess = F.createIdentifier(resolverName);
if (metadata.name != null) {
resolverAccess = F.createPropertyAccessExpression(resolverAccess, F.createIdentifier(metadata.name));
}
return this.method(methodName, usedArgs.map(function (name) {
return _this.param(name);
}), [
F.createReturnStatement(F.createCallExpression(F.createIdentifier(resolverName), undefined, usedArgs.map(function (name) {
F.createReturnStatement(F.createCallExpression(resolverAccess, undefined, usedArgs.map(function (name) {
return F.createIdentifier(name);

@@ -168,22 +203,57 @@ }))),

}
var propertyName = fieldDirective(field, metadataDirectives_1.FIELD_NAME_DIRECTIVE);
if (propertyName != null) {
var name = (0, metadataDirectives_1.parsePropertyNameDirective)(propertyName).name;
var prop = F.createPropertyAccessExpression(F.createIdentifier("source"), F.createIdentifier(name));
var callExpression = F.createCallExpression(prop, undefined, args.map(function (name) {
return F.createIdentifier(name);
}));
var isFunc = F.createStrictEquality(F.createTypeOfExpression(prop), F.createStringLiteral("function"));
var ternary = F.createConditionalExpression(isFunc, undefined, callExpression, undefined, prop);
return this.method(methodName, args.map(function (name) {
return _this.param(name);
}), [F.createReturnStatement(ternary)]);
if (metadata.name != null) {
var prop = F.createPropertyAccessExpression(F.createIdentifier("source"), F.createIdentifier(metadata.name));
var valueExpression = prop;
if (metadata.argCount != null) {
valueExpression = F.createCallExpression(prop, undefined, RESOLVER_ARGS.map(function (name) {
return F.createIdentifier(name);
}));
}
return this.method(methodName, RESOLVER_ARGS.map(function (name) { return _this.param(name); }), [F.createReturnStatement(valueExpression)]);
}
// If the resolver name matches the field name, and the field is not backed by a function,
// we can just use the default resolver.
return null;
};
Codegen.prototype.fields = function (obj) {
// If a field is smantically non-null, we need to wrap the resolver in a
// runtime check to ensure that the resolver does not return null.
Codegen.prototype.maybeApplySemanticNullRuntimeCheck = function (field, method_) {
var _a;
var semanticNonNull = fieldDirective(field, publicDirectives_1.SEMANTIC_NON_NULL_DIRECTIVE);
if (semanticNonNull == null) {
return method_;
}
if (!this._helpers.has(codegenHelpers_1.ASSERT_NON_NULL_HELPER)) {
this._helpers.set(codegenHelpers_1.ASSERT_NON_NULL_HELPER, (0, codegenHelpers_1.createAssertNonNullHelper)());
}
var method = method_ !== null && method_ !== void 0 ? method_ : this.defaultResolverMethod();
var bodyStatements = (_a = method.body) === null || _a === void 0 ? void 0 : _a.statements;
if (bodyStatements == null || bodyStatements.length === 0) {
throw new Error("Expected method to have a body");
}
var foundReturn = false;
var newBodyStatements = bodyStatements.map(function (statement) {
if (ts.isReturnStatement(statement)) {
foundReturn = true;
// We need to wrap the return statement in a call to the runtime check
return F.createReturnStatement(F.createCallExpression(F.createIdentifier(codegenHelpers_1.ASSERT_NON_NULL_HELPER), [], [(0, helpers_1.nullThrows)(statement.expression)]));
}
return statement;
});
if (!foundReturn) {
throw new Error("Expected method to have a return statement");
}
return __assign(__assign({}, method), { body: F.createBlock(newBodyStatements, true) });
};
Codegen.prototype.defaultResolverMethod = function () {
var _this = this;
return this.method("resolve", RESOLVER_ARGS.map(function (name) { return _this.param(name); }), [
F.createReturnStatement(F.createCallExpression(this.graphQLImport("defaultFieldResolver"), undefined, RESOLVER_ARGS.map(function (name) { return F.createIdentifier(name); }))),
]);
};
Codegen.prototype.fields = function (obj, isInterface) {
var _this = this;
var fields = Object.entries(obj.getFields()).map(function (_a) {
var _b = __read(_a, 2), name = _b[0], field = _b[1];
return F.createPropertyAssignment(name, _this.fieldConfig(field, obj.name));
return F.createPropertyAssignment(name, _this.fieldConfig(field, obj.name, isInterface));
});

@@ -216,3 +286,3 @@ return this.method("fields", [], [F.createReturnStatement(this.objectLiteral(fields))]);

F.createPropertyAssignment("name", F.createStringLiteral(obj.name)),
this.fields(obj),
this.fields(obj, true),
this.interfaces(obj),

@@ -293,4 +363,4 @@ ]);

};
Codegen.prototype.fieldConfig = function (field, parentTypeName) {
return this.objectLiteral(__spreadArray([
Codegen.prototype.fieldConfig = function (field, parentTypeName, isInterface) {
var props = [
this.description(field.description),

@@ -302,14 +372,21 @@ this.deprecated(field),

? F.createPropertyAssignment("args", this.argMap(field.args))
: null
], __read(this.fieldMethods(field, parentTypeName)), false));
: null,
];
if (!isInterface) {
(0, helpers_1.extend)(props, this.fieldMethods(field, parentTypeName));
}
return this.objectLiteral(props);
};
Codegen.prototype.fieldMethods = function (field, parentTypeName) {
var asyncIterable = fieldDirective(field, metadataDirectives_1.ASYNC_ITERABLE_TYPE_DIRECTIVE);
if (asyncIterable == null) {
return [this.resolveMethod(field, "resolve", parentTypeName)];
// Note: We assume the default name is used here. When custom operation types are supported
// we'll need to update this.
if (parentTypeName !== "Subscription") {
var resolve = this.resolveMethod(field, "resolve", parentTypeName);
return [this.maybeApplySemanticNullRuntimeCheck(field, resolve)];
}
return [
// TODO: Maybe avoid adding `assertNonNull` for subscription resolvers?
this.resolveMethod(field, "subscribe", parentTypeName),
// Identity function (method?)
this.method("resolve", [this.param("payload")], [F.createReturnStatement(F.createIdentifier("payload"))]),
this.maybeApplySemanticNullRuntimeCheck(field, this.method("resolve", [this.param("payload")], [F.createReturnStatement(F.createIdentifier("payload"))])),
];

@@ -446,2 +523,5 @@ };

};
Codegen.prototype.functionDeclaration = function (name, modifiers, type, body) {
this._statements.push(F.createFunctionDeclaration(modifiers, undefined, name, undefined, [], type, body));
};
// Helper to allow for nullable elements.

@@ -456,4 +536,4 @@ Codegen.prototype.objectLiteral = function (properties) {

// Helper for the common case of a single string argument.
Codegen.prototype.param = function (name) {
return F.createParameterDeclaration(undefined, undefined, name, undefined, undefined, undefined);
Codegen.prototype.param = function (name, type) {
return F.createParameterDeclaration(undefined, undefined, name, undefined, type, undefined);
};

@@ -471,2 +551,5 @@ Codegen.prototype.import = function (from, names) {

};
Codegen.prototype.importDefault = function (from, as) {
this._imports.push(F.createImportDeclaration(undefined, F.createImportClause(false, F.createIdentifier(as), undefined), F.createStringLiteral(from)));
};
Codegen.prototype.print = function () {

@@ -476,3 +559,3 @@ var printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

this.import("graphql", __spreadArray([], __read(this._graphQLImports), false).map(function (name) { return ({ name: name }); }));
return printer.printList(ts.ListFormat.MultiLine, F.createNodeArray(__spreadArray(__spreadArray([], __read(this._imports), false), __read(this._statements), false)), sourceFile);
return printer.printList(ts.ListFormat.MultiLine, F.createNodeArray(__spreadArray(__spreadArray(__spreadArray([], __read(this._imports), false), __read(this._helpers.values()), false), __read(this._statements), false)), sourceFile);
};

@@ -499,1 +582,5 @@ return Codegen;

}
// https://github.com/sindresorhus/slash/blob/98b618f5a3bfcb5dd374b204868818845b87bb2f/index.js#L8C9-L8C33
function normalizeRelativePathToPosix(unknownPath) {
return unknownPath.replace(/\\/g, "/");
}

@@ -0,1 +1,2 @@

export declare const ISSUE_URL = "https://github.com/captbaritone/grats/issues";
/**

@@ -26,9 +27,11 @@ * Error messages for Grats

export declare function functionFieldNotTopLevel(): string;
export declare function staticMethodClassNotTopLevel(): string;
export declare function staticMethodFieldClassNotExported(): string;
export declare function functionFieldParentTypeMissing(): string;
export declare function functionFieldParentTypeNotValid(): string;
export declare function functionFieldNotNamed(): string;
export declare function functionFieldDefaultExport(): string;
export declare function functionFieldNotNamedExport(): string;
export declare function inputTypeNotLiteral(): string;
export declare function inputTypeFieldNotProperty(): string;
export declare function inputInterfaceFieldNotProperty(): string;
export declare function inputFieldUntyped(): string;

@@ -54,3 +57,4 @@ export declare function typeTagOnUnnamedClass(): string;

export declare function methodMissingType(): string;
export declare function promiseMissingTypeArg(): string;
export declare function wrapperMissingTypeArg(): string;
export declare function invalidWrapperOnInputType(wrapperName: string): string;
export declare function cannotResolveSymbolForDescription(): string;

@@ -67,3 +71,3 @@ export declare function propertyFieldMissingType(): string;

export declare function pluralTypeMissingParameter(): string;
export declare function expectedIdentifier(): string;
export declare function expectedNameIdentifier(): string;
export declare function killsParentOnExceptionWithWrongConfig(): string;

@@ -73,3 +77,2 @@ export declare function killsParentOnExceptionOnNullable(): string;

export declare function mergedInterfaces(): string;
export declare function implementsTagMissingValue(): string;
export declare function implementsTagOnClass(): string;

@@ -94,4 +97,19 @@ export declare function implementsTagOnInterface(): string;

export declare function subscriptionFieldNotAsyncIterable(): string;
export declare function nonSubscriptionFieldAsyncIterable(): string;
export declare function operationTypeNotUnknown(): string;
export declare function expectedNullableArgumentToBeOptional(): string;
export declare function gqlTagInLineComment(): string;
export declare function gqlTagInNonJSDocBlockComment(): string;
export declare function gqlTagInDetachedJSDocBlockComment(): string;
export declare function gqlFieldTagOnInputType(): string;
export declare function gqlFieldParentMissingTag(): string;
export declare function missingSpecifiedByUrl(): string;
export declare function specifiedByOnWrongNode(): string;
export declare function missingGenericType(templateName: string, paramName: string): string;
export declare function nonGraphQLGenericType(templateName: string, paramName: string): string;
export declare function genericTypeUsedAsUnionMember(): string;
export declare function genericTypeImplementsInterface(): string;
export declare function concreteTypeMissingTypename(implementor: string): string;
export declare function invalidFieldNonPublicAccessModifier(): string;
export declare function invalidStaticModifier(): string;
export declare function staticMethodOnNonClass(): string;
export declare function staticMethodClassWithNamedExportNotNamed(): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultArgPropertyMissingName = exports.defaultArgElementIsNotAssignment = exports.defaultValueIsNotLiteral = exports.ambiguousNumberType = exports.expectedOneNonNullishType = exports.propertyFieldMissingType = exports.cannotResolveSymbolForDescription = exports.promiseMissingTypeArg = exports.methodMissingType = exports.gqlEntityMissingName = exports.enumVariantMissingInitializer = exports.enumVariantNotStringLiteral = exports.enumTagOnInvalidNode = exports.argNotTyped = exports.argNameNotLiteral = exports.argIsNotProperty = exports.argumentParamIsNotObject = exports.argumentParamIsMissingType = exports.typeNameDoesNotMatchExpected = exports.typeNameTypeNotStringLiteral = exports.typeNameMissingTypeAnnotation = exports.typeNameInitializerWrong = exports.typeNameInitializeNotString = exports.typeNameMissingInitializer = exports.typeNameNotDeclaration = exports.typeTagOnAliasOfNonObjectOrUnknown = exports.typeTagOnUnnamedClass = exports.inputFieldUntyped = exports.inputTypeFieldNotProperty = exports.inputTypeNotLiteral = exports.functionFieldNotNamedExport = exports.functionFieldDefaultExport = exports.functionFieldNotNamed = exports.functionFieldParentTypeNotValid = exports.functionFieldParentTypeMissing = exports.functionFieldNotTopLevel = exports.invalidReturnTypeForFunctionField = exports.invalidParentArgForFunctionField = exports.expectedUnionTypeReference = exports.expectedUnionTypeNode = exports.invalidUnionTagUsage = exports.invalidInputTagUsage = exports.invalidEnumTagUsage = exports.invalidInterfaceTagUsage = exports.invalidScalarTagUsage = exports.invalidTypeTagUsage = exports.invalidGratsTag = exports.wrongCasingForGratsTag = exports.killsParentOnExceptionOnWrongNode = exports.fieldTagOnWrongNode = void 0;
exports.expectedNullableArgumentToBeOptional = exports.operationTypeNotUnknown = exports.nonSubscriptionFieldAsyncIterable = exports.subscriptionFieldNotAsyncIterable = exports.graphQLTagNameHasWhitespace = exports.graphQLNameHasLeadingNewlines = exports.multipleContextTypes = exports.unexpectedParamSpreadForContextParam = exports.expectedTypeAnnotationOnContextToHaveDeclaration = exports.expectedTypeAnnotationOnContextToBeResolvable = exports.expectedTypeAnnotationOfReferenceOnContext = exports.expectedTypeAnnotationOnContext = exports.unresolvedTypeReference = exports.invalidTypePassedToFieldFunction = exports.parameterPropertyMissingType = exports.parameterPropertyNotPublic = exports.parameterWithoutModifiers = exports.duplicateInterfaceTag = exports.duplicateTag = exports.implementsTagOnTypeAlias = exports.implementsTagOnInterface = exports.implementsTagOnClass = exports.implementsTagMissingValue = exports.mergedInterfaces = exports.nonNullTypeCannotBeOptional = exports.killsParentOnExceptionOnNullable = exports.killsParentOnExceptionWithWrongConfig = exports.expectedIdentifier = exports.pluralTypeMissingParameter = exports.unknownGraphQLType = exports.unsupportedTypeLiteral = exports.defaultArgPropertyMissingInitializer = void 0;
exports.expectedOneNonNullishType = exports.propertyFieldMissingType = exports.cannotResolveSymbolForDescription = exports.invalidWrapperOnInputType = exports.wrapperMissingTypeArg = exports.methodMissingType = exports.gqlEntityMissingName = exports.enumVariantMissingInitializer = exports.enumVariantNotStringLiteral = exports.enumTagOnInvalidNode = exports.argNotTyped = exports.argNameNotLiteral = exports.argIsNotProperty = exports.argumentParamIsNotObject = exports.argumentParamIsMissingType = exports.typeNameDoesNotMatchExpected = exports.typeNameTypeNotStringLiteral = exports.typeNameMissingTypeAnnotation = exports.typeNameInitializerWrong = exports.typeNameInitializeNotString = exports.typeNameMissingInitializer = exports.typeNameNotDeclaration = exports.typeTagOnAliasOfNonObjectOrUnknown = exports.typeTagOnUnnamedClass = exports.inputFieldUntyped = exports.inputInterfaceFieldNotProperty = exports.inputTypeFieldNotProperty = exports.inputTypeNotLiteral = exports.functionFieldNotNamedExport = exports.functionFieldNotNamed = exports.functionFieldParentTypeNotValid = exports.functionFieldParentTypeMissing = exports.staticMethodFieldClassNotExported = exports.staticMethodClassNotTopLevel = exports.functionFieldNotTopLevel = exports.invalidReturnTypeForFunctionField = exports.invalidParentArgForFunctionField = exports.expectedUnionTypeReference = exports.expectedUnionTypeNode = exports.invalidUnionTagUsage = exports.invalidInputTagUsage = exports.invalidEnumTagUsage = exports.invalidInterfaceTagUsage = exports.invalidScalarTagUsage = exports.invalidTypeTagUsage = exports.invalidGratsTag = exports.wrongCasingForGratsTag = exports.killsParentOnExceptionOnWrongNode = exports.fieldTagOnWrongNode = exports.ISSUE_URL = void 0;
exports.staticMethodClassWithNamedExportNotNamed = exports.staticMethodOnNonClass = exports.invalidStaticModifier = exports.invalidFieldNonPublicAccessModifier = exports.concreteTypeMissingTypename = exports.genericTypeImplementsInterface = exports.genericTypeUsedAsUnionMember = exports.nonGraphQLGenericType = exports.missingGenericType = exports.specifiedByOnWrongNode = exports.missingSpecifiedByUrl = exports.gqlFieldParentMissingTag = exports.gqlFieldTagOnInputType = exports.gqlTagInDetachedJSDocBlockComment = exports.gqlTagInNonJSDocBlockComment = exports.gqlTagInLineComment = exports.expectedNullableArgumentToBeOptional = exports.operationTypeNotUnknown = exports.subscriptionFieldNotAsyncIterable = exports.graphQLTagNameHasWhitespace = exports.graphQLNameHasLeadingNewlines = exports.multipleContextTypes = exports.unexpectedParamSpreadForContextParam = exports.expectedTypeAnnotationOnContextToHaveDeclaration = exports.expectedTypeAnnotationOnContextToBeResolvable = exports.expectedTypeAnnotationOfReferenceOnContext = exports.expectedTypeAnnotationOnContext = exports.unresolvedTypeReference = exports.invalidTypePassedToFieldFunction = exports.parameterPropertyMissingType = exports.parameterPropertyNotPublic = exports.parameterWithoutModifiers = exports.duplicateInterfaceTag = exports.duplicateTag = exports.implementsTagOnTypeAlias = exports.implementsTagOnInterface = exports.implementsTagOnClass = exports.mergedInterfaces = exports.nonNullTypeCannotBeOptional = exports.killsParentOnExceptionOnNullable = exports.killsParentOnExceptionWithWrongConfig = exports.expectedNameIdentifier = exports.pluralTypeMissingParameter = exports.unknownGraphQLType = exports.unsupportedTypeLiteral = exports.defaultArgPropertyMissingInitializer = exports.defaultArgPropertyMissingName = exports.defaultArgElementIsNotAssignment = exports.defaultValueIsNotLiteral = exports.ambiguousNumberType = void 0;
var Extractor_1 = require("./Extractor");
exports.ISSUE_URL = "https://github.com/captbaritone/grats/issues";
// TODO: Move these to short URLS that are easier to keep from breaking.

@@ -10,2 +11,3 @@ var DOC_URLS = {

parameterProperties: "https://grats.capt.dev/docs/docblock-tags/fields#class-based-fields",
commentSyntax: "https://grats.capt.dev/docs/getting-started/comment-syntax",
};

@@ -23,3 +25,3 @@ /**

function fieldTagOnWrongNode() {
return "`@".concat(Extractor_1.FIELD_TAG, "` can only be used on method/property declarations or signatures.");
return "`@".concat(Extractor_1.FIELD_TAG, "` can only be used on method/property declarations, signatures, or function declarations.");
}

@@ -41,31 +43,31 @@ exports.fieldTagOnWrongNode = fieldTagOnWrongNode;

function invalidTypeTagUsage() {
return "`@".concat(Extractor_1.TYPE_TAG, "` can only be used on class or interface declarations.");
return "`@".concat(Extractor_1.TYPE_TAG, "` can only be used on class, interface or type declarations. e.g. `class MyType {}`");
}
exports.invalidTypeTagUsage = invalidTypeTagUsage;
function invalidScalarTagUsage() {
return "`@".concat(Extractor_1.SCALAR_TAG, "` can only be used on type alias declarations.");
return "`@".concat(Extractor_1.SCALAR_TAG, "` can only be used on type alias declarations. e.g. `type MyScalar = string`");
}
exports.invalidScalarTagUsage = invalidScalarTagUsage;
function invalidInterfaceTagUsage() {
return "`@".concat(Extractor_1.INTERFACE_TAG, "` can only be used on interface declarations.");
return "`@".concat(Extractor_1.INTERFACE_TAG, "` can only be used on interface declarations. e.g. `interface MyInterface {}`");
}
exports.invalidInterfaceTagUsage = invalidInterfaceTagUsage;
function invalidEnumTagUsage() {
return "`@".concat(Extractor_1.ENUM_TAG, "` can only be used on enum declarations or TypeScript unions.");
return "`@".concat(Extractor_1.ENUM_TAG, "` can only be used on enum declarations or TypeScript unions. e.g. `enum MyEnum {}` or `type MyEnum = \"foo\" | \"bar\"`");
}
exports.invalidEnumTagUsage = invalidEnumTagUsage;
function invalidInputTagUsage() {
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type alias declarations.");
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type alias or interface declarations. e.g. `type MyInput = { foo: string }` or `interface MyInput { foo: string }`");
}
exports.invalidInputTagUsage = invalidInputTagUsage;
function invalidUnionTagUsage() {
return "`@".concat(Extractor_1.UNION_TAG, "` can only be used on type alias declarations.");
return "`@".concat(Extractor_1.UNION_TAG, "` can only be used on type alias declarations. e.g. `type MyUnion = TypeA | TypeB`");
}
exports.invalidUnionTagUsage = invalidUnionTagUsage;
function expectedUnionTypeNode() {
return "Expected a TypeScript union. `@".concat(Extractor_1.UNION_TAG, "` can only be used on TypeScript unions.");
return "Expected a TypeScript union. `@".concat(Extractor_1.UNION_TAG, "` can only be used on TypeScript unions. e.g. `type MyUnion = TypeA | TypeB`");
}
exports.expectedUnionTypeNode = expectedUnionTypeNode;
function expectedUnionTypeReference() {
return "Expected `@".concat(Extractor_1.UNION_TAG, "` union members to be type references.");
return "Expected `@".concat(Extractor_1.UNION_TAG, "` union members to be type references. Grats expects union members to be references to something annotated with `@gqlType`.");
}

@@ -78,43 +80,52 @@ exports.expectedUnionTypeReference = expectedUnionTypeReference;

function invalidReturnTypeForFunctionField() {
return "Expected GraphQL field to have an explicit return type.";
return 'Expected GraphQL field to have an explicit return type. This is needed to allow Grats to "see" the type of the field.';
}
exports.invalidReturnTypeForFunctionField = invalidReturnTypeForFunctionField;
function functionFieldNotTopLevel() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be a top-level declaration.");
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be a top-level declaration. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be an exported.");
}
exports.functionFieldNotTopLevel = functionFieldNotTopLevel;
function staticMethodClassNotTopLevel() {
return "Expected class with a static `@".concat(Extractor_1.FIELD_TAG, "` method to be a top-level declaration. Grats needs to import resolver methods into it's generated schema module, so the resolver's class must be an exported.");
}
exports.staticMethodClassNotTopLevel = staticMethodClassNotTopLevel;
function staticMethodFieldClassNotExported() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` static method's class to be exported. Grats needs to import resolvers into it's generated schema module, so the resolver class must be an exported.");
}
exports.staticMethodFieldClassNotExported = staticMethodFieldClassNotExported;
var FUNCTION_PARENT_TYPE_CONTEXT = "Grats treats the first argument as the parent object of the field. Therefore Grats needs to see the _type_ of the first argument in order to know to which type/interface this field should be added.";
function functionFieldParentTypeMissing() {
return "Expected first argument of a `@".concat(Extractor_1.FIELD_TAG, "` function to have an explicit type annotation.");
return "Expected first argument of a `@".concat(Extractor_1.FIELD_TAG, "` function to have an explicit type annotation. ").concat(FUNCTION_PARENT_TYPE_CONTEXT);
}
exports.functionFieldParentTypeMissing = functionFieldParentTypeMissing;
function functionFieldParentTypeNotValid() {
return "Expected first argument of a `@".concat(Extractor_1.FIELD_TAG, "` function to be typed as a `@").concat(Extractor_1.TYPE_TAG, "` type.");
return "Expected first argument of a `@".concat(Extractor_1.FIELD_TAG, "` function to be typed as a type reference. ").concat(FUNCTION_PARENT_TYPE_CONTEXT);
}
exports.functionFieldParentTypeNotValid = functionFieldParentTypeNotValid;
function functionFieldNotNamed() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be named.");
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be named. Grats uses the name of the function to derive the name of the GraphQL field. Additionally, Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export.");
}
exports.functionFieldNotNamed = functionFieldNotNamed;
function functionFieldDefaultExport() {
return "Expected a `@".concat(Extractor_1.FIELD_TAG, "` function to be a named export, not a default export.");
}
exports.functionFieldDefaultExport = functionFieldDefaultExport;
function functionFieldNotNamedExport() {
return "Expected a `@".concat(Extractor_1.FIELD_TAG, "` function to be a named export.");
return "Expected a `@".concat(Extractor_1.FIELD_TAG, "` function to be a named export. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export.");
}
exports.functionFieldNotNamedExport = functionFieldNotNamedExport;
function inputTypeNotLiteral() {
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type literals.");
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type literals. e.g. `type MyInput = { foo: string }`");
}
exports.inputTypeNotLiteral = inputTypeNotLiteral;
function inputTypeFieldNotProperty() {
return "`@".concat(Extractor_1.INPUT_TAG, "` types only support property signature members.");
return "`@".concat(Extractor_1.INPUT_TAG, "` types only support property signature members. e.g. `type MyInput = { foo: string }`");
}
exports.inputTypeFieldNotProperty = inputTypeFieldNotProperty;
function inputInterfaceFieldNotProperty() {
return "`@".concat(Extractor_1.INPUT_TAG, "` interfaces only support property signature members. e.g. `interface MyInput { foo: string }`");
}
exports.inputInterfaceFieldNotProperty = inputInterfaceFieldNotProperty;
function inputFieldUntyped() {
return "Input field must have a type annotation.";
return 'Input field must have an explicit type annotation. Grats uses the type annotation to determine the type of the field, so it must be explicit in order for Grats to "see" the type.';
}
exports.inputFieldUntyped = inputFieldUntyped;
function typeTagOnUnnamedClass() {
return "Unexpected `@".concat(Extractor_1.TYPE_TAG, "` annotation on unnamed class declaration.");
return "Unexpected `@".concat(Extractor_1.TYPE_TAG, "` annotation on unnamed class declaration. Grats uses the name of the class to derive the name of the GraphQL type. Consider naming the class.");
}

@@ -127,83 +138,88 @@ exports.typeTagOnUnnamedClass = typeTagOnUnnamedClass;

function typeNameNotDeclaration() {
return "Expected `__typename` to be a property declaration.";
return "Expected `__typename` to be a property declaration. For example: `__typename: \"MyType\"`.";
}
exports.typeNameNotDeclaration = typeNameNotDeclaration;
var TYPENAME_CONTEXT = "This lets Grats know that the GraphQL executor will be able to derive the type of the object at runtime.";
function typeNameMissingInitializer() {
return "Expected `__typename` property to have an initializer or a string literal type. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`.";
return "Expected `__typename` property to have an initializer or a string literal type. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`. ".concat(TYPENAME_CONTEXT);
}
exports.typeNameMissingInitializer = typeNameMissingInitializer;
function typeNameInitializeNotString() {
return "Expected `__typename` property initializer to be a string literal. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`.";
return "Expected `__typename` property initializer to be a string literal. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`. ".concat(TYPENAME_CONTEXT);
}
exports.typeNameInitializeNotString = typeNameInitializeNotString;
function typeNameInitializerWrong(expected, actual) {
return "Expected `__typename` property initializer to be `\"".concat(expected, "\"`, found `\"").concat(actual, "\"`.");
return "Expected `__typename` property initializer to be `\"".concat(expected, "\"`, found `\"").concat(actual, "\"`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameInitializerWrong = typeNameInitializerWrong;
function typeNameMissingTypeAnnotation(expected) {
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`");
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameMissingTypeAnnotation = typeNameMissingTypeAnnotation;
function typeNameTypeNotStringLiteral(expected) {
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`");
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameTypeNotStringLiteral = typeNameTypeNotStringLiteral;
function typeNameDoesNotMatchExpected(expected) {
return "Expected `__typename` property to be `\"".concat(expected, "\"`");
return "Expected `__typename` property to be `\"".concat(expected, "\"`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected;
function argumentParamIsMissingType() {
return "Expected GraphQL field arguments to have a TypeScript type. If there are no arguments, you can use `args: unknown`.";
return "Expected GraphQL field arguments to have an explicit type annotation. If there are no arguments, you can use `args: unknown`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";
}
exports.argumentParamIsMissingType = argumentParamIsMissingType;
function argumentParamIsNotObject() {
return "Expected GraphQL field arguments to be typed using a literal object: `{someField: string}`. If there are no arguments, you can use `args: unknown`.";
return "Expected GraphQL field arguments to be typed using an inline literal object: `{someField: string}`. If there are no arguments, you can use `args: unknown`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";
}
exports.argumentParamIsNotObject = argumentParamIsNotObject;
function argIsNotProperty() {
return "Expected GraphQL field argument type to be a property signature.";
return "Expected GraphQL field argument type to be a property signature. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";
}
exports.argIsNotProperty = argIsNotProperty;
function argNameNotLiteral() {
return "Expected GraphQL field argument names to be a literal.";
return "Expected GraphQL field argument names to be a literal. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";
}
exports.argNameNotLiteral = argNameNotLiteral;
function argNotTyped() {
return "Expected GraphQL field argument to have a type.";
return "Expected GraphQL field argument to have an explicit type annotation. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";
}
exports.argNotTyped = argNotTyped;
function enumTagOnInvalidNode() {
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` to be a union type, or a string literal in the edge case of a single value enum.");
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` to be a union type, or a string literal in the edge case of a single value enum. For example: `type MyEnum = \"foo\" | \"bar\"` or `type MyEnum = \"foo\"`.");
}
exports.enumTagOnInvalidNode = enumTagOnInvalidNode;
function enumVariantNotStringLiteral() {
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to be string literal types. For example: `'foo'`.");
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to be string literal types. For example: `'foo'`. Grats needs to be able to see the concrete value of the enum member to generate the GraphQL schema.");
}
exports.enumVariantNotStringLiteral = enumVariantNotStringLiteral;
function enumVariantMissingInitializer() {
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to have string literal initializers. For example: `FOO = 'foo'`.");
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to have string literal initializers. For example: `FOO = 'foo'`. In GraphQL enum values are strings, and Grats needs to be able to see the concrete value of the enum member to generate the GraphQL schema.");
}
exports.enumVariantMissingInitializer = enumVariantMissingInitializer;
function gqlEntityMissingName() {
return "Expected GraphQL entity to have a name.";
return "Expected GraphQL entity to have a name. Grats uses the name of the entity to derive the name of the GraphQL construct.";
}
exports.gqlEntityMissingName = gqlEntityMissingName;
function methodMissingType() {
return "Expected GraphQL field to have a type.";
return "Expected GraphQL field methods to have an explicitly defined return type. Grats needs to be able to see the type of the field to generate its type in the GraphQL schema.";
}
exports.methodMissingType = methodMissingType;
function promiseMissingTypeArg() {
return "Expected type reference to have type arguments.";
function wrapperMissingTypeArg() {
return "Expected wrapper type reference to have type arguments. Grats needs to be able to see the return type in order to generate a GraphQL schema.";
}
exports.promiseMissingTypeArg = promiseMissingTypeArg;
exports.wrapperMissingTypeArg = wrapperMissingTypeArg;
function invalidWrapperOnInputType(wrapperName) {
return "Invalid input type. `".concat(wrapperName, "` is not a valid type when used as a GraphQL input value.");
}
exports.invalidWrapperOnInputType = invalidWrapperOnInputType;
function cannotResolveSymbolForDescription() {
return "Expected TypeScript to be able to resolve this GraphQL entity to a symbol.";
return "Expected TypeScript to be able to resolve this GraphQL entity to a symbol. Is it possible that this type is not defined in this file? Grats needs to follow type references to their declaration in order to determine which GraphQL name is being referenced.";
}
exports.cannotResolveSymbolForDescription = cannotResolveSymbolForDescription;
function propertyFieldMissingType() {
return "Expected GraphQL field to have a type.";
return "Expected GraphQL field to have an explicitly defined type annotation. Grats needs to be able to see the type of the field to generate a field's type in the GraphQL schema.";
}
exports.propertyFieldMissingType = propertyFieldMissingType;
function expectedOneNonNullishType() {
return "Expected exactly one non-nullish type.";
return "Expected exactly one non-nullish type. GraphQL does not support fields returning an arbitrary union of types. Consider defining an explicit `@".concat(Extractor_1.UNION_TAG, "` union type and returning that.");
}

@@ -216,43 +232,43 @@ exports.expectedOneNonNullishType = expectedOneNonNullishType;

function defaultValueIsNotLiteral() {
return "Expected GraphQL field argument default values to be a literal.";
return 'Expected GraphQL field argument default values to be a literal. Grats interprets argument defaults as GraphQL default values, which must be literals. For example: `10` or `"foo"`.';
}
exports.defaultValueIsNotLiteral = defaultValueIsNotLiteral;
function defaultArgElementIsNotAssignment() {
return "Expected object literal property to be a property assignment.";
return "Expected property to be a default assignment. For example: `{ first = 10}`. Grats needs to extract a literal GraphQL value here, and that requires Grats being able to see the literal value in the source code.";
}
exports.defaultArgElementIsNotAssignment = defaultArgElementIsNotAssignment;
function defaultArgPropertyMissingName() {
return "Expected object literal property to have a name.";
return "Expected object literal property to have a name. Grats needs to extract a literal value here, and that requires Grats being able to see the literal value and its field name in the source code.";
}
exports.defaultArgPropertyMissingName = defaultArgPropertyMissingName;
function defaultArgPropertyMissingInitializer() {
return "Expected object literal property to have an initializer. For example: `{ offset = 10}`.";
return "Expected object literal property to have an initializer. For example: `{ offset = 10}`. Grats needs to extract a literal GraphQL value here, and that requires Grats being able to see the literal value in the source code.";
}
exports.defaultArgPropertyMissingInitializer = defaultArgPropertyMissingInitializer;
function unsupportedTypeLiteral() {
return "Unexpected type literal. You may want to define a named GraphQL type elsewhere and reference it here.";
return "Unexpected type literal. Grats expects types in GraphQL positions to be scalar types, or reference a named GraphQL type directly. You may want to define a named GraphQL type elsewhere and reference it here.";
}
exports.unsupportedTypeLiteral = unsupportedTypeLiteral;
function unknownGraphQLType() {
return "Unknown GraphQL type.";
return "Unknown GraphQL type. Grats doe not know how to map this type to a GraphQL type. You may want to define a named GraphQL type elsewhere and reference it here. If you think Grats should be able to infer a GraphQL type from this type, please file an issue.";
}
exports.unknownGraphQLType = unknownGraphQLType;
function pluralTypeMissingParameter() {
return "Expected type reference to have type arguments.";
return "Expected wrapper type reference to have type arguments. Grats needs to be able to see the return type in order to generate a GraphQL schema.";
}
exports.pluralTypeMissingParameter = pluralTypeMissingParameter;
function expectedIdentifier() {
return "Expected an identifier.";
function expectedNameIdentifier() {
return "Expected an name identifier. Grats expected to find a name here which it could use to derive the GraphQL name.";
}
exports.expectedIdentifier = expectedIdentifier;
exports.expectedNameIdentifier = expectedNameIdentifier;
function killsParentOnExceptionWithWrongConfig() {
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` is only supported when the Grats config `nullableByDefault` is enabled.");
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` is only supported when the Grats config option `nullableByDefault` is enabled in your `tsconfig.json`.");
}
exports.killsParentOnExceptionWithWrongConfig = killsParentOnExceptionWithWrongConfig;
function killsParentOnExceptionOnNullable() {
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` is unnecessary on fields that are already nullable.");
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag on field typed as nullable. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` will force a field to appear as non-nullable in the schema, so it's implementation must also be non-nullable. .");
}
exports.killsParentOnExceptionOnNullable = killsParentOnExceptionOnNullable;
function nonNullTypeCannotBeOptional() {
return "Unexpected optional argument that does not also accept `null`. Optional arguments in GraphQL may get passed an explicit `null` value. This means optional arguments must be typed to also accept `null`.";
return "Unexpected optional argument that does not also accept `null`. Optional arguments in GraphQL may get passed an explicit `null` value by the GraphQL executor. This means optional arguments must be typed to also accept `null`. Consider adding `| null` to the end of the argument type.";
}

@@ -264,3 +280,3 @@ exports.nonNullTypeCannotBeOptional = nonNullTypeCannotBeOptional;

"If an interface is declared multiple times in a scope, TypeScript merges them.",
"To avoid ambiguity Grats does not support using merged interfaces as GraphQL interfaces.",
"To avoid ambiguity Grats does not support using merged interfaces as GraphQL definitions.",
"Consider using a unique name for your TypeScript interface and renaming it.\n\n",

@@ -271,6 +287,2 @@ "Learn more: ".concat(DOC_URLS.mergedInterfaces),

exports.mergedInterfaces = mergedInterfaces;
function implementsTagMissingValue() {
return "Expected `@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` to be followed by one or more interface names.");
}
exports.implementsTagMissingValue = implementsTagMissingValue;
function implementsTagOnClass() {

@@ -311,3 +323,3 @@ return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `class MyType implements MyInterface`.");

function parameterPropertyMissingType() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` parameter property to have a type annotation.");
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` parameter property to have an explicit type annotation. Grats needs to be able to see the type of the parameter property to generate a GraphQL schema.");
}

@@ -320,11 +332,11 @@ exports.parameterPropertyMissingType = parameterPropertyMissingType;

function unresolvedTypeReference() {
return "This type is not a valid GraphQL type. Did you mean to annotate it's definition with a `/** @gql */` tag such as `/** @gqlType */` or `/** @gqlInput **/`?";
return "Unable to resolve type reference. In order to generate a GraphQL schema, Grats needs to determine which GraphQL type is being referenced. This requires being able to resolve type references to their `@gql` annotated declaration. However this reference could not be resolved. Is it possible that this type is not defined in this file?";
}
exports.unresolvedTypeReference = unresolvedTypeReference;
function expectedTypeAnnotationOnContext() {
return "Expected context parameter to have a type annotation. Grats validates that your context parameter is type-safe by checking all context values reference the same type declaration.";
return "Expected context parameter to have an explicit type annotation. Grats validates that your context parameter is type-safe by checking that all context values reference the same type declaration.";
}
exports.expectedTypeAnnotationOnContext = expectedTypeAnnotationOnContext;
function expectedTypeAnnotationOfReferenceOnContext() {
return "Expected context parameter's type to be a type reference Grats validates that your context parameter is type-safe by checking all context values reference the same type declaration.";
return "Expected context parameter's type to be a type reference. Grats validates that your context parameter is type-safe by checking that all context values reference the same type declaration.";
}

@@ -335,3 +347,3 @@ exports.expectedTypeAnnotationOfReferenceOnContext = expectedTypeAnnotationOfReferenceOnContext;

// TODO: I don't think we have a test case that triggers this error.
return "Unable to resolve context parameter type. Grats validates that your context parameter is type-safe by checking all context values reference the same type declaration.";
return "Unable to resolve context parameter type. Grats validates that your context parameter is type-safe by checking that all context values reference the same type declaration.";
}

@@ -344,3 +356,3 @@ exports.expectedTypeAnnotationOnContextToBeResolvable = expectedTypeAnnotationOnContextToBeResolvable;

function unexpectedParamSpreadForContextParam() {
return "Unexpected spread parameter in context parameter position. Grats expects the context parameter to be a single, explicitly typed, argument.";
return "Unexpected spread parameter in context parameter position. Grats expects the context parameter to be a single, explicitly-typed argument.";
}

@@ -361,16 +373,76 @@ exports.unexpectedParamSpreadForContextParam = unexpectedParamSpreadForContextParam;

function subscriptionFieldNotAsyncIterable() {
return "Expected fields on `Subscription` to return an AsyncIterable.";
return "Expected fields on `Subscription` to return an `AsyncIterable`. Fields on `Subscription` model a subscription, which is a stream of events. Grats expects fields on `Subscription` to return an `AsyncIterable` which can be used to model this stream.";
}
exports.subscriptionFieldNotAsyncIterable = subscriptionFieldNotAsyncIterable;
function nonSubscriptionFieldAsyncIterable() {
return "Unexpected AsyncIterable. Only fields on `Subscription` should return an AsyncIterable.";
}
exports.nonSubscriptionFieldAsyncIterable = nonSubscriptionFieldAsyncIterable;
function operationTypeNotUnknown() {
return "Operation types `Query`, `Mutation`, and `Subscription` must be defined as type aliases of `unknown`. E.g. `type Query = unknown`.";
return "Operation types `Query`, `Mutation`, and `Subscription` must be defined as type aliases of `unknown`. E.g. `type Query = unknown`. This is because GraphQL servers do not have an agreed upon way to produce root values, and Grats errs on the side of safety. If you are trying to implement dependency injection, consider using the `context` argument passed to each resolver instead. If you have a strong use case for a concrete root value, please file an issue.";
}
exports.operationTypeNotUnknown = operationTypeNotUnknown;
function expectedNullableArgumentToBeOptional() {
return "Expected nullable argument to be optional. graphql-js may not define properties where an undefined argument is passed. To guard against this add a `?` to the end of the argument name to make it optional.";
return "Expected nullable argument to _also_ be optional (`?`). graphql-js may omit properties on the argument object where an undefined GraphQL variable is passed, or if the argument is omitted in the operation text. To ensure your resolver is capable of handing this scenario, add a `?` to the end of the argument name to make it optional. e.g. `{greeting?: string | null}`";
}
exports.expectedNullableArgumentToBeOptional = expectedNullableArgumentToBeOptional;
function gqlTagInLineComment() {
return "Unexpected Grats tag in line (`//`) comment. Grats looks for tags in JSDoc-style block comments. e.g. `/** @gqlType */`. For more information see: ".concat(DOC_URLS.commentSyntax);
}
exports.gqlTagInLineComment = gqlTagInLineComment;
function gqlTagInNonJSDocBlockComment() {
return "Unexpected Grats tag in non-JSDoc-style block comment. Grats only looks for tags in JSDoc-style block comments which start with `/**`. For more information see: ".concat(DOC_URLS.commentSyntax);
}
exports.gqlTagInNonJSDocBlockComment = gqlTagInNonJSDocBlockComment;
function gqlTagInDetachedJSDocBlockComment() {
return "Unexpected Grats tag in detached docblock. Grats was unable to determine which TypeScript declaration this docblock is associated with. Moving the docblock to a position with is unambiguously \"above\" the relevant declaration may help. For more information see: ".concat(DOC_URLS.commentSyntax);
}
exports.gqlTagInDetachedJSDocBlockComment = gqlTagInDetachedJSDocBlockComment;
function gqlFieldTagOnInputType() {
return "The tag `@".concat(Extractor_1.FIELD_TAG, "` is not needed on fields of input types. All fields are automatically included as part of the input type. This tag can be safely removed.");
}
exports.gqlFieldTagOnInputType = gqlFieldTagOnInputType;
function gqlFieldParentMissingTag() {
return "Unexpected `@".concat(Extractor_1.FIELD_TAG, "`. The parent construct must be either a `@").concat(Extractor_1.TYPE_TAG, "` or `@").concat(Extractor_1.INTERFACE_TAG, "` tag. Are you missing one of these tags?");
}
exports.gqlFieldParentMissingTag = gqlFieldParentMissingTag;
function missingSpecifiedByUrl() {
return "Expected `@".concat(Extractor_1.SPECIFIED_BY_TAG, "` tag to be followed by a URL. This URL will be used as the `url` argument to the `@specifiedBy` directive in the generated GraphQL schema. See https://spec.graphql.org/draft/#sec--specifiedBy for more information.");
}
exports.missingSpecifiedByUrl = missingSpecifiedByUrl;
function specifiedByOnWrongNode() {
return "Unexpected `@".concat(Extractor_1.SPECIFIED_BY_TAG, "` tag on non-scalar declaration. `@").concat(Extractor_1.SPECIFIED_BY_TAG, "` can only be used on custom scalar declarations. Are you missing a `@").concat(Extractor_1.SCALAR_TAG, "` tag?");
}
exports.specifiedByOnWrongNode = specifiedByOnWrongNode;
function missingGenericType(templateName, paramName) {
return "Missing type argument for generic GraphQL type. Expected `".concat(templateName, "` to be passed a GraphQL type argument for type parameter `").concat(paramName, "`.");
}
exports.missingGenericType = missingGenericType;
function nonGraphQLGenericType(templateName, paramName) {
return "Expected `".concat(templateName, "` to be passed a GraphQL type argument for type parameter `").concat(paramName, "`.");
}
exports.nonGraphQLGenericType = nonGraphQLGenericType;
function genericTypeUsedAsUnionMember() {
return "Unexpected generic type used as union member. Generic type may not currently be used as members of a union. Grats requires that all union members define a `__typename` field typed as a string literal matching the type's name. Since generic types are synthesized into multiple types with different names, Grats cannot ensure they have a correct `__typename` property and thus cannot be used as members of a union.";
}
exports.genericTypeUsedAsUnionMember = genericTypeUsedAsUnionMember;
function genericTypeImplementsInterface() {
return "Unexpected `implements` on generic `".concat(Extractor_1.TYPE_TAG, "`. Generic types may not currently declare themselves as implementing interfaces. Grats requires that all types which implement an interface define a `__typename` field typed as a string literal matching the type's name. Since generic types are synthesized into multiple types with different names, Grats cannot ensure they have a correct `__typename` property and thus declare themselves as interface implementors.");
}
exports.genericTypeImplementsInterface = genericTypeImplementsInterface;
function concreteTypeMissingTypename(implementor) {
return "Missing `__typename` on `".concat(implementor, "`. The type `").concat(implementor, "` is used in a union or interface, so it must have a `__typename` field.");
}
exports.concreteTypeMissingTypename = concreteTypeMissingTypename;
function invalidFieldNonPublicAccessModifier() {
return "Unexpected access modifier on `@".concat(Extractor_1.FIELD_TAG, "` method. GraphQL fields must be able to be called by the GraphQL executor.");
}
exports.invalidFieldNonPublicAccessModifier = invalidFieldNonPublicAccessModifier;
function invalidStaticModifier() {
return "Unexpected `static` modifier on non-method `@".concat(Extractor_1.FIELD_TAG, "`. `static` is only valid on method signatures.");
}
exports.invalidStaticModifier = invalidStaticModifier;
function staticMethodOnNonClass() {
return "Unexpected `@".concat(Extractor_1.FIELD_TAG, "` `static` method on non-class declaration. Static method fields may only be declared on exported class declarations.");
}
exports.staticMethodOnNonClass = staticMethodOnNonClass;
function staticMethodClassWithNamedExportNotNamed() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` static method's class to be named if exported without the `default` keyword.");
}
exports.staticMethodClassWithNamedExportNotNamed = staticMethodClassWithNamedExportNotNamed;

@@ -1,10 +0,7 @@

import { NameNode } from "graphql";
import { NameNode, DefinitionNode } from "graphql";
import { DiagnosticsResult } from "./utils/DiagnosticError";
import * as ts from "typescript";
import { NameDefinition } from "./TypeContext";
import { ConfigOptions } from "./lib";
import { GratsDefinitionNode } from "./GraphQLConstructor";
export declare const LIBRARY_IMPORT_NAME = "grats";
export declare const LIBRARY_NAME = "Grats";
export declare const ISSUE_URL = "https://github.com/captbaritone/grats/issues";
export declare const TYPE_TAG = "gqlType";

@@ -20,8 +17,9 @@ export declare const FIELD_TAG = "gqlField";

export declare const ALL_TAGS: string[];
export declare const SPECIFIED_BY_TAG = "specifiedBy";
export type ExtractionSnapshot = {
readonly definitions: GratsDefinitionNode[];
readonly unresolvedNames: Map<ts.Node, NameNode>;
readonly nameDefinitions: Map<ts.Node, NameDefinition>;
readonly definitions: DefinitionNode[];
readonly unresolvedNames: Map<ts.EntityName, NameNode>;
readonly nameDefinitions: Map<ts.DeclarationStatement, NameDefinition>;
readonly contextReferences: Array<ts.Node>;
readonly typesWithTypenameField: Set<string>;
readonly typesWithTypename: Set<string>;
readonly interfaceDeclarations: Array<ts.InterfaceDeclaration>;

@@ -39,2 +37,2 @@ };

*/
export declare function extract(options: ConfigOptions, sourceFile: ts.SourceFile): DiagnosticsResult<ExtractionSnapshot>;
export declare function extract(sourceFile: ts.SourceFile): DiagnosticsResult<ExtractionSnapshot>;

@@ -1,15 +0,12 @@

import { ListTypeNode, NamedTypeNode, Location as GraphQLLocation, NameNode, Token, TypeNode, NonNullTypeNode, StringValueNode, ConstValueNode, ConstDirectiveNode, ConstArgumentNode, UnionTypeDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, FloatValueNode, IntValueNode, NullValueNode, BooleanValueNode, ConstListValueNode, ConstObjectValueNode, ConstObjectFieldNode, ObjectTypeDefinitionNode, EnumValueDefinitionNode, ScalarTypeDefinitionNode, InputObjectTypeDefinitionNode, EnumTypeDefinitionNode, InterfaceTypeDefinitionNode, DefinitionNode, Location } from "graphql";
import { ListTypeNode, NamedTypeNode, Location as GraphQLLocation, NameNode, TypeNode, NonNullTypeNode, StringValueNode, ConstValueNode, ConstDirectiveNode, ConstArgumentNode, UnionTypeDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, FloatValueNode, IntValueNode, NullValueNode, BooleanValueNode, ConstListValueNode, ConstObjectValueNode, ConstObjectFieldNode, ObjectTypeDefinitionNode, EnumValueDefinitionNode, ScalarTypeDefinitionNode, InputObjectTypeDefinitionNode, EnumTypeDefinitionNode, InterfaceTypeDefinitionNode, ASTNode, ObjectTypeExtensionNode } from "graphql";
import * as ts from "typescript";
import { ExportedMetadata, PropertyNameMetadata } from "./metadataDirectives";
export type GratsDefinitionNode = DefinitionNode | AbstractFieldDefinitionNode;
export type AbstractFieldDefinitionNode = {
readonly kind: "AbstractFieldDefinition";
readonly loc: Location;
readonly onType: NameNode;
readonly field: FieldDefinitionNode;
};
import { TsLocatableNode } from "./utils/DiagnosticError";
export declare class GraphQLConstructor {
exportedDirective(node: ts.Node, exported: ExportedMetadata): ConstDirectiveNode;
propertyNameDirective(node: ts.Node, propertyName: PropertyNameMetadata): ConstDirectiveNode;
asyncIterableDirective(node: ts.Node): ConstDirectiveNode;
fieldMetadataDirective(node: ts.Node, metadata: {
tsModulePath: string | null;
name: string | null;
exportName: string | null;
argCount: number | null;
}): ConstDirectiveNode;
killsParentOnExceptionDirective(node: ts.Node): ConstDirectiveNode;
unionTypeDefinition(node: ts.Node, name: NameNode, types: NamedTypeNode[], description: StringValueNode | null): UnionTypeDefinitionNode;

@@ -19,3 +16,3 @@ objectTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null): ObjectTypeDefinitionNode;

enumTypeDefinition(node: ts.Node, name: NameNode, values: readonly EnumValueDefinitionNode[], description: StringValueNode | null): EnumTypeDefinitionNode;
abstractFieldDefinition(node: ts.Node, onType: NameNode, field: FieldDefinitionNode): AbstractFieldDefinitionNode;
abstractFieldDefinition(node: ts.Node, onType: NameNode, field: FieldDefinitionNode): ObjectTypeExtensionNode;
fieldDefinition(node: ts.Node, name: NameNode, type: TypeNode, args: readonly InputValueDefinitionNode[] | null, directives: readonly ConstDirectiveNode[], description: StringValueNode | null): FieldDefinitionNode;

@@ -25,3 +22,3 @@ constObjectField(node: ts.Node, name: NameNode, value: ConstValueNode): ConstObjectFieldNode;

enumValueDefinition(node: ts.Node, name: NameNode, directives: readonly ConstDirectiveNode[] | undefined, description: StringValueNode | null): EnumValueDefinitionNode;
scalarTypeDefinition(node: ts.Node, name: NameNode, description: StringValueNode | null): ScalarTypeDefinitionNode;
scalarTypeDefinition(node: ts.Node, name: NameNode, directives: readonly ConstDirectiveNode[] | null, description: StringValueNode | null): ScalarTypeDefinitionNode;
inputObjectTypeDefinition(node: ts.Node, name: NameNode, fields: InputValueDefinitionNode[] | null, directives: readonly ConstDirectiveNode[] | null, description: StringValueNode | null): InputObjectTypeDefinitionNode;

@@ -35,2 +32,3 @@ name(node: ts.Node, value: string): NameNode;

list(node: ts.Node, values: ConstValueNode[]): ConstListValueNode;
withLocation<T = ASTNode>(node: ts.Node, value: T): T;
constArgument(node: ts.Node, name: NameNode, value: ConstValueNode): ConstArgumentNode;

@@ -44,4 +42,3 @@ constDirective(node: ts.Node, name: NameNode, args: ReadonlyArray<ConstArgumentNode> | null): ConstDirectiveNode;

_optionalList<T>(input: readonly T[] | null): readonly T[] | undefined;
_loc(node: ts.Node): GraphQLLocation;
_dummyToken(sourceFile: ts.SourceFile, pos: number): Token;
}
export declare function loc(node: TsLocatableNode): GraphQLLocation;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphQLConstructor = void 0;
exports.loc = exports.GraphQLConstructor = void 0;
var graphql_1 = require("graphql");
var metadataDirectives_1 = require("./metadataDirectives");
var helpers_1 = require("./utils/helpers");
var GraphQLConstructor = /** @class */ (function () {
function GraphQLConstructor() {
}
/* Metadata Directives */
GraphQLConstructor.prototype.exportedDirective = function (node, exported) {
return (0, metadataDirectives_1.makeExportedDirective)(this._loc(node), exported);
GraphQLConstructor.prototype.fieldMetadataDirective = function (node, metadata) {
var args = [];
if (metadata.tsModulePath != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.TS_MODULE_PATH_ARG), this.string(node, metadata.tsModulePath)));
}
if (metadata.name != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.FIELD_NAME_ARG), this.string(node, metadata.name)));
}
if (metadata.exportName != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.EXPORT_NAME_ARG), this.string(node, metadata.exportName)));
}
if (metadata.argCount != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.ARG_COUNT), this.int(node, metadata.argCount.toString())));
}
return this.constDirective(node, this.name(node, metadataDirectives_1.FIELD_METADATA_DIRECTIVE), args);
};
GraphQLConstructor.prototype.propertyNameDirective = function (node, propertyName) {
return (0, metadataDirectives_1.makePropertyNameDirective)(this._loc(node), propertyName);
GraphQLConstructor.prototype.killsParentOnExceptionDirective = function (node) {
return (0, metadataDirectives_1.makeKillsParentOnExceptionDirective)(loc(node));
};
GraphQLConstructor.prototype.asyncIterableDirective = function (node) {
return (0, metadataDirectives_1.makeAsyncIterableDirective)(this._loc(node));
};
/* Top Level Types */

@@ -23,3 +44,3 @@ GraphQLConstructor.prototype.unionTypeDefinition = function (node, name, types, description) {

kind: graphql_1.Kind.UNION_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -33,3 +54,3 @@ name: name,

kind: graphql_1.Kind.OBJECT_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -45,3 +66,3 @@ directives: undefined,

kind: graphql_1.Kind.INTERFACE_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -57,3 +78,3 @@ directives: undefined,

kind: graphql_1.Kind.ENUM_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -67,6 +88,7 @@ name: name,

return {
kind: "AbstractFieldDefinition",
loc: this._loc(node),
onType: onType,
field: field,
kind: graphql_1.Kind.OBJECT_TYPE_EXTENSION,
loc: loc(node),
name: onType,
fields: [field],
mayBeInterface: true,
};

@@ -78,3 +100,3 @@ };

kind: graphql_1.Kind.FIELD_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -88,3 +110,3 @@ name: name,

GraphQLConstructor.prototype.constObjectField = function (node, name, value) {
return { kind: graphql_1.Kind.OBJECT_FIELD, loc: this._loc(node), name: name, value: value };
return { kind: graphql_1.Kind.OBJECT_FIELD, loc: loc(node), name: name, value: value };
};

@@ -94,3 +116,3 @@ GraphQLConstructor.prototype.inputValueDefinition = function (node, name, type, directives, defaultValue, description) {

kind: graphql_1.Kind.INPUT_VALUE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -106,3 +128,3 @@ name: name,

kind: graphql_1.Kind.ENUM_VALUE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -113,9 +135,9 @@ name: name,

};
GraphQLConstructor.prototype.scalarTypeDefinition = function (node, name, description) {
GraphQLConstructor.prototype.scalarTypeDefinition = function (node, name, directives, description) {
return {
kind: graphql_1.Kind.SCALAR_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,
name: name,
directives: undefined,
directives: this._optionalList(directives),
};

@@ -126,3 +148,3 @@ };

kind: graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -136,3 +158,8 @@ name: name,

GraphQLConstructor.prototype.name = function (node, value) {
return { kind: graphql_1.Kind.NAME, loc: this._loc(node), value: value };
return {
kind: graphql_1.Kind.NAME,
loc: loc(node),
value: value,
tsIdentifier: (0, helpers_1.uniqueId)(),
};
};

@@ -142,3 +169,3 @@ GraphQLConstructor.prototype.namedType = function (node, value) {

kind: graphql_1.Kind.NAMED_TYPE,
loc: this._loc(node),
loc: loc(node),
name: this.name(node, value),

@@ -148,3 +175,3 @@ };

GraphQLConstructor.prototype.object = function (node, fields) {
return { kind: graphql_1.Kind.OBJECT, loc: this._loc(node), fields: fields };
return { kind: graphql_1.Kind.OBJECT, loc: loc(node), fields: fields };
};

@@ -156,3 +183,3 @@ /* Helpers */

}
return { kind: graphql_1.Kind.NON_NULL_TYPE, loc: this._loc(node), type: type };
return { kind: graphql_1.Kind.NON_NULL_TYPE, loc: loc(node), type: type };
};

@@ -167,9 +194,12 @@ GraphQLConstructor.prototype.nullableType = function (type) {

GraphQLConstructor.prototype.listType = function (node, type) {
return { kind: graphql_1.Kind.LIST_TYPE, loc: this._loc(node), type: type };
return { kind: graphql_1.Kind.LIST_TYPE, loc: loc(node), type: type };
};
GraphQLConstructor.prototype.list = function (node, values) {
return { kind: graphql_1.Kind.LIST, loc: this._loc(node), values: values };
return { kind: graphql_1.Kind.LIST, loc: loc(node), values: values };
};
GraphQLConstructor.prototype.withLocation = function (node, value) {
return __assign(__assign({}, value), { loc: loc(node) });
};
GraphQLConstructor.prototype.constArgument = function (node, name, value) {
return { kind: graphql_1.Kind.ARGUMENT, loc: this._loc(node), name: name, value: value };
return { kind: graphql_1.Kind.ARGUMENT, loc: loc(node), name: name, value: value };
};

@@ -179,3 +209,3 @@ GraphQLConstructor.prototype.constDirective = function (node, name, args) {

kind: graphql_1.Kind.DIRECTIVE,
loc: this._loc(node),
loc: loc(node),
name: name,

@@ -186,15 +216,15 @@ arguments: this._optionalList(args),

GraphQLConstructor.prototype.string = function (node, value, block) {
return { kind: graphql_1.Kind.STRING, loc: this._loc(node), value: value, block: block };
return { kind: graphql_1.Kind.STRING, loc: loc(node), value: value, block: block };
};
GraphQLConstructor.prototype.float = function (node, value) {
return { kind: graphql_1.Kind.FLOAT, loc: this._loc(node), value: value };
return { kind: graphql_1.Kind.FLOAT, loc: loc(node), value: value };
};
GraphQLConstructor.prototype.int = function (node, value) {
return { kind: graphql_1.Kind.INT, loc: this._loc(node), value: value };
return { kind: graphql_1.Kind.INT, loc: loc(node), value: value };
};
GraphQLConstructor.prototype.null = function (node) {
return { kind: graphql_1.Kind.NULL, loc: this._loc(node) };
return { kind: graphql_1.Kind.NULL, loc: loc(node) };
};
GraphQLConstructor.prototype.boolean = function (node, value) {
return { kind: graphql_1.Kind.BOOLEAN, loc: this._loc(node), value: value };
return { kind: graphql_1.Kind.BOOLEAN, loc: loc(node), value: value };
};

@@ -207,18 +237,19 @@ GraphQLConstructor.prototype._optionalList = function (input) {

};
// TODO: This is potentially quite expensive, and we only need it if we report
// an error at one of these locations. We could consider some trick to return a
// proxy object that would lazily compute the line/column info.
GraphQLConstructor.prototype._loc = function (node) {
var sourceFile = node.getSourceFile();
var source = new graphql_1.Source(sourceFile.text, sourceFile.fileName);
var startToken = this._dummyToken(sourceFile, node.getStart());
var endToken = this._dummyToken(sourceFile, node.getEnd());
return new graphql_1.Location(startToken, endToken, source);
};
GraphQLConstructor.prototype._dummyToken = function (sourceFile, pos) {
var _a = sourceFile.getLineAndCharacterOfPosition(pos), line = _a.line, character = _a.character;
return new graphql_1.Token(graphql_1.TokenKind.SOF, pos, pos, line, character, undefined);
};
return GraphQLConstructor;
}());
exports.GraphQLConstructor = GraphQLConstructor;
// TODO: This is potentially quite expensive, and we only need it if we report
// an error at one of these locations. We could consider some trick to return a
// proxy object that would lazily compute the line/column info.
function loc(node) {
var sourceFile = node.getSourceFile();
var source = new graphql_1.Source(sourceFile.text, sourceFile.fileName);
var startToken = _dummyToken(sourceFile, node.getStart());
var endToken = _dummyToken(sourceFile, node.getEnd());
return new graphql_1.Location(startToken, endToken, source);
}
exports.loc = loc;
function _dummyToken(sourceFile, pos) {
var _a = sourceFile.getLineAndCharacterOfPosition(pos), line = _a.line, character = _a.character;
return new graphql_1.Token(graphql_1.TokenKind.SOF, pos, pos, line, character, undefined);
}

@@ -6,2 +6,3 @@ import * as ts from "typescript";

nullableByDefault: boolean;
strictSemanticNullability: boolean;
reportTypeScriptTypeErrors: boolean;

@@ -11,3 +12,3 @@ schemaHeader: string | null;

};
export type ParsedCommandLineGrats = ts.ParsedCommandLine & {
export type ParsedCommandLineGrats = Omit<ts.ParsedCommandLine, "raw"> & {
raw: {

@@ -14,0 +15,0 @@ grats: ConfigOptions;

@@ -13,2 +13,13 @@ "use strict";

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -18,6 +29,32 @@ exports.validateGratsOptions = void 0;

var DEFAULT_TYPESCRIPT_HEADER = "/**\n * Executable schema generated by Grats (https://grats.capt.dev)\n * Do not manually edit. Regenerate by running `npx grats`.\n */";
var VALID_CONFIG_KEYS = new Set([
"graphqlSchema",
"tsSchema",
"nullableByDefault",
"strictSemanticNullability",
"reportTypeScriptTypeErrors",
"schemaHeader",
"tsSchemaHeader",
]);
// TODO: Make this return diagnostics
function validateGratsOptions(options) {
var _a, _b;
var gratsOptions = __assign({}, ((_b = (_a = options.raw) === null || _a === void 0 ? void 0 : _a.grats) !== null && _b !== void 0 ? _b : {}));
var e_1, _a;
var _b, _c;
var gratsOptions = __assign({}, ((_c = (_b = options.raw) === null || _b === void 0 ? void 0 : _b.grats) !== null && _c !== void 0 ? _c : {}));
try {
for (var _d = __values(Object.keys(gratsOptions)), _e = _d.next(); !_e.done; _e = _d.next()) {
var key = _e.value;
if (!VALID_CONFIG_KEYS.has(key)) {
// TODO: Suggest similar?
throw new Error("Grats: Unknown Grats config option `".concat(key, "`"));
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
}
finally { if (e_1) throw e_1.error; }
}
if (gratsOptions.nullableByDefault === undefined) {

@@ -29,2 +66,12 @@ gratsOptions.nullableByDefault = true;

}
if (gratsOptions.strictSemanticNullability === undefined) {
gratsOptions.strictSemanticNullability = false;
}
else if (typeof gratsOptions.strictSemanticNullability !== "boolean") {
throw new Error("Grats: The Grats config option `strictSemanticNullability` must be a boolean if provided.");
}
else if (gratsOptions.strictSemanticNullability &&
!gratsOptions.nullableByDefault) {
throw new Error("Grats: The Grats config option `strictSemanticNullability` cannot be true if `nullableByDefault` is false.");
}
if (gratsOptions.reportTypeScriptTypeErrors === undefined) {

@@ -53,5 +100,11 @@ gratsOptions.reportTypeScriptTypeErrors = false;

}
else if (Array.isArray(gratsOptions.schemaHeader)) {
if (!gratsOptions.schemaHeader.every(function (segment) { return typeof segment === "string"; })) {
throw new Error("Grats: If the Grats config option `schemaHeader` is an array, it must be an array of strings.");
}
gratsOptions.schemaHeader = gratsOptions.schemaHeader.join("");
}
else if (typeof gratsOptions.schemaHeader !== "string" &&
gratsOptions.schemaHeader !== null) {
throw new Error("Grats: The Grats config option `schemaHeader` must be a string or `null` if provided.");
throw new Error("Grats: The Grats config option `schemaHeader` must be a string, an array of strings, or `null` if provided.");
}

@@ -61,5 +114,11 @@ if (gratsOptions.tsSchemaHeader === undefined) {

}
else if (Array.isArray(gratsOptions.tsSchemaHeader)) {
if (!gratsOptions.tsSchemaHeader.every(function (segment) { return typeof segment === "string"; })) {
throw new Error("Grats: If the Grats config option `tsSchemaHeader` is an array, it must be an array of strings.");
}
gratsOptions.tsSchemaHeader = gratsOptions.tsSchemaHeader.join("");
}
else if (typeof gratsOptions.tsSchemaHeader !== "string" &&
gratsOptions.tsSchemaHeader !== null) {
throw new Error("Grats: The Grats config option `tsSchemaHeader` must be a string or `null` if provided.");
throw new Error("Grats: The Grats config option `tsSchemaHeader` must be a string, an array of strings, or `null` if provided.");
}

@@ -66,0 +125,0 @@ return __assign(__assign({}, options), { raw: __assign(__assign({}, options.raw), { grats: gratsOptions }) });

@@ -1,7 +0,9 @@

import { ParsedCommandLineGrats } from "./lib";
import { ReportableDiagnostics, Result } from "./utils/DiagnosticError";
export { printSDLWithoutDirectives } from "./printSchema";
import { ParsedCommandLineGrats } from "./gratsConfig";
import { ReportableDiagnostics } from "./utils/DiagnosticError";
import { Result } from "./utils/Result";
export { printSDLWithoutMetadata } from "./printSchema";
export * from "./Types";
export * from "./lib";
export { extract } from "./Extractor";
export { codegen } from "./codegen";
export declare function getParsedTsConfig(configFile: string): Result<ParsedCommandLineGrats, ReportableDiagnostics>;

@@ -17,10 +17,14 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getParsedTsConfig = exports.codegen = exports.printSDLWithoutDirectives = void 0;
exports.getParsedTsConfig = exports.codegen = exports.extract = exports.printSDLWithoutMetadata = void 0;
var ts = require("typescript");
var lib_1 = require("./lib");
var gratsConfig_1 = require("./gratsConfig");
var DiagnosticError_1 = require("./utils/DiagnosticError");
var Result_1 = require("./utils/Result");
var printSchema_1 = require("./printSchema");
Object.defineProperty(exports, "printSDLWithoutDirectives", { enumerable: true, get: function () { return printSchema_1.printSDLWithoutDirectives; } });
Object.defineProperty(exports, "printSDLWithoutMetadata", { enumerable: true, get: function () { return printSchema_1.printSDLWithoutMetadata; } });
__exportStar(require("./Types"), exports);
__exportStar(require("./lib"), exports);
// Used by the experimental TypeScript plugin
var Extractor_1 = require("./Extractor");
Object.defineProperty(exports, "extract", { enumerable: true, get: function () { return Extractor_1.extract; } });
var codegen_1 = require("./codegen");

@@ -40,6 +44,6 @@ Object.defineProperty(exports, "codegen", { enumerable: true, get: function () { return codegen_1.codegen; } });

if (parsed.errors.length > 0) {
return (0, DiagnosticError_1.err)(DiagnosticError_1.ReportableDiagnostics.fromDiagnostics(parsed.errors));
return (0, Result_1.err)(DiagnosticError_1.ReportableDiagnostics.fromDiagnostics(parsed.errors));
}
return (0, DiagnosticError_1.ok)((0, lib_1.validateGratsOptions)(parsed));
return (0, Result_1.ok)((0, gratsConfig_1.validateGratsOptions)(parsed));
}
exports.getParsedTsConfig = getParsedTsConfig;

@@ -1,4 +0,4 @@

import { GratsDefinitionNode } from "./GraphQLConstructor";
import { TypeContext } from "./TypeContext";
import { DefaultMap } from "./utils/helpers";
import { DefinitionNode } from "graphql";
export type InterfaceImplementor = {

@@ -12,2 +12,2 @@ kind: "TYPE" | "INTERFACE";

*/
export declare function computeInterfaceMap(typeContext: TypeContext, docs: GratsDefinitionNode[]): InterfaceMap;
export declare function computeInterfaceMap(typeContext: TypeContext, docs: DefinitionNode[]): InterfaceMap;

@@ -37,3 +37,3 @@ "use strict";

var implementor = _g.value;
var resolved = typeContext.resolveNamedType(implementor.name);
var resolved = typeContext.resolveUnresolvedNamedType(implementor.name);
if (resolved.kind === "ERROR") {

@@ -62,3 +62,3 @@ // We trust that these errors will be reported elsewhere.

var implementor = _j.value;
var resolved = typeContext.resolveNamedType(implementor.name);
var resolved = typeContext.resolveUnresolvedNamedType(implementor.name);
if (resolved.kind === "ERROR") {

@@ -65,0 +65,0 @@ // We trust that these errors will be reported elsewhere.

import { DocumentNode, GraphQLSchema } from "graphql";
import { DiagnosticsResult, Result, ReportableDiagnostics } from "./utils/DiagnosticError";
import { DiagnosticsWithoutLocationResult, ReportableDiagnostics } from "./utils/DiagnosticError";
import { Result } from "./utils/Result";
import * as ts from "typescript";
import { ExtractionSnapshot } from "./Extractor";
import { ParsedCommandLineGrats } from "./gratsConfig";
export * from "./gratsConfig";
export declare function buildSchemaResult(options: ParsedCommandLineGrats): Result<GraphQLSchema, ReportableDiagnostics>;
export declare function buildSchemaResultWithHost(options: ParsedCommandLineGrats, compilerHost: ts.CompilerHost): Result<GraphQLSchema, ReportableDiagnostics>;
export type SchemaAndDoc = {
schema: GraphQLSchema;
doc: DocumentNode;
};
export declare function buildSchemaAndDocResult(options: ParsedCommandLineGrats): Result<SchemaAndDoc, ReportableDiagnostics>;
export declare function buildSchemaAndDocResultWithHost(options: ParsedCommandLineGrats, compilerHost: ts.CompilerHost): Result<SchemaAndDoc, ReportableDiagnostics>;
/**
* Given a merged snapshot representing the whole program, construct a GraphQL
* schema document with metadata directives attached.
* The core transformation pipeline of Grats.
*/
export declare function docFromSnapshot(program: ts.Program, host: ts.CompilerHost, snapshot: ExtractionSnapshot): DiagnosticsResult<DocumentNode>;
export declare function extractSchemaAndDoc(options: ParsedCommandLineGrats, program: ts.Program): DiagnosticsWithoutLocationResult<SchemaAndDoc>;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __values = (this && this.__values) || function(o) {

@@ -44,5 +30,7 @@ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;

Object.defineProperty(exports, "__esModule", { value: true });
exports.docFromSnapshot = exports.buildSchemaResultWithHost = exports.buildSchemaResult = void 0;
exports.extractSchemaAndDoc = exports.buildSchemaAndDocResultWithHost = exports.buildSchemaAndDocResult = void 0;
var graphql_1 = require("graphql");
var DiagnosticError_1 = require("./utils/DiagnosticError");
var Result_1 = require("./utils/Result");
var Result_2 = require("./utils/Result");
var ts = require("typescript");

@@ -56,11 +44,13 @@ var TypeContext_1 = require("./TypeContext");

var metadataDirectives_1 = require("./metadataDirectives");
var helpers_1 = require("./utils/helpers");
var addInterfaceFields_1 = require("./transforms/addInterfaceFields");
var filterNonGqlInterfaces_1 = require("./transforms/filterNonGqlInterfaces");
var validateAsyncIterable_1 = require("./validations/validateAsyncIterable");
var applyDefaultNullability_1 = require("./transforms/applyDefaultNullability");
var mergeExtensions_1 = require("./transforms/mergeExtensions");
var sortSchemaAst_1 = require("./transforms/sortSchemaAst");
var validateSemanticNullability_1 = require("./validations/validateSemanticNullability");
var resolveTypes_1 = require("./transforms/resolveTypes");
var validateAsyncIterable_1 = require("./validations/validateAsyncIterable");
__exportStar(require("./gratsConfig"), exports);
// Construct a schema, using GraphQL schema language
// Exported for tests that want to intercept diagnostic errors.
function buildSchemaResult(options) {
function buildSchemaAndDocResult(options) {
// https://stackoverflow.com/a/66604532/1263117

@@ -70,28 +60,67 @@ var compilerHost = ts.createCompilerHost(options.options,

true);
return buildSchemaResultWithHost(options, compilerHost);
return buildSchemaAndDocResultWithHost(options, compilerHost);
}
exports.buildSchemaResult = buildSchemaResult;
function buildSchemaResultWithHost(options, compilerHost) {
var schemaResult = extractSchema(options, compilerHost);
if (schemaResult.kind === "ERROR") {
return (0, DiagnosticError_1.err)(new DiagnosticError_1.ReportableDiagnostics(compilerHost, schemaResult.err));
}
return (0, DiagnosticError_1.ok)(schemaResult.value);
exports.buildSchemaAndDocResult = buildSchemaAndDocResult;
function buildSchemaAndDocResultWithHost(options, compilerHost) {
var program = ts.createProgram(options.fileNames, options.options, compilerHost);
return new Result_1.ResultPipe(extractSchemaAndDoc(options, program))
.mapErr(function (e) { return new DiagnosticError_1.ReportableDiagnostics(compilerHost, e); })
.result();
}
exports.buildSchemaResultWithHost = buildSchemaResultWithHost;
function extractSchema(options, host) {
var program = ts.createProgram(options.fileNames, options.options, host);
var snapshotsResult = (0, snapshotsFromProgram_1.snapshotsFromProgram)(program, options);
if (snapshotsResult.kind === "ERROR") {
return snapshotsResult;
}
var snapshot = reduceSnapshots(snapshotsResult.value);
var docResult = docFromSnapshot(program, host, snapshot);
if (docResult.kind === "ERROR") {
return docResult;
}
return buildSchemaFromDocumentNode(docResult.value, snapshot.typesWithTypenameField);
exports.buildSchemaAndDocResultWithHost = buildSchemaAndDocResultWithHost;
/**
* The core transformation pipeline of Grats.
*/
function extractSchemaAndDoc(options, program) {
return new Result_1.ResultPipe((0, snapshotsFromProgram_1.extractSnapshotsFromProgram)(program, options))
.map(function (snapshots) { return combineSnapshots(snapshots); })
.andThen(function (snapshot) {
var typesWithTypename = snapshot.typesWithTypename;
var config = options.raw.grats;
var checker = program.getTypeChecker();
var ctx = TypeContext_1.TypeContext.fromSnapshot(checker, snapshot);
// Collect validation errors
var validationResult = (0, Result_1.concatResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateContextReferences_1.validateContextReferences)(ctx, snapshot.contextReferences));
var docResult = new Result_1.ResultPipe(validationResult)
// Add the metadata directive definitions to definitions
// found in the snapshot.
.map(function () { return (0, metadataDirectives_1.addMetadataDirectives)(snapshot.definitions); })
// Filter out any `implements` clauses that are not GraphQL interfaces.
.map(function (definitions) { return (0, filterNonGqlInterfaces_1.filterNonGqlInterfaces)(ctx, definitions); })
.andThen(function (definitions) { return (0, resolveTypes_1.resolveTypes)(ctx, definitions); })
// If you define a field on an interface using the functional style, we need to add
// that field to each concrete type as well. This must be done after all types are created,
// but before we validate the schema.
.andThen(function (definitions) { return (0, addInterfaceFields_1.addInterfaceFields)(ctx, definitions); })
// Convert the definitions into a DocumentNode
.map(function (definitions) { return ({ kind: graphql_1.Kind.DOCUMENT, definitions: definitions }); })
// Ensure all subscription fields return an AsyncIterable.
.andThen(function (doc) { return (0, validateAsyncIterable_1.validateAsyncIterable)(doc); })
// Apply default nullability to fields and arguments, and detect any misuse of
// `@killsParentOnException`.
.andThen(function (doc) { return (0, applyDefaultNullability_1.applyDefaultNullability)(doc, config); })
// Merge any `extend` definitions into their base definitions.
.map(function (doc) { return (0, mergeExtensions_1.mergeExtensions)(doc); })
// Sort the definitions in the document to ensure a stable output.
.map(function (doc) { return (0, sortSchemaAst_1.sortSchemaAst)(doc); })
.result();
if (docResult.kind === "ERROR") {
return docResult;
}
var doc = docResult.value;
// Build and validate the schema with regards to the GraphQL spec.
return (new Result_1.ResultPipe(buildSchemaFromDoc(doc))
// Ensure that every type which implements an interface or is a member of a
// union has a __typename field.
.andThen(function (schema) { return (0, validateTypenames_1.validateTypenames)(schema, typesWithTypename); })
.andThen(function (schema) { return (0, validateSemanticNullability_1.validateSemanticNullability)(schema, config); })
// Combine the schema and document into a single result.
.map(function (schema) { return ({ schema: schema, doc: doc }); })
.result());
})
.result();
}
exports.extractSchemaAndDoc = extractSchemaAndDoc;
// Given a SDL AST, build and validate a GraphQLSchema.
function buildSchemaFromDocumentNode(doc, typesWithTypenameField) {
function buildSchemaFromDoc(doc) {
// TODO: Currently this does not detect definitions that shadow builtins

@@ -101,7 +130,5 @@ // (`String`, `Int`, etc). However, if we pass a second param (extending an

// shadow builtins.
var validationErrors = (0, validate_1.validateSDL)(doc).map(function (e) {
return (0, DiagnosticError_1.graphQlErrorToDiagnostic)(e);
});
var validationErrors = (0, validate_1.validateSDL)(doc);
if (validationErrors.length > 0) {
return (0, DiagnosticError_1.err)(validationErrors);
return (0, Result_2.err)(validationErrors.map(DiagnosticError_1.graphQlErrorToDiagnostic));
}

@@ -111,80 +138,11 @@ var schema = (0, graphql_1.buildASTSchema)(doc, { assumeValidSDL: true });

// FIXME: Handle case where query is not defined (no location)
.filter(function (e) { return e.source && e.locations && e.positions; })
.map(function (e) { return (0, DiagnosticError_1.graphQlErrorToDiagnostic)(e); });
.filter(function (e) { return e.source && e.locations && e.positions; });
if (diagnostics.length > 0) {
return (0, DiagnosticError_1.err)(diagnostics);
return (0, Result_2.err)(diagnostics.map(DiagnosticError_1.graphQlErrorToDiagnostic));
}
var typenameDiagnostics = (0, validateTypenames_1.validateTypenames)(schema, typesWithTypenameField);
if (typenameDiagnostics.length > 0)
return (0, DiagnosticError_1.err)(typenameDiagnostics);
return (0, DiagnosticError_1.ok)(schema);
return (0, Result_2.ok)(schema);
}
/**
* Given a merged snapshot representing the whole program, construct a GraphQL
* schema document with metadata directives attached.
*/
function docFromSnapshot(program, host, snapshot) {
var e_1, _a, e_2, _b;
var checker = program.getTypeChecker();
var ctx = new TypeContext_1.TypeContext(checker, host);
// Validate the snapshot
var mergedResult = (0, DiagnosticError_1.combineResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateContextReferences_1.validateContextReferences)(ctx, snapshot.contextReferences));
if (mergedResult.kind === "ERROR") {
return mergedResult;
}
try {
// Propagate snapshot data to type context
for (var _c = __values(snapshot.unresolvedNames), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), node = _e[0], typeName = _e[1];
ctx.markUnresolvedType(node, typeName);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
try {
for (var _f = __values(snapshot.nameDefinitions), _g = _f.next(); !_g.done; _g = _f.next()) {
var _h = __read(_g.value, 2), node = _h[0], definition = _h[1];
ctx.recordTypeName(node, definition.name, definition.kind);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
// Fixup the schema SDL
var definitions = Array.from(metadataDirectives_1.DIRECTIVES_AST.definitions);
(0, helpers_1.extend)(definitions, snapshot.definitions);
// If you define a field on an interface using the functional style, we need to add
// that field to each concrete type as well. This must be done after all types are created,
// but before we validate the schema.
var definitionsResult = (0, addInterfaceFields_1.addInterfaceFields)(ctx, definitions);
if (definitionsResult.kind === "ERROR") {
return definitionsResult;
}
var filteredDoc = (0, filterNonGqlInterfaces_1.filterNonGqlInterfaces)(ctx, {
kind: graphql_1.Kind.DOCUMENT,
definitions: definitionsResult.value,
});
var docResult = (0, resolveTypes_1.resolveTypes)(ctx, filteredDoc);
if (docResult.kind === "ERROR")
return docResult;
var doc = docResult.value;
var subscriptionsValidationResult = (0, validateAsyncIterable_1.validateAsyncIterable)(doc);
if (subscriptionsValidationResult.kind === "ERROR") {
return subscriptionsValidationResult;
}
return (0, DiagnosticError_1.ok)(doc);
}
exports.docFromSnapshot = docFromSnapshot;
// Given a list of snapshots, merge them into a single snapshot.
function reduceSnapshots(snapshots) {
var e_3, _a, e_4, _b, e_5, _c, e_6, _d, e_7, _e, e_8, _f, e_9, _g;
function combineSnapshots(snapshots) {
var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f, e_7, _g;
var result = {

@@ -195,3 +153,3 @@ definitions: [],

contextReferences: [],
typesWithTypenameField: new Set(),
typesWithTypename: new Set(),
interfaceDeclarations: [],

@@ -203,3 +161,3 @@ };

try {
for (var _h = (e_4 = void 0, __values(snapshot.definitions)), _j = _h.next(); !_j.done; _j = _h.next()) {
for (var _h = (e_2 = void 0, __values(snapshot.definitions)), _j = _h.next(); !_j.done; _j = _h.next()) {
var definition = _j.value;

@@ -209,3 +167,3 @@ result.definitions.push(definition);

}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {

@@ -215,6 +173,6 @@ try {

}
finally { if (e_4) throw e_4.error; }
finally { if (e_2) throw e_2.error; }
}
try {
for (var _k = (e_5 = void 0, __values(snapshot.nameDefinitions)), _l = _k.next(); !_l.done; _l = _k.next()) {
for (var _k = (e_3 = void 0, __values(snapshot.nameDefinitions)), _l = _k.next(); !_l.done; _l = _k.next()) {
var _m = __read(_l.value, 2), node = _m[0], definition = _m[1];

@@ -224,3 +182,3 @@ result.nameDefinitions.set(node, definition);

}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {

@@ -230,6 +188,6 @@ try {

}
finally { if (e_5) throw e_5.error; }
finally { if (e_3) throw e_3.error; }
}
try {
for (var _o = (e_6 = void 0, __values(snapshot.unresolvedNames)), _p = _o.next(); !_p.done; _p = _o.next()) {
for (var _o = (e_4 = void 0, __values(snapshot.unresolvedNames)), _p = _o.next(); !_p.done; _p = _o.next()) {
var _q = __read(_p.value, 2), node = _q[0], typeName = _q[1];

@@ -239,3 +197,3 @@ result.unresolvedNames.set(node, typeName);

}
catch (e_6_1) { e_6 = { error: e_6_1 }; }
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {

@@ -245,6 +203,6 @@ try {

}
finally { if (e_6) throw e_6.error; }
finally { if (e_4) throw e_4.error; }
}
try {
for (var _r = (e_7 = void 0, __values(snapshot.contextReferences)), _s = _r.next(); !_s.done; _s = _r.next()) {
for (var _r = (e_5 = void 0, __values(snapshot.contextReferences)), _s = _r.next(); !_s.done; _s = _r.next()) {
var contextReference = _s.value;

@@ -254,3 +212,3 @@ result.contextReferences.push(contextReference);

}
catch (e_7_1) { e_7 = { error: e_7_1 }; }
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {

@@ -260,11 +218,11 @@ try {

}
finally { if (e_7) throw e_7.error; }
finally { if (e_5) throw e_5.error; }
}
try {
for (var _t = (e_8 = void 0, __values(snapshot.typesWithTypenameField)), _u = _t.next(); !_u.done; _u = _t.next()) {
for (var _t = (e_6 = void 0, __values(snapshot.typesWithTypename)), _u = _t.next(); !_u.done; _u = _t.next()) {
var typeName = _u.value;
result.typesWithTypenameField.add(typeName);
result.typesWithTypename.add(typeName);
}
}
catch (e_8_1) { e_8 = { error: e_8_1 }; }
catch (e_6_1) { e_6 = { error: e_6_1 }; }
finally {

@@ -274,6 +232,6 @@ try {

}
finally { if (e_8) throw e_8.error; }
finally { if (e_6) throw e_6.error; }
}
try {
for (var _v = (e_9 = void 0, __values(snapshot.interfaceDeclarations)), _w = _v.next(); !_w.done; _w = _v.next()) {
for (var _v = (e_7 = void 0, __values(snapshot.interfaceDeclarations)), _w = _v.next(); !_w.done; _w = _v.next()) {
var interfaceDeclaration = _w.value;

@@ -283,3 +241,3 @@ result.interfaceDeclarations.push(interfaceDeclaration);

}
catch (e_9_1) { e_9 = { error: e_9_1 }; }
catch (e_7_1) { e_7 = { error: e_7_1 }; }
finally {

@@ -289,7 +247,7 @@ try {

}
finally { if (e_9) throw e_9.error; }
finally { if (e_7) throw e_7.error; }
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {

@@ -299,5 +257,5 @@ try {

}
finally { if (e_3) throw e_3.error; }
finally { if (e_1) throw e_1.error; }
}
return result;
}
import { GraphQLSchema, Location } from "graphql";
import { Result } from "./utils/DiagnosticError";
import { Result } from "./utils/Result";
/**

@@ -4,0 +4,0 @@ * Given an entity name of the format `ParentType` or `ParentType.fieldName`,

@@ -5,3 +5,4 @@ "use strict";

var graphql_1 = require("graphql");
var DiagnosticError_1 = require("./utils/DiagnosticError");
var Result_1 = require("./utils/Result");
var helpers_1 = require("./utils/helpers");
/**

@@ -19,9 +20,9 @@ * Given an entity name of the format `ParentType` or `ParentType.fieldName`,

if (type == null) {
return (0, DiagnosticError_1.err)("Cannot locate type `".concat(entity.parent, "`."));
return (0, Result_1.err)("Cannot locate type `".concat(entity.parent, "`."));
}
if (entity.field == null) {
if (type.astNode == null || type.astNode.name.loc == null) {
if (type.astNode == null) {
throw new Error("Grats bug: Cannot find location of type `".concat(entity.parent, "`."));
}
return (0, DiagnosticError_1.ok)(type.astNode.name.loc);
return (0, Result_1.ok)((0, helpers_1.loc)(type.astNode.name));
}

@@ -31,12 +32,12 @@ if (!(type instanceof graphql_1.GraphQLObjectType ||

type instanceof graphql_1.GraphQLInputObjectType)) {
return (0, DiagnosticError_1.err)("Cannot locate field `".concat(entity.field, "` on type `").concat(entity.parent, "`. Only object types, interfaces, and input objects have fields."));
return (0, Result_1.err)("Cannot locate field `".concat(entity.field, "` on type `").concat(entity.parent, "`. Only object types, interfaces, and input objects have fields."));
}
var field = type.getFields()[entity.field];
if (field == null) {
return (0, DiagnosticError_1.err)("Cannot locate field `".concat(entity.field, "` on type `").concat(entity.parent, "`."));
return (0, Result_1.err)("Cannot locate field `".concat(entity.field, "` on type `").concat(entity.parent, "`."));
}
if (field.astNode == null || field.astNode.name.loc == null) {
if (field.astNode == null) {
throw new Error("Grats bug: Cannot find location of field `".concat(entity.field, "` on type `").concat(entity.parent, "`."));
}
return (0, DiagnosticError_1.ok)(field.astNode.name.loc);
return (0, Result_1.ok)((0, helpers_1.loc)(field.astNode.name));
}

@@ -48,7 +49,7 @@ exports.locate = locate;

if (match == null) {
return (0, DiagnosticError_1.err)("Invalid entity name: `".concat(entityName, "`. Expected `ParentType` or `ParentType.fieldName`."));
return (0, Result_1.err)("Invalid entity name: `".concat(entityName, "`. Expected `ParentType` or `ParentType.fieldName`."));
}
var parent = match[1];
var field = match[2] || null;
return (0, DiagnosticError_1.ok)({ parent: parent, field: field });
return (0, Result_1.ok)({ parent: parent, field: field });
}

@@ -1,21 +0,74 @@

import { ConstDirectiveNode, DocumentNode, Location } from "graphql";
export declare const FIELD_NAME_DIRECTIVE = "propertyName";
export declare const EXPORTED_DIRECTIVE = "exported";
export declare const ASYNC_ITERABLE_TYPE_DIRECTIVE = "asyncIterable";
import { ConstDirectiveNode, DefinitionNode, DocumentNode, Location } from "graphql";
/**
* In most cases we can use directives to annotate constructs
* however, it't not possible to annotate an individual TypeNode.
* Additionally, we can't use sets or maps to "tag" nodes because
* there are places where we immutably update the AST to make changes.
*
* Instead, we cheat and add properties to some nodes. These types use
* interface merging to add our own properties to the AST.
*
* We try to use this approach sparingly.
*/
declare module "graphql" {
interface ListTypeNode {
/**
* Grats metadata: Whether the list type was defined as an AsyncIterable.
* Used to ensure that all fields on `Subscription` return an AsyncIterable.
*/
isAsyncIterable?: boolean;
}
interface NameNode {
/**
* Grats metadata: A unique identifier for the node. Used to track
* data about nodes in lookup data structures.
*/
tsIdentifier: number;
}
interface ObjectTypeDefinitionNode {
/**
* Grats metadata: Indicates that the type was materialized as part of
* generic type resolution.
*/
wasSynthesized?: boolean;
}
interface UnionTypeDefinitionNode {
/**
* Grats metadata: Indicates that the type was materialized as part of
* generic type resolution.
*/
wasSynthesized?: boolean;
}
interface InterfaceTypeDefinitionNode {
/**
* Grats metadata: Indicates that the type was materialized as part of
* generic type resolution.
*/
wasSynthesized?: boolean;
}
interface ObjectTypeExtensionNode {
/**
* Grats metadata: Indicates that we don't know yet if this is extending an interface
* or a type.
*/
mayBeInterface?: boolean;
}
}
export declare const FIELD_METADATA_DIRECTIVE = "metadata";
export declare const EXPORT_NAME_ARG = "exportName";
export declare const FIELD_NAME_ARG = "name";
export declare const TS_MODULE_PATH_ARG = "tsModulePath";
export declare const ARG_COUNT = "argCount";
export declare const ASYNC_ITERABLE_ARG = "asyncIterable";
export declare const KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = "killsParentOnException";
export declare const METADATA_DIRECTIVE_NAMES: Set<string>;
export declare const DIRECTIVES_AST: DocumentNode;
export type AsyncIterableTypeMetadata = true;
export type PropertyNameMetadata = {
name: string;
export declare function addMetadataDirectives(definitions: Array<DefinitionNode>): Array<DefinitionNode>;
export type FieldMetadata = {
tsModulePath: string | null;
name: string | null;
exportName: string | null;
argCount: number | null;
};
export type ExportedMetadata = {
tsModulePath: string;
exportedFunctionName: string;
argCount: number;
};
export declare function makePropertyNameDirective(loc: Location, propertyName: PropertyNameMetadata): ConstDirectiveNode;
export declare function makeExportedDirective(loc: Location, exported: ExportedMetadata): ConstDirectiveNode;
export declare function makeAsyncIterableDirective(loc: Location): ConstDirectiveNode;
export declare function parseAsyncIterableTypeDirective(directive: ConstDirectiveNode): AsyncIterableTypeMetadata;
export declare function parsePropertyNameDirective(directive: ConstDirectiveNode): PropertyNameMetadata;
export declare function parseExportedDirective(directive: ConstDirectiveNode): ExportedMetadata;
export declare function makeKillsParentOnExceptionDirective(loc: Location): ConstDirectiveNode;
export declare function parseFieldMetadataDirective(directive: ConstDirectiveNode): FieldMetadata;
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseExportedDirective = exports.parsePropertyNameDirective = exports.parseAsyncIterableTypeDirective = exports.makeAsyncIterableDirective = exports.makeExportedDirective = exports.makePropertyNameDirective = exports.DIRECTIVES_AST = exports.METADATA_DIRECTIVE_NAMES = exports.ASYNC_ITERABLE_TYPE_DIRECTIVE = exports.EXPORTED_DIRECTIVE = exports.FIELD_NAME_DIRECTIVE = void 0;
exports.parseFieldMetadataDirective = exports.makeKillsParentOnExceptionDirective = exports.addMetadataDirectives = exports.DIRECTIVES_AST = exports.METADATA_DIRECTIVE_NAMES = exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = exports.ASYNC_ITERABLE_ARG = exports.ARG_COUNT = exports.TS_MODULE_PATH_ARG = exports.FIELD_NAME_ARG = exports.EXPORT_NAME_ARG = exports.FIELD_METADATA_DIRECTIVE = void 0;
var graphql_1 = require("graphql");
exports.FIELD_NAME_DIRECTIVE = "propertyName";
var FIELD_NAME_ARG = "name";
exports.EXPORTED_DIRECTIVE = "exported";
var TS_MODULE_PATH_ARG = "tsModulePath";
var ARG_COUNT = "argCount";
var EXPORTED_FUNCTION_NAME_ARG = "functionName";
exports.ASYNC_ITERABLE_TYPE_DIRECTIVE = "asyncIterable";
var helpers_1 = require("./utils/helpers");
exports.FIELD_METADATA_DIRECTIVE = "metadata";
exports.EXPORT_NAME_ARG = "exportName";
exports.FIELD_NAME_ARG = "name";
exports.TS_MODULE_PATH_ARG = "tsModulePath";
exports.ARG_COUNT = "argCount";
exports.ASYNC_ITERABLE_ARG = "asyncIterable";
exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = "killsParentOnException";
exports.METADATA_DIRECTIVE_NAMES = new Set([
exports.FIELD_NAME_DIRECTIVE,
exports.EXPORTED_DIRECTIVE,
exports.ASYNC_ITERABLE_TYPE_DIRECTIVE,
exports.FIELD_METADATA_DIRECTIVE,
exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE,
]);
exports.DIRECTIVES_AST = (0, graphql_1.parse)("\n directive @".concat(exports.ASYNC_ITERABLE_TYPE_DIRECTIVE, " on FIELD_DEFINITION\n directive @").concat(exports.FIELD_NAME_DIRECTIVE, "(").concat(FIELD_NAME_ARG, ": String!) on FIELD_DEFINITION\n directive @").concat(exports.EXPORTED_DIRECTIVE, "(\n ").concat(TS_MODULE_PATH_ARG, ": String!,\n ").concat(EXPORTED_FUNCTION_NAME_ARG, ": String!\n ").concat(ARG_COUNT, ": Int!\n ) on FIELD_DEFINITION\n"));
function makePropertyNameDirective(loc, propertyName) {
return {
kind: graphql_1.Kind.DIRECTIVE,
loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: exports.FIELD_NAME_DIRECTIVE },
arguments: [makeStringArg(loc, FIELD_NAME_ARG, propertyName.name)],
};
exports.DIRECTIVES_AST = (0, graphql_1.parse)("\n directive @".concat(exports.FIELD_METADATA_DIRECTIVE, "(\n \"\"\"\n Name of property/method/function. Defaults to field name.\n \"\"\"\n ").concat(exports.FIELD_NAME_ARG, ": String\n \"\"\"\n Path of the TypeScript module to import if the field is a function.\n \"\"\"\n ").concat(exports.TS_MODULE_PATH_ARG, ": String\n \"\"\"\n Export name of the field. For function fields this is the exported function name,\n for static method fields, this is the exported class name.\n \"\"\"\n ").concat(exports.EXPORT_NAME_ARG, ": String\n \"\"\"\n Number of arguments. No value means property access\n \"\"\"\n ").concat(exports.ARG_COUNT, ": Int\n ) on FIELD_DEFINITION\n directive @").concat(exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE, " on FIELD_DEFINITION\n"));
function addMetadataDirectives(definitions) {
return __spreadArray(__spreadArray([], __read(exports.DIRECTIVES_AST.definitions), false), __read(definitions), false);
}
exports.makePropertyNameDirective = makePropertyNameDirective;
function makeExportedDirective(loc, exported) {
exports.addMetadataDirectives = addMetadataDirectives;
function makeKillsParentOnExceptionDirective(loc) {
return {
kind: graphql_1.Kind.DIRECTIVE,
loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: exports.EXPORTED_DIRECTIVE },
arguments: [
makeStringArg(loc, TS_MODULE_PATH_ARG, exported.tsModulePath),
makeStringArg(loc, EXPORTED_FUNCTION_NAME_ARG, exported.exportedFunctionName),
makeIntArg(loc, ARG_COUNT, exported.argCount),
],
};
}
exports.makeExportedDirective = makeExportedDirective;
function makeAsyncIterableDirective(loc) {
return {
kind: graphql_1.Kind.DIRECTIVE,
loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: exports.ASYNC_ITERABLE_TYPE_DIRECTIVE },
name: {
kind: graphql_1.Kind.NAME,
loc: loc,
value: exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE,
tsIdentifier: (0, helpers_1.uniqueId)(),
},
arguments: [],
};
}
exports.makeAsyncIterableDirective = makeAsyncIterableDirective;
function parseAsyncIterableTypeDirective(directive) {
if (directive.name.value !== exports.ASYNC_ITERABLE_TYPE_DIRECTIVE) {
throw new Error("Expected directive to be ".concat(exports.ASYNC_ITERABLE_TYPE_DIRECTIVE));
exports.makeKillsParentOnExceptionDirective = makeKillsParentOnExceptionDirective;
function parseFieldMetadataDirective(directive) {
if (directive.name.value !== exports.FIELD_METADATA_DIRECTIVE) {
throw new Error("Expected directive to be ".concat(exports.FIELD_METADATA_DIRECTIVE));
}
return true;
}
exports.parseAsyncIterableTypeDirective = parseAsyncIterableTypeDirective;
function parsePropertyNameDirective(directive) {
if (directive.name.value !== exports.FIELD_NAME_DIRECTIVE) {
throw new Error("Expected directive to be ".concat(exports.FIELD_NAME_DIRECTIVE));
}
return { name: getStringArg(directive, FIELD_NAME_ARG) };
}
exports.parsePropertyNameDirective = parsePropertyNameDirective;
function parseExportedDirective(directive) {
if (directive.name.value !== exports.EXPORTED_DIRECTIVE) {
throw new Error("Expected directive to be ".concat(exports.EXPORTED_DIRECTIVE));
}
return {
tsModulePath: getStringArg(directive, TS_MODULE_PATH_ARG),
exportedFunctionName: getStringArg(directive, EXPORTED_FUNCTION_NAME_ARG),
argCount: getIntArg(directive, ARG_COUNT),
name: getStringArg(directive, exports.FIELD_NAME_ARG),
tsModulePath: getStringArg(directive, exports.TS_MODULE_PATH_ARG),
exportName: getStringArg(directive, exports.EXPORT_NAME_ARG),
argCount: getIntArg(directive, exports.ARG_COUNT),
};
}
exports.parseExportedDirective = parseExportedDirective;
exports.parseFieldMetadataDirective = parseFieldMetadataDirective;
function getStringArg(directive, argName) {

@@ -78,3 +77,3 @@ var _a;

if (!arg) {
throw new Error("Expected to find argument ".concat(argName));
return null;
}

@@ -90,3 +89,3 @@ if (arg.value.kind !== graphql_1.Kind.STRING) {

if (!arg) {
throw new Error("Expected to find argument ".concat(argName));
return null;
}

@@ -98,17 +97,1 @@ if (arg.value.kind !== graphql_1.Kind.INT) {

}
function makeStringArg(loc, argName, value) {
return {
kind: graphql_1.Kind.ARGUMENT,
loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: argName },
value: { kind: graphql_1.Kind.STRING, loc: loc, value: value },
};
}
function makeIntArg(loc, argName, value) {
return {
kind: graphql_1.Kind.ARGUMENT,
loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: argName },
value: { kind: graphql_1.Kind.INT, loc: loc, value: value.toString() },
};
}

@@ -1,3 +0,3 @@

import { GraphQLSchema } from "graphql";
import { ConfigOptions } from "./lib";
import { DocumentNode, GraphQLSchema } from "graphql";
import { ConfigOptions } from "./gratsConfig";
/**

@@ -8,2 +8,3 @@ * Prints code for a TypeScript module that exports a GraphQLSchema.

export declare function printExecutableSchema(schema: GraphQLSchema, config: ConfigOptions, destination: string): string;
export declare function applyTypeScriptHeader(config: ConfigOptions, code: string): string;
/**

@@ -13,3 +14,4 @@ * Prints SDL, potentially omitting directives depending upon the config.

*/
export declare function printGratsSDL(schema: GraphQLSchema, config: ConfigOptions): string;
export declare function printSDLWithoutDirectives(schema: GraphQLSchema): string;
export declare function printGratsSDL(doc: DocumentNode, config: ConfigOptions): string;
export declare function applySDLHeader(config: ConfigOptions, sdl: string): string;
export declare function printSDLWithoutMetadata(doc: DocumentNode): string;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.printSDLWithoutDirectives = exports.printGratsSDL = exports.printExecutableSchema = void 0;
exports.printSDLWithoutMetadata = exports.applySDLHeader = exports.printGratsSDL = exports.applyTypeScriptHeader = exports.printExecutableSchema = void 0;
var graphql_1 = require("graphql");

@@ -24,8 +13,9 @@ var codegen_1 = require("./codegen");

var code = (0, codegen_1.codegen)(schema, destination);
if (config.tsSchemaHeader) {
return "".concat(config.tsSchemaHeader, "\n").concat(code);
}
return code;
return applyTypeScriptHeader(config, code);
}
exports.printExecutableSchema = printExecutableSchema;
function applyTypeScriptHeader(config, code) {
return formatHeader(config.tsSchemaHeader, code);
}
exports.applyTypeScriptHeader = applyTypeScriptHeader;
/**

@@ -35,15 +25,33 @@ * Prints SDL, potentially omitting directives depending upon the config.

*/
function printGratsSDL(schema, config) {
var sdl = printSDLWithoutDirectives(schema);
if (config.schemaHeader) {
return "".concat(config.schemaHeader, "\n").concat(sdl);
}
return sdl;
function printGratsSDL(doc, config) {
var sdl = printSDLWithoutMetadata(doc);
return applySDLHeader(config, sdl) + "\n";
}
exports.printGratsSDL = printGratsSDL;
function printSDLWithoutDirectives(schema) {
return (0, graphql_1.printSchema)(new graphql_1.GraphQLSchema(__assign(__assign({}, schema.toConfig()), { directives: schema.getDirectives().filter(function (directive) {
return !metadataDirectives_1.METADATA_DIRECTIVE_NAMES.has(directive.name);
}) })));
function applySDLHeader(config, sdl) {
return formatHeader(config.schemaHeader, sdl);
}
exports.printSDLWithoutDirectives = printSDLWithoutDirectives;
exports.applySDLHeader = applySDLHeader;
function printSDLWithoutMetadata(doc) {
var trimmed = (0, graphql_1.visit)(doc, {
DirectiveDefinition: function (t) {
return metadataDirectives_1.METADATA_DIRECTIVE_NAMES.has(t.name.value) ? null : t;
},
Directive: function (t) {
return metadataDirectives_1.METADATA_DIRECTIVE_NAMES.has(t.name.value) ? null : t;
},
ScalarTypeDefinition: function (t) {
return graphql_1.specifiedScalarTypes.some(function (scalar) { return scalar.name === t.name.value; })
? null
: t;
},
});
return (0, graphql_1.print)(trimmed);
}
exports.printSDLWithoutMetadata = printSDLWithoutMetadata;
function formatHeader(header, code) {
if (header !== null) {
return "".concat(header, "\n").concat(code);
}
return code;
}
import { DefinitionNode } from "graphql";
import { TypeContext } from "../TypeContext";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { GratsDefinitionNode } from "../GraphQLConstructor";
/**

@@ -13,2 +12,2 @@ * Grats allows you to define GraphQL fields on TypeScript interfaces using

*/
export declare function addInterfaceFields(ctx: TypeContext, docs: GratsDefinitionNode[]): DiagnosticsResult<DefinitionNode[]>;
export declare function addInterfaceFields(ctx: TypeContext, docs: DefinitionNode[]): DiagnosticsResult<DefinitionNode[]>;

@@ -29,6 +29,7 @@ "use strict";

var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
var InterfaceGraph_1 = require("../InterfaceGraph");
var helpers_1 = require("../utils/helpers");
var Extractor_1 = require("../Extractor");
var metadataDirectives_1 = require("../metadataDirectives");
var Extractor_1 = require("../Extractor");
/**

@@ -50,6 +51,6 @@ * Grats allows you to define GraphQL fields on TypeScript interfaces using

var doc = docs_1_1.value;
if (doc.kind === "AbstractFieldDefinition") {
if (doc.kind === graphql_1.Kind.OBJECT_TYPE_EXTENSION && doc.mayBeInterface) {
var abstractDocResults = addAbstractFieldDefinition(ctx, doc, interfaceGraph);
if (abstractDocResults.kind === "ERROR") {
(0, helpers_1.extend)(errors, abstractDocResults.err);
errors.push(abstractDocResults.err);
}

@@ -73,5 +74,5 @@ else {

if (errors.length > 0) {
return (0, DiagnosticError_1.err)(errors);
return (0, Result_1.err)(errors);
}
return (0, DiagnosticError_1.ok)(newDocs);
return (0, Result_1.ok)(newDocs);
}

@@ -83,5 +84,5 @@ exports.addInterfaceFields = addInterfaceFields;

var e_2, _a;
var _b;
var _b, _c;
var newDocs = [];
var definitionResult = ctx.getNameDefinition(doc.onType);
var definitionResult = ctx.gqlNameDefinitionForGqlName(doc.name);
if (definitionResult.kind === "ERROR") {

@@ -91,2 +92,3 @@ return definitionResult;

var nameDefinition = definitionResult.value;
var field = (0, helpers_1.nullThrows)((_b = doc.fields) === null || _b === void 0 ? void 0 : _b[0]);
switch (nameDefinition.kind) {

@@ -97,4 +99,4 @@ case "TYPE":

kind: graphql_1.Kind.OBJECT_TYPE_EXTENSION,
name: doc.onType,
fields: [doc.field],
name: doc.name,
fields: [field],
loc: doc.loc,

@@ -108,17 +110,18 @@ });

// need to annotate it with the details of the implementation.
var directives = (_b = doc.field.directives) === null || _b === void 0 ? void 0 : _b.filter(function (directive) {
return directive.name.value !== metadataDirectives_1.EXPORTED_DIRECTIVE;
var directives = (_c = field.directives) === null || _c === void 0 ? void 0 : _c.filter(function (directive) {
return directive.name.value !== metadataDirectives_1.FIELD_METADATA_DIRECTIVE;
});
newDocs.push({
kind: graphql_1.Kind.INTERFACE_TYPE_EXTENSION,
name: doc.onType,
fields: [__assign(__assign({}, doc.field), { directives: directives })],
name: doc.name,
fields: [__assign(__assign({}, field), { directives: directives })],
});
try {
for (var _c = __values(interfaceGraph.get(nameDefinition.name.value)), _d = _c.next(); !_d.done; _d = _c.next()) {
var implementor = _d.value;
for (var _d = __values(interfaceGraph.get(nameDefinition.name.value)), _e = _d.next(); !_e.done; _e = _d.next()) {
var implementor = _e.value;
var name = {
kind: graphql_1.Kind.NAME,
value: implementor.name,
loc: doc.loc, // Bit of a lie, but I don't see a better option.
loc: doc.loc,
tsIdentifier: (0, helpers_1.uniqueId)(),
};

@@ -130,3 +133,3 @@ switch (implementor.kind) {

name: name,
fields: [doc.field],
fields: [field],
loc: doc.loc,

@@ -139,3 +142,3 @@ });

name: name,
fields: [__assign(__assign({}, doc.field), { directives: directives })],
fields: [__assign(__assign({}, field), { directives: directives })],
loc: doc.loc,

@@ -150,3 +153,3 @@ });

try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
}

@@ -159,18 +162,10 @@ finally { if (e_2) throw e_2.error; }

// Extending any other type of definition is not supported.
var loc = doc.onType.loc;
if (loc == null) {
throw new Error("Expected onType to have a location.");
}
var relatedLoc = nameDefinition.name.loc;
if (relatedLoc == null) {
throw new Error("Expected nameDefinition to have a location.");
}
return (0, DiagnosticError_1.err)([
(0, DiagnosticError_1.gqlErr)(loc, E.invalidTypePassedToFieldFunction(), [
(0, DiagnosticError_1.gqlRelated)(relatedLoc, "This is the type that was passed to `@".concat(Extractor_1.FIELD_TAG, "`.")),
]),
]);
var loc = (0, helpers_1.nullThrows)(doc.name.loc);
var relatedLoc = (0, helpers_1.nullThrows)(nameDefinition.name.loc);
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(loc, E.invalidTypePassedToFieldFunction(), [
(0, DiagnosticError_1.gqlRelated)(relatedLoc, "This is the type that was passed to `@".concat(Extractor_1.FIELD_TAG, "`.")),
]));
}
}
return (0, DiagnosticError_1.ok)(newDocs);
return (0, Result_1.ok)(newDocs);
}

@@ -1,2 +0,2 @@

import { DocumentNode } from "graphql";
import { DefinitionNode } from "graphql";
import { TypeContext } from "../TypeContext";

@@ -9,2 +9,2 @@ /**

*/
export declare function filterNonGqlInterfaces(ctx: TypeContext, doc: DocumentNode): DocumentNode;
export declare function filterNonGqlInterfaces(ctx: TypeContext, definitions: DefinitionNode[]): DefinitionNode[];

@@ -22,10 +22,12 @@ "use strict";

*/
function filterNonGqlInterfaces(ctx, doc) {
var _a;
return (0, graphql_1.visit)(doc, (_a = {},
_a[graphql_1.Kind.INTERFACE_TYPE_DEFINITION] = function (t) { return filterInterfaces(ctx, t); },
_a[graphql_1.Kind.OBJECT_TYPE_DEFINITION] = function (t) { return filterInterfaces(ctx, t); },
_a[graphql_1.Kind.OBJECT_TYPE_EXTENSION] = function (t) { return filterInterfaces(ctx, t); },
_a[graphql_1.Kind.INTERFACE_TYPE_EXTENSION] = function (t) { return filterInterfaces(ctx, t); },
_a));
function filterNonGqlInterfaces(ctx, definitions) {
return definitions.map(function (def) {
if (def.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION ||
def.kind === graphql_1.Kind.INTERFACE_TYPE_EXTENSION ||
def.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION ||
def.kind === graphql_1.Kind.OBJECT_TYPE_EXTENSION) {
return filterInterfaces(ctx, def);
}
return def;
});
}

@@ -32,0 +34,0 @@ exports.filterNonGqlInterfaces = filterNonGqlInterfaces;

@@ -1,10 +0,10 @@

import { DocumentNode } from "graphql";
import { DefinitionNode } from "graphql";
import { TypeContext } from "../TypeContext";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { TypeContext } from "../TypeContext";
/**
* During the extraction process when we observe a type reference in a GraphQL
* position we don't actually resolve that to its GraphQL type name during
* extraction. Instead we rely on this transform to resolve those references and
* ensure that they point to `@gql` types.
* During extraction we are operating purely syntactically, so we don't actually know
* which types are being referred to. This function resolves those references.
*
* It also materializes any generic type references into concrete types.
*/
export declare function resolveTypes(ctx: TypeContext, doc: DocumentNode): DiagnosticsResult<DocumentNode>;
export declare function resolveTypes(ctx: TypeContext, definitions: Array<DefinitionNode>): DiagnosticsResult<DefinitionNode[]>;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveTypes = void 0;
var graphql_1 = require("graphql");
var GraphQLConstructor_1 = require("../GraphQLConstructor");
var ts = require("typescript");
var Result_1 = require("../utils/Result");
var DiagnosticError_1 = require("../utils/DiagnosticError");
var helpers_1 = require("../utils/helpers");
var E = require("../Errors");
/**
* During the extraction process when we observe a type reference in a GraphQL
* position we don't actually resolve that to its GraphQL type name during
* extraction. Instead we rely on this transform to resolve those references and
* ensure that they point to `@gql` types.
* During extraction we are operating purely syntactically, so we don't actually know
* which types are being referred to. This function resolves those references.
*
* It also materializes any generic type references into concrete types.
*/
function resolveTypes(ctx, doc) {
var _a;
var errors = [];
var newDoc = (0, graphql_1.visit)(doc, (_a = {},
_a[graphql_1.Kind.NAME] = function (t) {
var namedTypeResult = ctx.resolveNamedType(t);
if (namedTypeResult.kind === "ERROR") {
errors.push(namedTypeResult.err);
return t;
function resolveTypes(ctx, definitions) {
var templateExtractor = new TemplateExtractor(ctx);
return templateExtractor.materializeGenericTypeReferences(definitions);
}
exports.resolveTypes = resolveTypes;
/**
* Template extraction happens in two phases and resolves named type references
* as a side effect.
*
* 1. We walk all declarations checking if they contain type references in
* GraphQL positions which point back to the declaration's type parameters. If
* so, they are considered templates and are removed from the list of "real"
* declarations.
* 2. We walk the remaining "real" declarations and resolve any type references,
* if a reference refers to a template we first validate and resolve its type
* arguments and then use those as inputs to materialize a new type to match
* those type arguments.
*
* ## Two Types of Recursion
*
* 1. Type arguments may themselves be parameterized, and so we must
* process generic type references recursively in a depth-first manner.
*
* 2. When materializing templates we may encounter more parameterized
* references to other templates. In this way, template materialization can be
* recursive, and we must take care to avoid infinite loops. We must also take
* care to correctly track our scope such that type references in templates
* which refer to generic types resolve to the correct type.
*/
var TemplateExtractor = /** @class */ (function () {
function TemplateExtractor(ctx) {
this.ctx = ctx;
this._templates = new Map();
this._definitions = [];
this._definedTemplates = new Set();
this._errors = [];
}
TemplateExtractor.prototype.materializeGenericTypeReferences = function (definitions) {
var _this = this;
// We filter out all template declarations and index them as a first pass.
var filtered = definitions.filter(function (definition) {
return !_this.maybeExtractAsTemplate(definition);
});
// Now we can visit the remaining "real" definitions and materialize any
// generic type references.
filtered.forEach(function (definition) {
_this._definitions.push(_this.materializeTemplatesForNode(definition));
});
if (this._errors.length > 0) {
return (0, Result_1.err)(this._errors);
}
return (0, Result_1.ok)(this._definitions);
};
/**
* Walks GraphQL ASTs and expands generic types into their concrete types
* adding their materialized definitions to the `_definitions` array as we go.
*
* **Note:** Here we also detect generics being used as members of a union and
* report that as an error.
*/
TemplateExtractor.prototype.materializeTemplatesForNode = function (node) {
var _a;
var _this = this;
return (0, graphql_1.visit)(node, (_a = {},
_a[graphql_1.Kind.NAME] = function (node) {
var referenceNode = _this.getReferenceNode(node);
if (referenceNode == null)
return node;
var name = _this.resolveTypeReferenceOrReport(referenceNode);
if (name == null)
return node;
return __assign(__assign({}, node), { value: name });
},
_a));
};
TemplateExtractor.prototype.resolveTypeReferenceOrReport = function (node, generics) {
var e_1, _a;
var _b;
var declaration = this.asNullable(this.ctx.tsDeclarationForTsName(node.typeName));
if (declaration == null)
return null;
if (generics != null) {
var genericName = generics.get(declaration);
if (genericName != null) {
return genericName;
}
return namedTypeResult.value;
},
_a));
if (errors.length > 0) {
return (0, DiagnosticError_1.err)(errors);
}
var template = this._templates.get(declaration);
if (template != null) {
var templateName = template.declarationTemplate.name.value;
var typeArguments = (_b = node.typeArguments) !== null && _b !== void 0 ? _b : [];
var genericIndexes = new Map();
try {
for (var _c = __values(template.genericNodes), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), node_1 = _e[0], index = _e[1];
genericIndexes.set(index, node_1);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
var names = [];
for (var i = 0; i < template.typeParameters.length; i++) {
var exampleGenericNode = genericIndexes.get(i);
if (exampleGenericNode == null) {
continue;
}
var param = template.typeParameters[i];
var paramName = param.name.text;
var arg = typeArguments[i];
if (arg == null) {
return this.report(node, E.missingGenericType(templateName, paramName), [
(0, DiagnosticError_1.tsErr)(param, "Type parameter `".concat(paramName, "` is defined here")),
(0, DiagnosticError_1.tsErr)(exampleGenericNode, "and expects a GraphQL type because it was used in a GraphQL position here."),
]);
}
if (!ts.isTypeReferenceNode(arg)) {
return this.report(arg, E.nonGraphQLGenericType(templateName, paramName), [
(0, DiagnosticError_1.tsErr)(param, "Type parameter `".concat(paramName, "` is defined here")),
(0, DiagnosticError_1.tsErr)(exampleGenericNode, "and expects a GraphQL type because it was used in a GraphQL position here."),
]);
}
var name = this.resolveTypeReferenceOrReport(arg, generics);
// resolveTypeReference will report an error if the definition is not found.
if (name == null)
return null;
names.push(name);
}
return this.materializeTemplate(node, names, template);
}
var nameResult = this.ctx.gqlNameForTsName(node.typeName);
return this.asNullable(nameResult);
};
TemplateExtractor.prototype.materializeTemplate = function (referenceLoc, typeParams, template) {
var e_2, _a, _b;
var _this = this;
var paramsPrefix = typeParams.join("");
var derivedName = paramsPrefix + template.declarationTemplate.name.value;
if (this._definedTemplates.has(derivedName)) {
// We've either already materialized this permutation or we're in the middle
// of doing so.
return derivedName;
}
this._definedTemplates.add(derivedName);
var genericsContext = new Map();
try {
for (var _c = __values(new Set(template.genericNodes.values())), _d = _c.next(); !_d.done; _d = _c.next()) {
var i = _d.value;
var name = (0, helpers_1.nullThrows)(typeParams[i]);
var param = (0, helpers_1.nullThrows)(template.typeParameters[i]);
genericsContext.set(param, name);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_2) throw e_2.error; }
}
var gqlLoc = (0, GraphQLConstructor_1.loc)(referenceLoc);
var original = template.declarationTemplate;
var renamedDefinition = renameDefinition(original, derivedName, gqlLoc);
var definition = (0, graphql_1.visit)(renamedDefinition, (_b = {},
_b[graphql_1.Kind.NAMED_TYPE] = function (node) {
var referenceNode = _this.getReferenceNode(node.name);
if (referenceNode == null)
return node;
var name = _this.resolveTypeReferenceOrReport(referenceNode, genericsContext);
if (name == null)
return node;
return __assign(__assign({}, node), { name: __assign(__assign({}, node.name), { value: name }) });
},
_b));
this._definitions.push(definition);
return derivedName;
};
TemplateExtractor.prototype.maybeExtractAsTemplate = function (definition) {
var _a;
var _this = this;
if (!mayReferenceGenerics(definition)) {
return false;
}
var declaration = this.ctx.tsDeclarationForGqlDefinition(definition);
var typeParams = getTypeParameters(declaration);
if (typeParams == null || typeParams.length === 0) {
return false;
}
var genericNodes = new Map();
(0, graphql_1.visit)(definition, (_a = {},
_a[graphql_1.Kind.NAMED_TYPE] = function (node) {
var e_3, _a;
var referenceNode = _this.getReferenceNode(node.name);
if (referenceNode == null)
return;
var references = findAllReferences(referenceNode);
try {
for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
var reference = references_1_1.value;
var declarationResult = _this.ctx.tsDeclarationForTsName(reference.typeName);
if (declarationResult.kind === "ERROR") {
_this._errors.push(declarationResult.err);
return;
}
var declaration_1 = declarationResult.value;
// If the type points to a type param...
if (!ts.isTypeParameterDeclaration(declaration_1)) {
return;
}
// And it's one of our parent type's type params...
var genericIndex = typeParams.indexOf(declaration_1);
if (genericIndex !== -1) {
genericNodes.set(reference.typeName, genericIndex);
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
}
finally { if (e_3) throw e_3.error; }
}
},
_a));
if (genericNodes.size === 0) {
return false;
}
if (definition.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION) {
if (definition.interfaces && definition.interfaces.length > 0) {
var loc_1 = (0, helpers_1.loc)(definition.interfaces[0].name);
this._errors.push((0, DiagnosticError_1.gqlErr)(loc_1, E.genericTypeImplementsInterface()));
}
}
this._templates.set(declaration, {
declarationTemplate: definition,
genericNodes: genericNodes,
typeParameters: typeParams,
});
return true;
};
// --- Helpers ---
TemplateExtractor.prototype.getReferenceNode = function (name) {
var node = this.ctx.getEntityName(name);
if (node == null) {
return null;
}
if (ts.isTypeReferenceNode(node.parent))
return node.parent;
// Heritage clauses are not actually type references since they have
// runtime semantics. Instead they are an "ExpressionWithTypeArguments"
if (ts.isExpressionWithTypeArguments(node.parent) &&
ts.isIdentifier(node.parent.expression)) {
return new EntityNameWithTypeArguments(node.parent.expression, node.parent.typeArguments);
}
return null;
};
TemplateExtractor.prototype.asNullable = function (result) {
if (result.kind === "ERROR") {
this._errors.push(result.err);
return null;
}
return result.value;
};
TemplateExtractor.prototype.report = function (node, message, relatedInformation) {
this._errors.push((0, DiagnosticError_1.tsErr)(node, message, relatedInformation));
return null;
};
return TemplateExtractor;
}());
function mayReferenceGenerics(definition) {
return (definition.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION ||
definition.kind === graphql_1.Kind.UNION_TYPE_DEFINITION ||
definition.kind === graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION ||
definition.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION);
}
function getTypeParameters(declaration) {
var _a, _b, _c;
if (ts.isTypeAliasDeclaration(declaration)) {
return (_a = declaration.typeParameters) !== null && _a !== void 0 ? _a : null;
}
return (0, DiagnosticError_1.ok)(newDoc);
if (ts.isInterfaceDeclaration(declaration)) {
return (_b = declaration.typeParameters) !== null && _b !== void 0 ? _b : null;
}
if (ts.isClassDeclaration(declaration)) {
return (_c = declaration.typeParameters) !== null && _c !== void 0 ? _c : null;
}
// TODO: Handle other types of declarations which have generics.
return null;
}
exports.resolveTypes = resolveTypes;
/**
* Abstraction that can be derived from a typeReference or an expression with
* type arguments. Gives us a common shape which can model both a
* `ts.TypeReferenceNode` and a `ts.ExpressionWithTypeArguments` while also
* being able to use it to report diagnostics
*/
var EntityNameWithTypeArguments = /** @class */ (function () {
function EntityNameWithTypeArguments(typeName, typeArguments) {
this.typeName = typeName;
this.typeArguments = typeArguments;
}
EntityNameWithTypeArguments.prototype.getStart = function () {
return this.typeName.getStart();
};
EntityNameWithTypeArguments.prototype.getEnd = function () {
if (this.typeArguments == null || this.typeArguments.length === 0) {
return this.typeName.getEnd();
}
return this.typeArguments[this.typeArguments.length - 1].getEnd();
};
EntityNameWithTypeArguments.prototype.getSourceFile = function () {
return this.typeName.getSourceFile();
};
return EntityNameWithTypeArguments;
}());
// Given a type reference, recursively walk its type arguments and return all
// type references in the current scope.
function findAllReferences(node) {
var e_4, _a;
var references = [];
if (node.typeArguments != null) {
try {
for (var _b = __values(node.typeArguments), _c = _b.next(); !_c.done; _c = _b.next()) {
var arg = _c.value;
if (ts.isTypeReferenceNode(arg)) {
(0, helpers_1.extend)(references, findAllReferences(arg));
}
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_4) throw e_4.error; }
}
}
references.push(node);
return references;
}
function renameDefinition(original, newName, loc) {
var name = __assign(__assign({}, original.name), { value: newName, loc: loc });
return __assign(__assign({}, original), { loc: loc, name: name, wasSynthesized: true });
}
import * as ts from "typescript";
import { ParsedCommandLineGrats } from "../gratsConfig";
import { ExtractionSnapshot } from "../Extractor";
import { DiagnosticsResult } from "../utils/DiagnosticError";
export declare function snapshotsFromProgram(program: ts.Program, options: ParsedCommandLineGrats): DiagnosticsResult<ExtractionSnapshot[]>;
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
export declare function extractSnapshotsFromProgram(program: ts.Program, options: ParsedCommandLineGrats): DiagnosticsWithoutLocationResult<ExtractionSnapshot[]>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.snapshotsFromProgram = void 0;
exports.extractSnapshotsFromProgram = void 0;
var ts = require("typescript");
var Extractor_1 = require("../Extractor");
var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
var Result_2 = require("../utils/Result");
var helpers_1 = require("../utils/helpers");
var TAG_REGEX = /@(gql)|(killsParentOnException)/i;
// Given a ts.Program, extract a set of ExtractionSnapshots from it.
// In the future this part might be able to be incremental, were we only run extraction
// on changed files.
function snapshotsFromProgram(program, options) {
function extractSnapshotsFromProgram(program, options) {
var errors = [];
var gratsSourceFiles = program.getSourceFiles().filter(function (sourceFile) {
// If the file doesn't contain any GraphQL definitions, skip it.
if (!/@gql/i.test(sourceFile.text)) {
if (!TAG_REGEX.test(sourceFile.text)) {
return false;

@@ -40,9 +42,9 @@ }

if (errors.length > 0) {
return (0, DiagnosticError_1.err)(errors);
return (0, Result_2.err)(errors);
}
var extractResults = gratsSourceFiles.map(function (sourceFile) {
return (0, Extractor_1.extract)(options.raw.grats, sourceFile);
return (0, Extractor_1.extract)(sourceFile);
});
return (0, DiagnosticError_1.collectResults)(extractResults);
return (0, Result_1.collectResults)(extractResults);
}
exports.snapshotsFromProgram = snapshotsFromProgram;
exports.extractSnapshotsFromProgram = extractSnapshotsFromProgram;

@@ -1,4 +0,5 @@

import { NameNode } from "graphql";
import { InputObjectTypeDefinitionNode, InterfaceTypeDefinitionNode, NameNode, ObjectTypeDefinitionNode, UnionTypeDefinitionNode } from "graphql";
import * as ts from "typescript";
import { DiagnosticResult, DiagnosticsResult } from "./utils/DiagnosticError";
import { DiagnosticResult } from "./utils/DiagnosticError";
import { ExtractionSnapshot } from "./Extractor";
export declare const UNRESOLVED_REFERENCE_NAME = "__UNRESOLVED_REFERENCE__";

@@ -9,2 +10,3 @@ export type NameDefinition = {

};
type TsIdentifier = number;
/**

@@ -24,13 +26,20 @@ * Used to track TypeScript references.

checker: ts.TypeChecker;
host: ts.CompilerHost;
_symbolToName: Map<ts.Symbol, NameDefinition>;
_unresolvedTypes: Map<NameNode, ts.Symbol>;
constructor(checker: ts.TypeChecker, host: ts.CompilerHost);
recordTypeName(node: ts.Node, name: NameNode, kind: NameDefinition["kind"]): void;
markUnresolvedType(node: ts.Node, name: NameNode): void;
_declarationToName: Map<ts.Declaration, NameDefinition>;
_unresolvedNodes: Map<TsIdentifier, ts.EntityName>;
_idToDeclaration: Map<TsIdentifier, ts.Declaration>;
static fromSnapshot(checker: ts.TypeChecker, snapshot: ExtractionSnapshot): TypeContext;
constructor(checker: ts.TypeChecker);
private _recordTypeName;
private _markUnresolvedType;
findSymbolDeclaration(startSymbol: ts.Symbol): ts.Declaration | null;
resolveSymbol(startSymbol: ts.Symbol): ts.Symbol;
resolveNamedType(unresolved: NameNode): DiagnosticResult<NameNode>;
private resolveSymbol;
resolveUnresolvedNamedType(unresolved: NameNode): DiagnosticResult<NameNode>;
unresolvedNameIsGraphQL(unresolved: NameNode): boolean;
getNameDefinition(nameNode: NameNode): DiagnosticsResult<NameDefinition>;
gqlNameDefinitionForGqlName(nameNode: NameNode): DiagnosticResult<NameDefinition>;
gqlNameForTsName(node: ts.EntityName): DiagnosticResult<string>;
private maybeTsDeclarationForTsName;
tsDeclarationForTsName(node: ts.EntityName): DiagnosticResult<ts.Declaration>;
tsDeclarationForGqlDefinition(definition: ObjectTypeDefinitionNode | UnionTypeDefinitionNode | InputObjectTypeDefinitionNode | InterfaceTypeDefinitionNode): ts.Declaration;
getEntityName(name: NameNode): ts.EntityName | null;
}
export {};

@@ -13,2 +13,29 @@ "use strict";

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -18,3 +45,5 @@ exports.TypeContext = exports.UNRESOLVED_REFERENCE_NAME = void 0;

var DiagnosticError_1 = require("./utils/DiagnosticError");
var Result_1 = require("./utils/Result");
var E = require("./Errors");
var helpers_1 = require("./utils/helpers");
exports.UNRESOLVED_REFERENCE_NAME = "__UNRESOLVED_REFERENCE__";

@@ -34,31 +63,49 @@ /**

var TypeContext = /** @class */ (function () {
function TypeContext(checker, host) {
this._symbolToName = new Map();
this._unresolvedTypes = new Map();
function TypeContext(checker) {
this._declarationToName = new Map();
this._unresolvedNodes = new Map();
this._idToDeclaration = new Map();
this.checker = checker;
this.host = host;
}
// Record that a GraphQL construct of type `kind` with the name `name` is
// declared at `node`.
TypeContext.prototype.recordTypeName = function (node, name, kind) {
var symbol = this.checker.getSymbolAtLocation(node);
if (symbol == null) {
// FIXME: Make this a diagnostic
throw new Error("Could not resolve type reference. You probably have a TypeScript error.");
TypeContext.fromSnapshot = function (checker, snapshot) {
var e_1, _a, e_2, _b;
var self = new TypeContext(checker);
try {
for (var _c = __values(snapshot.unresolvedNames), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), node = _e[0], typeName = _e[1];
self._markUnresolvedType(node, typeName);
}
}
if (this._symbolToName.has(symbol)) {
// Ensure we never try to record the same name twice.
throw new Error("Unexpected double recording of typename.");
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
this._symbolToName.set(symbol, { name: name, kind: kind });
};
// Record that a type reference `node`
TypeContext.prototype.markUnresolvedType = function (node, name) {
var symbol = this.checker.getSymbolAtLocation(node);
if (symbol == null) {
//
throw new Error("Could not resolve type reference. You probably have a TypeScript error.");
try {
for (var _f = __values(snapshot.nameDefinitions), _g = _f.next(); !_g.done; _g = _f.next()) {
var _h = __read(_g.value, 2), node = _h[0], definition = _h[1];
self._recordTypeName(node, definition.name, definition.kind);
}
}
this._unresolvedTypes.set(name, this.resolveSymbol(symbol));
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
return self;
};
// Record that a GraphQL construct of type `kind` with the name `name` is
// declared at `node`.
TypeContext.prototype._recordTypeName = function (node, name, kind) {
this._idToDeclaration.set(name.tsIdentifier, node);
this._declarationToName.set(node, { name: name, kind: kind });
};
// Record that a type references `node`
TypeContext.prototype._markUnresolvedType = function (node, name) {
this._unresolvedNodes.set(name.tsIdentifier, node);
};
TypeContext.prototype.findSymbolDeclaration = function (startSymbol) {

@@ -84,44 +131,96 @@ var _a;

};
TypeContext.prototype.resolveNamedType = function (unresolved) {
var symbol = this._unresolvedTypes.get(unresolved);
if (symbol == null) {
if (unresolved.value === exports.UNRESOLVED_REFERENCE_NAME) {
// This is a logic error on our side.
throw new Error("Unexpected unresolved reference name.");
}
return (0, DiagnosticError_1.ok)(unresolved);
TypeContext.prototype.resolveUnresolvedNamedType = function (unresolved) {
if (unresolved.value !== exports.UNRESOLVED_REFERENCE_NAME) {
return (0, Result_1.ok)(unresolved);
}
var nameDefinition = this._symbolToName.get(symbol);
var typeReference = this.getEntityName(unresolved);
if (typeReference == null) {
throw new Error("Unexpected unresolved reference name.");
}
var declarationResult = this.tsDeclarationForTsName(typeReference);
if (declarationResult.kind === "ERROR") {
return (0, Result_1.err)(declarationResult.err);
}
if (ts.isTypeParameterDeclaration(declarationResult.value)) {
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), "Type parameters are not supported in this context."));
}
var nameDefinition = this._declarationToName.get(declarationResult.value);
if (nameDefinition == null) {
if (unresolved.loc == null) {
throw new Error("Expected namedType to have a location.");
}
return (0, DiagnosticError_1.err)((0, DiagnosticError_1.gqlErr)(unresolved.loc, E.unresolvedTypeReference()));
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), E.unresolvedTypeReference()));
}
return (0, DiagnosticError_1.ok)(__assign(__assign({}, unresolved), { value: nameDefinition.name.value }));
return (0, Result_1.ok)(__assign(__assign({}, unresolved), { value: nameDefinition.name.value }));
};
TypeContext.prototype.unresolvedNameIsGraphQL = function (unresolved) {
var symbol = this._unresolvedTypes.get(unresolved);
return symbol != null && this._symbolToName.has(symbol);
var referenceNode = this.getEntityName(unresolved);
if (referenceNode == null)
return false;
var declaration = this.maybeTsDeclarationForTsName(referenceNode);
if (declaration == null)
return false;
return this._declarationToName.has(declaration);
};
// TODO: Merge this with resolveNamedType
TypeContext.prototype.getNameDefinition = function (nameNode) {
var typeNameResult = this.resolveNamedType(nameNode);
if (typeNameResult.kind === "ERROR") {
return (0, DiagnosticError_1.err)([typeNameResult.err]);
TypeContext.prototype.gqlNameDefinitionForGqlName = function (nameNode) {
var referenceNode = this.getEntityName(nameNode);
if (referenceNode == null) {
throw new Error("Expected to find reference node for name node.");
}
var symbol = this._unresolvedTypes.get(nameNode);
if (symbol == null) {
// This should have already been handled by resolveNamedType
throw new Error("Expected to find unresolved type.");
var declaration = this.maybeTsDeclarationForTsName(referenceNode);
if (declaration == null) {
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(nameNode), E.unresolvedTypeReference()));
}
var nameDefinition = this._symbolToName.get(symbol);
if (nameDefinition == null) {
// This should have already been handled by resolveNamedType
var definition = this._declarationToName.get(declaration);
if (definition == null) {
throw new Error("Expected to find name definition.");
}
return (0, DiagnosticError_1.ok)(nameDefinition);
return (0, Result_1.ok)(definition);
};
// Note! This assumes you have already handled any type parameters.
TypeContext.prototype.gqlNameForTsName = function (node) {
var declarationResult = this.tsDeclarationForTsName(node);
if (declarationResult.kind === "ERROR") {
return (0, Result_1.err)(declarationResult.err);
}
if (ts.isTypeParameterDeclaration(declarationResult.value)) {
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, "Type parameter not valid", [
(0, DiagnosticError_1.tsErr)(declarationResult.value, "Defined here"),
]));
}
var nameDefinition = this._declarationToName.get(declarationResult.value);
if (nameDefinition == null) {
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.unresolvedTypeReference()));
}
return (0, Result_1.ok)(nameDefinition.name.value);
};
TypeContext.prototype.maybeTsDeclarationForTsName = function (node) {
var symbol = this.checker.getSymbolAtLocation(node);
if (symbol == null) {
return null;
}
return this.findSymbolDeclaration(symbol);
};
TypeContext.prototype.tsDeclarationForTsName = function (node) {
var declaration = this.maybeTsDeclarationForTsName(node);
if (!declaration) {
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.unresolvedTypeReference()));
}
return (0, Result_1.ok)(declaration);
};
TypeContext.prototype.tsDeclarationForGqlDefinition = function (definition) {
var name = definition.name;
var declaration = this._idToDeclaration.get(name.tsIdentifier);
if (!declaration) {
throw new Error("Could not find declaration for ".concat(name.value));
}
return declaration;
};
TypeContext.prototype.getEntityName = function (name) {
var _a;
var entityName = (_a = this._unresolvedNodes.get(name.tsIdentifier)) !== null && _a !== void 0 ? _a : null;
if (entityName == null && name.value === exports.UNRESOLVED_REFERENCE_NAME) {
throw new Error("Expected unresolved reference to have a node.");
}
return entityName;
};
return TypeContext;
}());
exports.TypeContext = TypeContext;
import { GraphQLError, Location, Source } from "graphql";
import * as ts from "typescript";
type Ok<T> = {
kind: "OK";
value: T;
};
type Err<E> = {
kind: "ERROR";
err: E;
};
export type Result<T, E> = Ok<T> | Err<E>;
export type DiagnosticResult<T> = Result<T, ts.Diagnostic>;
export type DiagnosticsResult<T> = Result<T, ts.Diagnostic[]>;
export declare function ok<T>(value: T): Ok<T>;
export declare function err<E>(err: E): Err<E>;
export declare function collectResults<T>(results: DiagnosticsResult<T>[]): DiagnosticsResult<T[]>;
export declare function combineResults<T, U>(result1: DiagnosticsResult<T>, result2: DiagnosticsResult<U>): DiagnosticsResult<[T, U]>;
import { Result } from "./Result";
export type DiagnosticResult<T> = Result<T, ts.DiagnosticWithLocation>;
export type DiagnosticsResult<T> = Result<T, ts.DiagnosticWithLocation[]>;
export type DiagnosticsWithoutLocationResult<T> = Result<T, ts.Diagnostic[]>;
export declare class ReportableDiagnostics {

@@ -28,7 +17,19 @@ _host: ts.FormatDiagnosticsHost;

export declare function graphQlErrorToDiagnostic(error: GraphQLError): ts.Diagnostic;
export declare function gqlErr(loc: Location, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.Diagnostic;
export declare function gqlErr(loc: Location, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function gqlRelated(loc: Location, message: string): ts.DiagnosticRelatedInformation;
export declare function tsErr(node: ts.Node, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.Diagnostic;
export declare function rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
/**
* A generic version of the methods on ts.Node that we need
* to create diagnostics.
*
* This interface allows us to create diagnostics from our
* own classes.
*/
export interface TsLocatableNode {
getStart(): number;
getEnd(): number;
getSourceFile(): ts.SourceFile;
}
export declare function tsErr(node: TsLocatableNode, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function tsRelated(node: ts.Node, message: string): ts.DiagnosticRelatedInformation;
export declare function graphqlSourceToSourceFile(source: Source): ts.SourceFile;
export {};
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {

@@ -29,63 +18,16 @@ var m = typeof Symbol === "function" && o[Symbol.iterator];

};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.graphqlSourceToSourceFile = exports.tsRelated = exports.tsErr = exports.gqlRelated = exports.gqlErr = exports.graphQlErrorToDiagnostic = exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = exports.combineResults = exports.collectResults = exports.err = exports.ok = void 0;
exports.graphqlSourceToSourceFile = exports.tsRelated = exports.tsErr = exports.rangeErr = exports.gqlRelated = exports.gqlErr = exports.graphQlErrorToDiagnostic = exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = void 0;
var ts = require("typescript");
function ok(value) {
return { kind: "OK", value: value };
}
exports.ok = ok;
function err(err) {
return { kind: "ERROR", err: err };
}
exports.err = err;
function collectResults(results) {
var e_1, _a;
var errors = [];
var values = [];
try {
for (var results_1 = __values(results), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
var result = results_1_1.value;
if (result.kind === "ERROR") {
errors.push.apply(errors, __spreadArray([], __read(result.err), false));
}
else {
values.push(result.value);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (results_1_1 && !results_1_1.done && (_a = results_1.return)) _a.call(results_1);
}
finally { if (e_1) throw e_1.error; }
}
if (errors.length > 0) {
return err(errors);
}
return ok(values);
}
exports.collectResults = collectResults;
function combineResults(result1, result2) {
if (result1.kind === "ERROR" && result2.kind === "ERROR") {
return err(__spreadArray(__spreadArray([], __read(result1.err), false), __read(result2.err), false));
}
if (result1.kind === "ERROR") {
return result1;
}
if (result2.kind === "ERROR") {
return result2;
}
return ok([result1.value, result2.value]);
}
exports.combineResults = combineResults;
var ReportableDiagnostics = /** @class */ (function () {

@@ -130,3 +72,3 @@ function ReportableDiagnostics(host, diagnostics) {

function graphQlErrorToDiagnostic(error) {
var e_2, _a;
var e_1, _a;
var position = error.positions[0];

@@ -158,3 +100,3 @@ if (position == null) {

}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {

@@ -164,3 +106,3 @@ try {

}
finally { if (e_2) throw e_2.error; }
finally { if (e_1) throw e_1.error; }
}

@@ -182,2 +124,3 @@ }

relatedInformation: relatedInformation,
source: "Grats",
};

@@ -195,2 +138,3 @@ }

relatedInformation: relatedInformation,
source: "Grats",
};

@@ -210,2 +154,17 @@ }

exports.gqlRelated = gqlRelated;
function rangeErr(file, commentRange, message, relatedInformation) {
var start = commentRange.pos;
var length = commentRange.end - commentRange.pos;
return {
messageText: message,
file: file,
code: exports.FAKE_ERROR_CODE,
category: ts.DiagnosticCategory.Error,
start: start,
length: length,
relatedInformation: relatedInformation,
source: "Grats",
};
}
exports.rangeErr = rangeErr;
function tsErr(node, message, relatedInformation) {

@@ -223,2 +182,3 @@ var start = node.getStart();

relatedInformation: relatedInformation,
source: "Grats",
};

@@ -225,0 +185,0 @@ }

@@ -0,1 +1,2 @@

import { Location } from "graphql";
export declare class DefaultMap<K, V> {

@@ -8,1 +9,9 @@ private readonly getDefault;

export declare function extend<T>(a: T[], b: readonly T[]): void;
export declare function loc(item: {
loc?: Location;
}): Location;
export declare function astNode<T>(item: {
astNode?: T | undefined | null;
}): T;
export declare function uniqueId(): number;
export declare function nullThrows<T>(value: T | null | undefined): T;

@@ -14,3 +14,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extend = exports.DefaultMap = void 0;
exports.nullThrows = exports.uniqueId = exports.astNode = exports.loc = exports.extend = exports.DefaultMap = void 0;
var DefaultMap = /** @class */ (function () {

@@ -49,1 +49,27 @@ function DefaultMap(getDefault) {

exports.extend = extend;
function loc(item) {
if (item.loc == null) {
throw new Error("Expected item to have loc");
}
return item.loc;
}
exports.loc = loc;
function astNode(item) {
if (item.astNode == null) {
throw new Error("Expected item to have astNode");
}
return item.astNode;
}
exports.astNode = astNode;
var i = 0;
function uniqueId() {
return i++;
}
exports.uniqueId = uniqueId;
function nullThrows(value) {
if (value == null) {
throw new Error("Grats Error. Expected value to be non-nullish. This error represents an error in Grats. Please report it.");
}
return value;
}
exports.nullThrows = nullThrows;
import { DocumentNode } from "graphql";
import { DiagnosticsResult } from "../utils/DiagnosticError";
/**
* Ensure that all fields on `Subscription` return an AsyncIterable, and that no other
* fields do.
* Ensure that all fields on `Subscription` return an AsyncIterable and transform
* the return type of subscription fields to not treat AsyncIterable as as list type.
*/
export declare function validateAsyncIterable(doc: DocumentNode): DiagnosticsResult<void>;
export declare function validateAsyncIterable(doc: DocumentNode): DiagnosticsResult<DocumentNode>;
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
return __assign.apply(this, arguments);
};

@@ -17,7 +17,8 @@ Object.defineProperty(exports, "__esModule", { value: true });

var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
var E = require("../Errors");
var metadataDirectives_1 = require("../metadataDirectives");
var helpers_1 = require("../utils/helpers");
/**
* Ensure that all fields on `Subscription` return an AsyncIterable, and that no other
* fields do.
* Ensure that all fields on `Subscription` return an AsyncIterable and transform
* the return type of subscription fields to not treat AsyncIterable as as list type.
*/

@@ -27,9 +28,28 @@ function validateAsyncIterable(doc) {

var errors = [];
var visitNode = function (t) {
var validateFieldsResult = validateField(t);
if (validateFieldsResult != null) {
errors.push(validateFieldsResult);
var visitNode = {
enter: function (t) {
// Note: We assume the default name is used here. When custom operation types are supported
// we'll need to update this.
if (t.name.value !== "Subscription") {
// Don't visit nodes that aren't the Subscription type.
return false;
}
},
};
var visitSubscriptionField = function (field) {
var inner = innerType(field.type); // Remove any non-null wrapper types
if (inner.kind !== graphql_1.Kind.LIST_TYPE || !inner.isAsyncIterable) {
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(field.type), E.subscriptionFieldNotAsyncIterable()));
return field;
}
var itemType = inner.type;
// If either field.type or item type is nullable, the field should be nullable
if (isNullable(field.type) || isNullable(itemType)) {
var innerInner = innerType(itemType);
return __assign(__assign({}, field), { type: innerInner });
}
// If _both_ are non-nullable, we will preserve the non-nullability.
return __assign(__assign({}, field), { type: itemType });
};
(0, graphql_1.visit)(doc, (_a = {},
var newDoc = (0, graphql_1.visit)(doc, (_a = {},
_a[graphql_1.Kind.INTERFACE_TYPE_DEFINITION] = visitNode,

@@ -39,45 +59,18 @@ _a[graphql_1.Kind.INTERFACE_TYPE_EXTENSION] = visitNode,

_a[graphql_1.Kind.OBJECT_TYPE_EXTENSION] = visitNode,
_a[graphql_1.Kind.FIELD_DEFINITION] = visitSubscriptionField,
_a));
if (errors.length > 0) {
return (0, DiagnosticError_1.err)(errors);
return (0, Result_1.err)(errors);
}
return (0, DiagnosticError_1.ok)(undefined);
return (0, Result_1.ok)(newDoc);
}
exports.validateAsyncIterable = validateAsyncIterable;
function validateField(t) {
var e_1, _a;
var _b;
if (t.fields == null)
return;
// Note: We assume the default name is used here. When custom operation types are supported
// we'll need to update this.
var isSubscription = t.name.value === "Subscription" &&
(t.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION ||
t.kind === graphql_1.Kind.OBJECT_TYPE_EXTENSION);
try {
for (var _c = __values(t.fields), _d = _c.next(); !_d.done; _d = _c.next()) {
var field = _d.value;
var asyncDirective = (_b = field.directives) === null || _b === void 0 ? void 0 : _b.find(function (directive) { return directive.name.value === metadataDirectives_1.ASYNC_ITERABLE_TYPE_DIRECTIVE; });
if (isSubscription && asyncDirective == null) {
if (field.type.loc == null) {
throw new Error("Expected field type to have a location.");
}
return (0, DiagnosticError_1.gqlErr)(field.type.loc, E.subscriptionFieldNotAsyncIterable());
}
if (!isSubscription && asyncDirective != null) {
if (asyncDirective.loc == null) {
throw new Error("Expected asyncDirective to have a location.");
}
return (0, DiagnosticError_1.gqlErr)(asyncDirective.loc, // Directive location is the AsyncIterable type.
E.nonSubscriptionFieldAsyncIterable());
}
}
function innerType(type) {
if (type.kind === graphql_1.Kind.NON_NULL_TYPE) {
return innerType(type.type);
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
return type;
}
function isNullable(t) {
return t.kind !== graphql_1.Kind.NON_NULL_TYPE;
}
import * as ts from "typescript";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
import { TypeContext } from "../TypeContext";

@@ -8,2 +8,2 @@ /**

*/
export declare function validateContextReferences(ctx: TypeContext, references: ts.Node[]): DiagnosticsResult<void>;
export declare function validateContextReferences(ctx: TypeContext, references: ts.Node[]): DiagnosticsWithoutLocationResult<void>;

@@ -17,2 +17,3 @@ "use strict";

var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
/**

@@ -30,3 +31,3 @@ * Ensure that all context type references resolve to the same

if (symbol == null) {
return (0, DiagnosticError_1.err)([
return (0, Result_1.err)([
(0, DiagnosticError_1.tsErr)(typeName, E.expectedTypeAnnotationOnContextToBeResolvable()),

@@ -37,3 +38,3 @@ ]);

if (declaration == null) {
return (0, DiagnosticError_1.err)([
return (0, Result_1.err)([
(0, DiagnosticError_1.tsErr)(typeName, E.expectedTypeAnnotationOnContextToHaveDeclaration()),

@@ -50,3 +51,3 @@ ]);

else if (gqlContext.declaration !== declaration) {
return (0, DiagnosticError_1.err)([
return (0, Result_1.err)([
(0, DiagnosticError_1.tsErr)(typeName, E.multipleContextTypes(), [

@@ -66,4 +67,4 @@ (0, DiagnosticError_1.tsRelated)(gqlContext.firstReference, "A different type reference was used here"),

}
return (0, DiagnosticError_1.ok)(undefined);
return (0, Result_1.ok)(undefined);
}
exports.validateContextReferences = validateContextReferences;
import * as ts from "typescript";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
/**

@@ -7,2 +7,2 @@ * Prevent using merged interfaces as GraphQL interfaces.

*/
export declare function validateMergedInterfaces(checker: ts.TypeChecker, interfaces: ts.InterfaceDeclaration[]): DiagnosticsResult<void>;
export declare function validateMergedInterfaces(checker: ts.TypeChecker, interfaces: ts.InterfaceDeclaration[]): DiagnosticsWithoutLocationResult<void>;

@@ -18,2 +18,3 @@ "use strict";

var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
/**

@@ -28,16 +29,24 @@ * Prevent using merged interfaces as GraphQL interfaces.

var symbol = checker.getSymbolAtLocation(node.name);
if (symbol != null &&
symbol.declarations != null &&
symbol.declarations.length > 1) {
var otherLocations = symbol.declarations
.filter(function (d) { return d !== node && ts.isInterfaceDeclaration(d); })
.map(function (d) {
var _a;
var locNode = (_a = ts.getNameOfDeclaration(d)) !== null && _a !== void 0 ? _a : d;
return (0, DiagnosticError_1.tsRelated)(locNode, "Other declaration");
});
if (otherLocations.length > 0) {
errors.push((0, DiagnosticError_1.tsErr)(node.name, E.mergedInterfaces(), otherLocations));
}
if (symbol == null) {
return "continue";
}
// @ts-ignore Exposed as public in https://github.com/microsoft/TypeScript/pull/56193
var mergedSymbol = checker.getMergedSymbol(symbol);
if (mergedSymbol.declarations == null ||
mergedSymbol.declarations.length < 2) {
return "continue";
}
var otherLocations = mergedSymbol.declarations
.filter(function (d) {
return d !== node &&
(ts.isInterfaceDeclaration(d) || ts.isClassDeclaration(d));
})
.map(function (d) {
var _a;
var locNode = (_a = ts.getNameOfDeclaration(d)) !== null && _a !== void 0 ? _a : d;
return (0, DiagnosticError_1.tsRelated)(locNode, "Other declaration");
});
if (otherLocations.length > 0) {
errors.push((0, DiagnosticError_1.tsErr)(node.name, E.mergedInterfaces(), otherLocations));
}
};

@@ -58,6 +67,6 @@ try {

if (errors.length > 0) {
return (0, DiagnosticError_1.err)(errors);
return (0, Result_1.err)(errors);
}
return (0, DiagnosticError_1.ok)(undefined);
return (0, Result_1.ok)(undefined);
}
exports.validateMergedInterfaces = validateMergedInterfaces;

@@ -1,3 +0,3 @@

import * as ts from "typescript";
import { GraphQLSchema } from "graphql";
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
/**

@@ -7,2 +7,2 @@ * Ensure that every type which implements an interface or is a member of a

*/
export declare function validateTypenames(schema: GraphQLSchema, hasTypename: Set<string>): ts.Diagnostic[];
export declare function validateTypenames(schema: GraphQLSchema, hasTypename: Set<string>): DiagnosticsWithoutLocationResult<GraphQLSchema>;

@@ -17,2 +17,5 @@ "use strict";

var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
var helpers_1 = require("../utils/helpers");
var E = require("../Errors");
/**

@@ -24,4 +27,3 @@ * Ensure that every type which implements an interface or is a member of a

var e_1, _a, e_2, _b;
var _c, _d;
var typenameDiagnostics = [];
var errors = [];
var abstractTypes = Object.values(schema.getTypeMap()).filter(graphql_1.isAbstractType);

@@ -36,9 +38,15 @@ try {

var implementor = typeImplementors_1_1.value;
if (!hasTypename.has(implementor.name)) {
var loc = (_d = (_c = implementor.astNode) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.loc;
if (loc == null) {
throw new Error("Grats expected the parsed type `".concat(implementor.name, "` to have location information. This is a bug in Grats. Please report it."));
}
typenameDiagnostics.push((0, DiagnosticError_1.gqlErr)(loc, "Missing __typename on `".concat(implementor.name, "`. The type `").concat(type.name, "` is used in a union or interface, so it must have a `__typename` field.")));
var ast = (0, helpers_1.nullThrows)(implementor.astNode);
// Synthesized type cannot guarantee that they have the correct __typename field, so we
// prevent their use in interfaces and unions.
if (ast.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION && ast.wasSynthesized) {
var message = type instanceof graphql_1.GraphQLInterfaceType
? E.genericTypeImplementsInterface()
: E.genericTypeUsedAsUnionMember();
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(ast.name), message));
}
else if (!hasTypename.has(implementor.name)) {
var err_1 = (0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(ast.name), E.concreteTypeMissingTypename(implementor.name));
errors.push(err_1);
}
}

@@ -62,4 +70,7 @@ }

}
return typenameDiagnostics;
if (errors.length > 0) {
return (0, Result_1.err)(errors);
}
return (0, Result_1.ok)(schema);
}
exports.validateTypenames = validateTypenames;
{
"name": "grats",
"version": "0.0.0-main-8e63ea66",
"version": "0.0.0-main-957a70fd",
"main": "dist/src/index.js",

@@ -9,3 +9,4 @@ "bin": "dist/src/cli.js",

"files": [
"dist"
"dist",
"!dist/src/tests"
],

@@ -20,2 +21,3 @@ "dependencies": {

"@types/node": "^18.14.6",
"@types/semver": "^7.5.6",
"@typescript-eslint/eslint-plugin": "^5.55.0",

@@ -29,2 +31,3 @@ "@typescript-eslint/parser": "^5.55.0",

"process": "^0.11.10",
"semver": "^7.5.4",
"ts-node": "^10.9.1"

@@ -40,9 +43,29 @@ },

},
"bugs": {
"url": "https://github.com/captbaritone/grats/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/captbaritone/grats.git"
},
"author": {
"name": "Jordan Eldredge",
"email": "jordan@jordaneldredge.com",
"url": "https://jordaneldredge.com"
},
"keywords": [
"graphql",
"typescript",
"resolvers",
"schema",
"code-first",
"implementation-first"
],
"scripts": {
"test": "ts-node src/tests/test.ts",
"integration-tests": "node src/tests/integration.mjs",
"build": "tsc --build",
"build": "rm -rf dist/ && tsc --build",
"format": "prettier . --write",
"lint": "eslint src/**/*.ts && prettier . --check"
"lint": "eslint . && prettier . --check"
}
}

@@ -5,3 +5,3 @@ # Grats: Implementation-First GraphQL for TypeScript

_Beta Software: Grats is largely stable and being used in production in multiple places. If you encounter any issues, dont hesitate to let us know._
_Beta Software: Grats is largely stable and being used in production in multiple places. If you encounter any issues, don't hesitate to let us know._

@@ -36,3 +36,3 @@ **What if building a GraphQL server were as simple as just writing functions?**

After running `npx grats`, you'll find a `schema.ts` module that exports an executable schema, and a `schema.graphql` file contins your GraphQL schema definition:
After running `npx grats`, you'll find a `schema.ts` module that exports an executable schema, and a `schema.graphql` file contains your GraphQL schema definition:

@@ -46,3 +46,3 @@ ```graphql

That's just the begining! To learn more, **Read the docs: https://grats.capt.dev/**
That's just the beginning! To learn more, **Read the docs: https://grats.capt.dev/**

@@ -58,3 +58,3 @@ ## Contributing

- [@bradzacher](https://github.com/bradzacher) for tips on how to handle TypeScript ASTs.
- Everyone who worked on Meta's Hack GraphQL server, the developer experince of which inspired this project.
- Everyone who worked on Meta's Hack GraphQL server, the developer experience of which inspired this project.
- A number of other projects which seem to have explored similar ideas in the past:

@@ -64,1 +64,5 @@ - [ts2gql](https://github.com/convoyinc/ts2gql)

- [typegraphql-reflection-poc](https://github.com/MichalLytek/typegraphql-reflection-poc)
## License
Grats is [MIT licensed](./LICENSE).

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc