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

graphql-codegen-visitor-plugin-common

Package Overview
Dependencies
Maintainers
1
Versions
123
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-codegen-visitor-plugin-common - npm Package Compare versions

Comparing version 0.19.0-alpha.89ed12b6 to 0.19.0-alpha.8e3376c3

cjs/index.js

15

dist/base-documents-visitor.d.ts

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

import { ScalarsMap } from './types';
import { ScalarsMap, NamingConvention, ConvertFn, ConvertOptions } from './types';
import { DeclarationBlockConfig } from './utils';
import { GraphQLSchema, FragmentDefinitionNode, OperationDefinitionNode } from 'graphql';
import { GraphQLSchema, FragmentDefinitionNode, OperationDefinitionNode, ASTNode } from 'graphql';
import { SelectionSetToObject } from './selection-set-to-object';
import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitorConvertOptions } from './base-visitor';
export interface ParsedDocumentsConfig {
scalars: ScalarsMap;
convert: (str: string) => string;
convert: ConvertFn<ConvertOptions>;
typesPrefix: string;

@@ -14,3 +15,3 @@ addTypename: boolean;

scalars?: ScalarsMap;
namingConvention?: string;
namingConvention?: NamingConvention;
typesPrefix?: string;

@@ -30,3 +31,3 @@ skipTypename?: boolean;

setVariablesTransformer(variablesTransfomer: OperationVariablesToObject): void;
convertName(name: any, addPrefix?: boolean): string;
convertName(node: ASTNode | string, options?: ConvertOptions & BaseVisitorConvertOptions): string;
readonly config: TPluginConfig;

@@ -37,4 +38,4 @@ readonly schema: GraphQLSchema;

private handleAnonymouseOperation;
FragmentDefinition: (node: FragmentDefinitionNode) => string;
OperationDefinition: (node: OperationDefinitionNode) => string;
FragmentDefinition(node: FragmentDefinitionNode): string;
OperationDefinition(node: OperationDefinitionNode): string;
}

@@ -1,19 +0,6 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var autoBind = require("auto-bind");
var graphql_codegen_plugin_helpers_1 = require("graphql-codegen-plugin-helpers");
var scalars_1 = require("./scalars");
var utils_1 = require("./utils");
var variables_to_object_1 = require("./variables-to-object");
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { toPascalCase, DeclarationBlock } from './utils';
import { OperationVariablesToObject } from './variables-to-object';
import { convertFactory } from './naming';
function getRootType(operation, schema) {

@@ -29,89 +16,83 @@ switch (operation) {

}
var BaseDocumentsVisitor = /** @class */ (function () {
function BaseDocumentsVisitor(rawConfig, additionalConfig, _schema, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
var _this = this;
export class BaseDocumentsVisitor {
constructor(rawConfig, additionalConfig, _schema, defaultScalars = DEFAULT_SCALARS) {
this._schema = _schema;
this._declarationBlockConfig = {};
this._unnamedCounter = 1;
this.FragmentDefinition = function (node) {
var fragmentRootType = _this._schema.getType(node.typeCondition.name.value);
var selectionSet = _this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
return new utils_1.DeclarationBlock(_this._declarationBlockConfig)
.export()
.asKind('type')
.withName(_this.convertName(node.name.value + 'Fragment', true))
.withContent(selectionSet.string).string;
};
this.OperationDefinition = function (node) {
var name = _this.handleAnonymouseOperation(node.name && node.name.value ? node.name.value : null);
var operationRootType = getRootType(node.operation, _this._schema);
var selectionSet = _this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
var visitedOperationVariables = _this._variablesTransfomer.transform(node.variableDefinitions);
var operationResult = new utils_1.DeclarationBlock(_this._declarationBlockConfig)
.export()
.asKind('type')
.withName(_this.convertName(name + utils_1.toPascalCase(node.operation)))
.withContent(selectionSet.string).string;
var operationVariables = new utils_1.DeclarationBlock(_this._declarationBlockConfig)
.export()
.asKind('type')
.withName(_this.convertName(name + utils_1.toPascalCase(node.operation) + 'Variables'))
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(function (r) { return r; }).join('\n\n');
};
this._parsedConfig = __assign({ addTypename: !rawConfig.skipTypename, scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: rawConfig.namingConvention ? graphql_codegen_plugin_helpers_1.resolveExternalModuleAndFn(rawConfig.namingConvention) : utils_1.toPascalCase, typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
this._parsedConfig = Object.assign({ addTypename: !rawConfig.skipTypename, scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
autoBind(this);
this._variablesTransfomer = new variables_to_object_1.OperationVariablesToObject(this.scalars, this.convertName);
this._variablesTransfomer = new OperationVariablesToObject(this.scalars, this.convertName);
}
BaseDocumentsVisitor.prototype.setSelectionSetHandler = function (handler) {
setSelectionSetHandler(handler) {
this._selectionSetToObject = handler;
};
BaseDocumentsVisitor.prototype.setDeclarationBlockConfig = function (config) {
}
setDeclarationBlockConfig(config) {
this._declarationBlockConfig = config;
};
BaseDocumentsVisitor.prototype.setVariablesTransformer = function (variablesTransfomer) {
}
setVariablesTransformer(variablesTransfomer) {
this._variablesTransfomer = variablesTransfomer;
};
BaseDocumentsVisitor.prototype.convertName = function (name, addPrefix) {
if (addPrefix === void 0) { addPrefix = true; }
return (addPrefix ? this._parsedConfig.typesPrefix : '') + this._parsedConfig.convert(name);
};
Object.defineProperty(BaseDocumentsVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "schema", {
get: function () {
return this._schema;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "addTypename", {
get: function () {
return this._parsedConfig.addTypename;
},
enumerable: true,
configurable: true
});
BaseDocumentsVisitor.prototype.handleAnonymouseOperation = function (name) {
}
convertName(node, options) {
const useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this._parsedConfig.typesPrefix : '') + this._parsedConfig.convert(node, options);
}
get config() {
return this._parsedConfig;
}
get schema() {
return this._schema;
}
get scalars() {
return this.config.scalars;
}
get addTypename() {
return this._parsedConfig.addTypename;
}
handleAnonymouseOperation(node) {
const name = node.name && node.name.value;
if (name) {
return this.convertName(name);
return this.convertName(node, {
useTypesPrefix: false
});
}
return this.convertName("Unnamed_" + this._unnamedCounter++ + "_");
};
return BaseDocumentsVisitor;
}());
exports.BaseDocumentsVisitor = BaseDocumentsVisitor;
return this.convertName(this._unnamedCounter++ + '', {
prefix: 'Unnamed_',
suffix: '_',
useTypesPrefix: false
});
}
FragmentDefinition(node) {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node, {
useTypesPrefix: true,
suffix: 'Fragment'
}))
.withContent(selectionSet.string).string;
}
OperationDefinition(node) {
const name = this.handleAnonymouseOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform(node.variableDefinitions);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(name, {
suffix: toPascalCase(node.operation)
}))
.withContent(selectionSet.string).string;
const operationVariables = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(name, {
suffix: toPascalCase(node.operation) + 'Variables'
}))
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
}
//# sourceMappingURL=base-documents-visitor.js.map

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

import { ScalarsMap } from './types';
import { ScalarsMap, NamingConvention, ConvertFn, ConvertOptions } from './types';
import { DeclarationBlockConfig } from './utils';

@@ -7,2 +7,3 @@ import { NameNode, ListTypeNode, NamedTypeNode, FieldDefinitionNode, ObjectTypeDefinitionNode, GraphQLSchema } from 'graphql';

import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitorConvertOptions } from './base-visitor';
interface ParsedMapper {

@@ -15,3 +16,3 @@ isExternal: boolean;

scalars: ScalarsMap;
convert: (str: string) => string;
convert: ConvertFn;
typesPrefix: string;

@@ -29,3 +30,3 @@ contextType: string;

scalars?: ScalarsMap;
namingConvention?: string;
namingConvention?: NamingConvention;
typesPrefix?: string;

@@ -40,2 +41,5 @@ }

};
protected _collectedDirectiveResolvers: {
[key: string]: string;
};
protected _variablesTransfomer: OperationVariablesToObject;

@@ -51,7 +55,8 @@ constructor(rawConfig: TRawConfig, additionalConfig: TPluginConfig, _schema: GraphQLSchema, defaultScalars?: ScalarsMap);

protected buildMapperImport(source: string, types: string[]): string;
convertName(name: any, addPrefix?: boolean): string;
convertName(name: any, options?: ConvertOptions & BaseVisitorConvertOptions): string;
setDeclarationBlockConfig(config: DeclarationBlockConfig): void;
setVariablesTransformer(variablesTransfomer: OperationVariablesToObject): void;
readonly rootResolver: string;
getRootResolver(): string;
protected formatRootResolver(schemaTypeName: string, resolverType: string): string;
getAllDirectiveResolvers(): string;
Name(node: NameNode): string;

@@ -61,3 +66,3 @@ ListType(node: ListTypeNode): string;

NonNullType(node: NonNullTypeNode): string;
FieldDefinition(node: FieldDefinitionNode, key: string | number, parent: any): (parentName: any) => string;
FieldDefinition(node: FieldDefinitionNode, key: string | number, parent: any): (parentName: string) => string;
ObjectTypeDefinition(node: ObjectTypeDefinitionNode): string;

@@ -68,3 +73,4 @@ UnionTypeDefinition(node: UnionTypeDefinitionNode, key: string | number, parent: any): string;

InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode): string;
SchemaDefinition(): any;
}
export {};

