Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

grats

Package Overview
Dependencies
Maintainers
0
Versions
238
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-a7f15f89 to 0.0.0-main-a8ec3e2a

dist/src/CodeActions.d.ts

8

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

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

"commander": "^10.0.0",
"graphql": "^16.6.0",
"typescript": "^5.0.2"
"graphql": "^16.9.0",
"typescript": "5.5.4"
},

@@ -46,3 +46,3 @@ "devDependencies": {

"node": ">=16 <=21",
"pnpm": "^8"
"pnpm": ">=8 <=9"
},

@@ -49,0 +49,0 @@ "bugs": {

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.formatLoc = void 0;
exports.formatLoc = formatLoc;
var _1 = require("./");

@@ -59,16 +59,14 @@ var lib_1 = require("./lib");

.option("--watch", "Watch for changes and rebuild schema files as needed")
.action(function (_a) {
var tsconfig = _a.tsconfig, watch = _a.watch;
return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_b) {
if (watch) {
startWatchMode(tsconfig);
}
else {
runBuild(tsconfig);
}
return [2 /*return*/];
});
.action(function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
var tsconfig = _b.tsconfig, watch = _b.watch;
return __generator(this, function (_c) {
if (watch) {
startWatchMode(tsconfig);
}
else {
runBuild(tsconfig);
}
return [2 /*return*/];
});
});
}); });
program

@@ -129,9 +127,9 @@ .command("locate")

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)(schema, gratsOptions, dest);
var gratsConfig = config.raw.grats;
var dest = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsConfig.tsSchema);
var code = (0, printSchema_1.printExecutableSchema)(schema, gratsConfig, dest);
(0, fs_1.writeFileSync)(dest, code);
console.error("Grats: Wrote TypeScript schema to `".concat(dest, "`."));
var schemaStr = (0, printSchema_1.printGratsSDL)(doc, gratsOptions);
var absOutput = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsOptions.graphqlSchema);
var schemaStr = (0, printSchema_1.printGratsSDL)(doc, gratsConfig);
var absOutput = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsConfig.graphqlSchema);
(0, fs_1.writeFileSync)(absOutput, schemaStr);

@@ -165,2 +163,1 @@ console.error("Grats: Wrote schema to `".concat(absOutput, "`."));

}
exports.formatLoc = formatLoc;
import { GraphQLSchema } from "graphql";
export declare function codegen(schema: GraphQLSchema, destination: string): string;
import { GratsConfig } from "./gratsConfig.js";
export declare function codegen(schema: GraphQLSchema, config: GratsConfig, destination: string): string;

@@ -38,4 +38,15 @@ "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 });
exports.codegen = void 0;
exports.codegen = codegen;
var graphql_1 = require("graphql");

@@ -49,2 +60,3 @@ var ts = require("typescript");

var helpers_1 = require("./utils/helpers");
var naturalCompare_1 = require("./utils/naturalCompare");
var RESOLVER_ARGS = ["source", "args", "context", "info"];

@@ -54,11 +66,14 @@ var F = ts.factory;

