Socket
Socket
Sign inDemoInstall

apollo-codegen

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

apollo-codegen - npm Package Compare versions

Comparing version 0.10.11 to 0.10.12

lib/printSchema.js

145

lib/cli.js
#!/usr/bin/env node
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

@@ -12,2 +16,6 @@

var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _glob = require('glob');

@@ -38,3 +46,3 @@

// Make sure unhandled errors in async code are propagated correctly
_process2.default.on('unhandledRejection', error => {
_process2.default.on('unhandledRejection', function (error) {
throw error;

@@ -62,16 +70,37 @@ });

type: 'array',
coerce: arg => {
let additionalHeaders = {};
for (const header of arg) {
var _header$split = header.split(/\s*:\s*/),
_header$split2 = (0, _slicedToArray3.default)(_header$split, 2);
coerce: function coerce(arg) {
var additionalHeaders = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
const name = _header$split2[0],
try {
for (var _iterator = (0, _getIterator3.default)(arg), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var header = _step.value;
var _header$split = header.split(/\s*:\s*/),
_header$split2 = (0, _slicedToArray3.default)(_header$split, 2),
name = _header$split2[0],
value = _header$split2[1];
if (!(name && value)) {
throw new _errors.ToolError('Headers should be specified as "Name: Value"');
if (!(name && value)) {
throw new _errors.ToolError('Headers should be specified as "Name: Value"');
}
additionalHeaders[name] = value;
}
additionalHeaders[name] = value;
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return additionalHeaders;

@@ -85,24 +114,79 @@ }

}
}, (() => {
var _ref = (0, _asyncToGenerator3.default)(function* (argv) {
const schema = argv.schema,
output = argv.output,
header = argv.header,
insecure = argv.insecure;
}, function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(argv) {
var schema, output, header, insecure, urlRegex;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
schema = argv.schema, output = argv.output, header = argv.header, insecure = argv.insecure;
urlRegex = /^https?:\/\//i;
if (!urlRegex.test(schema)) {
_context.next = 7;
break;
}
const urlRegex = /^https?:\/\//i;
if (urlRegex.test(schema)) {
yield (0, _.downloadSchema)(schema, output, header, insecure);
} else {
yield (0, _.introspectSchema)(schema, output);
}
});
_context.next = 5;
return (0, _.downloadSchema)(schema, output, header, insecure);
case 5:
_context.next = 9;
break;
case 7:
_context.next = 9;
return (0, _.introspectSchema)(schema, output);
case 9:
case 'end':
return _context.stop();
}
}
}, _callee, undefined);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
})()).command('generate [input...]', 'Generate code from a GraphQL schema and query documents', {
}()).command(['print-schema [schema]'], 'Print the provided schema in the GraphQL schema language format', {
schema: {
demand: true,
describe: 'Path to GraphQL introspection query result',
default: 'schema.json',
normalize: true,
coerce: _path2.default.resolve
},
output: {
demand: true,
describe: 'Output path for GraphQL schema language file',
default: 'schema.graphql',
normalize: true,
coerce: _path2.default.resolve
}
}, function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(argv) {
var schema, output;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
schema = argv.schema, output = argv.output;
_context2.next = 3;
return (0, _.printSchema)(schema, output);
case 3:
case 'end':
return _context2.stop();
}
}
}, _callee2, undefined);
}));
return function (_x2) {
return _ref2.apply(this, arguments);
};
}()).command('generate [input...]', 'Generate code from a GraphQL schema and query documents', {
schema: {
demand: true,
describe: 'Path to GraphQL schema file',

@@ -135,4 +219,4 @@ default: 'schema.json',

}
}, argv => {
let input = argv.input;
}, function (argv) {
var input = argv.input;

@@ -144,5 +228,10 @@ // Use glob if the user's shell was unable to expand the pattern

}
const inputPaths = input.map(input => _path2.default.resolve(input));
const options = { passthroughCustomScalars: argv["passthrough-custom-scalars"] || argv["custom-scalars-prefix"] !== '', customScalarsPrefix: argv["custom-scalars-prefix"] || '' };
var inputPaths = input.map(function (input) {
return _path2.default.resolve(input);
})
// Sort to normalize different glob expansions between different terminals.
.sort();
var options = { passthroughCustomScalars: argv["passthrough-custom-scalars"] || argv["custom-scalars-prefix"] !== '', customScalarsPrefix: argv["custom-scalars-prefix"] || '' };
(0, _.generate)(inputPaths, argv.schema, argv.output, argv.target, options);

@@ -149,0 +238,0 @@ }).fail(function (message, error) {

831

lib/compilation.js

@@ -12,6 +12,10 @@ 'use strict';

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _from = require('babel-runtime/core-js/array/from');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _from2 = _interopRequireDefault(_from);
var _entries = require('babel-runtime/core-js/object/entries');
var _entries2 = _interopRequireDefault(_entries);
var _assign = require('babel-runtime/core-js/object/assign');

@@ -21,5 +25,5 @@

var _entries = require('babel-runtime/core-js/object/entries');
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _entries2 = _interopRequireDefault(_entries);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

@@ -38,6 +42,2 @@ var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _values = require('babel-runtime/core-js/object/values');

@@ -47,2 +47,14 @@

var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _create = require('babel-runtime/core-js/object/create');

@@ -67,3 +79,3 @@

const builtInScalarTypes = new _set2.default([_graphql.GraphQLString, _graphql.GraphQLInt, _graphql.GraphQLFloat, _graphql.GraphQLBoolean, _graphql.GraphQLID]);
var builtInScalarTypes = new _set2.default([_graphql.GraphQLString, _graphql.GraphQLInt, _graphql.GraphQLFloat, _graphql.GraphQLBoolean, _graphql.GraphQLID]);

@@ -77,23 +89,25 @@ function isBuiltInScalarType(type) {

function compileToIR(schema, document) {
const compiler = new Compiler(schema, document);
var compiler = new Compiler(schema, document);
const operations = (0, _create2.default)(null);
var operations = (0, _create2.default)(null);
compiler.operations.forEach(operation => {
compiler.operations.forEach(function (operation) {
operations[operation.name.value] = compiler.compileOperation(operation);
});
const fragments = (0, _create2.default)(null);
var fragments = (0, _create2.default)(null);
compiler.fragments.forEach(fragment => {
compiler.fragments.forEach(function (fragment) {
fragments[fragment.name.value] = compiler.compileFragment(fragment);
});
const typesUsed = compiler.typesUsed;
var typesUsed = compiler.typesUsed;
return { schema: schema, operations: operations, fragments: fragments, typesUsed: typesUsed };
return { schema, operations, fragments, typesUsed };
}
class Compiler {
constructor(schema, document) {
var Compiler = exports.Compiler = function () {
function Compiler(schema, document) {
(0, _classCallCheck3.default)(this, Compiler);
this.schema = schema;

@@ -106,11 +120,32 @@

for (const definition of document.definitions) {
switch (definition.kind) {
case _graphql.Kind.OPERATION_DEFINITION:
this.operations.push(definition);
break;
case _graphql.Kind.FRAGMENT_DEFINITION:
this.fragmentMap[definition.name.value] = definition;
break;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(document.definitions), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var definition = _step.value;
switch (definition.kind) {
case _graphql.Kind.OPERATION_DEFINITION:
this.operations.push(definition);
break;
case _graphql.Kind.FRAGMENT_DEFINITION:
this.fragmentMap[definition.name.value] = definition;
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}

@@ -121,347 +156,597 @@

addTypeUsed(type) {
if (type instanceof _graphql.GraphQLEnumType || type instanceof _graphql.GraphQLInputObjectType || type instanceof _graphql.GraphQLScalarType && !isBuiltInScalarType(type)) {
this.typesUsedSet.add(type);
}
if (type instanceof _graphql.GraphQLInputObjectType) {
for (const field of (0, _values2.default)(type.getFields())) {
this.addTypeUsed((0, _graphql.getNamedType)(field.type));
(0, _createClass3.default)(Compiler, [{
key: 'addTypeUsed',
value: function addTypeUsed(type) {
if (this.typesUsedSet.has(type)) return;
if (type instanceof _graphql.GraphQLEnumType || type instanceof _graphql.GraphQLInputObjectType || type instanceof _graphql.GraphQLScalarType && !isBuiltInScalarType(type)) {
this.typesUsedSet.add(type);
}
}
}
if (type instanceof _graphql.GraphQLInputObjectType) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
get typesUsed() {
return (0, _from2.default)(this.typesUsedSet);
}
try {
for (var _iterator2 = (0, _getIterator3.default)((0, _values2.default)(type.getFields())), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var field = _step2.value;
fragmentNamed(fragmentName) {
return this.fragmentMap[fragmentName];
}
this.addTypeUsed((0, _graphql.getNamedType)(field.type));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}
}, {
key: 'fragmentNamed',
value: function fragmentNamed(fragmentName) {
return this.fragmentMap[fragmentName];
}
}, {
key: 'compileOperation',
value: function compileOperation(operationDefinition) {
var _this = this;
get fragments() {
return (0, _values2.default)(this.fragmentMap);
}
var filePath = (0, _graphql2.filePathForNode)(operationDefinition);
var operationName = operationDefinition.name.value;
var operationType = operationDefinition.operation;
compileOperation(operationDefinition) {
const filePath = (0, _graphql2.filePathForNode)(operationDefinition);
const operationName = operationDefinition.name.value;
const operationType = operationDefinition.operation;
var variables = operationDefinition.variableDefinitions.map(function (node) {
var name = node.variable.name.value;
var type = (0, _graphql.typeFromAST)(_this.schema, node.type);
_this.addTypeUsed((0, _graphql.getNamedType)(type));
return { name, type };
});
const variables = operationDefinition.variableDefinitions.map(node => {
const name = node.variable.name.value;
const type = (0, _graphql.typeFromAST)(this.schema, node.type);
this.addTypeUsed((0, _graphql.getNamedType)(type));
return { name: name, type: type };
});
var source = (0, _graphql.print)(withTypenameFieldAddedWhereNeeded(this.schema, operationDefinition));
const source = (0, _graphql.print)(withTypenameFieldAddedWhereNeeded(this.schema, operationDefinition));
var rootType = (0, _graphql2.getOperationRootType)(this.schema, operationDefinition);
const rootType = (0, _graphql2.getOperationRootType)(this.schema, operationDefinition);
var groupedVisitedFragmentSet = new _map2.default();
var groupedFieldSet = this.collectFields(rootType, operationDefinition.selectionSet, undefined, groupedVisitedFragmentSet);
const groupedVisitedFragmentSet = new _map2.default();
const groupedFieldSet = this.collectFields(rootType, operationDefinition.selectionSet, undefined, groupedVisitedFragmentSet);
var fragmentsReferencedSet = (0, _create2.default)(null);
const fragmentsReferencedSet = (0, _create2.default)(null);
var _resolveFields = this.resolveFields(rootType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet),
fields = _resolveFields.fields;
var _resolveFields = this.resolveFields(rootType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet);
var fragmentsReferenced = (0, _keys2.default)(fragmentsReferencedSet);
const fields = _resolveFields.fields;
return { filePath, operationName, operationType, variables, source, fields, fragmentsReferenced };
}
}, {
key: 'compileFragment',
value: function compileFragment(fragmentDefinition) {
var filePath = (0, _graphql2.filePathForNode)(fragmentDefinition);
var fragmentName = fragmentDefinition.name.value;
const fragmentsReferenced = (0, _keys2.default)(fragmentsReferencedSet);
var source = (0, _graphql.print)(withTypenameFieldAddedWhereNeeded(this.schema, fragmentDefinition));
return { filePath: filePath, operationName: operationName, operationType: operationType, variables: variables, source: source, fields: fields, fragmentsReferenced: fragmentsReferenced };
}
var typeCondition = (0, _graphql.typeFromAST)(this.schema, fragmentDefinition.typeCondition);
var possibleTypes = this.possibleTypesForType(typeCondition);
compileFragment(fragmentDefinition) {
const filePath = (0, _graphql2.filePathForNode)(fragmentDefinition);
const fragmentName = fragmentDefinition.name.value;
var groupedVisitedFragmentSet = new _map2.default();
var groupedFieldSet = this.collectFields(typeCondition, fragmentDefinition.selectionSet, undefined, groupedVisitedFragmentSet);
const source = (0, _graphql.print)(withTypenameFieldAddedWhereNeeded(this.schema, fragmentDefinition));
var fragmentsReferencedSet = (0, _create2.default)(null);
const typeCondition = (0, _graphql.typeFromAST)(this.schema, fragmentDefinition.typeCondition);
const possibleTypes = this.possibleTypesForType(typeCondition);
var _resolveFields2 = this.resolveFields(typeCondition, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet),
fields = _resolveFields2.fields,
fragmentSpreads = _resolveFields2.fragmentSpreads,
inlineFragments = _resolveFields2.inlineFragments;
const groupedVisitedFragmentSet = new _map2.default();
const groupedFieldSet = this.collectFields(typeCondition, fragmentDefinition.selectionSet, undefined, groupedVisitedFragmentSet);
var fragmentsReferenced = (0, _keys2.default)(fragmentsReferencedSet);
const fragmentsReferencedSet = (0, _create2.default)(null);
return { filePath, fragmentName, source, typeCondition, possibleTypes, fields, fragmentSpreads, inlineFragments, fragmentsReferenced };
}
}, {
key: 'collectFields',
value: function collectFields(parentType, selectionSet) {
var groupedFieldSet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, _create2.default)(null);
var groupedVisitedFragmentSet = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _map2.default();
var _resolveFields2 = this.resolveFields(typeCondition, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet);
if (!(0, _graphql.isCompositeType)(parentType)) {
throw new Error(`parentType should be a composite type, but is "${String(parentType)}"`);
}
const fields = _resolveFields2.fields,
fragmentSpreads = _resolveFields2.fragmentSpreads,
inlineFragments = _resolveFields2.inlineFragments;
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
const fragmentsReferenced = (0, _keys2.default)(fragmentsReferencedSet);
try {
for (var _iterator3 = (0, _getIterator3.default)(selectionSet.selections), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var selection = _step3.value;
return { filePath: filePath, fragmentName: fragmentName, source: source, typeCondition: typeCondition, possibleTypes: possibleTypes, fields: fields, fragmentSpreads: fragmentSpreads, inlineFragments: inlineFragments, fragmentsReferenced: fragmentsReferenced };
}
switch (selection.kind) {
case _graphql.Kind.FIELD:
{
var fieldName = selection.name.value;
var responseName = selection.alias ? selection.alias.value : fieldName;
collectFields(parentType, selectionSet) {
let groupedFieldSet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, _create2.default)(null);
let groupedVisitedFragmentSet = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _map2.default();
var field = (0, _graphql2.getFieldDef)(this.schema, parentType, selection);
if (!field) {
throw new _graphql.GraphQLError(`Cannot query field "${fieldName}" on type "${String(parentType)}"`, [selection]);
}
if (!(0, _graphql.isCompositeType)(parentType)) {
throw new Error(`parentType should be a composite type, but is "${String(parentType)}"`);
}
if (groupedFieldSet) {
if (!groupedFieldSet[responseName]) {
groupedFieldSet[responseName] = [];
}
for (const selection of selectionSet.selections) {
switch (selection.kind) {
case _graphql.Kind.FIELD:
{
const fieldName = selection.name.value;
const responseName = selection.alias ? selection.alias.value : fieldName;
groupedFieldSet[responseName].push([parentType, {
responseName,
fieldName,
args: argumentsFromAST(selection.arguments),
type: field.type,
directives: selection.directives,
selectionSet: selection.selectionSet
}]);
}
break;
}
case _graphql.Kind.INLINE_FRAGMENT:
{
var typeCondition = selection.typeCondition;
var inlineFragmentType = typeCondition ? (0, _graphql.typeFromAST)(this.schema, typeCondition) : parentType;
const field = (0, _graphql2.getFieldDef)(this.schema, parentType, selection);
if (!field) {
throw new _graphql.GraphQLError(`Cannot query field "${fieldName}" on type "${String(parentType)}"`, [selection]);
}
var effectiveType = parentType instanceof _graphql.GraphQLObjectType ? parentType : inlineFragmentType;
if (inlineFragmentType !== effectiveType && !(0, _graphql2.isTypeProperSuperTypeOf)(this.schema, inlineFragmentType, effectiveType)) {
break;
}
if (groupedFieldSet) {
if (!groupedFieldSet[responseName]) {
groupedFieldSet[responseName] = [];
this.collectFields(effectiveType, selection.selectionSet, groupedFieldSet, groupedVisitedFragmentSet);
break;
}
case _graphql.Kind.FRAGMENT_SPREAD:
{
var fragmentName = selection.name.value;
groupedFieldSet[responseName].push([parentType, {
responseName: responseName,
fieldName: fieldName,
args: argumentsFromAST(selection.arguments),
type: field.type,
directives: selection.directives,
selectionSet: selection.selectionSet
}]);
}
break;
}
case _graphql.Kind.INLINE_FRAGMENT:
{
const typeCondition = selection.typeCondition;
const inlineFragmentType = typeCondition ? (0, _graphql.typeFromAST)(this.schema, typeCondition) : parentType;
var fragment = this.fragmentNamed(fragmentName);
if (!fragment) throw new _graphql.GraphQLError(`Cannot find fragment "${fragmentName}"`);
const effectiveType = parentType instanceof _graphql.GraphQLObjectType ? parentType : inlineFragmentType;
var _typeCondition = fragment.typeCondition;
var fragmentType = (0, _graphql.typeFromAST)(this.schema, _typeCondition);
this.collectFields(effectiveType, selection.selectionSet, groupedFieldSet, groupedVisitedFragmentSet);
break;
}
case _graphql.Kind.FRAGMENT_SPREAD:
{
const fragmentName = selection.name.value;
if (groupedVisitedFragmentSet) {
var visitedFragmentSet = groupedVisitedFragmentSet.get(parentType);
if (!visitedFragmentSet) {
visitedFragmentSet = {};
groupedVisitedFragmentSet.set(parentType, visitedFragmentSet);
}
const fragment = this.fragmentNamed(fragmentName);
if (!fragment) throw new _graphql.GraphQLError(`Cannot find fragment "${fragmentName}"`);
if (visitedFragmentSet[fragmentName]) continue;
visitedFragmentSet[fragmentName] = true;
}
const typeCondition = fragment.typeCondition;
const fragmentType = (0, _graphql.typeFromAST)(this.schema, typeCondition);
var _effectiveType = parentType instanceof _graphql.GraphQLObjectType ? parentType : fragmentType;
if (groupedVisitedFragmentSet) {
let visitedFragmentSet = groupedVisitedFragmentSet.get(parentType);
if (!visitedFragmentSet) {
visitedFragmentSet = {};
groupedVisitedFragmentSet.set(parentType, visitedFragmentSet);
this.collectFields(_effectiveType, fragment.selectionSet, null, groupedVisitedFragmentSet);
break;
}
if (visitedFragmentSet[fragmentName]) continue;
visitedFragmentSet[fragmentName] = true;
}
const effectiveType = parentType instanceof _graphql.GraphQLObjectType ? parentType : fragmentType;
this.collectFields(effectiveType, fragment.selectionSet, null, groupedVisitedFragmentSet);
break;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
return groupedFieldSet;
}
}, {
key: 'possibleTypesForType',
value: function possibleTypesForType(type) {
if ((0, _graphql.isAbstractType)(type)) {
return this.schema.getPossibleTypes(type);
} else {
return [type];
}
}
}, {
key: 'mergeSelectionSets',
value: function mergeSelectionSets(parentType, fieldSet, groupedVisitedFragmentSet) {
var groupedFieldSet = (0, _create2.default)(null);
return groupedFieldSet;
}
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
possibleTypesForType(type) {
if ((0, _graphql.isAbstractType)(type)) {
return this.schema.getPossibleTypes(type);
} else {
return [type];
}
}
try {
for (var _iterator4 = (0, _getIterator3.default)(fieldSet), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var _ref = _step4.value;
mergeSelectionSets(parentType, fieldSet, groupedVisitedFragmentSet) {
const groupedFieldSet = (0, _create2.default)(null);
var _ref2 = (0, _slicedToArray3.default)(_ref, 2);
for (const _ref of fieldSet) {
var _ref2 = (0, _slicedToArray3.default)(_ref, 2);
var field = _ref2[1];
const field = _ref2[1];
var selectionSet = field.selectionSet;
const selectionSet = field.selectionSet;
if (selectionSet) {
this.collectFields(parentType, selectionSet, groupedFieldSet, groupedVisitedFragmentSet);
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
if (selectionSet) {
this.collectFields(parentType, selectionSet, groupedFieldSet, groupedVisitedFragmentSet);
}
return groupedFieldSet;
}
}, {
key: 'resolveFields',
value: function resolveFields(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet) {
var _this2 = this;
return groupedFieldSet;
}
var fields = [];
resolveFields(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet) {
const fields = [];
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
for (let _ref3 of (0, _entries2.default)(groupedFieldSet)) {
var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);
try {
for (var _iterator5 = (0, _getIterator3.default)((0, _entries2.default)(groupedFieldSet)), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var _ref3 = _step5.value;
let responseName = _ref4[0];
let fieldSet = _ref4[1];
var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);
fieldSet = fieldSet.filter((_ref5) => {
var _ref6 = (0, _slicedToArray3.default)(_ref5, 1);
var responseName = _ref4[0];
var fieldSet = _ref4[1];
let typeCondition = _ref6[0];
return (0, _graphql.isTypeSubTypeOf)(this.schema, parentType, typeCondition);
});
if (fieldSet.length < 1) continue;
fieldSet = fieldSet.filter(function (_ref5) {
var _ref6 = (0, _slicedToArray3.default)(_ref5, 1),
typeCondition = _ref6[0];
var _fieldSet$ = (0, _slicedToArray3.default)(fieldSet[0], 2);
return (0, _graphql.isTypeSubTypeOf)(_this2.schema, parentType, typeCondition);
});
if (fieldSet.length < 1) continue;
const firstField = _fieldSet$[1];
var _fieldSet$ = (0, _slicedToArray3.default)(fieldSet[0], 2),
firstField = _fieldSet$[1];
const fieldName = firstField.fieldName;
const args = firstField.args;
const type = firstField.type;
var fieldName = firstField.fieldName;
var args = firstField.args;
var type = firstField.type;
let field = { responseName: responseName, fieldName: fieldName, type: type };
var field = { responseName, fieldName, type };
if (args && args.length > 0) {
field.args = args;
}
if (args && args.length > 0) {
field.args = args;
}
const isConditional = fieldSet.some((_ref7) => {
var _ref8 = (0, _slicedToArray3.default)(_ref7, 2);
var isConditional = fieldSet.some(function (_ref7) {
var _ref8 = (0, _slicedToArray3.default)(_ref7, 2),
field = _ref8[1];
let field = _ref8[1];
return field.directives && field.directives.some(function (directive) {
var directiveName = directive.name.value;
return directiveName == 'skip' || directiveName == 'include';
});
});
return field.directives && field.directives.some(directive => {
const directiveName = directive.name.value;
return directiveName == 'skip' || directiveName == 'include';
});
});
if (isConditional) {
field.isConditional = true;
}
if (isConditional) {
field.isConditional = true;
}
var description = parentType.getFields()[fieldName].description;
const description = parentType.getFields()[fieldName].description;
if (description) {
field.description = description;
}
if (description) {
field.description = description;
}
var bareType = (0, _graphql.getNamedType)(type);
const bareType = (0, _graphql.getNamedType)(type);
this.addTypeUsed(bareType);
this.addTypeUsed(bareType);
if ((0, _graphql.isCompositeType)(bareType)) {
var subSelectionGroupedVisitedFragmentSet = new _map2.default();
var subSelectionGroupedFieldSet = this.mergeSelectionSets(bareType, fieldSet, subSelectionGroupedVisitedFragmentSet);
if ((0, _graphql.isCompositeType)(bareType)) {
const subSelectionGroupedVisitedFragmentSet = new _map2.default();
const subSelectionGroupedFieldSet = this.mergeSelectionSets(bareType, fieldSet, subSelectionGroupedVisitedFragmentSet);
var _resolveFields3 = this.resolveFields(bareType, subSelectionGroupedFieldSet, subSelectionGroupedVisitedFragmentSet, fragmentsReferencedSet),
_fields = _resolveFields3.fields,
_fragmentSpreads = _resolveFields3.fragmentSpreads,
_inlineFragments = _resolveFields3.inlineFragments;
var _resolveFields3 = this.resolveFields(bareType, subSelectionGroupedFieldSet, subSelectionGroupedVisitedFragmentSet, fragmentsReferencedSet);
(0, _assign2.default)(field, { fields: _fields, fragmentSpreads: _fragmentSpreads, inlineFragments: _inlineFragments });
}
const fields = _resolveFields3.fields,
fragmentSpreads = _resolveFields3.fragmentSpreads,
inlineFragments = _resolveFields3.inlineFragments;
(0, _assign2.default)(field, { fields: fields, fragmentSpreads: fragmentSpreads, inlineFragments: inlineFragments });
fields.push(field);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
fields.push(field);
}
var fragmentSpreads = this.fragmentSpreadsForParentType(parentType, groupedVisitedFragmentSet);
var inlineFragments = this.resolveInlineFragments(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet);
const fragmentSpreads = this.fragmentSpreadsForParentType(parentType, groupedVisitedFragmentSet);
const inlineFragments = this.resolveInlineFragments(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet);
if (fragmentsReferencedSet) {
_assign2.default.apply(Object, [fragmentsReferencedSet].concat((0, _toConsumableArray3.default)(groupedVisitedFragmentSet.values())));
if (fragmentsReferencedSet) {
_assign2.default.apply(Object, [fragmentsReferencedSet].concat((0, _toConsumableArray3.default)(groupedVisitedFragmentSet.values())));
// TODO: This is a really inefficient way of keeping track of fragments referenced by other fragments
// We need to either cache compiled fragments or find a way to make resolveFields smarter
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
// TODO: This is a really inefficient way of keeping track of fragments referenced by other fragments
// We need to either cache compiled fragments or find a way to make resolveFields smarter
for (let fragmentName of fragmentSpreads) {
const fragment = this.fragmentNamed(fragmentName);
if (!fragment) throw new _graphql.GraphQLError(`Cannot find fragment "${fragmentName}"`);
try {
for (var _iterator6 = (0, _getIterator3.default)(fragmentSpreads), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var fragmentName = _step6.value;
var _compileFragment = this.compileFragment(fragment);
var fragment = this.fragmentNamed(fragmentName);
if (!fragment) throw new _graphql.GraphQLError(`Cannot find fragment "${fragmentName}"`);
const fragmentsReferencedFromFragment = _compileFragment.fragmentsReferenced;
var _compileFragment = this.compileFragment(fragment),
fragmentsReferencedFromFragment = _compileFragment.fragmentsReferenced;
for (let fragmentReferenced of fragmentsReferencedFromFragment) {
fragmentsReferencedSet[fragmentReferenced] = true;
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = (0, _getIterator3.default)(fragmentsReferencedFromFragment), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var fragmentReferenced = _step7.value;
fragmentsReferencedSet[fragmentReferenced] = true;
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
}
return { fields, fragmentSpreads, inlineFragments };
}
}, {
key: 'resolveInlineFragments',
value: function resolveInlineFragments(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet) {
var _this3 = this;
return { fields: fields, fragmentSpreads: fragmentSpreads, inlineFragments: inlineFragments };
}
return this.collectPossibleTypes(parentType, groupedFieldSet, groupedVisitedFragmentSet).map(function (typeCondition) {
var _resolveFields4 = _this3.resolveFields(typeCondition, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet),
fields = _resolveFields4.fields,
fragmentSpreads = _resolveFields4.fragmentSpreads;
resolveInlineFragments(parentType, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet) {
return this.collectPossibleTypes(parentType, groupedFieldSet, groupedVisitedFragmentSet).map(typeCondition => {
var _resolveFields4 = this.resolveFields(typeCondition, groupedFieldSet, groupedVisitedFragmentSet, fragmentsReferencedSet);
var possibleTypes = _this3.possibleTypesForType(typeCondition);
return { typeCondition, possibleTypes, fields, fragmentSpreads };
});
}
}, {
key: 'collectPossibleTypes',
value: function collectPossibleTypes(parentType, groupedFieldSet, groupedVisitedFragmentSet) {
if (!(0, _graphql.isAbstractType)(parentType)) return [];
const fields = _resolveFields4.fields,
fragmentSpreads = _resolveFields4.fragmentSpreads;
var possibleTypes = new _set2.default();
const possibleTypes = this.possibleTypesForType(typeCondition);
return { typeCondition: typeCondition, possibleTypes: possibleTypes, fields: fields, fragmentSpreads: fragmentSpreads };
});
}
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
collectPossibleTypes(parentType, groupedFieldSet, groupedVisitedFragmentSet) {
if (!(0, _graphql.isAbstractType)(parentType)) return [];
try {
for (var _iterator8 = (0, _getIterator3.default)((0, _values2.default)(groupedFieldSet)), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var fieldSet = _step8.value;
var _iteratorNormalCompletion10 = true;
var _didIteratorError10 = false;
var _iteratorError10 = undefined;
const possibleTypes = new _set2.default();
try {
for (var _iterator10 = (0, _getIterator3.default)(fieldSet), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
var _ref9 = _step10.value;
for (const fieldSet of (0, _values2.default)(groupedFieldSet)) {
for (const _ref9 of fieldSet) {
var _ref10 = (0, _slicedToArray3.default)(_ref9, 1);
var _ref10 = (0, _slicedToArray3.default)(_ref9, 1);
const typeCondition = _ref10[0];
var typeCondition = _ref10[0];
if (this.schema.isPossibleType(parentType, typeCondition)) {
possibleTypes.add(typeCondition);
if (this.schema.isPossibleType(parentType, typeCondition)) {
possibleTypes.add(typeCondition);
}
}
} catch (err) {
_didIteratorError10 = true;
_iteratorError10 = err;
} finally {
try {
if (!_iteratorNormalCompletion10 && _iterator10.return) {
_iterator10.return();
}
} finally {
if (_didIteratorError10) {
throw _iteratorError10;
}
}
}
}
// Also include type conditions for fragment spreads
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
}
// Also include type conditions for fragment spreads
if (groupedVisitedFragmentSet) {
for (const effectiveType of groupedVisitedFragmentSet.keys()) {
if (this.schema.isPossibleType(parentType, effectiveType)) {
possibleTypes.add(effectiveType);
if (groupedVisitedFragmentSet) {
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
for (var _iterator9 = (0, _getIterator3.default)(groupedVisitedFragmentSet.keys()), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
var effectiveType = _step9.value;
if (this.schema.isPossibleType(parentType, effectiveType)) {
possibleTypes.add(effectiveType);
}
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
}
return (0, _from2.default)(possibleTypes);
}
}, {
key: 'fragmentSpreadsForParentType',
value: function fragmentSpreadsForParentType(parentType, groupedVisitedFragmentSet) {
if (!groupedVisitedFragmentSet) return [];
return (0, _from2.default)(possibleTypes);
}
var fragmentSpreads = new _set2.default();
fragmentSpreadsForParentType(parentType, groupedVisitedFragmentSet) {
if (!groupedVisitedFragmentSet) return [];
var _iteratorNormalCompletion11 = true;
var _didIteratorError11 = false;
var _iteratorError11 = undefined;
let fragmentSpreads = new _set2.default();
try {
for (var _iterator11 = (0, _getIterator3.default)(groupedVisitedFragmentSet), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
var _ref11 = _step11.value;
for (const _ref11 of groupedVisitedFragmentSet) {
var _ref12 = (0, _slicedToArray3.default)(_ref11, 2);
var _ref12 = (0, _slicedToArray3.default)(_ref11, 2);
const effectiveType = _ref12[0];
const visitedFragmentSet = _ref12[1];
var effectiveType = _ref12[0];
var visitedFragmentSet = _ref12[1];
if (!(0, _graphql2.isTypeProperSuperTypeOf)(this.schema, effectiveType, parentType)) continue;
if (!(0, _graphql2.isTypeProperSuperTypeOf)(this.schema, effectiveType, parentType)) continue;
for (const fragmentName of (0, _keys2.default)(visitedFragmentSet)) {
fragmentSpreads.add(fragmentName);
var _iteratorNormalCompletion12 = true;
var _didIteratorError12 = false;
var _iteratorError12 = undefined;
try {
for (var _iterator12 = (0, _getIterator3.default)((0, _keys2.default)(visitedFragmentSet)), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
var fragmentName = _step12.value;
fragmentSpreads.add(fragmentName);
}
} catch (err) {
_didIteratorError12 = true;
_iteratorError12 = err;
} finally {
try {
if (!_iteratorNormalCompletion12 && _iterator12.return) {
_iterator12.return();
}
} finally {
if (_didIteratorError12) {
throw _iteratorError12;
}
}
}
}
} catch (err) {
_didIteratorError11 = true;
_iteratorError11 = err;
} finally {
try {
if (!_iteratorNormalCompletion11 && _iterator11.return) {
_iterator11.return();
}
} finally {
if (_didIteratorError11) {
throw _iteratorError11;
}
}
}
return (0, _from2.default)(fragmentSpreads);
}
}, {
key: 'typesUsed',
get: function get() {
return (0, _from2.default)(this.typesUsedSet);
}
}, {
key: 'fragments',
get: function get() {
return (0, _values2.default)(this.fragmentMap);
}
}]);
return Compiler;
}();
return (0, _from2.default)(fragmentSpreads);
}
}
var typenameField = { kind: _graphql.Kind.FIELD, name: { kind: _graphql.Kind.NAME, value: '__typename' } };
exports.Compiler = Compiler;
const typenameField = { kind: _graphql.Kind.FIELD, name: { kind: _graphql.Kind.NAME, value: '__typename' } };
function withTypenameFieldAddedWhereNeeded(schema, ast) {

@@ -472,8 +757,8 @@ function isOperationRootType(type) {

const typeInfo = new _graphql.TypeInfo(schema);
var typeInfo = new _graphql.TypeInfo(schema);
return (0, _graphql.visit)(ast, (0, _graphql.visitWithTypeInfo)(typeInfo, {
leave: {
SelectionSet: node => {
const parentType = typeInfo.getParentType();
SelectionSet: function SelectionSet(node) {
var parentType = typeInfo.getParentType();

@@ -493,3 +778,3 @@ if (!isOperationRootType(parentType)) {

function argumentsFromAST(args) {
return args.map(arg => {
return args.map(function (arg) {
return { name: arg.name.value, value: (0, _graphql2.valueFromValueNode)(arg.value) };

@@ -500,8 +785,12 @@ });

function printIR(_ref13) {
let fields = _ref13.fields,
var fields = _ref13.fields,
inlineFragments = _ref13.inlineFragments,
fragmentSpreads = _ref13.fragmentSpreads;
return fields && (0, _printing.wrap)('<', (0, _printing.join)(fragmentSpreads, ', '), '> ') + (0, _printing.block)(fields.map(field => `${field.name}: ${String(field.type)}` + (0, _printing.wrap)(' ', printIR(field))).concat(inlineFragments && inlineFragments.map(inlineFragment => `${String(inlineFragment.typeCondition)}` + (0, _printing.wrap)(' ', printIR(inlineFragment)))));
return fields && (0, _printing.wrap)('<', (0, _printing.join)(fragmentSpreads, ', '), '> ') + (0, _printing.block)(fields.map(function (field) {
return `${field.name}: ${String(field.type)}` + (0, _printing.wrap)(' ', printIR(field));
}).concat(inlineFragments && inlineFragments.map(function (inlineFragment) {
return `${String(inlineFragment.typeCondition)}` + (0, _printing.wrap)(' ', printIR(inlineFragment));
})));
}
//# sourceMappingURL=compilation.js.map

@@ -7,2 +7,6 @@ 'use strict';

var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _stringify = require('babel-runtime/core-js/json/stringify');

@@ -44,3 +48,3 @@

const defaultHeaders = {
var defaultHeaders = {
'Accept': 'application/json',

@@ -50,33 +54,66 @@ 'Content-Type': 'application/json'

exports.default = (() => {
var _ref = (0, _asyncToGenerator3.default)(function* (url, outputPath, additionalHeaders, insecure) {
const headers = (0, _assign2.default)(defaultHeaders, additionalHeaders);
const agent = insecure ? new _https2.default.Agent({ rejectUnauthorized: false }) : null;
exports.default = function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(url, outputPath, additionalHeaders, insecure) {
var headers, agent, result, response, schemaData;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
headers = (0, _assign2.default)(defaultHeaders, additionalHeaders);
agent = insecure ? new _https2.default.Agent({ rejectUnauthorized: false }) : null;
result = void 0;
_context.prev = 3;
_context.next = 6;
return (0, _nodeFetch2.default)(url, {
method: 'POST',
headers: headers,
body: (0, _stringify2.default)({ 'query': _utilities.introspectionQuery }),
agent
});
let result;
try {
const response = yield (0, _nodeFetch2.default)(url, {
method: 'POST',
headers: headers,
body: (0, _stringify2.default)({ 'query': _utilities.introspectionQuery }),
agent: agent
});
case 6:
response = _context.sent;
_context.next = 9;
return response.json();
result = yield response.json();
} catch (error) {
throw new _errors.ToolError(`Error while fetching introspection query result: ${error.message}`);
}
case 9:
result = _context.sent;
_context.next = 15;
break;
if (result.errors) {
throw new _errors.ToolError(`Errors in introspection query result: ${result.errors}`);
}
case 12:
_context.prev = 12;
_context.t0 = _context['catch'](3);
throw new _errors.ToolError(`Error while fetching introspection query result: ${_context.t0.message}`);
const schemaData = result;
if (!schemaData.data) {
throw new _errors.ToolError(`No introspection query result data found, server responded with: ${(0, _stringify2.default)(result)}`);
}
case 15:
if (!result.errors) {
_context.next = 17;
break;
}
_fs2.default.writeFileSync(outputPath, (0, _stringify2.default)(schemaData, null, 2));
});
throw new _errors.ToolError(`Errors in introspection query result: ${result.errors}`);
case 17:
schemaData = result;
if (schemaData.data) {
_context.next = 20;
break;
}
throw new _errors.ToolError(`No introspection query result data found, server responded with: ${(0, _stringify2.default)(result)}`);
case 20:
_fs2.default.writeFileSync(outputPath, (0, _stringify2.default)(schemaData, null, 2));
case 21:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[3, 12]]);
}));
function downloadSchema(_x, _x2, _x3, _x4) {

@@ -87,3 +124,3 @@ return _ref.apply(this, arguments);

return downloadSchema;
})();
}();
//# sourceMappingURL=downloadSchema.js.map

@@ -7,2 +7,6 @@ 'use strict';

var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _create = require('babel-runtime/core-js/object/create');

@@ -32,3 +36,3 @@

const isRunningFromXcodeScript = process.env.XCODE_VERSION_ACTUAL;
var isRunningFromXcodeScript = process.env.XCODE_VERSION_ACTUAL;

@@ -39,6 +43,27 @@ function logError(error) {

} else if (error instanceof _graphql.GraphQLError) {
const fileName = error.source && error.source.name;
var fileName = error.source && error.source.name;
if (error.locations) {
for (const location of error.locations) {
logErrorMessage(error.message, fileName, location.line);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(error.locations), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var location = _step.value;
logErrorMessage(error.message, fileName, location.line);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}

@@ -45,0 +70,0 @@ } else {

@@ -51,12 +51,16 @@ 'use strict';

function generateSource(context) {
const generator = new _CodeGenerator2.default(context);
var generator = new _CodeGenerator2.default(context);
generator.printOnNewline('/* @flow */');
generator.printOnNewline('// This file was automatically generated and should not be edited.');
typeDeclarationForGraphQLType(context.typesUsed.forEach(type => typeDeclarationForGraphQLType(generator, type)));
(0, _values2.default)(context.operations).forEach(operation => {
typeDeclarationForGraphQLType(context.typesUsed.forEach(function (type) {
return typeDeclarationForGraphQLType(generator, type);
}));
(0, _values2.default)(context.operations).forEach(function (operation) {
interfaceVariablesDeclarationForOperation(generator, operation);
typeDeclarationForOperation(generator, operation);
});
(0, _values2.default)(context.fragments).forEach(operation => typeDeclarationForFragment(generator, operation));
(0, _values2.default)(context.fragments).forEach(function (operation) {
return typeDeclarationForFragment(generator, operation);
});

@@ -75,6 +79,6 @@ return generator.output;

function enumerationDeclaration(generator, type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;
const values = type.getValues();
var values = type.getValues();

@@ -84,4 +88,6 @@ generator.printNewlineIfNeeded();

generator.printOnNewline(`export type ${name} =`);
const nValues = values.length;
values.forEach((value, i) => generator.printOnNewline(` "${value.value}"${i === nValues - 1 ? ';' : ' |'}${(0, _printing.wrap)(' // ', value.description)}`));
var nValues = values.length;
values.forEach(function (value, i) {
return generator.printOnNewline(` "${value.value}"${i === nValues - 1 ? ';' : ' |'}${(0, _printing.wrap)(' // ', value.description)}`);
});
generator.printNewline();

@@ -91,7 +97,7 @@ }

function structDeclarationForInputObjectType(generator, type) {
const interfaceName = (0, _changeCase.pascalCase)(type.name);
var interfaceName = (0, _changeCase.pascalCase)(type.name);
(0, _language.typeDeclaration)(generator, {
interfaceName: interfaceName
}, () => {
const properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
interfaceName
}, function () {
var properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
propertyDeclarations(generator, properties, true);

@@ -102,3 +108,3 @@ });

function interfaceNameFromOperation(_ref) {
let operationName = _ref.operationName,
var operationName = _ref.operationName,
operationType = _ref.operationType;

@@ -122,3 +128,3 @@

function interfaceVariablesDeclarationForOperation(generator, _ref2) {
let operationName = _ref2.operationName,
var operationName = _ref2.operationName,
operationType = _ref2.operationType,

@@ -133,8 +139,8 @@ variables = _ref2.variables,

}
const interfaceName = `${interfaceNameFromOperation({ operationName: operationName, operationType: operationType })}Variables`;
var interfaceName = `${interfaceNameFromOperation({ operationName, operationType })}Variables`;
(0, _language.typeDeclaration)(generator, {
interfaceName: interfaceName
}, () => {
const properties = propertiesFromFields(generator.context, variables);
interfaceName
}, function () {
var properties = propertiesFromFields(generator.context, variables);
propertyDeclarations(generator, properties, true);

@@ -145,3 +151,3 @@ });

function typeDeclarationForOperation(generator, _ref3) {
let operationName = _ref3.operationName,
var operationName = _ref3.operationName,
operationType = _ref3.operationType,

@@ -154,8 +160,10 @@ variables = _ref3.variables,

const interfaceName = interfaceNameFromOperation({ operationName: operationName, operationType: operationType });
var interfaceName = interfaceNameFromOperation({ operationName, operationType });
(0, _language.typeDeclaration)(generator, {
interfaceName: interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(f => `${(0, _changeCase.pascalCase)(f)}Fragment`) : null
}, () => {
const properties = propertiesFromFields(generator.context, fields);
interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(function (f) {
return `${(0, _changeCase.pascalCase)(f)}Fragment`;
}) : null
}, function () {
var properties = propertiesFromFields(generator.context, fields);
propertyDeclarations(generator, properties, true);

@@ -166,3 +174,3 @@ });

function typeDeclarationForFragment(generator, _ref4) {
let fragmentName = _ref4.fragmentName,
var fragmentName = _ref4.fragmentName,
typeCondition = _ref4.typeCondition,

@@ -174,11 +182,15 @@ fields = _ref4.fields,

const interfaceName = `${(0, _changeCase.pascalCase)(fragmentName)}Fragment`;
var interfaceName = `${(0, _changeCase.pascalCase)(fragmentName)}Fragment`;
(0, _language.typeDeclaration)(generator, {
interfaceName: interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(f => `${(0, _changeCase.pascalCase)(f)}Fragment`) : null
}, () => {
interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(function (f) {
return `${(0, _changeCase.pascalCase)(f)}Fragment`;
}) : null
}, function () {
var _propertiesFromFields;
const properties = (_propertiesFromFields = propertiesFromFields(generator.context, fields)).concat.apply(_propertiesFromFields, (0, _toConsumableArray3.default)((inlineFragments || []).map(fragment => propertiesFromFields(generator.context, fragment.fields, true))));
var properties = (_propertiesFromFields = propertiesFromFields(generator.context, fields)).concat.apply(_propertiesFromFields, (0, _toConsumableArray3.default)((inlineFragments || []).map(function (fragment) {
return propertiesFromFields(generator.context, fragment.fields, true);
})));

@@ -190,7 +202,9 @@ propertyDeclarations(generator, properties, true);

function propertiesFromFields(context, fields, forceNullable) {
return fields.map(field => propertyFromField(context, field, forceNullable));
return fields.map(function (field) {
return propertyFromField(context, field, forceNullable);
});
}
function propertyFromField(context, field, forceNullable) {
let fieldName = field.name,
var fieldName = field.name,
fieldType = field.type,

@@ -203,12 +217,12 @@ description = field.description,

const propertyName = fieldName;
var propertyName = fieldName;
let property = { fieldName: fieldName, fieldType: fieldType, propertyName: propertyName, description: description };
var property = { fieldName, fieldType, propertyName, description };
const namedType = (0, _graphql.getNamedType)(fieldType);
var namedType = (0, _graphql.getNamedType)(fieldType);
if ((0, _graphql.isCompositeType)(namedType)) {
const bareTypeName = (0, _changeCase.pascalCase)(_inflected2.default.singularize(propertyName));
const typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType, bareTypeName);
let isArray = false;
var bareTypeName = (0, _changeCase.pascalCase)(_inflected2.default.singularize(propertyName));
var typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType, bareTypeName);
var isArray = false;
if (fieldType instanceof _graphql.GraphQLList) {

@@ -219,3 +233,3 @@ isArray = true;

}
let isNullable = true;
var isNullable = true;
if (fieldType instanceof _graphql.GraphQLNonNull && !forceNullable) {

@@ -225,8 +239,8 @@ isNullable = false;

return (0, _extends3.default)({}, property, {
typeName: typeName, bareTypeName: bareTypeName, fields: field.fields, isComposite: true, fragmentSpreads: fragmentSpreads, inlineFragments: inlineFragments, fieldType: fieldType,
isArray: isArray, isNullable: isNullable
typeName, bareTypeName, fields: field.fields, isComposite: true, fragmentSpreads, inlineFragments, fieldType,
isArray, isNullable
});
} else {
const typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType);
return (0, _extends3.default)({}, property, { typeName: typeName, isComposite: false, fieldType: fieldType });
var _typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType);
return (0, _extends3.default)({}, property, { typeName: _typeName, isComposite: false, fieldType });
}

@@ -237,12 +251,14 @@ }

if (!properties) return;
properties.forEach(property => {
properties.forEach(function (property) {
if (property.fields && property.fields.length > 0 || property.inlineFragments && property.inlineFragments.length > 0) {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface: inInterface }), () => {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface }), function () {
var _propertiesFromFields2;
const properties = (_propertiesFromFields2 = propertiesFromFields(generator.context, property.fields)).concat.apply(_propertiesFromFields2, (0, _toConsumableArray3.default)((property.inlineFragments || []).map(fragment => propertiesFromFields(generator.context, fragment.fields, true))));
var properties = (_propertiesFromFields2 = propertiesFromFields(generator.context, property.fields)).concat.apply(_propertiesFromFields2, (0, _toConsumableArray3.default)((property.inlineFragments || []).map(function (fragment) {
return propertiesFromFields(generator.context, fragment.fields, true);
})));
propertyDeclarations(generator, properties);
});
} else {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface: inInterface }));
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface }));
}

@@ -249,0 +265,0 @@ });

@@ -15,3 +15,3 @@ 'use strict';

function typeDeclaration(generator, _ref, closure) {
let interfaceName = _ref.interfaceName;
var interfaceName = _ref.interfaceName;

@@ -28,3 +28,3 @@ generator.printNewlineIfNeeded();

function propertyDeclaration(generator, _ref2, closure) {
let propertyName = _ref2.propertyName,
var propertyName = _ref2.propertyName,
typeName = _ref2.typeName,

@@ -52,5 +52,7 @@ description = _ref2.description,

generator.withinBlock(() => {
generator.withinBlock(function () {
if (fragmentSpreads && fragmentSpreads.length > 0) {
fragmentSpreads.forEach(n => generator.printOnNewline(`...${(0, _changeCase.pascalCase)(n)}Fragment,`));
fragmentSpreads.forEach(function (n) {
return generator.printOnNewline(`...${(0, _changeCase.pascalCase)(n)}Fragment,`);
});
}

@@ -71,4 +73,6 @@

generator.withinBlock(() => {
fragmentSpreads.forEach(n => generator.printOnNewline(`...${(0, _changeCase.pascalCase)(n)}Fragment,`));
generator.withinBlock(function () {
fragmentSpreads.forEach(function (n) {
return generator.printOnNewline(`...${(0, _changeCase.pascalCase)(n)}Fragment,`);
});
}, '{|', '|}');

@@ -85,4 +89,6 @@

if (!properties) return;
properties.forEach(property => propertyDeclaration(generator, property));
properties.forEach(function (property) {
return propertyDeclaration(generator, property);
});
}
//# sourceMappingURL=language.js.map

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

const builtInScalarMap = {
var builtInScalarMap = {
[_graphql.GraphQLString.name]: 'string',

@@ -24,3 +24,3 @@ [_graphql.GraphQLInt.name]: 'number',

function typeNameFromGraphQLType(context, type, bareTypeName) {
let nullable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var nullable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

@@ -31,3 +31,3 @@ if (type instanceof _graphql.GraphQLNonNull) {

let typeName;
var typeName = void 0;
if (type instanceof _graphql.GraphQLList) {

@@ -34,0 +34,0 @@ typeName = `Array< ${typeNameFromGraphQLType(context, type.ofType, bareTypeName, true)} >`;

@@ -38,12 +38,12 @@ 'use strict';

function generate(inputPaths, schemaPath, outputPath, target, options) {
const schema = (0, _loading.loadSchema)(schemaPath);
var schema = (0, _loading.loadSchema)(schemaPath);
const document = (0, _loading.loadAndMergeQueryDocuments)(inputPaths);
var document = (0, _loading.loadAndMergeQueryDocuments)(inputPaths);
(0, _validation.validateQueryDocument)(schema, document);
const context = (0, _compilation.compileToIR)(schema, document);
var context = (0, _compilation.compileToIR)(schema, document);
(0, _assign2.default)(context, options);
let output;
var output = void 0;
switch (target) {

@@ -50,0 +50,0 @@ case 'json':

@@ -6,21 +6,40 @@ 'use strict';

});
exports.generate = exports.introspectSchema = exports.downloadSchema = undefined;
var _downloadSchema2 = require('./downloadSchema');
var _downloadSchema = require('./downloadSchema');
var _downloadSchema3 = _interopRequireDefault(_downloadSchema2);
Object.defineProperty(exports, 'downloadSchema', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_downloadSchema).default;
}
});
var _introspectSchema2 = require('./introspectSchema');
var _introspectSchema = require('./introspectSchema');
var _introspectSchema3 = _interopRequireDefault(_introspectSchema2);
Object.defineProperty(exports, 'introspectSchema', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_introspectSchema).default;
}
});
var _generate2 = require('./generate');
var _printSchema = require('./printSchema');
var _generate3 = _interopRequireDefault(_generate2);
Object.defineProperty(exports, 'printSchema', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_printSchema).default;
}
});
var _generate = require('./generate');
Object.defineProperty(exports, 'generate', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_generate).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.downloadSchema = _downloadSchema3.default;
exports.introspectSchema = _introspectSchema3.default;
exports.generate = _generate3.default;
//# sourceMappingURL=index.js.map

@@ -12,2 +12,6 @@ 'use strict';

var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

@@ -17,12 +21,28 @@

let introspect = exports.introspect = (() => {
var _ref = (0, _asyncToGenerator3.default)(function* (schemaContents) {
const schema = (0, _graphql.buildASTSchema)((0, _graphql.parse)(schemaContents));
return yield (0, _graphql.graphql)(schema, _utilities.introspectionQuery);
});
var introspect = exports.introspect = function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(schemaContents) {
var schema;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
schema = (0, _graphql.buildASTSchema)((0, _graphql.parse)(schemaContents));
_context.next = 3;
return (0, _graphql.graphql)(schema, _utilities.introspectionQuery);
case 3:
return _context.abrupt('return', _context.sent);
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function introspect(_x) {
return _ref.apply(this, arguments);
};
})();
}();

@@ -41,18 +61,43 @@ var _fs = require('fs');

exports.default = (() => {
var _ref2 = (0, _asyncToGenerator3.default)(function* (schemaPath, outputPath) {
if (!_fs2.default.existsSync(schemaPath)) {
throw new _errors.ToolError(`Cannot find GraphQL schema file: ${schemaPath}`);
}
exports.default = function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(schemaPath, outputPath) {
var schemaContents, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (_fs2.default.existsSync(schemaPath)) {
_context2.next = 2;
break;
}
const schemaContents = _fs2.default.readFileSync(schemaPath).toString();
const result = yield introspect(schemaContents);
throw new _errors.ToolError(`Cannot find GraphQL schema file: ${schemaPath}`);
if (result.errors) {
throw new _errors.ToolError(`Errors in introspection query result: ${result.errors}`);
}
case 2:
schemaContents = _fs2.default.readFileSync(schemaPath).toString();
_context2.next = 5;
return introspect(schemaContents);
_fs2.default.writeFileSync(outputPath, (0, _stringify2.default)(result, null, 2));
});
case 5:
result = _context2.sent;
if (!result.errors) {
_context2.next = 8;
break;
}
throw new _errors.ToolError(`Errors in introspection query result: ${result.errors}`);
case 8:
_fs2.default.writeFileSync(outputPath, (0, _stringify2.default)(result, null, 2));
case 9:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function introspectSchema(_x2, _x3) {

@@ -63,3 +108,3 @@ return _ref2.apply(this, arguments);

return introspectSchema;
})();
}();
//# sourceMappingURL=introspectSchema.js.map

@@ -31,3 +31,3 @@ 'use strict';

}
const schemaData = require(schemaPath);
var schemaData = require(schemaPath);

@@ -41,4 +41,4 @@ if (!schemaData.data && !schemaData.__schema) {

function loadAndMergeQueryDocuments(inputPaths) {
const sources = inputPaths.map(inputPath => {
const body = _fs2.default.readFileSync(inputPath, 'utf8');
var sources = inputPaths.map(function (inputPath) {
var body = _fs2.default.readFileSync(inputPath, 'utf8');
if (!body) {

@@ -48,6 +48,10 @@ return null;

return new _graphql.Source(body, inputPath);
}).filter(source => source);
}).filter(function (source) {
return source;
});
return (0, _graphql.concatAST)(sources.map(source => (0, _graphql.parse)(source)));
return (0, _graphql.concatAST)(sources.map(function (source) {
return (0, _graphql.parse)(source);
}));
}
//# sourceMappingURL=loading.js.map

@@ -55,12 +55,14 @@ 'use strict';

function serializeEnumType(type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;
const values = type.getValues();
var values = type.getValues();
return {
kind: 'EnumType',
name: name,
description: description,
values: values.map(value => ({ name: value.name, description: value.description }))
name,
description,
values: values.map(function (value) {
return { name: value.name, description: value.description };
})
};

@@ -70,12 +72,12 @@ }

function serializeInputObjectType(type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;
const fields = (0, _values2.default)(type.getFields());
var fields = (0, _values2.default)(type.getFields());
return {
kind: 'InputObjectType',
name: name,
description: description,
fields: fields
name,
description,
fields
};

@@ -85,4 +87,4 @@ }

function serializeScalarType(type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;

@@ -92,6 +94,6 @@

kind: 'ScalarType',
name: name,
description: description
name,
description
};
}
//# sourceMappingURL=serializeToJSON.js.map

@@ -65,3 +65,3 @@ 'use strict';

function generateSource(context) {
const generator = new _CodeGenerator2.default(context);
var generator = new _CodeGenerator2.default(context);

@@ -72,11 +72,11 @@ generator.printOnNewline('// This file was automatically generated and should not be edited.');

context.typesUsed.forEach(type => {
context.typesUsed.forEach(function (type) {
typeDeclarationForGraphQLType(generator, type);
});
(0, _values2.default)(context.operations).forEach(operation => {
(0, _values2.default)(context.operations).forEach(function (operation) {
classDeclarationForOperation(generator, operation);
});
(0, _values2.default)(context.fragments).forEach(fragment => {
(0, _values2.default)(context.fragments).forEach(function (fragment) {
structDeclarationForFragment(generator, fragment);

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

function classDeclarationForOperation(generator, _ref) {
let operationName = _ref.operationName,
var operationName = _ref.operationName,
operationType = _ref.operationType,

@@ -98,4 +98,4 @@ variables = _ref.variables,

let className;
let protocol;
var className = void 0;
var protocol = void 0;

@@ -116,9 +116,9 @@ switch (operationType) {

(0, _language.classDeclaration)(generator, {
className: className,
className,
modifiers: ['public', 'final'],
adoptedProtocols: [protocol]
}, () => {
}, function () {
if (source) {
generator.printOnNewline('public static let operationDefinition =');
generator.withIndent(() => {
generator.withIndent(function () {
(0, _values3.multilineString)(generator, source);

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

generator.printOnNewline('public static let queryDocument = operationDefinition');
fragmentsReferenced.forEach(fragment => {
fragmentsReferenced.forEach(function (fragment) {
generator.print(`.appending(${typeNameForFragmentName(fragment)}.fragmentDefinition)`);

@@ -137,10 +137,10 @@ });

if (variables && variables.length > 0) {
const properties = variables.map((_ref2) => {
let name = _ref2.name,
var properties = variables.map(function (_ref2) {
var name = _ref2.name,
type = _ref2.type;
const propertyName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(name));
const typeName = (0, _types.typeNameFromGraphQLType)(generator.context, type);
const isOptional = !(type instanceof _graphql.GraphQLNonNull || type.ofType instanceof _graphql.GraphQLNonNull);
return { name: name, propertyName: propertyName, type: type, typeName: typeName, isOptional: isOptional };
var propertyName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(name));
var typeName = (0, _types.typeNameFromGraphQLType)(generator.context, type);
var isOptional = !(type instanceof _graphql.GraphQLNonNull || type.ofType instanceof _graphql.GraphQLNonNull);
return { name, propertyName, type, typeName, isOptional };
});

@@ -153,5 +153,5 @@ generator.printNewlineIfNeeded();

generator.printOnNewline(`public var variables: GraphQLMap?`);
generator.withinBlock(() => {
generator.printOnNewline((0, _printing.wrap)(`return [`, (0, _printing.join)(properties.map((_ref3) => {
let name = _ref3.name,
generator.withinBlock(function () {
generator.printOnNewline((0, _printing.wrap)(`return [`, (0, _printing.join)(properties.map(function (_ref3) {
var name = _ref3.name,
propertyName = _ref3.propertyName;

@@ -167,3 +167,3 @@ return `"${name}": ${propertyName}`;

structName: "Data",
fields: fields
fields
});

@@ -176,4 +176,4 @@ });

generator.print('(');
generator.print((0, _printing.join)(properties.map((_ref4) => {
let propertyName = _ref4.propertyName,
generator.print((0, _printing.join)(properties.map(function (_ref4) {
var propertyName = _ref4.propertyName,
type = _ref4.type,

@@ -186,5 +186,5 @@ typeName = _ref4.typeName,

generator.withinBlock(() => {
properties.forEach((_ref5) => {
let propertyName = _ref5.propertyName;
generator.withinBlock(function () {
properties.forEach(function (_ref5) {
var propertyName = _ref5.propertyName;

@@ -197,3 +197,3 @@ generator.printOnNewline(`self.${propertyName} = ${propertyName}`);

function structDeclarationForFragment(generator, _ref6) {
let fragmentName = _ref6.fragmentName,
var fragmentName = _ref6.fragmentName,
typeCondition = _ref6.typeCondition,

@@ -206,16 +206,16 @@ possibleTypes = _ref6.possibleTypes,

const structName = (0, _changeCase.pascalCase)(fragmentName);
var structName = (0, _changeCase.pascalCase)(fragmentName);
structDeclarationForSelectionSet(generator, {
structName: structName,
structName,
adoptedProtocols: ['GraphQLNamedFragment'],
parentType: typeCondition,
possibleTypes: possibleTypes,
fields: fields,
fragmentSpreads: fragmentSpreads,
inlineFragments: inlineFragments
}, () => {
possibleTypes,
fields,
fragmentSpreads,
inlineFragments
}, function () {
if (source) {
generator.printOnNewline('public static let fragmentDefinition =');
generator.withIndent(() => {
generator.withIndent(function () {
(0, _values3.multilineString)(generator, source);

@@ -228,5 +228,5 @@ });

function structDeclarationForSelectionSet(generator, _ref7, beforeClosure) {
let structName = _ref7.structName;
var _ref7$adoptedProtocol = _ref7.adoptedProtocols;
let adoptedProtocols = _ref7$adoptedProtocol === undefined ? ['GraphQLMappable'] : _ref7$adoptedProtocol,
var structName = _ref7.structName,
_ref7$adoptedProtocol = _ref7.adoptedProtocols,
adoptedProtocols = _ref7$adoptedProtocol === undefined ? ['GraphQLMappable'] : _ref7$adoptedProtocol,
parentType = _ref7.parentType,

@@ -238,3 +238,3 @@ possibleTypes = _ref7.possibleTypes,

(0, _language.structDeclaration)(generator, { structName: structName, adoptedProtocols: adoptedProtocols }, () => {
(0, _language.structDeclaration)(generator, { structName, adoptedProtocols }, function () {
if (beforeClosure) {

@@ -247,24 +247,26 @@ beforeClosure();

generator.printOnNewline('public static let possibleTypes = [');
generator.print((0, _printing.join)(possibleTypes.map(type => `"${String(type)}"`), ', '));
generator.print((0, _printing.join)(possibleTypes.map(function (type) {
return `"${String(type)}"`;
}), ', '));
generator.print(']');
}
const properties = fields && propertiesFromFields(generator.context, fields);
var properties = fields && propertiesFromFields(generator.context, fields);
const fragmentProperties = fragmentSpreads && fragmentSpreads.map(fragmentName => {
const fragment = generator.context.fragments[fragmentName];
var fragmentProperties = fragmentSpreads && fragmentSpreads.map(function (fragmentName) {
var fragment = generator.context.fragments[fragmentName];
if (!fragment) {
throw new _graphql.GraphQLError(`Cannot find fragment "${fragmentName}"`);
}
const propertyName = (0, _changeCase.camelCase)(fragmentName);
const typeName = typeNameForFragmentName(fragmentName);
const isProperSuperType = (0, _graphql2.isTypeProperSuperTypeOf)(generator.context.schema, fragment.typeCondition, parentType);
return { propertyName: propertyName, typeName: typeName, bareTypeName: typeName, isProperSuperType: isProperSuperType };
var propertyName = (0, _changeCase.camelCase)(fragmentName);
var typeName = typeNameForFragmentName(fragmentName);
var isProperSuperType = (0, _graphql2.isTypeProperSuperTypeOf)(generator.context.schema, fragment.typeCondition, parentType);
return { propertyName, typeName, bareTypeName: typeName, isProperSuperType };
});
const inlineFragmentProperties = inlineFragments && inlineFragments.map(inlineFragment => {
const bareTypeName = 'As' + (0, _changeCase.pascalCase)(String(inlineFragment.typeCondition));
const propertyName = (0, _changeCase.camelCase)(bareTypeName);
const typeName = bareTypeName + '?';
return (0, _extends3.default)({}, inlineFragment, { propertyName: propertyName, typeName: typeName, bareTypeName: bareTypeName });
var inlineFragmentProperties = inlineFragments && inlineFragments.map(function (inlineFragment) {
var bareTypeName = 'As' + (0, _changeCase.pascalCase)(String(inlineFragment.typeCondition));
var propertyName = (0, _changeCase.camelCase)(bareTypeName);
var typeName = bareTypeName + '?';
return (0, _extends3.default)({}, inlineFragment, { propertyName, typeName, bareTypeName });
});

@@ -292,3 +294,3 @@

generator.printOnNewline('public init(reader: GraphQLResultReader) throws');
generator.withinBlock(() => {
generator.withinBlock(function () {
if (parentType) {

@@ -299,3 +301,5 @@ generator.printOnNewline(`__typename = try reader.value(for: Field(responseName: "__typename"))`);

if (properties) {
properties.forEach(property => initializationForProperty(generator, property));
properties.forEach(function (property) {
return initializationForProperty(generator, property);
});
}

@@ -305,4 +309,4 @@

generator.printNewlineIfNeeded();
fragmentProperties.forEach((_ref8) => {
let propertyName = _ref8.propertyName,
fragmentProperties.forEach(function (_ref8) {
var propertyName = _ref8.propertyName,
typeName = _ref8.typeName,

@@ -320,4 +324,4 @@ bareTypeName = _ref8.bareTypeName,

generator.printOnNewline(`fragments = Fragments(`);
generator.print((0, _printing.join)(fragmentSpreads.map(fragmentName => {
const propertyName = (0, _changeCase.camelCase)(fragmentName);
generator.print((0, _printing.join)(fragmentSpreads.map(function (fragmentName) {
var propertyName = (0, _changeCase.camelCase)(fragmentName);
return `${propertyName}: ${propertyName}`;

@@ -330,4 +334,4 @@ }), ', '));

generator.printNewlineIfNeeded();
inlineFragmentProperties.forEach((_ref9) => {
let propertyName = _ref9.propertyName,
inlineFragmentProperties.forEach(function (_ref9) {
var propertyName = _ref9.propertyName,
typeName = _ref9.typeName,

@@ -344,5 +348,5 @@ bareTypeName = _ref9.bareTypeName;

structName: 'Fragments'
}, () => {
fragmentProperties.forEach((_ref10) => {
let propertyName = _ref10.propertyName,
}, function () {
fragmentProperties.forEach(function (_ref10) {
var propertyName = _ref10.propertyName,
typeName = _ref10.typeName,

@@ -354,3 +358,3 @@ isProperSuperType = _ref10.isProperSuperType;

}
(0, _language.propertyDeclaration)(generator, { propertyName: propertyName, typeName: typeName });
(0, _language.propertyDeclaration)(generator, { propertyName, typeName });
});

@@ -361,3 +365,3 @@ });

if (inlineFragmentProperties && inlineFragmentProperties.length > 0) {
inlineFragmentProperties.forEach(property => {
inlineFragmentProperties.forEach(function (property) {
structDeclarationForSelectionSet(generator, {

@@ -375,3 +379,5 @@ structName: property.bareTypeName,

if (properties) {
properties.filter(property => property.isComposite).forEach(property => {
properties.filter(function (property) {
return property.isComposite;
}).forEach(function (property) {
structDeclarationForSelectionSet(generator, {

@@ -390,3 +396,3 @@ structName: structNameForProperty(property),

function initializationForProperty(generator, _ref11) {
let propertyName = _ref11.propertyName,
var propertyName = _ref11.propertyName,
responseName = _ref11.responseName,

@@ -398,8 +404,8 @@ fieldName = _ref11.fieldName,

const isList = type instanceof _graphql.GraphQLList || type.ofType instanceof _graphql.GraphQLList;
var isList = type instanceof _graphql.GraphQLList || type.ofType instanceof _graphql.GraphQLList;
const methodName = isOptional ? isList ? 'optionalList' : 'optionalValue' : isList ? 'list' : 'value';
var methodName = isOptional ? isList ? 'optionalList' : 'optionalValue' : isList ? 'list' : 'value';
const fieldInitArgs = (0, _printing.join)([`responseName: "${responseName}"`, responseName != fieldName ? `fieldName: "${fieldName}"` : null, fieldArgs && fieldArgs.length && `arguments: ${dictionaryLiteralForFieldArguments(fieldArgs)}`], ', ');
const args = [`for: Field(${fieldInitArgs})`];
var fieldInitArgs = (0, _printing.join)([`responseName: "${responseName}"`, responseName != fieldName ? `fieldName: "${fieldName}"` : null, fieldArgs && fieldArgs.length && `arguments: ${dictionaryLiteralForFieldArguments(fieldArgs)}`], ', ');
var args = [`for: Field(${fieldInitArgs})`];

@@ -416,6 +422,5 @@ generator.printOnNewline(`${propertyName} = try reader.${methodName}(${(0, _printing.join)(args, ', ')})`);

} else if (typeof value === 'object') {
return (0, _printing.wrap)('[', (0, _printing.join)((0, _entries2.default)(value).map((_ref12) => {
var _ref13 = (0, _slicedToArray3.default)(_ref12, 2);
let key = _ref13[0],
return (0, _printing.wrap)('[', (0, _printing.join)((0, _entries2.default)(value).map(function (_ref12) {
var _ref13 = (0, _slicedToArray3.default)(_ref12, 2),
key = _ref13[0],
value = _ref13[1];

@@ -430,3 +435,3 @@

return (0, _printing.wrap)('[', (0, _printing.join)(args.map(arg => {
return (0, _printing.wrap)('[', (0, _printing.join)(args.map(function (arg) {
return `"${arg.name}": ${expressionFromValue(arg.value)}`;

@@ -437,20 +442,22 @@ }), ', ') || ':', ']');

function propertiesFromFields(context, fields) {
return fields.map(field => propertyFromField(context, field));
return fields.map(function (field) {
return propertyFromField(context, field);
});
}
function propertyFromField(context, field) {
const name = field.name || field.responseName;
const propertyName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(name));
var name = field.name || field.responseName;
var propertyName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(name));
const type = field.type;
const isOptional = field.isConditional || !(type instanceof _graphql.GraphQLNonNull);
const bareType = (0, _graphql.getNamedType)(type);
var type = field.type;
var isOptional = field.isConditional || !(type instanceof _graphql.GraphQLNonNull);
var bareType = (0, _graphql.getNamedType)(type);
if ((0, _graphql.isCompositeType)(bareType)) {
const bareTypeName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.pascalCase)(_inflected2.default.singularize(name)));
const typeName = (0, _types.typeNameFromGraphQLType)(context, type, bareTypeName, isOptional);
return (0, _extends3.default)({}, field, { propertyName: propertyName, typeName: typeName, bareTypeName: bareTypeName, isOptional: isOptional, isComposite: true });
var bareTypeName = (0, _language.escapeIdentifierIfNeeded)((0, _changeCase.pascalCase)(_inflected2.default.singularize(name)));
var typeName = (0, _types.typeNameFromGraphQLType)(context, type, bareTypeName, isOptional);
return (0, _extends3.default)({}, field, { propertyName, typeName, bareTypeName, isOptional, isComposite: true });
} else {
const typeName = (0, _types.typeNameFromGraphQLType)(context, type, undefined, isOptional);
return (0, _extends3.default)({}, field, { propertyName: propertyName, typeName: typeName, isOptional: isOptional, isComposite: false });
var _typeName = (0, _types.typeNameFromGraphQLType)(context, type, undefined, isOptional);
return (0, _extends3.default)({}, field, { propertyName, typeName: _typeName, isOptional, isComposite: false });
}

@@ -476,6 +483,6 @@ }

function enumerationDeclaration(generator, type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;
const values = type.getValues();
var values = type.getValues();

@@ -485,4 +492,6 @@ generator.printNewlineIfNeeded();

generator.printOnNewline(`public enum ${name}: String`);
generator.withinBlock(() => {
values.forEach(value => generator.printOnNewline(`case ${(0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(value.name))} = "${value.value}"${(0, _printing.wrap)(' /// ', value.description)}`));
generator.withinBlock(function () {
values.forEach(function (value) {
return generator.printOnNewline(`case ${(0, _language.escapeIdentifierIfNeeded)((0, _changeCase.camelCase)(value.name))} = "${value.value}"${(0, _printing.wrap)(' /// ', value.description)}`);
});
});

@@ -494,9 +503,9 @@ generator.printNewline();

function structDeclarationForInputObjectType(generator, type) {
const structName = type.name,
description = type.description;
var structName = type.name,
description = type.description;
const adoptedProtocols = ['GraphQLMapConvertible'];
const properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
var adoptedProtocols = ['GraphQLMapConvertible'];
var properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
(0, _language.structDeclaration)(generator, { structName: structName, description: description, adoptedProtocols: adoptedProtocols }, () => {
(0, _language.structDeclaration)(generator, { structName, description, adoptedProtocols }, function () {
generator.printOnNewline(`public var graphQLMap: GraphQLMap`);

@@ -507,4 +516,4 @@

generator.print('(');
generator.print((0, _printing.join)(properties.map((_ref14) => {
let propertyName = _ref14.propertyName,
generator.print((0, _printing.join)(properties.map(function (_ref14) {
var propertyName = _ref14.propertyName,
type = _ref14.type,

@@ -517,5 +526,5 @@ typeName = _ref14.typeName,

generator.withinBlock(() => {
generator.printOnNewline((0, _printing.wrap)(`graphQLMap = [`, (0, _printing.join)(properties.map((_ref15) => {
let name = _ref15.name,
generator.withinBlock(function () {
generator.printOnNewline((0, _printing.wrap)(`graphQLMap = [`, (0, _printing.join)(properties.map(function (_ref15) {
var name = _ref15.name,
propertyName = _ref15.propertyName;

@@ -522,0 +531,0 @@ return `"${name}": ${propertyName}`;

@@ -28,8 +28,14 @@ 'use strict';

function printDescription(generator, description) {
description && description.split('/n').forEach(function (line) {
generator.printOnNewline(`/// ${line.trim()}`);
});
}
function classDeclaration(generator, _ref, closure) {
let className = _ref.className,
var className = _ref.className,
modifiers = _ref.modifiers,
superClass = _ref.superClass;
var _ref$adoptedProtocols = _ref.adoptedProtocols;
let adoptedProtocols = _ref$adoptedProtocols === undefined ? [] : _ref$adoptedProtocols,
superClass = _ref.superClass,
_ref$adoptedProtocols = _ref.adoptedProtocols,
adoptedProtocols = _ref$adoptedProtocols === undefined ? [] : _ref$adoptedProtocols,
properties = _ref.properties;

@@ -48,9 +54,9 @@

function structDeclaration(generator, _ref2, closure) {
let structName = _ref2.structName,
description = _ref2.description;
var _ref2$adoptedProtocol = _ref2.adoptedProtocols;
let adoptedProtocols = _ref2$adoptedProtocol === undefined ? [] : _ref2$adoptedProtocol;
var structName = _ref2.structName,
description = _ref2.description,
_ref2$adoptedProtocol = _ref2.adoptedProtocols,
adoptedProtocols = _ref2$adoptedProtocol === undefined ? [] : _ref2$adoptedProtocol;
generator.printNewlineIfNeeded();
generator.printOnNewline(description && `/// ${description}`);
printDescription(generator, description);
generator.printOnNewline(`public struct ${structName}`);

@@ -64,8 +70,8 @@ generator.print((0, _printing.wrap)(': ', (0, _printing.join)(adoptedProtocols, ', ')));

function propertyDeclaration(generator, _ref3) {
let propertyName = _ref3.propertyName,
var propertyName = _ref3.propertyName,
typeName = _ref3.typeName,
description = _ref3.description;
printDescription(generator, description);
generator.printOnNewline(`public let ${propertyName}: ${typeName}`);
generator.print(description && ` /// ${description}`);
}

@@ -75,7 +81,9 @@

if (!properties) return;
properties.forEach(property => propertyDeclaration(generator, property));
properties.forEach(function (property) {
return propertyDeclaration(generator, property);
});
}
function protocolDeclaration(generator, _ref4, closure) {
let protocolName = _ref4.protocolName,
var protocolName = _ref4.protocolName,
adoptedProtocols = _ref4.adoptedProtocols,

@@ -93,3 +101,3 @@ properties = _ref4.properties;

function protocolPropertyDeclaration(generator, _ref5) {
let propertyName = _ref5.propertyName,
var propertyName = _ref5.propertyName,
typeName = _ref5.typeName;

@@ -102,6 +110,8 @@

if (!properties) return;
properties.forEach(property => protocolPropertyDeclaration(generator, property));
properties.forEach(function (property) {
return protocolPropertyDeclaration(generator, property);
});
}
const reservedKeywords = new _set2.default(['associatedtype', 'class', 'deinit', 'enum', 'extension', 'fileprivate', 'func', 'import', 'init', 'inout', 'internal', 'let', 'open', 'operator', 'private', 'protocol', 'public', 'static', 'struct', 'subscript', 'typealias', 'var', 'break', 'case', 'continue', 'default', 'defer', 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'repeat', 'return', 'switch', 'where', 'while', 'as', 'Any', 'catch', 'false', 'is', 'nil', 'rethrows', 'super', 'self', 'Self', 'throw', 'throws', 'true', 'try', 'associativity', 'convenience', 'dynamic', 'didSet', 'final', 'get', 'infix', 'indirect', 'lazy', 'left', 'mutating', 'none', 'nonmutating', 'optional', 'override', 'postfix', 'precedence', 'prefix', 'Protocol', 'required', 'right', 'set', 'Type', 'unowned', 'weak', 'willSet']);
var reservedKeywords = new _set2.default(['associatedtype', 'class', 'deinit', 'enum', 'extension', 'fileprivate', 'func', 'import', 'init', 'inout', 'internal', 'let', 'open', 'operator', 'private', 'protocol', 'public', 'static', 'struct', 'subscript', 'typealias', 'var', 'break', 'case', 'continue', 'default', 'defer', 'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'repeat', 'return', 'switch', 'where', 'while', 'as', 'Any', 'catch', 'false', 'is', 'nil', 'rethrows', 'super', 'self', 'Self', 'throw', 'throws', 'true', 'try', 'associativity', 'convenience', 'dynamic', 'didSet', 'final', 'get', 'infix', 'indirect', 'lazy', 'left', 'mutating', 'none', 'nonmutating', 'optional', 'override', 'postfix', 'precedence', 'prefix', 'Protocol', 'required', 'right', 'set', 'Type', 'unowned', 'weak', 'willSet']);

@@ -108,0 +118,0 @@ function escapeIdentifierIfNeeded(identifier) {

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

const builtInScalarMap = {
var builtInScalarMap = {
[_graphql.GraphQLString.name]: 'String',

@@ -30,3 +30,3 @@ [_graphql.GraphQLInt.name]: 'Int',

let typeName;
var typeName = void 0;
if (type instanceof _graphql.GraphQLList) {

@@ -33,0 +33,0 @@ typeName = '[' + typeNameFromGraphQLType(context, type.ofType, bareTypeName) + ']';

@@ -16,5 +16,5 @@ 'use strict';

function multilineString(context, string) {
const lines = string.split('\n');
lines.forEach((line, index) => {
const isLastLine = index != lines.length - 1;
var lines = string.split('\n');
lines.forEach(function (line, index) {
var isLastLine = index != lines.length - 1;
context.printOnNewline(`"${escapedString(line)}"` + (isLastLine ? ' +' : ''));

@@ -21,0 +21,0 @@ });

@@ -51,3 +51,3 @@ 'use strict';

function generateSource(context) {
const generator = new _CodeGenerator2.default(context);
var generator = new _CodeGenerator2.default(context);

@@ -57,8 +57,12 @@ generator.printOnNewline('// This file was automatically generated and should not be edited.');

typeDeclarationForGraphQLType(context.typesUsed.forEach(type => typeDeclarationForGraphQLType(generator, type)));
(0, _values2.default)(context.operations).forEach(operation => {
typeDeclarationForGraphQLType(context.typesUsed.forEach(function (type) {
return typeDeclarationForGraphQLType(generator, type);
}));
(0, _values2.default)(context.operations).forEach(function (operation) {
interfaceVariablesDeclarationForOperation(generator, operation);
interfaceDeclarationForOperation(generator, operation);
});
(0, _values2.default)(context.fragments).forEach(operation => interfaceDeclarationForFragment(generator, operation));
(0, _values2.default)(context.fragments).forEach(function (operation) {
return interfaceDeclarationForFragment(generator, operation);
});

@@ -80,6 +84,6 @@ generator.printOnNewline('/* tslint:enable */');

function enumerationDeclaration(generator, type) {
const name = type.name,
description = type.description;
var name = type.name,
description = type.description;
const values = type.getValues();
var values = type.getValues();

@@ -89,4 +93,6 @@ generator.printNewlineIfNeeded();

generator.printOnNewline(`export type ${name} =`);
const nValues = values.length;
values.forEach((value, i) => generator.printOnNewline(` "${value.value}"${i === nValues - 1 ? ';' : ' |'}${(0, _printing.wrap)(' // ', value.description)}`));
var nValues = values.length;
values.forEach(function (value, i) {
return generator.printOnNewline(` "${value.value}"${i === nValues - 1 ? ';' : ' |'}${(0, _printing.wrap)(' // ', value.description)}`);
});
generator.printNewline();

@@ -96,7 +102,7 @@ }

function structDeclarationForInputObjectType(generator, type) {
const interfaceName = (0, _changeCase.pascalCase)(type.name);
var interfaceName = (0, _changeCase.pascalCase)(type.name);
(0, _language.interfaceDeclaration)(generator, {
interfaceName: interfaceName
}, () => {
const properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
interfaceName
}, function () {
var properties = propertiesFromFields(generator.context, (0, _values2.default)(type.getFields()));
propertyDeclarations(generator, properties, true);

@@ -107,3 +113,3 @@ });

function interfaceNameFromOperation(_ref) {
let operationName = _ref.operationName,
var operationName = _ref.operationName,
operationType = _ref.operationType;

@@ -127,3 +133,3 @@

function interfaceVariablesDeclarationForOperation(generator, _ref2) {
let operationName = _ref2.operationName,
var operationName = _ref2.operationName,
operationType = _ref2.operationType,

@@ -138,8 +144,8 @@ variables = _ref2.variables,

}
const interfaceName = `${interfaceNameFromOperation({ operationName: operationName, operationType: operationType })}Variables`;
var interfaceName = `${interfaceNameFromOperation({ operationName, operationType })}Variables`;
(0, _language.interfaceDeclaration)(generator, {
interfaceName: interfaceName
}, () => {
const properties = propertiesFromFields(generator.context, variables);
interfaceName
}, function () {
var properties = propertiesFromFields(generator.context, variables);
propertyDeclarations(generator, properties, true);

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

function interfaceDeclarationForOperation(generator, _ref3) {
let operationName = _ref3.operationName,
var operationName = _ref3.operationName,
operationType = _ref3.operationType,

@@ -159,8 +165,10 @@ variables = _ref3.variables,

const interfaceName = interfaceNameFromOperation({ operationName: operationName, operationType: operationType });
var interfaceName = interfaceNameFromOperation({ operationName, operationType });
(0, _language.interfaceDeclaration)(generator, {
interfaceName: interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(f => `${(0, _changeCase.pascalCase)(f)}Fragment`) : null
}, () => {
const properties = propertiesFromFields(generator.context, fields);
interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(function (f) {
return `${(0, _changeCase.pascalCase)(f)}Fragment`;
}) : null
}, function () {
var properties = propertiesFromFields(generator.context, fields);
propertyDeclarations(generator, properties, true);

@@ -171,3 +179,3 @@ });

function interfaceDeclarationForFragment(generator, _ref4) {
let fragmentName = _ref4.fragmentName,
var fragmentName = _ref4.fragmentName,
typeCondition = _ref4.typeCondition,

@@ -179,11 +187,15 @@ fields = _ref4.fields,

const interfaceName = `${(0, _changeCase.pascalCase)(fragmentName)}Fragment`;
var interfaceName = `${(0, _changeCase.pascalCase)(fragmentName)}Fragment`;
(0, _language.interfaceDeclaration)(generator, {
interfaceName: interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(f => `${(0, _changeCase.pascalCase)(f)}Fragment`) : null
}, () => {
interfaceName,
extendTypes: fragmentSpreads ? fragmentSpreads.map(function (f) {
return `${(0, _changeCase.pascalCase)(f)}Fragment`;
}) : null
}, function () {
var _propertiesFromFields;
const properties = (_propertiesFromFields = propertiesFromFields(generator.context, fields)).concat.apply(_propertiesFromFields, (0, _toConsumableArray3.default)((inlineFragments || []).map(fragment => propertiesFromFields(generator.context, fragment.fields, true))));
var properties = (_propertiesFromFields = propertiesFromFields(generator.context, fields)).concat.apply(_propertiesFromFields, (0, _toConsumableArray3.default)((inlineFragments || []).map(function (fragment) {
return propertiesFromFields(generator.context, fragment.fields, true);
})));

@@ -195,7 +207,9 @@ propertyDeclarations(generator, properties, true);

function propertiesFromFields(context, fields, forceNullable) {
return fields.map(field => propertyFromField(context, field, forceNullable));
return fields.map(function (field) {
return propertyFromField(context, field, forceNullable);
});
}
function propertyFromField(context, field, forceNullable) {
let fieldName = field.name,
var fieldName = field.name,
fieldType = field.type,

@@ -208,12 +222,12 @@ description = field.description,

const propertyName = fieldName;
var propertyName = fieldName;
let property = { fieldName: fieldName, fieldType: fieldType, propertyName: propertyName, description: description };
var property = { fieldName, fieldType, propertyName, description };
const namedType = (0, _graphql.getNamedType)(fieldType);
var namedType = (0, _graphql.getNamedType)(fieldType);
if ((0, _graphql.isCompositeType)(namedType)) {
const bareTypeName = (0, _changeCase.pascalCase)(_inflected2.default.singularize(propertyName));
const typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType, bareTypeName);
let isArray = false;
var bareTypeName = (0, _changeCase.pascalCase)(_inflected2.default.singularize(propertyName));
var typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType, bareTypeName);
var isArray = false;
if (fieldType instanceof _graphql.GraphQLList) {

@@ -224,3 +238,3 @@ isArray = true;

}
let isNullable = true;
var isNullable = true;
if (fieldType instanceof _graphql.GraphQLNonNull && !forceNullable) {

@@ -230,8 +244,8 @@ isNullable = false;

return (0, _extends3.default)({}, property, {
typeName: typeName, bareTypeName: bareTypeName, fields: field.fields, isComposite: true, fragmentSpreads: fragmentSpreads, inlineFragments: inlineFragments, fieldType: fieldType,
isArray: isArray, isNullable: isNullable
typeName, bareTypeName, fields: field.fields, isComposite: true, fragmentSpreads, inlineFragments, fieldType,
isArray, isNullable
});
} else {
const typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType);
return (0, _extends3.default)({}, property, { typeName: typeName, isComposite: false, fieldType: fieldType });
var _typeName = (0, _types.typeNameFromGraphQLType)(context, fieldType);
return (0, _extends3.default)({}, property, { typeName: _typeName, isComposite: false, fieldType });
}

@@ -242,12 +256,14 @@ }

if (!properties) return;
properties.forEach(property => {
properties.forEach(function (property) {
if (property.fields && property.fields.length > 0 || property.inlineFragments && property.inlineFragments.length > 0) {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface: inInterface }), () => {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface }), function () {
var _propertiesFromFields2;
const properties = (_propertiesFromFields2 = propertiesFromFields(generator.context, property.fields)).concat.apply(_propertiesFromFields2, (0, _toConsumableArray3.default)((property.inlineFragments || []).map(fragment => propertiesFromFields(generator.context, fragment.fields, true))));
var properties = (_propertiesFromFields2 = propertiesFromFields(generator.context, property.fields)).concat.apply(_propertiesFromFields2, (0, _toConsumableArray3.default)((property.inlineFragments || []).map(function (fragment) {
return propertiesFromFields(generator.context, fragment.fields, true);
})));
propertyDeclarations(generator, properties);
});
} else {
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface: inInterface }));
(0, _language.propertyDeclaration)(generator, (0, _extends3.default)({}, property, { inInterface }));
}

@@ -254,0 +270,0 @@ });

@@ -15,3 +15,3 @@ 'use strict';

function interfaceDeclaration(generator, _ref, closure) {
let interfaceName = _ref.interfaceName,
var interfaceName = _ref.interfaceName,
extendTypes = _ref.extendTypes;

@@ -31,3 +31,3 @@

function propertyDeclaration(generator, _ref2, closure) {
let propertyName = _ref2.propertyName,
var propertyName = _ref2.propertyName,
typeName = _ref2.typeName,

@@ -47,3 +47,5 @@ description = _ref2.description,

if (fragmentSpreads && fragmentSpreads.length > 0) {
generator.print(` ${fragmentSpreads.map(n => `${(0, _changeCase.pascalCase)(n)}Fragment`).join(' & ')} &`);
generator.print(` ${fragmentSpreads.map(function (n) {
return `${(0, _changeCase.pascalCase)(n)}Fragment`;
}).join(' & ')} &`);
}

@@ -60,3 +62,5 @@ generator.pushScope({ typeName: propertyName });

} else if (fragmentSpreads && fragmentSpreads.length > 0) {
generator.printOnNewline(`${propertyName}: ${isArray ? 'Array<' : ''}${fragmentSpreads.map(n => `${(0, _changeCase.pascalCase)(n)}Fragment`).join(' & ')}${isArray ? '>' : ''}`);
generator.printOnNewline(`${propertyName}: ${isArray ? 'Array<' : ''}${fragmentSpreads.map(function (n) {
return `${(0, _changeCase.pascalCase)(n)}Fragment`;
}).join(' & ')}${isArray ? '>' : ''}`);
} else {

@@ -70,4 +74,6 @@ generator.printOnNewline(`${propertyName}: ${typeName}`);

if (!properties) return;
properties.forEach(property => propertyDeclaration(generator, property));
properties.forEach(function (property) {
return propertyDeclaration(generator, property);
});
}
//# sourceMappingURL=language.js.map

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

const builtInScalarMap = {
var builtInScalarMap = {
[_graphql.GraphQLString.name]: 'string',

@@ -24,3 +24,3 @@ [_graphql.GraphQLInt.name]: 'number',

function typeNameFromGraphQLType(context, type, bareTypeName) {
let nullable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var nullable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

@@ -31,3 +31,3 @@ if (type instanceof _graphql.GraphQLNonNull) {

let typeName;
var typeName = void 0;
if (type instanceof _graphql.GraphQLList) {

@@ -34,0 +34,0 @@ typeName = `Array< ${typeNameFromGraphQLType(context, type.ofType, bareTypeName, true)} >`;

@@ -7,6 +7,18 @@ 'use strict';

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _printing = require('./printing');
class CodeGenerator {
constructor(context) {
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CodeGenerator = function () {
function CodeGenerator(context) {
(0, _classCallCheck3.default)(this, CodeGenerator);
this.context = context;

@@ -22,61 +34,74 @@

pushScope(scope) {
this.scopeStack.push(scope);
}
popScope() {
return this.scopeStack.pop();
}
print(maybeString) {
if (maybeString) {
this.output += maybeString;
(0, _createClass3.default)(CodeGenerator, [{
key: 'pushScope',
value: function pushScope(scope) {
this.scopeStack.push(scope);
}
}
printNewline() {
if (this.output) {
this.print('\n');
this.startOfIndentLevel = false;
}, {
key: 'popScope',
value: function popScope() {
return this.scopeStack.pop();
}
}
}, {
key: 'print',
value: function print(maybeString) {
if (maybeString) {
this.output += maybeString;
}
}
}, {
key: 'printNewline',
value: function printNewline() {
if (this.output) {
this.print('\n');
this.startOfIndentLevel = false;
}
}
}, {
key: 'printNewlineIfNeeded',
value: function printNewlineIfNeeded() {
if (!this.startOfIndentLevel) {
this.printNewline();
}
}
}, {
key: 'printOnNewline',
value: function printOnNewline(maybeString) {
if (maybeString) {
this.printNewline();
this.printIndent();
this.print(maybeString);
}
}
}, {
key: 'printIndent',
value: function printIndent() {
var indentation = ' '.repeat(this.indentLevel * this.indentWidth);
this.output += indentation;
}
}, {
key: 'withIndent',
value: function withIndent(closure) {
if (!closure) return;
printNewlineIfNeeded() {
if (!this.startOfIndentLevel) {
this.printNewline();
this.indentLevel++;
this.startOfIndentLevel = true;
closure();
this.indentLevel--;
}
}
}, {
key: 'withinBlock',
value: function withinBlock(closure) {
var open = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' {';
var close = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '}';
printOnNewline(maybeString) {
if (maybeString) {
this.printNewline();
this.printIndent();
this.print(maybeString);
this.print(open);
this.withIndent(closure);
this.printOnNewline(close);
}
}
}]);
return CodeGenerator;
}();
printIndent() {
const indentation = ' '.repeat(this.indentLevel * this.indentWidth);
this.output += indentation;
}
withIndent(closure) {
if (!closure) return;
this.indentLevel++;
this.startOfIndentLevel = true;
closure();
this.indentLevel--;
}
withinBlock(closure) {
let open = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' {';
let close = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '}';
this.print(open);
this.withIndent(closure);
this.printOnNewline(close);
}
}
exports.default = CodeGenerator;
//# sourceMappingURL=CodeGenerator.js.map

@@ -20,3 +20,3 @@ 'use strict';

function filePathForNode(node) {
const name = node.loc.source && node.loc.source.name;
var name = node.loc.source && node.loc.source.name;
return name === "GraphQL" ? undefined : name;

@@ -26,3 +26,3 @@ }

function valueFromValueNode(valueNode) {
const kind = valueNode.kind;
var kind = valueNode.kind;

@@ -36,3 +36,3 @@ if (kind === 'IntValue' || kind === 'FloatValue') {

} else if (kind === 'ObjectValue') {
return valueNode.fields.reduce((object, field) => {
return valueNode.fields.reduce(function (object, field) {
object[field.name.value] = valueFromValueNode(field.value);

@@ -42,3 +42,3 @@ return object;

} else if (kind === 'Variable') {
return { kind: kind, variableName: valueNode.name.value };
return { kind, variableName: valueNode.name.value };
} else {

@@ -63,3 +63,3 @@ return valueNode.value;

case 'mutation':
const mutationType = schema.getMutationType();
var mutationType = schema.getMutationType();
if (!mutationType) {

@@ -70,3 +70,3 @@ throw new GraphQLError('Schema is not configured for mutations', [operation]);

case 'subscription':
const subscriptionType = schema.getSubscriptionType();
var subscriptionType = schema.getSubscriptionType();
if (!subscriptionType) {

@@ -87,3 +87,3 @@ throw new GraphQLError('Schema is not configured for subscriptions', [operation]);

function getFieldDef(schema, parentType, fieldAST) {
const name = fieldAST.name.value;
var name = fieldAST.name.value;
if (name === _graphql.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {

@@ -90,0 +90,0 @@ return _graphql.SchemaMetaFieldDef;

@@ -17,3 +17,5 @@ 'use strict';

function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
}

@@ -20,0 +22,0 @@

@@ -6,2 +6,7 @@ 'use strict';

});
var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.validateQueryDocument = validateQueryDocument;

@@ -16,10 +21,34 @@ exports.NoAnonymousQueries = NoAnonymousQueries;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function validateQueryDocument(schema, document) {
const rules = [NoAnonymousQueries, NoExplicitTypename, NoTypenameAlias].concat(_graphql.specifiedRules);
var rules = [NoAnonymousQueries, NoExplicitTypename, NoTypenameAlias].concat(_graphql.specifiedRules);
const validationErrors = (0, _graphql.validate)(schema, document, rules);
var validationErrors = (0, _graphql.validate)(schema, document, rules);
if (validationErrors && validationErrors.length > 0) {
for (const error of validationErrors) {
(0, _errors.logError)(error);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(validationErrors), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var error = _step.value;
(0, _errors.logError)(error);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
throw new _errors.ToolError("Validation of GraphQL query document failed");

@@ -31,3 +60,3 @@ }

return {
OperationDefinition: function OperationDefinition(node) {
OperationDefinition(node) {
if (!node.name) {

@@ -43,4 +72,4 @@ context.reportError(new _graphql.GraphQLError('Apollo does not support anonymous operations', [node]));

return {
Field: function Field(node) {
const fieldName = node.name.value;
Field(node) {
var fieldName = node.name.value;
if (fieldName == "__typename") {

@@ -55,4 +84,4 @@ context.reportError(new _graphql.GraphQLError('Apollo inserts __typename automatically when needed, please do not include it explicitly', [node]));

return {
Field: function Field(node) {
const aliasName = node.alias && node.alias.value;
Field(node) {
var aliasName = node.alias && node.alias.value;
if (aliasName == "__typename") {

@@ -59,0 +88,0 @@ context.reportError(new _graphql.GraphQLError('Apollo needs to be able to insert __typename when needed, please do not use it as an alias', [node]));

{
"name": "apollo-codegen",
"version": "0.10.11",
"version": "0.10.12",
"description": "Generate API code or type annotations based on a GraphQL schema and query documents",

@@ -11,3 +11,3 @@ "main": "./lib/index.js",

"prepublish": "rm -rf lib && npm run compile",
"test": "mocha --recursive --compilers js:babel-register"
"test": "jest"
},

@@ -24,10 +24,10 @@ "repository": {

"devDependencies": {
"babel-cli": "^6.11.4",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-full-node4": "^1.0.0",
"babel-register": "^6.16.3",
"chai": "^3.5.0",
"chai-subset": "^1.3.0",
"babel-cli": "^6.24.1",
"babel-jest": "^19.0.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.4.0",
"babel-register": "^6.24.1",
"common-tags": "^1.3.0",
"mocha": "^3.1.2"
"jest": "^19.0.2"
},

@@ -39,3 +39,3 @@ "dependencies": {

"change-case": "^3.0.0",
"graphql": "^0.9.1",
"graphql": "^0.9.5",
"inflected": "^1.1.7",

@@ -45,3 +45,13 @@ "mkdirp": "^0.5.1",

"yargs": "^7.0.1"
},
"jest": {
"testMatch": [
"**/test/**/*.js",
"**/test/*.js"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/lib/"
]
}
}

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

import chai, { expect } from 'chai'
import chaiSubset from 'chai-subset'
chai.use(chaiSubset);
import { stripIndent } from 'common-tags'

@@ -24,3 +20,3 @@

describe('Compiling query documents', () => {
it(`should include variables defined in operations`, () => {
test(`should include variables defined in operations`, () => {
const document = parse(`

@@ -51,23 +47,8 @@ query HeroName($episode: Episode) {

expect(filteredIR(operations['HeroName']).variables).to.deep.equal(
[
{ name: 'episode', type: 'Episode' }
]
);
expect(filteredIR(operations['Search']).variables).to.deep.equal(
[
{ name: 'text', type: 'String!' }
]
);
expect(filteredIR(operations['CreateReviewForEpisode']).variables).to.deep.equal(
[
{ name: 'episode', type: 'Episode!' },
{ name: 'review', type: 'ReviewInput!' }
]
);
expect(filteredIR(operations['HeroName']).variables).toMatchSnapshot();
expect(filteredIR(operations['Search']).variables).toMatchSnapshot();
expect(filteredIR(operations['CreateReviewForEpisode']).variables).toMatchSnapshot();
});
it(`should keep track of enums and input object types used in variables`, () => {
test(`should keep track of enums and input object types used in variables`, () => {
const document = parse(`

@@ -98,6 +79,6 @@ query HeroName($episode: Episode) {

expect(filteredIR(typesUsed)).to.deep.equal(['Episode', 'ReviewInput', 'ColorInput']);
expect(filteredIR(typesUsed)).toEqual(['Episode', 'ReviewInput', 'ColorInput']);
});
it(`should keep track of enums used in fields`, () => {
test(`should keep track of enums used in fields`, () => {
const document = parse(`

@@ -118,6 +99,6 @@ query Hero {

expect(filteredIR(typesUsed)).to.deep.equal(['Episode']);
expect(filteredIR(typesUsed)).toEqual(['Episode']);
});
it(`should keep track of types used in fields of input objects`, () => {
test(`should keep track of types used in fields of input objects`, () => {
const bookstore_schema = loadSchema(require.resolve('./bookstore/schema.json'));

@@ -151,7 +132,7 @@ const document = parse(`

const { typesUsed } = compileToIR(bookstore_schema, document);
expect(filteredIR(typesUsed)).to.deep.include('IdInput');
expect(filteredIR(typesUsed)).to.deep.include('WrittenByInput');
expect(filteredIR(typesUsed)).toContain('IdInput');
expect(filteredIR(typesUsed)).toContain('WrittenByInput');
});
it(`should include the original field name for an aliased field`, () => {
test(`should include the original field name for an aliased field`, () => {
const document = parse(`

@@ -170,6 +151,6 @@ query HeroName {

expect(operations['HeroName'].fields[0].fieldName).to.equal("hero");
expect(operations['HeroName'].fields[0].fieldName).toBe("hero");
});
it(`should include field arguments`, () => {
test(`should include field arguments`, () => {
const document = parse(`

@@ -186,6 +167,6 @@ query HeroName {

expect(operations['HeroName'].fields[0].args)
.to.deep.equal([{ name: "episode", value: "EMPIRE" }]);
.toEqual([{ name: "episode", value: "EMPIRE" }]);
});
it(`should include isOptional if a field has skip or include directives`, () => {
test(`should include isOptional if a field has skip or include directives`, () => {
const document = parse(`

@@ -207,52 +188,7 @@ query HeroNameConditionalInclusion {

expect(filteredIR(operations['HeroNameConditionalInclusion'])).to.deep.equal({
operationName: 'HeroNameConditionalInclusion',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!',
isConditional: true
},
],
fragmentSpreads: [],
inlineFragments: []
}
]
});
expect(filteredIR(operations['HeroNameConditionalExclusion'])).to.deep.equal({
operationName: 'HeroNameConditionalExclusion',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!',
isConditional: true
},
],
fragmentSpreads: [],
inlineFragments: []
}
]
});
expect(filteredIR(operations['HeroNameConditionalInclusion'])).toMatchSnapshot();
expect(filteredIR(operations['HeroNameConditionalExclusion'])).toMatchSnapshot();
});
it(`should recursively flatten inline fragments with type conditions that match the parent type`, () => {
test(`should recursively flatten inline fragments with type conditions that match the parent type`, () => {
const document = parse(`

@@ -276,37 +212,6 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
},
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'appearsIn',
fieldName: 'appearsIn',
type: '[Episode]!'
}
],
fragmentSpreads: [],
inlineFragments: []
}
]
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
});
it(`should recursively include fragment spreads with type conditions that match the parent type`, () => {
test(`should recursively include fragment spreads with type conditions that match the parent type`, () => {
const document = parse(`

@@ -334,68 +239,8 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: ['HeroDetails', 'MoreHeroDetails'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
}
],
fragmentSpreads: ['HeroDetails', 'MoreHeroDetails'],
inlineFragments: [],
}
],
});
expect(filteredIR(fragments['HeroDetails'])).to.deep.equal({
fragmentName: 'HeroDetails',
typeCondition: 'Character',
fragmentsReferenced: ['MoreHeroDetails'],
fields: [
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
},
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
fragmentSpreads: ['MoreHeroDetails'],
inlineFragments: [],
possibleTypes: ['Human', 'Droid']
});
expect(filteredIR(fragments['MoreHeroDetails'])).to.deep.equal({
fragmentName: 'MoreHeroDetails',
typeCondition: 'Character',
fragmentsReferenced: [],
fields: [
{ responseName: 'appearsIn',
fieldName: 'appearsIn',
type: '[Episode]!'
},
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
}
],
fragmentSpreads: [],
inlineFragments: [],
possibleTypes: ['Human', 'Droid']
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
expect(filteredIR(fragments['HeroDetails'])).toMatchSnapshot();
expect(filteredIR(fragments['MoreHeroDetails'])).toMatchSnapshot();
});
it(`should include fragment spreads from subselections`, () => {
test(`should include fragment spreads from subselections`, () => {
const document = parse(`

@@ -422,66 +267,7 @@ query HeroAndFriends {

expect(filteredIR(operations['HeroAndFriends'])).to.deep.equal({
operationName: 'HeroAndFriends',
operationType: 'query',
variables: [],
fragmentsReferenced: ['HeroDetails'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{ responseName: 'appearsIn',
fieldName: 'appearsIn',
type: '[Episode]!'
},
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
},
{
responseName: 'friends',
fieldName: 'friends',
type: '[Character]',
fields: [
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
}
],
fragmentSpreads: ['HeroDetails'],
inlineFragments: []
}
],
fragmentSpreads: ['HeroDetails'],
inlineFragments: []
}
]
});
expect(filteredIR(fragments['HeroDetails'])).to.deep.equal({
fragmentName: 'HeroDetails',
typeCondition: 'Character',
possibleTypes: ['Human', 'Droid'],
fragmentsReferenced: [],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'id',
fieldName: 'id',
type: 'ID!'
}
],
fragmentSpreads: [],
inlineFragments: []
});
expect(filteredIR(operations['HeroAndFriends'])).toMatchSnapshot();
expect(filteredIR(fragments['HeroDetails'])).toMatchSnapshot();
});
it(`should include type conditions with merged fields for inline fragments`, () => {
test(`should include type conditions with merged fields for inline fragments`, () => {
const document = parse(`

@@ -503,62 +289,6 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
fragmentSpreads: [],
inlineFragments: [
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'primaryFunction',
fieldName: 'primaryFunction',
type: 'String'
},
],
fragmentSpreads: []
},
{
typeCondition: 'Human',
possibleTypes: ['Human'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'height',
fieldName: 'height',
type: 'Float'
},
],
fragmentSpreads: []
}
]
}
]
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
});
it(`should include fragment spreads with type conditions`, () => {
test(`should include fragment spreads with type conditions`, () => {
const document = parse(`

@@ -584,59 +314,8 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: ['DroidDetails', 'HumanDetails'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fragmentSpreads: ['DroidDetails', 'HumanDetails'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
inlineFragments: []
}
]
});
expect(filteredIR(fragments['DroidDetails'])).to.deep.equal({
fragmentName: 'DroidDetails',
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fragmentsReferenced: [],
fields: [
{
responseName: 'primaryFunction',
fieldName: 'primaryFunction',
type: 'String'
}
],
fragmentSpreads: [],
inlineFragments: []
});
expect(filteredIR(fragments['HumanDetails'])).to.deep.equal({
fragmentName: 'HumanDetails',
typeCondition: 'Human',
possibleTypes: ['Human'],
fragmentsReferenced: [],
fields: [
{
responseName: 'height',
fieldName: 'height',
type: 'Float'
}
],
fragmentSpreads: [],
inlineFragments: []
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
expect(filteredIR(fragments['DroidDetails'])).toMatchSnapshot();
expect(filteredIR(fragments['HumanDetails'])).toMatchSnapshot();
});
it(`should not include type conditions for fragment spreads with type conditions that match the parent type`, () => {
test(`should not include type conditions for fragment spreads with type conditions that match the parent type`, () => {
const document = parse(`

@@ -657,27 +336,6 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: ['HeroDetails'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fragmentSpreads: ['HeroDetails'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
inlineFragments: []
}
],
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
});
it(`should include type conditions for inline fragments in fragments`, () => {
test(`should include type conditions for inline fragments in fragments`, () => {
const document = parse(`

@@ -703,72 +361,7 @@ query Hero {

expect(filteredIR(operations['Hero'])).to.deep.equal({
operationName: 'Hero',
operationType: 'query',
variables: [],
fragmentsReferenced: ['HeroDetails'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [],
fragmentSpreads: ['HeroDetails'],
inlineFragments: []
}
]
});
expect(filteredIR(fragments['HeroDetails'])).to.deep.equal({
fragmentName: 'HeroDetails',
typeCondition: 'Character',
possibleTypes: ['Human', 'Droid'],
fragmentsReferenced: [],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
fragmentSpreads: [],
inlineFragments: [
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'primaryFunction',
fieldName: 'primaryFunction',
type: 'String'
},
],
fragmentSpreads: []
},
{
typeCondition: 'Human',
possibleTypes: ['Human'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'height',
fieldName: 'height',
type: 'Float'
},
],
fragmentSpreads: []
}
]
});
expect(filteredIR(operations['Hero'])).toMatchSnapshot();
expect(filteredIR(fragments['HeroDetails'])).toMatchSnapshot();
});
it(`should inherit type condition when nesting an inline fragment in an inline fragment with a more specific type condition`, () => {
test(`should inherit type condition when nesting an inline fragment in an inline fragment with a more specific type condition`, () => {
const document = parse(`

@@ -788,34 +381,6 @@ query HeroName {

expect(filteredIR(operations['HeroName'])).to.deep.equal({
operationName: 'HeroName',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [],
fragmentSpreads: [],
inlineFragments: [
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
fragmentSpreads: []
}
]
}
]
});
expect(filteredIR(operations['HeroName'])).toMatchSnapshot();
});
it(`should not inherit type condition when nesting an inline fragment in an inline fragment with a less specific type condition`, () => {
test(`should not inherit type condition when nesting an inline fragment in an inline fragment with a less specific type condition`, () => {
const document = parse(`

@@ -835,34 +400,6 @@ query HeroName {

expect(filteredIR(operations['HeroName'])).to.deep.equal({
operationName: 'HeroName',
operationType: 'query',
variables: [],
fragmentsReferenced: [],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [],
fragmentSpreads: [],
inlineFragments: [
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
}
],
fragmentSpreads: [],
}
]
}
]
});
expect(filteredIR(operations['HeroName'])).toMatchSnapshot();
});
it(`should inherit type condition when nesting a fragment spread in an inline fragment with a more specific type condition`, () => {
test(`should inherit type condition when nesting a fragment spread in an inline fragment with a more specific type condition`, () => {
const document = parse(`

@@ -884,28 +421,32 @@ query HeroName {

expect(filteredIR(operations['HeroName'])).to.deep.equal({
operationName: 'HeroName',
operationType: 'query',
variables: [],
fragmentsReferenced: ['HeroName'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [],
fragmentSpreads: [],
inlineFragments: [
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fragmentSpreads: ['HeroName'],
fields: [],
}
]
expect(filteredIR(operations['HeroName'])).toMatchSnapshot();
});
test(`should ignore a fragment's inline fragments whose type conditions do not match more specific effective type`, () => {
const document = parse(`
fragment CharacterFragment on Character {
... on Droid {
primaryFunction
}
]
});
... on Human {
height
}
}
query HumanAndDroid {
human(id: "human") {
...CharacterFragment
}
droid(id: "droid") {
...CharacterFragment
}
}
`);
const { operations } = compileToIR(schema, document);
expect(filteredIR(operations['HumanAndDroid'])).toMatchSnapshot();
});
it(`should not inherit type condition when nesting a fragment spread in an inline fragment with a less specific type condition`, () => {
test(`should not inherit type condition when nesting a fragment spread in an inline fragment with a less specific type condition`, () => {
const document = parse(`

@@ -926,22 +467,6 @@ query HeroName {

const { operations } = compileToIR(schema, document);
expect(filteredIR(operations['HeroName'])).to.deep.equal({
operationName: 'HeroName',
operationType: 'query',
variables: [],
fragmentsReferenced: ['DroidName'],
fields: [
{
responseName: 'hero',
fieldName: 'hero',
type: 'Character',
fields: [],
fragmentSpreads: ['DroidName'],
inlineFragments: []
}
]
});
expect(filteredIR(operations['HeroName'])).toMatchSnapshot();
});
it(`should include type conditions for inline fragments on a union type`, () => {
test(`should include type conditions for inline fragments on a union type`, () => {
const document = parse(`

@@ -965,41 +490,6 @@ query Search {

expect(filteredIR(operations['Search']).fields[0].inlineFragments).to.deep.equal([
{
typeCondition: 'Droid',
possibleTypes: ['Droid'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'primaryFunction',
fieldName: 'primaryFunction',
type: 'String'
},
],
fragmentSpreads: [],
},
{
typeCondition: 'Human',
possibleTypes: ['Human'],
fields: [
{
responseName: 'name',
fieldName: 'name',
type: 'String!'
},
{
responseName: 'height',
fieldName: 'height',
type: 'Float'
},
],
fragmentSpreads: [],
}
]);
expect(filteredIR(operations['Search']).fields[0].inlineFragments).toMatchSnapshot();
});
it(`should keep track of fragments referenced in a subselection`, () => {
test(`should keep track of fragments referenced in a subselection`, () => {
const document = parse(`

@@ -1022,6 +512,6 @@ query HeroAndFriends {

expect(operations['HeroAndFriends'].fragmentsReferenced).to.deep.equal(['HeroDetails']);
expect(operations['HeroAndFriends'].fragmentsReferenced).toEqual(['HeroDetails']);
});
it(`should keep track of fragments referenced in a fragment within a subselection`, () => {
test(`should keep track of fragments referenced in a fragment within a subselection`, () => {
const document = parse(`

@@ -1047,6 +537,6 @@ query HeroAndFriends {

expect(operations['HeroAndFriends'].fragmentsReferenced).to.deep.equal(['HeroDetails', 'HeroName']);
expect(operations['HeroAndFriends'].fragmentsReferenced).toEqual(['HeroDetails', 'HeroName']);
});
it(`should keep track of fragments referenced in a subselection nested in an inline fragment`, () => {
test(`should keep track of fragments referenced in a subselection nested in an inline fragment`, () => {
const document = parse(`

@@ -1071,6 +561,6 @@ query HeroAndFriends {

expect(operations['HeroAndFriends'].fragmentsReferenced).to.deep.equal(['HeroDetails']);
expect(operations['HeroAndFriends'].fragmentsReferenced).toEqual(['HeroDetails']);
});
it(`should include the source of operations with __typename added for abstract types`, () => {
test(`should include the source of operations with __typename added for abstract types`, () => {
const source = stripIndent`

@@ -1087,13 +577,6 @@ query HeroName {

expect(operations['HeroName'].source).to.equal(stripIndent`
query HeroName {
hero {
__typename
name
}
}
`);
expect(operations['HeroName'].source).toMatchSnapshot();
});
it(`should include the source of fragments with __typename added for abstract types`, () => {
test(`should include the source of fragments with __typename added for abstract types`, () => {
const source = stripIndent`

@@ -1108,3 +591,3 @@ fragment HeroDetails on Character {

expect(fragments['HeroDetails'].source).to.equal(stripIndent`
expect(fragments['HeroDetails'].source).toBe(stripIndent`
fragment HeroDetails on Character {

@@ -1117,3 +600,3 @@ __typename

it(`should include the operationType for a query`, () => {
test(`should include the operationType for a query`, () => {
const source = stripIndent`

@@ -1130,6 +613,6 @@ query HeroName {

expect(operations['HeroName'].operationType).to.equal('query');
expect(operations['HeroName'].operationType).toBe('query');
});
it(`should include the operationType for a mutation`, () => {
test(`should include the operationType for a mutation`, () => {
const source = stripIndent`

@@ -1147,3 +630,3 @@ mutation CreateReview {

expect(operations['CreateReview'].operationType).to.equal('mutation');
expect(operations['CreateReview'].operationType).toBe('mutation');
});

@@ -1150,0 +633,0 @@ });

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

import { expect } from 'chai';
import { stripIndent } from 'common-tags';
import {

@@ -45,3 +41,3 @@ parse,

const addFragment = (fragment) => {
this.generator.context.fragments[fragment.fragmentName] = fragment;
generator.context.fragments[fragment.fragmentName] = fragment;
};

@@ -54,3 +50,3 @@

describe('#generateSource()', function() {
it(`should generate simple query operations`, function() {
test(`should generate simple query operations`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -66,16 +62,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
export type HeroNameQuery = {|
hero: ? {|
name: string,
|},
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate simple query operations including input variables`, function() {
test(`should generate simple query operations including input variables`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -91,27 +77,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export type HeroNameQueryVariables = {|
episode: ?Episode,
|};
export type HeroNameQuery = {|
hero: ? {|
name: string,
|},
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate simple nested query operations including input variables`, function() {
test(`should generate simple nested query operations including input variables`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -130,30 +95,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export type HeroAndFriendsNamesQueryVariables = {|
episode: ?Episode,
|};
export type HeroAndFriendsNamesQuery = {|
hero: ? {|
name: string,
friends: ?Array< {|
name: string,
|} >,
|},
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate fragmented query operations`, function() {
test(`should generate fragmented query operations`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -176,23 +117,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
export type HeroAndFriendsNamesQuery = {|
hero: ? {|
...HeroFriendsFragment,
name: string,
|},
|};
export type HeroFriendsFragment = {|
friends: ?Array< {|
name: string,
|} >,
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate query operations with inline fragments`, function() {
test(`should generate query operations with inline fragments`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -218,22 +142,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
export type HeroAndDetailsQuery = {|
hero: ? {|
...HeroDetailsFragment,
name: string,
|},
|};
export type HeroDetailsFragment = {|
primaryFunction: ?string,
height: ?number,
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate mutation operations with complex input types`, function() {
test(`should generate mutation operations with complex input types`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -250,44 +158,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export type ReviewInput = {|
// 0-5 stars
stars: number,
// Comment about the movie, optional
commentary: ?string,
// Favorite color, optional
favorite_color: ?ColorInput,
|};
export type ColorInput = {|
red: number,
green: number,
blue: number,
|};
export type ReviewMovieMutationVariables = {|
episode: ?Episode,
review: ?ReviewInput,
|};
export type ReviewMovieMutation = {|
createReview: ? {|
stars: number,
commentary: ?string,
|},
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate correct typedefs with a single custom fragment`, function() {
test(`should generate correct typedefs with a single custom fragment`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -310,32 +180,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export type HeroAndFriendsNamesQueryVariables = {|
episode: ?Episode,
|};
export type HeroAndFriendsNamesQuery = {|
hero: ? {|
name: string,
friends: Array<FriendFragment>,
|},
|};
export type FriendFragment = {|
name: string,
|};
`);
expect(source).toMatchSnapshot();
});
it(`should generate correct typedefs with a multiple custom fragments`, function() {
test(`should generate correct typedefs with a multiple custom fragments`, function() {
const { compileFromSource } = setup(swapiSchema);

@@ -363,39 +207,6 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export type HeroAndFriendsNamesQueryVariables = {|
episode: ?Episode,
|};
export type HeroAndFriendsNamesQuery = {|
hero: ? {|
name: string,
friends: Array<{|
...FriendFragment,
...PersonFragment,
|}>,
|},
|};
export type FriendFragment = {|
name: string,
|};
export type PersonFragment = {|
name: string,
|};
`);
expect(source).toMatchSnapshot();
});
it(`should annotate custom scalars as string`, function() {
test(`should annotate custom scalars as string`, function() {
const { compileFromSource } = setup(miscSchema);

@@ -411,15 +222,5 @@ const context = compileFromSource(`

const source = generateSource(context);
expect(source).to.include(stripIndent`
/* @flow */
// This file was automatically generated and should not be edited.
export type CustomScalarQuery = {|
misc: ? {|
date: ?any,
|},
|};
`);
expect(source).toMatchSnapshot();
});
});
});

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

import chai, { expect } from 'chai'
import { readFileSync } from 'fs'

@@ -8,3 +7,3 @@ import { join } from 'path'

describe('Introspecting GraphQL schema documents', () => {
it(`should generate valid introspection JSON file`, async () => {
test(`should generate valid introspection JSON file`, async () => {
const schemaContents = readFileSync(join(__dirname, './starwars/schema.graphql')).toString();

@@ -15,4 +14,4 @@ const expected = readFileSync(join(__dirname, './starwars/schema.json')).toString();

expect(JSON.stringify(schema, null, 2)).to.be.equal(expected);
expect(JSON.stringify(schema, null, 2)).toEqual(expected);
});
})
})

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

import { expect } from 'chai';
import { stripIndent } from 'common-tags';

@@ -34,2 +32,6 @@

describe('Swift code generation', function() {
let generator;
let compileFromSource;
let addFragment;
beforeEach(function() {

@@ -43,13 +45,13 @@ const context = {

this.generator = new CodeGenerator(context);
generator = new CodeGenerator(context);
this.compileFromSource = (source) => {
compileFromSource = (source) => {
const document = parse(source);
const context = compileToIR(schema, document);
this.generator.context = context;
generator.context = context;
return context;
};
this.addFragment = (fragment) => {
this.generator.context.fragments[fragment.fragmentName] = fragment;
addFragment = (fragment) => {
generator.context.fragments[fragment.fragmentName] = fragment;
};

@@ -59,4 +61,4 @@ });

describe('#classDeclarationForOperation()', function() {
it(`should generate a class declaration for a query with variables`, function() {
const { operations } = this.compileFromSource(`
test(`should generate a class declaration for a query with variables`, function() {
const { operations } = compileFromSource(`
query HeroName($episode: Episode) {

@@ -69,28 +71,8 @@ hero(episode: $episode) {

classDeclarationForOperation(this.generator, operations['HeroName']);
expect(this.generator.output).to.include(stripIndent`
public final class HeroNameQuery: GraphQLQuery {
public static let operationDefinition =
"query HeroName($episode: Episode) {" +
" hero(episode: $episode) {" +
" __typename" +
" name" +
" }" +
"}"
public let episode: Episode?
public init(episode: Episode? = nil) {
self.episode = episode
}
public var variables: GraphQLMap? {
return ["episode": episode]
}
`);
classDeclarationForOperation(generator, operations['HeroName']);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a class declaration for a query with fragment spreads`, function() {
const { operations } = this.compileFromSource(`
test(`should generate a class declaration for a query with fragment spreads`, function() {
const { operations } = compileFromSource(`
query Hero {

@@ -107,47 +89,8 @@ hero {

classDeclarationForOperation(this.generator, operations['Hero']);
expect(this.generator.output).to.equal(stripIndent`
public final class HeroQuery: GraphQLQuery {
public static let operationDefinition =
"query Hero {" +
" hero {" +
" __typename" +
" ...HeroDetails" +
" }" +
"}"
public static let queryDocument = operationDefinition.appending(HeroDetails.fragmentDefinition)
public init() {
}
public struct Data: GraphQLMappable {
public let hero: Hero?
public init(reader: GraphQLResultReader) throws {
hero = try reader.optionalValue(for: Field(responseName: "hero"))
}
public struct Hero: GraphQLMappable {
public let __typename: String
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
let heroDetails = try HeroDetails(reader: reader)
fragments = Fragments(heroDetails: heroDetails)
}
public struct Fragments {
public let heroDetails: HeroDetails
}
}
}
}
`);
classDeclarationForOperation(generator, operations['Hero']);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a class declaration for a query with conditional fragment spreads`, function() {
const { operations } = this.compileFromSource(`
test(`should generate a class declaration for a query with conditional fragment spreads`, function() {
const { operations } = compileFromSource(`
query Hero {

@@ -164,47 +107,8 @@ hero {

classDeclarationForOperation(this.generator, operations['Hero']);
expect(this.generator.output).to.equal(stripIndent`
public final class HeroQuery: GraphQLQuery {
public static let operationDefinition =
"query Hero {" +
" hero {" +
" __typename" +
" ...DroidDetails" +
" }" +
"}"
public static let queryDocument = operationDefinition.appending(DroidDetails.fragmentDefinition)
public init() {
}
public struct Data: GraphQLMappable {
public let hero: Hero?
public init(reader: GraphQLResultReader) throws {
hero = try reader.optionalValue(for: Field(responseName: "hero"))
}
public struct Hero: GraphQLMappable {
public let __typename: String
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
let droidDetails = try DroidDetails(reader: reader, ifTypeMatches: __typename)
fragments = Fragments(droidDetails: droidDetails)
}
public struct Fragments {
public let droidDetails: DroidDetails?
}
}
}
}
`);
classDeclarationForOperation(generator, operations['Hero']);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a class declaration for a query with a fragment spread nested in an inline fragment`, function() {
const { operations } = this.compileFromSource(`
test(`should generate a class declaration for a query with a fragment spread nested in an inline fragment`, function() {
const { operations } = compileFromSource(`
query Hero {

@@ -223,64 +127,9 @@ hero {

classDeclarationForOperation(this.generator, operations['Hero']);
classDeclarationForOperation(generator, operations['Hero']);
expect(this.generator.output).to.equal(stripIndent`
public final class HeroQuery: GraphQLQuery {
public static let operationDefinition =
"query Hero {" +
" hero {" +
" __typename" +
" ... on Droid {" +
" __typename" +
" ...HeroDetails" +
" }" +
" }" +
"}"
public static let queryDocument = operationDefinition.appending(HeroDetails.fragmentDefinition)
public init() {
}
public struct Data: GraphQLMappable {
public let hero: Hero?
public init(reader: GraphQLResultReader) throws {
hero = try reader.optionalValue(for: Field(responseName: "hero"))
}
public struct Hero: GraphQLMappable {
public let __typename: String
public let asDroid: AsDroid?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
asDroid = try AsDroid(reader: reader, ifTypeMatches: __typename)
}
public struct AsDroid: GraphQLConditionalFragment {
public static let possibleTypes = ["Droid"]
public let __typename: String
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
let heroDetails = try HeroDetails(reader: reader)
fragments = Fragments(heroDetails: heroDetails)
}
public struct Fragments {
public let heroDetails: HeroDetails
}
}
}
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a class declaration for a mutation with variables`, function() {
const { operations } = this.compileFromSource(`
test(`should generate a class declaration for a mutation with variables`, function() {
const { operations } = compileFromSource(`
mutation CreateReview($episode: Episode) {

@@ -294,25 +143,5 @@ createReview(episode: $episode, review: { stars: 5, commentary: "Wow!" }) {

classDeclarationForOperation(this.generator, operations['CreateReview']);
classDeclarationForOperation(generator, operations['CreateReview']);
expect(this.generator.output).to.include(stripIndent`
public final class CreateReviewMutation: GraphQLMutation {
public static let operationDefinition =
"mutation CreateReview($episode: Episode) {" +
" createReview(episode: $episode, review: {stars: 5, commentary: \\"Wow!\\"}) {" +
" __typename" +
" stars" +
" commentary" +
" }" +
"}"
public let episode: Episode?
public init(episode: Episode? = nil) {
self.episode = episode
}
public var variables: GraphQLMap? {
return ["episode": episode]
}
`);
expect(generator.output).toMatchSnapshot();
});

@@ -322,28 +151,20 @@ });

describe('#initializerDeclarationForProperties()', function() {
it(`should generate initializer for a property`, function() {
initializerDeclarationForProperties(this.generator, [
test(`should generate initializer for a property`, function() {
initializerDeclarationForProperties(generator, [
{ propertyName: 'episode', type: new GraphQLNonNull(schema.getType('Episode')), typeName: 'Episode' }
]);
expect(this.generator.output).to.equal(stripIndent`
public init(episode: Episode) {
self.episode = episode
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate initializer for an optional property`, function() {
initializerDeclarationForProperties(this.generator, [
test(`should generate initializer for an optional property`, function() {
initializerDeclarationForProperties(generator, [
{ propertyName: 'episode', type: schema.getType('Episode'), typeName: 'Episode?', isOptional: true }
]);
expect(this.generator.output).to.equal(stripIndent`
public init(episode: Episode? = nil) {
self.episode = episode
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate initializer for multiple properties`, function() {
initializerDeclarationForProperties(this.generator, [
test(`should generate initializer for multiple properties`, function() {
initializerDeclarationForProperties(generator, [
{ propertyName: 'episode', type: schema.getType('Episode'), typeName: 'Episode?', isOptional: true },

@@ -353,8 +174,3 @@ { propertyName: 'scene', type: GraphQLString, typeName: 'String?', isOptional: true }

expect(this.generator.output).to.equal(stripIndent`
public init(episode: Episode? = nil, scene: String? = nil) {
self.episode = episode
self.scene = scene
}
`);
expect(generator.output).toMatchSnapshot();
});

@@ -364,4 +180,4 @@ });

describe('#structDeclarationForFragment()', function() {
it(`should generate a struct declaration for a fragment with an abstract type condition`, function() {
const { fragments } = this.compileFromSource(`
test(`should generate a struct declaration for a fragment with an abstract type condition`, function() {
const { fragments } = compileFromSource(`
fragment HeroDetails on Character {

@@ -373,30 +189,9 @@ name

structDeclarationForFragment(this.generator, fragments['HeroDetails']);
structDeclarationForFragment(generator, fragments['HeroDetails']);
expect(this.generator.output).to.equal(stripIndent`
public struct HeroDetails: GraphQLNamedFragment {
public static let fragmentDefinition =
"fragment HeroDetails on Character {" +
" __typename" +
" name" +
" appearsIn" +
"}"
public static let possibleTypes = ["Human", "Droid"]
public let __typename: String
public let name: String
public let appearsIn: [Episode?]
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
appearsIn = try reader.list(for: Field(responseName: "appearsIn"))
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a fragment with a concrete type condition`, function() {
const { fragments } = this.compileFromSource(`
test(`should generate a struct declaration for a fragment with a concrete type condition`, function() {
const { fragments } = compileFromSource(`
fragment DroidDetails on Droid {

@@ -408,30 +203,9 @@ name

structDeclarationForFragment(this.generator, fragments['DroidDetails']);
structDeclarationForFragment(generator, fragments['DroidDetails']);
expect(this.generator.output).to.equal(stripIndent`
public struct DroidDetails: GraphQLNamedFragment {
public static let fragmentDefinition =
"fragment DroidDetails on Droid {" +
" __typename" +
" name" +
" primaryFunction" +
"}"
public static let possibleTypes = ["Droid"]
public let __typename: String
public let name: String
public let primaryFunction: String?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
primaryFunction = try reader.optionalValue(for: Field(responseName: "primaryFunction"))
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a fragment with a subselection`, function() {
const { fragments } = this.compileFromSource(`
test(`should generate a struct declaration for a fragment with a subselection`, function() {
const { fragments } = compileFromSource(`
fragment HeroDetails on Character {

@@ -445,43 +219,9 @@ name

structDeclarationForFragment(this.generator, fragments['HeroDetails']);
structDeclarationForFragment(generator, fragments['HeroDetails']);
expect(this.generator.output).to.equal(stripIndent`
public struct HeroDetails: GraphQLNamedFragment {
public static let fragmentDefinition =
"fragment HeroDetails on Character {" +
" __typename" +
" name" +
" friends {" +
" __typename" +
" name" +
" }" +
"}"
public static let possibleTypes = ["Human", "Droid"]
public let __typename: String
public let name: String
public let friends: [Friend?]?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
friends = try reader.optionalList(for: Field(responseName: "friends"))
}
public struct Friend: GraphQLMappable {
public let __typename: String
public let name: String
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
}
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a fragment that includes a fragment spread`, function() {
const { fragments } = this.compileFromSource(`
test(`should generate a struct declaration for a fragment that includes a fragment spread`, function() {
const { fragments } = compileFromSource(`
fragment HeroDetails on Character {

@@ -497,33 +237,5 @@ name

structDeclarationForFragment(this.generator, fragments['HeroDetails']);
structDeclarationForFragment(generator, fragments['HeroDetails']);
expect(this.generator.output).to.equal(stripIndent`
public struct HeroDetails: GraphQLNamedFragment {
public static let fragmentDefinition =
"fragment HeroDetails on Character {" +
" __typename" +
" name" +
" ...MoreHeroDetails" +
"}"
public static let possibleTypes = ["Human", "Droid"]
public let __typename: String
public let name: String
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
let moreHeroDetails = try MoreHeroDetails(reader: reader)
fragments = Fragments(moreHeroDetails: moreHeroDetails)
}
public struct Fragments {
public let moreHeroDetails: MoreHeroDetails
}
}
`);
expect(generator.output).toMatchSnapshot();
});

@@ -533,4 +245,4 @@ });

describe('#structDeclarationForSelectionSet()', function() {
it(`should generate a struct declaration for a selection set`, function() {
structDeclarationForSelectionSet(this.generator, {
test(`should generate a struct declaration for a selection set`, function() {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -547,17 +259,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let name: String?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.optionalValue(for: Field(responseName: "name"))
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should escape reserved keywords in a struct declaration for a selection set`, function() {
structDeclarationForSelectionSet(this.generator, {
test(`should escape reserved keywords in a struct declaration for a selection set`, function() {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -574,17 +276,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let \`private\`: String?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
\`private\` = try reader.optionalValue(for: Field(responseName: "private", fieldName: "name"))
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a nested struct declaration for a selection set with subselections`, function() {
structDeclarationForSelectionSet(this.generator, {
test(`should generate a nested struct declaration for a selection set with subselections`, function() {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -608,27 +300,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let friends: [Friend?]?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
friends = try reader.optionalList(for: Field(responseName: "friends"))
}
public struct Friend: GraphQLMappable {
public let __typename: String
public let name: String?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.optionalValue(for: Field(responseName: "name"))
}
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a selection set with a fragment spread that matches the parent type`, function() {
this.addFragment({
test(`should generate a struct declaration for a selection set with a fragment spread that matches the parent type`, function() {
addFragment({
fragmentName: 'HeroDetails',

@@ -638,3 +310,3 @@ typeCondition: schema.getType('Character')

structDeclarationForSelectionSet(this.generator, {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -652,26 +324,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let name: String?
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.optionalValue(for: Field(responseName: "name"))
let heroDetails = try HeroDetails(reader: reader)
fragments = Fragments(heroDetails: heroDetails)
}
public struct Fragments {
public let heroDetails: HeroDetails
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a selection set with a fragment spread with a more specific type condition`, function() {
this.addFragment({
test(`should generate a struct declaration for a selection set with a fragment spread with a more specific type condition`, function() {
addFragment({
fragmentName: 'DroidDetails',

@@ -681,3 +334,3 @@ typeCondition: schema.getType('Droid')

structDeclarationForSelectionSet(this.generator, {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -695,26 +348,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let name: String?
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.optionalValue(for: Field(responseName: "name"))
let droidDetails = try DroidDetails(reader: reader, ifTypeMatches: __typename)
fragments = Fragments(droidDetails: droidDetails)
}
public struct Fragments {
public let droidDetails: DroidDetails?
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a selection set with an inline fragment`, function() {
structDeclarationForSelectionSet(this.generator, {
test(`should generate a struct declaration for a selection set with an inline fragment`, function() {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -749,35 +383,7 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let name: String
public let asDroid: AsDroid?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
asDroid = try AsDroid(reader: reader, ifTypeMatches: __typename)
}
public struct AsDroid: GraphQLConditionalFragment {
public static let possibleTypes = ["Droid"]
public let __typename: String
public let name: String
public let primaryFunction: String?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
name = try reader.value(for: Field(responseName: "name"))
primaryFunction = try reader.optionalValue(for: Field(responseName: "primaryFunction"))
}
}
}
`);
expect(generator.output).toMatchSnapshot();
});
it(`should generate a struct declaration for a fragment spread nested in an inline fragment`, function() {
this.addFragment({
test(`should generate a struct declaration for a fragment spread nested in an inline fragment`, function() {
addFragment({
fragmentName: 'HeroDetails',

@@ -787,3 +393,3 @@ typeCondition: schema.getType('Character')

structDeclarationForSelectionSet(this.generator, {
structDeclarationForSelectionSet(generator, {
structName: 'Hero',

@@ -802,34 +408,3 @@ parentType: schema.getType('Character'),

expect(this.generator.output).to.equal(stripIndent`
public struct Hero: GraphQLMappable {
public let __typename: String
public let asDroid: AsDroid?
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
asDroid = try AsDroid(reader: reader, ifTypeMatches: __typename)
}
public struct AsDroid: GraphQLConditionalFragment {
public static let possibleTypes = ["Droid"]
public let __typename: String
public let fragments: Fragments
public init(reader: GraphQLResultReader) throws {
__typename = try reader.value(for: Field(responseName: "__typename"))
let heroDetails = try HeroDetails(reader: reader)
fragments = Fragments(heroDetails: heroDetails)
}
public struct Fragments {
public let heroDetails: HeroDetails
}
}
}
`);
expect(generator.output).toMatchSnapshot();
});

@@ -839,4 +414,4 @@ });

describe('#dictionaryLiteralForFieldArguments()', function() {
it('should include expressions for input objects with variables', function() {
const { operations } = this.compileFromSource(`
test('should include expressions for input objects with variables', function() {
const { operations } = compileFromSource(`
mutation FieldArgumentsWithInputObjects($commentary: String!, $red: Int!) {

@@ -852,3 +427,3 @@ createReview(episode: JEDI, review: { stars: 2, commentary: $commentary, favorite_color: { red: $red, blue: 100, green: 50 } }) {

expect(dictionaryLiteral).to.equal('["episode": "JEDI", "review": ["stars": 2, "commentary": reader.variables["commentary"], "favorite_color": ["red": reader.variables["red"], "blue": 100, "green": 50]]]');
expect(dictionaryLiteral).toBe('["episode": "JEDI", "review": ["stars": 2, "commentary": reader.variables["commentary"], "favorite_color": ["red": reader.variables["red"], "blue": 100, "green": 50]]]');
});

@@ -858,3 +433,3 @@ });

describe('#typeDeclarationForGraphQLType()', function() {
it('should generate an enum declaration for a GraphQLEnumType', function() {
test('should generate an enum declaration for a GraphQLEnumType', function() {
const generator = new CodeGenerator();

@@ -864,15 +439,6 @@

expect(generator.output).to.equal(stripIndent`
/// The episodes in the Star Wars trilogy
public enum Episode: String {
case newhope = "NEWHOPE" /// Star Wars Episode IV: A New Hope, released in 1977.
case empire = "EMPIRE" /// Star Wars Episode V: The Empire Strikes Back, released in 1980.
case jedi = "JEDI" /// Star Wars Episode VI: Return of the Jedi, released in 1983.
}
extension Episode: JSONDecodable, JSONEncodable {}
`);
expect(generator.output).toMatchSnapshot();
});
it('should escape identifiers in cases of enum declaration for a GraphQLEnumType', function() {
test('should escape identifiers in cases of enum declaration for a GraphQLEnumType', function() {
const generator = new CodeGenerator();

@@ -887,13 +453,6 @@

expect(generator.output).to.equal(stripIndent`
public enum AlbumPrivacies: String {
case \`public\` = "PUBLIC"
case \`private\` = "PRIVATE"
}
extension AlbumPrivacies: JSONDecodable, JSONEncodable {}
`);
expect(generator.output).toMatchSnapshot();
});
it('should generate a struct declaration for a GraphQLInputObjectType', function() {
test('should generate a struct declaration for a GraphQLInputObjectType', function() {
const generator = new CodeGenerator();

@@ -903,14 +462,5 @@

expect(generator.output).to.equal(stripIndent`
/// The input object sent when someone is creating a new review
public struct ReviewInput: GraphQLMapConvertible {
public var graphQLMap: GraphQLMap
public init(stars: Int, commentary: String? = nil, favoriteColor: ColorInput? = nil) {
graphQLMap = ["stars": stars, "commentary": commentary, "favorite_color": favoriteColor]
}
}
`);
expect(generator.output).toMatchSnapshot();
});
});
});

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

import { expect } from 'chai';
import { stripIndent } from 'common-tags';

@@ -16,13 +14,15 @@

describe('Swift code generation: Basic language constructs', function() {
let generator;
beforeEach(function() {
this.generator = new CodeGenerator();
generator = new CodeGenerator();
});
it(`should generate a class declaration`, function() {
classDeclaration(this.generator, { className: 'Hero', modifiers: ['public', 'final'] }, () => {
propertyDeclaration(this.generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(this.generator, { propertyName: 'age', typeName: 'Int' });
test(`should generate a class declaration`, function() {
classDeclaration(generator, { className: 'Hero', modifiers: ['public', 'final'] }, () => {
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(generator, { propertyName: 'age', typeName: 'Int' });
});
expect(this.generator.output).to.equal(stripIndent`
expect(generator.output).toBe(stripIndent`
public final class Hero {

@@ -35,9 +35,9 @@ public let name: String

it(`should generate a struct declaration`, function() {
structDeclaration(this.generator, { structName: 'Hero' }, () => {
propertyDeclaration(this.generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(this.generator, { propertyName: 'age', typeName: 'Int' });
test(`should generate a struct declaration`, function() {
structDeclaration(generator, { structName: 'Hero' }, () => {
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(generator, { propertyName: 'age', typeName: 'Int' });
});
expect(this.generator.output).to.equal(stripIndent`
expect(generator.output).toBe(stripIndent`
public struct Hero {

@@ -50,13 +50,13 @@ public let name: String

it(`should generate nested struct declarations`, function() {
structDeclaration(this.generator, { structName: 'Hero' }, () => {
propertyDeclaration(this.generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(this.generator, { propertyName: 'friends', typeName: '[Friend]' });
test(`should generate nested struct declarations`, function() {
structDeclaration(generator, { structName: 'Hero' }, () => {
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String' });
propertyDeclaration(generator, { propertyName: 'friends', typeName: '[Friend]' });
structDeclaration(this.generator, { structName: 'Friend' }, () => {
propertyDeclaration(this.generator, { propertyName: 'name', typeName: 'String' });
structDeclaration(generator, { structName: 'Friend' }, () => {
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String' });
});
});
expect(this.generator.output).to.equal(stripIndent`
expect(generator.output).toBe(stripIndent`
public struct Hero {

@@ -73,9 +73,9 @@ public let name: String

it(`should generate a protocol declaration`, function() {
protocolDeclaration(this.generator, { protocolName: 'HeroDetails', adoptedProtocols: ['HasName'] }, () => {
protocolPropertyDeclaration(this.generator, { propertyName: 'name', typeName: 'String' });
protocolPropertyDeclaration(this.generator, { propertyName: 'age', typeName: 'Int' });
test(`should generate a protocol declaration`, function() {
protocolDeclaration(generator, { protocolName: 'HeroDetails', adoptedProtocols: ['HasName'] }, () => {
protocolPropertyDeclaration(generator, { propertyName: 'name', typeName: 'String' });
protocolPropertyDeclaration(generator, { propertyName: 'age', typeName: 'Int' });
});
expect(this.generator.output).to.equal(stripIndent`
expect(generator.output).toBe(stripIndent`
public protocol HeroDetails: HasName {

@@ -87,2 +87,11 @@ var name: String { get }

});
test(`should handle multi-line descriptions`, () => {
structDeclaration(generator, { structName: 'Hero', description: 'A hero' }, () => {
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String', description: `A multiline comment /n on the hero's name.` });
propertyDeclaration(generator, { propertyName: 'age', typeName: 'String', description: `A multiline comment /n on the hero's age.` });
});
expect(generator.output).toMatchSnapshot();
});
});

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

import { expect } from 'chai';
import { stripIndent } from 'common-tags'

@@ -25,62 +23,62 @@

describe('#typeNameFromGraphQLType()', function() {
it('should return String? for GraphQLString', function() {
expect(typeNameFromGraphQLType({}, GraphQLString)).to.equal('String?');
test('should return String? for GraphQLString', function() {
expect(typeNameFromGraphQLType({}, GraphQLString)).toBe('String?');
});
it('should return String for GraphQLNonNull(GraphQLString)', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(GraphQLString))).to.equal('String');
test('should return String for GraphQLNonNull(GraphQLString)', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(GraphQLString))).toBe('String');
});
it('should return [String?]? for GraphQLList(GraphQLString)', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(GraphQLString))).to.equal('[String?]?');
test('should return [String?]? for GraphQLList(GraphQLString)', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(GraphQLString))).toBe('[String?]?');
});
it('should return [String?] for GraphQLNonNull(GraphQLList(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(new GraphQLList(GraphQLString)))).to.equal('[String?]');
test('should return [String?] for GraphQLNonNull(GraphQLList(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(new GraphQLList(GraphQLString)))).toBe('[String?]');
});
it('should return [String]? for GraphQLList(GraphQLNonNull(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLNonNull(GraphQLString)))).to.equal('[String]?');
test('should return [String]? for GraphQLList(GraphQLNonNull(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLNonNull(GraphQLString)))).toBe('[String]?');
});
it('should return [String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))))).to.equal('[String]');
test('should return [String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))))).toBe('[String]');
});
it('should return [[String?]?]? for GraphQLList(GraphQLList(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLList(GraphQLString)))).to.equal('[[String?]?]?');
test('should return [[String?]?]? for GraphQLList(GraphQLList(GraphQLString))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLList(GraphQLString)))).toBe('[[String?]?]?');
});
it('should return [[String?]]? for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))))).to.equal('[[String?]]?');
test('should return [[String?]]? for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))', function() {
expect(typeNameFromGraphQLType({}, new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))))).toBe('[[String?]]?');
});
it('should return Int? for GraphQLInt', function() {
expect(typeNameFromGraphQLType({}, GraphQLInt)).to.equal('Int?');
test('should return Int? for GraphQLInt', function() {
expect(typeNameFromGraphQLType({}, GraphQLInt)).toBe('Int?');
});
it('should return Double? for GraphQLFloat', function() {
expect(typeNameFromGraphQLType({}, GraphQLFloat)).to.equal('Double?');
test('should return Double? for GraphQLFloat', function() {
expect(typeNameFromGraphQLType({}, GraphQLFloat)).toBe('Double?');
});
it('should return Bool? for GraphQLBoolean', function() {
expect(typeNameFromGraphQLType({}, GraphQLBoolean)).to.equal('Bool?');
test('should return Bool? for GraphQLBoolean', function() {
expect(typeNameFromGraphQLType({}, GraphQLBoolean)).toBe('Bool?');
});
it('should return GraphQLID? for GraphQLID', function() {
expect(typeNameFromGraphQLType({}, GraphQLID)).to.equal('GraphQLID?');
test('should return GraphQLID? for GraphQLID', function() {
expect(typeNameFromGraphQLType({}, GraphQLID)).toBe('GraphQLID?');
});
it('should return String? for a custom scalar type', function() {
expect(typeNameFromGraphQLType({}, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).to.equal('String?');
test('should return String? for a custom scalar type', function() {
expect(typeNameFromGraphQLType({}, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('String?');
});
it('should return a passed through custom scalar type with the passthroughCustomScalars option', function() {
expect(typeNameFromGraphQLType({ passthroughCustomScalars: true, customScalarsPrefix: '' }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).to.equal('CustomScalarType?');
test('should return a passed through custom scalar type with the passthroughCustomScalars option', function() {
expect(typeNameFromGraphQLType({ passthroughCustomScalars: true, customScalarsPrefix: '' }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('CustomScalarType?');
});
it('should return a passed through custom scalar type with a prefix with the customScalarsPrefix option', function() {
expect(typeNameFromGraphQLType({ passthroughCustomScalars: true, customScalarsPrefix: 'My' }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).to.equal('MyCustomScalarType?');
test('should return a passed through custom scalar type with a prefix with the customScalarsPrefix option', function() {
expect(typeNameFromGraphQLType({ passthroughCustomScalars: true, customScalarsPrefix: 'My' }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('MyCustomScalarType?');
});
});
});

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

import { expect } from 'chai';
import { stripIndent } from 'common-tags';

@@ -27,2 +25,6 @@

describe('TypeScript code generation', function() {
let generator;
let compileFromSource;
let addFragment;
beforeEach(function() {

@@ -36,13 +38,13 @@ const context = {

this.generator = new CodeGenerator(context);
generator = new CodeGenerator(context);
this.compileFromSource = (source) => {
compileFromSource = (source) => {
const document = parse(source);
const context = compileToIR(schema, document);
this.generator.context = context;
generator.context = context;
return context;
};
this.addFragment = (fragment) => {
this.generator.context.fragments[fragment.fragmentName] = fragment;
addFragment = (fragment) => {
generator.context.fragments[fragment.fragmentName] = fragment;
};

@@ -52,4 +54,4 @@ });

describe('#generateSource()', function() {
it(`should generate simple query operations`, function() {
const context = this.compileFromSource(`
test(`should generate simple query operations`, function() {
const context = compileFromSource(`
query HeroName {

@@ -63,18 +65,7 @@ hero {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
export interface HeroNameQuery {
hero: {
name: string,
} | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate simple query operations including input variables`, function() {
const context = this.compileFromSource(`
test(`should generate simple query operations including input variables`, function() {
const context = compileFromSource(`
query HeroName($episode: Episode) {

@@ -88,29 +79,7 @@ hero(episode: $episode) {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export interface HeroNameQueryVariables {
episode: Episode | null;
}
export interface HeroNameQuery {
hero: {
name: string,
} | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate simple nested query operations including input variables`, function() {
const context = this.compileFromSource(`
test(`should generate simple nested query operations including input variables`, function() {
const context = compileFromSource(`
query HeroAndFriendsNames($episode: Episode) {

@@ -127,32 +96,7 @@ hero(episode: $episode) {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export interface HeroAndFriendsNamesQueryVariables {
episode: Episode | null;
}
export interface HeroAndFriendsNamesQuery {
hero: {
name: string,
friends: Array< {
name: string,
} > | null,
} | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate fragmented query operations`, function() {
const context = this.compileFromSource(`
test(`should generate fragmented query operations`, function() {
const context = compileFromSource(`
query HeroAndFriendsNames {

@@ -173,24 +117,7 @@ hero {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
export interface HeroAndFriendsNamesQuery {
hero: HeroFriendsFragment & {
name: string,
} | null;
}
export interface HeroFriendsFragment {
friends: Array< {
name: string,
} > | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate query operations with inline fragments`, function() {
const context = this.compileFromSource(`
test(`should generate query operations with inline fragments`, function() {
const context = compileFromSource(`
query HeroAndDetails {

@@ -214,23 +141,7 @@ hero {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
export interface HeroAndDetailsQuery {
hero: HeroDetailsFragment & {
name: string,
} | null;
}
export interface HeroDetailsFragment {
primaryFunction: string | null;
height: number | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate mutation operations with complex input types`, function() {
const context = this.compileFromSource(`
test(`should generate mutation operations with complex input types`, function() {
const context = compileFromSource(`
mutation ReviewMovie($episode: Episode, $review: ReviewInput) {

@@ -245,46 +156,7 @@ createReview(episode: $episode, review: $review) {

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export interface ReviewInput {
// 0-5 stars
stars: number;
// Comment about the movie, optional
commentary: string | null;
// Favorite color, optional
favorite_color: ColorInput | null;
}
export interface ColorInput {
red: number;
green: number;
blue: number;
}
export interface ReviewMovieMutationVariables {
episode: Episode | null;
review: ReviewInput | null;
}
export interface ReviewMovieMutation {
createReview: {
stars: number,
commentary: string | null,
} | null;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
it(`should generate correct list with custom fragment`, function() {
const context = this.compileFromSource(`
test(`should generate correct list with custom fragment`, function() {
const context = compileFromSource(`
fragment Friend on Character {

@@ -305,32 +177,5 @@ name

const source = generateSource(context);
expect(source).to.include(stripIndent`
// This file was automatically generated and should not be edited.
/* tslint:disable */
// The episodes in the Star Wars trilogy
export type Episode =
"NEWHOPE" | // Star Wars Episode IV: A New Hope, released in 1977.
"EMPIRE" | // Star Wars Episode V: The Empire Strikes Back, released in 1980.
"JEDI"; // Star Wars Episode VI: Return of the Jedi, released in 1983.
export interface HeroAndFriendsNamesQueryVariables {
episode: Episode | null;
}
export interface HeroAndFriendsNamesQuery {
hero: {
name: string,
friends: Array<FriendFragment>,
} | null;
}
export interface FriendFragment {
name: string;
}
/* tslint:enable */
` + `\n`);
expect(source).toMatchSnapshot();
});
});
});

@@ -1,22 +0,20 @@

import { assert } from 'chai'
import {readFileSync} from 'fs';
import path from 'path';
import { readFileSync } from 'fs'
import path from 'path'
import {loadSchema, loadAndMergeQueryDocuments} from '../src/loading';
import {
loadSchema,
loadAndMergeQueryDocuments,
} from '../src/loading'
import {validateQueryDocument} from '../src/validation';
import { validateQueryDocument } from '../src/validation'
const schema = loadSchema(require.resolve('./starwars/schema.json'));
describe('Validation', () => {
it(`should throw an error for AnonymousQuery.graphql`, () => {
const inputPaths = [path.join(__dirname, './starwars/AnonymousQuery.graphql')];
test(`should throw an error for AnonymousQuery.graphql`, () => {
const inputPaths = [
path.join(__dirname, './starwars/AnonymousQuery.graphql'),
];
const document = loadAndMergeQueryDocuments(inputPaths);
assert.throws(
() => validateQueryDocument(schema, document),
expect(
() => validateQueryDocument(schema, document)
).toThrow(
'Validation of GraphQL query document failed'

@@ -26,8 +24,11 @@ );

it(`should throw an error for ExplicitTypename.graphql`, () => {
const inputPaths = [path.join(__dirname, './starwars/ExplicitTypename.graphql')];
test(`should throw an error for ExplicitTypename.graphql`, () => {
const inputPaths = [
path.join(__dirname, './starwars/ExplicitTypename.graphql'),
];
const document = loadAndMergeQueryDocuments(inputPaths);
assert.throws(
() => validateQueryDocument(schema, document),
expect(
() => validateQueryDocument(schema, document)
).toThrow(
'Validation of GraphQL query document failed'

@@ -37,8 +38,11 @@ );

it(`should throw an error for TypenameAlias.graphql`, () => {
const inputPaths = [path.join(__dirname, './starwars/TypenameAlias.graphql')];
test(`should throw an error for TypenameAlias.graphql`, () => {
const inputPaths = [
path.join(__dirname, './starwars/TypenameAlias.graphql'),
];
const document = loadAndMergeQueryDocuments(inputPaths);
assert.throws(
() => validateQueryDocument(schema, document),
expect(
() => validateQueryDocument(schema, document)
).toThrow(
'Validation of GraphQL query document failed'

@@ -45,0 +49,0 @@ );

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

import { expect } from 'chai'
import {

@@ -10,64 +8,64 @@ parseValue,

describe('#valueFromValueNode', () => {
it(`should return a number for an IntValue`, () => {
test(`should return a number for an IntValue`, () => {
const valueNode = parseValue("1");
const value = valueFromValueNode(valueNode);
expect(value).to.equal(1);
expect(value).toBe(1);
});
it(`should return a number for a FloatValue`, () => {
test(`should return a number for a FloatValue`, () => {
const valueNode = parseValue("1.0");
const value = valueFromValueNode(valueNode);
expect(value).to.equal(1.0);
expect(value).toBe(1.0);
});
it(`should return a boolean for a BooleanValue`, () => {
test(`should return a boolean for a BooleanValue`, () => {
const valueNode = parseValue("true");
const value = valueFromValueNode(valueNode);
expect(value).to.equal(true);
expect(value).toBe(true);
});
it(`should return null for a NullValue`, () => {
test(`should return null for a NullValue`, () => {
const valueNode = parseValue("null");
const value = valueFromValueNode(valueNode);
expect(value).to.equal(null);
expect(value).toBe(null);
});
it(`should return a string for a StringValue`, () => {
test(`should return a string for a StringValue`, () => {
const valueNode = parseValue("\"foo\"");
const value = valueFromValueNode(valueNode);
expect(value).to.equal("foo");
expect(value).toBe("foo");
});
it(`should return a string for an EnumValue`, () => {
test(`should return a string for an EnumValue`, () => {
const valueNode = parseValue("JEDI");
const value = valueFromValueNode(valueNode);
expect(value).to.equal("JEDI");
expect(value).toBe("JEDI");
});
it(`should return an object for a Variable`, () => {
test(`should return an object for a Variable`, () => {
const valueNode = parseValue("$something");
const value = valueFromValueNode(valueNode);
expect(value).to.deep.equal({ kind: 'Variable', variableName: 'something' });
expect(value).toEqual({ kind: 'Variable', variableName: 'something' });
});
it(`should return an array for a ListValue`, () => {
test(`should return an array for a ListValue`, () => {
const valueNode = parseValue("[ \"foo\", 1, JEDI, $something ]");
const value = valueFromValueNode(valueNode);
expect(value).to.deep.equal([ "foo", 1, "JEDI", { kind: 'Variable', variableName: 'something' } ]);
expect(value).toEqual([ "foo", 1, "JEDI", { kind: 'Variable', variableName: 'something' } ]);
});
it(`should return an object for an ObjectValue`, () => {
test(`should return an object for an ObjectValue`, () => {
const valueNode = parseValue("{ foo: \"foo\", bar: 1, bla: JEDI, baz: $something }");
const value = valueFromValueNode(valueNode);
expect(value).to.deep.equal({ foo: "foo", bar: 1, bla: "JEDI", baz: { kind: 'Variable', variableName: 'something' } });
expect(value).toEqual({ foo: "foo", bar: 1, bla: "JEDI", baz: { kind: 'Variable', variableName: 'something' } });
});
});

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

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

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