@@ -1,40 +0,27 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_codegen_plugin_helpers_1 = require("graphql-codegen-plugin-helpers");
var autoBind = require("auto-bind");
var scalars_1 = require("./scalars");
var utils_1 = require("./utils");
var graphql_1 = require("graphql");
var variables_to_object_1 = require("./variables-to-object");
var BaseResolversVisitor = /** @class */ (function () {
function BaseResolversVisitor(rawConfig, additionalConfig, _schema, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, indent, getBaseTypeNode } from './utils';
import { GraphQLObjectType } from 'graphql';
import { OperationVariablesToObject } from './variables-to-object';
import { convertFactory } from './naming';
export class BaseResolversVisitor {
constructor(rawConfig, additionalConfig, _schema, defaultScalars = DEFAULT_SCALARS) {
this._schema = _schema;
this._declarationBlockConfig = {};
this._collectedResolvers = {};
this._parsedConfig = __assign({ scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: rawConfig.namingConvention ? graphql_codegen_plugin_helpers_1.resolveExternalModuleAndFn(rawConfig.namingConvention) : utils_1.toPascalCase, typesPrefix: rawConfig.typesPrefix || '', contextType: rawConfig.contextType || 'any', mappers: this.transformMappers(rawConfig.mappers || {}) }, (additionalConfig || {}));
this._collectedDirectiveResolvers = {};
this._parsedConfig = Object.assign({ scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '', contextType: rawConfig.contextType || 'any', mappers: this.transformMappers(rawConfig.mappers || {}) }, (additionalConfig || {}));
autoBind(this);
this._variablesTransfomer = new variables_to_object_1.OperationVariablesToObject(this.scalars, this.convertName);
this._variablesTransfomer = new OperationVariablesToObject(this.scalars, this.convertName);
}
BaseResolversVisitor.prototype.isExternalMapper = function (value) {
isExternalMapper(value) {
return value.includes('#');
};
BaseResolversVisitor.prototype.parseMapper = function (mapper) {
}
parseMapper(mapper) {
if (this.isExternalMapper(mapper)) {
var _a = mapper.split('#'), source = _a[0], type = _a[1];
const [source, type] = mapper.split('#');
return {
isExternal: true,
source: source,
type: type
source,
type
};

@@ -46,118 +33,115 @@ }

};
};
BaseResolversVisitor.prototype.transformMappers = function (rawMappers) {
var _this = this;
var result = {};
Object.keys(rawMappers).forEach(function (gqlTypeName) {
var mapperDef = rawMappers[gqlTypeName];
var parsedMapper = _this.parseMapper(mapperDef);
}
transformMappers(rawMappers) {
const result = {};
Object.keys(rawMappers).forEach(gqlTypeName => {
const mapperDef = rawMappers[gqlTypeName];
const parsedMapper = this.parseMapper(mapperDef);
result[gqlTypeName] = parsedMapper;
});
return result;
};
Object.defineProperty(BaseResolversVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "schema", {
get: function () {
return this._schema;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "mappersImports", {
get: function () {
var _this = this;
var groupedMappers = {};
Object.keys(this.config.mappers)
.filter(function (gqlTypeName) { return _this.config.mappers[gqlTypeName].isExternal; })
.forEach(function (gqlTypeName) {
var mapper = _this.config.mappers[gqlTypeName];
if (!groupedMappers[mapper.source]) {
groupedMappers[mapper.source] = [];
}
groupedMappers[mapper.source].push(mapper.type);
});
return Object.keys(groupedMappers).map(function (source) { return _this.buildMapperImport(source, groupedMappers[source]); });
},
enumerable: true,
configurable: true
});
BaseResolversVisitor.prototype.buildMapperImport = function (source, types) {
return "import { " + types.join(', ') + " } from '" + source + "';";
};
BaseResolversVisitor.prototype.convertName = function (name, addPrefix) {
if (addPrefix === void 0) { addPrefix = true; }
return (addPrefix ? this.config.typesPrefix : '') + this.config.convert(name);
};
BaseResolversVisitor.prototype.setDeclarationBlockConfig = function (config) {
}
get config() {
return this._parsedConfig;
}
get schema() {
return this._schema;
}
get scalars() {
return this.config.scalars;
}
get mappersImports() {
const groupedMappers = {};
Object.keys(this.config.mappers)
.filter(gqlTypeName => this.config.mappers[gqlTypeName].isExternal)
.forEach(gqlTypeName => {
const mapper = this.config.mappers[gqlTypeName];
if (!groupedMappers[mapper.source]) {
groupedMappers[mapper.source] = [];
}
groupedMappers[mapper.source].push(mapper.type);
});
return Object.keys(groupedMappers).map(source => this.buildMapperImport(source, groupedMappers[source]));
}
buildMapperImport(source, types) {
return `import { ${types.join(', ')} } from '${source}';`;
}
convertName(name, options) {
const useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this.config.typesPrefix : '') + this.config.convert(name, options);
}
setDeclarationBlockConfig(config) {
this._declarationBlockConfig = config;
};
BaseResolversVisitor.prototype.setVariablesTransformer = function (variablesTransfomer) {
}
setVariablesTransformer(variablesTransfomer) {
this._variablesTransfomer = variablesTransfomer;
};
Object.defineProperty(BaseResolversVisitor.prototype, "rootResolver", {
get: function () {
var _this = this;
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(this.convertName('ResolversRoot'))
.withBlock(Object.keys(this._collectedResolvers)
.map(function (schemaTypeName) {
var resolverType = _this._collectedResolvers[schemaTypeName];
return utils_1.indent(_this.formatRootResolver(schemaTypeName, resolverType));
})
.join('\n')).string;
},
enumerable: true,
configurable: true
});
BaseResolversVisitor.prototype.formatRootResolver = function (schemaTypeName, resolverType) {
return schemaTypeName + "?: " + resolverType + ",";
};
BaseResolversVisitor.prototype.Name = function (node) {
}
getRootResolver() {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName('IResolvers'), `<Context = ${this.config.contextType}>`)
.withBlock(Object.keys(this._collectedResolvers)
.map(schemaTypeName => {
const resolverType = this._collectedResolvers[schemaTypeName];
return indent(this.formatRootResolver(schemaTypeName, resolverType));
})
.join('\n')).string;
}
formatRootResolver(schemaTypeName, resolverType) {
return `${schemaTypeName}?: ${resolverType},`;
}
getAllDirectiveResolvers() {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName('IDirectiveResolvers'), `<Context = ${this.config.contextType}>`)
.withBlock(Object.keys(this._collectedDirectiveResolvers)
.map(schemaTypeName => {
const resolverType = this._collectedDirectiveResolvers[schemaTypeName];
return indent(this.formatRootResolver(schemaTypeName, resolverType));
})
.join('\n')).string;
}
Name(node) {
return node.value;
};
BaseResolversVisitor.prototype.ListType = function (node) {
var asString = node.type;
return "Array<" + asString + ">";
};
BaseResolversVisitor.prototype.NamedType = function (node) {
var asString = node.name;
var type = this.config.scalars[asString] || this.convertName(asString);
return "" + type;
};
BaseResolversVisitor.prototype.NonNullType = function (node) {
var asString = node.type;
}
ListType(node) {
const asString = node.type;
return `Array<${asString}>`;
}
NamedType(node) {
const type = this.config.scalars[node.name] || this.convertName(node);
return `${type}`;
}
NonNullType(node) {
const asString = node.type;
return asString;
};
BaseResolversVisitor.prototype.FieldDefinition = function (node, key, parent) {
var _this = this;
var hasArguments = node.arguments && node.arguments.length > 0;
return function (parentName) {
var original = parent[key];
var realType = utils_1.getBaseTypeNode(original.type).name.value;
var mappedType = _this.config.mappers[realType]
? _this._variablesTransfomer.wrapAstTypeWithModifiers(_this.config.mappers[realType].type, original.type)
}
FieldDefinition(node, key, parent) {
const hasArguments = node.arguments && node.arguments.length > 0;
return (parentName) => {
const original = parent[key];
const realType = getBaseTypeNode(original.type).name.value;
const mappedType = this.config.mappers[realType]
? this._variablesTransfomer.wrapAstTypeWithModifiers(this.config.mappers[realType].type, original.type)
: node.type;
var subscriptionType = _this._schema.getSubscriptionType();
var isSubscriptionType = subscriptionType && subscriptionType.name === parentName;
return utils_1.indent(node.name + "?: " + (isSubscriptionType ? 'SubscriptionResolver' : 'Resolver') + "<" + mappedType + ", ParentType, Context" + (hasArguments ? ", " + (_this.convertName(parentName, true) + _this.convertName(node.name, false) + 'Args') : '') + ">,");
const subscriptionType = this._schema.getSubscriptionType();
const isSubscriptionType = subscriptionType && subscriptionType.name === parentName;
return indent(`${node.name}?: ${isSubscriptionType ? 'SubscriptionResolver' : 'Resolver'}<${mappedType}, ParentType, Context${hasArguments
? `, ${this.convertName(parentName, {
useTypesPrefix: true
}) +
this.convertName(node.name, {
useTypesPrefix: false
}) +
'Args'}`
: ''}>,`);
};
};
BaseResolversVisitor.prototype.ObjectTypeDefinition = function (node) {
var name = this.convertName(node.name + 'Resolvers');
var type = null;
}
ObjectTypeDefinition(node) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
let type = null;
if (this.config.mappers[node.name]) {

@@ -167,57 +151,65 @@ type = this.config.mappers[node.name].type;

else {
type = this.config.scalars[node.name] || this.convertName(node.name);
type = this.config.scalars[node.name] || this.convertName(node);
}
var block = new utils_1.DeclarationBlock(this._declarationBlockConfig)
const block = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + type + ">")
.withBlock(node.fields.map(function (f) { return f(node.name); }).join('\n'));
this._collectedResolvers[node.name] = name;
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${type}>`)
.withBlock(node.fields.map((f) => f(node.name)).join('\n'));
this._collectedResolvers[node.name] = name + '<Context>';
return block.string;
};
BaseResolversVisitor.prototype.UnionTypeDefinition = function (node, key, parent) {
var _this = this;
var name = this.convertName(node.name + 'Resolvers');
var originalNode = parent[key];
var possibleTypes = originalNode.types
.map(function (node) { return _this.convertName(node.name.value); })
.map(function (f) { return "'" + f + "'"; })
}
UnionTypeDefinition(node, key, parent) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
const originalNode = parent[key];
const possibleTypes = originalNode.types
.map(node => this.convertName(node))
.map(f => `'${f}'`)
.join(' | ');
this._collectedResolvers[node.name] = name;
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + node.name + ">")
.withBlock(utils_1.indent("__resolveType: TypeResolveFn<" + possibleTypes + ">")).string;
};
BaseResolversVisitor.prototype.ScalarTypeDefinition = function (node) {
var baseName = this.convertName(node.name);
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${node.name}>`)
.withBlock(indent(`__resolveType: TypeResolveFn<${possibleTypes}>`)).string;
}
ScalarTypeDefinition(node) {
const baseName = this.convertName(node);
this._collectedResolvers[node.name] = 'GraphQLScalarType';
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(this.convertName(node.name + 'ScalarConfig'), " extends GraphQLScalarTypeConfig<" + baseName + ", any>")
.withBlock(utils_1.indent("name: '" + node.name + "'")).string;
};
BaseResolversVisitor.prototype.DirectiveDefinition = function (node) {
var directiveName = this.convertName(node.name + 'DirectiveResolver');
var hasArguments = node.arguments && node.arguments.length > 0;
var directiveArgs = hasArguments
.withName(this.convertName(node, {
suffix: 'ScalarConfig'
}), ` extends GraphQLScalarTypeConfig<${baseName}, any>`)
.withBlock(indent(`name: '${node.name}'`)).string;
}
DirectiveDefinition(node) {
const directiveName = this.convertName(node, {
suffix: 'DirectiveResolver'
});
const hasArguments = node.arguments && node.arguments.length > 0;
const directiveArgs = hasArguments
? this._variablesTransfomer.transform(node.arguments)
: '';
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
this._collectedDirectiveResolvers[node.name] = directiveName + '<any, any, Context>';
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(directiveName, '<Result>')
.withContent("DirectiveResolverFn<Result, { " + directiveArgs + " }, " + this.config.contextType + ">").string;
};
BaseResolversVisitor.prototype.InterfaceTypeDefinition = function (node) {
var name = this.convertName(node.name + 'Resolvers');
var allTypesMap = this._schema.getTypeMap();
var implementingTypes = [];
.withName(directiveName, `<Result, Parent, Context = ${this.config.contextType}, Args = { ${directiveArgs} }>`)
.withContent(`DirectiveResolverFn<Result, Parent, Context, Args>`).string;
}
InterfaceTypeDefinition(node) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
const allTypesMap = this._schema.getTypeMap();
const implementingTypes = [];
this._collectedResolvers[node.name] = name;
for (var _i = 0, _a = Object.values(allTypesMap); _i < _a.length; _i++) {
var graphqlType = _a[_i];
if (graphqlType instanceof graphql_1.GraphQLObjectType) {
var allInterfaces = graphqlType.getInterfaces();
if (allInterfaces.find(function (int) { return int.name === node.name; })) {
for (const graphqlType of Object.values(allTypesMap)) {
if (graphqlType instanceof GraphQLObjectType) {
const allInterfaces = graphqlType.getInterfaces();
if (allInterfaces.find(int => int.name === node.name)) {
implementingTypes.push(graphqlType.name);

@@ -227,12 +219,13 @@ }

}
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + node.name + ">")
.withBlock(utils_1.indent("__resolveType: TypeResolveFn<" + implementingTypes.map(function (name) { return "'" + name + "'"; }).join(' | ') + ">"))
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${node.name}>`)
.withBlock(indent(`__resolveType: TypeResolveFn<${implementingTypes.map(name => `'${name}'`).join(' | ')}>`))
.string;
};
return BaseResolversVisitor;
}());
exports.BaseResolversVisitor = BaseResolversVisitor;
}
SchemaDefinition() {
return null;
}
}
//# sourceMappingURL=base-resolvers-visitor.js.map

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

import { ScalarsMap, EnumValuesMap } from './types';
import { ScalarsMap, NamingConvention, ConvertFn, ConvertOptions } from './types';
import { DeclarationBlockConfig } from './utils';
import { NamedTypeNode, ListTypeNode, NonNullTypeNode, DirectiveDefinitionNode, NameNode, InputObjectTypeDefinitionNode, InputValueDefinitionNode, EnumTypeDefinitionNode, ScalarTypeDefinitionNode } from 'graphql';
import { FieldDefinitionNode, UnionTypeDefinitionNode, ObjectTypeDefinitionNode, InterfaceTypeDefinitionNode, EnumValueDefinitionNode } from 'graphql/language/ast';
import { OperationVariablesToObject } from './variables-to-object';
import { ASTNode } from 'graphql';
export interface BaseVisitorConvertOptions {
useTypesPrefix?: boolean;
}
export interface ParsedConfig {
scalars: ScalarsMap;
enumValues: EnumValuesMap;
convert: (str: string) => string;
convert: ConvertFn;
typesPrefix: string;

@@ -14,4 +14,3 @@ }

scalars?: ScalarsMap;
enumValues?: EnumValuesMap;
namingConvention?: string;
namingConvention?: NamingConvention;
typesPrefix?: string;

@@ -21,25 +20,7 @@ }

protected _parsedConfig: TPluginConfig;
protected _argumentsTransformer: OperationVariablesToObject;
protected _declarationBlockConfig: DeclarationBlockConfig;
constructor(rawConfig: TRawConfig, additionalConfig: TPluginConfig, defaultScalars?: ScalarsMap);
setDeclarationBlockConfig(config: DeclarationBlockConfig): void;
setArgumentsTransformer(argumentsTransfomer: OperationVariablesToObject): void;
readonly config: TPluginConfig;
readonly scalars: ScalarsMap;
convertName(name: any, addPrefix?: boolean): string;
DirectiveDefinition(node: DirectiveDefinitionNode): string;
NamedType(node: NamedTypeNode): string;
ListType(node: ListTypeNode): string;
protected wrapWithListType(str: string): string;
NonNullType(node: NonNullTypeNode): string;
InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode): string;
InputValueDefinition(node: InputValueDefinitionNode): string;
Name(node: NameNode): string;
FieldDefinition(node: FieldDefinitionNode): string;
UnionTypeDefinition(node: UnionTypeDefinitionNode, key: string | number, parent: any): string;
ObjectTypeDefinition(node: ObjectTypeDefinitionNode, key: number | string, parent: any): string;
InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode): string;
ScalarTypeDefinition(node: ScalarTypeDefinitionNode): string;
EnumTypeDefinition(node: EnumTypeDefinitionNode): string;
protected buildEnumValuesBlock(values: ReadonlyArray<EnumValueDefinitionNode>): string;
protected convertName(node: ASTNode | string, options?: BaseVisitorConvertOptions & ConvertOptions): string;
}

@@ -1,153 +0,21 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var graphql_codegen_plugin_helpers_1 = require("graphql-codegen-plugin-helpers");
var autoBind = require("auto-bind");
var variables_to_object_1 = require("./variables-to-object");
var scalars_1 = require("./scalars");
var BaseVisitor = /** @class */ (function () {
function BaseVisitor(rawConfig, additionalConfig, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { convertFactory } from './naming';
export class BaseVisitor {
constructor(rawConfig, additionalConfig, defaultScalars = DEFAULT_SCALARS) {
this._declarationBlockConfig = {};
this._parsedConfig = __assign({ scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), enumValues: rawConfig.enumValues || {}, convert: rawConfig.namingConvention ? graphql_codegen_plugin_helpers_1.resolveExternalModuleAndFn(rawConfig.namingConvention) : utils_1.toPascalCase, typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
this._parsedConfig = Object.assign({ scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
autoBind(this);
this._argumentsTransformer = new variables_to_object_1.OperationVariablesToObject(this.scalars, this.convertName);
}
BaseVisitor.prototype.setDeclarationBlockConfig = function (config) {
this._declarationBlockConfig = config;
};
BaseVisitor.prototype.setArgumentsTransformer = function (argumentsTransfomer) {
this._argumentsTransformer = argumentsTransfomer;
};
Object.defineProperty(BaseVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
BaseVisitor.prototype.convertName = function (name, addPrefix) {
if (addPrefix === void 0) { addPrefix = true; }
return (addPrefix ? this.config.typesPrefix : '') + this.config.convert(name);
};
BaseVisitor.prototype.DirectiveDefinition = function (node) {
return '';
};
BaseVisitor.prototype.NamedType = function (node) {
var asString = node.name;
var type = this.scalars[asString] || this.convertName(asString);
return type;
};
BaseVisitor.prototype.ListType = function (node) {
var asString = node.type;
return this.wrapWithListType(asString);
};
BaseVisitor.prototype.wrapWithListType = function (str) {
return "Array<" + str + ">";
};
BaseVisitor.prototype.NonNullType = function (node) {
var asString = node.type;
return asString;
};
BaseVisitor.prototype.InputObjectTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node.name))
.withBlock(node.fields.join('\n')).string;
};
BaseVisitor.prototype.InputValueDefinition = function (node) {
return utils_1.indent(node.name + ": " + node.type + ",");
};
BaseVisitor.prototype.Name = function (node) {
return node.value;
};
BaseVisitor.prototype.FieldDefinition = function (node) {
var typeString = node.type;
return utils_1.indent(node.name + ": " + typeString + ",");
};
BaseVisitor.prototype.UnionTypeDefinition = function (node, key, parent) {
var _this = this;
var originalNode = parent[key];
var possibleTypes = originalNode.types.map(function (t) { return _this.convertName(t.name.value); }).join(' | ');
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node.name))
.withContent(possibleTypes).string;
};
BaseVisitor.prototype.ObjectTypeDefinition = function (node, key, parent) {
var _this = this;
var originalNode = parent[key];
var interfaces = originalNode.interfaces && node.interfaces.length > 0
? originalNode.interfaces.map(function (i) { return _this.convertName(i.name.value); }).join(' & ') + ' & '
: '';
var typeDefinition = new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node.name))
.withContent(interfaces)
.withBlock(node.fields.join('\n')).string;
var original = parent[key];
var fieldsWithArguments = original.fields.filter(function (field) { return field.arguments && field.arguments.length > 0; });
var fieldsArguments = fieldsWithArguments.map(function (field) {
var name = original.name.value + _this.convertName(field.name.value, false) + 'Args';
return new utils_1.DeclarationBlock(_this._declarationBlockConfig)
.export()
.asKind('type')
.withName(_this.convertName(name))
.withBlock(_this._argumentsTransformer.transform(field.arguments)).string;
});
return [typeDefinition].concat(fieldsArguments).filter(function (f) { return f; }).join('\n\n');
};
BaseVisitor.prototype.InterfaceTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node.name))
.withBlock(node.fields.join('\n')).string;
};
BaseVisitor.prototype.ScalarTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node.name))
.withContent(this.config.scalars[node.name] || 'any').string;
};
BaseVisitor.prototype.EnumTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('enum')
.withName(this.convertName(node.name))
.withBlock(this.buildEnumValuesBlock(node.values)).string;
};
BaseVisitor.prototype.buildEnumValuesBlock = function (values) {
var _this = this;
return values
.map(function (enumOption) {
return utils_1.indent("" + _this.convertName(enumOption.name) + _this._declarationBlockConfig.enumNameValueSeparator + " " + utils_1.wrapWithSingleQuotes(_this.config.enumValues[enumOption.name] || enumOption.name));
})
.join(', \n');
};
return BaseVisitor;
}());
exports.BaseVisitor = BaseVisitor;
get config() {
return this._parsedConfig;
}
get scalars() {
return this.config.scalars;
}
convertName(node, options) {
const useTypesPrefix = typeof (options && options.useTypesPrefix) === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this.config.typesPrefix : '') + this.config.convert(node, options);
}
}
//# sourceMappingURL=base-visitor.js.map

@@ -5,5 +5,7 @@ export * from './types';

export * from './base-visitor';
export * from './base-types-visitor';
export * from './base-documents-visitor';
export * from './base-resolvers-visitor';
export * from './client-side-base-visitor';
export * from './variables-to-object';
export * from './selection-set-to-object';

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

"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./utils"));
__export(require("./scalars"));
__export(require("./base-visitor"));
__export(require("./base-documents-visitor"));
__export(require("./base-resolvers-visitor"));
__export(require("./variables-to-object"));
__export(require("./selection-set-to-object"));
export * from './utils';
export * from './scalars';
export * from './base-visitor';
export * from './base-types-visitor';
export * from './base-documents-visitor';
export * from './base-resolvers-visitor';
export * from './client-side-base-visitor';
export * from './variables-to-object';
export * from './selection-set-to-object';
//# sourceMappingURL=index.js.map

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_SCALARS = {
export const DEFAULT_SCALARS = {
ID: 'string',

@@ -5,0 +3,0 @@ String: 'string',

import { SelectionSetNode, FieldNode, FragmentSpreadNode, InlineFragmentNode, GraphQLNamedType, GraphQLSchema } from 'graphql';
import { ScalarsMap, ConvertNameFn } from './types';
import { GraphQLObjectType, GraphQLNonNull, GraphQLList } from 'graphql';
import { BaseVisitorConvertOptions } from './base-visitor';
export declare type PrimitiveField = string;

@@ -22,3 +23,3 @@ export declare type PrimitiveAliasedFields = {

protected _schema: GraphQLSchema;
protected _convertName: ConvertNameFn;
protected _convertName: ConvertNameFn<BaseVisitorConvertOptions>;
protected _addTypename: boolean;

@@ -33,3 +34,3 @@ protected _parentSchemaType?: GraphQLNamedType;

protected _queriedForTypename: boolean;
constructor(_scalars: ScalarsMap, _schema: GraphQLSchema, _convertName: ConvertNameFn, _addTypename: boolean, _parentSchemaType?: GraphQLNamedType, _selectionSet?: SelectionSetNode);
constructor(_scalars: ScalarsMap, _schema: GraphQLSchema, _convertName: ConvertNameFn<BaseVisitorConvertOptions>, _addTypename: boolean, _parentSchemaType?: GraphQLNamedType, _selectionSet?: SelectionSetNode);
createNext(parentSchemaType: GraphQLNamedType, selectionSet: SelectionSetNode): SelectionSetToObject;

@@ -36,0 +37,0 @@ protected wrapTypeWithModifiers(baseType: string, type: GraphQLObjectType | GraphQLNonNull<GraphQLObjectType> | GraphQLList<GraphQLObjectType>): string;

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var utils_1 = require("./utils");
import { Kind, isObjectType, isUnionType, isInterfaceType, isEnumType, isEqualType, SchemaMetaFieldDef, TypeMetaFieldDef } from 'graphql';
import { getBaseType, quoteIfNeeded } from './utils';
function isMetadataFieldName(name) {

@@ -9,12 +7,12 @@ return ['__schema', '__type'].includes(name);

function isRootType(type, schema) {
return (graphql_1.isEqualType(type, schema.getQueryType()) ||
graphql_1.isEqualType(type, schema.getMutationType()) ||
graphql_1.isEqualType(type, schema.getSubscriptionType()));
return (isEqualType(type, schema.getQueryType()) ||
isEqualType(type, schema.getMutationType()) ||
isEqualType(type, schema.getSubscriptionType()));
}
var metadataFieldMap = {
__schema: graphql_1.SchemaMetaFieldDef,
__type: graphql_1.TypeMetaFieldDef
const metadataFieldMap = {
__schema: SchemaMetaFieldDef,
__type: TypeMetaFieldDef
};
var SelectionSetToObject = /** @class */ (function () {
function SelectionSetToObject(_scalars, _schema, _convertName, _addTypename, _parentSchemaType, _selectionSet) {
export class SelectionSetToObject {
constructor(_scalars, _schema, _convertName, _addTypename, _parentSchemaType, _selectionSet) {
this._scalars = _scalars;

@@ -33,9 +31,9 @@ this._schema = _schema;

}
SelectionSetToObject.prototype.createNext = function (parentSchemaType, selectionSet) {
throw new Error("You must override createNext in your SelectionSetToObject implementation!");
};
SelectionSetToObject.prototype.wrapTypeWithModifiers = function (baseType, type) {
throw new Error("You must override wrapTypeWithModifiers in your SelectionSetToObject implementation!");
};
SelectionSetToObject.prototype._collectField = function (field) {
createNext(parentSchemaType, selectionSet) {
throw new Error(`You must override createNext in your SelectionSetToObject implementation!`);
}
wrapTypeWithModifiers(baseType, type) {
throw new Error(`You must override wrapTypeWithModifiers in your SelectionSetToObject implementation!`);
}
_collectField(field) {
if (field.name.value === '__typename') {

@@ -45,4 +43,4 @@ this._queriedForTypename = true;

}
if (graphql_1.isObjectType(this._parentSchemaType) || graphql_1.isInterfaceType(this._parentSchemaType)) {
var schemaField = void 0;
if (isObjectType(this._parentSchemaType) || isInterfaceType(this._parentSchemaType)) {
let schemaField;
if (isRootType(this._parentSchemaType, this._schema) && isMetadataFieldName(field.name.value)) {

@@ -54,6 +52,6 @@ schemaField = metadataFieldMap[field.name.value];

}
var rawType = schemaField.type;
var baseType = utils_1.getBaseType(rawType);
var typeName = baseType.name;
if (this._scalars[typeName] || graphql_1.isEnumType(baseType)) {
const rawType = schemaField.type;
const baseType = getBaseType(rawType);
const typeName = baseType.name;
if (this._scalars[typeName] || isEnumType(baseType)) {
if (field.alias && field.alias.value) {

@@ -70,3 +68,3 @@ this._primitiveAliasedFields.push({

else {
var selectionSetToObject = this.createNext(baseType, field.selectionSet);
const selectionSetToObject = this.createNext(baseType, field.selectionSet);
this._linksFields.push({

@@ -80,10 +78,10 @@ alias: field.alias ? field.alias.value : null,

}
};
SelectionSetToObject.prototype._collectFragmentSpread = function (node) {
}
_collectFragmentSpread(node) {
this._fragmentSpreads.push(node.name.value);
};
SelectionSetToObject.prototype._collectInlineFragment = function (node) {
var onType = node.typeCondition.name.value;
var schemaType = this._schema.getType(onType);
var selectionSet = this.createNext(schemaType, node.selectionSet);
}
_collectInlineFragment(node) {
const onType = node.typeCondition.name.value;
const schemaType = this._schema.getType(onType);
const selectionSet = this.createNext(schemaType, node.selectionSet);
if (!this._inlineFragments[onType]) {

@@ -93,42 +91,39 @@ this._inlineFragments[onType] = [];

this._inlineFragments[onType].push(selectionSet.string);
};
Object.defineProperty(SelectionSetToObject.prototype, "string", {
get: function () {
if (!this._selectionSet || !this._selectionSet.selections || this._selectionSet.selections.length === 0) {
return '';
}
get string() {
if (!this._selectionSet || !this._selectionSet.selections || this._selectionSet.selections.length === 0) {
return '';
}
const { selections } = this._selectionSet;
for (const selection of selections) {
switch (selection.kind) {
case Kind.FIELD:
this._collectField(selection);
break;
case Kind.FRAGMENT_SPREAD:
this._collectFragmentSpread(selection);
break;
case Kind.INLINE_FRAGMENT:
this._collectInlineFragment(selection);
break;
}
var selections = this._selectionSet.selections;
for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
var selection = selections_1[_i];
switch (selection.kind) {
case graphql_1.Kind.FIELD:
this._collectField(selection);
break;
case graphql_1.Kind.FRAGMENT_SPREAD:
this._collectFragmentSpread(selection);
break;
case graphql_1.Kind.INLINE_FRAGMENT:
this._collectInlineFragment(selection);
break;
}
}
var parentName = this._convertName(this._parentSchemaType.name, true);
var typeName = this._addTypename || this._queriedForTypename ? this.buildTypeNameField() : null;
var baseFields = this.buildPrimitiveFields(parentName, this._primitiveFields);
var aliasBaseFields = this.buildAliasedPrimitiveFields(parentName, this._primitiveAliasedFields);
var linksFields = this.buildLinkFields(this._linksFields);
var inlineFragments = this.buildInlineFragments(this._inlineFragments);
var fragmentSpreads = this.buildFragmentSpread(this._fragmentSpreads);
var fieldsSet = [typeName, baseFields, aliasBaseFields, linksFields, fragmentSpreads, inlineFragments].filter(function (f) { return f && f !== ''; });
return this.mergeAllFields(fieldsSet);
},
enumerable: true,
configurable: true
});
SelectionSetToObject.prototype.mergeAllFields = function (fieldsSet) {
return utils_1.quoteIfNeeded(fieldsSet, ' & ');
};
SelectionSetToObject.prototype.buildTypeNameField = function () {
var possibleTypes = [];
if (!graphql_1.isUnionType(this._parentSchemaType) && !graphql_1.isInterfaceType(this._parentSchemaType)) {
}
const parentName = this._convertName(this._parentSchemaType.name, {
useTypesPrefix: true
});
const typeName = this._addTypename || this._queriedForTypename ? this.buildTypeNameField() : null;
const baseFields = this.buildPrimitiveFields(parentName, this._primitiveFields);
const aliasBaseFields = this.buildAliasedPrimitiveFields(parentName, this._primitiveAliasedFields);
const linksFields = this.buildLinkFields(this._linksFields);
const inlineFragments = this.buildInlineFragments(this._inlineFragments);
const fragmentSpreads = this.buildFragmentSpread(this._fragmentSpreads);
const fieldsSet = [typeName, baseFields, aliasBaseFields, linksFields, fragmentSpreads, inlineFragments].filter(f => f && f !== '');
return this.mergeAllFields(fieldsSet);
}
mergeAllFields(fieldsSet) {
return quoteIfNeeded(fieldsSet, ' & ');
}
buildTypeNameField() {
const possibleTypes = [];
if (!isUnionType(this._parentSchemaType) && !isInterfaceType(this._parentSchemaType)) {
possibleTypes.push(this._parentSchemaType.name);

@@ -139,47 +134,45 @@ }

}
return "{ " + this.formatNamedField('__typename') + (this._queriedForTypename ? '' : '?') + ": " + possibleTypes
.map(function (t) { return "'" + t + "'"; })
.join(' | ') + " }";
};
SelectionSetToObject.prototype.buildPrimitiveFields = function (parentName, fields) {
return `{ ${this.formatNamedField('__typename')}${this._queriedForTypename ? '' : '?'}: ${possibleTypes
.map(t => `'${t}'`)
.join(' | ')} }`;
}
buildPrimitiveFields(parentName, fields) {
if (fields.length === 0) {
return null;
}
return "Pick<" + parentName + ", " + fields.map(function (field) { return "'" + field + "'"; }).join(' | ') + ">";
};
SelectionSetToObject.prototype.buildAliasedPrimitiveFields = function (parentName, fields) {
var _this = this;
return `Pick<${parentName}, ${fields.map(field => `'${field}'`).join(' | ')}>`;
}
buildAliasedPrimitiveFields(parentName, fields) {
if (fields.length === 0) {
return null;
}
return "{ " + fields
.map(function (aliasedField) { return _this.formatNamedField(aliasedField.alias) + ": " + parentName + "['" + aliasedField.fieldName + "']"; })
.join(', ') + " }";
};
SelectionSetToObject.prototype.formatNamedField = function (name) {
return `{ ${fields
.map(aliasedField => `${this.formatNamedField(aliasedField.alias)}: ${parentName}['${aliasedField.fieldName}']`)
.join(', ')} }`;
}
formatNamedField(name) {
return name;
};
SelectionSetToObject.prototype.buildLinkFields = function (fields) {
var _this = this;
}
buildLinkFields(fields) {
if (fields.length === 0) {
return null;
}
return "{ " + fields
.map(function (field) { return _this.formatNamedField(field.alias || field.name) + ": " + field.selectionSet; })
.join(', ') + " }";
};
SelectionSetToObject.prototype.buildInlineFragments = function (inlineFragments) {
var allPossibleTypes = Object.keys(inlineFragments).map(function (typeName) { return inlineFragments[typeName].join(' & '); });
return allPossibleTypes.length === 0 ? null : "(" + allPossibleTypes.join(' | ') + ")";
};
SelectionSetToObject.prototype.buildFragmentSpread = function (fragmentsSpread) {
var _this = this;
return `{ ${fields
.map(field => `${this.formatNamedField(field.alias || field.name)}: ${field.selectionSet}`)
.join(', ')} }`;
}
buildInlineFragments(inlineFragments) {
const allPossibleTypes = Object.keys(inlineFragments).map(typeName => inlineFragments[typeName].join(' & '));
return allPossibleTypes.length === 0 ? null : `(${allPossibleTypes.join(' | ')})`;
}
buildFragmentSpread(fragmentsSpread) {
if (fragmentsSpread.length === 0) {
return null;
}
return utils_1.quoteIfNeeded(fragmentsSpread.map(function (fragmentName) { return _this._convertName(fragmentName + 'Fragment', true); }), ' & ');
};
return SelectionSetToObject;
}());
exports.SelectionSetToObject = SelectionSetToObject;
return quoteIfNeeded(fragmentsSpread.map(fragmentName => this._convertName(fragmentName, {
suffix: 'Fragment',
useTypesPrefix: true
})), ' & ');
}
}
//# sourceMappingURL=selection-set-to-object.js.map

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

import { ASTNode } from 'graphql';
export declare type ScalarsMap = {

@@ -7,2 +8,13 @@ [name: string]: string;

};
export declare type ConvertNameFn = (name: any, addPrefix: boolean) => string;
export declare type ConvertNameFn<T = {}> = ConvertFn<T>;
export interface ConvertOptions {
prefix?: string;
suffix?: string;
}
export declare type ConvertFn<T = {}> = (node: ASTNode | string, options?: ConvertOptions & T) => string;
export declare type NamingConventionResolvePath = string;
export declare type NamingConvention = string | NamingConventionMap;
export interface NamingConventionMap {
enumValues?: 'keep' | NamingConventionResolvePath | Function;
typeNames?: 'keep' | NamingConventionResolvePath | Function;
}

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

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
import { NameNode, TypeNode, NamedTypeNode, GraphQLObjectType, GraphQLNonNull, GraphQLList, GraphQLOutputType, GraphQLNamedType } from 'graphql';
export declare const getConfigValue: <T = any>(value: T, defaultValue: T) => T;
export declare function getBaseType(type: GraphQLOutputType): GraphQLNamedType;

@@ -7,3 +8,3 @@ export declare function quoteIfNeeded(array: string[], joinWith?: string): string;

export declare function breakLine(str: string): string;
export declare function indent(str: string): string;
export declare function indent(str: string, count?: number): string;
export interface DeclarationBlockConfig {

@@ -10,0 +11,0 @@ blockWrapper?: string;

@@ -1,20 +0,13 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var change_case_1 = require("change-case");
var graphql_1 = require("graphql");
import { pascalCase } from 'change-case';
import { Kind, isNonNullType, isListType } from 'graphql';
function isWrapperType(t) {
return graphql_1.isListType(t) || graphql_1.isNonNullType(t);
return isListType(t) || isNonNullType(t);
}
function getBaseType(type) {
export const getConfigValue = (value, defaultValue) => {
if (value === null || value === undefined) {
return defaultValue;
}
return value;
};
export function getBaseType(type) {
if (isWrapperType(type)) {

@@ -27,5 +20,3 @@ return getBaseType(type.ofType);

}
exports.getBaseType = getBaseType;
function quoteIfNeeded(array, joinWith) {
if (joinWith === void 0) { joinWith = ' & '; }
export function quoteIfNeeded(array, joinWith = ' & ') {
if (array.length === 0) {

@@ -38,24 +29,19 @@ return '';

else {
return "(" + array.join(joinWith) + ")";
return `(${array.join(joinWith)})`;
}
}
exports.quoteIfNeeded = quoteIfNeeded;
function block(array) {
export function block(array) {
return array && array.length !== 0 ? '{\n' + array.join('\n') + '\n}' : '';
}
exports.block = block;
function wrapWithSingleQuotes(str) {
return "'" + str + "'";
export function wrapWithSingleQuotes(str) {
return `'${str}'`;
}
exports.wrapWithSingleQuotes = wrapWithSingleQuotes;
function breakLine(str) {
export function breakLine(str) {
return str + '\n';
}
exports.breakLine = breakLine;
function indent(str) {
return ' ' + str;
export function indent(str, count = 1) {
return new Array(count).fill(' ').join('') + str;
}
exports.indent = indent;
var DeclarationBlock = /** @class */ (function () {
function DeclarationBlock(_config) {
export class DeclarationBlock {
constructor(_config) {
this._config = _config;

@@ -69,75 +55,71 @@ this._export = false;

this._nameGenerics = null;
this._config = __assign({ blockWrapper: '', enumNameValueSeparator: ':' }, this._config);
this._config = Object.assign({ blockWrapper: '', enumNameValueSeparator: ':' }, this._config);
}
DeclarationBlock.prototype.export = function (exp) {
if (exp === void 0) { exp = true; }
export(exp = true) {
this._export = exp;
return this;
};
DeclarationBlock.prototype.asKind = function (kind) {
}
asKind(kind) {
this._kind = kind;
return this;
};
DeclarationBlock.prototype.withMethodCall = function (methodName) {
}
withMethodCall(methodName) {
this._methodName = methodName;
return this;
};
DeclarationBlock.prototype.withBlock = function (block) {
}
withBlock(block) {
this._block = block;
return this;
};
DeclarationBlock.prototype.withContent = function (content) {
}
withContent(content) {
this._content = content;
return this;
};
DeclarationBlock.prototype.withName = function (name, generics) {
if (generics === void 0) { generics = null; }
}
withName(name, generics = null) {
this._name = name;
this._nameGenerics = generics;
return this;
};
Object.defineProperty(DeclarationBlock.prototype, "string", {
get: function () {
var result = '';
if (this._export) {
result += 'export ';
}
get string() {
let result = '';
if (this._export) {
result += 'export ';
}
if (this._kind) {
let extra = '';
let name = '';
if (['type', 'const', 'var', 'let'].includes(this._kind)) {
extra = '= ';
}
if (this._kind) {
var extra = '';
var name = '';
if (['type', 'const', 'var', 'let'].includes(this._kind)) {
extra = '= ';
}
if (this._name) {
name = this._name + (this._nameGenerics || '') + ' ';
}
result += this._kind + ' ' + name + extra;
if (this._name) {
name = this._name + (this._nameGenerics || '') + ' ';
}
if (this._block) {
if (this._content) {
result += this._content;
}
if (this._methodName) {
result += this._methodName + "({" + this._config.blockWrapper + "\n" + this._block + "\n" + this._config.blockWrapper + "})";
}
else {
result += "{" + this._config.blockWrapper + "\n" + this._block + "\n" + this._config.blockWrapper + "}";
}
}
else if (this._content) {
result += this._kind + ' ' + name + extra;
}
if (this._block) {
if (this._content) {
result += this._content;
}
else if (this._kind) {
result += '{}';
if (this._methodName) {
result += `${this._methodName}({${this._config.blockWrapper}
${this._block}
${this._config.blockWrapper}})`;
}
return result + (this._kind === 'interface' ? '' : ';') + '\n';
},
enumerable: true,
configurable: true
});
return DeclarationBlock;
}());
exports.DeclarationBlock = DeclarationBlock;
function getBaseTypeNode(typeNode) {
if (typeNode.kind === graphql_1.Kind.LIST_TYPE || typeNode.kind === graphql_1.Kind.NON_NULL_TYPE) {
else {
result += `{${this._config.blockWrapper}
${this._block}
${this._config.blockWrapper}}`;
}
}
else if (this._content) {
result += this._content;
}
else if (this._kind) {
result += '{}';
}
return result + (this._kind === 'interface' ? '' : ';') + '\n';
}
}
export function getBaseTypeNode(typeNode) {
if (typeNode.kind === Kind.LIST_TYPE || typeNode.kind === Kind.NON_NULL_TYPE) {
return getBaseTypeNode(typeNode.type);

@@ -147,25 +129,20 @@ }

}
exports.getBaseTypeNode = getBaseTypeNode;
function toPascalCase(str) {
export function toPascalCase(str) {
return str
.split('_')
.map(function (s) { return change_case_1.pascalCase(s); })
.map(s => pascalCase(s))
.join('_');
}
exports.toPascalCase = toPascalCase;
exports.wrapTypeWithModifiers = function (prefix) {
if (prefix === void 0) { prefix = ''; }
return function (baseType, type) {
if (graphql_1.isNonNullType(type)) {
return exports.wrapTypeWithModifiers(prefix)(baseType, type.ofType).substr(1);
}
else if (graphql_1.isListType(type)) {
var innerType = exports.wrapTypeWithModifiers(prefix)(baseType, type.ofType);
return prefix + "Array<" + innerType + ">";
}
else {
return "" + prefix + baseType;
}
};
export const wrapTypeWithModifiers = (prefix = '') => (baseType, type) => {
if (isNonNullType(type)) {
return wrapTypeWithModifiers(prefix)(baseType, type.ofType).substr(1);
}
else if (isListType(type)) {
const innerType = wrapTypeWithModifiers(prefix)(baseType, type.ofType);
return `${prefix}Array<${innerType}>`;
}
else {
return `${prefix}${baseType}`;
}
};
//# sourceMappingURL=utils.js.map
import { TypeNode, VariableNode, NameNode, ValueNode } from 'graphql';
import { ScalarsMap, ConvertNameFn } from './types';
import { BaseVisitorConvertOptions } from './base-visitor';
export interface InterfaceOrVariable {

@@ -11,4 +12,4 @@ name?: NameNode;

protected _scalars: ScalarsMap;
protected _convertName: ConvertNameFn;
constructor(_scalars: ScalarsMap, _convertName: ConvertNameFn);
protected _convertName: ConvertNameFn<BaseVisitorConvertOptions>;
constructor(_scalars: ScalarsMap, _convertName: ConvertNameFn<BaseVisitorConvertOptions>);
getName<TDefinitionType extends InterfaceOrVariable>(node: TDefinitionType): string;

@@ -15,0 +16,0 @@ transform<TDefinitionType extends InterfaceOrVariable>(variablesNode: ReadonlyArray<TDefinitionType>): string;

@@ -1,8 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var utils_1 = require("./utils");
var autoBind = require("auto-bind");
var OperationVariablesToObject = /** @class */ (function () {
function OperationVariablesToObject(_scalars, _convertName) {
import { Kind } from 'graphql';
import { indent, getBaseTypeNode } from './utils';
import autoBind from 'auto-bind';
export class OperationVariablesToObject {
constructor(_scalars, _convertName) {
this._scalars = _scalars;

@@ -12,3 +10,3 @@ this._convertName = _convertName;

}
OperationVariablesToObject.prototype.getName = function (node) {
getName(node) {
if (node.name) {

@@ -24,34 +22,34 @@ if (typeof node.name === 'string') {

return null;
};
OperationVariablesToObject.prototype.transform = function (variablesNode) {
var _this = this;
}
transform(variablesNode) {
if (!variablesNode || variablesNode.length === 0) {
return null;
}
return variablesNode.map(function (variable) { return utils_1.indent(_this.transformVariable(variable)); }).join(',\n');
};
OperationVariablesToObject.prototype.transformVariable = function (variable) {
var baseType = typeof variable.type === 'string' ? variable.type : utils_1.getBaseTypeNode(variable.type);
var typeName = typeof baseType === 'string' ? baseType : baseType.name.value;
var typeValue = this._scalars[typeName] ? this._scalars[typeName] : this._convertName(typeName, true);
var fieldName = this.getName(variable);
var fieldType = this.wrapAstTypeWithModifiers(typeValue, variable.type);
var hasDefaultValue = variable.defaultValue != null && typeof variable.defaultValue !== 'undefined';
var isNonNullType = variable.type.kind === graphql_1.Kind.NON_NULL_TYPE;
var formattedFieldString = this.formatFieldString(fieldName, isNonNullType, hasDefaultValue);
var formattedTypeString = this.formatTypeString(fieldType, isNonNullType, hasDefaultValue);
return formattedFieldString + ": " + formattedTypeString;
};
OperationVariablesToObject.prototype.wrapAstTypeWithModifiers = function (baseType, typeNode) {
throw new Error("You must override \"wrapAstTypeWithModifiers\" of OperationVariablesToObject!");
};
OperationVariablesToObject.prototype.formatFieldString = function (fieldName, isNonNullType, hasDefaultValue) {
return variablesNode.map(variable => indent(this.transformVariable(variable))).join(',\n');
}
transformVariable(variable) {
const baseType = typeof variable.type === 'string' ? variable.type : getBaseTypeNode(variable.type);
const typeName = typeof baseType === 'string' ? baseType : baseType.name.value;
const typeValue = this._scalars[typeName] ||
this._convertName(baseType, {
useTypesPrefix: true
});
const fieldName = this.getName(variable);
const fieldType = this.wrapAstTypeWithModifiers(typeValue, variable.type);
const hasDefaultValue = variable.defaultValue != null && typeof variable.defaultValue !== 'undefined';
const isNonNullType = variable.type.kind === Kind.NON_NULL_TYPE;
const formattedFieldString = this.formatFieldString(fieldName, isNonNullType, hasDefaultValue);
const formattedTypeString = this.formatTypeString(fieldType, isNonNullType, hasDefaultValue);
return `${formattedFieldString}: ${formattedTypeString}`;
}
wrapAstTypeWithModifiers(baseType, typeNode) {
throw new Error(`You must override "wrapAstTypeWithModifiers" of OperationVariablesToObject!`);
}
formatFieldString(fieldName, isNonNullType, hasDefaultValue) {
return fieldName;
};
OperationVariablesToObject.prototype.formatTypeString = function (fieldType, isNonNullType, hasDefaultValue) {
}
formatTypeString(fieldType, isNonNullType, hasDefaultValue) {
return fieldType;
};
return OperationVariablesToObject;
}());
exports.OperationVariablesToObject = OperationVariablesToObject;
}
}
//# sourceMappingURL=variables-to-object.js.map
{
"name": "graphql-codegen-visitor-plugin-common",
"version": "0.19.0-alpha.89ed12b6",
"version": "0.19.0-alpha.8e3376c3",
"license": "MIT",

@@ -10,3 +10,7 @@ "scripts": {

"auto-bind": "2.0.0",
"graphql-codegen-core": "0.19.0-alpha.89ed12b6"
"dependency-graph": "0.8.0",
"esm": "3.2.11",
"graphql-codegen-plugin-helpers": "0.19.0-alpha.8e3376c3",
"graphql-tag": "2.10.1",
"tslib": "1.9.3"
},

@@ -19,5 +23,7 @@ "peerDependencies": {

"graphql": "14.1.1",
"graphql-codegen-testing": "0.19.0-alpha.8e3376c3",
"typescript": "3.3.3333"
},
"main": "./dist/index.js",
"main": "cjs/index.js",
"module": "dist/index.js",
"typings": "dist/index.d.ts",

@@ -30,3 +36,6 @@ "typescript": {

"ts-jest": {
"enableTsDiagnostics": false
"enableTsDiagnostics": false,
"tsConfig": {
"esModuleInterop": true
}
}

@@ -33,0 +42,0 @@ },

{
"compilerOptions": {
"importHelpers": true,
"experimentalDecorators": true,
"module": "commonjs",
"target": "es5",
"module": "esnext",
"target": "es2018",
"lib": ["es6", "esnext", "es2015"],

@@ -7,0 +8,0 @@ "suppressImplicitAnyIndexErrors": true,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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