// GraphQLSchema implementing that schema.
function codegen(schema, destination) {
var codegen = new Codegen(schema, destination);
function codegen(schema, config, destination) {
var codegen = new Codegen(schema, config, destination);
codegen.schemaDeclarationExport();
return codegen.print();
}
exports.codegen = codegen;
var Codegen = /** @class */ (function () {
function Codegen(schema, destination) {
function Codegen(_schema, _config, _destination) {
this._schema = _schema;
this._config = _config;
this._destination = _destination;
this._imports = [];
this._typeNameMappings = new Map();
this._helpers = new Map();

@@ -68,4 +83,2 @@ this._typeDefinitions = new Set();

this._statements = [];
this._schema = schema;
this._destination = destination;
}

@@ -167,41 +180,71 @@ Codegen.prototype.createBlockWithScope = function (closure) {

};
Codegen.prototype.importUserConstruct = function (tsModulePath, exportName, localName) {
var abs = (0, gratsRoot_1.resolveRelativePath)(tsModulePath);
var relative = replaceExt(path.relative(path.dirname(this._destination), abs), this._config.importModuleSpecifierEnding);
var modulePath = "./".concat(normalizeRelativePathToPosix(relative));
if (exportName == null) {
this.importDefault(modulePath, localName);
}
else {
this.import(modulePath, [{ name: exportName, as: localName }]);
}
};
Codegen.prototype.resolveMethod = function (field, methodName, parentTypeName) {
var _this = this;
var metadataDirective = fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE);
if (metadataDirective == null) {
throw new Error("Expected to find metadata directive.");
}
var _a, _b;
var metadataDirective = (0, helpers_1.nullThrows)(fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE));
var metadata = (0, metadataDirectives_1.parseFieldMetadataDirective)(metadataDirective);
var fieldAst = (0, helpers_1.nullThrows)(field.astNode);
var resolverParams = (_a = fieldAst.resolverParams) === null || _a === void 0 ? void 0 : _a.map(function (param) {
switch (param.kind) {
case "named":
case "positionalArg":
return param;
case "unresolved":
throw new Error("Expected resolver param to have been resolved.");
default: {
var _exhaustive = param;
throw new Error("Unexpected param kind");
}
}
});
if (metadata.tsModulePath != null) {
var module_1 = metadata.tsModulePath;
var funcName = metadata.name;
if (funcName == null) {
throw new Error("Expected to find name in metadata directive.");
// 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);
this.importUserConstruct(metadata.tsModulePath, metadata.exportName, resolverName);
var resolverAccess = F.createIdentifier(resolverName);
if (metadata.name != null) {
resolverAccess = F.createPropertyAccessExpression(resolverAccess, F.createIdentifier(metadata.name));
}
var argCount = metadata.argCount;
if (argCount == null) {
throw new Error("Expected to find argCount in metadata directive.");
}
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 = RESOLVER_ARGS.slice(0, argCount);
return this.method(methodName, usedArgs.map(function (name) {
// Params expected by the user-defined resolver function.
var usedResolverParams = resolverParams !== null && resolverParams !== void 0 ? resolverParams : [];
// Params passed to the default resolver function.
var wrapperParams = extractUsedParams(usedResolverParams);
return this.method(methodName, wrapperParams.map(function (name) {
return _this.param(name);
}), [
F.createReturnStatement(F.createCallExpression(F.createIdentifier(resolverName), undefined, usedArgs.map(function (name) {
return F.createIdentifier(name);
F.createReturnStatement(F.createCallExpression(resolverAccess, undefined, usedResolverParams.map(function (name) {
return _this.resolverParam(name);
}))),
]);
}
if (metadata.name != null) {
var prop = F.createPropertyAccessExpression(F.createIdentifier("source"), F.createIdentifier(metadata.name));
var defaultParams = resolverParams == null || paramsAreInDefaultOrder(resolverParams);
if (metadata.name != null || !defaultParams) {
var prop = F.createPropertyAccessExpression(F.createIdentifier("source"), F.createIdentifier((_b = metadata.name) !== null && _b !== void 0 ? _b : field.name));
var valueExpression = prop;
if (metadata.argCount != null) {
valueExpression = F.createCallExpression(prop, undefined, RESOLVER_ARGS.map(function (name) {
return F.createIdentifier(name);
if (resolverParams != null) {
valueExpression = F.createCallExpression(prop, undefined, resolverParams.map(function (name) {
return _this.resolverParam(name);
}));
}
return this.method(methodName, RESOLVER_ARGS.map(function (name) { return _this.param(name); }), [F.createReturnStatement(valueExpression)]);
var usedWrapperParams = [
{ kind: "named", name: "source" },
];
if (resolverParams != null) {
// Push with ... is safe because resolverParams is known to be
// a small array.
usedWrapperParams.push.apply(usedWrapperParams, __spreadArray([], __read(resolverParams), false));
}
return this.method(methodName, extractUsedParams(usedWrapperParams).map(function (name) { return _this.param(name); }), [F.createReturnStatement(valueExpression)]);
}

@@ -212,2 +255,16 @@ // If the resolver name matches the field name, and the field is not backed by a function,

};
// Either `args`, `context`, `info`, or a positional argument like
// `args.someArg`.
Codegen.prototype.resolverParam = function (param) {
switch (param.kind) {
case "named":
return F.createIdentifier(param.name);
case "positionalArg":
return F.createPropertyAccessExpression(F.createIdentifier("args"), F.createIdentifier(param.inputDefinition.name.value));
default: {
var _exhaustive = param;
throw new Error("Unexpected param kind");
}
}
};
// If a field is smantically non-null, we need to wrap the resolver in a

@@ -232,8 +289,5 @@ // runtime check to ensure that the resolver does not return null.

if (ts.isReturnStatement(statement)) {
if (statement.expression == null) {
throw new Error("Expected return statement to have an expression");
}
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), [], [statement.expression]));
return F.createReturnStatement(F.createCallExpression(F.createIdentifier(codegenHelpers_1.ASSERT_NON_NULL_HELPER), [], [(0, helpers_1.nullThrows)(statement.expression)]));
}

@@ -282,2 +336,3 @@ return statement;

Codegen.prototype.interfaceTypeConfig = function (obj) {
this._schema.getPossibleTypes(obj);
return this.objectLiteral([

@@ -288,2 +343,3 @@ this.description(obj.description),

this.interfaces(obj),
this.resolveType(obj),
]);

@@ -302,2 +358,36 @@ };

};
Codegen.prototype.resolveType = function (obj) {
var e_1, _a;
var needsResolveType = false;
try {
for (var _b = __values(this._schema.getPossibleTypes(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
var t = _c.value;
var ast = (0, helpers_1.nullThrows)(t.astNode);
if (ast.hasTypeNameField) {
continue;
}
var exportedMetadata = ast.exported;
if (exportedMetadata != null) {
if (!this._typeNameMappings.has(t.name)) {
var localName = "".concat(t.name, "Class");
this.importUserConstruct(exportedMetadata.tsModulePath, exportedMetadata.exportName, localName);
this._typeNameMappings.set(t.name, localName);
}
needsResolveType = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
if (needsResolveType) {
return F.createShorthandPropertyAssignment("resolveType");
}
// Just use the default resolveType
return null;
};
Codegen.prototype.unionTypeConfig = function (obj) {

@@ -311,2 +401,3 @@ var _this = this;

]),
this.resolveType(obj),
]);

@@ -343,7 +434,11 @@ };

Codegen.prototype.inputTypeConfig = function (obj) {
return this.objectLiteral([
var properties = [
this.description(obj.description),
F.createPropertyAssignment("name", F.createStringLiteral(obj.name)),
this.inputFields(obj),
]);
];
if (obj.isOneOf) {
properties.push(F.createPropertyAssignment("isOneOf", F.createTrue()));
}
return this.objectLiteral(properties);
};

@@ -382,8 +477,5 @@ Codegen.prototype.inputFields = function (obj) {

Codegen.prototype.fieldMethods = function (field, parentTypeName) {
var metadataDirective = fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE);
if (metadataDirective == null) {
throw new Error("Expected to find metadata directive.");
}
var metadata = (0, metadataDirectives_1.parseFieldMetadataDirective)(metadataDirective);
if (!metadata.asyncIterable) {
// 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);

@@ -554,6 +646,59 @@ return [this.maybeApplySemanticNullRuntimeCheck(field, resolve)];

};
Codegen.prototype.importDefault = function (from, as) {
this._imports.push(F.createImportDeclaration(undefined, F.createImportClause(false, F.createIdentifier(as), undefined), F.createStringLiteral(from)));
};
Codegen.prototype.resolveTypeFunctionDeclaration = function () {
return F.createFunctionDeclaration(undefined, undefined, "resolveType", undefined, [
F.createParameterDeclaration(undefined, undefined, "obj", undefined, F.createTypeReferenceNode("any")),
], F.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), F.createBlock([
F.createIfStatement(F.createBinaryExpression(F.createTypeOfExpression(F.createPropertyAccessExpression(F.createIdentifier("obj"), F.createIdentifier("__typename"))), ts.SyntaxKind.EqualsEqualsEqualsToken, F.createStringLiteral("string")), F.createBlock([
F.createReturnStatement(F.createPropertyAccessExpression(F.createIdentifier("obj"), F.createIdentifier("__typename"))),
], true)),
F.createVariableStatement(undefined, F.createVariableDeclarationList([
F.createVariableDeclaration(F.createIdentifier("prototype"), undefined, undefined, F.createCallExpression(F.createPropertyAccessExpression(F.createIdentifier("Object"), F.createIdentifier("getPrototypeOf")), undefined, [F.createIdentifier("obj")])),
], ts.NodeFlags.Let)),
F.createWhileStatement(F.createIdentifier("prototype"), F.createBlock([
F.createVariableStatement(undefined, F.createVariableDeclarationList([
F.createVariableDeclaration(F.createIdentifier("name"), undefined, undefined, F.createCallExpression(F.createPropertyAccessExpression(F.createIdentifier("typeNameMap"), F.createIdentifier("get")), undefined, [
F.createPropertyAccessExpression(F.createIdentifier("prototype"), F.createIdentifier("constructor")),
])),
], ts.NodeFlags.Const)),
F.createIfStatement(F.createBinaryExpression(F.createIdentifier("name"), ts.SyntaxKind.ExclamationEqualsToken, F.createNull()), F.createBlock([F.createReturnStatement(F.createIdentifier("name"))], true)),
F.createExpressionStatement(F.createAssignment(F.createIdentifier("prototype"), F.createCallExpression(F.createPropertyAccessExpression(F.createIdentifier("Object"), F.createIdentifier("getPrototypeOf")), undefined, [F.createIdentifier("prototype")]))),
], true)),
F.createThrowStatement(F.createNewExpression(F.createIdentifier("Error"), undefined, [
F.createStringLiteral("Cannot find type name."),
])),
], true));
};
Codegen.prototype.print = function () {
var e_2, _a;
var printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
var sourceFile = ts.createSourceFile("tempFile.ts", "", ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
this.import("graphql", __spreadArray([], __read(this._graphQLImports), false).map(function (name) { return ({ name: name }); }));
if (this._typeNameMappings.size > 0) {
this._statements.push(F.createVariableStatement(undefined, F.createVariableDeclarationList([
F.createVariableDeclaration(F.createIdentifier("typeNameMap"), undefined, undefined, F.createNewExpression(F.createIdentifier("Map"), undefined, [])),
], ts.NodeFlags.Const)));
var typeNameEntries = Array.from(this._typeNameMappings.entries());
typeNameEntries.sort(function (_a, _b) {
var _c = __read(_a, 1), aTypeName = _c[0];
var _d = __read(_b, 1), bTypeName = _d[0];
return (0, naturalCompare_1.naturalCompare)(aTypeName, bTypeName);
});
try {
for (var typeNameEntries_1 = __values(typeNameEntries), typeNameEntries_1_1 = typeNameEntries_1.next(); !typeNameEntries_1_1.done; typeNameEntries_1_1 = typeNameEntries_1.next()) {
var _b = __read(typeNameEntries_1_1.value, 2), typeName = _b[0], className = _b[1];
this._statements.push(F.createExpressionStatement(F.createCallExpression(F.createPropertyAccessExpression(F.createIdentifier("typeNameMap"), F.createIdentifier("set")), undefined, [F.createIdentifier(className), F.createStringLiteral(typeName)])));
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (typeNameEntries_1_1 && !typeNameEntries_1_1.done && (_a = typeNameEntries_1.return)) _a.call(typeNameEntries_1);
}
finally { if (e_2) throw e_2.error; }
}
this._statements.push(this.resolveTypeFunctionDeclaration());
}
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);

@@ -563,2 +708,33 @@ };

}());
// Here we try to avoid including unused args.
//
// Unused trailing args are trimmed, unused intermediate args are prefixed with
// an underscore.
function extractUsedParams(resolverParams) {
var wrapperArgs = [];
var adding = false;
var _loop_1 = function (i) {
var name = RESOLVER_ARGS[i];
var used = resolverParams.some(function (param) {
return ((param.kind === "named" && param.name === name) ||
(param.kind === "positionalArg" && name) === "args");
});
if (used) {
adding = true;
}
if (!adding) {
return "continue";
}
wrapperArgs.unshift(used ? name : "_".concat(name));
};
for (var i = RESOLVER_ARGS.length - 1; i >= 0; i--) {
_loop_1(i);
}
return wrapperArgs;
}
function paramsAreInDefaultOrder(params) {
return params.every(function (param, i) {
return param.kind === "named" && param.name === RESOLVER_ARGS[i + 1];
});
}
function fieldDirective(field, name) {

@@ -568,5 +744,5 @@ var _a, _b, _c;

}
function stripExt(filePath) {
function replaceExt(filePath, newSuffix) {
var ext = path.extname(filePath);
return filePath.slice(0, -ext.length);
return filePath.slice(0, -ext.length) + newSuffix;
}

@@ -583,1 +759,5 @@ // Predicate function for filtering out null values

}
// https://github.com/sindresorhus/slash/blob/98b618f5a3bfcb5dd374b204868818845b87bb2f/index.js#L8C9-L8C33
function normalizeRelativePathToPosix(unknownPath) {
return unknownPath.replace(/\\/g, "/");
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAssertNonNullHelper = exports.ASSERT_NON_NULL_HELPER = void 0;
exports.ASSERT_NON_NULL_HELPER = void 0;
exports.createAssertNonNullHelper = createAssertNonNullHelper;
var ts = require("typescript");

@@ -34,2 +35,1 @@ exports.ASSERT_NON_NULL_HELPER = "assertNonNull";

}
exports.createAssertNonNullHelper = createAssertNonNullHelper;

@@ -30,6 +30,8 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.forEachComment = exports.detectInvalidComments = void 0;
exports.detectInvalidComments = detectInvalidComments;
exports.forEachComment = forEachComment;
var ts = require("typescript");
var DiagnosticError_1 = require("./utils/DiagnosticError");
var E = require("./Errors");
var Act = require("./CodeActions");
var Extractor_1 = require("./Extractor");

@@ -62,7 +64,15 @@ // A line that starts with optional *s followed by @gql or @killsParentOnException

if (isLine) {
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInLineComment()));
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInLineComment(), [], {
fixName: "convert-line-comment-to-docblock-comment",
description: "Convert to a docblock comment",
changes: [Act.convertLineCommentToDocblock(sourceFile, comment)],
}));
}
else {
if (textSlice[0] !== "*") {
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInNonJSDocBlockComment()));
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInNonJSDocBlockComment(), [], {
fixName: "convert-block-comment-to-docblock-comment",
description: "Convert to a docblock comment",
changes: [Act.convertBlockCommentToDocblock(sourceFile, comment)],
}));
}

@@ -85,3 +95,2 @@ else {

}
exports.detectInvalidComments = detectInvalidComments;
// Extract @gql or @killsParentOnException tags from a JSDoc block comment.

@@ -149,3 +158,2 @@ // along with their positions.

}
exports.forEachComment = forEachComment;
function forEachToken(sourceFile, callback) {

@@ -152,0 +160,0 @@ var queue = [];

@@ -27,6 +27,7 @@ export declare const ISSUE_URL = "https://github.com/captbaritone/grats/issues";

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;

@@ -41,3 +42,7 @@ export declare function inputTypeNotLiteral(): string;

export declare function typeNameMissingInitializer(): string;
export declare function typeNameInitializeNotString(): string;
export declare function typeNameInitializeNotString(expectedName: string): string;
export declare function typeNameInitializeNotExpression(expectedName: string): string;
export declare function typeNameTypeNotReferenceNode(expectedName: string): string;
export declare function typeNameTypeNameNotIdentifier(expectedName: string): string;
export declare function typeNameTypeNameNotConst(expectedName: string): string;
export declare function typeNameInitializerWrong(expected: string, actual: string): string;

@@ -47,4 +52,4 @@ export declare function typeNameMissingTypeAnnotation(expected: string): string;

export declare function typeNameDoesNotMatchExpected(expected: string): string;
export declare function argumentParamIsMissingType(): string;
export declare function argumentParamIsNotObject(): string;
export declare function resolverParamIsMissingType(): string;
export declare function multipleResolverTypeLiterals(): string;
export declare function argIsNotProperty(): string;

@@ -59,2 +64,3 @@ export declare function argNameNotLiteral(): string;

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

@@ -90,3 +96,6 @@ export declare function propertyFieldMissingType(): string;

export declare function expectedTypeAnnotationOnContextToHaveDeclaration(): string;
export declare function unexpectedParamSpreadForContextParam(): string;
export declare function unexpectedParamSpreadForResolverParam(): string;
export declare function resolverParamIsUnknown(): string;
export declare function resolverParamIsNever(): string;
export declare function unexpectedResolverParamType(): string;
export declare function multipleContextTypes(): string;

@@ -96,3 +105,2 @@ export declare function graphQLNameHasLeadingNewlines(name: string, tagName: string): string;

export declare function subscriptionFieldNotAsyncIterable(): string;
export declare function nonSubscriptionFieldAsyncIterable(): string;
export declare function operationTypeNotUnknown(): string;

@@ -103,1 +111,30 @@ export declare function expectedNullableArgumentToBeOptional(): 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 concreteTypenameImplementingInterfaceCannotBeResolved(implementor: string, interfaceName: string): string;
export declare function concreteTypenameInUnionCannotBeResolved(implementor: string, unionName: string): string;
export declare function invalidFieldNonPublicAccessModifier(): string;
export declare function invalidStaticModifier(): string;
export declare function staticMethodOnNonClass(): string;
export declare function staticMethodClassWithNamedExportNotNamed(): string;
export declare function oneOfNotSupportedGraphql(requiredVersion: string, foundVersion: string): string;
export declare function oneOfNotOnUnion(): string;
export declare function oneOfFieldNotTypeLiteralWithOneProperty(): string;
export declare function oneOfPropertyMissingTypeAnnotation(): string;
export declare function contextTagOnNonDeclaration(): string;
export declare function duplicateContextTag(): string;
export declare function userDefinedInfoTag(): string;
export declare function invalidResolverParamType(): string;
export declare function exportedArrowFunctionNotConst(): string;
export declare function exportedFieldVariableMultipleDeclarations(n: number): string;
export declare function fieldVariableNotTopLevelExported(): string;
export declare function fieldVariableIsNotArrowFunction(): string;
export declare function positionalResolverArgDoesNotHaveName(): string;
export declare function positionalArgAndArgsObject(): string;
export declare function contextOrInfoUsedInGraphQLPosition(kind: "CONTEXT" | "INFO"): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultValueIsNotLiteral = exports.ambiguousNumberType = exports.expectedOneNonNullishType = exports.propertyFieldMissingType = exports.cannotResolveSymbolForDescription = 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.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 = exports.ISSUE_URL = void 0;
exports.gqlTagInDetachedJSDocBlockComment = exports.gqlTagInNonJSDocBlockComment = exports.gqlTagInLineComment = 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.mergedInterfaces = exports.nonNullTypeCannotBeOptional = exports.killsParentOnExceptionOnNullable = exports.killsParentOnExceptionWithWrongConfig = exports.expectedNameIdentifier = exports.pluralTypeMissingParameter = exports.unknownGraphQLType = exports.unsupportedTypeLiteral = exports.defaultArgPropertyMissingInitializer = exports.defaultArgPropertyMissingName = exports.defaultArgElementIsNotAssignment = void 0;
exports.ISSUE_URL = void 0;
exports.fieldTagOnWrongNode = fieldTagOnWrongNode;
exports.killsParentOnExceptionOnWrongNode = killsParentOnExceptionOnWrongNode;
exports.wrongCasingForGratsTag = wrongCasingForGratsTag;
exports.invalidGratsTag = invalidGratsTag;
exports.invalidTypeTagUsage = invalidTypeTagUsage;
exports.invalidScalarTagUsage = invalidScalarTagUsage;
exports.invalidInterfaceTagUsage = invalidInterfaceTagUsage;
exports.invalidEnumTagUsage = invalidEnumTagUsage;
exports.invalidInputTagUsage = invalidInputTagUsage;
exports.invalidUnionTagUsage = invalidUnionTagUsage;
exports.expectedUnionTypeNode = expectedUnionTypeNode;
exports.expectedUnionTypeReference = expectedUnionTypeReference;
exports.invalidParentArgForFunctionField = invalidParentArgForFunctionField;
exports.invalidReturnTypeForFunctionField = invalidReturnTypeForFunctionField;
exports.functionFieldNotTopLevel = functionFieldNotTopLevel;
exports.staticMethodClassNotTopLevel = staticMethodClassNotTopLevel;
exports.staticMethodFieldClassNotExported = staticMethodFieldClassNotExported;
exports.functionFieldParentTypeMissing = functionFieldParentTypeMissing;
exports.functionFieldParentTypeNotValid = functionFieldParentTypeNotValid;
exports.functionFieldNotNamed = functionFieldNotNamed;
exports.functionFieldNotNamedExport = functionFieldNotNamedExport;
exports.inputTypeNotLiteral = inputTypeNotLiteral;
exports.inputTypeFieldNotProperty = inputTypeFieldNotProperty;
exports.inputInterfaceFieldNotProperty = inputInterfaceFieldNotProperty;
exports.inputFieldUntyped = inputFieldUntyped;
exports.typeTagOnUnnamedClass = typeTagOnUnnamedClass;
exports.typeTagOnAliasOfNonObjectOrUnknown = typeTagOnAliasOfNonObjectOrUnknown;
exports.typeNameNotDeclaration = typeNameNotDeclaration;
exports.typeNameMissingInitializer = typeNameMissingInitializer;
exports.typeNameInitializeNotString = typeNameInitializeNotString;
exports.typeNameInitializeNotExpression = typeNameInitializeNotExpression;
exports.typeNameTypeNotReferenceNode = typeNameTypeNotReferenceNode;
exports.typeNameTypeNameNotIdentifier = typeNameTypeNameNotIdentifier;
exports.typeNameTypeNameNotConst = typeNameTypeNameNotConst;
exports.typeNameInitializerWrong = typeNameInitializerWrong;
exports.typeNameMissingTypeAnnotation = typeNameMissingTypeAnnotation;
exports.typeNameTypeNotStringLiteral = typeNameTypeNotStringLiteral;
exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected;
exports.resolverParamIsMissingType = resolverParamIsMissingType;
exports.multipleResolverTypeLiterals = multipleResolverTypeLiterals;
exports.argIsNotProperty = argIsNotProperty;
exports.argNameNotLiteral = argNameNotLiteral;
exports.argNotTyped = argNotTyped;
exports.enumTagOnInvalidNode = enumTagOnInvalidNode;
exports.enumVariantNotStringLiteral = enumVariantNotStringLiteral;
exports.enumVariantMissingInitializer = enumVariantMissingInitializer;
exports.gqlEntityMissingName = gqlEntityMissingName;
exports.methodMissingType = methodMissingType;
exports.wrapperMissingTypeArg = wrapperMissingTypeArg;
exports.invalidWrapperOnInputType = invalidWrapperOnInputType;
exports.cannotResolveSymbolForDescription = cannotResolveSymbolForDescription;
exports.propertyFieldMissingType = propertyFieldMissingType;
exports.expectedOneNonNullishType = expectedOneNonNullishType;
exports.ambiguousNumberType = ambiguousNumberType;
exports.defaultValueIsNotLiteral = defaultValueIsNotLiteral;
exports.defaultArgElementIsNotAssignment = defaultArgElementIsNotAssignment;
exports.defaultArgPropertyMissingName = defaultArgPropertyMissingName;
exports.defaultArgPropertyMissingInitializer = defaultArgPropertyMissingInitializer;
exports.unsupportedTypeLiteral = unsupportedTypeLiteral;
exports.unknownGraphQLType = unknownGraphQLType;
exports.pluralTypeMissingParameter = pluralTypeMissingParameter;
exports.expectedNameIdentifier = expectedNameIdentifier;
exports.killsParentOnExceptionWithWrongConfig = killsParentOnExceptionWithWrongConfig;
exports.killsParentOnExceptionOnNullable = killsParentOnExceptionOnNullable;
exports.nonNullTypeCannotBeOptional = nonNullTypeCannotBeOptional;
exports.mergedInterfaces = mergedInterfaces;
exports.implementsTagOnClass = implementsTagOnClass;
exports.implementsTagOnInterface = implementsTagOnInterface;
exports.implementsTagOnTypeAlias = implementsTagOnTypeAlias;
exports.duplicateTag = duplicateTag;
exports.duplicateInterfaceTag = duplicateInterfaceTag;
exports.parameterWithoutModifiers = parameterWithoutModifiers;
exports.parameterPropertyNotPublic = parameterPropertyNotPublic;
exports.parameterPropertyMissingType = parameterPropertyMissingType;
exports.invalidTypePassedToFieldFunction = invalidTypePassedToFieldFunction;
exports.unresolvedTypeReference = unresolvedTypeReference;
exports.expectedTypeAnnotationOnContext = expectedTypeAnnotationOnContext;
exports.expectedTypeAnnotationOfReferenceOnContext = expectedTypeAnnotationOfReferenceOnContext;
exports.expectedTypeAnnotationOnContextToBeResolvable = expectedTypeAnnotationOnContextToBeResolvable;
exports.expectedTypeAnnotationOnContextToHaveDeclaration = expectedTypeAnnotationOnContextToHaveDeclaration;
exports.unexpectedParamSpreadForResolverParam = unexpectedParamSpreadForResolverParam;
exports.resolverParamIsUnknown = resolverParamIsUnknown;
exports.resolverParamIsNever = resolverParamIsNever;
exports.unexpectedResolverParamType = unexpectedResolverParamType;
exports.multipleContextTypes = multipleContextTypes;
exports.graphQLNameHasLeadingNewlines = graphQLNameHasLeadingNewlines;
exports.graphQLTagNameHasWhitespace = graphQLTagNameHasWhitespace;
exports.subscriptionFieldNotAsyncIterable = subscriptionFieldNotAsyncIterable;
exports.operationTypeNotUnknown = operationTypeNotUnknown;
exports.expectedNullableArgumentToBeOptional = expectedNullableArgumentToBeOptional;
exports.gqlTagInLineComment = gqlTagInLineComment;
exports.gqlTagInNonJSDocBlockComment = gqlTagInNonJSDocBlockComment;
exports.gqlTagInDetachedJSDocBlockComment = gqlTagInDetachedJSDocBlockComment;
exports.gqlFieldTagOnInputType = gqlFieldTagOnInputType;
exports.gqlFieldParentMissingTag = gqlFieldParentMissingTag;
exports.missingSpecifiedByUrl = missingSpecifiedByUrl;
exports.specifiedByOnWrongNode = specifiedByOnWrongNode;
exports.missingGenericType = missingGenericType;
exports.nonGraphQLGenericType = nonGraphQLGenericType;
exports.genericTypeUsedAsUnionMember = genericTypeUsedAsUnionMember;
exports.genericTypeImplementsInterface = genericTypeImplementsInterface;
exports.concreteTypenameImplementingInterfaceCannotBeResolved = concreteTypenameImplementingInterfaceCannotBeResolved;
exports.concreteTypenameInUnionCannotBeResolved = concreteTypenameInUnionCannotBeResolved;
exports.invalidFieldNonPublicAccessModifier = invalidFieldNonPublicAccessModifier;
exports.invalidStaticModifier = invalidStaticModifier;
exports.staticMethodOnNonClass = staticMethodOnNonClass;
exports.staticMethodClassWithNamedExportNotNamed = staticMethodClassWithNamedExportNotNamed;
exports.oneOfNotSupportedGraphql = oneOfNotSupportedGraphql;
exports.oneOfNotOnUnion = oneOfNotOnUnion;
exports.oneOfFieldNotTypeLiteralWithOneProperty = oneOfFieldNotTypeLiteralWithOneProperty;
exports.oneOfPropertyMissingTypeAnnotation = oneOfPropertyMissingTypeAnnotation;
exports.contextTagOnNonDeclaration = contextTagOnNonDeclaration;
exports.duplicateContextTag = duplicateContextTag;
exports.userDefinedInfoTag = userDefinedInfoTag;
exports.invalidResolverParamType = invalidResolverParamType;
exports.exportedArrowFunctionNotConst = exportedArrowFunctionNotConst;
exports.exportedFieldVariableMultipleDeclarations = exportedFieldVariableMultipleDeclarations;
exports.fieldVariableNotTopLevelExported = fieldVariableNotTopLevelExported;
exports.fieldVariableIsNotArrowFunction = fieldVariableIsNotArrowFunction;
exports.positionalResolverArgDoesNotHaveName = positionalResolverArgDoesNotHaveName;
exports.positionalArgAndArgsObject = positionalArgAndArgsObject;
exports.contextOrInfoUsedInGraphQLPosition = contextOrInfoUsedInGraphQLPosition;
var Extractor_1 = require("./Extractor");

@@ -24,13 +145,11 @@ exports.ISSUE_URL = "https://github.com/captbaritone/grats/issues";

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.");
}
exports.fieldTagOnWrongNode = fieldTagOnWrongNode;
function killsParentOnExceptionOnWrongNode() {
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "`. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` can only be used in field annotation docblocks. Perhaps you are missing a `@").concat(Extractor_1.FIELD_TAG, "` tag?");
}
exports.killsParentOnExceptionOnWrongNode = killsParentOnExceptionOnWrongNode;
function wrongCasingForGratsTag(actual, expected) {
return "Incorrect casing for Grats tag `@".concat(actual, "`. Use `@").concat(expected, "` instead.");
}
exports.wrongCasingForGratsTag = wrongCasingForGratsTag;
// TODO: Add code action
function invalidGratsTag(actual) {

@@ -40,47 +159,41 @@ var validTagList = Extractor_1.ALL_TAGS.map(function (t) { return "`@".concat(t, "`"); }).join(", ");

}
exports.invalidGratsTag = invalidGratsTag;
function invalidTypeTagUsage() {
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. e.g. `type MyScalar = string`");
}
exports.invalidScalarTagUsage = invalidScalarTagUsage;
function invalidInterfaceTagUsage() {
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. 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 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. 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. e.g. `type MyUnion = TypeA | TypeB`");
}
exports.expectedUnionTypeNode = expectedUnionTypeNode;
function expectedUnionTypeReference() {
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`.");
}
exports.expectedUnionTypeReference = expectedUnionTypeReference;
function invalidParentArgForFunctionField() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to have a first argument representing the type to extend. If you don't need access to the parent object in the function, you can name the variable `_` to indicate that it is unused. e.g. `function myField(_: ParentType) {}`");
}
exports.invalidParentArgForFunctionField = invalidParentArgForFunctionField;
function invalidReturnTypeForFunctionField() {
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. 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.");
}
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.");
}
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.";

@@ -90,176 +203,152 @@ function functionFieldParentTypeMissing() {

}
exports.functionFieldParentTypeMissing = functionFieldParentTypeMissing;
function functionFieldParentTypeNotValid() {
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. 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. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export.");
}
exports.functionFieldDefaultExport = functionFieldDefaultExport;
function functionFieldNotNamedExport() {
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. e.g. `type MyInput = { foo: string }`");
}
exports.inputTypeNotLiteral = inputTypeNotLiteral;
function inputTypeFieldNotProperty() {
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 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. Grats uses the name of the class to derive the name of the GraphQL type. Consider naming the class.");
}
exports.typeTagOnUnnamedClass = typeTagOnUnnamedClass;
function typeTagOnAliasOfNonObjectOrUnknown() {
return "Expected `@".concat(Extractor_1.TYPE_TAG, "` type to be an object type literal (`{ }`) or `unknown`. For example: `type Foo = { bar: string }` or `type Query = unknown`.");
}
exports.typeTagOnAliasOfNonObjectOrUnknown = typeTagOnAliasOfNonObjectOrUnknown;
// TODO: Add code action
function typeNameNotDeclaration() {
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.";
var TYPENAME_CONTEXT = "This is needed to ensure Grats can determine the type of this object during GraphQL execution.";
function _typeNamePropertyExample(expectedName) {
return "For example: `__typename = \"".concat(expectedName, "\" as const` or `__typename: \"").concat(expectedName, "\";`.");
}
function typeNameMissingInitializer() {
return "Expected `__typename` property to have an initializer or a string literal type. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`. ".concat(TYPENAME_CONTEXT);
return "Expected `__typename` property to have an initializer or a string literal type. ".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\";`. ".concat(TYPENAME_CONTEXT);
function typeNameInitializeNotString(expectedName) {
return "Expected `__typename` property initializer to be a string literal. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameInitializeNotString = typeNameInitializeNotString;
function typeNameInitializeNotExpression(expectedName) {
return "Expected `__typename` property initializer to be an expression with a const assertion. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
function typeNameTypeNotReferenceNode(expectedName) {
return "Expected `__typename` property must be correctly defined. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
function typeNameTypeNameNotIdentifier(expectedName) {
return "Expected `__typename` property name must be correctly specified. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
function typeNameTypeNameNotConst(expectedName) {
return "Expected `__typename` property type name to be \"const\". ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
function typeNameInitializerWrong(expected, 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, "\";`. ").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, "\";`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameTypeNotStringLiteral = typeNameTypeNotStringLiteral;
function typeNameDoesNotMatchExpected(expected) {
return "Expected `__typename` property to be `\"".concat(expected, "\"`. ").concat(TYPENAME_CONTEXT);
}
exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected;
function argumentParamIsMissingType() {
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.";
function resolverParamIsMissingType() {
return "Missing type annotation for resolver argument. Expected all resolver arguments to have an explicit type annotation. Grats needs to be able to see the type of the arguments to generate an executable GraphQL schema.";
}
exports.argumentParamIsMissingType = argumentParamIsMissingType;
function argumentParamIsNotObject() {
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.";
function multipleResolverTypeLiterals() {
return "Unexpected multiple resolver parameters typed with an object literal. Grats assumes a resolver parameter typed with object literals describes the GraphQL arguments. Therefore only one such parameter is permitted.";
}
exports.argumentParamIsNotObject = argumentParamIsNotObject;
function argIsNotProperty() {
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. 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 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. 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'`. 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'`. 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. Grats uses the name of the entity to derive the name of the GraphQL construct.";
}
exports.gqlEntityMissingName = gqlEntityMissingName;
function methodMissingType() {
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 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.wrapperMissingTypeArg = wrapperMissingTypeArg;
function invalidWrapperOnInputType(wrapperName) {
return "Invalid input type. `".concat(wrapperName, "` is not a valid type when used as a GraphQL input value.");
}
function cannotResolveSymbolForDescription() {
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 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. 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.");
}
exports.expectedOneNonNullishType = expectedOneNonNullishType;
// TODO: Add code action
function ambiguousNumberType() {
return "Unexpected number type. GraphQL supports both Int and Float, making `number` ambiguous. Instead, import the `Int` or `Float` type from `".concat(Extractor_1.LIBRARY_IMPORT_NAME, "` and use that. e.g. `import { Int, Float } from \"").concat(Extractor_1.LIBRARY_IMPORT_NAME, "\";`.");
}
exports.ambiguousNumberType = ambiguousNumberType;
function defaultValueIsNotLiteral() {
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 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. 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}`. 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. 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. 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.";
return "Unknown GraphQL type. Grats does 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 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 expectedNameIdentifier() {
return "Expected an name identifier. Grats expected to find a name here which it could use to derive the GraphQL name.";
return "Expected a name identifier. Grats expected to find a name here which it could use to derive the GraphQL name.";
}
exports.expectedNameIdentifier = expectedNameIdentifier;
// TODO: Add code action
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 option `nullableByDefault` is enabled in your `tsconfig.json`.");
}
exports.killsParentOnExceptionWithWrongConfig = killsParentOnExceptionWithWrongConfig;
// TODO: Add code action
function killsParentOnExceptionOnNullable() {
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;
// TODO: Add code action
function nonNullTypeCannotBeOptional() {
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.";
}
exports.nonNullTypeCannotBeOptional = nonNullTypeCannotBeOptional;
function mergedInterfaces() {

@@ -274,23 +363,21 @@ return [

}
exports.mergedInterfaces = mergedInterfaces;
// TODO: Add code action
function implementsTagOnClass() {
return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `class MyType implements MyInterface`.");
}
exports.implementsTagOnClass = implementsTagOnClass;
// TODO: Add code action
function implementsTagOnInterface() {
return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `interface MyType extends MyInterface`.");
}
exports.implementsTagOnInterface = implementsTagOnInterface;
function implementsTagOnTypeAlias() {
return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Types which implement GraphQL interfaces should be defined using TypeScript class or interface declarations.");
}
exports.implementsTagOnTypeAlias = implementsTagOnTypeAlias;
// TODO: Add code action
function duplicateTag(tagName) {
return "Unexpected duplicate `@".concat(tagName, "` tag. Grats does not accept multiple instances of the same tag.");
}
exports.duplicateTag = duplicateTag;
function duplicateInterfaceTag() {
return "Unexpected duplicate `@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` tag. To declare that a type or interface implements multiple interfaces list them as comma separated values: `@").concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, " interfaceA, interfaceB`.");
}
exports.duplicateInterfaceTag = duplicateInterfaceTag;
// TODO: Add code action
function parameterWithoutModifiers() {

@@ -302,3 +389,2 @@ return [

}
exports.parameterWithoutModifiers = parameterWithoutModifiers;
function parameterPropertyNotPublic() {

@@ -310,23 +396,17 @@ return [

}
exports.parameterPropertyNotPublic = parameterPropertyNotPublic;
function parameterPropertyMissingType() {
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.");
}
exports.parameterPropertyMissingType = parameterPropertyMissingType;
function invalidTypePassedToFieldFunction() {
return "Unexpected type passed to `@".concat(Extractor_1.FIELD_TAG, "` function. `@").concat(Extractor_1.FIELD_TAG, "` functions can only be used to extend `@").concat(Extractor_1.TYPE_TAG, "` and `@").concat(Extractor_1.INTERFACE_TAG, "` types.");
}
exports.invalidTypePassedToFieldFunction = invalidTypePassedToFieldFunction;
function unresolvedTypeReference() {
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 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 that all context values reference the same type declaration.";
}
exports.expectedTypeAnnotationOfReferenceOnContext = expectedTypeAnnotationOfReferenceOnContext;
function expectedTypeAnnotationOnContextToBeResolvable() {

@@ -337,50 +417,136 @@ // TODO: Provide guidance?

}
exports.expectedTypeAnnotationOnContextToBeResolvable = expectedTypeAnnotationOnContextToBeResolvable;
function expectedTypeAnnotationOnContextToHaveDeclaration() {
return "Unable to locate the declaration of the context parameter's type. Grats validates that your context parameter is type-safe by checking all context values reference the same type declaration. Did you forget to import or define this type?";
}
exports.expectedTypeAnnotationOnContextToHaveDeclaration = expectedTypeAnnotationOnContextToHaveDeclaration;
function unexpectedParamSpreadForContextParam() {
return "Unexpected spread parameter in context parameter position. Grats expects the context parameter to be a single, explicitly-typed argument.";
function unexpectedParamSpreadForResolverParam() {
return "Unexpected spread argument in resolver. Grats expects all resolver arguments to be a single, explicitly-typed argument.";
}
exports.unexpectedParamSpreadForContextParam = unexpectedParamSpreadForContextParam;
function resolverParamIsUnknown() {
// TODO: Give guidance that this is a change?
return "Unexpected `unknown` type for resolver argument. If a resolver argument is not needed by the resolver, it may be omitted.";
}
function resolverParamIsNever() {
// TODO: Give guidance that this is a change?
return "Unexpected `never` type for resolver argument. If a resolver argument is not needed by the resolver, it may be omitted.";
}
function unexpectedResolverParamType() {
return "Unexpected type for resolver argument. Resolver arguments must be typed with either an object literal (`{}`) or a reference to a named type.";
}
function multipleContextTypes() {
return "Context argument's type does not match. Grats expects all resolvers that read the context argument to use the same type for that argument. Did you use the incorrect type in one of your resolvers?";
}
exports.multipleContextTypes = multipleContextTypes;
function graphQLNameHasLeadingNewlines(name, tagName) {
return "Expected the GraphQL name `".concat(name, "` to be on the same line as it's `@").concat(tagName, "` tag.");
}
exports.graphQLNameHasLeadingNewlines = graphQLNameHasLeadingNewlines;
function graphQLTagNameHasWhitespace(tagName) {
return "Expected text following a `@".concat(tagName, "` tag to be a GraphQL name. If you intended this text to be a description, place it at the top of the docblock before any `@tags`.");
}
exports.graphQLTagNameHasWhitespace = graphQLTagNameHasWhitespace;
function subscriptionFieldNotAsyncIterable() {
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`. Non-subscription fields are only expected to return a single value.";
}
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`. 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 _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.");
}
// TODO: Add code action
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?");
}
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.");
}
// TODO: Add code action
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?");
}
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, "`.");
}
function nonGraphQLGenericType(templateName, paramName) {
return "Expected `".concat(templateName, "` to be passed a GraphQL type argument for type parameter `").concat(paramName, "`.");
}
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.";
}
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.");
}
function concreteTypenameImplementingInterfaceCannotBeResolved(implementor, interfaceName) {
return "Cannot resolve typename. The type `".concat(implementor, "` implements `").concat(interfaceName, "`, so it must either have a `__typename` property or be an exported class.");
}
function concreteTypenameInUnionCannotBeResolved(implementor, unionName) {
return "Cannot resolve typename. The type `".concat(implementor, "` is a member of `").concat(unionName, "`, so it must either have a `__typename` property or be an exported class.");
}
// TODO: Add code action
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.");
}
function invalidStaticModifier() {
return "Unexpected `static` modifier on non-method `@".concat(Extractor_1.FIELD_TAG, "`. `static` is only valid on method signatures.");
}
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.");
}
function staticMethodClassWithNamedExportNotNamed() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` static method's class to be named if exported without the `default` keyword.");
}
function oneOfNotSupportedGraphql(requiredVersion, foundVersion) {
return "OneOf input types are only supported in `graphql@".concat(requiredVersion, "` and later but Grats found `graphql@").concat(foundVersion, "`. Please upgrade your version of graphql-js in order to use this feature.");
}
function oneOfNotOnUnion() {
return "Expected the type of a @gqlInput with @oneOf to be attached to a TypeScript union.";
}
function oneOfFieldNotTypeLiteralWithOneProperty() {
return "Expected each member of a @oneOf @gqlInput to be a TypeScript object literal with exactly one property.";
}
function oneOfPropertyMissingTypeAnnotation() {
return "Expected each property of a @oneOf @gqlInput to have a type annotation.";
}
function contextTagOnNonDeclaration() {
return "Invalid `@".concat(Extractor_1.CONTEXT_TAG, "` tag annotation. Expected the `@").concat(Extractor_1.CONTEXT_TAG, "` tag to be attached to a type, interface or class declaration.");
}
function duplicateContextTag() {
return "Unexpected duplicate `@".concat(Extractor_1.CONTEXT_TAG, "` tag. Only one type in a project may be annotated with the `@").concat(Extractor_1.CONTEXT_TAG, "`.");
}
function userDefinedInfoTag() {
return "Unexpected user-defined `@".concat(Extractor_1.INFO_TAG, "` tag. Use the type `GqlInfo` exported from `grats`: `import { GqlInfo } from \"grats\";`.");
}
function invalidResolverParamType() {
return "Unexpected GraphQL type used as resolver parameter. Resolver input arguments must be specified as a single `args` object literal: `args: {argName: ArgType}`.";
}
function exportedArrowFunctionNotConst() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` arrow function to be declared as `const`.");
}
function exportedFieldVariableMultipleDeclarations(n) {
return "Expected only one declaration when defining a `@".concat(Extractor_1.FIELD_TAG, "`, found ").concat(n, ".");
}
function fieldVariableNotTopLevelExported() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` to be an exported top-level declaration. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be exported from the module.");
}
function fieldVariableIsNotArrowFunction() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` on variable declaration to be attached to an arrow function.");
}
function positionalResolverArgDoesNotHaveName() {
return "Expected resolver argument to have a name. Grats needs to be able to see the name of the argument in order to derive a GraphQL argument name.";
}
function positionalArgAndArgsObject() {
return "Unexpected arguments object in resolver that is also using positional GraphQL arguments. Grats expects that either all GraphQL arguments will be defined in a single object, or that all GraphQL arguments will be defined using positional arguments. The two strategies may not be combined.";
}
function contextOrInfoUsedInGraphQLPosition(kind) {
var tag = kind === "CONTEXT" ? Extractor_1.CONTEXT_TAG : Extractor_1.INFO_TAG;
return "Cannot use `".concat(tag, "` as a type in GraphQL type position.");
}

@@ -1,6 +0,5 @@

import { NameNode } from "graphql";
import { NameNode, DefinitionNode } from "graphql";
import { DiagnosticsResult } from "./utils/DiagnosticError";
import * as ts from "typescript";
import { NameDefinition } from "./TypeContext";
import { GratsDefinitionNode } from "./GraphQLConstructor";
export declare const LIBRARY_IMPORT_NAME = "grats";

@@ -15,10 +14,13 @@ export declare const LIBRARY_NAME = "Grats";

export declare const INPUT_TAG = "gqlInput";
export declare const CONTEXT_TAG = "gqlContext";
export declare const INFO_TAG = "gqlInfo";
export declare const IMPLEMENTS_TAG_DEPRECATED = "gqlImplements";
export declare const KILLS_PARENT_ON_EXCEPTION_TAG = "killsParentOnException";
export declare const ALL_TAGS: string[];
export declare const SPECIFIED_BY_TAG = "specifiedBy";
export declare const ONE_OF_TAG = "oneOf";
export type ExtractionSnapshot = {
readonly definitions: GratsDefinitionNode[];
readonly unresolvedNames: Map<ts.Node, NameNode>;
readonly nameDefinitions: Map<ts.Node, NameDefinition>;
readonly contextReferences: Array<ts.Node>;
readonly definitions: DefinitionNode[];
readonly unresolvedNames: Map<ts.EntityName, NameNode>;
readonly nameDefinitions: Map<ts.DeclarationStatement, NameDefinition>;
readonly typesWithTypename: Set<string>;

@@ -25,0 +27,0 @@ readonly interfaceDeclarations: Array<ts.InterfaceDeclaration>;

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

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, ASTNode } 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";
export type GratsDefinitionNode = DefinitionNode | AbstractFieldDefinitionNode;
export type AbstractFieldDefinitionNode = {
readonly kind: "AbstractFieldDefinition";
readonly loc: Location;
readonly onType: NameNode;
readonly field: FieldDefinitionNode;
};
import { UnresolvedResolverParam, InputValueDefinitionNodeOrResolverArg } from "./metadataDirectives";
import { DiagnosticResult, TsLocatableNode } from "./utils/DiagnosticError";
export declare class GraphQLConstructor {

@@ -14,16 +9,19 @@ fieldMetadataDirective(node: ts.Node, metadata: {

name: string | null;
argCount: number | null;
asyncIterable?: ts.Node | null;
exportName: string | null;
}): ConstDirectiveNode;
killsParentOnExceptionDirective(node: ts.Node): ConstDirectiveNode;
unionTypeDefinition(node: ts.Node, name: NameNode, types: NamedTypeNode[], description: StringValueNode | null): UnionTypeDefinitionNode;
objectTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null): ObjectTypeDefinitionNode;
objectTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null, hasTypeNameField: boolean, exported: {
tsModulePath: string;
exportName: string | null;
} | null): ObjectTypeDefinitionNode;
interfaceTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null): InterfaceTypeDefinitionNode;
enumTypeDefinition(node: ts.Node, name: NameNode, values: readonly EnumValueDefinitionNode[], description: StringValueNode | null): EnumTypeDefinitionNode;
abstractFieldDefinition(node: ts.Node, onType: NameNode, field: FieldDefinitionNode): AbstractFieldDefinitionNode;
fieldDefinition(node: ts.Node, name: NameNode, type: TypeNode, args: readonly InputValueDefinitionNode[] | null, directives: readonly ConstDirectiveNode[], description: StringValueNode | null): FieldDefinitionNode;
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, resolverParams: UnresolvedResolverParam[] | null): FieldDefinitionNode;
constObjectField(node: ts.Node, name: NameNode, value: ConstValueNode): ConstObjectFieldNode;
inputValueDefinition(node: ts.Node, name: NameNode, type: TypeNode, directives: readonly ConstDirectiveNode[] | null, defaultValue: ConstValueNode | null, description: StringValueNode | null): InputValueDefinitionNode;
inputValueDefinitionOrResolverArg(node: ts.Node, name: DiagnosticResult<NameNode>, type: TypeNode, directives: readonly ConstDirectiveNode[] | null, defaultValue: ConstValueNode | null, description: StringValueNode | null): InputValueDefinitionNodeOrResolverArg;
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;

@@ -46,4 +44,3 @@ name(node: ts.Node, value: string): NameNode;

_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;

@@ -15,4 +15,6 @@ "use strict";

exports.GraphQLConstructor = void 0;
exports.loc = loc;
var graphql_1 = require("graphql");
var metadataDirectives_1 = require("./metadataDirectives");
var helpers_1 = require("./utils/helpers");
var GraphQLConstructor = /** @class */ (function () {

@@ -29,12 +31,9 @@ function GraphQLConstructor() {

}
if (metadata.argCount != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.ARG_COUNT), this.int(node, metadata.argCount.toString())));
if (metadata.exportName != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.EXPORT_NAME_ARG), this.string(node, metadata.exportName)));
}
if (metadata.asyncIterable) {
args.push(this.constArgument(metadata.asyncIterable, this.name(node, metadataDirectives_1.ASYNC_ITERABLE_ARG), this.boolean(node, true)));
}
return this.constDirective(node, this.name(node, metadataDirectives_1.FIELD_METADATA_DIRECTIVE), args);
};
GraphQLConstructor.prototype.killsParentOnExceptionDirective = function (node) {
return (0, metadataDirectives_1.makeKillsParentOnExceptionDirective)(this._loc(node));
return (0, metadataDirectives_1.makeKillsParentOnExceptionDirective)(loc(node));
};

@@ -45,3 +44,3 @@ /* Top Level Types */

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

@@ -52,11 +51,12 @@ name: name,

};
GraphQLConstructor.prototype.objectTypeDefinition = function (node, name, fields, interfaces, description) {
GraphQLConstructor.prototype.objectTypeDefinition = function (node, name, fields, interfaces, description, hasTypeNameField, exported) {
return {
kind: graphql_1.Kind.OBJECT_TYPE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,
directives: undefined,
name: name,
fields: fields,
interfaces: interfaces !== null && interfaces !== void 0 ? interfaces : undefined,
hasTypeNameField: hasTypeNameField,
exported: exported !== null && exported !== void 0 ? exported : undefined,
};

@@ -67,3 +67,3 @@ };

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

@@ -79,3 +79,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,

@@ -89,13 +89,14 @@ 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,
};
};
/* Field Definitions */
GraphQLConstructor.prototype.fieldDefinition = function (node, name, type, args, directives, description) {
GraphQLConstructor.prototype.fieldDefinition = function (node, name, type, args, directives, description, resolverParams) {
return {
kind: graphql_1.Kind.FIELD_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -106,6 +107,7 @@ name: name,

directives: this._optionalList(directives),
resolverParams: resolverParams !== null && resolverParams !== void 0 ? resolverParams : undefined,
};
};
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 };
};

@@ -115,3 +117,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,

@@ -124,6 +126,17 @@ name: name,

};
GraphQLConstructor.prototype.inputValueDefinitionOrResolverArg = function (node, name, type, directives, defaultValue, description) {
return {
kind: graphql_1.Kind.INPUT_VALUE_DEFINITION,
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,
name: name,
type: type,
defaultValue: defaultValue !== null && defaultValue !== void 0 ? defaultValue : undefined,
directives: this._optionalList(directives),
};
};
GraphQLConstructor.prototype.enumValueDefinition = function (node, name, directives, description) {
return {
kind: graphql_1.Kind.ENUM_VALUE_DEFINITION,
loc: this._loc(node),
loc: loc(node),
description: description !== null && description !== void 0 ? description : undefined,

@@ -134,9 +147,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),
};

@@ -147,3 +160,3 @@ };

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

@@ -157,3 +170,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)(),
};
};

@@ -163,3 +181,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),

@@ -169,3 +187,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 };
};

@@ -177,3 +195,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 };
};

@@ -188,12 +206,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: this._loc(node) });
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 };
};

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

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

@@ -210,15 +228,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 };
};

@@ -231,18 +249,18 @@ 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);
}
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);
}
import * as ts from "typescript";
export type ConfigOptions = {
export type GratsConfig = {
graphqlSchema: string;

@@ -10,8 +10,9 @@ tsSchema: string;

tsSchemaHeader: string | null;
importModuleSpecifierEnding: string;
};
export type ParsedCommandLineGrats = Omit<ts.ParsedCommandLine, "raw"> & {
raw: {
grats: ConfigOptions;
grats: GratsConfig;
};
};
export declare function validateGratsOptions(options: ts.ParsedCommandLine): ParsedCommandLineGrats;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateGratsOptions = void 0;
exports.validateGratsOptions = validateGratsOptions;
var DEFAULT_SDL_HEADER = "# Schema generated by Grats (https://grats.capt.dev)\n# Do not manually edit. Regenerate by running `npx grats`.";

@@ -37,2 +37,3 @@ 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 */";

"tsSchemaHeader",
"importModuleSpecifierEnding",
]);

@@ -122,4 +123,9 @@ // TODO: Make this return diagnostics

}
if (gratsOptions.importModuleSpecifierEnding === undefined) {
gratsOptions.importModuleSpecifierEnding = "";
}
else if (typeof gratsOptions.importModuleSpecifierEnding !== "string") {
throw new Error("Grats: The Grats config option `importModuleSpecifierEnding` must be a string if provided.");
}
return __assign(__assign({}, options), { raw: __assign(__assign({}, options.raw), { grats: gratsOptions }) });
}
exports.validateGratsOptions = validateGratsOptions;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveRelativePath = exports.relativePath = void 0;
exports.relativePath = relativePath;
exports.resolveRelativePath = resolveRelativePath;
var path_1 = require("path");

@@ -16,6 +17,4 @@ // Grats parses TypeScript files and finds resolvers. If the field resolver is a

}
exports.relativePath = relativePath;
function resolveRelativePath(relativePath) {
return (0, path_1.resolve)(gratsRoot, relativePath);
}
exports.resolveRelativePath = resolveRelativePath;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.getParsedTsConfig = exports.codegen = exports.extract = exports.printSDLWithoutMetadata = void 0;
exports.codegen = exports.extract = exports.printSDLWithoutMetadata = void 0;
exports.getParsedTsConfig = getParsedTsConfig;
var ts = require("typescript");

@@ -48,2 +49,1 @@ var gratsConfig_1 = require("./gratsConfig");

}
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;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.computeInterfaceMap = void 0;
exports.computeInterfaceMap = computeInterfaceMap;
var helpers_1 = require("./utils/helpers");

@@ -38,3 +38,3 @@ var graphql_1 = require("graphql");

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

@@ -63,3 +63,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") {

@@ -92,2 +92,1 @@ // We trust that these errors will be reported elsewhere.

}
exports.computeInterfaceMap = computeInterfaceMap;

@@ -7,2 +7,3 @@ import { DocumentNode, GraphQLSchema } from "graphql";

export { initTsPlugin } from "./tsPlugin/initTsPlugin";
export { GratsConfig } from "./gratsConfig";
export type SchemaAndDoc = {

@@ -9,0 +10,0 @@ schema: GraphQLSchema;

@@ -30,3 +30,6 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSchemaAndDoc = exports.buildSchemaAndDocResultWithHost = exports.buildSchemaAndDocResult = exports.initTsPlugin = void 0;
exports.initTsPlugin = void 0;
exports.buildSchemaAndDocResult = buildSchemaAndDocResult;
exports.buildSchemaAndDocResultWithHost = buildSchemaAndDocResultWithHost;
exports.extractSchemaAndDoc = extractSchemaAndDoc;
var graphql_1 = require("graphql");

@@ -42,7 +45,5 @@ var DiagnosticError_1 = require("./utils/DiagnosticError");

var validateMergedInterfaces_1 = require("./validations/validateMergedInterfaces");
var validateContextReferences_1 = require("./validations/validateContextReferences");
var metadataDirectives_1 = require("./metadataDirectives");
var addInterfaceFields_1 = require("./transforms/addInterfaceFields");
var filterNonGqlInterfaces_1 = require("./transforms/filterNonGqlInterfaces");
var resolveTypes_1 = require("./transforms/resolveTypes");
var validateAsyncIterable_1 = require("./validations/validateAsyncIterable");

@@ -52,3 +53,8 @@ var applyDefaultNullability_1 = require("./transforms/applyDefaultNullability");

var sortSchemaAst_1 = require("./transforms/sortSchemaAst");
var validateDuplicateContextOrInfo_1 = require("./validations/validateDuplicateContextOrInfo");
var validateSemanticNullability_1 = require("./validations/validateSemanticNullability");
var resolveTypes_1 = require("./transforms/resolveTypes");
var resolveResolverParams_1 = require("./transforms/resolveResolverParams");
// Export the TypeScript plugin implementation used by
// grats-ts-plugin
var initTsPlugin_1 = require("./tsPlugin/initTsPlugin");

@@ -65,3 +71,2 @@ Object.defineProperty(exports, "initTsPlugin", { enumerable: true, get: function () { return initTsPlugin_1.initTsPlugin; } });

}
exports.buildSchemaAndDocResult = buildSchemaAndDocResult;
function buildSchemaAndDocResultWithHost(options, compilerHost) {

@@ -73,3 +78,2 @@ var program = ts.createProgram(options.fileNames, options.options, compilerHost);

}
exports.buildSchemaAndDocResultWithHost = buildSchemaAndDocResultWithHost;
/**

@@ -87,3 +91,3 @@ * The core transformation pipeline of Grats.

// Collect validation errors
var validationResult = (0, Result_1.concatResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateContextReferences_1.validateContextReferences)(ctx, snapshot.contextReferences));
var validationResult = (0, Result_1.concatResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateDuplicateContextOrInfo_1.validateDuplicateContextOrInfo)(ctx));
var docResult = new Result_1.ResultPipe(validationResult)

@@ -93,2 +97,6 @@ // Add the metadata directive definitions to definitions

.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, resolveResolverParams_1.resolveResolverParams)(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

@@ -100,11 +108,7 @@ // that field to each concrete type as well. This must be done after all types are created,

.map(function (definitions) { return ({ kind: graphql_1.Kind.DOCUMENT, definitions: definitions }); })
// Filter out any `implements` clauses that are not GraphQL interfaces.
.map(function (doc) { return (0, filterNonGqlInterfaces_1.filterNonGqlInterfaces)(ctx, doc); })
// 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); })
// Resolve TypeScript type references to the GraphQL types they represent (or error).
.andThen(function (doc) { return (0, resolveTypes_1.resolveTypes)(ctx, doc); })
// Ensure all subscription fields, and _only_ subscription fields, return an AsyncIterable.
.andThen(function (doc) { return (0, validateAsyncIterable_1.validateAsyncIterable)(doc); })
// Merge any `extend` definitions into their base definitions.

@@ -131,3 +135,2 @@ .map(function (doc) { return (0, mergeExtensions_1.mergeExtensions)(doc); })

}
exports.extractSchemaAndDoc = extractSchemaAndDoc;
// Given a SDL AST, build and validate a GraphQLSchema.

@@ -154,3 +157,3 @@ function buildSchemaFromDoc(doc) {

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 e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
var result = {

@@ -160,3 +163,2 @@ definitions: [],

unresolvedNames: new Map(),
contextReferences: [],
typesWithTypename: new Set(),

@@ -169,4 +171,4 @@ interfaceDeclarations: [],

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

@@ -178,3 +180,3 @@ }

try {
if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
}

@@ -184,4 +186,4 @@ finally { if (e_2) throw e_2.error; }

try {
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];
for (var _j = (e_3 = void 0, __values(snapshot.nameDefinitions)), _k = _j.next(); !_k.done; _k = _j.next()) {
var _l = __read(_k.value, 2), node = _l[0], definition = _l[1];
result.nameDefinitions.set(node, definition);

@@ -193,3 +195,3 @@ }

try {
if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
}

@@ -199,4 +201,4 @@ finally { if (e_3) throw e_3.error; }

try {
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];
for (var _m = (e_4 = void 0, __values(snapshot.unresolvedNames)), _o = _m.next(); !_o.done; _o = _m.next()) {
var _p = __read(_o.value, 2), node = _p[0], typeName = _p[1];
result.unresolvedNames.set(node, typeName);

@@ -208,3 +210,3 @@ }

try {
if (_p && !_p.done && (_d = _o.return)) _d.call(_o);
if (_o && !_o.done && (_d = _m.return)) _d.call(_m);
}

@@ -214,5 +216,5 @@ finally { if (e_4) throw e_4.error; }

try {
for (var _r = (e_5 = void 0, __values(snapshot.contextReferences)), _s = _r.next(); !_s.done; _s = _r.next()) {
var contextReference = _s.value;
result.contextReferences.push(contextReference);
for (var _q = (e_5 = void 0, __values(snapshot.typesWithTypename)), _r = _q.next(); !_r.done; _r = _q.next()) {
var typeName = _r.value;
result.typesWithTypename.add(typeName);
}

@@ -223,3 +225,3 @@ }

try {
if (_s && !_s.done && (_e = _r.return)) _e.call(_r);
if (_r && !_r.done && (_e = _q.return)) _e.call(_q);
}

@@ -229,5 +231,5 @@ finally { if (e_5) throw e_5.error; }

try {
for (var _t = (e_6 = void 0, __values(snapshot.typesWithTypename)), _u = _t.next(); !_u.done; _u = _t.next()) {
var typeName = _u.value;
result.typesWithTypename.add(typeName);
for (var _s = (e_6 = void 0, __values(snapshot.interfaceDeclarations)), _t = _s.next(); !_t.done; _t = _s.next()) {
var interfaceDeclaration = _t.value;
result.interfaceDeclarations.push(interfaceDeclaration);
}

@@ -238,19 +240,6 @@ }

try {
if (_u && !_u.done && (_f = _t.return)) _f.call(_t);
if (_t && !_t.done && (_f = _s.return)) _f.call(_s);
}
finally { if (e_6) throw e_6.error; }
}
try {
for (var _v = (e_7 = void 0, __values(snapshot.interfaceDeclarations)), _w = _v.next(); !_w.done; _w = _v.next()) {
var interfaceDeclaration = _w.value;
result.interfaceDeclarations.push(interfaceDeclaration);
}
}
catch (e_7_1) { e_7 = { error: e_7_1 }; }
finally {
try {
if (_w && !_w.done && (_g = _v.return)) _g.call(_v);
}
finally { if (e_7) throw e_7.error; }
}
}

@@ -257,0 +246,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.locate = void 0;
exports.locate = locate;
var graphql_1 = require("graphql");

@@ -41,3 +41,2 @@ var Result_1 = require("./utils/Result");

}
exports.locate = locate;
var ENTITY_NAME_REGEX = /^([A-Za-z0-9_]+)(?:\.([A-Za-z0-9_]+))?$/;

@@ -44,0 +43,0 @@ function parseEntityName(entityName) {

@@ -1,7 +0,105 @@

import { ConstDirectiveNode, DocumentNode, Location } from "graphql";
import { GratsDefinitionNode } from "./GraphQLConstructor";
import * as ts from "typescript";
import { ConstDirectiveNode, ConstValueNode, DefinitionNode, DocumentNode, InputValueDefinitionNode, Kind, Location, NameNode, StringValueNode, TypeNode } from "graphql";
import { DiagnosticResult } from "./utils/DiagnosticError.js";
/**
* 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;
hasTypeNameField: boolean;
exported?: {
tsModulePath: string;
exportName: string | null;
};
}
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;
}
interface FieldDefinitionNode {
/**
* Grats metadata: Indicates the params expected by the field resolver and their order
*/
resolverParams?: UnresolvedResolverParam[];
}
}
/**
* At extraction time we don't know if a resolver arg is context, info, or a
* positional GraphQL argument. If it's a positional argument, we need to ensure
* it has a valid name. If it's just info or context, it's fine if it doesn't
* have a name e.g. (destructured).
*/
export interface InputValueDefinitionNodeOrResolverArg {
readonly kind: Kind.INPUT_VALUE_DEFINITION;
readonly loc: Location;
readonly description?: StringValueNode;
readonly name: DiagnosticResult<NameNode>;
readonly type: TypeNode;
readonly defaultValue?: ConstValueNode;
readonly directives?: ReadonlyArray<ConstDirectiveNode>;
}
export type UnresolvedResolverParam = NamedFieldParam | PositionalFieldParam | Unresolved;
export type ResolvedResolverParam = NamedFieldParam | PositionalFieldParam;
export type NamedFieldParam = {
kind: "named";
sourceNode?: ts.Node;
name: FieldParam;
};
export type PositionalFieldParam = {
kind: "positionalArg";
inputDefinition: InputValueDefinitionNode;
};
export type Unresolved = {
kind: "unresolved";
inputDefinition: InputValueDefinitionNodeOrResolverArg;
};
export type FieldParam = "source" | "args" | "context" | "info";
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";

@@ -11,10 +109,9 @@ export declare const KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = "killsParentOnException";

export declare const DIRECTIVES_AST: DocumentNode;
export declare function addMetadataDirectives(definitions: Array<GratsDefinitionNode>): Array<GratsDefinitionNode>;
export declare function addMetadataDirectives(definitions: Array<DefinitionNode>): Array<DefinitionNode>;
export type FieldMetadata = {
tsModulePath: string | null;
name: string | null;
argCount: number | null;
asyncIterable?: Location | null;
exportName: string | null;
};
export declare function makeKillsParentOnExceptionDirective(loc: Location): ConstDirectiveNode;
export declare function parseFieldMetadataDirective(directive: ConstDirectiveNode): FieldMetadata;

@@ -28,8 +28,12 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
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.FIELD_METADATA_DIRECTIVE = void 0;
exports.DIRECTIVES_AST = exports.METADATA_DIRECTIVE_NAMES = exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = exports.ASYNC_ITERABLE_ARG = exports.TS_MODULE_PATH_ARG = exports.FIELD_NAME_ARG = exports.EXPORT_NAME_ARG = exports.FIELD_METADATA_DIRECTIVE = void 0;
exports.addMetadataDirectives = addMetadataDirectives;
exports.makeKillsParentOnExceptionDirective = makeKillsParentOnExceptionDirective;
exports.parseFieldMetadataDirective = parseFieldMetadataDirective;
var graphql_1 = require("graphql");
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";

@@ -41,7 +45,6 @@ exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = "killsParentOnException";

]);
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. For\n function-backed fields, this is the function's export 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 Number of arguments. No value means property access\n \"\"\"\n ").concat(exports.ARG_COUNT, ": Int\n \"\"\"\n Whether the field is an async iterable. If true, the argument's\n location is the typescript AsyncIterable identifier.\n \"\"\"\n ").concat(exports.ASYNC_ITERABLE_ARG, ": Boolean\n ) on FIELD_DEFINITION\n directive @").concat(exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE, " on FIELD_DEFINITION\n"));
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 ) 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.addMetadataDirectives = addMetadataDirectives;
function makeKillsParentOnExceptionDirective(loc) {

@@ -51,26 +54,21 @@ return {

loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE },
name: {
kind: graphql_1.Kind.NAME,
loc: loc,
value: exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE,
tsIdentifier: (0, helpers_1.uniqueId)(),
},
arguments: [],
};
}
exports.makeKillsParentOnExceptionDirective = makeKillsParentOnExceptionDirective;
function parseFieldMetadataDirective(directive) {
var _a;
if (directive.name.value !== exports.FIELD_METADATA_DIRECTIVE) {
throw new Error("Expected directive to be ".concat(exports.FIELD_METADATA_DIRECTIVE));
}
var asyncIterableNode = (_a = directive.arguments) === null || _a === void 0 ? void 0 : _a.find(function (arg) { return arg.name.value === exports.ASYNC_ITERABLE_ARG; });
if ((asyncIterableNode === null || asyncIterableNode === void 0 ? void 0 : asyncIterableNode.value.kind) === graphql_1.Kind.BOOLEAN) {
if (!asyncIterableNode.value.value) {
throw new Error("Expected ".concat(exports.ASYNC_ITERABLE_ARG, " to be true"));
}
}
return {
name: getStringArg(directive, exports.FIELD_NAME_ARG),
tsModulePath: getStringArg(directive, exports.TS_MODULE_PATH_ARG),
argCount: getIntArg(directive, exports.ARG_COUNT),
asyncIterable: asyncIterableNode === null || asyncIterableNode === void 0 ? void 0 : asyncIterableNode.loc,
exportName: getStringArg(directive, exports.EXPORT_NAME_ARG),
};
}
exports.parseFieldMetadataDirective = parseFieldMetadataDirective;
function getStringArg(directive, argName) {

@@ -87,12 +85,1 @@ var _a;

}
function getIntArg(directive, argName) {
var _a;
var arg = (_a = directive.arguments) === null || _a === void 0 ? void 0 : _a.find(function (arg) { return arg.name.value === argName; });
if (!arg) {
return null;
}
if (arg.value.kind !== graphql_1.Kind.INT) {
throw new Error("Expected argument ".concat(argName, " to be an int"));
}
return parseInt(arg.value.value, 10);
}
import { DocumentNode, GraphQLSchema } from "graphql";
import { ConfigOptions } from "./gratsConfig";
import { GratsConfig } from "./gratsConfig";
/**

@@ -7,4 +7,4 @@ * 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;
export declare function printExecutableSchema(schema: GraphQLSchema, config: GratsConfig, destination: string): string;
export declare function applyTypeScriptHeader(config: GratsConfig, code: string): string;
/**

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

*/
export declare function printGratsSDL(doc: DocumentNode, config: ConfigOptions): string;
export declare function applySDLHeader(config: ConfigOptions, sdl: string): string;
export declare function printGratsSDL(doc: DocumentNode, config: GratsConfig): string;
export declare function applySDLHeader(config: GratsConfig, sdl: string): string;
export declare function printSDLWithoutMetadata(doc: DocumentNode): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.printSDLWithoutMetadata = exports.applySDLHeader = exports.printGratsSDL = exports.applyTypeScriptHeader = exports.printExecutableSchema = void 0;
exports.printExecutableSchema = printExecutableSchema;
exports.applyTypeScriptHeader = applyTypeScriptHeader;
exports.printGratsSDL = printGratsSDL;
exports.applySDLHeader = applySDLHeader;
exports.printSDLWithoutMetadata = printSDLWithoutMetadata;
var graphql_1 = require("graphql");

@@ -12,10 +16,8 @@ var codegen_1 = require("./codegen");

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

@@ -29,7 +31,5 @@ * Prints SDL, potentially omitting directives depending upon the config.

}
exports.printGratsSDL = printGratsSDL;
function applySDLHeader(config, sdl) {
return formatHeader(config.schemaHeader, sdl);
}
exports.applySDLHeader = applySDLHeader;
function printSDLWithoutMetadata(doc) {

@@ -51,3 +51,2 @@ var trimmed = (0, graphql_1.visit)(doc, {

}
exports.printSDLWithoutMetadata = printSDLWithoutMetadata;
function formatHeader(header, code) {

@@ -54,0 +53,0 @@ if (header !== null) {

@@ -28,4 +28,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.makeSemanticNonNullDirective = exports.addSemanticNonNullDirective = exports.DIRECTIVES_AST = exports.SEMANTIC_NON_NULL_DIRECTIVE = void 0;
exports.DIRECTIVES_AST = exports.SEMANTIC_NON_NULL_DIRECTIVE = void 0;
exports.addSemanticNonNullDirective = addSemanticNonNullDirective;
exports.makeSemanticNonNullDirective = makeSemanticNonNullDirective;
var graphql_1 = require("graphql");
var helpers_1 = require("./utils/helpers");
/**

@@ -42,3 +45,2 @@ * Grats supports some additional, non-spec server directives in order to

}
exports.addSemanticNonNullDirective = addSemanticNonNullDirective;
function makeSemanticNonNullDirective(loc) {

@@ -48,5 +50,9 @@ return {

loc: loc,
name: { kind: graphql_1.Kind.NAME, loc: loc, value: exports.SEMANTIC_NON_NULL_DIRECTIVE },
name: {
kind: graphql_1.Kind.NAME,
loc: loc,
value: exports.SEMANTIC_NON_NULL_DIRECTIVE,
tsIdentifier: (0, helpers_1.uniqueId)(),
},
};
}
exports.makeSemanticNonNullDirective = makeSemanticNonNullDirective;
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[]>;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.addInterfaceFields = void 0;
exports.addInterfaceFields = addInterfaceFields;
var E = require("../Errors");

@@ -51,6 +51,6 @@ var graphql_1 = require("graphql");

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);
}

@@ -78,3 +78,2 @@ else {

}
exports.addInterfaceFields = addInterfaceFields;
// A field definition may be on a concrete type, or on an interface. If it's on an interface,

@@ -84,5 +83,5 @@ // we need to add it to each concrete type that implements the interface.

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") {

@@ -92,2 +91,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) {

@@ -98,4 +98,4 @@ case "TYPE":

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

@@ -109,3 +109,3 @@ });

// 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) {
var directives = (_c = field.directives) === null || _c === void 0 ? void 0 : _c.filter(function (directive) {
return directive.name.value !== metadataDirectives_1.FIELD_METADATA_DIRECTIVE;

@@ -115,8 +115,8 @@ });

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 = {

@@ -126,2 +126,3 @@ kind: graphql_1.Kind.NAME,

loc: doc.loc, // Bit of a lie, but I don't see a better option.
tsIdentifier: (0, helpers_1.uniqueId)(),
};

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

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

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

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

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

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

@@ -162,15 +163,7 @@ 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, 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, "`.")),
]),
]);
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, "`.")),
]));
}

