graphql-genie
Version:
1,594 lines (1,431 loc) • 237 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var graphql = require('graphql');
var graphql__default = _interopDefault(graphql);
var graphqlTools = require('graphql-tools');
var language = _interopDefault(require('graphql/language'));
var lodash = require('lodash');
var fortune = _interopDefault(require('fortune'));
var fortuneCommon = require('fortune/lib/adapter/adapters/common');
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var formatter = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// Parses an RFC 3339 compliant time-string into a Date.
// It does this by combining the current date with the time-string
// to create a new Date instance.
//
// Example:
// Suppose the current date is 2016-01-01, then
// parseTime('11:00:12Z') parses to a Date corresponding to
// 2016-01-01T11:00:12Z.
var parseTime = exports.parseTime = function parseTime(time) {
var currentDateString = new Date().toISOString();
return new Date(currentDateString.substr(0, currentDateString.indexOf('T') + 1) + time);
};
// Serializes a Date into an RFC 3339 compliant time-string in the
// format hh:mm:ss.sssZ.
var serializeTime = exports.serializeTime = function serializeTime(date) {
var dateTimeString = date.toISOString();
return dateTimeString.substr(dateTimeString.indexOf('T') + 1);
};
// Serializes an RFC 3339 compliant time-string by shifting
// it to UTC.
var serializeTimeString = exports.serializeTimeString = function serializeTimeString(time) {
// If already formatted to UTC then return the time string
if (time.indexOf('Z') !== -1) {
return time;
} else {
// These are time-strings with timezone information,
// these need to be shifted to UTC.
// Convert to UTC time string in
// format hh:mm:ss.sssZ.
var date = parseTime(time);
var timeUTC = serializeTime(date);
// Regex to look for fractional second part in time string
// such as 00:00:00.345+01:00
var regexFracSec = /\.\d{1,}/;
// Retrieve the fractional second part of the time
// string if it exists.
var fractionalPart = time.match(regexFracSec);
if (fractionalPart == null) {
// These are time-strings without the fractional
// seconds. So we remove them from the UTC time-string.
timeUTC = timeUTC.replace(regexFracSec, '');
return timeUTC;
} else {
// These are time-string with fractional seconds.
// Make sure that we inject the fractional
// second part back in. The `timeUTC` variable
// has millisecond precision, we may want more or less
// depending on the string that was passed.
timeUTC = timeUTC.replace(regexFracSec, fractionalPart[0]);
return timeUTC;
}
}
};
// Parses an RFC 3339 compliant date-string into a Date.
//
// Example:
// parseDate('2016-01-01') parses to a Date corresponding to
// 2016-01-01T00:00:00.000Z.
var parseDate = exports.parseDate = function parseDate(date) {
return new Date(date);
};
// Serializes a Date into a RFC 3339 compliant date-string
// in the format YYYY-MM-DD.
var serializeDate = exports.serializeDate = function serializeDate(date) {
return date.toISOString().split('T')[0];
};
// Parses an RFC 3339 compliant date-time-string into a Date.
var parseDateTime = exports.parseDateTime = function parseDateTime(dateTime) {
return new Date(dateTime);
};
// Serializes a Date into an RFC 3339 compliant date-time-string
// in the format YYYY-MM-DDThh:mm:ss.sssZ.
var serializeDateTime = exports.serializeDateTime = function serializeDateTime(dateTime) {
return dateTime.toISOString();
};
// Serializes an RFC 3339 compliant date-time-string by shifting
// it to UTC.
var serializeDateTimeString = exports.serializeDateTimeString = function serializeDateTimeString(dateTime) {
// If already formatted to UTC then return the time string
if (dateTime.indexOf('Z') !== -1) {
return dateTime;
} else {
// These are time-strings with timezone information,
// these need to be shifted to UTC.
// Convert to UTC time string in
// format YYYY-MM-DDThh:mm:ss.sssZ.
var dateTimeUTC = new Date(dateTime).toISOString();
// Regex to look for fractional second part in date-time string
var regexFracSec = /\.\d{1,}/;
// Retrieve the fractional second part of the time
// string if it exists.
var fractionalPart = dateTime.match(regexFracSec);
if (fractionalPart == null) {
// The date-time-string has no fractional part,
// so we remove it from the dateTimeUTC variable.
dateTimeUTC = dateTimeUTC.replace(regexFracSec, '');
return dateTimeUTC;
} else {
// These are datetime-string with fractional seconds.
// Make sure that we inject the fractional
// second part back in. The `dateTimeUTC` variable
// has millisecond precision, we may want more or less
// depending on the string that was passed.
dateTimeUTC = dateTimeUTC.replace(regexFracSec, fractionalPart[0]);
return dateTimeUTC;
}
}
};
// Serializes a Unix timestamp to an RFC 3339 compliant date-time-string
// in the format YYYY-MM-DDThh:mm:ss.sssZ
var serializeUnixTimestamp = exports.serializeUnixTimestamp = function serializeUnixTimestamp(timestamp) {
return new Date(timestamp * 1000).toISOString();
};
});
unwrapExports(formatter);
var formatter_1 = formatter.parseTime;
var formatter_2 = formatter.serializeTime;
var formatter_3 = formatter.serializeTimeString;
var formatter_4 = formatter.parseDate;
var formatter_5 = formatter.serializeDate;
var formatter_6 = formatter.parseDateTime;
var formatter_7 = formatter.serializeDateTime;
var formatter_8 = formatter.serializeDateTimeString;
var formatter_9 = formatter.serializeUnixTimestamp;
var validator = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// Check whether a certain year is a leap year.
//
// Every year that is exactly divisible by four
// is a leap year, except for years that are exactly
// divisible by 100, but these centurial years are
// leap years if they are exactly divisible by 400.
// For example, the years 1700, 1800, and 1900 are not leap years,
// but the years 1600 and 2000 are.
//
var leapYear = function leapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
};
// Function that checks whether a time-string is RFC 3339 compliant.
//
// It checks whether the time-string is structured in one of the
// following formats:
//
// - hh:mm:ssZ
// - hh:mm:ss±hh:mm
// - hh:mm:ss.*sZ
// - hh:mm:ss.*s±hh:mm
//
// Where *s is a fraction of seconds with at least 1 digit.
//
// Note, this validator assumes that all minutes have
// 59 seconds. This assumption does not follow RFC 3339
// which includes leap seconds (in which case it is possible that
// there are 60 seconds in a minute).
//
// Leap seconds are ignored because it adds complexity in
// the following areas:
// - The native Javascript Date ignores them; i.e. Date.parse('1972-12-31T23:59:60Z')
// equals NaN.
// - Leap seconds cannot be known in advance.
//
var validateTime = exports.validateTime = function validateTime(time) {
var TIME_REGEX = /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\.\d{1,})?(([Z])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/;
return TIME_REGEX.test(time);
};
// Function that checks whether a date-string is RFC 3339 compliant.
//
// It checks whether the date-string is a valid date in the YYYY-MM-DD.
//
// Note, the number of days in each date are determined according to the
// following lookup table:
//
// Month Number Month/Year Maximum value of date-mday
// ------------ ---------- --------------------------
// 01 January 31
// 02 February, normal 28
// 02 February, leap year 29
// 03 March 31
// 04 April 30
// 05 May 31
// 06 June 30
// 07 July 31
// 08 August 31
// 09 September 30
// 10 October 31
// 11 November 30
// 12 December 31
//
var validateDate = exports.validateDate = function validateDate(datestring) {
var RFC_3339_REGEX = /^(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))$/;
if (!RFC_3339_REGEX.test(datestring)) {
return false;
}
// Verify the correct number of days for
// the month contained in the date-string.
var year = Number(datestring.substr(0, 4));
var month = Number(datestring.substr(5, 2));
var day = Number(datestring.substr(8, 2));
switch (month) {
case 2:
// February
if (leapYear(year) && day > 29) {
return false;
} else if (!leapYear(year) && day > 28) {
return false;
}
return true;
case 4: // April
case 6: // June
case 9: // September
case 11:
// November
if (day > 30) {
return false;
}
break;
}
return true;
};
// Function that checks whether a date-time-string is RFC 3339 compliant.
//
// It checks whether the time-string is structured in one of the
//
// - YYYY-MM-DDThh:mm:ssZ
// - YYYY-MM-DDThh:mm:ss±hh:mm
// - YYYY-MM-DDThh:mm:ss.*sZ
// - YYYY-MM-DDThh:mm:ss.*s±hh:mm
//
// Where *s is a fraction of seconds with at least 1 digit.
//
var validateDateTime = exports.validateDateTime = function validateDateTime(dateTimeString) {
var RFC_3339_REGEX = /^(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60))(\.\d{1,})?(([Z])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/;
// Validate the structure of the date-string
if (!RFC_3339_REGEX.test(dateTimeString)) {
return false;
}
// Check if it is a correct date using the javascript Date parse() method.
var time = Date.parse(dateTimeString);
if (time !== time) {
// eslint-disable-line
return false;
}
// Split the date-time-string up into the string-date and time-string part.
// and check whether these parts are RFC 3339 compliant.
var index = dateTimeString.indexOf('T');
var dateString = dateTimeString.substr(0, index);
var timeString = dateTimeString.substr(index + 1);
return validateDate(dateString) && validateTime(timeString);
};
// Function that checks whether a given number is a valid
// Unix timestamp.
//
// Unix timestamps are signed 32-bit integers. They are interpreted
// as the number of seconds since 00:00:00 UTC on 1 January 1970.
//
var validateUnixTimestamp = exports.validateUnixTimestamp = function validateUnixTimestamp(timestamp) {
var MAX_INT = 2147483647;
var MIN_INT = -2147483648;
return timestamp === timestamp && timestamp <= MAX_INT && timestamp >= MIN_INT; // eslint-disable-line
};
// Function that checks whether a javascript Date instance
// is valid.
//
var validateJSDate = exports.validateJSDate = function validateJSDate(date) {
var time = date.getTime();
return time === time; // eslint-disable-line
};
});
unwrapExports(validator);
var validator_1 = validator.validateTime;
var validator_2 = validator.validateDate;
var validator_3 = validator.validateDateTime;
var validator_4 = validator.validateUnixTimestamp;
var validator_5 = validator.validateJSDate;
var utils = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, 'serializeTime', {
enumerable: true,
get: function get() {
return formatter.serializeTime;
}
});
Object.defineProperty(exports, 'serializeTimeString', {
enumerable: true,
get: function get() {
return formatter.serializeTimeString;
}
});
Object.defineProperty(exports, 'serializeDate', {
enumerable: true,
get: function get() {
return formatter.serializeDate;
}
});
Object.defineProperty(exports, 'serializeDateTime', {
enumerable: true,
get: function get() {
return formatter.serializeDateTime;
}
});
Object.defineProperty(exports, 'serializeDateTimeString', {
enumerable: true,
get: function get() {
return formatter.serializeDateTimeString;
}
});
Object.defineProperty(exports, 'serializeUnixTimestamp', {
enumerable: true,
get: function get() {
return formatter.serializeUnixTimestamp;
}
});
Object.defineProperty(exports, 'parseTime', {
enumerable: true,
get: function get() {
return formatter.parseTime;
}
});
Object.defineProperty(exports, 'parseDate', {
enumerable: true,
get: function get() {
return formatter.parseDate;
}
});
Object.defineProperty(exports, 'parseDateTime', {
enumerable: true,
get: function get() {
return formatter.parseDateTime;
}
});
Object.defineProperty(exports, 'validateTime', {
enumerable: true,
get: function get() {
return validator.validateTime;
}
});
Object.defineProperty(exports, 'validateDate', {
enumerable: true,
get: function get() {
return validator.validateDate;
}
});
Object.defineProperty(exports, 'validateDateTime', {
enumerable: true,
get: function get() {
return validator.validateDateTime;
}
});
Object.defineProperty(exports, 'validateUnixTimestamp', {
enumerable: true,
get: function get() {
return validator.validateUnixTimestamp;
}
});
Object.defineProperty(exports, 'validateJSDate', {
enumerable: true,
get: function get() {
return validator.validateJSDate;
}
});
});
unwrapExports(utils);
var date = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* An RFC 3339 compliant date scalar.
*
* Input:
* This scalar takes an RFC 3339 date string as input and
* parses it to a javascript Date.
*
* Output:
* This scalar serializes javascript Dates and
* RFC 3339 date strings to RFC 3339 date strings.
*/
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var config = {
name: 'Date',
description: 'A date string, such as 2007-12-03, compliant with the `full-date` ' + 'format outlined in section 5.6 of the RFC 3339 profile of the ' + 'ISO 8601 standard for representation of dates and times using ' + 'the Gregorian calendar.',
serialize: function serialize(value) {
if (value instanceof Date) {
if ((0, utils.validateJSDate)(value)) {
return (0, utils.serializeDate)(value);
}
throw new TypeError('Date cannot represent an invalid Date instance');
} else if (typeof value === 'string' || value instanceof String) {
if ((0, utils.validateDate)(value)) {
return value;
}
throw new TypeError('Date cannot represent an invalid date-string ' + value + '.');
} else {
throw new TypeError('Date cannot represent a non string, or non Date type ' + JSON.stringify(value));
}
},
parseValue: function parseValue(value) {
if (!(typeof value === 'string' || value instanceof String)) {
throw new TypeError('Date cannot represent non string type ' + JSON.stringify(value));
}
if ((0, utils.validateDate)(value)) {
return (0, utils.parseDate)(value);
}
throw new TypeError('Date cannot represent an invalid date-string ' + value + '.');
},
parseLiteral: function parseLiteral(ast) {
if (ast.kind !== graphql__default.Kind.STRING) {
throw new TypeError('Date cannot represent non string type ' + String(ast.value != null ? ast.value : null));
}
var value = ast.value;
if ((0, utils.validateDate)(value)) {
return (0, utils.parseDate)(value);
}
throw new TypeError('Date cannot represent an invalid date-string ' + String(value) + '.');
}
}; // eslint-disable-line
exports.default = new graphql__default.GraphQLScalarType(config);
});
unwrapExports(date);
var time = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* An RFC 3339 compliant time scalar.
*
* Input:
* This scalar takes an RFC 3339 time string as input and
* parses it to a javascript Date (with a year-month-day relative
* to the current day).
*
* Output:
* This scalar serializes javascript Dates and
* RFC 3339 time strings to RFC 3339 UTC time strings.
*/
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var config = {
name: 'Time',
description: 'A time string at UTC, such as 10:15:30Z, compliant with ' + 'the `full-time` format outlined in section 5.6 of the RFC 3339' + 'profile of the ISO 8601 standard for representation of dates and ' + 'times using the Gregorian calendar.',
serialize: function serialize(value) {
if (value instanceof Date) {
if ((0, utils.validateJSDate)(value)) {
return (0, utils.serializeTime)(value);
}
throw new TypeError('Time cannot represent an invalid Date instance');
} else if (typeof value === 'string' || value instanceof String) {
if ((0, utils.validateTime)(value)) {
return (0, utils.serializeTimeString)(value);
}
throw new TypeError('Time cannot represent an invalid time-string ' + value + '.');
} else {
throw new TypeError('Time cannot be serialized from a non string, ' + 'or non Date type ' + JSON.stringify(value));
}
},
parseValue: function parseValue(value) {
if (!(typeof value === 'string' || value instanceof String)) {
throw new TypeError('Time cannot represent non string type ' + JSON.stringify(value));
}
if ((0, utils.validateTime)(value)) {
return (0, utils.parseTime)(value);
}
throw new TypeError('Time cannot represent an invalid time-string ' + value + '.');
},
parseLiteral: function parseLiteral(ast) {
if (ast.kind !== graphql__default.Kind.STRING) {
throw new TypeError('Time cannot represent non string type ' + String(ast.value != null ? ast.value : null));
}
var value = ast.value;
if ((0, utils.validateTime)(value)) {
return (0, utils.parseTime)(value);
}
throw new TypeError('Time cannot represent an invalid time-string ' + String(value) + '.');
}
}; // eslint-disable-line
exports.default = new graphql__default.GraphQLScalarType(config);
});
unwrapExports(time);
var dateTime = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* An RFC 3339 compliant date-time scalar.
*
* Input:
* This scalar takes an RFC 3339 date-time string as input and
* parses it to a javascript Date.
*
* Output:
* This scalar serializes javascript Dates,
* RFC 3339 date-time strings and unix timestamps
* to RFC 3339 UTC date-time strings.
*/
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var config = {
name: 'DateTime',
description: 'A date-time string at UTC, such as 2007-12-03T10:15:30Z, ' + 'compliant with the `date-time` format outlined in section 5.6 of ' + 'the RFC 3339 profile of the ISO 8601 standard for representation ' + 'of dates and times using the Gregorian calendar.',
serialize: function serialize(value) {
if (value instanceof Date) {
if ((0, utils.validateJSDate)(value)) {
return (0, utils.serializeDateTime)(value);
}
throw new TypeError('DateTime cannot represent an invalid Date instance');
} else if (typeof value === 'string' || value instanceof String) {
if ((0, utils.validateDateTime)(value)) {
return (0, utils.serializeDateTimeString)(value);
}
throw new TypeError('DateTime cannot represent an invalid date-time-string ' + value + '.');
} else if (typeof value === 'number' || value instanceof Number) {
if ((0, utils.validateUnixTimestamp)(value)) {
return (0, utils.serializeUnixTimestamp)(value);
}
throw new TypeError('DateTime cannot represent an invalid Unix timestamp ' + value);
} else {
throw new TypeError('DateTime cannot be serialized from a non string, ' + 'non numeric or non Date type ' + JSON.stringify(value));
}
},
parseValue: function parseValue(value) {
if (!(typeof value === 'string' || value instanceof String)) {
throw new TypeError('DateTime cannot represent non string type ' + JSON.stringify(value));
}
if ((0, utils.validateDateTime)(value)) {
return (0, utils.parseDateTime)(value);
}
throw new TypeError('DateTime cannot represent an invalid date-time-string ' + value + '.');
},
parseLiteral: function parseLiteral(ast) {
if (ast.kind !== graphql__default.Kind.STRING) {
throw new TypeError('DateTime cannot represent non string type ' + String(ast.value != null ? ast.value : null));
}
var value = ast.value;
if ((0, utils.validateDateTime)(value)) {
return (0, utils.parseDateTime)(value);
}
throw new TypeError('DateTime cannot represent an invalid date-time-string ' + String(value) + '.');
}
}; // eslint-disable-line
exports.default = new graphql__default.GraphQLScalarType(config);
});
unwrapExports(dateTime);
var dist = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, 'GraphQLDate', {
enumerable: true,
get: function get() {
return _interopRequireDefault(date).default;
}
});
Object.defineProperty(exports, 'GraphQLTime', {
enumerable: true,
get: function get() {
return _interopRequireDefault(time).default;
}
});
Object.defineProperty(exports, 'GraphQLDateTime', {
enumerable: true,
get: function get() {
return _interopRequireDefault(dateTime).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
});
unwrapExports(dist);
var dist_1 = dist.GraphQLDate;
var dist_2 = dist.GraphQLTime;
var dist_3 = dist.GraphQLDateTime;
var lib = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
function identity(value) {
return value;
}
function parseLiteral(ast, variables) {
switch (ast.kind) {
case language.Kind.STRING:
case language.Kind.BOOLEAN:
return ast.value;
case language.Kind.INT:
case language.Kind.FLOAT:
return parseFloat(ast.value);
case language.Kind.OBJECT:
{
var value = Object.create(null);
ast.fields.forEach(function (field) {
value[field.name.value] = parseLiteral(field.value, variables);
});
return value;
}
case language.Kind.LIST:
return ast.values.map(function (n) {
return parseLiteral(n, variables);
});
case language.Kind.NULL:
return null;
case language.Kind.VARIABLE:
{
var name = ast.name.value;
return variables ? variables[name] : undefined;
}
default:
return undefined;
}
}
var _default = new graphql__default.GraphQLScalarType({
name: 'JSON',
description: 'The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).',
serialize: identity,
parseValue: identity,
parseLiteral: parseLiteral
});
exports.default = _default;
module.exports = exports.default;
});
var GraphQLJSON = unwrapExports(lib);
var lib_1 = lib.GraphQLJSON;
var pluralize = createCommonjsModule(function (module, exports) {
/* global define */
(function (root, pluralize) {
/* istanbul ignore else */
if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
// Node.
module.exports = pluralize();
} else {
// Browser global.
root.pluralize = pluralize();
}
})(commonjsGlobal, function () {
// Rule storage - pluralize and singularize need to be run sequentially,
// while other rules can be optimized using an object for instant lookups.
var pluralRules = [];
var singularRules = [];
var uncountables = {};
var irregularPlurals = {};
var irregularSingles = {};
/**
* Sanitize a pluralization rule to a usable regular expression.
*
* @param {(RegExp|string)} rule
* @return {RegExp}
*/
function sanitizeRule (rule) {
if (typeof rule === 'string') {
return new RegExp('^' + rule + '$', 'i');
}
return rule;
}
/**
* Pass in a word token to produce a function that can replicate the case on
* another word.
*
* @param {string} word
* @param {string} token
* @return {Function}
*/
function restoreCase (word, token) {
// Tokens are an exact match.
if (word === token) return token;
// Upper cased words. E.g. "HELLO".
if (word === word.toUpperCase()) return token.toUpperCase();
// Title cased words. E.g. "Title".
if (word[0] === word[0].toUpperCase()) {
return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
}
// Lower cased words. E.g. "test".
return token.toLowerCase();
}
/**
* Interpolate a regexp string.
*
* @param {string} str
* @param {Array} args
* @return {string}
*/
function interpolate (str, args) {
return str.replace(/\$(\d{1,2})/g, function (match, index) {
return args[index] || '';
});
}
/**
* Replace a word using a rule.
*
* @param {string} word
* @param {Array} rule
* @return {string}
*/
function replace (word, rule) {
return word.replace(rule[0], function (match, index) {
var result = interpolate(rule[1], arguments);
if (match === '') {
return restoreCase(word[index - 1], result);
}
return restoreCase(match, result);
});
}
/**
* Sanitize a word by passing in the word and sanitization rules.
*
* @param {string} token
* @param {string} word
* @param {Array} rules
* @return {string}
*/
function sanitizeWord (token, word, rules) {
// Empty string or doesn't need fixing.
if (!token.length || uncountables.hasOwnProperty(token)) {
return word;
}
var len = rules.length;
// Iterate over the sanitization rules and use the first one to match.
while (len--) {
var rule = rules[len];
if (rule[0].test(word)) return replace(word, rule);
}
return word;
}
/**
* Replace a word with the updated word.
*
* @param {Object} replaceMap
* @param {Object} keepMap
* @param {Array} rules
* @return {Function}
*/
function replaceWord (replaceMap, keepMap, rules) {
return function (word) {
// Get the correct token and case restoration functions.
var token = word.toLowerCase();
// Check against the keep object map.
if (keepMap.hasOwnProperty(token)) {
return restoreCase(word, token);
}
// Check against the replacement map for a direct word replacement.
if (replaceMap.hasOwnProperty(token)) {
return restoreCase(word, replaceMap[token]);
}
// Run all the rules against the word.
return sanitizeWord(token, word, rules);
};
}
/**
* Check if a word is part of the map.
*/
function checkWord (replaceMap, keepMap, rules, bool) {
return function (word) {
var token = word.toLowerCase();
if (keepMap.hasOwnProperty(token)) return true;
if (replaceMap.hasOwnProperty(token)) return false;
return sanitizeWord(token, token, rules) === token;
};
}
/**
* Pluralize or singularize a word based on the passed in count.
*
* @param {string} word
* @param {number} count
* @param {boolean} inclusive
* @return {string}
*/
function pluralize (word, count, inclusive) {
var pluralized = count === 1
? pluralize.singular(word) : pluralize.plural(word);
return (inclusive ? count + ' ' : '') + pluralized;
}
/**
* Pluralize a word.
*
* @type {Function}
*/
pluralize.plural = replaceWord(
irregularSingles, irregularPlurals, pluralRules
);
/**
* Check if a word is plural.
*
* @type {Function}
*/
pluralize.isPlural = checkWord(
irregularSingles, irregularPlurals, pluralRules
);
/**
* Singularize a word.
*
* @type {Function}
*/
pluralize.singular = replaceWord(
irregularPlurals, irregularSingles, singularRules
);
/**
* Check if a word is singular.
*
* @type {Function}
*/
pluralize.isSingular = checkWord(
irregularPlurals, irregularSingles, singularRules
);
/**
* Add a pluralization rule to the collection.
*
* @param {(string|RegExp)} rule
* @param {string} replacement
*/
pluralize.addPluralRule = function (rule, replacement) {
pluralRules.push([sanitizeRule(rule), replacement]);
};
/**
* Add a singularization rule to the collection.
*
* @param {(string|RegExp)} rule
* @param {string} replacement
*/
pluralize.addSingularRule = function (rule, replacement) {
singularRules.push([sanitizeRule(rule), replacement]);
};
/**
* Add an uncountable word rule.
*
* @param {(string|RegExp)} word
*/
pluralize.addUncountableRule = function (word) {
if (typeof word === 'string') {
uncountables[word.toLowerCase()] = true;
return;
}
// Set singular and plural references for the word.
pluralize.addPluralRule(word, '$0');
pluralize.addSingularRule(word, '$0');
};
/**
* Add an irregular word definition.
*
* @param {string} single
* @param {string} plural
*/
pluralize.addIrregularRule = function (single, plural) {
plural = plural.toLowerCase();
single = single.toLowerCase();
irregularSingles[single] = plural;
irregularPlurals[plural] = single;
};
/**
* Irregular rules.
*/
[
// Pronouns.
['I', 'we'],
['me', 'us'],
['he', 'they'],
['she', 'they'],
['them', 'them'],
['myself', 'ourselves'],
['yourself', 'yourselves'],
['itself', 'themselves'],
['herself', 'themselves'],
['himself', 'themselves'],
['themself', 'themselves'],
['is', 'are'],
['was', 'were'],
['has', 'have'],
['this', 'these'],
['that', 'those'],
// Words ending in with a consonant and `o`.
['echo', 'echoes'],
['dingo', 'dingoes'],
['volcano', 'volcanoes'],
['tornado', 'tornadoes'],
['torpedo', 'torpedoes'],
// Ends with `us`.
['genus', 'genera'],
['viscus', 'viscera'],
// Ends with `ma`.
['stigma', 'stigmata'],
['stoma', 'stomata'],
['dogma', 'dogmata'],
['lemma', 'lemmata'],
['schema', 'schemata'],
['anathema', 'anathemata'],
// Other irregular rules.
['ox', 'oxen'],
['axe', 'axes'],
['die', 'dice'],
['yes', 'yeses'],
['foot', 'feet'],
['eave', 'eaves'],
['goose', 'geese'],
['tooth', 'teeth'],
['quiz', 'quizzes'],
['human', 'humans'],
['proof', 'proofs'],
['carve', 'carves'],
['valve', 'valves'],
['looey', 'looies'],
['thief', 'thieves'],
['groove', 'grooves'],
['pickaxe', 'pickaxes'],
['whiskey', 'whiskies']
].forEach(function (rule) {
return pluralize.addIrregularRule(rule[0], rule[1]);
});
/**
* Pluralization rules.
*/
[
[/s?$/i, 's'],
[/[^\u0000-\u007F]$/i, '$0'],
[/([^aeiou]ese)$/i, '$1'],
[/(ax|test)is$/i, '$1es'],
[/(alias|[^aou]us|tlas|gas|ris)$/i, '$1es'],
[/(e[mn]u)s?$/i, '$1s'],
[/([^l]ias|[aeiou]las|[emjzr]as|[iu]am)$/i, '$1'],
[/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
[/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
[/(seraph|cherub)(?:im)?$/i, '$1im'],
[/(her|at|gr)o$/i, '$1oes'],
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/([^ch][ieo][ln])ey$/i, '$1ies'],
[/(x|ch|ss|sh|zz)$/i, '$1es'],
[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
[/(m|l)(?:ice|ouse)$/i, '$1ice'],
[/(pe)(?:rson|ople)$/i, '$1ople'],
[/(child)(?:ren)?$/i, '$1ren'],
[/eaux$/i, '$0'],
[/m[ae]n$/i, 'men'],
['thou', 'you']
].forEach(function (rule) {
return pluralize.addPluralRule(rule[0], rule[1]);
});
/**
* Singularization rules.
*/
[
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
[/ies$/i, 'y'],
[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],
[/\b(mon|smil)ies$/i, '$1ey'],
[/(m|l)ice$/i, '$1ouse'],
[/(seraph|cherub)im$/i, '$1'],
[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|tlas|gas|(?:her|at|gr)o|ris)(?:es)?$/i, '$1'],
[/(analy|ba|diagno|parenthe|progno|synop|the|empha|cri)(?:sis|ses)$/i, '$1sis'],
[/(movie|twelve|abuse|e[mn]u)s$/i, '$1'],
[/(test)(?:is|es)$/i, '$1is'],
[/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
[/(alumn|alg|vertebr)ae$/i, '$1a'],
[/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
[/(matr|append)ices$/i, '$1ix'],
[/(pe)(rson|ople)$/i, '$1rson'],
[/(child)ren$/i, '$1'],
[/(eau)x?$/i, '$1'],
[/men$/i, 'man']
].forEach(function (rule) {
return pluralize.addSingularRule(rule[0], rule[1]);
});
/**
* Uncountable rules.
*/
[
// Singular words with no plurals.
'adulthood',
'advice',
'agenda',
'aid',
'alcohol',
'ammo',
'anime',
'athletics',
'audio',
'bison',
'blood',
'bream',
'buffalo',
'butter',
'carp',
'cash',
'chassis',
'chess',
'clothing',
'cod',
'commerce',
'cooperation',
'corps',
'debris',
'diabetes',
'digestion',
'elk',
'energy',
'equipment',
'excretion',
'expertise',
'flounder',
'fun',
'gallows',
'garbage',
'graffiti',
'headquarters',
'health',
'herpes',
'highjinks',
'homework',
'housework',
'information',
'jeans',
'justice',
'kudos',
'labour',
'literature',
'machinery',
'mackerel',
'mail',
'media',
'mews',
'moose',
'music',
'manga',
'news',
'pike',
'plankton',
'pliers',
'pollution',
'premises',
'rain',
'research',
'rice',
'salmon',
'scissors',
'series',
'sewage',
'shambles',
'shrimp',
'species',
'staff',
'swine',
'tennis',
'traffic',
'transporation',
'trout',
'tuna',
'wealth',
'welfare',
'whiting',
'wildebeest',
'wildlife',
'you',
// Regexes.
/[^aeiou]ese$/i, // "chinese", "japanese"
/deer$/i, // "deer", "reindeer"
/fish$/i, // "fish", "blowfish", "angelfish"
/measles$/i,
/o[iu]s$/i, // "carnivorous"
/pox$/i, // "chickpox", "smallpox"
/sheep$/i
].forEach(pluralize.addUncountableRule);
return pluralize;
});
});
const typeIsList = (type) => {
let isList = false;
if (type.name && type.name.endsWith('Connection')) {
isList = true;
}
while (!isList && (graphql.isListType(type) || graphql.isNonNullType(type) || type.kind === 'NON_NULL' || type.kind === 'LIST')) {
if (graphql.isListType(type) || type.kind === 'LIST') {
isList = true;
break;
}
type = type.ofType;
}
return isList;
};
const getReturnType = (type) => {
if (graphql.isListType(type) || graphql.isNonNullType(type) || type.kind === 'NON_NULL' || type.kind === 'LIST') {
return getReturnType(type.ofType);
}
else {
return type.name;
}
};
class FindByUniqueError extends Error {
constructor(message, code, properties) {
super(message);
if (properties) {
Object.keys(properties).forEach(key => {
this[key] = properties[key];
});
}
// if no name provided, use the default. defineProperty ensures that it stays non-enumerable
if (!this.name) {
Object.defineProperty(this, 'name', { value: 'ApolloError' });
}
// extensions are flattened to be included in the root of GraphQLError's, so
// don't add properties to extensions
this.extensions = { code };
}
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
class Relation {
constructor($type, $field, $field0isList) {
this.type0 = $type;
this.field0 = $field;
this.field0isList = $field0isList;
}
setRelative(relation) {
this.type1 = relation.type0;
this.field1 = relation.field0;
this.field1isList = relation.field0isList;
}
isValidRelative(relation) {
if (!this.type1) {
return true;
}
else {
return this.isSameRelation(relation) || this.isCurrentRelation(relation);
}
}
isSameRelation(relation) {
return this.type0 === relation.type0 && this.field0 === relation.field0 && this.field0isList === relation.field0isList;
}
isCurrentRelation(relation) {
return this.type1 === relation.type0 && this.field1 === relation.field0 && this.field1isList === relation.field0isList;
}
getInverse(type, field, inverseType) {
const inverse = this.getInverseTuple(type, field, inverseType);
return inverse ? inverse[1] : null;
}
getInverseTuple(type, field, inverseType) {
let inverse = null;
if (this.type0 === type && this.field0 === field && (!inverseType || this.type1 === inverseType)) {
inverse = [this.type1, this.field1];
}
else if (this.type1 === type && this.field1 === field && (!inverseType || this.type0 === inverseType)) {
inverse = [this.type0, this.field0];
}
return inverse;
}
}
class Relations {
constructor() {
this.relations = new Map();
}
getRelation(name) {
let relations = null;
if (this.relations.has(name)) {
relations = this.relations.get(name);
}
return relations;
}
getInverseWithoutName(type, field, inverseType) {
let inverse = null;
const iter = this.relations.values();
let relation = iter.next().value;
while (!inverse && relation) {
inverse = relation.getInverse(type, field, inverseType);
relation = iter.next().value;
}
return inverse;
}
getInverse(name, type, field) {
let inverse = null;
if (this.relations.has(name)) {
const relation = this.relations.get(name);
inverse = relation.getInverse(type, field);
}
return inverse;
}
setRelation(name, type, field, fieldIsList) {
const newRelation = new Relation(type, field, fieldIsList);
if (!this.relations.has(name)) {
this.relations.set(name, newRelation);
}
else {
const relation = this.relations.get(name);
if (relation.isValidRelative(newRelation)) {
if (!relation.isSameRelation(newRelation)) {
relation.setRelative(newRelation);
}
}
else {
this.throwError(name, type, field, relation.field0);
}
}
}
setSelfRelation(name, type, field, fieldIsList) {
const newRelation = new Relation(type, field, fieldIsList);
newRelation.setRelative(newRelation);
this.relations.set(name, newRelation);
}
throwError(name, type, primaryField, relatedField) {
throw new Error(`Bad schema, relation could apply to multiple fields
relation name: ${name}
fortune name: ${type}
curr field: ${primaryField}
other field: ${relatedField}`);
}
}
const computeNumFieldsOfType = (type, checkFieldTypeName) => {
let resultNum = 0;
lodash.each(type.fields, field => {
if (checkFieldTypeName === getReturnType(field.type)) {
resultNum++;
}
});
return resultNum;
};
const getNumFieldsOfType = (cache, type, checkFieldTypeName) => {
let numFields = 0;
const typeName = getReturnType(type);
if (cache.has(typeName) && cache.get(typeName).has(checkFieldTypeName)) {
numFields = cache.get(typeName).get(checkFieldTypeName);
}
else {
numFields = computeNumFieldsOfType(type, checkFieldTypeName);
if (!cache.has(typeName)) {
cache.set(typeName, new Map());
}
cache.get(typeName).set(checkFieldTypeName, numFields);
}
return numFields;
};
const computeRelations = (schemaInfo, typeNameResolver = (name) => name) => {
const numFieldsOfTypeCache = new Map();
const relations = new Relations();
lodash.each(lodash.keys(schemaInfo), (typeName) => {
const type = schemaInfo[typeName];
lodash.each(type.fields, field => {
const relation = lodash.get(field, 'metadata.relation');
const fieldTypeName = getReturnType(field.type);
const reslovedTypeName = typeNameResolver(fieldTypeName);
if (relation) {
relations.setRelation(relation.name, reslovedTypeName, field.name, typeIsList(field.type));
}
else if (typeName === fieldTypeName) {
relations.setSelfRelation(`${field.name}On${typeName}`, reslovedTypeName, field.name, typeIsList(field.type));
}
else {
const fieldTypeInfo = schemaInfo[fieldTypeName];
if (type && fieldTypeInfo) {
const numFields = getNumFieldsOfType(numFieldsOfTypeCache, type, fieldTypeName);
const reverseNumFields = getNumFieldsOfType(numFieldsOfTypeCache, fieldTypeInfo, typeName);
if (numFields === 1 && reverseNumFields === 1) {
const possibleTypes = [typeName, fieldTypeName];
possibleTypes.sort();
relations.setRelation(possibleTypes.join('_'), reslovedTypeName, field.name, typeIsList(field.type));
}
}
}
});
});
return relations;
};
var Mutation;
(function (Mutation) {
Mutation[Mutation["Create"] = 0] = "Create";
Mutation[Mutation["Update"] = 1] = "Update";
Mutation[Mutation["Delete"] = 2] = "Delete";
Mutation[Mutation["Upsert"] = 3] = "Upsert";
})(Mutation || (Mutation = {}));
const clean = (obj) => {
const returnObj = {};
for (const propName in obj) {
if (obj[propName] !== null && obj[propName] !== undefined) {
// tslint:disable-next-line:prefer-conditional-expression
if (lodash.isObject(obj[propName]) && !lodash.isEmpty(obj[propName])) {
returnObj[propName] = obj[propName];
}
else {
returnObj[propName] = obj[propName];
}
}
}
return returnObj;
};
const setupArgs = (results, args) => {
// setup the arguments to use the new types
results.forEach((types) => {
types = types ? types : [];
types.forEach(type => {
if (type && type.key && type.id && type.index > -1) {
const key = type.key;
const id = type.id;
const arg = args[type.index];
if (lodash.isArray(arg[key])) {
if (lodash.isArray(id)) {
arg[key] = lodash.union(id, arg[key]);
}
else if (!arg[key].includes(id)) {
arg[key].push(id);
}
}
else {
arg[key] = id;
}
}
});
});
return args;
};
const resolveArgs = (args, returnType, mutation, dataResolver, currRecord, _args, _context, _info) => __awaiter(void 0, void 0, void 0, function* () {
const promises = [];
args.forEach((currArg, index) => {
for (const argName in currArg) {
let argReturnType;
let argReturnRootType;
if ((graphql.isObjectType(returnType) || graphql.isInterfaceType(returnType)) && returnType.getFields()[argName]) {
argReturnType = returnType.getFields()[argName].type;
argReturnRootType = graphql.getNamedType(argReturnType);
if (argReturnRootType['name'].endsWith('Connection')) {
argReturnRootType = _info.schema.getType(argReturnRootType['name'].replace(/Connection$/g, ''));
argReturnType = new graphql.GraphQLList(argReturnRootType);
}
}
if (argReturnRootType && !graphql.isScalarType(argReturnRootType) && !graphql.isEnumType(argReturnRootType)) {
const arg = currArg[argName];
if (lodash.isObject(arg) && argReturnType) {
currArg[argName] = typeIsList(argReturnType) ? [] : undefined;
if (graphql.isInterfaceType(argReturnRootType) || graphql.isUnionType(argReturnRootType)) {
for (const argKey in arg) {
const argTypeName = pluralize.singular(argKey).toLowerCase();
argReturnRootType = lodash.find(_info.schema.getTypeMap(), type => {
return type.name.toLowerCase() === argTypeName;
});
promises.push(mutateResolver(mutation, dataResolver)(currRecord, arg[argKey], _context, _info, index, argName, argReturnRootType));
}
}
else {
promises.push(mutateResolver(mutation, dataResolver)(currRecord, arg, _context, _info, index, argName, argReturnRootType));
}
}
}
}
});
const results = yield Promise.all(promises);
args = setupArgs(results, args);
return args;
});
const mutateResolver = (mutation, dataResolver) => {
return (currRecord, _args, _context, _info, index, key, returnType) => __awaiter(void 0, void 0, void 0, function* () {
yield dataResolver.beginTransaction();
// iterate over all the non-id arguments