@@ -177,0 +170,0 @@ }

import { DocumentNode } from "graphql";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { ConfigOptions } from "../gratsConfig";
import { GratsConfig } from "../gratsConfig";
/**

@@ -8,2 +8,2 @@ * Grats has options to make all fields nullable by default to conform to

*/
export declare function applyDefaultNullability(doc: DocumentNode, { nullableByDefault, strictSemanticNullability }: ConfigOptions): DiagnosticsResult<DocumentNode>;
export declare function applyDefaultNullability(doc: DocumentNode, { nullableByDefault, strictSemanticNullability }: GratsConfig): DiagnosticsResult<DocumentNode>;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.applyDefaultNullability = void 0;
exports.applyDefaultNullability = applyDefaultNullability;
var graphql_1 = require("graphql");

@@ -96,2 +96,1 @@ var DiagnosticError_1 = require("../utils/DiagnosticError");

}
exports.applyDefaultNullability = applyDefaultNullability;

@@ -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[];

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.filterNonGqlInterfaces = void 0;
exports.filterNonGqlInterfaces = filterNonGqlInterfaces;
var graphql_1 = require("graphql");

@@ -23,12 +23,13 @@ /**

*/
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;
});
}
exports.filterNonGqlInterfaces = filterNonGqlInterfaces;
function filterInterfaces(ctx, t) {

@@ -35,0 +36,0 @@ if (t.interfaces == null || t.interfaces.length === 0) {

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeExtensions = void 0;
exports.mergeExtensions = mergeExtensions;
var graphql_1 = require("graphql");

@@ -94,3 +94,2 @@ var helpers_1 = require("../utils/helpers");

}
exports.mergeExtensions = mergeExtensions;
// Map a key to an array of values.

@@ -97,0 +96,0 @@ var MultiMap = /** @class */ (function () {

@@ -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;
exports.resolveTypes = resolveTypes;
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);
}
/**
* 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, Result_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, Result_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 });
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSnapshotsFromProgram = void 0;
exports.extractSnapshotsFromProgram = extractSnapshotsFromProgram;
var ts = require("typescript");

@@ -49,2 +49,1 @@ var Extractor_1 = require("../Extractor");

}
exports.extractSnapshotsFromProgram = extractSnapshotsFromProgram;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.sortSchemaAst = void 0;
exports.sortSchemaAst = sortSchemaAst;
var graphql_1 = require("graphql");

@@ -65,3 +65,2 @@ var naturalCompare_1 = require("../utils/naturalCompare");

}
exports.sortSchemaAst = sortSchemaAst;
// Given an optional array of AST nodes, sort them by name or kind.

@@ -68,0 +67,0 @@ function sortNamed(arr) {

@@ -39,4 +39,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.initTsPlugin = void 0;
exports.initTsPlugin = initTsPlugin;
var typescript_1 = require("typescript");
var Extractor_1 = require("../Extractor");
var DiagnosticError_1 = require("../utils/DiagnosticError");
var helpers_1 = require("../utils/helpers");
// An experimental plugin for TypeScript that adds a new language service

@@ -78,2 +81,18 @@ // which reports diagnostics for the current file. Currently it only reports

}
if (ts.version !== typescript_1.version) {
proxy.getCompilerOptionsDiagnostics = function () {
var prev = info.languageService.getCompilerOptionsDiagnostics();
return __spreadArray(__spreadArray([], __read(prev), false), [
{
category: ts.DiagnosticCategory.Error,
code: 0,
messageText: typeScriptVersionMismatch(ts.version),
file: undefined,
start: undefined,
length: undefined,
},
], false);
};
return proxy;
}
proxy.getSyntacticDiagnostics = function (filename) {

@@ -90,2 +109,32 @@ var _a;

};
proxy.getSupportedCodeFixes = function (fileName) {
info.project.projectService.logger.info("Grats: getSupportedCodeFixes called with ".concat(fileName));
return __spreadArray(__spreadArray([], __read(info.languageService.getSupportedCodeFixes(fileName)), false), [
String(DiagnosticError_1.FAKE_ERROR_CODE),
], false);
};
proxy.getCodeFixesAtPosition = function (fileName, start, end, errorCodes, formatOptions, preferences) {
var _a;
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition called with ".concat(fileName, " and ").concat(errorCodes));
var prior = info.languageService.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
var doc = (_a = info.languageService.getProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFile(fileName);
if (doc == null)
return prior;
var result = (0, Extractor_1.extract)(doc);
if (result.kind === "OK")
return prior;
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition got ".concat(result.err.length, " errors in ").concat(fileName));
var relatedDiagnostics = result.err.filter(function (err) {
return (err.fix != null &&
err.start === start &&
err.length === end - start &&
err.file.fileName === doc.fileName &&
errorCodes.includes(err.code));
});
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition matched ".concat(relatedDiagnostics.length, " errors in ").concat(fileName));
var fixes = relatedDiagnostics.map(function (err) {
return (0, helpers_1.nullThrows)(err.fix);
});
return __spreadArray(__spreadArray([], __read(prior), false), __read(fixes), false);
};
return proxy;

@@ -95,2 +144,4 @@ }

}
exports.initTsPlugin = initTsPlugin;
function typeScriptVersionMismatch(extensionVersion) {
return "grats-plugin-ts error: The version of TypeScript picked up by Grats does not match the version used by VSCode.\nGrats is using ".concat(typescript_1.version, " but VSCode is using ").concat(extensionVersion, ".\nThis may be caused by a yarn.lock or package-lock.json which is pinning a different version of TypeScript for Grats than the version used by the rest of your project.\nSee https://github.com/captbaritone/grats/issues/142> for more information.");
}

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

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";

@@ -8,4 +8,5 @@ export declare const UNRESOLVED_REFERENCE_NAME = "__UNRESOLVED_REFERENCE__";

name: NameNode;
kind: "TYPE" | "INTERFACE" | "UNION" | "SCALAR" | "INPUT_OBJECT" | "ENUM";
kind: "TYPE" | "INTERFACE" | "UNION" | "SCALAR" | "INPUT_OBJECT" | "ENUM" | "CONTEXT" | "INFO";
};
type TsIdentifier = number;
/**

@@ -25,13 +26,21 @@ * Used to track TypeScript references.

checker: ts.TypeChecker;
_symbolToName: Map<ts.Symbol, NameDefinition>;
_unresolvedTypes: Map<NameNode, ts.Symbol>;
_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);
_recordTypeName(node: ts.Node, name: NameNode, kind: NameDefinition["kind"]): void;
_markUnresolvedType(node: ts.Node, name: NameNode): void;
private _recordTypeName;
private _markUnresolvedType;
allNameDefinitions(): Iterable<NameDefinition>;
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 {};

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

function TypeContext(checker) {
this._symbolToName = new Map();
this._unresolvedTypes = new Map();
this._declarationToName = new Map();
this._unresolvedNodes = new Map();
this._idToDeclaration = new Map();
this.checker = checker;

@@ -101,22 +102,12 @@ }

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.");
}
if (this._symbolToName.has(symbol)) {
// Ensure we never try to record the same name twice.
throw new Error("Unexpected double recording of typename.");
}
this._symbolToName.set(symbol, { name: name, kind: kind });
this._idToDeclaration.set(name.tsIdentifier, node);
this._declarationToName.set(node, { name: name, kind: kind });
};
// Record that a type reference `node`
// Record that a type references `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.");
}
this._unresolvedTypes.set(name, this.resolveSymbol(symbol));
this._unresolvedNodes.set(name.tsIdentifier, node);
};
TypeContext.prototype.allNameDefinitions = function () {
return this._declarationToName.values();
};
TypeContext.prototype.findSymbolDeclaration = function (startSymbol) {

@@ -142,41 +133,104 @@ 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.");
}
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) {
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), E.unresolvedTypeReference()));
}
if (nameDefinition.kind === "CONTEXT" || nameDefinition.kind === "INFO") {
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), E.contextOrInfoUsedInGraphQLPosition(nameDefinition.kind), [(0, DiagnosticError_1.gqlRelated)((0, helpers_1.loc)(nameDefinition.name), "Defined here")]));
}
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, Result_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);
var definition = this._declarationToName.get(declaration);
if (definition == null) {
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(nameNode), E.unresolvedTypeReference()));
}
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) {
// This should have already been handled by resolveNamedType
throw new Error("Expected to find name definition.");
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.unresolvedTypeReference()));
}
return (0, Result_1.ok)(nameDefinition);
if (nameDefinition.kind === "CONTEXT" || nameDefinition.kind === "INFO") {
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.contextOrInfoUsedInGraphQLPosition(nameDefinition.kind), [
(0, DiagnosticError_1.gqlRelated)((0, helpers_1.loc)(nameDefinition.name), "Defined here"),
]));
}
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;

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

import type { GraphQLResolveInfo } from "graphql";
/** @gqlScalar */

@@ -7,1 +8,3 @@ export type Float = number;

export type ID = string;
/** @gqlInfo */
export type GqlInfo = GraphQLResolveInfo;
import { GraphQLError, Location, Source } from "graphql";
import * as ts from "typescript";
import { Result } from "./Result";
export type DiagnosticResult<T> = Result<T, ts.DiagnosticWithLocation>;
export type DiagnosticsResult<T> = Result<T, ts.DiagnosticWithLocation[]>;
type FixableDiagnostic = ts.Diagnostic & {
fix?: ts.CodeFixAction;
};
export type FixableDiagnosticWithLocation = ts.DiagnosticWithLocation & {
fix?: ts.CodeFixAction;
};
export type DiagnosticResult<T> = Result<T, FixableDiagnosticWithLocation>;
export type DiagnosticsResult<T> = Result<T, FixableDiagnosticWithLocation[]>;
export type DiagnosticsWithoutLocationResult<T> = Result<T, ts.Diagnostic[]>;
export declare class ReportableDiagnostics {
_host: ts.FormatDiagnosticsHost;
_diagnostics: ts.Diagnostic[];
constructor(host: ts.FormatDiagnosticsHost, diagnostics: ts.Diagnostic[]);
_diagnostics: FixableDiagnostic[];
constructor(host: ts.FormatDiagnosticsHost, diagnostics: FixableDiagnostic[]);
static fromDiagnostics(diagnostics: ts.Diagnostic[]): ReportableDiagnostics;

@@ -15,9 +21,22 @@ formatDiagnosticsWithColorAndContext(): string;

}
export declare const FAKE_ERROR_CODE = 349389149282;
export declare const FAKE_ERROR_CODE = 1038;
export declare function graphQlErrorToDiagnostic(error: GraphQLError): 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 rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function tsErr(node: ts.Node, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[], fix?: ts.CodeFixAction): FixableDiagnosticWithLocation;
/**
* 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[], fix?: ts.CodeFixAction): FixableDiagnosticWithLocation;
export declare function tsRelated(node: ts.Node, message: string): ts.DiagnosticRelatedInformation;
export declare function graphqlSourceToSourceFile(source: Source): ts.SourceFile;
export {};

@@ -30,3 +30,10 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.graphqlSourceToSourceFile = exports.tsRelated = exports.tsErr = exports.rangeErr = exports.gqlRelated = exports.gqlErr = exports.graphQlErrorToDiagnostic = exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = void 0;
exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = void 0;
exports.graphQlErrorToDiagnostic = graphQlErrorToDiagnostic;
exports.gqlErr = gqlErr;
exports.gqlRelated = gqlRelated;
exports.rangeErr = rangeErr;
exports.tsErr = tsErr;
exports.tsRelated = tsRelated;
exports.graphqlSourceToSourceFile = graphqlSourceToSourceFile;
var ts = require("typescript");

@@ -63,3 +70,3 @@ var ReportableDiagnostics = /** @class */ (function () {

// We pick a very random number to avoid collisions with real error messages.
exports.FAKE_ERROR_CODE = 349389149282;
exports.FAKE_ERROR_CODE = 1038;
function stripColor(str) {

@@ -125,3 +132,2 @@ // eslint-disable-next-line no-control-regex

}
exports.graphQlErrorToDiagnostic = graphQlErrorToDiagnostic;
function gqlErr(loc, message, relatedInformation) {

@@ -139,3 +145,2 @@ return {

}
exports.gqlErr = gqlErr;
function gqlRelated(loc, message) {

@@ -151,4 +156,3 @@ return {

}
exports.gqlRelated = gqlRelated;
function rangeErr(file, commentRange, message, relatedInformation) {
function rangeErr(file, commentRange, message, relatedInformation, fix) {
var start = commentRange.pos;

@@ -165,6 +169,6 @@ var length = commentRange.end - commentRange.pos;

source: "Grats",
fix: fix,
};
}
exports.rangeErr = rangeErr;
function tsErr(node, message, relatedInformation) {
function tsErr(node, message, relatedInformation, fix) {
var start = node.getStart();

@@ -182,5 +186,5 @@ var length = node.getEnd() - start;

source: "Grats",
fix: fix,
};
}
exports.tsErr = tsErr;
function tsRelated(node, message) {

@@ -196,6 +200,4 @@ return {

}
exports.tsRelated = tsRelated;
function graphqlSourceToSourceFile(source) {
return ts.createSourceFile(source.name, source.body, ts.ScriptTarget.Latest);
}
exports.graphqlSourceToSourceFile = graphqlSourceToSourceFile;

@@ -15,1 +15,4 @@ import { Location } from "graphql";

}): T;
export declare function uniqueId(): number;
export declare function invariant(condition: unknown, message: string): asserts condition;
export declare function nullThrows<T>(value: T | null | undefined): T;

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

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

@@ -48,3 +54,2 @@ function DefaultMap(getDefault) {

}
exports.extend = extend;
function loc(item) {

@@ -56,3 +61,2 @@ if (item.loc == null) {

}
exports.loc = loc;
function astNode(item) {

@@ -64,2 +68,16 @@ if (item.astNode == null) {

}
exports.astNode = astNode;
var i = 0;
function uniqueId() {
return i++;
}
function invariant(condition, message) {
if (!condition) {
throw new Error("Grats Error. Invariant failed: ".concat(message, ". This error represents an error in Grats. Please report it."));
}
}
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;
}

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.traverseJSDocTags = void 0;
exports.traverseJSDocTags = traverseJSDocTags;
var ts = require("typescript");

@@ -51,2 +51,1 @@ // Recursively search for all JSDoc tags calling `cb` on each one with its

}
exports.traverseJSDocTags = traverseJSDocTags;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.naturalCompare = void 0;
exports.naturalCompare = naturalCompare;
/**

@@ -52,3 +52,2 @@ * Returns a number indicating whether a reference string comes before, or after,

}
exports.naturalCompare = naturalCompare;
var DIGIT_0 = 48;

@@ -55,0 +54,0 @@ var DIGIT_9 = 57;

@@ -39,3 +39,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.concatResults = exports.collectResults = exports.ResultPipe = exports.err = exports.ok = void 0;
exports.ResultPipe = void 0;
exports.ok = ok;
exports.err = err;
exports.collectResults = collectResults;
exports.concatResults = concatResults;
// Create a new `Result` in an OK state.

@@ -45,3 +49,2 @@ function ok(value) {

}
exports.ok = ok;
// Create a new `Result` in an ERROR state.

@@ -51,3 +54,2 @@ function err(err) {

}
exports.err = err;
/**

@@ -117,3 +119,2 @@ * Helper class for chaining together a series of `Result` operations.

}
exports.collectResults = collectResults;
function concatResults(result1, result2) {

@@ -131,2 +132,1 @@ if (result1.kind === "ERROR" && result2.kind === "ERROR") {

}
exports.concatResults = concatResults;
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<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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAsyncIterable = void 0;
exports.validateAsyncIterable = validateAsyncIterable;
var graphql_1 = require("graphql");

@@ -19,7 +19,6 @@ var DiagnosticError_1 = require("../utils/DiagnosticError");

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.
*/

@@ -29,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,

@@ -41,2 +59,3 @@ _a[graphql_1.Kind.INTERFACE_TYPE_EXTENSION] = visitNode,

_a[graphql_1.Kind.OBJECT_TYPE_EXTENSION] = visitNode,
_a[graphql_1.Kind.FIELD_DEFINITION] = visitSubscriptionField,
_a));

@@ -46,44 +65,12 @@ if (errors.length > 0) {

}
return (0, Result_1.ok)(doc);
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);
var isInterface = t.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION ||
t.kind === graphql_1.Kind.INTERFACE_TYPE_EXTENSION;
try {
for (var _c = __values(t.fields), _d = _c.next(); !_d.done; _d = _c.next()) {
var field = _d.value;
var metadataDirective = (_b = field.directives) === null || _b === void 0 ? void 0 : _b.find(function (directive) { return directive.name.value === metadataDirectives_1.FIELD_METADATA_DIRECTIVE; });
if (isInterface && metadataDirective == null) {
return;
}
if (metadataDirective == null) {
throw new Error("Expected to find metadata directive on non-interface field \"".concat(t.name.value, ".").concat(field.name.value, "\"."));
}
var asyncIterable = (0, metadataDirectives_1.parseFieldMetadataDirective)(metadataDirective).asyncIterable;
if (isSubscription && !asyncIterable) {
return (0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(field.type), E.subscriptionFieldNotAsyncIterable());
}
if (!isSubscription && asyncIterable) {
return (0, DiagnosticError_1.gqlErr)(asyncIterable, // Arg location is the AsyncIterable type reference.
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;
}

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateMergedInterfaces = void 0;
exports.validateMergedInterfaces = validateMergedInterfaces;
var ts = require("typescript");

@@ -70,2 +70,1 @@ var E = require("../Errors");

}
exports.validateMergedInterfaces = validateMergedInterfaces;
import { GraphQLSchema } from "graphql";
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
import { ConfigOptions } from "../gratsConfig";
import { GratsConfig } from "../gratsConfig";
/**

@@ -8,2 +8,2 @@ * Ensure that all semantically non-nullable fields on an interface are also

*/
export declare function validateSemanticNullability(schema: GraphQLSchema, config: ConfigOptions): DiagnosticsWithoutLocationResult<GraphQLSchema>;
export declare function validateSemanticNullability(schema: GraphQLSchema, config: GratsConfig): DiagnosticsWithoutLocationResult<GraphQLSchema>;

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSemanticNullability = void 0;
exports.validateSemanticNullability = validateSemanticNullability;
var graphql_1 = require("graphql");

@@ -97,3 +97,2 @@ var DiagnosticError_1 = require("../utils/DiagnosticError");

}
exports.validateSemanticNullability = validateSemanticNullability;
function findSemanticNonNull(field) {

@@ -100,0 +99,0 @@ var _a, _b;

@@ -14,6 +14,8 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTypenames = void 0;
exports.validateTypenames = validateTypenames;
var graphql_1 = require("graphql");
var DiagnosticError_1 = require("../utils/DiagnosticError");
var Result_1 = require("../utils/Result");
var helpers_1 = require("../utils/helpers");
var E = require("../Errors");
/**

@@ -25,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);

@@ -32,3 +33,2 @@ try {

var type = abstractTypes_1_1.value;
// TODO: If we already implement resolveType, we don't need to check implementors
var typeImplementors = schema.getPossibleTypes(type).filter(graphql_1.isType);

@@ -38,9 +38,20 @@ 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) && ast.exported == null) {
var message = type instanceof graphql_1.GraphQLInterfaceType
? E.concreteTypenameImplementingInterfaceCannotBeResolved(implementor.name, type.name)
: E.concreteTypenameInUnionCannotBeResolved(implementor.name, type.name);
var err_1 = (0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(ast.name), message, [
(0, DiagnosticError_1.gqlRelated)((0, helpers_1.loc)((0, helpers_1.nullThrows)(type.astNode).name), "".concat(type.name, " is defined here:")),
]);
errors.push(err_1);
}
}

@@ -64,7 +75,6 @@ }

}
if (typenameDiagnostics.length > 0) {
return (0, Result_1.err)(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-a7f15f89",
"version": "0.0.0-main-a8ec3e2a",
"main": "dist/src/index.js",

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

"commander": "^10.0.0",
"graphql": "^16.6.0",
"typescript": "^5.0.2"
"graphql": "^16.9.0",
"typescript": "5.5.4"
},

@@ -36,6 +36,5 @@ "devDependencies": {

},
"packageManager": "pnpm@8.12.0",
"engines": {
"node": ">=16 <=21",
"pnpm": "^8"
"pnpm": ">=8 <=9"
},

@@ -42,0 +41,0 @@ "bugs": {

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

**What if building a GraphQL server were as simple as just writing functions?**
**The simplest way to build a GraphQL server in TypeScript**

@@ -19,2 +19,4 @@ When you write your GraphQL server in TypeScript, your fields and resolvers

Read the [blog post](https://jordaneldredge.com/blog/grats).
## Example

@@ -62,1 +64,5 @@

- [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