#!/usr/bin/env node /** * Relay v7.0.0 * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 48); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/interopRequireDefault"); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(7), GraphQLError = _require.GraphQLError; /** * Creates an error describing invalid application code (GraphQL/Schema) * that must be fixed by the end developer. This should only be used * for local errors that don't affect processing of other user code. */ function createUserError(message, locations, nodes) { var _nodes; var messageWithLocations = message; if (locations != null) { var printedLocations = printLocations(locations); messageWithLocations = printedLocations.length === 0 ? message : [message].concat(printedLocations).join('\n\n') + '\n'; } return new GraphQLError(messageWithLocations, (_nodes = nodes) !== null && _nodes !== void 0 ? _nodes : []); } /** * Similar to createUserError but for errors that are *not* recoverable: * the compiler should not continue to process other inputs because their * validity can't be determined. */ function createNonRecoverableUserError(message, locations, nodes) { var _nodes2; var messageWithLocations = message; if (locations != null) { var printedLocations = printLocations(locations); messageWithLocations = printedLocations.length === 0 ? message : [message].concat(printedLocations).join('\n\n') + '\n'; } var error = new GraphQLError(messageWithLocations, (_nodes2 = nodes) !== null && _nodes2 !== void 0 ? _nodes2 : []); return new Error(error.message); } /** * Creates an error describing a problem with the compiler itself - such * as a broken invariant - that must be fixed within the compiler. */ function createCompilerError(message, locations, nodes) { var _nodes3; var messageWithLocations = message; if (locations != null) { var printedLocations = printLocations(locations); messageWithLocations = printedLocations.length === 0 ? message : [message].concat(printedLocations).join('\n\n') + '\n'; } var error = new GraphQLError("Internal Error: ".concat(messageWithLocations), (_nodes3 = nodes) !== null && _nodes3 !== void 0 ? _nodes3 : []); return new Error(error.message); } /** * Iterates over the elements of some iterable value, calling the * supplied callback for each item with a guard for user errors. * * Non-user errors abort the iteration and are instantly rethrown. * User errors are collected and rethrown at the end, if multiple user errors * occur, a combined error is thrown. */ function eachWithCombinedError(iterable, fn) { var errors = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var item = _step.value; try { fn(item); } catch (error) { if (error instanceof GraphQLError) { errors.push(error); } else { throw error; } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (errors.length > 0) { if (errors.length === 1) { throw errors[0]; } throw createUserError("Encountered ".concat(errors.length, " errors:\n") + errors.map(function (error) { return String(error).split('\n').map(function (line, index) { return index === 0 ? "- ".concat(line) : " ".concat(line); }).join('\n'); }).join('\n')); } } function printLocations(locations) { var printedLocations = []; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var location = _step2.value; var sourceLocation = location; while (sourceLocation.kind === 'Derived') { sourceLocation = sourceLocation.source; } switch (sourceLocation.kind) { case 'Source': { // source location var prefix = sourceLocation === location ? 'Source: ' : 'Source (derived): '; printedLocations.push(prefix + highlightSourceAtLocation(sourceLocation.source, getLocation(sourceLocation.source, sourceLocation.start))); break; } case 'Generated': { printedLocations.push('Source: (generated)'); break; } case 'Unknown': { printedLocations.push('Source: (unknown)'); break; } default: { sourceLocation; throw createCompilerError("RelayCompilerError: cannot print location '".concat(String(sourceLocation), "'.")); } } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return printedLocations; } /** * Render a helpful description of the location of the error in the GraphQL * Source document. */ function highlightSourceAtLocation(source, location) { var firstLineColumnOffset = source.locationOffset.column - 1; var body = whitespace(firstLineColumnOffset) + source.body; var lineIndex = location.line - 1; var lineOffset = source.locationOffset.line - 1; var lineNum = location.line + lineOffset; var columnOffset = location.line === 1 ? firstLineColumnOffset : 0; var columnNum = location.column + columnOffset; var lines = body.split(/\r\n|[\n\r]/g); return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"], ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]); } function printPrefixedLines(lines) { var existingLines = lines.filter(function (_ref) { var _ = _ref[0], line = _ref[1]; return line !== undefined; }); var padLen = 0; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _step3$value = _step3.value, prefix = _step3$value[0]; padLen = Math.max(padLen, prefix.length); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { _iterator3["return"](); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } return existingLines.map(function (_ref2) { var prefix = _ref2[0], line = _ref2[1]; return lpad(padLen, prefix) + line; }).join('\n'); } function whitespace(len) { return Array(len + 1).join(' '); } function lpad(len, str) { return whitespace(len - str.length) + str; } function getLocation(source, position) { var lineRegexp = /\r\n|[\n\r]/g; var line = 1; var column = position + 1; var match; while ((match = lineRegexp.exec(source.body)) && match.index < position) { line += 1; column = position + 1 - (match.index + match[0].length); } return { line: line, column: column }; } module.exports = { createCompilerError: createCompilerError, createNonRecoverableUserError: createNonRecoverableUserError, createUserError: createUserError, eachWithCombinedError: eachWithCombinedError }; /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/objectSpread"); /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var invariant = __webpack_require__(4); var _require = __webpack_require__(1), eachWithCombinedError = _require.eachWithCombinedError; /** * @public * * Helper for writing compiler transforms that apply "map" and/or "filter"-style * operations to compiler contexts. The `visitor` argument accepts a map of IR * kinds to user-defined functions that can map nodes of that kind to new values * (of the same kind). * * If a visitor function is defined for a kind, the visitor function is * responsible for traversing its children (by calling `this.traverse(node)`) * and returning either the input (to indicate no changes), a new node (to * indicate changes), or null/undefined (to indicate the removal of that node * from the output). * * If a visitor function is *not* defined for a kind, a default traversal is * used to evaluate its children. * * The `stateInitializer` argument accepts an optional function to construct the * state for each document (fragment or root) in the context. Any documents for * which the initializer returns null/undefined is deleted from the context * without being traversed. * * Example: Alias all scalar fields with the reverse of their name: * * ``` * transform(context, { * ScalarField: visitScalarField, * }); * * function visitScalarField(field: ScalarField, state: State): ?ScalarField { * // Traverse child nodes - for a scalar field these are the arguments & * // directives. * const nextField = this.traverse(field, state); * // Return a new node with a different alias. * return { * ...nextField, * alias: nextField.name.split('').reverse().join(''), * }; * } * ``` */ function transform(context, visitor, stateInitializer) { var transformer = new Transformer(context, visitor); return context.withMutations(function (ctx) { var nextContext = ctx; eachWithCombinedError(context.documents(), function (prevNode) { var nextNode; if (stateInitializer === undefined) { nextNode = transformer.visit(prevNode, undefined); } else { var _state = stateInitializer(prevNode); if (_state != null) { nextNode = transformer.visit(prevNode, _state); } } if (!nextNode) { nextContext = nextContext.remove(prevNode.name); } else if (nextNode !== prevNode) { nextContext = nextContext.replace(nextNode); } }); return nextContext; }); } /** * @internal */ var Transformer = /*#__PURE__*/ function () { function Transformer(context, visitor) { this._context = context; this._states = []; this._visitor = visitor; } /** * @public * * Returns the original compiler context that is being transformed. This can * be used to look up fragments by name, for example. */ var _proto = Transformer.prototype; _proto.getContext = function getContext() { return this._context; } /** * @public * * Transforms the node, calling a user-defined visitor function if defined for * the node's kind. Uses the given state for this portion of the traversal. * * Note: This differs from `traverse` in that it calls a visitor function for * the node itself. */ ; _proto.visit = function visit(node, state) { this._states.push(state); var nextNode = this._visit(node); this._states.pop(); return nextNode; } /** * @public * * Transforms the children of the given node, skipping the user-defined * visitor function for the node itself. Uses the given state for this portion * of the traversal. * * Note: This differs from `visit` in that it does not call a visitor function * for the node itself. */ ; _proto.traverse = function traverse(node, state) { this._states.push(state); var nextNode = this._traverse(node); this._states.pop(); return nextNode; }; _proto._visit = function _visit(node) { var nodeVisitor = this._visitor[node.kind]; if (nodeVisitor) { // If a handler for the kind is defined, it is responsible for calling // `traverse` to transform children as necessary. var _state2 = this._getState(); var nextNode = nodeVisitor.call(this, node, _state2); return nextNode; } // Otherwise traverse is called automatically. return this._traverse(node); }; _proto._traverse = function _traverse(prevNode) { var nextNode; switch (prevNode.kind) { case 'Argument': nextNode = this._traverseChildren(prevNode, null, ['value']); break; case 'Literal': case 'LocalArgumentDefinition': case 'RootArgumentDefinition': case 'Variable': nextNode = prevNode; break; case 'Defer': nextNode = this._traverseChildren(prevNode, ['selections'], ['if']); break; case 'Stream': nextNode = this._traverseChildren(prevNode, ['selections'], ['if', 'initialCount']); break; case 'ClientExtension': nextNode = this._traverseChildren(prevNode, ['selections']); break; case 'Directive': nextNode = this._traverseChildren(prevNode, ['args']); break; case 'ModuleImport': nextNode = this._traverseChildren(prevNode, ['selections']); if (!nextNode.selections.length) { nextNode = null; } break; case 'FragmentSpread': case 'ScalarField': nextNode = this._traverseChildren(prevNode, ['args', 'directives']); break; case 'InlineDataFragmentSpread': nextNode = this._traverseChildren(prevNode, ['selections']); break; case 'ConnectionField': case 'LinkedField': nextNode = this._traverseChildren(prevNode, ['args', 'directives', 'selections']); if (!nextNode.selections.length) { nextNode = null; } break; case 'Connection': nextNode = this._traverseChildren(prevNode, ['args', 'selections']); if (!nextNode.selections.length) { nextNode = null; } break; case 'Condition': nextNode = this._traverseChildren(prevNode, ['directives', 'selections'], ['condition']); if (!nextNode.selections.length) { nextNode = null; } break; case 'InlineFragment': nextNode = this._traverseChildren(prevNode, ['directives', 'selections']); if (!nextNode.selections.length) { nextNode = null; } break; case 'Fragment': case 'Root': nextNode = this._traverseChildren(prevNode, ['argumentDefinitions', 'directives', 'selections']); break; case 'Request': nextNode = this._traverseChildren(prevNode, null, ['fragment', 'root']); break; case 'SplitOperation': nextNode = this._traverseChildren(prevNode, ['selections']); break; default: prevNode; true ? true ? invariant(false, 'GraphQLIRTransformer: Unknown kind `%s`.', prevNode.kind) : undefined : undefined; } return nextNode; }; _proto._traverseChildren = function _traverseChildren(prevNode, pluralKeys, singularKeys) { var _this = this; var nextNode; pluralKeys && pluralKeys.forEach(function (key) { var prevItems = prevNode[key]; if (!prevItems) { return; } !Array.isArray(prevItems) ? true ? invariant(false, 'GraphQLIRTransformer: Expected data for `%s` to be an array, got `%s`.', key, prevItems) : undefined : void 0; var nextItems = _this._map(prevItems); if (nextNode || nextItems !== prevItems) { nextNode = nextNode || (0, _objectSpread2["default"])({}, prevNode); nextNode[key] = nextItems; } }); singularKeys && singularKeys.forEach(function (key) { var prevItem = prevNode[key]; if (!prevItem) { return; } var nextItem = _this._visit(prevItem); if (nextNode || nextItem !== prevItem) { nextNode = nextNode || (0, _objectSpread2["default"])({}, prevNode); nextNode[key] = nextItem; } }); return nextNode || prevNode; }; _proto._map = function _map(prevItems) { var _this2 = this; var nextItems; prevItems.forEach(function (prevItem, index) { var nextItem = _this2._visit(prevItem); if (nextItems || nextItem !== prevItem) { nextItems = nextItems || prevItems.slice(0, index); if (nextItem) { nextItems.push(nextItem); } } }); return nextItems || prevItems; }; _proto._getState = function _getState() { !this._states.length ? true ? invariant(false, 'GraphQLIRTransformer: Expected a current state to be set but found none. ' + 'This is usually the result of mismatched number of pushState()/popState() ' + 'calls.') : undefined : void 0; return this._states[this._states.length - 1]; }; return Transformer; }(); module.exports = { transform: transform }; /***/ }), /* 4 */ /***/ (function(module, exports) { module.exports = require("fbjs/lib/invariant"); /***/ }), /* 5 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/toConsumableArray"); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _asyncToGenerator = __webpack_require__(10); var invariant = __webpack_require__(4); /** * The compiler profiler builds a "call graph" of high level operations as a * means of tracking time spent over the course of running the compiler. */ var enabled = false; var traces = [{ ph: 'M', pid: 0, tid: 0, name: 'process_name', args: { name: 'relay-compiler' } }, { ph: 'M', pid: 0, tid: 0, name: 'thread_name', args: { name: 'relay-compiler' } }]; var stack = []; function enable() { enabled = true; } function getTraces() { return traces; } /** * Run the provided function as part of a stack profile. */ function run(name, fn) { return instrument(fn, name)(); } /** * Run the provided async function as part context in a stack profile. * See instrumentAsyncContext() for limitations and usage notes. */ function asyncContext(name, fn) { return instrumentAsyncContext(fn, name)(); } /** * Wait for the provided async operation as an async profile. */ function waitFor(name, fn) { return instrumentWait(fn, name)(); } /** * Return a new instrumented sync function to be part of a stack profile. * * This instruments synchronous functions to be displayed in a stack * visualization. To instrument async functions, see instrumentAsyncContext() * and instrumentWait(). */ function instrument(fn, name) { var _ref, _name; if (!enabled) { return fn; } var profileName = (_ref = (_name = name) !== null && _name !== void 0 ? _name : // $FlowFixMe - Flow no longer considers statics of functions as any fn.displayName) !== null && _ref !== void 0 ? _ref : fn.name; var instrumented = function instrumented() { var traceId = start(profileName); try { return fn.apply(this, arguments); } finally { end(traceId); } }; instrumented.displayName = profileName; return instrumented; } /** * Return a new instrumented async function which provides context for a stack. * * Because the resulting profiling information will be incorporated into a * stack visualization, the instrumented function must represent a distinct * region of time which does not overlap with any other async context. * * In other words, functions instrumented with instrumentAsyncContext must not * run in parallel via Promise.all(). * * To instrument functions which will run in parallel, use instrumentWait(). */ function instrumentAsyncContext(fn, name) { var _ref2, _name2; if (!enabled) { return fn; } var profileName = (_ref2 = (_name2 = name) !== null && _name2 !== void 0 ? _name2 : // $FlowFixMe - Flow no longer considers statics of functions as any fn.displayName) !== null && _ref2 !== void 0 ? _ref2 : fn.name; var instrumented = /*#__PURE__*/ function () { var _instrumented = _asyncToGenerator(function* () { var traceId = start(profileName); try { return yield fn.apply(this, arguments); } finally { end(traceId); } }); function instrumented() { return _instrumented.apply(this, arguments); } return instrumented; }(); instrumented.displayName = profileName; return instrumented; } /** * Return a new instrumented function which performs an awaited async operation. * * The instrumented function is not included in the overall run time of the * compiler, instead it captures the time waiting on some asynchronous external * resource such as network or filesystem which are often run in parallel. */ function instrumentWait(fn, name) { var _ref3, _name3; if (!enabled) { return fn; } var profileName = (_ref3 = (_name3 = name) !== null && _name3 !== void 0 ? _name3 : // $FlowFixMe - Flow no longer considers statics of functions as any fn.displayName) !== null && _ref3 !== void 0 ? _ref3 : fn.name; var instrumented = /*#__PURE__*/ function () { var _instrumented2 = _asyncToGenerator(function* () { var traceId = startWait(profileName); try { return yield fn.apply(this, arguments); } finally { end(traceId); } }); function instrumented() { return _instrumented2.apply(this, arguments); } return instrumented; }(); instrumented.displayName = profileName; return instrumented; } var T_ZERO = process.hrtime(); // Return a Uint32 of microtime duration since program start. function microtime() { var hrtime = process.hrtime(T_ZERO); // eslint-disable-next-line no-bitwise return 0 | hrtime[0] * 1e6 + Math.round(hrtime[1] / 1e3); } /** * Start a stack profile with a particular name, returns an ID to pass to end(). * * Other profiles may start before this one ends, which will be represented as * nested operations, however all nested operations must end before this ends. * * In particular, be careful to end after errors. */ function start(name) { var beginTrace = { ph: 'B', name: name, pid: 0, tid: 0, ts: microtime() }; traces.push(beginTrace); stack.push(beginTrace); return traces.length - 1; } var asyncID = 0; /** * Start an async wait profile with a particular name, returns an ID to pass * to end(). * * Other profiles may start before this one ends, which will be represented as * nested operations, however all nested operations must end before this ends. * * In particular, be careful to end after errors. */ function startWait(name) { traces.push({ ph: 'b', name: name, cat: 'wait', id: asyncID++, pid: 0, tid: 0, ts: microtime() }); return traces.length - 1; } function end(traceIdx) { var trace = traces[traceIdx]; if (trace.ph === 'b') { traces.push({ ph: 'e', cat: trace.cat, name: trace.name, id: trace.id, pid: trace.pid, tid: trace.tid, ts: microtime() }); return; } !(trace.ph === 'B') ? true ? invariant(false, 'Begin trace phase') : undefined : void 0; !(stack.pop() === trace) ? true ? invariant(false, 'GraphQLCompilerProfiler: The profile trace %s ended before nested traces. ' + 'If it is async, try using Profile.waitFor or Profile.profileWait.', trace.name) : undefined : void 0; var prevTrace = traces[traces.length - 1]; if (trace === prevTrace) { traces[traceIdx] = { ph: 'X', name: trace.name, pid: trace.pid, tid: trace.tid, ts: trace.ts, dur: microtime() - trace.ts }; return; } traces.push({ ph: 'E', name: trace.name, pid: trace.pid, tid: trace.tid, ts: microtime() }); } module.exports = { enable: enable, getTraces: getTraces, run: run, asyncContext: asyncContext, waitFor: waitFor, instrument: instrument, instrumentAsyncContext: instrumentAsyncContext, instrumentWait: instrumentWait, start: start, startWait: startWait, end: end }; /***/ }), /* 7 */ /***/ (function(module, exports) { module.exports = require("graphql"); /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("path"); /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = require("relay-runtime"); /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/asyncToGenerator"); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var ID = 'id'; /** * @public * * Determine if an AST node contains a fragment/operation definition. */ function isExecutableDefinitionAST(ast) { return ast.kind === 'FragmentDefinition' || ast.kind === 'OperationDefinition'; } /** * @public * * Determine if an AST node contains a schema definition. */ function isSchemaDefinitionAST(ast) { return ast.kind === 'SchemaDefinition' || ast.kind === 'ScalarTypeDefinition' || ast.kind === 'ObjectTypeDefinition' || ast.kind === 'InterfaceTypeDefinition' || ast.kind === 'UnionTypeDefinition' || ast.kind === 'EnumTypeDefinition' || ast.kind === 'InputObjectTypeDefinition' || ast.kind === 'DirectiveDefinition' || ast.kind === 'ScalarTypeExtension' || ast.kind === 'ObjectTypeExtension' || ast.kind === 'InterfaceTypeExtension' || ast.kind === 'UnionTypeExtension' || ast.kind === 'EnumTypeExtension' || ast.kind === 'InputObjectTypeExtension'; } function generateIDField(idType) { return { kind: 'ScalarField', alias: ID, args: [], directives: [], handles: null, loc: { kind: 'Generated' }, metadata: null, name: ID, type: idType }; } function getNullableBooleanInput(schema) { return schema.assertInputType(schema.expectBooleanType()); } function getNonNullBooleanInput(schema) { return schema.assertInputType(schema.getNonNullType(schema.expectBooleanType())); } function getNullableStringInput(schema) { return schema.assertInputType(schema.expectStringType()); } function getNonNullStringInput(schema) { return schema.assertInputType(schema.getNonNullType(schema.expectStringType())); } function getNullableIdInput(schema) { return schema.assertInputType(schema.expectIdType()); } function getNonNullIdInput(schema) { return schema.assertInputType(schema.getNonNullType(schema.expectIdType())); } module.exports = { generateIDField: generateIDField, isExecutableDefinitionAST: isExecutableDefinitionAST, isSchemaDefinitionAST: isSchemaDefinitionAST, getNullableBooleanInput: getNullableBooleanInput, getNonNullBooleanInput: getNonNullBooleanInput, getNullableStringInput: getNullableStringInput, getNonNullStringInput: getNonNullStringInput, getNullableIdInput: getNullableIdInput, getNonNullIdInput: getNonNullIdInput }; /***/ }), /* 12 */ /***/ (function(module, exports) { module.exports = require("crypto"); /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = require("fs"); /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = require("immutable"); /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(7), visit = _require.visit; var NodeKeys = { Argument: ['value'], ClientExtension: ['selections'], Condition: ['condition', 'selections'], Defer: ['selections', 'if'], Connection: ['args', 'selections'], ConnectionField: ['args', 'directives', 'selections'], Directive: ['args'], Fragment: ['argumentDefinitions', 'directives', 'selections'], FragmentSpread: ['args', 'directives'], InlineDataFragmentSpread: ['selections'], InlineFragment: ['directives', 'selections'], LinkedField: ['args', 'directives', 'selections'], Literal: [], LocalArgumentDefinition: [], ModuleImport: ['selections'], Request: ['fragment', 'root'], Root: ['argumentDefinitions', 'directives', 'selections'], RootArgumentDefinition: [], ScalarField: ['args', 'directives'], SplitOperation: ['selections'], Stream: ['selections', 'if', 'initialCount'], Variable: [] }; function visitIR(root, visitor) { return visit(root, visitor, NodeKeys); } module.exports = { visit: visitIR }; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ // Copy of Variables type from '../../../react-relay/classic/tools/RelayTypes' // Duplicating here rather than importing it since we can't take on a dependency // outside of relay-compiler. function getLiteralArgumentValues(args) { var values = {}; args.forEach(function (arg) { if (arg.value.kind === 'Literal') { values[arg.name] = arg.value.value; } }); return values; } module.exports = getLiteralArgumentValues; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var GraphQLCompilerContext = __webpack_require__(19); var GraphQLIRVisitor = __webpack_require__(15); var SchemaUtils = __webpack_require__(11); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError; /** * Returns a transformed version of the input context where each document's * argument definitions are updated to accurately describe the root variables * used (or reachable) from that document: * - Fragment argument definitions are updated to include local argument * definitions and any root variables that are referenced * by the fragment (or any fragments it transitively spreads). * - Root argument definitions are updated to reflect the variables * referenced locally and all root variables referenced by any * fragments it (transitively) spreads. */ function inferRootArgumentDefinitions(context) { // This transform does two main tasks: // - Determine the set of root variables referenced locally in each // fragment. Note that RootArgumentDefinitions in the fragment's // argumentDefinitions can contain spurious entries for legacy // reasons. Instead of using those the fragment is traversed // to reanalyze variable usage. // - Determine the set of root variables that are transitively referenced // by each fragment, ie the union of all root variables used in the // fragment and any fragments it transitively spreads. // Cache fragments as they are transformed to avoid duplicate processing. // Because @argument values don't matter (only variable names/types), // each reachable fragment only has to be checked once. var transformed = new Map(); var nextContext = new GraphQLCompilerContext(context.getSchema()); return nextContext.addAll(Array.from(context.documents(), function (node) { switch (node.kind) { case 'Fragment': { var argumentDefinitions = transformFragmentArguments(context, transformed, node); return (0, _objectSpread2["default"])({}, node, { argumentDefinitions: Array.from(argumentDefinitions.values()) }); } case 'Root': { return transformRoot(context, transformed, node); } case 'SplitOperation': { return node; } default: { node; throw createCompilerError("inferRootArgumentDefinitions: Unsupported kind '".concat(node.kind, "'.")); } } })); } function transformRoot(context, transformed, root) { // Ignore argument definitions, determine what root variables are // transitively referenced var argumentDefinitions = new Map(); var localArgumentDefinitions = new Map(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = root.argumentDefinitions.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _step.value, name = _step$value[0], argDef = _step$value[1]; if (argDef.kind === 'LocalArgumentDefinition') { localArgumentDefinitions.set(name, argDef); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } visit(context, transformed, argumentDefinitions, root); return (0, _objectSpread2["default"])({}, root, { argumentDefinitions: Array.from(argumentDefinitions.values(), function (argDef) { var _ref, _ref2; if (argDef.kind !== 'RootArgumentDefinition') { throw createCompilerError("inferRootArgumentDefinitions: Expected inferred variable '$".concat(argDef.name, "' to be a root variables."), [argDef.loc]); } var localDefinition = localArgumentDefinitions.get(argDef.name); var type = (_ref = localDefinition === null || localDefinition === void 0 ? void 0 : localDefinition.type) !== null && _ref !== void 0 ? _ref : argDef.type; return { defaultValue: (_ref2 = localDefinition === null || localDefinition === void 0 ? void 0 : localDefinition.defaultValue) !== null && _ref2 !== void 0 ? _ref2 : null, kind: 'LocalArgumentDefinition', loc: argDef.loc, name: argDef.name, type: type }; }) }); } function transformFragmentArguments(context, transformed, fragment) { var name = fragment.name; var transformedArguments = transformed.get(name); if (transformedArguments != null) { return transformedArguments; } // Start with only the explicitly defined local arguments, recover the // correct set of root variables excluding invalid @arguments values. var argumentDefinitions = new Map(); fragment.argumentDefinitions.forEach(function (argDef) { if (argDef.kind === 'LocalArgumentDefinition') { argumentDefinitions.set(argDef.name, argDef); } }); // Break cycles by initially caching a version that only has local // arguments. If the current fragment is reached again, it won't have // any root variables to add to its parents. The traversal below will // find any root variables and update the cached version of the // fragment. transformed.set(name, argumentDefinitions); visit(context, transformed, argumentDefinitions, fragment); transformed.set(name, argumentDefinitions); return argumentDefinitions; } function visit(context, transformed, argumentDefinitions, node) { GraphQLIRVisitor.visit(node, { FragmentSpread: function FragmentSpread(fragmentSpread) { var fragment = context.getFragment(fragmentSpread.name, fragmentSpread.loc); var referencedFragmentArguments = transformFragmentArguments(context, transformed, fragment); // Detect root variables being passed as the value of @arguments; // recover the expected type from the corresponding argument definitions. fragmentSpread.args.forEach(function (arg) { var argDef = referencedFragmentArguments.get(arg.name); if (argDef != null && arg.value.kind === 'Variable' && !argumentDefinitions.has(arg.value.variableName)) { argumentDefinitions.set(arg.value.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: arg.loc }, name: arg.value.variableName, type: argDef.type }); } }); // Merge any root variables referenced by the spread fragment // into this (parent) fragment's arguments. var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = referencedFragmentArguments.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var argDef = _step2.value; if (argDef.kind === 'RootArgumentDefinition') { argumentDefinitions.set(argDef.name, argDef); } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } }, Argument: function Argument(argument) { var _variable$type; if (argument.value.kind !== 'Variable') { return false; } var variable = argument.value; var type = (_variable$type = variable.type) !== null && _variable$type !== void 0 ? _variable$type : argument.type; if (type == null) { return; } if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: argument.loc }, name: variable.variableName, type: type }); } return false; }, Condition: function Condition(condition) { var _variable$type2; var variable = condition.condition; if (variable.kind !== 'Variable') { return; } var type = (_variable$type2 = variable.type) !== null && _variable$type2 !== void 0 ? _variable$type2 : SchemaUtils.getNonNullBooleanInput(context.getSchema()); if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: variable.loc }, name: variable.variableName, type: type }); } }, Connection: function Connection(connection) { var stream = connection.stream; if (stream == null) { return; } var defaultType = SchemaUtils.getNonNullBooleanInput(context.getSchema()); [stream["if"], stream.initialCount].forEach(function (variable) { var _variable$type3; if (variable == null || variable.kind !== 'Variable') { return; } var type = (_variable$type3 = variable.type) !== null && _variable$type3 !== void 0 ? _variable$type3 : defaultType; if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: variable.loc }, name: variable.variableName, type: type }); } }); }, Defer: function Defer(defer) { var _variable$type4; var variable = defer["if"]; if (variable == null || variable.kind !== 'Variable') { return; } var type = (_variable$type4 = variable.type) !== null && _variable$type4 !== void 0 ? _variable$type4 : SchemaUtils.getNonNullBooleanInput(context.getSchema()); if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: variable.loc }, name: variable.variableName, type: type }); } }, Stream: function Stream(stream) { [stream["if"], stream.initialCount].forEach(function (variable) { var _variable$type5; if (variable == null || variable.kind !== 'Variable') { return; } var type = (_variable$type5 = variable.type) !== null && _variable$type5 !== void 0 ? _variable$type5 : SchemaUtils.getNonNullBooleanInput(context.getSchema()); if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: variable.loc }, name: variable.variableName, type: type }); } }); }, LinkedField: function LinkedField(field) { if (!field.handles) { return; } field.handles.forEach(function (handle) { var _variable$type6; var variable = handle.dynamicKey; if (variable == null) { return; } var type = (_variable$type6 = variable.type) !== null && _variable$type6 !== void 0 ? _variable$type6 : SchemaUtils.getNullableStringInput(context.getSchema()); if (!argumentDefinitions.has(variable.variableName)) { // root variable argumentDefinitions.set(variable.variableName, { kind: 'RootArgumentDefinition', loc: { kind: 'Derived', source: variable.loc }, name: variable.variableName, type: type }); } }); } }); } module.exports = inferRootArgumentDefinitions; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @emails oncall+relay */ var _asyncToGenerator = __webpack_require__(10); var childProcess = __webpack_require__(53); var watchman = __webpack_require__(54); var MAX_ATTEMPT_LIMIT = 5; function delay(delayMs) { return new Promise(function (resolve) { return setTimeout(resolve, delayMs); }); } var GraphQLWatchmanClient = /*#__PURE__*/ function () { GraphQLWatchmanClient.isAvailable = function isAvailable() { return new Promise(function (resolve) { // This command not only will verify that watchman CLI is available // More than that `watchman version` is a command that runs on the server. // And it can tell us that watchman is up and running // Also `watchman version` check ``relative_root`` capability // under the covers var proc = childProcess.spawn('watchman', ['version']); proc.on('error', function () { resolve(false); }); proc.on('close', function (code) { resolve(code === 0); }); }); }; function GraphQLWatchmanClient() { var attemptLimit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; this._client = new watchman.Client(); this._attemptLimit = Math.max(Math.min(MAX_ATTEMPT_LIMIT, attemptLimit), 0); } var _proto = GraphQLWatchmanClient.prototype; _proto._command = function _command() { var _this = this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve, reject) { _this._client.command(args, function (error, response) { if (error) { reject(error); } else { resolve(response); } }); }); }; _proto.command = /*#__PURE__*/ function () { var _command2 = _asyncToGenerator(function* () { var attempt = 0; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } while (true) { try { attempt++; return yield this._command.apply(this, args); } catch (error) { if (attempt > this._attemptLimit) { throw error; } yield delay(Math.pow(2, attempt) * 500); this._client.end(); this._client = new watchman.Client(); } } }); function command() { return _command2.apply(this, arguments); } return command; }(); _proto.hasCapability = /*#__PURE__*/ function () { var _hasCapability = _asyncToGenerator(function* (capability) { var resp = yield this.command('list-capabilities'); return resp.capabilities.includes(capability); }); function hasCapability(_x) { return _hasCapability.apply(this, arguments); } return hasCapability; }(); _proto.watchProject = /*#__PURE__*/ function () { var _watchProject = _asyncToGenerator(function* (baseDir) { var resp = yield this.command('watch-project', baseDir); if ('warning' in resp) { console.error('Warning:', resp.warning); } return { root: resp.watch, relativePath: resp.relative_path }; }); function watchProject(_x2) { return _watchProject.apply(this, arguments); } return watchProject; }(); _proto.on = function on(event, callback) { this._client.on(event, callback); }; _proto.end = function end() { this._client.end(); }; return GraphQLWatchmanClient; }(); module.exports = GraphQLWatchmanClient; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var Profiler = __webpack_require__(6); var invariant = __webpack_require__(4); var _require = __webpack_require__(1), createUserError = _require.createUserError; // $FlowFixMe - immutable.js is not flow-typed var _require2 = __webpack_require__(14), ImmutableOrderedMap = _require2.OrderedMap; /** * An immutable representation of a corpus of documents being compiled together. * For each document, the context stores the IR and any validation errors. */ var GraphQLCompilerContext = /*#__PURE__*/ function () { function GraphQLCompilerContext(schema) { this._isMutable = false; this._documents = new ImmutableOrderedMap(); this._withTransform = new WeakMap(); this._schema = schema; } /** * Returns the documents for the context in the order they were added. */ var _proto = GraphQLCompilerContext.prototype; _proto.documents = function documents() { return this._documents.toArray(); }; _proto.forEachDocument = function forEachDocument(fn) { this._documents.forEach(fn); }; _proto.replace = function replace(node) { return this._update(this._documents.update(node.name, function (existing) { !existing ? true ? invariant(false, 'GraphQLCompilerContext: Expected to replace existing node %s, but' + 'one was not found in the context.', node.name) : undefined : void 0; return node; })); }; _proto.add = function add(node) { return this._update(this._documents.update(node.name, function (existing) { !!existing ? true ? invariant(false, 'GraphQLCompilerContext: Duplicate document named `%s`. GraphQL ' + 'fragments and roots must have unique names.', node.name) : undefined : void 0; return node; })); }; _proto.addAll = function addAll(nodes) { return this.withMutations(function (mutable) { return nodes.reduce(function (ctx, definition) { return ctx.add(definition); }, mutable); }); } /** * Apply a list of compiler transforms and return a new compiler context. */ ; _proto.applyTransforms = function applyTransforms(transforms, reporter) { var _this = this; return Profiler.run('applyTransforms', function () { return transforms.reduce(function (ctx, transform) { return ctx.applyTransform(transform, reporter); }, _this); }); } /** * Applies a transform to this context, returning a new context. * * This is memoized such that applying the same sequence of transforms will * not result in duplicated work. */ ; _proto.applyTransform = function applyTransform(transform, reporter) { var transformed = this._withTransform.get(transform); if (!transformed) { var start = process.hrtime(); transformed = Profiler.instrument(transform)(this); var delta = process.hrtime(start); var deltaMs = Math.round((delta[0] * 1e9 + delta[1]) / 1e6); reporter && reporter.reportTime(transform.name, deltaMs); this._withTransform.set(transform, transformed); } return transformed; }; _proto.get = function get(name) { return this._documents.get(name); }; _proto.getFragment = function getFragment(name, referencedFrom) { var node = this._documents.get(name); if (node == null) { throw createUserError("Cannot find fragment '".concat(name, "'."), referencedFrom != null ? [referencedFrom] : null); } else if (node.kind !== 'Fragment') { throw createUserError("Cannot find fragment '".concat(name, "', a document with this name exists ") + 'but is not a fragment.', [node.loc, referencedFrom].filter(Boolean)); } return node; }; _proto.getRoot = function getRoot(name) { var node = this._documents.get(name); if (node == null) { throw createUserError("Cannot find root '".concat(name, "'.")); } else if (node.kind !== 'Root') { throw createUserError("Cannot find root '".concat(name, "', a document with this name exists but ") + 'is not a root.', [node.loc]); } return node; }; _proto.remove = function remove(name) { return this._update(this._documents["delete"](name)); }; _proto.withMutations = function withMutations(fn) { var mutableCopy = this._update(this._documents.asMutable()); mutableCopy._isMutable = true; var result = fn(mutableCopy); result._isMutable = false; result._documents = result._documents.asImmutable(); return this._documents === result._documents ? this : result; }; _proto._update = function _update(documents) { var context = this._isMutable ? this : new GraphQLCompilerContext(this.getSchema()); context._documents = documents; return context; }; _proto.getSchema = function getSchema() { return this._schema; }; return GraphQLCompilerContext; }(); module.exports = GraphQLCompilerContext; /***/ }), /* 20 */ /***/ (function(module, exports) { module.exports = require("nullthrows"); /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ function buildFragmentSpread(fragment) { var args = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fragment.argumentDefinitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var argDef = _step.value; if (argDef.kind !== 'LocalArgumentDefinition') { continue; } args.push({ kind: 'Argument', loc: { kind: 'Derived', source: argDef.loc }, name: argDef.name, type: argDef.type, value: { kind: 'Variable', loc: { kind: 'Derived', source: argDef.loc }, variableName: argDef.name, type: argDef.type } }); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return { args: args, directives: [], kind: 'FragmentSpread', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: fragment.name }; } function buildOperationArgumentDefinitions(argumentDefinitions) { return argumentDefinitions.map(function (argDef) { if (argDef.kind === 'LocalArgumentDefinition') { return argDef; } else { return { kind: 'LocalArgumentDefinition', name: argDef.name, type: argDef.type, defaultValue: null, loc: argDef.loc }; } }); } module.exports = { buildFragmentSpread: buildFragmentSpread, buildOperationArgumentDefinitions: buildOperationArgumentDefinitions }; /***/ }), /* 22 */ /***/ (function(module, exports) { module.exports = require("@babel/types"); /***/ }), /* 23 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/defineProperty"); /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _asyncToGenerator = __webpack_require__(10); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var Profiler = __webpack_require__(6); var crypto = __webpack_require__(12); var invariant = __webpack_require__(4); var path = __webpack_require__(8); var CodegenDirectory = /*#__PURE__*/ function () { function CodegenDirectory(dir, options) { var _this = this; var _options$filesystem, _options$shards; this._filesystem = (_options$filesystem = options.filesystem) !== null && _options$filesystem !== void 0 ? _options$filesystem : __webpack_require__(13); this.onlyValidate = options.onlyValidate; this._shards = (_options$shards = options.shards) !== null && _options$shards !== void 0 ? _options$shards : 1; if (this._filesystem.existsSync(dir)) { !this._filesystem.statSync(dir).isDirectory() ? true ? invariant(false, 'Expected `%s` to be a directory.', dir) : undefined : void 0; } if (!this.onlyValidate) { var dirs = []; var parent = dir; while (!this._filesystem.existsSync(parent)) { dirs.unshift(parent); parent = path.dirname(parent); } dirs.forEach(function (d) { return _this._filesystem.mkdirSync(d); }); if (this._shards > 1) { for (var shard = 0; shard < this._shards; shard++) { var shardDir = path.join(dir, this._getShardName(shard)); if (this._filesystem.existsSync(shardDir)) { !this._filesystem.statSync(dir).isDirectory() ? true ? invariant(false, 'Expected `%s` to be a directory.', dir) : undefined : void 0; } else { this._filesystem.mkdirSync(shardDir); } } } } this._files = new Set(); this.changes = { deleted: [], updated: [], created: [], unchanged: [] }; this._dir = dir; } CodegenDirectory.combineChanges = function combineChanges(dirs) { var changes = { deleted: [], updated: [], created: [], unchanged: [] }; dirs.forEach(function (dir) { var _changes$deleted, _changes$updated, _changes$created, _changes$unchanged; (_changes$deleted = changes.deleted).push.apply(_changes$deleted, (0, _toConsumableArray2["default"])(dir.changes.deleted)); (_changes$updated = changes.updated).push.apply(_changes$updated, (0, _toConsumableArray2["default"])(dir.changes.updated)); (_changes$created = changes.created).push.apply(_changes$created, (0, _toConsumableArray2["default"])(dir.changes.created)); (_changes$unchanged = changes.unchanged).push.apply(_changes$unchanged, (0, _toConsumableArray2["default"])(dir.changes.unchanged)); }); return changes; }; CodegenDirectory.hasChanges = function hasChanges(changes) { return changes.created.length > 0 || changes.updated.length > 0 || changes.deleted.length > 0; }; CodegenDirectory.formatChanges = function formatChanges(changes, options) { var output = []; function formatFiles(label, files) { if (files.length > 0) { output.push(label + ':'); files.forEach(function (file) { output.push(' - ' + file); }); } } if (options.onlyValidate) { formatFiles('Missing', changes.created); formatFiles('Out of date', changes.updated); formatFiles('Extra', changes.deleted); } else { formatFiles('Created', changes.created); formatFiles('Updated', changes.updated); formatFiles('Deleted', changes.deleted); output.push("Unchanged: ".concat(changes.unchanged.length, " files")); } return output.join('\n'); }; CodegenDirectory.printChanges = function printChanges(changes, options) { Profiler.run('CodegenDirectory.printChanges', function () { var output = CodegenDirectory.formatChanges(changes, options); // eslint-disable-next-line no-console console.log(output); }); }; CodegenDirectory.getAddedRemovedFiles = function getAddedRemovedFiles(dirs) { var added = []; var removed = []; dirs.forEach(function (dir) { dir.changes.created.forEach(function (name) { added.push(dir.getPath(name)); }); dir.changes.deleted.forEach(function (name) { removed.push(dir.getPath(name)); }); }); return { added: added, removed: removed }; }; CodegenDirectory.sourceControlAddRemove = /*#__PURE__*/ function () { var _sourceControlAddRemove = _asyncToGenerator(function* (sourceControl, dirs) { var _CodegenDirectory$get = CodegenDirectory.getAddedRemovedFiles(dirs), added = _CodegenDirectory$get.added, removed = _CodegenDirectory$get.removed; sourceControl.addRemove(added, removed); }); function sourceControlAddRemove(_x, _x2) { return _sourceControlAddRemove.apply(this, arguments); } return sourceControlAddRemove; }(); var _proto = CodegenDirectory.prototype; _proto.printChanges = function printChanges() { CodegenDirectory.printChanges(this.changes, { onlyValidate: this.onlyValidate }); }; _proto.read = function read(filename) { var filePath = path.join(this._dir, filename); if (this._filesystem.existsSync(filePath)) { return this._filesystem.readFileSync(filePath, 'utf8'); } return null; }; _proto.markUnchanged = function markUnchanged(filename) { this._addGenerated(filename); this.changes.unchanged.push(filename); } /** * Marks a files as updated or out of date without actually writing the file. * This is probably only be useful when doing validation without intention to * actually write to disk. */ ; _proto.markUpdated = function markUpdated(filename) { this._addGenerated(filename); this.changes.updated.push(filename); }; _proto.writeFile = function writeFile(filename, content) { var _this2 = this; var shouldRepersist = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; Profiler.run('CodegenDirectory.writeFile', function () { _this2._addGenerated(filename); var filePath = _this2.getPath(filename); if (_this2._filesystem.existsSync(filePath)) { var existingContent = _this2._filesystem.readFileSync(filePath, 'utf8'); if (existingContent === content && !shouldRepersist) { _this2.changes.unchanged.push(filename); } else { _this2._writeFile(filePath, content); _this2.changes.updated.push(filename); } } else { _this2._writeFile(filePath, content); _this2.changes.created.push(filename); } }); }; _proto._writeFile = function _writeFile(filePath, content) { if (!this.onlyValidate) { this._filesystem.writeFileSync(filePath, content, 'utf8'); } } /** * Deletes all non-generated files, except for invisible "dot" files (ie. * files with names starting with "."). */ ; _proto.deleteExtraFiles = function deleteExtraFiles() { var _this3 = this; Profiler.run('CodegenDirectory.deleteExtraFiles', function () { if (_this3._shards > 1) { _this3._filesystem.readdirSync(_this3._dir).forEach(function (firstLevel) { if (firstLevel.startsWith('.')) { // allow hidden files on the first level of the codegen directory return; } var firstLevelPath = path.join(_this3._dir, firstLevel); if (!_this3._filesystem.statSync(firstLevelPath).isDirectory()) { // Delete all files on the top level, all files need to be in a // shard directory. _this3._filesystem.unlinkSync(firstLevelPath); return; } _this3._filesystem.readdirSync(firstLevelPath).forEach(function (actualFile) { if (_this3._files.has(actualFile)) { return; } if (!_this3.onlyValidate) { try { _this3._filesystem.unlinkSync(path.join(firstLevelPath, actualFile)); } catch (_unused) { throw new Error('CodegenDirectory: Failed to delete `' + actualFile + '` in `' + _this3._dir + '`.'); } } _this3.changes.deleted.push(actualFile); }); }); } else { _this3._filesystem.readdirSync(_this3._dir).forEach(function (actualFile) { if (actualFile.startsWith('.') || _this3._files.has(actualFile)) { return; } if (!_this3.onlyValidate) { try { _this3._filesystem.unlinkSync(path.join(_this3._dir, actualFile)); } catch (_unused2) { throw new Error('CodegenDirectory: Failed to delete `' + actualFile + '` in `' + _this3._dir + '`.'); } } _this3.changes.deleted.push(actualFile); }); } }); }; _proto.getPath = function getPath(filename) { if (this._shards > 1) { var hasher = crypto.createHash('md5'); hasher.update(filename, 'utf8'); var shard = hasher.digest().readUInt32BE(0) % this._shards; return path.join(this._dir, this._getShardName(shard), filename); } return path.join(this._dir, filename); }; _proto._getShardName = function _getShardName(shardNumber) { var base16length = Math.ceil(Math.log2(256) / 4); return shardNumber.toString(16).padStart(base16length, '0'); }; _proto._addGenerated = function _addGenerated(filename) { !!this._files.has(filename) ? true ? invariant(false, 'CodegenDirectory: Tried to generate `%s` twice in `%s`.', filename, this._dir) : undefined : void 0; this._files.add(filename); }; return CodegenDirectory; }(); module.exports = CodegenDirectory; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var Profiler = __webpack_require__(6); var _require = __webpack_require__(11), isExecutableDefinitionAST = _require.isExecutableDefinitionAST, isSchemaDefinitionAST = _require.isSchemaDefinitionAST; var _require2 = __webpack_require__(7), extendSchema = _require2.extendSchema, parse = _require2.parse, print = _require2.print, visit = _require2.visit; function convertASTDocuments(schema, documents, transform) { return Profiler.run('ASTConvert.convertASTDocuments', function () { var definitions = definitionsFromDocuments(documents); var astDefinitions = []; documents.forEach(function (doc) { doc.definitions.forEach(function (definition) { if (isExecutableDefinitionAST(definition)) { astDefinitions.push(definition); } }); }); return convertASTDefinitions(schema, definitions, transform); }); } function convertASTDocumentsWithBase(schema, baseDocuments, documents, transform) { return Profiler.run('ASTConvert.convertASTDocumentsWithBase', function () { var baseDefinitions = definitionsFromDocuments(baseDocuments); var definitions = definitionsFromDocuments(documents); var requiredDefinitions = new Map(); var baseMap = new Map(); baseDefinitions.forEach(function (definition) { if (isExecutableDefinitionAST(definition)) { var definitionName = definition.name && definition.name.value; // If there's no name, no reason to put in the map if (definitionName != null) { if (baseMap.has(definitionName)) { throw new Error("Duplicate definition of '".concat(definitionName, "'.")); } baseMap.set(definitionName, definition); } } }); var definitionsToVisit = []; definitions.forEach(function (definition) { if (isExecutableDefinitionAST(definition)) { definitionsToVisit.push(definition); } }); while (definitionsToVisit.length > 0) { var definition = definitionsToVisit.pop(); var name = definition.name && definition.name.value; if (name == null) { continue; } if (requiredDefinitions.has(name)) { if (requiredDefinitions.get(name) !== definition) { throw new Error("Duplicate definition of '".concat(name, "'.")); } continue; } requiredDefinitions.set(name, definition); visit(definition, { FragmentSpread: function FragmentSpread(spread) { var baseDefinition = baseMap.get(spread.name.value); if (baseDefinition) { // We only need to add those definitions not already included // in definitions definitionsToVisit.push(baseDefinition); } } }); } var definitionsToConvert = []; requiredDefinitions.forEach(function (definition) { return definitionsToConvert.push(definition); }); return convertASTDefinitions(schema, definitionsToConvert, transform); }); } function convertASTDefinitions(schema, definitions, transform) { var operationDefinitions = []; definitions.forEach(function (definition) { if (isExecutableDefinitionAST(definition)) { operationDefinitions.push(definition); } }); return transform(schema, operationDefinitions); } function definitionsFromDocuments(documents) { var definitions = []; documents.forEach(function (doc) { doc.definitions.forEach(function (definition) { return definitions.push(definition); }); }); return definitions; } /** * Extends a GraphQLSchema with a list of schema extensions in string form. */ function transformASTSchema(schema, schemaExtensions) { return Profiler.run('ASTConvert.transformASTSchema', function () { if (schemaExtensions.length === 0) { return schema; } var extension = schemaExtensions.join('\n'); return cachedExtend(schema, extension, function () { return extendSchema(schema, parse(extension)); }); }); } /** * Extends a GraphQLSchema with a list of schema extensions in AST form. */ function extendASTSchema(baseSchema, documents) { return Profiler.run('ASTConvert.extendASTSchema', function () { var schemaExtensions = []; documents.forEach(function (doc) { doc.definitions.forEach(function (definition) { if (isSchemaDefinitionAST(definition)) { schemaExtensions.push(definition); } }); }); if (schemaExtensions.length === 0) { return baseSchema; } var key = schemaExtensions.map(print).join('\n'); return cachedExtend(baseSchema, key, function () { return extendSchema(baseSchema, { kind: 'Document', definitions: schemaExtensions }, // TODO T24511737 figure out if this is dangerous { assumeValid: true }); }); }); } var extendedSchemas = new Map(); function cachedExtend(schema, key, compute) { var cache = extendedSchemas.get(schema); if (!cache) { cache = {}; extendedSchemas.set(schema, cache); } var extendedSchema = cache[key]; if (!extendedSchema) { extendedSchema = compute(); cache[key] = extendedSchema; } return extendedSchema; } module.exports = { convertASTDocuments: convertASTDocuments, convertASTDocumentsWithBase: convertASTDocumentsWithBase, extendASTSchema: extendASTSchema, transformASTSchema: transformASTSchema }; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var Profiler = __webpack_require__(6); var _require = __webpack_require__(14), ImmutableMap = _require.Map; var ASTCache = /*#__PURE__*/ function () { function ASTCache(config) { this._documents = new Map(); this._baseDir = config.baseDir; this._parse = Profiler.instrument(config.parse, 'ASTCache.parseFn'); } // Short-term: we don't do subscriptions/delta updates, instead always use all definitions var _proto = ASTCache.prototype; _proto.documents = function documents() { return ImmutableMap(this._documents); } // parse should return the set of changes ; _proto.parseFiles = function parseFiles(files) { var _this = this; var documents = ImmutableMap(); files.forEach(function (file) { if (!file.exists) { _this._documents["delete"](file.relPath); return; } var doc = function () { try { return _this._parse(_this._baseDir, file); } catch (error) { throw new Error("Parse error: ".concat(error, " in \"").concat(file.relPath, "\"")); } }(); if (!doc) { _this._documents["delete"](file.relPath); return; } documents = documents.set(file.relPath, doc); _this._documents.set(file.relPath, doc); }); return documents; }; return ASTCache; }(); module.exports = ASTCache; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var Profiler = __webpack_require__(6); var orList = __webpack_require__(62); var partitionArray = __webpack_require__(28); var _require = __webpack_require__(29), DEFAULT_HANDLE_KEY = _require.DEFAULT_HANDLE_KEY; var _require2 = __webpack_require__(1), createCompilerError = _require2.createCompilerError, createUserError = _require2.createUserError, eachWithCombinedError = _require2.eachWithCombinedError; var _require3 = __webpack_require__(11), isExecutableDefinitionAST = _require3.isExecutableDefinitionAST; var _require4 = __webpack_require__(30), getFieldDefinitionLegacy = _require4.getFieldDefinitionLegacy; var _require5 = __webpack_require__(7), parseGraphQL = _require5.parse, parseType = _require5.parseType, print = _require5.print, Source = _require5.Source; var ARGUMENT_DEFINITIONS = 'argumentDefinitions'; var ARGUMENTS = 'arguments'; var DEPRECATED_UNCHECKED_ARGUMENTS = 'uncheckedArguments_DEPRECATED'; var DIRECTIVE_WHITELIST = new Set([ARGUMENT_DEFINITIONS, DEPRECATED_UNCHECKED_ARGUMENTS, ARGUMENTS]); /** * @internal * * This directive is not intended for use by developers directly. To set a field * handle in product code use a compiler plugin. */ var CLIENT_FIELD = '__clientField'; var CLIENT_FIELD_HANDLE = 'handle'; var CLIENT_FIELD_KEY = 'key'; var CLIENT_FIELD_FILTERS = 'filters'; var INCLUDE = 'include'; var SKIP = 'skip'; var IF = 'if'; /** * Transforms GraphQL text into Relay Compiler's internal, strongly-typed * intermediate representation (IR). */ function parse(schema, text, filename) { var ast = parseGraphQL(new Source(text, filename)); // TODO T24511737 figure out if this is dangerous var parser = new RelayParser(schema.DEPRECATED__extend(ast), ast.definitions); return parser.transform(); } /** * Transforms untyped GraphQL parse trees (ASTs) into Relay Compiler's * internal, strongly-typed intermediate representation (IR). */ function transform(schema, definitions) { return Profiler.run('RelayParser.transform', function () { var parser = new RelayParser(schema, definitions); return parser.transform(); }); } /** * @private */ var RelayParser = /*#__PURE__*/ function () { function RelayParser(schema, definitions) { var _this = this; this._definitions = new Map(); // leaving this configurable to make it easy to experiment w changing later this._getFieldDefinition = getFieldDefinitionLegacy; this._schema = schema; var duplicated = new Set(); definitions.forEach(function (def) { if (isExecutableDefinitionAST(def)) { var name = getName(def); if (_this._definitions.has(name)) { duplicated.add(name); return; } _this._definitions.set(name, def); } }); if (duplicated.size) { throw createUserError('RelayParser: Encountered duplicate definitions for one or more ' + 'documents: each document must have a unique name. Duplicated documents:\n' + Array.from(duplicated, function (name) { return "- ".concat(name); }).join('\n')); } } var _proto = RelayParser.prototype; _proto.transform = function transform() { var _this2 = this; var nodes = []; var entries = new Map(); // Construct a mapping of name to definition ast + variable definitions. // This allows the subsequent AST -> IR tranformation to reference the // defined arguments of referenced fragments. eachWithCombinedError(this._definitions, function (_ref4) { var name = _ref4[0], definition = _ref4[1]; var variableDefinitions = _this2._buildArgumentDefinitions(definition); entries.set(name, { definition: definition, variableDefinitions: variableDefinitions }); }); // Convert the ASTs to IR. eachWithCombinedError(entries.values(), function (_ref5) { var definition = _ref5.definition, variableDefinitions = _ref5.variableDefinitions; var node = parseDefinition(_this2._schema, _this2._getFieldDefinition, entries, definition, variableDefinitions); nodes.push(node); }); return nodes; } /** * Constructs a mapping of variable names to definitions for the given * operation/fragment definition. */ ; _proto._buildArgumentDefinitions = function _buildArgumentDefinitions(definition) { switch (definition.kind) { case 'OperationDefinition': return this._buildOperationArgumentDefinitions(definition); case 'FragmentDefinition': return this._buildFragmentArgumentDefinitions(definition); default: definition; throw createCompilerError("Unexpected ast kind '".concat(definition.kind, "'."), [definition]); } } /** * Constructs a mapping of variable names to definitions using the * variables defined in `@argumentDefinitions`. */ ; _proto._buildFragmentArgumentDefinitions = function _buildFragmentArgumentDefinitions(fragment) { var _this3 = this; var variableDirectives = (fragment.directives || []).filter(function (directive) { return getName(directive) === ARGUMENT_DEFINITIONS; }); if (!variableDirectives.length) { return new Map(); } if (variableDirectives.length !== 1) { throw createUserError("Directive @".concat(ARGUMENT_DEFINITIONS, " may be defined at most once per ") + 'fragment.', null, variableDirectives); } var variableDirective = variableDirectives[0]; // $FlowIssue: refining directly on `variableDirective.arguments` doesn't // work, below accesses all report arguments could still be null/undefined. var args = variableDirective.arguments; if (variableDirective == null || !Array.isArray(args)) { return new Map(); } if (!args.length) { throw createUserError("Directive @".concat(ARGUMENT_DEFINITIONS, " requires arguments: remove the ") + 'directive to skip defining local variables for this fragment.', null, [variableDirective]); } var variables = new Map(); args.forEach(function (arg) { var _ref; var argName = getName(arg); var previousVariable = variables.get(argName); if (previousVariable != null) { throw createUserError("Duplicate definition for variable '$".concat(argName, "'."), null, [previousVariable.ast, arg]); } if (arg.value.kind !== 'ObjectValue') { throw createUserError("Expected definition for variable '$".concat(argName, "' to be an object ") + "with the shape: '{type: string, defaultValue?: mixed}.", null, [arg.value]); } var defaultValueNode; var typeString; arg.value.fields.forEach(function (field) { var name = getName(field); if (name === 'type') { typeString = transformLiteralValue(field.value, field); } else if (name === 'defaultValue') { defaultValueNode = field.value; } else { throw createUserError("Expected definition for variable '$".concat(argName, "' to be an object ") + "with the shape: '{type: string, defaultValue?: mixed}.", null, [arg.value]); } }); if (typeof typeString !== 'string') { throw createUserError("Expected definition for variable '$".concat(argName, "' to be an object ") + "with the shape: '{type: string, defaultValue?: mixed}.", null, [arg.value]); } var typeFromAST = _this3._schema.getTypeFromAST(parseType(typeString)); if (typeFromAST == null) { throw createUserError("Unknown type \"".concat(typeString, "\" referenced in the argument definitions."), null, [arg]); } var type = _this3._schema.asInputType(typeFromAST); if (type == null) { throw createUserError("Expected type \"".concat(typeString, "\" to be an input type in the \"").concat(arg.name.value, "\" argument definitions."), null, [arg.value]); } var defaultValue = defaultValueNode != null ? transformValue(_this3._schema, defaultValueNode, type, function (variableAst) { throw createUserError("Expected 'defaultValue' to be a literal, got a variable.", null, [variableAst]); }, { nonStrictEnums: true }) : null; if (defaultValue != null && defaultValue.kind !== 'Literal') { throw createUserError("Expected 'defaultValue' to be a literal, got a variable.", [defaultValue.loc]); } variables.set(argName, { ast: arg, defaultValue: (_ref = defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.value) !== null && _ref !== void 0 ? _ref : null, defined: true, name: argName, type: type }); }); return variables; } /** * Constructs a mapping of variable names to definitions using the * standard GraphQL syntax for variable definitions. */ ; _proto._buildOperationArgumentDefinitions = function _buildOperationArgumentDefinitions(operation) { var schema = this._schema; var variableDefinitions = new Map(); (operation.variableDefinitions || []).forEach(function (def) { var name = getName(def.variable); var typeFromAST = schema.getTypeFromAST(def.type); if (typeFromAST == null) { throw createUserError("Unknown type: '".concat(getTypeName(def.type), "'."), null, [def.type]); } var type = schema.asInputType(typeFromAST); if (type == null) { throw createUserError("Expected type \"".concat(getTypeName(def.type), "\" to be an input type."), null, [def.type]); } var defaultValue = def.defaultValue ? transformLiteralValue(def.defaultValue, def) : null; var previousDefinition = variableDefinitions.get(name); if (previousDefinition != null) { throw createUserError("Duplicate definition for variable '$".concat(name, "'."), null, [previousDefinition.ast, def]); } variableDefinitions.set(name, { ast: def, defaultValue: defaultValue, defined: true, name: name, type: type }); }); return variableDefinitions; }; return RelayParser; }(); /** * @private */ function parseDefinition(schema, getFieldDefinition, entries, definition, variableDefinitions) { var parser = new GraphQLDefinitionParser(schema, getFieldDefinition, entries, definition, variableDefinitions); return parser.transform(); } /** * @private */ var GraphQLDefinitionParser = /*#__PURE__*/ function () { function GraphQLDefinitionParser(schema, getFieldDefinition, entries, definition, variableDefinitions) { this._definition = definition; this._entries = entries; this._getFieldDefinition = getFieldDefinition; this._schema = schema; this._variableDefinitions = variableDefinitions; this._unknownVariables = new Map(); } var _proto2 = GraphQLDefinitionParser.prototype; _proto2.transform = function transform() { var definition = this._definition; switch (definition.kind) { case 'OperationDefinition': return this._transformOperation(definition); case 'FragmentDefinition': return this._transformFragment(definition); default: definition; throw createCompilerError("Unsupported definition type ".concat(definition.kind), [definition]); } }; _proto2._recordAndVerifyVariableReference = function _recordAndVerifyVariableReference(variable, name, usedAsType) { // Special case for variables used in @arguments where we currently // aren't guaranteed to be able to resolve the type. if (usedAsType == null) { if (!this._variableDefinitions.has(name) && !this._unknownVariables.has(name)) { this._unknownVariables.set(name, { ast: variable, type: null }); } return; } var variableDefinition = this._variableDefinitions.get(name); if (variableDefinition != null) { // If the variable is defined, all usages must be compatible var effectiveType = variableDefinition.type; if (variableDefinition.defaultValue != null) { // If a default value is defined then it is guaranteed to be used // at runtime such that the effective type of the variable is non-null effectiveType = this._schema.getNonNullType(this._schema.getNullableType(effectiveType)); } if (!this._schema.isTypeSubTypeOf(effectiveType, usedAsType)) { throw createUserError("Variable '$".concat(name, "' was defined as type '").concat(String(variableDefinition.type), "' but used in a location expecting the type '").concat(String(usedAsType), "'"), null, [variableDefinition.ast, variable]); } } else { var previous = this._unknownVariables.get(name); if (!previous || !previous.type) { // No previous usage, current type is strongest this._unknownVariables.set(name, { ast: variable, type: usedAsType }); } else { var previousVariable = previous.ast, previousType = previous.type; if (!(this._schema.isTypeSubTypeOf(usedAsType, previousType) || this._schema.isTypeSubTypeOf(previousType, usedAsType))) { throw createUserError("Variable '$".concat(name, "' was used in locations expecting the conflicting types '").concat(String(previousType), "' and '").concat(String(usedAsType), "'."), null, [previousVariable, variable]); } // If the new used type has stronger requirements, use that type as reference, // otherwise keep referencing the previous type if (this._schema.isTypeSubTypeOf(usedAsType, previousType)) { this._unknownVariables.set(name, { ast: variable, type: usedAsType }); } } } }; _proto2._getDirectiveLocations = function _getDirectiveLocations() { if (!this._directiveLocations) { var directiveDefs = this._schema.getDirectives(); this._directiveLocations = new Map(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = directiveDefs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var def = _step.value; this._directiveLocations.set(def.name, def.locations); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return this._directiveLocations; }; _proto2._validateDirectivesLocation = function _validateDirectivesLocation(directives, allowedLocaction) { if (!directives || !directives.length) { return; } var directiveLocs = this._getDirectiveLocations(); var mismatches = directives.filter(function (directive) { var name = getName(directive); if (DIRECTIVE_WHITELIST.has(name)) { return false; } var locs = directiveLocs.get(name); if (locs == null) { throw createUserError("Unknown directive '".concat(name, "'."), null, [directive]); } return !locs.some(function (loc) { return loc === allowedLocaction; }); }); if (mismatches.length) { var invalidDirectives = mismatches.map(function (directive) { return '@' + getName(directive); }).join(', '); throw createUserError("Invalid directives ".concat(invalidDirectives, " found on ").concat(allowedLocaction, "."), null, mismatches); } }; _proto2._transformFragment = function _transformFragment(fragment) { var directives = this._transformDirectives((fragment.directives || []).filter(function (directive) { return getName(directive) !== ARGUMENT_DEFINITIONS; }), 'FRAGMENT_DEFINITION'); var typeFromAST = this._schema.getTypeFromAST(fragment.typeCondition); if (typeFromAST == null) { throw createUserError("Fragment \"".concat(fragment.name.value, "\" cannot condition on unknown ") + "type \"".concat(String(fragment.typeCondition.name.value), "\"."), null, [fragment.typeCondition]); } var type = this._schema.asCompositeType(typeFromAST); if (type == null) { throw createUserError("Fragment \"".concat(fragment.name.value, "\" cannot condition on non composite ") + "type \"".concat(String(type), "\"."), null, [fragment.typeCondition]); } var selections = this._transformSelections(fragment.selectionSet, type, fragment.typeCondition); var argumentDefinitions = (0, _toConsumableArray2["default"])(buildArgumentDefinitions(this._variableDefinitions)); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = this._unknownVariables[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _step2$value = _step2.value, name = _step2$value[0], variableReference = _step2$value[1]; argumentDefinitions.push({ kind: 'RootArgumentDefinition', loc: buildLocation(variableReference.ast.loc), name: name, type: variableReference.type }); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return { kind: 'Fragment', directives: directives, loc: buildLocation(fragment.loc), metadata: null, name: getName(fragment), selections: selections, type: type, // $FlowFixMe - could be null argumentDefinitions: argumentDefinitions }; }; _proto2._getLocationFromOperation = function _getLocationFromOperation(definition) { switch (definition.operation) { case 'query': return 'QUERY'; case 'mutation': return 'MUTATION'; case 'subscription': return 'SUBSCRIPTION'; default: definition.operation; throw createCompilerError("Unknown operation type '".concat(definition.operation, "'."), null, [definition]); } }; _proto2._transformOperation = function _transformOperation(definition) { var name = getName(definition); var directives = this._transformDirectives(definition.directives || [], this._getLocationFromOperation(definition)); var type; var operation; var schema = this._schema; switch (definition.operation) { case 'query': operation = 'query'; type = schema.expectQueryType(); break; case 'mutation': operation = 'mutation'; type = schema.expectMutationType(); break; case 'subscription': operation = 'subscription'; type = schema.expectSubscriptionType(); break; default: definition.operation; throw createCompilerError("Unknown operation type '".concat(definition.operation, "'."), null, [definition]); } if (!definition.selectionSet) { throw createUserError('Expected operation to have selections.', null, [definition]); } var selections = this._transformSelections(definition.selectionSet, type); var argumentDefinitions = buildArgumentDefinitions(this._variableDefinitions); if (this._unknownVariables.size !== 0) { throw createUserError("Query '".concat(name, "' references undefined variables."), null, Array.from(this._unknownVariables.values(), function (variableReference) { return variableReference.ast; })); } return { kind: 'Root', operation: operation, loc: buildLocation(definition.loc), metadata: null, name: name, argumentDefinitions: argumentDefinitions, directives: directives, selections: selections, type: type }; }; _proto2._transformSelections = function _transformSelections(selectionSet, parentType, parentTypeAST) { var _this4 = this; return selectionSet.selections.map(function (selection) { var node; if (selection.kind === 'Field') { node = _this4._transformField(selection, parentType); } else if (selection.kind === 'FragmentSpread') { node = _this4._transformFragmentSpread(selection, parentType, parentTypeAST); } else if (selection.kind === 'InlineFragment') { node = _this4._transformInlineFragment(selection, parentType, parentTypeAST); } else { selection.kind; throw createCompilerError("Unknown ast kind '".concat(selection.kind, "'."), [selection]); } var _this4$_splitConditio = _this4._splitConditions(node.directives), conditions = _this4$_splitConditio[0], directives = _this4$_splitConditio[1]; var conditionalNodes = applyConditions(conditions, // $FlowFixMe(>=0.28.0) [(0, _objectSpread2["default"])({}, node, { directives: directives })]); if (conditionalNodes.length !== 1) { throw createCompilerError('Expected exactly one condition node.', null, selection.directives); } return conditionalNodes[0]; }); }; _proto2._transformInlineFragment = function _transformInlineFragment(fragment, parentType, parentTypeAST) { var schema = this._schema; var typeCondition = fragment.typeCondition != null ? schema.getTypeFromAST(fragment.typeCondition) : parentType; if (typeCondition == null) { var _fragment$typeConditi; throw createUserError('Inline fragments can only be on object, interface or union types' + ", got unknown type '".concat(getTypeName(fragment.typeCondition), "'."), null, [(_fragment$typeConditi = fragment.typeCondition) !== null && _fragment$typeConditi !== void 0 ? _fragment$typeConditi : fragment]); } var typeConditionName = schema.getTypeString(typeCondition); typeCondition = schema.asCompositeType(typeCondition); if (typeCondition == null) { var _fragment$typeConditi2; throw createUserError('Inline fragments can only be on object, interface or union types' + ", got '".concat(typeConditionName, "'."), null, [(_fragment$typeConditi2 = fragment.typeCondition) !== null && _fragment$typeConditi2 !== void 0 ? _fragment$typeConditi2 : fragment]); } var rawParentType = this._schema.assertCompositeType(this._schema.getRawType(parentType)); checkFragmentSpreadTypeCompatibility(this._schema, typeCondition, rawParentType, null, fragment.typeCondition, parentTypeAST); var directives = this._transformDirectives(fragment.directives || [], 'INLINE_FRAGMENT'); var selections = this._transformSelections(fragment.selectionSet, typeCondition, fragment.typeCondition); return { kind: 'InlineFragment', directives: directives, loc: buildLocation(fragment.loc), metadata: null, selections: selections, typeCondition: typeCondition }; }; _proto2._transformFragmentSpread = function _transformFragmentSpread(fragmentSpread, parentType, parentTypeAST) { var _this5 = this; var fragmentName = getName(fragmentSpread); var _partitionArray = partitionArray(fragmentSpread.directives || [], function (directive) { var name = getName(directive); return name === ARGUMENTS || name === DEPRECATED_UNCHECKED_ARGUMENTS; }), argumentDirectives = _partitionArray[0], otherDirectives = _partitionArray[1]; if (argumentDirectives.length > 1) { throw createUserError("Directive @".concat(ARGUMENTS, " may be used at most once per a fragment spread."), null, argumentDirectives); } var fragmentDefinition = this._entries.get(fragmentName); if (fragmentDefinition == null) { throw createUserError("Unknown fragment '".concat(fragmentName, "'."), null, [fragmentSpread.name]); } var fragmentTypeNode = getFragmentType(fragmentDefinition.definition); var fragmentType = this._schema.assertCompositeType(this._schema.expectTypeFromAST(fragmentTypeNode)); var rawParentType = this._schema.assertCompositeType(this._schema.getRawType(parentType)); checkFragmentSpreadTypeCompatibility(this._schema, fragmentType, rawParentType, fragmentSpread.name.value, fragmentSpread, parentTypeAST); var fragmentArgumentDefinitions = fragmentDefinition.variableDefinitions; var argumentsDirective = argumentDirectives[0]; var args; if (argumentsDirective != null) { var isDeprecatedUncheckedArguments = getName(argumentsDirective) === DEPRECATED_UNCHECKED_ARGUMENTS; var hasInvalidArgument = false; args = (argumentsDirective.arguments || []).map(function (arg) { var _ref2; var argName = getName(arg); var argValue = arg.value; var argumentDefinition = fragmentArgumentDefinitions.get(argName); var argumentType = (_ref2 = argumentDefinition === null || argumentDefinition === void 0 ? void 0 : argumentDefinition.type) !== null && _ref2 !== void 0 ? _ref2 : null; if (argValue.kind === 'Variable') { if (argumentDefinition == null && !isDeprecatedUncheckedArguments) { throw createUserError("Variable @".concat(ARGUMENTS, " values are only supported when the ") + "argument is defined with @".concat(ARGUMENT_DEFINITIONS, ". Check ") + "the definition of fragment '".concat(fragmentName, "'."), null, [arg.value, fragmentDefinition.definition]); } hasInvalidArgument = hasInvalidArgument || argumentDefinition == null; // TODO: check the type of the variable and use the type return { kind: 'Argument', loc: buildLocation(arg.loc), name: argName, value: _this5._transformVariable(argValue, null), type: null }; } else { if (argumentType == null) { throw createUserError("Literal @".concat(ARGUMENTS, " values are only supported when the ") + "argument is defined with @".concat(ARGUMENT_DEFINITIONS, ". Check ") + "the definition of fragment '".concat(fragmentName, "'."), null, [arg.value, fragmentDefinition.definition]); } var value = _this5._transformValue(argValue, argumentType); return { kind: 'Argument', loc: buildLocation(arg.loc), name: argName, value: value, type: argumentType }; } }); if (isDeprecatedUncheckedArguments && !hasInvalidArgument) { throw createUserError("Invalid use of @".concat(DEPRECATED_UNCHECKED_ARGUMENTS, ": all arguments ") + "are defined, use @".concat(ARGUMENTS, " instead."), null, [argumentsDirective]); } } var directives = this._transformDirectives(otherDirectives, 'FRAGMENT_SPREAD'); return { kind: 'FragmentSpread', args: args || [], metadata: null, loc: buildLocation(fragmentSpread.loc), name: fragmentName, directives: directives }; }; _proto2._transformField = function _transformField(field, parentType) { var _ref3, _field$alias; var schema = this._schema; var name = getName(field); var fieldDef = this._getFieldDefinition(schema, parentType, name, field); if (fieldDef == null) { throw createUserError("Unknown field '".concat(name, "' on type '").concat(schema.getTypeString(parentType), "'."), null, [field]); } var alias = (_ref3 = (_field$alias = field.alias) === null || _field$alias === void 0 ? void 0 : _field$alias.value) !== null && _ref3 !== void 0 ? _ref3 : name; var args = this._transformArguments(field.arguments || [], schema.getFieldArgs(fieldDef), fieldDef); var _partitionArray2 = partitionArray(field.directives || [], function (directive) { return getName(directive) !== CLIENT_FIELD; }), otherDirectives = _partitionArray2[0], clientFieldDirectives = _partitionArray2[1]; var directives = this._transformDirectives(otherDirectives, 'FIELD'); var type = schema.getFieldType(fieldDef); var handles = this._transformHandle(name, args, clientFieldDirectives); if (schema.isLeafType(schema.getRawType(type))) { if (field.selectionSet && field.selectionSet.selections && field.selectionSet.selections.length) { throw createUserError("Expected no selections for scalar field '".concat(name, "'."), null, [field]); } return { kind: 'ScalarField', alias: alias, args: args, directives: directives, handles: handles, loc: buildLocation(field.loc), metadata: null, name: name, type: schema.assertScalarFieldType(type) }; } else { var selections = field.selectionSet ? this._transformSelections(field.selectionSet, type) : null; if (selections == null || selections.length === 0) { throw createUserError("Expected at least one selection for non-scalar field '".concat(name, "' on type '").concat(schema.getTypeString(type), "'."), null, [field]); } return { kind: 'LinkedField', alias: alias, args: args, connection: false, directives: directives, handles: handles, loc: buildLocation(field.loc), metadata: null, name: name, selections: selections, type: schema.assertLinkedFieldType(type) }; } }; _proto2._transformHandle = function _transformHandle(fieldName, fieldArgs, clientFieldDirectives) { var handles = null; clientFieldDirectives.forEach(function (clientFieldDirective) { var handleArgument = (clientFieldDirective.arguments || []).find(function (arg) { return getName(arg) === CLIENT_FIELD_HANDLE; }); if (handleArgument) { var name = null; var key = DEFAULT_HANDLE_KEY; var filters = null; var maybeHandle = transformLiteralValue(handleArgument.value, handleArgument); if (typeof maybeHandle !== 'string') { throw createUserError("Expected a string literal argument for the @".concat(CLIENT_FIELD, " directive."), null, [handleArgument.value]); } name = maybeHandle; var keyArgument = (clientFieldDirective.arguments || []).find(function (arg) { return getName(arg) === CLIENT_FIELD_KEY; }); if (keyArgument) { var maybeKey = transformLiteralValue(keyArgument.value, keyArgument); if (typeof maybeKey !== 'string') { throw createUserError("Expected a string literal argument for the @".concat(CLIENT_FIELD, " directive."), null, [keyArgument.value]); } key = maybeKey; } var filtersArgument = (clientFieldDirective.arguments || []).find(function (arg) { return getName(arg) === CLIENT_FIELD_FILTERS; }); if (filtersArgument) { var maybeFilters = transformLiteralValue(filtersArgument.value, filtersArgument); if (!(Array.isArray(maybeFilters) && maybeFilters.every(function (filter) { return typeof filter === 'string' && fieldArgs.some(function (fieldArg) { return fieldArg.name === filter; }); }))) { throw createUserError("Expected an array of argument names on field '".concat(fieldName, "'."), null, [filtersArgument.value]); } // $FlowFixMe filters = maybeFilters; } var dynamicKeyArgument = (clientFieldDirective.arguments || []).find(function (arg) { return getName(arg) === 'dynamicKey_UNSTABLE'; }); if (dynamicKeyArgument != null) { throw createUserError('Dynamic keys are only supported with @connection.', null, [dynamicKeyArgument.value]); } handles = handles || []; handles.push({ name: name, key: key, filters: filters, dynamicKey: null }); } }); return handles; }; _proto2._transformDirectives = function _transformDirectives(directives, location) { var _this6 = this; this._validateDirectivesLocation(directives, location); return directives.map(function (directive) { var name = getName(directive); var directiveDef = _this6._schema.getDirective(name); if (directiveDef == null) { throw createUserError("Unknown directive '".concat(name, "'."), null, [directive]); } var args = _this6._transformArguments(directive.arguments || [], directiveDef.args.map(function (item) { return { name: item.name, type: item.type, defaultValue: item.defaultValue }; }), null, name); return { kind: 'Directive', loc: buildLocation(directive.loc), name: name, args: args }; }); }; _proto2._transformArguments = function _transformArguments(args, argumentDefinitions, field, directiveName) { var _this7 = this; return args.map(function (arg) { var argName = getName(arg); var argDef = argumentDefinitions.find(function (def) { return def.name === argName; }); if (argDef == null) { var message = "Unknown argument '".concat(argName, "'") + (field ? " on field '".concat(_this7._schema.getFieldName(field), "'") + " of type '".concat(_this7._schema.getTypeString(_this7._schema.getFieldParentType(field)), "'.") : directiveName != null ? " on directive '@".concat(directiveName, "'.") : '.'); throw createUserError(message, null, [arg]); } var value = _this7._transformValue(arg.value, argDef.type); return { kind: 'Argument', loc: buildLocation(arg.loc), name: argName, value: value, type: argDef.type }; }); }; _proto2._splitConditions = function _splitConditions(mixedDirectives) { var _partitionArray3 = partitionArray(mixedDirectives, function (directive) { return directive.name === INCLUDE || directive.name === SKIP; }), conditionDirectives = _partitionArray3[0], otherDirectives = _partitionArray3[1]; var conditions = conditionDirectives.map(function (directive) { var passingValue = directive.name === INCLUDE; var arg = directive.args[0]; if (arg == null || arg.name !== IF) { throw createUserError("Expected an 'if' argument to @".concat(directive.name, "."), [directive.loc]); } if (!(arg.value.kind === 'Variable' || arg.value.kind === 'Literal')) { throw createUserError("Expected the 'if' argument to @".concat(directive.name, " to be a variable or literal."), [directive.loc]); } return { kind: 'Condition', condition: arg.value, loc: directive.loc, passingValue: passingValue, selections: [] }; }); var sortedConditions = conditions.sort(function (a, b) { if (a.condition.kind === 'Variable' && b.condition.kind === 'Variable') { return a.condition.variableName < b.condition.variableName ? -1 : a.condition.variableName > b.condition.variableName ? 1 : 0; } else { // sort literals earlier, variables later return a.condition.kind === 'Variable' ? 1 : b.condition.kind === 'Variable' ? -1 : 0; } }); return [sortedConditions, otherDirectives]; }; _proto2._transformVariable = function _transformVariable(ast, usedAsType) { var variableName = getName(ast); this._recordAndVerifyVariableReference(ast, variableName, usedAsType); return { kind: 'Variable', loc: buildLocation(ast.loc), variableName: variableName, type: usedAsType }; }; _proto2._transformValue = function _transformValue(ast, type) { var _this8 = this; return transformValue(this._schema, ast, type, function (variableAst, variableType) { return _this8._transformVariable(variableAst, variableType); }); }; return GraphQLDefinitionParser; }(); /** * Transforms and validates argument values according to the expected * type. */ function transformValue(schema, ast, type, transformVariable) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { nonStrictEnums: false }; if (ast.kind === 'Variable') { // Special case variables since there is no value to parse return transformVariable(ast, type); } else if (ast.kind === 'NullValue') { // Special case null literals since there is no value to parse if (schema.isNonNull(type)) { throw createUserError("Expected a value matching type '".concat(String(type), "'."), null, [ast]); } return { kind: 'Literal', loc: buildLocation(ast.loc), value: null }; } else { return transformNonNullLiteral(schema, ast, type, transformVariable, options); } } /** * Transforms and validates non-null literal (non-variable) values * according to the expected type. */ function transformNonNullLiteral(schema, ast, type, transformVariable, options) { // Transform the value based on the type without a non-null wrapper. // Note that error messages should still use the original `type` // since that accurately describes to the user what the expected // type is (using nullableType would suggest that `null` is legal // even when it may not be, for example). var nullableType = schema.getNullableType(type); if (schema.isList(nullableType)) { if (ast.kind !== 'ListValue') { // Parse singular (non-list) values flowing into a list type // as scalars, ie without wrapping them in an array. if (!schema.isInputType(schema.getListItemType(nullableType))) { throw createUserError("Expected type ".concat(schema.getTypeString(nullableType), " to be an input type."), null, [ast]); } return transformValue(schema, ast, schema.assertInputType(schema.getListItemType(nullableType)), transformVariable, options); } var itemType = schema.assertInputType(schema.getListItemType(nullableType)); var literalList = []; ast.values.forEach(function (item) { var itemValue = transformValue(schema, item, itemType, transformVariable, options); if (itemValue.kind === 'Literal') { literalList.push(itemValue.value); } else if (itemValue.kind === 'Variable') { throw createUserError('Complex argument values (Lists or InputObjects with nested variables) are not supported.', null, [item]); } }); return { kind: 'Literal', loc: buildLocation(ast.loc), value: literalList }; } else if (schema.isInputObject(nullableType)) { if (ast.kind !== 'ObjectValue') { throw createUserError("Expected a value matching type '".concat(schema.getTypeString(type), "'."), null, [ast]); } var literalObject = {}; var inputType = schema.assertInputObjectType(nullableType); ast.fields.forEach(function (field) { var fieldName = getName(field); var fieldID = schema.getFieldByName(inputType, fieldName); if (!fieldID) { throw createUserError("Unknown field '".concat(fieldName, "' on type '").concat(schema.getTypeString(inputType), "'."), null, [field]); } var fieldConfig = schema.getFieldConfig(fieldID); var fieldType = schema.assertInputType(fieldConfig.type); var fieldValue = transformValue(schema, field.value, fieldType, transformVariable, options); if (fieldValue.kind === 'Literal') { literalObject[field.name.value] = fieldValue.value; } else if (fieldValue.kind === 'Variable') { throw createUserError('Complex argument values (Lists or InputObjects with nested variables) are not supported.', null, [field.value]); } }); return { kind: 'Literal', loc: buildLocation(ast.loc), value: literalObject }; } else if (schema.isId(nullableType)) { // GraphQLID's parseLiteral() always returns the string value. However // the int/string distinction may be important at runtime, so this // transform parses int/string literals into the corresponding JS types. if (ast.kind === 'IntValue') { return { kind: 'Literal', loc: buildLocation(ast.loc), value: parseInt(ast.value, 10) }; } else if (ast.kind === 'StringValue') { return { kind: 'Literal', loc: buildLocation(ast.loc), value: ast.value }; } else { throw createUserError("Invalid value, expected a value matching type '".concat(schema.getTypeString(type), "'."), null, [ast]); } } else if (schema.isEnum(nullableType)) { var enumType = schema.assertEnumType(nullableType); var value = schema.parseLiteral(enumType, ast); if (value == null) { if (options.nonStrictEnums) { if (ast.kind === 'StringValue' || ast.kind === 'EnumValue') { var _schema$parseValue; var alternateValue = (_schema$parseValue = schema.parseValue(enumType, ast.value.toUpperCase())) !== null && _schema$parseValue !== void 0 ? _schema$parseValue : schema.parseValue(enumType, ast.value.toLowerCase()); if (alternateValue != null) { // Use the original raw value return { kind: 'Literal', loc: buildLocation(ast.loc), value: ast.value }; } } } var suggestions = schema.getEnumValues(enumType); // parseLiteral() should return a non-null JavaScript value // if the ast value is valid for the type. throw createUserError("Expected a value matching type '".concat(schema.getTypeString(type), "'. Possible values: ").concat(orList(suggestions), "?'"), null, [ast]); } return { kind: 'Literal', loc: buildLocation(ast.loc), value: value }; } else if (schema.isScalar(nullableType)) { var _value = schema.parseLiteral(schema.assertScalarType(nullableType), ast); if (_value == null) { // parseLiteral() should return a non-null JavaScript value // if the ast value is valid for the type. throw createUserError("Expected a value matching type '".concat(schema.getTypeString(type), "'."), null, [ast]); } return { kind: 'Literal', loc: buildLocation(ast.loc), value: _value }; } else { throw createCompilerError("Unsupported type '".concat(schema.getTypeString(type), "' for input value, expected a GraphQLList, ") + 'GraphQLInputObjectType, GraphQLEnumType, or GraphQLScalarType.', null, [ast]); } } /** * @private */ function transformLiteralValue(ast, context) { switch (ast.kind) { case 'IntValue': return parseInt(ast.value, 10); case 'FloatValue': return parseFloat(ast.value); case 'StringValue': return ast.value; case 'BooleanValue': // Note: duplicated because Flow does not understand fall-through cases return ast.value; case 'EnumValue': // Note: duplicated because Flow does not understand fall-through cases return ast.value; case 'ListValue': return ast.values.map(function (item) { return transformLiteralValue(item, context); }); case 'NullValue': return null; case 'ObjectValue': { var objectValue = {}; ast.fields.forEach(function (field) { var fieldName = getName(field); var value = transformLiteralValue(field.value, context); objectValue[fieldName] = value; }); return objectValue; } case 'Variable': throw createUserError('Unexpected variable where a literal (static) value is required.', null, [ast, context]); default: ast.kind; throw createCompilerError("Unknown ast kind '".concat(ast.kind, "'."), [ast]); } } /** * @private */ function buildArgumentDefinitions(variables) { return Array.from(variables.values(), function (_ref6) { var ast = _ref6.ast, name = _ref6.name, defaultValue = _ref6.defaultValue, type = _ref6.type; return { kind: 'LocalArgumentDefinition', loc: buildLocation(ast.loc), name: name, type: type, defaultValue: defaultValue }; }); } /** * @private */ function buildLocation(loc) { if (loc == null) { return { kind: 'Unknown' }; } return { kind: 'Source', start: loc.start, end: loc.end, source: loc.source }; } /** * @private */ function applyConditions(conditions, selections) { var nextSelections = selections; conditions.forEach(function (condition) { nextSelections = [(0, _objectSpread2["default"])({}, condition, { selections: nextSelections })]; }); return nextSelections; } /** * @private */ function getName(ast) { var _ast$name; var name = (_ast$name = ast.name) === null || _ast$name === void 0 ? void 0 : _ast$name.value; if (typeof name !== 'string') { throw createCompilerError("Expected ast node to have a 'name'.", null, [ast]); } return name; } function getTypeName(ast) { return ast ? print(ast) : 'Undefined Type Name'; } /** * @private */ function getFragmentType(ast) { if (ast.kind === 'FragmentDefinition') { return ast.typeCondition; } throw createCompilerError('Expected ast node to be a FragmentDefinition node.', null, [ast]); } function checkFragmentSpreadTypeCompatibility(schema, fragmentType, parentType, fragmentName, fragmentTypeAST, parentTypeAST) { if (!schema.doTypesOverlap(fragmentType, schema.assertCompositeType(parentType))) { var nodes = []; if (parentTypeAST) { nodes.push(parentTypeAST); } if (fragmentTypeAST) { nodes.push(fragmentTypeAST); } var possibleConcreteTypes = schema.isAbstractType(parentType) ? Array.from(schema.getPossibleTypes(schema.assertAbstractType(parentType))) : []; var suggestedTypesMessage = ''; if (possibleConcreteTypes.length !== 0) { suggestedTypesMessage = " Possible concrete types include ".concat(possibleConcreteTypes.slice(0, 3).map(function (type) { return "'".concat(schema.getTypeString(type), "'"); }).join(', '), ", etc."); } throw createUserError((fragmentName != null ? "Fragment '".concat(fragmentName, "' cannot be spread here as objects of ") : 'Fragment cannot be spread here as objects of ') + "type '".concat(schema.getTypeString(parentType), "' ") + "can never be of type '".concat(schema.getTypeString(fragmentType), "'.") + suggestedTypesMessage, null, nodes); } } module.exports = { parse: parse, transform: transform }; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /** * Partitions an array given a predicate. All elements satisfying the predicate * are part of the first returned array, and all elements that don't are in the * second. */ function partitionArray(array, predicate) { var first = []; var second = []; for (var i = 0; i < array.length; i++) { var item = array[i]; if (predicate(item)) { first.push(item); } else { second.push(item); } } return [first, second]; } module.exports = partitionArray; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ module.exports = { DEFAULT_HANDLE_KEY: '' }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError; var _require2 = __webpack_require__(7), SchemaMetaFieldDef = _require2.SchemaMetaFieldDef, TypeMetaFieldDef = _require2.TypeMetaFieldDef; /** * Find the definition of a field of the specified type using strict * resolution rules per the GraphQL spec. */ function getFieldDefinitionStrict(schema, parentType, fieldName) { var type = schema.getRawType(parentType); var queryType = schema.getQueryType(); var isQueryType = queryType != null && schema.areEqualTypes(type, queryType); var hasTypeName = schema.isAbstractType(type) || schema.isObject(type); var schemaFieldDef; if (isQueryType && fieldName === SchemaMetaFieldDef.name) { schemaFieldDef = queryType != null ? schema.getFieldByName(queryType, '__schema') : null; } else if (isQueryType && fieldName === TypeMetaFieldDef.name) { schemaFieldDef = queryType != null ? schema.getFieldByName(queryType, '__type') : null; } else if (hasTypeName && fieldName === '__typename') { schemaFieldDef = schema.getFieldByName(schema.assertCompositeType(type), '__typename'); } else if (hasTypeName && fieldName === '__id') { schemaFieldDef = schema.getFieldByName(schema.assertCompositeType(type), '__id'); } else if (schema.isInterface(type) || schema.isObject(type)) { var compositeType = schema.assertCompositeType(type); if (schema.hasField(compositeType, fieldName)) { schemaFieldDef = schema.getFieldByName(compositeType, fieldName); } else { return null; } } return schemaFieldDef; } /** * Find the definition of a field of the specified type, first trying * the standard spec-compliant resolution process and falling back * to legacy mode that supports fat interfaces. */ function getFieldDefinitionLegacy(schema, parentType, fieldName, fieldAST) { var _schemaFieldDef; var schemaFieldDef = getFieldDefinitionStrict(schema, parentType, fieldName); if (!schemaFieldDef) { schemaFieldDef = getFieldDefinitionLegacyImpl(schema, parentType, fieldName, fieldAST); } return (_schemaFieldDef = schemaFieldDef) !== null && _schemaFieldDef !== void 0 ? _schemaFieldDef : null; } /** * @private */ function getFieldDefinitionLegacyImpl(schema, type, fieldName, fieldAST) { var rawType = schema.getRawType(type); if (schema.isAbstractType(rawType) && fieldAST && fieldAST.directives && fieldAST.directives.some(function (directive) { return getName(directive) === 'fixme_fat_interface'; })) { var possibleTypes = schema.getPossibleTypes(schema.assertAbstractType(rawType)); var schemaFieldDef; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { var _loop = function _loop() { var possibleType = _step.value; var possibleField = schema.getFieldByName(possibleType, fieldName); if (possibleField) { // Fat interface fields can have differing arguments. Try to return // a field with matching arguments, but still return a field if the // arguments do not match. schemaFieldDef = possibleField; if (fieldAST && fieldAST.arguments) { var argumentsAllExist = fieldAST.arguments.every(function (argument) { return schema.getFieldArgByName(possibleField, getName(argument)) != null; }); if (argumentsAllExist) { return "break"; } } } }; for (var _iterator = possibleTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _ret = _loop(); if (_ret === "break") break; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return schemaFieldDef; } } /** * @private */ function getName(ast) { var name = ast.name ? ast.name.value : null; if (typeof name !== 'string') { throw createCompilerError("Expected ast node to have a 'name'.", null, [ast]); } return name; } module.exports = { getFieldDefinitionLegacy: getFieldDefinitionLegacy, getFieldDefinitionStrict: getFieldDefinitionStrict }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var invariant = __webpack_require__(4); var _require = __webpack_require__(29), DEFAULT_HANDLE_KEY = _require.DEFAULT_HANDLE_KEY; var INDENT = ' '; /** * Converts a GraphQLIR node into a GraphQL string. Custom Relay * extensions (directives) are not supported; to print fragments with * variables or fragment spreads with arguments, transform the node * prior to printing. */ function print(schema, node) { switch (node.kind) { case 'Fragment': return "fragment ".concat(node.name, " on ").concat(schema.getTypeString(node.type)) + printFragmentArgumentDefinitions(schema, node.argumentDefinitions) + printDirectives(schema, node.directives) + printSelections(schema, node, '', {}) + '\n'; case 'Root': return "".concat(node.operation, " ").concat(node.name) + printArgumentDefinitions(schema, node.argumentDefinitions) + printDirectives(schema, node.directives) + printSelections(schema, node, '', {}) + '\n'; case 'SplitOperation': return "SplitOperation ".concat(node.name, " on ").concat(schema.getTypeString(node.type)) + printSelections(schema, node, '', {}) + '\n'; default: node; true ? true ? invariant(false, 'GraphQLIRPrinter: Unsupported IR node `%s`.', node.kind) : undefined : undefined; } } function printSelections(schema, node, indent, options) { var selections = node.selections; if (selections == null) { return ''; } var printed = selections.map(function (selection) { return printSelection(schema, selection, indent, options); }); return printed.length ? " {\n".concat(indent + INDENT).concat(printed.join('\n' + indent + INDENT), "\n").concat(indent).concat((options === null || options === void 0 ? void 0 : options.isClientExtension) === true ? '# ' : '', "}") : ''; } /** * Prints a field without subselections. */ function printField(schema, field, options) { var _ref; var parentDirectives = (_ref = options === null || options === void 0 ? void 0 : options.parentDirectives) !== null && _ref !== void 0 ? _ref : ''; var isClientExtension = (options === null || options === void 0 ? void 0 : options.isClientExtension) === true; return (isClientExtension ? '# ' : '') + (field.alias === field.name ? field.name : field.alias + ': ' + field.name) + printArguments(schema, field.args) + parentDirectives + printDirectives(schema, field.directives) + printHandles(schema, field); } function printSelection(schema, selection, indent, options) { var _ref2; var str; var parentDirectives = (_ref2 = options === null || options === void 0 ? void 0 : options.parentDirectives) !== null && _ref2 !== void 0 ? _ref2 : ''; var isClientExtension = (options === null || options === void 0 ? void 0 : options.isClientExtension) === true; if (selection.kind === 'LinkedField' || selection.kind === 'ConnectionField') { str = printField(schema, selection, { parentDirectives: parentDirectives, isClientExtension: isClientExtension }); str += printSelections(schema, selection, indent + INDENT, { isClientExtension: isClientExtension }); } else if (selection.kind === 'ModuleImport' || selection.kind === 'Connection') { str = selection.selections.map(function (matchSelection) { return printSelection(schema, matchSelection, indent, { parentDirectives: parentDirectives, isClientExtension: isClientExtension }); }).join('\n' + indent + INDENT); } else if (selection.kind === 'ScalarField') { str = printField(schema, selection, { parentDirectives: parentDirectives, isClientExtension: isClientExtension }); } else if (selection.kind === 'InlineFragment') { str = ''; if (isClientExtension) { str += '# '; } str += '... on ' + schema.getTypeString(selection.typeCondition); str += parentDirectives; str += printDirectives(schema, selection.directives); str += printSelections(schema, selection, indent + INDENT, { isClientExtension: isClientExtension }); } else if (selection.kind === 'FragmentSpread') { str = ''; if (isClientExtension) { str += '# '; } str += '...' + selection.name; str += parentDirectives; str += printFragmentArguments(schema, selection.args); str += printDirectives(schema, selection.directives); } else if (selection.kind === 'InlineDataFragmentSpread') { str = "# ".concat(selection.name, " @inline") + "\n".concat(indent).concat(INDENT, "...") + parentDirectives + printSelections(schema, selection, indent + INDENT, {}); } else if (selection.kind === 'Condition') { var value = printValue(schema, selection.condition, null); // For Flow !(value != null) ? true ? invariant(false, 'GraphQLIRPrinter: Expected a variable for condition, got a literal `null`.') : undefined : void 0; var condStr = selection.passingValue ? ' @include' : ' @skip'; condStr += '(if: ' + value + ')'; condStr += parentDirectives; // For multi-selection conditions, pushes the condition down to each var subSelections = selection.selections.map(function (sel) { return printSelection(schema, sel, indent, { parentDirectives: condStr, isClientExtension: isClientExtension }); }); str = subSelections.join('\n' + INDENT); } else if (selection.kind === 'Stream') { var streamStr = " @stream(label: \"".concat(selection.label, "\""); if (selection["if"] !== null) { var _printValue; streamStr += ", if: ".concat((_printValue = printValue(schema, selection["if"], null)) !== null && _printValue !== void 0 ? _printValue : ''); } if (selection.initialCount !== null) { var _printValue2; streamStr += ", initial_count: ".concat((_printValue2 = printValue(schema, selection.initialCount, null)) !== null && _printValue2 !== void 0 ? _printValue2 : ''); } streamStr += ')'; streamStr += parentDirectives; var _subSelections = selection.selections.map(function (sel) { return printSelection(schema, sel, indent, { parentDirectives: streamStr, isClientExtension: isClientExtension }); }); str = _subSelections.join('\n' + INDENT); } else if (selection.kind === 'Defer') { var deferStr = " @defer(label: \"".concat(selection.label, "\""); if (selection["if"] !== null) { var _printValue3; deferStr += ", if: ".concat((_printValue3 = printValue(schema, selection["if"], null)) !== null && _printValue3 !== void 0 ? _printValue3 : ''); } deferStr += ')'; deferStr += parentDirectives; if (selection.selections.every(function (subSelection) { return subSelection.kind === 'InlineFragment' || subSelection.kind === 'FragmentSpread'; })) { var _subSelections2 = selection.selections.map(function (sel) { return printSelection(schema, sel, indent, { parentDirectives: deferStr, isClientExtension: isClientExtension }); }); str = _subSelections2.join('\n' + INDENT); } else { if (selection.metadata != null && selection.metadata.fragmentTypeCondition != null) { str = "... on ".concat(schema.getTypeString(selection.metadata.fragmentTypeCondition)) + deferStr; } else { str = '...' + deferStr; } str += printSelections(schema, selection, indent + INDENT, { isClientExtension: isClientExtension }); } } else if (selection.kind === 'ClientExtension') { !(isClientExtension === false) ? true ? invariant(false, 'GraphQLIRPrinter: Did not expect to encounter a ClientExtension node ' + 'as a descendant of another ClientExtension node.') : undefined : void 0; str = '# Client-only selections:\n' + indent + INDENT + selection.selections.map(function (sel) { return printSelection(schema, sel, indent, { parentDirectives: parentDirectives, isClientExtension: true }); }).join('\n' + indent + INDENT); } else { selection; true ? true ? invariant(false, 'GraphQLIRPrinter: Unknown selection kind `%s`.', selection.kind) : undefined : undefined; } return str; } function printArgumentDefinitions(schema, argumentDefinitions) { var printed = argumentDefinitions.map(function (def) { var str = "$".concat(def.name, ": ").concat(schema.getTypeString(def.type)); if (def.defaultValue != null) { str += ' = ' + printLiteral(schema, def.defaultValue, def.type); } return str; }); return printed.length ? "(\n".concat(INDENT).concat(printed.join('\n' + INDENT), "\n)") : ''; } function printFragmentArgumentDefinitions(schema, argumentDefinitions) { var printed; argumentDefinitions.forEach(function (def) { if (def.kind !== 'LocalArgumentDefinition') { return; } printed = printed || []; var str = "".concat(def.name, ": {type: \"").concat(schema.getTypeString(def.type), "\""); if (def.defaultValue != null) { str += ", defaultValue: ".concat(printLiteral(schema, def.defaultValue, def.type)); } str += '}'; printed.push(str); }); return printed && printed.length ? " @argumentDefinitions(\n".concat(INDENT).concat(printed.join('\n' + INDENT), "\n)") : ''; } function printHandles(schema, field) { if (!field.handles) { return ''; } var printed = field.handles.map(function (handle) { // For backward compatibility and also because this module is shared by ComponentScript. var key = handle.key === DEFAULT_HANDLE_KEY ? '' : ", key: \"".concat(handle.key, "\""); var filters = handle.filters == null ? '' : ", filters: ".concat(JSON.stringify(Array.from(handle.filters).sort())); return "@__clientField(handle: \"".concat(handle.name, "\"").concat(key).concat(filters, ")"); }); return printed.length ? ' ' + printed.join(' ') : ''; } function printDirectives(schema, directives) { var printed = directives.map(function (directive) { return '@' + directive.name + printArguments(schema, directive.args); }); return printed.length ? ' ' + printed.join(' ') : ''; } function printFragmentArguments(schema, args) { var printedArgs = printArguments(schema, args); if (!printedArgs.length) { return ''; } return " @arguments".concat(printedArgs); } function printArguments(schema, args) { var printed = []; args.forEach(function (arg) { var printedValue = printValue(schema, arg.value, arg.type); if (printedValue != null) { printed.push(arg.name + ': ' + printedValue); } }); return printed.length ? '(' + printed.join(', ') + ')' : ''; } function printValue(schema, value, type) { if (type != null && schema.isNonNull(type)) { type = schema.getNullableType(type); } if (value.kind === 'Variable') { return '$' + value.variableName; } else if (value.value != null) { return printLiteral(schema, value.value, type); } else { return null; } } function printLiteral(schema, value, type) { if (value == null) { var _JSON$stringify; return (_JSON$stringify = JSON.stringify(value)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : 'null'; } if (type != null && schema.isNonNull(type)) { type = schema.getNullableType(type); } if (type && schema.isEnum(type)) { var _JSON$stringify2; var result = schema.serialize(schema.assertEnumType(type), value); if (result == null && typeof value === 'string') { // For backwards compatibility, print invalid input values as-is. This // can occur with literals defined as an @argumentDefinitions // defaultValue. result = value; } !(typeof result === 'string') ? true ? invariant(false, 'GraphQLIRPrinter: Expected value of type %s to be a valid enum value, got `%s`.', schema.getTypeString(type), (_JSON$stringify2 = JSON.stringify(value)) !== null && _JSON$stringify2 !== void 0 ? _JSON$stringify2 : 'null') : undefined : void 0; return result; } else if (type && (schema.isId(type) || schema.isInt(type))) { var _JSON$stringify3; return (_JSON$stringify3 = JSON.stringify(value)) !== null && _JSON$stringify3 !== void 0 ? _JSON$stringify3 : ''; } else if (type && schema.isScalar(type)) { var _JSON$stringify4; var _result = schema.serialize(schema.assertScalarType(type), value); return (_JSON$stringify4 = JSON.stringify(_result)) !== null && _JSON$stringify4 !== void 0 ? _JSON$stringify4 : ''; } else if (Array.isArray(value)) { !(type && schema.isList(type)) ? true ? invariant(false, 'GraphQLIRPrinter: Need a type in order to print arrays.') : undefined : void 0; var itemType = schema.getListItemType(type); return '[' + value.map(function (item) { return printLiteral(schema, item, itemType); }).join(', ') + ']'; } else if (type && schema.isList(type) && value != null) { // Not an array, but still a list. Treat as list-of-one as per spec 3.1.7: // http://facebook.github.io/graphql/October2016/#sec-Lists return printLiteral(schema, value, schema.getListItemType(type)); } else if (typeof value === 'object' && value != null) { var fields = []; !(type && schema.isInputObject(type)) ? true ? invariant(false, 'GraphQLIRPrinter: Need an InputObject type to print objects.') : undefined : void 0; var inputType = schema.assertInputObjectType(type); for (var key in value) { if (value.hasOwnProperty(key)) { var fieldConfig = schema.getFieldConfig(schema.expectField(inputType, key)); fields.push(key + ': ' + printLiteral(schema, value[key], fieldConfig.type)); } } return '{' + fields.join(', ') + '}'; } else { var _JSON$stringify5; return (_JSON$stringify5 = JSON.stringify(value)) !== null && _JSON$stringify5 !== void 0 ? _JSON$stringify5 : 'null'; } } module.exports = { print: print, printField: printField, printArguments: printArguments, printDirectives: printDirectives }; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /** * Marks a string of code as code to be replaced later. */ function moduleDependency(code) { return "@@MODULE_START@@".concat(code, "@@MODULE_END@@"); } /** * After JSON.stringify'ing some code that contained parts marked with `mark()`, * this post-processes the JSON to convert the marked code strings to raw code. * * Example: * CodeMarker.postProcess( * JSON.stringify({code: CodeMarker.mark('alert(1)')}) * ) */ function postProcess(json, printModule) { return json.replace(/"@@MODULE_START@@(.*?)@@MODULE_END@@"/g, function (_, moduleName) { return printModule(moduleName); }); } /** * Transforms a value such that any transitive CodeMarker strings are replaced * with the value of the named module in the given module map. */ function transform(node, moduleMap) { if (node == null) { return node; } else if (Array.isArray(node)) { return node.map(function (item) { return transform(item, moduleMap); }); } else if (typeof node === 'object') { var next = {}; Object.keys(node).forEach(function (key) { next[key] = transform(node[key], moduleMap); }); return next; } else if (typeof node === 'string') { var match = /^@@MODULE_START@@(.*?)@@MODULE_END@@$/.exec(node); if (match != null) { var moduleName = match[1]; if (moduleMap.hasOwnProperty(moduleName)) { return moduleMap[moduleName]; } else { throw new Error("Could not find a value for CodeMarker value '".concat(moduleName, "', ") + 'make sure to supply one in the module mapping.'); } } else if (node.indexOf('@@MODULE_START') >= 0) { throw new Error("Found unprocessed CodeMarker value '".concat(node, "'.")); } return node; } else { // mixed return node; } } module.exports = { moduleDependency: moduleDependency, postProcess: postProcess, transform: transform }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /** * Based on implementations by Gary Court and Austin Appleby, 2011, MIT. * @preserve-header */ var BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * @param {string} key A UTF-16 or ASCII string * @return {string} a base62 murmur hash */ function murmurHash(str) { /* eslint-disable no-bitwise */ var length = str.length; var rem = length & 3; var len = length ^ rem; var h = 0; var i = 0; var k; while (i !== len) { var ch4 = str.charCodeAt(i + 3); k = str.charCodeAt(i) ^ str.charCodeAt(i + 1) << 8 ^ str.charCodeAt(i + 2) << 16 ^ (ch4 & 0xff) << 24 ^ (ch4 & 0xff00) >> 8; i += 4; k = k * 0x2d51 + (k & 0xffff) * 0xcc9e0000 >>> 0; k = k << 15 | k >>> 17; k = k * 0x3593 + (k & 0xffff) * 0x1b870000 >>> 0; h ^= k; h = h << 13 | h >>> 19; h = h * 5 + 0xe6546b64 >>> 0; } k = 0; switch (rem) { /* eslint-disable no-fallthrough */ case 3: k ^= str.charCodeAt(len + 2) << 16; case 2: k ^= str.charCodeAt(len + 1) << 8; case 1: k ^= str.charCodeAt(len); k = k * 0x2d51 + (k & 0xffff) * 0xcc9e0000 >>> 0; k = k << 15 | k >>> 17; k = k * 0x3593 + (k & 0xffff) * 0x1b870000 >>> 0; h ^= k; } h ^= length; h ^= h >>> 16; h = h * 0xca6b + (h & 0xffff) * 0x85eb0000 >>> 0; h ^= h >>> 13; h = h * 0xae35 + (h & 0xffff) * 0xc2b20000 >>> 0; h ^= h >>> 16; h >>>= 0; if (!h) { return '0'; } var s = ''; while (h) { var d = h % 62; s = BASE62[d] + s; h = (h - d) / 62; } return s; } module.exports = murmurHash; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(35), buildConnectionMetadata = _require2.buildConnectionMetadata; var _require3 = __webpack_require__(9), ConnectionInterface = _require3.ConnectionInterface; var SCHEMA_EXTENSION = "\n directive @connection_resolver(label: String!) on FIELD\n directive @stream_connection_resolver(\n label: String!\n initial_count: Int!\n if: Boolean = true\n ) on FIELD\n"; /** * This transform rewrites LinkedField nodes with @connection_resolver and * rewrites their edges/pageInfo selections to be wrapped in a Connection node. */ function connectionFieldTransform(context) { return IRTransformer.transform(context, { Fragment: visitFragmentOrRoot, LinkedField: visitLinkedField, Root: visitFragmentOrRoot, ScalarField: visitScalarField }, function (node) { return { documentName: node.name, labels: new Map(), path: [], connectionMetadata: [] }; }); } function visitFragmentOrRoot(node, state) { var transformedNode = this.traverse(node, state); var connectionMetadata = state.connectionMetadata; if (connectionMetadata.length) { return (0, _objectSpread2["default"])({}, transformedNode, { metadata: (0, _objectSpread2["default"])({}, transformedNode.metadata, { connection: connectionMetadata }) }); } return transformedNode; } function visitLinkedField(field, state) { var context = this.getContext(); var schema = context.getSchema(); var path = state.path.concat(field.alias); var transformed = this.traverse(field, (0, _objectSpread2["default"])({}, state, { path: path })); var connectionDirective = transformed.directives.find(function (directive) { return directive.name === 'connection_resolver' || directive.name === 'stream_connection_resolver'; }); if (connectionDirective == null) { return transformed; } if (schema.isList(schema.getNullableType(transformed.type))) { throw createUserError("@connection_resolver fields must return a single value, not a list, found '" + "".concat(schema.getTypeString(transformed.type), "'"), [transformed.loc]); } var labelArg = connectionDirective.args.find(function (_ref4) { var name = _ref4.name; return name === 'label'; }); var label = getLiteralStringArgument(connectionDirective, 'label'); if (typeof label !== 'string' || label !== state.documentName && label.indexOf(state.documentName + '$') !== 0) { var _ref; throw createUserError('Invalid usage of @connection_resolver, expected a static string ' + "'label'. Labels may be the document name ('".concat(state.documentName, "') ") + "or be prefixed with the document name ('".concat(state.documentName, "$')"), [(_ref = labelArg === null || labelArg === void 0 ? void 0 : labelArg.loc) !== null && _ref !== void 0 ? _ref : connectionDirective.loc]); } var previousDirective = state.labels.get(label); if (previousDirective != null) { var _ref2; var prevLabelArg = previousDirective.args.find(function (_ref5) { var name = _ref5.name; return name === 'label'; }); var previousLocation = (_ref2 = prevLabelArg === null || prevLabelArg === void 0 ? void 0 : prevLabelArg.loc) !== null && _ref2 !== void 0 ? _ref2 : previousDirective.loc; if (labelArg) { throw createUserError('Invalid use of @connection_resolver, the provided label is ' + "not unique. Specify a unique 'label' as a literal string.", [labelArg === null || labelArg === void 0 ? void 0 : labelArg.loc, previousLocation]); } else { throw createUserError('Invalid use of @connection_resolver, could not generate a ' + "default label that is unique. Specify a unique 'label' " + 'as a literal string.', [connectionDirective.loc, previousLocation]); } } state.labels.set(label, connectionDirective); var stream = null; if (connectionDirective.name === 'stream_connection_resolver') { var initialCountArg = connectionDirective.args.find(function (arg) { return arg.name === 'initial_count'; }); var ifArg = connectionDirective.args.find(function (arg) { return arg.name === 'if'; }); if (initialCountArg == null || initialCountArg.value.kind === 'Literal' && !Number.isInteger(initialCountArg.value.value)) { var _ref3; throw createUserError("Invalid use of @connection_resolver, 'initial_count' is required " + "and must be an integer or variable of type 'Int!''.", [(_ref3 = initialCountArg === null || initialCountArg === void 0 ? void 0 : initialCountArg.loc) !== null && _ref3 !== void 0 ? _ref3 : connectionDirective.loc]); } stream = { deferLabel: label, initialCount: initialCountArg.value, "if": ifArg != null ? ifArg.value : null, streamLabel: label }; } var _ConnectionInterface$ = ConnectionInterface.get(), EDGES = _ConnectionInterface$.EDGES, PAGE_INFO = _ConnectionInterface$.PAGE_INFO; var edgeField; var pageInfoField; var selections = []; transformed.selections.forEach(function (selection) { if (!(selection.kind === 'LinkedField' || selection.kind === 'ScalarField')) { throw createUserError('Invalid use of @connection_resolver, selections on the connection ' + 'must be linked or scalar fields.', [selection.loc]); } if (selection.kind === 'LinkedField') { if (selection.name === EDGES) { edgeField = selection; } else if (selection.name === PAGE_INFO) { pageInfoField = selection; } else { selections.push(selection); } } else { selections.push(selection); } }); if (edgeField == null || pageInfoField == null) { throw createUserError("Invalid use of @connection_resolver, fields '".concat(EDGES, "' and ") + "'".concat(PAGE_INFO, "' must be fetched."), [connectionDirective.loc]); } var connectionType = schema.getRawType(transformed.type); var edgesFieldDef = schema.isObject(connectionType) ? schema.getFieldByName(schema.assertObjectType(connectionType), 'edges') : null; var edgesType = edgesFieldDef != null ? schema.getRawType(schema.getFieldType(edgesFieldDef)) : null; var nodeFieldDef = edgesType != null && schema.isObject(edgesType) ? schema.getFieldByName(schema.assertObjectType(edgesType), 'node') : null; var nodeType = nodeFieldDef != null ? schema.getRawType(schema.getFieldType(nodeFieldDef)) : null; if (edgesType == null || nodeType == null || !(schema.isObject(nodeType) || schema.isInterface(nodeType) || schema.isUnion(nodeType))) { throw createUserError('Invalid usage of @connection_resolver, expected field to have shape ' + "'field { edges { node { ...} } }'.", [transformed.loc]); } edgeField = (0, _objectSpread2["default"])({}, edgeField, { selections: [].concat((0, _toConsumableArray2["default"])(edgeField.selections), [{ alias: '__id', args: [], directives: [], handles: null, kind: 'ScalarField', loc: edgeField.loc, metadata: null, name: '__id', type: schema.assertScalarFieldType(schema.getNonNullType(schema.expectIdType())) }, { alias: 'node', args: [], connection: false, directives: [], handles: null, kind: 'LinkedField', loc: edgeField.loc, metadata: null, name: 'node', selections: [{ alias: '__id', args: [], directives: [], handles: null, kind: 'ScalarField', loc: edgeField.loc, metadata: null, name: '__id', type: schema.assertScalarFieldType(schema.getNonNullType(schema.expectIdType())) }], type: schema.assertLinkedFieldType(nodeType) }]) }); selections.push({ args: transformed.args, kind: 'Connection', label: label, loc: transformed.loc, name: transformed.name, selections: [edgeField, pageInfoField], stream: stream, type: transformed.type }); var connectionMetadata = buildConnectionMetadata(transformed, path, stream != null); state.connectionMetadata.push(connectionMetadata); return { alias: transformed.alias, args: transformed.args, directives: transformed.directives.filter(function (directive) { return directive !== connectionDirective; }), kind: 'ConnectionField', loc: transformed.loc, metadata: null, name: transformed.name, selections: selections, type: transformed.type }; } function visitScalarField(field) { var connectionDirective = field.directives.find(function (directive) { return directive.name === 'connection_resolver'; }); if (connectionDirective != null) { throw createUserError('The @connection_resolver direction is not supported on scalar fields, ' + 'only fields returning an object/interface/union', [connectionDirective.loc]); } return field; } function getLiteralStringArgument(directive, argName) { var arg = directive.args.find(function (_ref6) { var name = _ref6.name; return name === argName; }); if (arg == null) { return null; } var value = arg.value.kind === 'Literal' ? arg.value.value : null; if (value == null || typeof value !== 'string') { throw createUserError("Expected the '".concat(argName, "' value to @").concat(directive.name, " to be a string literal if provided."), [arg.value.loc]); } return value; } module.exports = { SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: connectionFieldTransform }; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var RelayParser = __webpack_require__(27); var SchemaUtils = __webpack_require__(11); var getLiteralArgumentValues = __webpack_require__(16); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createUserError = _require.createUserError; var _require2 = __webpack_require__(7), parse = _require2.parse; var _require3 = __webpack_require__(9), ConnectionInterface = _require3.ConnectionInterface, RelayFeatureFlags = _require3.RelayFeatureFlags; var AFTER = 'after'; var BEFORE = 'before'; var FIRST = 'first'; var KEY = 'key'; var LAST = 'last'; var CONNECTION = 'connection'; var STREAM_CONNECTION = 'stream_connection'; var HANDLER = 'handler'; /** * @public * * Transforms fields with the `@connection` directive: * - Verifies that the field type is connection-like. * - Adds a `handle` property to the field, either the user-provided `handle` * argument or the default value "connection". * - Inserts a sub-fragment on the field to ensure that standard connection * fields are fetched (e.g. cursors, node ids, page info). */ function connectionTransform(context) { return IRTransformer.transform(context, { Fragment: visitFragmentOrRoot, LinkedField: visitLinkedField, Root: visitFragmentOrRoot }, function (node) { return { documentName: node.name, path: [], connectionMetadata: [] }; }); } var SCHEMA_EXTENSION = "\n directive @connection(\n key: String!\n filters: [String]\n handler: String\n dynamicKey_UNSTABLE: String\n ) on FIELD\n\n directive @stream_connection(\n key: String!\n filters: [String]\n handler: String\n label: String!\n initial_count: Int!\n if: Boolean = true\n dynamicKey_UNSTABLE: String\n ) on FIELD\n"; /** * @internal */ function visitFragmentOrRoot(node, options) { var transformedNode = this.traverse(node, options); var connectionMetadata = options.connectionMetadata; if (connectionMetadata.length) { return (0, _objectSpread2["default"])({}, transformedNode, { metadata: (0, _objectSpread2["default"])({}, transformedNode.metadata, { connection: connectionMetadata }) }); } return transformedNode; } /** * @internal */ function visitLinkedField(field, options) { var _connectionArguments$; var context = this.getContext(); var schema = context.getSchema(); var nullableType = schema.getNullableType(field.type); var isPlural = schema.isList(nullableType); var path = options.path.concat(isPlural ? null : field.alias || field.name); var transformedField = this.traverse(field, (0, _objectSpread2["default"])({}, options, { path: path })); var connectionDirective = field.directives.find(function (directive) { return directive.name === CONNECTION || directive.name === STREAM_CONNECTION; }); if (!connectionDirective) { return transformedField; } if (!schema.isObject(nullableType) && !schema.isInterface(nullableType)) { throw new createUserError("@".concat(connectionDirective.name, " used on invalid field '").concat(field.name, "'. ") + 'Expected the return type to be a non-plural interface or object, ' + "got '".concat(schema.getTypeString(field.type), "'."), [transformedField.loc]); } validateConnectionSelection(transformedField); validateConnectionType(schema, transformedField, schema.assertCompositeType(nullableType), connectionDirective); var connectionArguments = buildConnectionArguments(transformedField, connectionDirective); var connectionMetadata = buildConnectionMetadata(transformedField, path, connectionArguments.stream != null); options.connectionMetadata.push(connectionMetadata); var handle = { name: (_connectionArguments$ = connectionArguments.handler) !== null && _connectionArguments$ !== void 0 ? _connectionArguments$ : CONNECTION, key: connectionArguments.key, dynamicKey: connectionArguments.dynamicKey, filters: connectionArguments.filters }; var direction = connectionMetadata.direction; if (direction != null) { var selections = transformConnectionSelections(this.getContext(), transformedField, schema.assertCompositeType(nullableType), direction, connectionArguments, connectionDirective.loc, options.documentName); transformedField = (0, _objectSpread2["default"])({}, transformedField, { selections: selections }); } return (0, _objectSpread2["default"])({}, transformedField, { directives: transformedField.directives.filter(function (directive) { return directive !== connectionDirective; }), connection: true, handles: transformedField.handles ? [].concat((0, _toConsumableArray2["default"])(transformedField.handles), [handle]) : [handle] }); } function buildConnectionArguments(field, connectionDirective) { var _getLiteralArgumentVa = getLiteralArgumentValues(connectionDirective.args), handler = _getLiteralArgumentVa.handler, key = _getLiteralArgumentVa.key, label = _getLiteralArgumentVa.label, literalFilters = _getLiteralArgumentVa.filters; if (handler != null && typeof handler !== 'string') { var _ref, _handleArg$value; var handleArg = connectionDirective.args.find(function (arg) { return arg.name === 'key'; }); throw createUserError("Expected the ".concat(HANDLER, " argument to @").concat(connectionDirective.name, " to ") + "be a string literal for field ".concat(field.name, "."), [(_ref = handleArg === null || handleArg === void 0 ? void 0 : (_handleArg$value = handleArg.value) === null || _handleArg$value === void 0 ? void 0 : _handleArg$value.loc) !== null && _ref !== void 0 ? _ref : connectionDirective.loc]); } if (typeof key !== 'string') { var _ref2, _keyArg$value; var keyArg = connectionDirective.args.find(function (arg) { return arg.name === 'key'; }); throw createUserError("Expected the ".concat(KEY, " argument to @").concat(connectionDirective.name, " to be a ") + "string literal for field ".concat(field.name, "."), [(_ref2 = keyArg === null || keyArg === void 0 ? void 0 : (_keyArg$value = keyArg.value) === null || _keyArg$value === void 0 ? void 0 : _keyArg$value.loc) !== null && _ref2 !== void 0 ? _ref2 : connectionDirective.loc]); } var postfix = field.alias || field.name; if (!key.endsWith('_' + postfix)) { var _ref3, _keyArg$value2; var _keyArg = connectionDirective.args.find(function (arg) { return arg.name === 'key'; }); throw createUserError("Expected the ".concat(KEY, " argument to @").concat(connectionDirective.name, " to be of ") + "form _".concat(postfix, ", got '").concat(key, "'. ") + 'For a detailed explanation, check out ' + 'https://relay.dev/docs/en/pagination-container#connection', [(_ref3 = _keyArg === null || _keyArg === void 0 ? void 0 : (_keyArg$value2 = _keyArg.value) === null || _keyArg$value2 === void 0 ? void 0 : _keyArg$value2.loc) !== null && _ref3 !== void 0 ? _ref3 : connectionDirective.loc]); } if (literalFilters != null && (!Array.isArray(literalFilters) || literalFilters.some(function (filter) { return typeof filter !== 'string'; }))) { var _ref4, _filtersArg$value; var filtersArg = connectionDirective.args.find(function (arg) { return arg.name === 'filters'; }); throw createUserError("Expected the 'filters' argument to @".concat(connectionDirective.name, " to be ") + 'a string literal.', [(_ref4 = filtersArg === null || filtersArg === void 0 ? void 0 : (_filtersArg$value = filtersArg.value) === null || _filtersArg$value === void 0 ? void 0 : _filtersArg$value.loc) !== null && _ref4 !== void 0 ? _ref4 : connectionDirective.loc]); } var filters = literalFilters; if (filters == null) { var generatedFilters = field.args.filter(function (arg) { return !ConnectionInterface.isConnectionCall({ name: arg.name, value: null }); }).map(function (arg) { return arg.name; }); filters = generatedFilters.length !== 0 ? generatedFilters : null; } var stream = null; if (connectionDirective.name === STREAM_CONNECTION) { var _label; var initialCountArg = connectionDirective.args.find(function (arg) { return arg.name === 'initial_count'; }); var ifArg = connectionDirective.args.find(function (arg) { return arg.name === 'if'; }); if (label != null && typeof label !== 'string') { var _ref5, _labelArg$value; var labelArg = connectionDirective.args.find(function (arg) { return arg.name === 'label'; }); throw createUserError("Expected the 'label' argument to @".concat(connectionDirective.name, " to be a string literal for field ").concat(field.name, "."), [(_ref5 = labelArg === null || labelArg === void 0 ? void 0 : (_labelArg$value = labelArg.value) === null || _labelArg$value === void 0 ? void 0 : _labelArg$value.loc) !== null && _ref5 !== void 0 ? _ref5 : connectionDirective.loc]); } stream = { "if": ifArg, initialCount: initialCountArg, label: (_label = label) !== null && _label !== void 0 ? _label : key }; } // T45504512: new connection model var dynamicKeyArg = connectionDirective.args.find(function (arg) { return arg.name === 'dynamicKey_UNSTABLE'; }); var dynamicKey = null; if (dynamicKeyArg != null) { if (RelayFeatureFlags.ENABLE_VARIABLE_CONNECTION_KEY && dynamicKeyArg.value.kind === 'Variable') { dynamicKey = dynamicKeyArg.value; } else { throw createUserError("Unsupported 'dynamicKey_UNSTABLE' argument to @".concat(connectionDirective.name, ". This argument is only valid when the feature flag is enabled and ") + 'the variable must be a variable', [connectionDirective.loc]); } } return { handler: handler, key: key, dynamicKey: dynamicKey, filters: filters, stream: stream }; } function buildConnectionMetadata(field, path, stream) { var pathHasPlural = path.includes(null); var firstArg = findArg(field, FIRST); var lastArg = findArg(field, LAST); var direction = null; var countArg = null; var cursorArg = null; if (firstArg && !lastArg) { direction = 'forward'; countArg = firstArg; cursorArg = findArg(field, AFTER); } else if (lastArg && !firstArg) { direction = 'backward'; countArg = lastArg; cursorArg = findArg(field, BEFORE); } else if (lastArg && firstArg) { direction = 'bidirectional'; // TODO(T26511885) Maybe add connection metadata to this case } var countVariable = countArg && countArg.value.kind === 'Variable' ? countArg.value.variableName : null; var cursorVariable = cursorArg && cursorArg.value.kind === 'Variable' ? cursorArg.value.variableName : null; if (stream) { return { count: countVariable, cursor: cursorVariable, direction: direction, path: pathHasPlural ? null : path, stream: true }; } return { count: countVariable, cursor: cursorVariable, direction: direction, path: pathHasPlural ? null : path }; } /** * @internal * * Transforms the selections on a connection field, generating fields necessary * for pagination (edges.cursor, pageInfo, etc) and adding/merging them with * existing selections. */ function transformConnectionSelections(context, field, nullableType, direction, connectionArguments, directiveLocation, documentName) { var schema = context.getSchema(); var derivedFieldLocation = { kind: 'Derived', source: field.loc }; var derivedDirectiveLocation = { kind: 'Derived', source: directiveLocation }; var _ConnectionInterface$ = ConnectionInterface.get(), CURSOR = _ConnectionInterface$.CURSOR, EDGES = _ConnectionInterface$.EDGES, END_CURSOR = _ConnectionInterface$.END_CURSOR, HAS_NEXT_PAGE = _ConnectionInterface$.HAS_NEXT_PAGE, HAS_PREV_PAGE = _ConnectionInterface$.HAS_PREV_PAGE, NODE = _ConnectionInterface$.NODE, PAGE_INFO = _ConnectionInterface$.PAGE_INFO, START_CURSOR = _ConnectionInterface$.START_CURSOR; // Find existing edges/pageInfo selections var edgesSelection; var pageInfoSelection; field.selections.forEach(function (selection) { if (selection.kind === 'LinkedField') { if (selection.name === EDGES) { if (edgesSelection != null) { throw createCompilerError("ConnectionTransform: Unexpected duplicate field '".concat(EDGES, "'."), [edgesSelection.loc, selection.loc]); } edgesSelection = selection; return; } else if (selection.name === PAGE_INFO) { if (pageInfoSelection != null) { throw createCompilerError("ConnectionTransform: Unexpected duplicate field '".concat(PAGE_INFO, "'."), [pageInfoSelection.loc, selection.loc]); } pageInfoSelection = selection; return; } } }); // If streaming is enabled, construct directives to apply to the edges/ // pageInfo fields var streamDirective; var stream = connectionArguments.stream; if (stream != null) { streamDirective = { args: [stream["if"], stream.initialCount, { kind: 'Argument', loc: derivedDirectiveLocation, name: 'label', type: SchemaUtils.getNullableStringInput(schema), value: { kind: 'Literal', loc: derivedDirectiveLocation, value: stream.label } }].filter(Boolean), kind: 'Directive', loc: derivedDirectiveLocation, name: 'stream' }; } // For backwards compatibility with earlier versions of this transform, // edges/pageInfo have to be generated as non-aliased fields (since product // code may be accessing the non-aliased response keys). But for streaming // mode we need to generate @stream/@defer directives on these fields *and* // we prefer to avoid generating extra selections (we want one payload per // item, not two as could happen with separate @stream directives on the // aliased and non-aliased edges fields). So we keep things simple by // disallowing aliases on edges/pageInfo in streaming mode. if (edgesSelection && edgesSelection.alias !== edgesSelection.name) { if (stream) { throw createUserError("@stream_connection does not support aliasing the '".concat(EDGES, "' field."), [edgesSelection.loc]); } edgesSelection = null; } if (pageInfoSelection && pageInfoSelection.alias !== pageInfoSelection.name) { if (stream) { throw createUserError("@stream_connection does not support aliasing the '".concat(PAGE_INFO, "' field."), [pageInfoSelection.loc]); } pageInfoSelection = null; } // Separately create transformed versions of edges/pageInfo so that we can // later replace the originals at the same point within the selection array var transformedEdgesSelection = edgesSelection; var transformedPageInfoSelection = pageInfoSelection; var edgesType = schema.getFieldConfig(schema.expectField(nullableType, EDGES)).type; var pageInfoType = schema.getFieldConfig(schema.expectField(nullableType, PAGE_INFO)).type; if (transformedEdgesSelection == null) { transformedEdgesSelection = { alias: EDGES, args: [], connection: false, directives: [], handles: null, kind: 'LinkedField', loc: derivedFieldLocation, metadata: null, name: EDGES, selections: [], type: schema.assertLinkedFieldType(edgesType) }; } if (transformedPageInfoSelection == null) { transformedPageInfoSelection = { alias: PAGE_INFO, args: [], connection: false, directives: [], handles: null, kind: 'LinkedField', loc: derivedFieldLocation, metadata: null, name: PAGE_INFO, selections: [], type: schema.assertLinkedFieldType(pageInfoType) }; } // Generate (additional) fields on pageInfo and add to the transformed // pageInfo field var pageInfoRawType = schema.getRawType(pageInfoType); var pageInfoText; if (direction === 'forward') { pageInfoText = "fragment PageInfo on ".concat(schema.getTypeString(pageInfoRawType), " {\n ").concat(END_CURSOR, "\n ").concat(HAS_NEXT_PAGE, "\n }"); } else if (direction === 'backward') { pageInfoText = "fragment PageInfo on ".concat(schema.getTypeString(pageInfoRawType), " {\n ").concat(HAS_PREV_PAGE, "\n ").concat(START_CURSOR, "\n }"); } else { pageInfoText = "fragment PageInfo on ".concat(schema.getTypeString(pageInfoRawType), " {\n ").concat(END_CURSOR, "\n ").concat(HAS_NEXT_PAGE, "\n ").concat(HAS_PREV_PAGE, "\n ").concat(START_CURSOR, "\n }"); } var pageInfoAst = parse(pageInfoText); var pageInfoFragment = RelayParser.transform(schema, [pageInfoAst.definitions[0]])[0]; if (transformedPageInfoSelection.kind !== 'LinkedField') { throw createCompilerError('ConnectionTransform: Expected generated pageInfo selection to be ' + 'a LinkedField', [field.loc]); } transformedPageInfoSelection = (0, _objectSpread2["default"])({}, transformedPageInfoSelection, { selections: [].concat((0, _toConsumableArray2["default"])(transformedPageInfoSelection.selections), [{ directives: [], kind: 'InlineFragment', loc: derivedFieldLocation, metadata: null, selections: pageInfoFragment.selections, typeCondition: pageInfoFragment.type }]) }); // When streaming the pageInfo field has to be deferred if (stream != null) { var _ref6, _stream$if; transformedPageInfoSelection = { "if": (_ref6 = (_stream$if = stream["if"]) === null || _stream$if === void 0 ? void 0 : _stream$if.value) !== null && _ref6 !== void 0 ? _ref6 : null, label: "".concat(documentName, "$defer$").concat(stream.label, "$").concat(PAGE_INFO), kind: 'Defer', loc: derivedFieldLocation, metadata: { fragmentTypeCondition: nullableType }, selections: [transformedPageInfoSelection] }; } // Generate additional fields on edges and append to the transformed edges // selection var edgeText = "\n fragment Edges on ".concat(schema.getTypeString(schema.getRawType(edgesType)), " {\n ").concat(CURSOR, "\n ").concat(NODE, " {\n __typename # rely on GenerateRequisiteFieldTransform to add \"id\"\n }\n }\n "); var edgeAst = parse(edgeText); var edgeFragment = RelayParser.transform(schema, [edgeAst.definitions[0]])[0]; // When streaming the edges field needs @stream transformedEdgesSelection = (0, _objectSpread2["default"])({}, transformedEdgesSelection, { directives: streamDirective != null ? [].concat((0, _toConsumableArray2["default"])(transformedEdgesSelection.directives), [streamDirective]) : transformedEdgesSelection.directives, selections: [].concat((0, _toConsumableArray2["default"])(transformedEdgesSelection.selections), [{ directives: [], kind: 'InlineFragment', loc: derivedFieldLocation, metadata: null, selections: edgeFragment.selections, typeCondition: edgeFragment.type }]) }); // Copy the original selections, replacing edges/pageInfo (if present) // with the generated locations. This is to maintain the original field // ordering. var selections = field.selections.map(function (selection) { if (transformedEdgesSelection != null && edgesSelection != null && selection === edgesSelection) { return transformedEdgesSelection; } else if (transformedPageInfoSelection != null && pageInfoSelection != null && selection === pageInfoSelection) { return transformedPageInfoSelection; } else { return selection; } }); // If edges/pageInfo were missing, append the generated versions instead. if (edgesSelection == null && transformedEdgesSelection != null) { selections.push(transformedEdgesSelection); } if (pageInfoSelection == null && transformedPageInfoSelection != null) { selections.push(transformedPageInfoSelection); } return selections; } function findArg(field, argName) { return field.args && field.args.find(function (arg) { return arg.name === argName; }); } /** * @internal * * Validates that the selection is a valid connection: * - Specifies a first or last argument to prevent accidental, unconstrained * data access. * - Has an `edges` selection, otherwise there is nothing to paginate. * * TODO: This implementation requires the edges field to be a direct selection * and not contained within an inline fragment or fragment spread. It's * technically possible to remove this restriction if this pattern becomes * common/necessary. */ function validateConnectionSelection(field) { var _ConnectionInterface$2 = ConnectionInterface.get(), EDGES = _ConnectionInterface$2.EDGES; if (!findArg(field, FIRST) && !findArg(field, LAST)) { throw createUserError("Expected field '".concat(field.name, "' to have a '").concat(FIRST, "' or '").concat(LAST, "' ") + 'argument.', [field.loc]); } if (!field.selections.some(function (selection) { return selection.kind === 'LinkedField' && selection.name === EDGES; })) { throw createUserError("Expected field '".concat(field.name, "' to have an '").concat(EDGES, "' selection."), [field.loc]); } } /** * @internal * * Validates that the type satisfies the Connection specification: * - The type has an edges field, and edges have scalar `cursor` and object * `node` fields. * - The type has a page info field which is an object with the correct * subfields. */ function validateConnectionType(schema, field, nullableType, connectionDirective) { var directiveName = connectionDirective.name; var _ConnectionInterface$3 = ConnectionInterface.get(), CURSOR = _ConnectionInterface$3.CURSOR, EDGES = _ConnectionInterface$3.EDGES, END_CURSOR = _ConnectionInterface$3.END_CURSOR, HAS_NEXT_PAGE = _ConnectionInterface$3.HAS_NEXT_PAGE, HAS_PREV_PAGE = _ConnectionInterface$3.HAS_PREV_PAGE, NODE = _ConnectionInterface$3.NODE, PAGE_INFO = _ConnectionInterface$3.PAGE_INFO, START_CURSOR = _ConnectionInterface$3.START_CURSOR; var typeName = schema.getTypeString(nullableType); if (!schema.hasField(nullableType, EDGES)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, "' field"), [field.loc]); } var edges = schema.getFieldConfig(schema.expectField(nullableType, EDGES)); var edgesType = schema.getNullableType(edges.type); if (!schema.isList(edgesType)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, "' field that returns ") + 'a list of objects.', [field.loc]); } var edgeType = schema.getNullableType(schema.getListItemType(edgesType)); if (!schema.isObject(edgeType) && !schema.isInterface(edgeType)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, "' field that returns ") + 'a list of objects.', [field.loc]); } edgeType = schema.assertCompositeType(edgeType); if (!schema.hasField(edgeType, NODE)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, " { ").concat(NODE, " }' field ") + 'that returns an object, interface, or union.', [field.loc]); } var node = schema.getFieldConfig(schema.expectField(edgeType, NODE)); var nodeType = schema.getNullableType(node.type); if (!(schema.isAbstractType(nodeType) || schema.isObject(nodeType))) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, " { ").concat(NODE, " }' field ") + 'that returns an object, interface, or union.', [field.loc]); } if (!schema.hasField(edgeType, CURSOR)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, " { ").concat(CURSOR, " }' field ") + 'that returns a scalar value.', [field.loc]); } var cursor = schema.getFieldConfig(schema.expectField(edgeType, CURSOR)); if (!schema.isScalar(schema.getNullableType(cursor.type))) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have an '").concat(EDGES, " { ").concat(CURSOR, " }' field ") + 'that returns a scalar value.', [field.loc]); } if (!schema.hasField(nullableType, PAGE_INFO)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have a '").concat(PAGE_INFO, "' field that returns ") + 'an object.', [field.loc]); } var pageInfo = schema.getFieldConfig(schema.expectField(nullableType, PAGE_INFO)); var pageInfoType = schema.getNullableType(pageInfo.type); if (!schema.isObject(pageInfoType)) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected the ") + "field type '".concat(typeName, "' to have a '").concat(PAGE_INFO, "' field that ") + 'returns an object.', [field.loc]); } [END_CURSOR, HAS_NEXT_PAGE, HAS_PREV_PAGE, START_CURSOR].forEach(function (fieldName) { var pageInfoField = schema.getFieldConfig(schema.expectField(schema.assertObjectType(pageInfoType), fieldName)); if (!schema.isScalar(schema.getNullableType(pageInfoField.type))) { throw createUserError("@".concat(directiveName, " used on invalid field '").concat(field.name, "'. Expected ") + "the field type '".concat(typeName, "' to have a '").concat(PAGE_INFO, " { ").concat(fieldName, " }' ") + 'field returns a scalar.', [field.loc]); } }); } module.exports = { buildConnectionMetadata: buildConnectionMetadata, CONNECTION: CONNECTION, SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: connectionTransform }; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var GraphQLIRTransformer = __webpack_require__(3); var areEqual = __webpack_require__(81); var getIdentifierForSelection = __webpack_require__(37); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createUserError = _require.createUserError; /** * Transform that flattens inline fragments, fragment spreads, and conditionals. * * Inline fragments are inlined (replaced with their selections) when: * - The fragment type matches the type of its parent. * - The fragment has an abstract type and the `flattenAbstractTypes` option has * been set. */ function flattenTransformImpl(context, options) { var state = { flattenAbstractTypes: !!(options && options.flattenAbstractTypes), parentType: null }; var visitorFn = memoizedFlattenSelection(new Map()); return GraphQLIRTransformer.transform(context, { Condition: visitorFn, Connection: visitorFn, ConnectionField: visitorFn, Defer: visitorFn, Fragment: visitorFn, InlineFragment: visitorFn, InlineDataFragmentSpread: visitorFn, LinkedField: visitorFn, Root: visitorFn, SplitOperation: visitorFn }, function () { return state; }); } function memoizedFlattenSelection(cache) { return function flattenSelectionsFn(node, state) { var context = this.getContext(); var nodeCache = cache.get(node); if (nodeCache == null) { nodeCache = new Map(); cache.set(node, nodeCache); } // Determine the current type. var parentType = state.parentType; var result = nodeCache.get(parentType); if (result != null) { return result; } var type = node.kind === 'LinkedField' || node.kind === 'Fragment' || node.kind === 'Root' || node.kind === 'SplitOperation' ? node.type : node.kind === 'InlineFragment' ? node.typeCondition : parentType; if (type == null) { throw createCompilerError('FlattenTransform: Expected a parent type.', [node.loc]); } // Flatten the selections in this node, creating a new node with flattened // selections if possible, then deeply traverse the flattened node, while // keeping track of the parent type. var nextSelections = new Map(); var hasFlattened = flattenSelectionsInto(context.getSchema(), nextSelections, node, state, type); var flattenedNode = hasFlattened ? (0, _objectSpread2["default"])({}, node, { selections: Array.from(nextSelections.values()) }) : node; state.parentType = type; var deeplyFlattenedNode = this.traverse(flattenedNode, state); state.parentType = parentType; nodeCache.set(parentType, deeplyFlattenedNode); return deeplyFlattenedNode; }; } /** * @private */ function flattenSelectionsInto(schema, flattenedSelections, node, state, type) { var hasFlattened = false; node.selections.forEach(function (selection) { if (selection.kind === 'InlineFragment' && shouldFlattenInlineFragment(schema, selection, state, type)) { hasFlattened = true; flattenSelectionsInto(schema, flattenedSelections, selection, state, type); return; } var nodeIdentifier = getIdentifierForSelection(schema, selection); var flattenedSelection = flattenedSelections.get(nodeIdentifier); // If this selection hasn't been seen before, keep track of it. if (!flattenedSelection) { flattenedSelections.set(nodeIdentifier, selection); return; } // Otherwise a similar selection exists which should be merged. hasFlattened = true; if (flattenedSelection.kind === 'InlineFragment') { if (selection.kind !== 'InlineFragment') { throw createCompilerError("FlattenTransform: Expected an InlineFragment, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, selection.typeCondition) })); } else if (flattenedSelection.kind === 'Condition') { if (selection.kind !== 'Condition') { throw createCompilerError("FlattenTransform: Expected a Condition, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, type) })); } else if (flattenedSelection.kind === 'ClientExtension') { if (selection.kind !== 'ClientExtension') { throw createCompilerError("FlattenTransform: Expected a ClientExtension, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, type) })); } else if (flattenedSelection.kind === 'FragmentSpread') {// Ignore duplicate fragment spreads. } else if (flattenedSelection.kind === 'ModuleImport') { if (selection.kind !== 'ModuleImport') { throw createCompilerError("FlattenTransform: Expected a ModuleImport, got a '".concat(selection.kind, "'"), [selection.loc]); } if (selection.name !== flattenedSelection.name || selection.module !== flattenedSelection.module || selection.documentName !== flattenedSelection.documentName) { throw createUserError('Found conflicting @module selections: use a unique alias on the ' + 'parent fields.', [selection.loc, flattenedSelection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, type) })); } else if (flattenedSelection.kind === 'Defer') { if (selection.kind !== 'Defer') { throw createCompilerError("FlattenTransform: Expected a Defer, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({ kind: 'Defer' }, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, type) })); } else if (flattenedSelection.kind === 'Stream') { if (selection.kind !== 'Stream') { throw createCompilerError("FlattenTransform: Expected a Stream, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({ kind: 'Stream' }, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, type) })); } else if (flattenedSelection.kind === 'LinkedField') { if (selection.kind !== 'LinkedField') { throw createCompilerError("FlattenTransform: Expected a LinkedField, got a '".concat(selection.kind, "'"), [selection.loc]); } assertUniqueArgsForAlias(selection, flattenedSelection); // NOTE: not using object spread here as this code is pretty hot flattenedSelections.set(nodeIdentifier, { kind: 'LinkedField', alias: flattenedSelection.alias, args: flattenedSelection.args, connection: flattenedSelection.connection || selection.connection, directives: flattenedSelection.directives, handles: mergeHandles(flattenedSelection, selection), loc: flattenedSelection.loc, metadata: flattenedSelection.metadata, name: flattenedSelection.name, selections: mergeSelections(schema, flattenedSelection, selection, state, selection.type), type: flattenedSelection.type }); } else if (flattenedSelection.kind === 'ScalarField') { if (selection.kind !== 'ScalarField') { throw createCompilerError("FlattenTransform: Expected a ScalarField, got a '".concat(selection.kind, "'"), [selection.loc]); } assertUniqueArgsForAlias(selection, flattenedSelection); if (selection.handles && selection.handles.length > 0) { flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({ kind: 'ScalarField' }, flattenedSelection, { handles: mergeHandles(selection, flattenedSelection) })); } } else if (flattenedSelection.kind === 'ConnectionField') { if (selection.kind !== 'ConnectionField') { throw createCompilerError("FlattenTransform: Expected a ConnectionField, got a '".concat(selection.kind, "'"), [selection.loc]); } assertUniqueArgsForAlias(selection, flattenedSelection); // NOTE: not using object spread here as this code is pretty hot flattenedSelections.set(nodeIdentifier, { kind: 'ConnectionField', alias: flattenedSelection.alias, args: flattenedSelection.args, directives: flattenedSelection.directives, loc: flattenedSelection.loc, metadata: flattenedSelection.metadata, name: flattenedSelection.name, selections: mergeSelections(schema, flattenedSelection, selection, state, selection.type), type: flattenedSelection.type }); } else if (flattenedSelection.kind === 'InlineDataFragmentSpread') { throw createCompilerError('FlattenTransform: did not expect an InlineDataFragmentSpread node. ' + 'Only expecting InlineDataFragmentSpread in reader ASTs and this ' + 'transform to run only on normalization ASTs.', [selection.loc]); } else if (flattenedSelection.kind === 'Connection') { if (selection.kind !== 'Connection') { throw createCompilerError("FlattenTransform: Expected a Connection, got a '".concat(selection.kind, "'"), [selection.loc]); } flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({ kind: 'Connection' }, flattenedSelection, { selections: mergeSelections(schema, flattenedSelection, selection, state, selection.type) })); } else { flattenedSelection.kind; throw createCompilerError("FlattenTransform: Unknown kind '".concat(flattenedSelection.kind, "'")); } }); return hasFlattened; } /** * @private */ function mergeSelections(schema, nodeA, nodeB, state, type) { var flattenedSelections = new Map(); flattenSelectionsInto(schema, flattenedSelections, nodeA, state, type); flattenSelectionsInto(schema, flattenedSelections, nodeB, state, type); return Array.from(flattenedSelections.values()); } /** * @private * TODO(T19327202) This is redundant with OverlappingFieldsCanBeMergedRule once * it can be enabled. */ function assertUniqueArgsForAlias(field, otherField) { if (!areEqualFields(field, otherField)) { throw createUserError('Expected all fields on the same parent with the name or alias ' + "'".concat(field.alias, "' to have the same name and arguments."), [field.loc, otherField.loc]); } } /** * @private */ function shouldFlattenInlineFragment(schema, fragment, state, type) { return schema.areEqualTypes(fragment.typeCondition, schema.getRawType(type)) || state.flattenAbstractTypes && schema.isAbstractType(fragment.typeCondition); } /** * @private * * Verify that two fields are equal in all properties other than their * selections. */ function areEqualFields(thisField, thatField) { return thisField.kind === thatField.kind && thisField.name === thatField.name && thisField.alias === thatField.alias && areEqualArgs(thisField.args, thatField.args); } /** * Verify that two sets of arguments are equivalent - same argument names * and values. Notably this ignores the types of arguments and values, which * may not always be inferred identically. */ function areEqualArgs(thisArgs, thatArgs) { return thisArgs.length === thatArgs.length && thisArgs.every(function (thisArg, index) { var thatArg = thatArgs[index]; return thisArg.name === thatArg.name && thisArg.value.kind === thatArg.value.kind && thisArg.value.variableName === thatArg.value.variableName && areEqual(thisArg.value.value, thatArg.value.value); }); } /** * @private */ function mergeHandles(nodeA, nodeB) { if (!nodeA.handles) { return nodeB.handles; } if (!nodeB.handles) { return nodeA.handles; } var uniqueItems = new Map(); nodeA.handles.concat(nodeB.handles).forEach(function (item) { return uniqueItems.set(item.name + item.key, item); }); return Array.from(uniqueItems.values()); } function transformWithOptions(options) { return function flattenTransform(context) { return flattenTransformImpl(context, options); }; } module.exports = { transformWithOptions: transformWithOptions }; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var invariant = __webpack_require__(4); var _require = __webpack_require__(31), printArguments = _require.printArguments, printDirectives = _require.printDirectives; /** * Generates an identifier that is unique to a given selection: the alias for * fields, the type for inline fragments, and a summary of the condition * variable and passing value for conditions. */ function getIdentifierForSelection(schema, node) { if (node.kind === 'LinkedField' || node.kind === 'ScalarField' || node.kind === 'ConnectionField') { return 'Field: ' + node.directives.length === 0 ? node.alias : node.alias + printDirectives(schema, node.directives); } else if (node.kind === 'Connection') { return 'Connection:' + node.label; } else if (node.kind === 'FragmentSpread') { return 'FragmentSpread:' + node.args.length === 0 ? node.name : node.name + printArguments(schema, node.args); } else if (node.kind === 'ModuleImport') { return 'ModuleImport:'; } else if (node.kind === 'Defer') { return 'Defer:' + node.label; } else if (node.kind === 'Stream') { return 'Stream:' + node.label; } else if (node.kind === 'InlineFragment') { return 'InlineFragment:' + schema.getTypeString(node.typeCondition); } else if (node.kind === 'ClientExtension') { return 'ClientExtension:'; } else if (node.kind === 'InlineDataFragmentSpread') { return 'InlineDataFragment:' + node.name; } else if (node.kind === 'Condition') { return 'Condition:' + (node.condition.kind === 'Variable' ? '$' + node.condition.variableName : String(node.condition.value)) + String(node.passingValue); } else { true ? true ? invariant(false, 'getIdentifierForSelection: Unexpected kind `%s`.', node.kind) : undefined : undefined; } } module.exports = getIdentifierForSelection; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ function hasUnaliasedSelection(field, fieldName) { return field.selections.some(function (selection) { return selection.kind === 'ScalarField' && selection.alias === fieldName && selection.name === fieldName; }); } module.exports = { hasUnaliasedSelection: hasUnaliasedSelection }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var IRTransformer = __webpack_require__(3); var invariant = __webpack_require__(4); var joinArgumentDefinitions = __webpack_require__(86); var _require = __webpack_require__(1), createUserError = _require.createUserError; /** * A transform that inlines fragment spreads with the @relay(mask: false) * directive. */ function maskTransform(context) { return IRTransformer.transform(context, { FragmentSpread: visitFragmentSpread, Fragment: visitFragment }, function () { return { reachableArguments: [] }; }); } function visitFragment(fragment, state) { var result = this.traverse(fragment, state); if (state.reachableArguments.length === 0) { return result; } var joinedArgumentDefinitions = joinArgumentDefinitions(this.getContext().getSchema(), fragment, state.reachableArguments, '@relay(unmask: true)'); return (0, _objectSpread2["default"])({}, result, { argumentDefinitions: joinedArgumentDefinitions }); } function visitFragmentSpread(fragmentSpread, state) { if (!isUnmaskedSpread(fragmentSpread)) { return fragmentSpread; } !(fragmentSpread.args.length === 0) ? true ? invariant(false, 'MaskTransform: Cannot unmask fragment spread `%s` with ' + 'arguments. Use the `ApplyFragmentArgumentTransform` before flattening', fragmentSpread.name) : undefined : void 0; var context = this.getContext(); var fragment = context.getFragment(fragmentSpread.name); var result = { kind: 'InlineFragment', directives: fragmentSpread.directives, loc: { kind: 'Derived', source: fragmentSpread.loc }, metadata: fragmentSpread.metadata, selections: fragment.selections, typeCondition: fragment.type }; if (fragment.directives.length > 0) { throw new createUserError('Cannot use @relay(mask: false) on fragment spreads for fragments ' + 'with directives.', [fragmentSpread.loc, fragment.directives[0].loc]); } var localArgDef = fragment.argumentDefinitions.find(function (argDef) { return argDef.kind === 'LocalArgumentDefinition'; }); if (localArgDef != null) { throw createUserError('MaskTransform: Cannot use @relay(mask: false) on fragment spread ' + 'because the fragment definition uses @argumentDefinitions.', [fragmentSpread.loc, localArgDef.loc]); } // Note: defer validating arguments to the containing fragment in order // to list all invalid variables/arguments instead of only one. var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fragment.argumentDefinitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var argDef = _step.value; state.reachableArguments.push(argDef); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return this.traverse(result, state); } /** * @private */ function isUnmaskedSpread(spread) { return Boolean(spread.metadata && spread.metadata.mask === false); } module.exports = { transform: maskTransform }; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var getLiteralArgumentValues = __webpack_require__(16); var getNormalizationOperationName = __webpack_require__(41); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(9), getModuleComponentKey = _require2.getModuleComponentKey, getModuleOperationKey = _require2.getModuleOperationKey; var SUPPORTED_ARGUMENT_NAME = 'supported'; var JS_FIELD_TYPE = 'JSDependency'; var JS_FIELD_MODULE_ARG = 'module'; var JS_FIELD_ID_ARG = 'id'; var JS_FIELD_NAME = 'js'; var SCHEMA_EXTENSION = "\n directive @match on FIELD\n\n directive @module(\n name: String!\n ) on FRAGMENT_SPREAD\n"; /** * This transform rewrites LinkedField nodes with @match and rewrites them * into `LinkedField` nodes with a `supported` argument. */ function matchTransform(context) { return IRTransformer.transform(context, { // TODO: type IRTransformer to allow changing result type FragmentSpread: visitFragmentSpread, LinkedField: visitLinkedField, InlineFragment: visitInlineFragment, ScalarField: visitScalarField }, function (node) { return { documentName: node.name, parentType: node.type, path: [] }; }); } function visitInlineFragment(node, state) { return this.traverse(node, (0, _objectSpread2["default"])({}, state, { parentType: node.typeCondition })); } function visitScalarField(field) { var context = this.getContext(); var schema = context.getSchema(); if (field.name === JS_FIELD_NAME) { var jsModuleType = schema.getTypeFromString(JS_FIELD_TYPE); if (jsModuleType == null || !schema.isServerType(jsModuleType)) { throw new createUserError("'".concat(JS_FIELD_NAME, "' should be defined on the server schema."), [field.loc]); } if (schema.isScalar(jsModuleType) && schema.areEqualTypes(schema.getRawType(field.type), jsModuleType)) { throw new createUserError("Direct use of the '".concat(JS_FIELD_NAME, "' field is not allowed, use ") + '@match/@module instead.', [field.loc]); } } return field; } function visitLinkedField(node, state) { var context = this.getContext(); var schema = context.getSchema(); state.path.push(node.alias); var transformedNode = this.traverse(node, (0, _objectSpread2["default"])({}, state, { parentType: node.type })); state.path.pop(); var matchDirective = transformedNode.directives.find(function (directive) { return directive.name === 'match'; }); if (matchDirective == null) { return transformedNode; } var parentType = state.parentType; var rawType = schema.getRawType(parentType); if (!(schema.isInterface(rawType) || schema.isObject(rawType))) { throw createUserError("@match used on incompatible field '".concat(transformedNode.name, "'.") + '@match may only be used with fields whose parent type is an ' + "interface or object, got invalid type '".concat(schema.getTypeString(parentType), "'."), [node.loc]); } var currentField = schema.getFieldConfig(schema.expectField(schema.assertCompositeType(rawType), transformedNode.name)); var supportedArgumentDefinition = currentField.args.find(function (_ref4) { var name = _ref4.name; return name === SUPPORTED_ARGUMENT_NAME; }); var supportedArgType = supportedArgumentDefinition != null ? schema.getNullableType(supportedArgumentDefinition.type) : null; var supportedArgOfType = supportedArgType != null && schema.isList(supportedArgType) ? schema.getListItemType(supportedArgType) : null; if (supportedArgumentDefinition == null || supportedArgType == null || supportedArgOfType == null || !schema.isString(schema.getNullableType(supportedArgOfType))) { throw createUserError("@match used on incompatible field '".concat(transformedNode.name, "'. ") + '@match may only be used with fields that accept a ' + "'supported: [String!]!' argument.", [node.loc]); } var rawFieldType = schema.getRawType(transformedNode.type); if (!schema.isAbstractType(rawFieldType)) { throw createUserError("@match used on incompatible field '".concat(transformedNode.name, "'.") + '@match may only be used with fields that return a union or interface.', [node.loc]); } var seenTypes = new Map(); var selections = []; transformedNode.selections.forEach(function (matchSelection) { if (matchSelection.kind === 'ScalarField' && matchSelection.name === '__typename') { selections.push(matchSelection); return; } var moduleImport = matchSelection.kind === 'InlineFragment' ? matchSelection.selections[0] : null; if (matchSelection.kind !== 'InlineFragment' || moduleImport == null || moduleImport.kind !== 'ModuleImport') { throw createUserError('Invalid @match selection: all selections should be ' + 'fragment spreads with @module.', [matchSelection.loc]); } var matchedType = matchSelection.typeCondition; var previousTypeUsage = seenTypes.get(matchedType); if (previousTypeUsage) { throw createUserError('Invalid @match selection: each concrete variant/implementor of ' + "'".concat(schema.getTypeString(rawFieldType), "' may be matched against at-most once, ") + "but '".concat(schema.getTypeString(matchedType), "' was matched against multiple times."), [matchSelection.loc, previousTypeUsage.loc]); } seenTypes.set(matchedType, matchSelection); selections.push(matchSelection); }); if (seenTypes.size === 0) { throw createUserError('Invalid @match selection: expected at least one @module selection. ' + "Remove @match or add a '...Fragment @module()' selection.", [matchDirective.loc]); } var supportedArg = transformedNode.args.find(function (arg) { return arg.name === SUPPORTED_ARGUMENT_NAME; }); if (supportedArg != null) { throw createUserError("Invalid @match selection: the '".concat(SUPPORTED_ARGUMENT_NAME, "' argument ") + 'is automatically added and cannot be supplied explicitly.', [supportedArg.loc]); } return { kind: 'LinkedField', alias: transformedNode.alias, args: [].concat((0, _toConsumableArray2["default"])(transformedNode.args), [{ kind: 'Argument', name: SUPPORTED_ARGUMENT_NAME, type: supportedArgumentDefinition.type, value: { kind: 'Literal', loc: node.loc, value: Array.from(seenTypes.keys()).map(function (type) { return schema.getTypeString(type); }) }, loc: node.loc }]), connection: false, directives: [], handles: null, loc: node.loc, metadata: null, name: transformedNode.name, type: transformedNode.type, selections: selections }; } // Transform @module function visitFragmentSpread(spread, _ref5) { var _ref, _moduleDirective$args2, _ref2, _moduleDirective$args3, _ref3, _moduleDirective$args4; var documentName = _ref5.documentName, path = _ref5.path; var transformedNode = this.traverse(spread); var moduleDirective = transformedNode.directives.find(function (directive) { return directive.name === 'module'; }); if (moduleDirective == null) { return transformedNode; } if (spread.args.length !== 0) { var _spread$args$; throw createUserError('@module does not support @arguments.', [(_spread$args$ = spread.args[0]) === null || _spread$args$ === void 0 ? void 0 : _spread$args$.loc].filter(Boolean)); } var context = this.getContext(); var schema = context.getSchema(); var jsModuleType = schema.asScalarFieldType(schema.getTypeFromString(JS_FIELD_TYPE)); if (jsModuleType == null || !schema.isServerType(jsModuleType)) { throw new createUserError("'".concat(JS_FIELD_NAME, "' should be defined on the server schema."), [spread.loc]); } if (!schema.isScalar(jsModuleType)) { throw createUserError('Using @module requires the schema to define a scalar ' + "'".concat(JS_FIELD_TYPE, "' type.")); } var fragment = context.getFragment(spread.name, spread.loc); if (!schema.isObject(fragment.type)) { throw createUserError("@module used on invalid fragment spread '...".concat(spread.name, "'. @module ") + 'may only be used with fragments on a concrete (object) type, ' + "but the fragment has abstract type '".concat(schema.getTypeString(fragment.type), "'."), [spread.loc, fragment.loc]); } var field = schema.getFieldByName(fragment.type, JS_FIELD_NAME); if (!field) { throw createUserError("@module used on invalid fragment spread '...".concat(spread.name, "'. @module ") + "requires the fragment type '".concat(schema.getTypeString(fragment.type), "' to have a ") + "'".concat(JS_FIELD_NAME, "(").concat(JS_FIELD_MODULE_ARG, ": String! ") + "[".concat(JS_FIELD_ID_ARG, ": String]): ").concat(JS_FIELD_TYPE, "' field (your ") + "schema may choose to omit the 'id' argument but if present it " + "must accept a 'String').", [moduleDirective.loc]); } var jsField = schema.getFieldConfig(field); var jsFieldModuleArg = jsField ? jsField.args.find(function (arg) { return arg.name === JS_FIELD_MODULE_ARG; }) : null; var jsFieldIdArg = jsField ? jsField.args.find(function (arg) { return arg.name === JS_FIELD_ID_ARG; }) : null; if (jsFieldModuleArg == null || !schema.isString(schema.getNullableType(jsFieldModuleArg.type)) || jsFieldIdArg != null && !schema.isString(jsFieldIdArg.type) || jsField.type !== jsModuleType) { throw createUserError("@module used on invalid fragment spread '...".concat(spread.name, "'. @module ") + "requires the fragment type '".concat(schema.getTypeString(fragment.type), "' to have a ") + "'".concat(JS_FIELD_NAME, "(").concat(JS_FIELD_MODULE_ARG, ": String! ") + "[".concat(JS_FIELD_ID_ARG, ": String]): ").concat(JS_FIELD_TYPE, "' field (your ") + "schema may choose to omit the 'id' argument but if present it " + "must accept a 'String').", [moduleDirective.loc]); } if (spread.directives.length !== 1) { throw createUserError("@module used on invalid fragment spread '...".concat(spread.name, "'. @module ") + 'may not have additional directives.', [spread.loc]); } var _getLiteralArgumentVa = getLiteralArgumentValues(moduleDirective.args), moduleName = _getLiteralArgumentVa.name; if (typeof moduleName !== 'string') { var _moduleDirective$args; throw createUserError("Expected the 'name' argument of @module to be a literal string", [((_moduleDirective$args = moduleDirective.args.find(function (arg) { return arg.name === 'name'; })) !== null && _moduleDirective$args !== void 0 ? _moduleDirective$args : spread).loc]); } var moduleId = [documentName].concat((0, _toConsumableArray2["default"])(path)).join('.'); var normalizationName = getNormalizationOperationName(spread.name) + '.graphql'; var componentKey = getModuleComponentKey(documentName); var componentField = { alias: componentKey, args: [{ kind: 'Argument', name: JS_FIELD_MODULE_ARG, type: jsFieldModuleArg.type, value: { kind: 'Literal', loc: (_ref = (_moduleDirective$args2 = moduleDirective.args[0]) === null || _moduleDirective$args2 === void 0 ? void 0 : _moduleDirective$args2.loc) !== null && _ref !== void 0 ? _ref : moduleDirective.loc, value: moduleName }, loc: moduleDirective.loc }, jsFieldIdArg != null ? { kind: 'Argument', name: JS_FIELD_ID_ARG, type: jsFieldIdArg.type, value: { kind: 'Literal', loc: (_ref2 = (_moduleDirective$args3 = moduleDirective.args[0]) === null || _moduleDirective$args3 === void 0 ? void 0 : _moduleDirective$args3.loc) !== null && _ref2 !== void 0 ? _ref2 : moduleDirective.loc, value: moduleId }, loc: moduleDirective.loc } : null].filter(Boolean), directives: [], handles: null, kind: 'ScalarField', loc: moduleDirective.loc, metadata: { skipNormalizationNode: true }, name: JS_FIELD_NAME, type: jsModuleType }; var operationKey = getModuleOperationKey(documentName); var operationField = { alias: operationKey, args: [{ kind: 'Argument', name: JS_FIELD_MODULE_ARG, type: jsFieldModuleArg.type, value: { kind: 'Literal', loc: moduleDirective.loc, value: normalizationName }, loc: moduleDirective.loc }, jsFieldIdArg != null ? { kind: 'Argument', name: JS_FIELD_ID_ARG, type: jsFieldIdArg.type, value: { kind: 'Literal', loc: (_ref3 = (_moduleDirective$args4 = moduleDirective.args[0]) === null || _moduleDirective$args4 === void 0 ? void 0 : _moduleDirective$args4.loc) !== null && _ref3 !== void 0 ? _ref3 : moduleDirective.loc, value: moduleId }, loc: moduleDirective.loc } : null].filter(Boolean), directives: [], handles: null, kind: 'ScalarField', loc: moduleDirective.loc, metadata: { skipNormalizationNode: true }, name: JS_FIELD_NAME, type: jsModuleType }; return { kind: 'InlineFragment', directives: [], loc: moduleDirective.loc, metadata: null, selections: [{ kind: 'ModuleImport', loc: moduleDirective.loc, documentName: documentName, id: moduleId, module: moduleName, name: spread.name, selections: [(0, _objectSpread2["default"])({}, spread, { directives: spread.directives.filter(function (directive) { return directive !== moduleDirective; }) }), operationField, componentField] }], typeCondition: fragment.type }; } module.exports = { SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: matchTransform }; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ function getNormalizationOperationName(name) { return "".concat(name, "$normalization"); } module.exports = getNormalizationOperationName; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var GraphQLIRVisitor = __webpack_require__(15); var getLiteralArgumentValues = __webpack_require__(16); var inferRootArgumentDefinitions = __webpack_require__(17); var _require = __webpack_require__(1), createUserError = _require.createUserError, eachWithCombinedError = _require.eachWithCombinedError; var _require2 = __webpack_require__(87), buildRefetchOperation = _require2.buildRefetchOperation; var SCHEMA_EXTENSION = "\n directive @refetchable(\n queryName: String!\n ) on FRAGMENT_DEFINITION\n"; /** * This transform synthesizes "refetch" queries for fragments that * are trivially refetchable. This is comprised of three main stages: * * 1. Validating that fragments marked with @refetchable qualify for * refetch query generation; mainly this means that the fragment * type is able to be refetched in some canonical way. * 2. Determining the variable definitions to use for each generated * query. GraphQL does not have a notion of fragment-local variables * at all, and although Relay adds this concept developers are still * allowed to reference global variables. This necessitates a * visiting all reachable fragments for each @refetchable fragment, * and finding the union of all global variables expceted to be defined. * 3. Building the refetch queries, a straightforward copying transform from * Fragment to Root IR nodes. */ function refetchableFragmentTransform(context) { var schema = context.getSchema(); var refetchOperations = buildRefetchMap(context); var nextContext = context; eachWithCombinedError(refetchOperations, function (_ref2) { var _connectionMetadata; var refetchName = _ref2[0], fragment = _ref2[1]; var _buildRefetchOperatio = buildRefetchOperation(schema, fragment, refetchName), path = _buildRefetchOperatio.path, node = _buildRefetchOperatio.node, transformedFragment = _buildRefetchOperatio.transformedFragment; var connectionMetadata = extractConnectionMetadata(context.getSchema(), transformedFragment); nextContext = nextContext.replace((0, _objectSpread2["default"])({}, transformedFragment, { metadata: (0, _objectSpread2["default"])({}, transformedFragment.metadata || {}, { refetch: { connection: (_connectionMetadata = connectionMetadata) !== null && _connectionMetadata !== void 0 ? _connectionMetadata : null, operation: refetchName, fragmentPathInResult: path } }) })); nextContext = nextContext.add((0, _objectSpread2["default"])({}, node, { metadata: (0, _objectSpread2["default"])({}, node.metadata || {}, { derivedFrom: transformedFragment.name, isRefetchableQuery: true }) })); }); return nextContext; } /** * Walk the documents of a compiler context and create a mapping of * refetch operation names to the source fragment from which the refetch * operation should be derived. */ function buildRefetchMap(context) { var refetchOperations = new Map(); eachWithCombinedError(context.documents(), function (node) { if (node.kind !== 'Fragment') { return; } var refetchName = getRefetchQueryName(node); if (refetchName === null) { return; } var previousOperation = refetchOperations.get(refetchName); if (previousOperation != null) { throw createUserError("Duplicate definition for @refetchable operation '".concat(refetchName, "' from fragments '").concat(node.name, "' and '").concat(previousOperation.name, "'"), [node.loc, previousOperation.loc]); } refetchOperations.set(refetchName, node); }); var transformed = inferRootArgumentDefinitions(context); return new Map(Array.from(refetchOperations.entries(), function (_ref3) { var name = _ref3[0], fragment = _ref3[1]; return [name, transformed.getFragment(fragment.name)]; })); } /** * Validate that any @connection usage is valid for refetching: * - Variables are used for both the "count" and "cursor" arguments * (after/first or before/last) * - Exactly one connection * - Has a stable path to the connection data * * Returns connection metadata to add to the transformed fragment or undefined * if there is no connection. */ function extractConnectionMetadata(schema, fragment) { var fields = []; var connectionField = null; var path = null; GraphQLIRVisitor.visit(fragment, { ConnectionField: { enter: function enter(field) { fields.push(field); // Disallow connections within plurals var pluralOnPath = fields.find(function (pathField) { return schema.isList(schema.getNullableType(pathField.type)); }); if (pluralOnPath) { throw createUserError("Invalid use of @refetchable with @connection in fragment '".concat(fragment.name, "', refetchable connections cannot appear inside plural fields."), [field.loc, pluralOnPath.loc]); } connectionField = field; path = fields.map(function (pathField) { return pathField.alias; }); }, leave: function leave() { fields.pop(); } }, LinkedField: { enter: function enter(field) { fields.push(field); if (field.connection === true || field.handles && field.handles.some(function (handle) { return handle.name === 'connection'; })) { // Disallow multiple @connections if (connectionField != null) { throw createUserError("Invalid use of @refetchable with @connection in fragment '".concat(fragment.name, "', at most once @connection can appear in a refetchable fragment."), [field.loc]); } // Disallow connections within plurals var pluralOnPath = fields.find(function (pathField) { return schema.isList(schema.getNullableType(pathField.type)); }); if (pluralOnPath) { throw createUserError("Invalid use of @refetchable with @connection in fragment '".concat(fragment.name, "', refetchable connections cannot appear inside plural fields."), [field.loc, pluralOnPath.loc]); } connectionField = field; path = fields.map(function (pathField) { return pathField.alias; }); } }, leave: function leave() { fields.pop(); } } }); if (connectionField == null || path == null) { return; } // Validate arguments: if either of before/last appear they must both appear // and use variables (not scalar values) var backward = null; var before = findArgument(connectionField, 'before'); var last = findArgument(connectionField, 'last'); if (before || last) { if (!before || !last || before.value.kind !== 'Variable' || last.value.kind !== 'Variable') { throw createUserError("Invalid use of @refetchable with @connection in fragment '".concat(fragment.name, "', refetchable connections must use variables for the before and last arguments."), [connectionField.loc, before && before.value.kind !== 'Variable' ? before.value.loc : null, last && last.value.kind !== 'Variable' ? last.value.loc : null].filter(Boolean)); } backward = { count: last.value.variableName, cursor: before.value.variableName }; } // Validate arguments: if either of after/first appear they must both appear // and use variables (not scalar values) var forward = null; var after = findArgument(connectionField, 'after'); var first = findArgument(connectionField, 'first'); if (after || first) { if (!after || !first || after.value.kind !== 'Variable' || first.value.kind !== 'Variable') { throw createUserError("Invalid use of @refetchable with @connection in fragment '".concat(fragment.name, "', refetchable connections must use variables for the after and first arguments."), [connectionField.loc, after && after.value.kind !== 'Variable' ? after.value.loc : null, first && first.value.kind !== 'Variable' ? first.value.loc : null].filter(Boolean)); } forward = { count: first.value.variableName, cursor: after.value.variableName }; } return { forward: forward, backward: backward, path: path }; } function getRefetchQueryName(fragment) { var refetchableDirective = fragment.directives.find(function (directive) { return directive.name === 'refetchable'; }); if (refetchableDirective == null) { return null; } var refetchArguments = getLiteralArgumentValues(refetchableDirective.args); var queryName = refetchArguments.queryName; if (queryName == null) { throw createUserError("Expected the 'queryName' argument of @refetchable to be provided", [refetchableDirective.loc]); } else if (typeof queryName !== 'string') { var _ref; var queryNameArg = refetchableDirective.args.find(function (arg) { return arg.name === 'queryName'; }); throw createUserError("Expected the 'queryName' argument of @refetchable to be a string, got '".concat(String(queryName), "'."), [(_ref = queryNameArg === null || queryNameArg === void 0 ? void 0 : queryNameArg.loc) !== null && _ref !== void 0 ? _ref : refetchableDirective.loc]); } return queryName; } function findArgument(field, argumentName) { var _field$args$find; return (_field$args$find = field.args.find(function (arg) { return arg.name === argumentName; })) !== null && _field$args$find !== void 0 ? _field$args$find : null; } module.exports = { SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: refetchableFragmentTransform }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var IRTransformer = __webpack_require__(3); var getLiteralArgumentValues = __webpack_require__(16); var invariant = __webpack_require__(4); var RELAY = 'relay'; var SCHEMA_EXTENSION = "\ndirective @relay(\n # Marks a fragment as being backed by a GraphQLList.\n plural: Boolean,\n\n # Marks a fragment spread which should be unmasked if provided false\n mask: Boolean = true,\n) on FRAGMENT_DEFINITION | FRAGMENT_SPREAD\n"; /** * A transform that extracts `@relay(plural: Boolean)` directives and converts * them to metadata that can be accessed at runtime. */ function relayDirectiveTransform(context) { return IRTransformer.transform(context, { Fragment: visitRelayMetadata(fragmentMetadata), FragmentSpread: visitRelayMetadata(fragmentSpreadMetadata) }); } function visitRelayMetadata(metadataFn) { return function (node) { var relayDirective = node.directives.find(function (_ref) { var name = _ref.name; return name === RELAY; }); if (!relayDirective) { return this.traverse(node); } var argValues = getLiteralArgumentValues(relayDirective.args); var metadata = metadataFn(argValues); return this.traverse((0, _objectSpread2["default"])({}, node, { directives: node.directives.filter(function (directive) { return directive !== relayDirective; }), metadata: (0, _objectSpread2["default"])({}, node.metadata || {}, metadata) })); }; } function fragmentMetadata(_ref2) { var mask = _ref2.mask, plural = _ref2.plural; !(plural === undefined || typeof plural === 'boolean') ? true ? invariant(false, 'RelayDirectiveTransform: Expected the "plural" argument to @relay ' + 'to be a boolean literal if specified.') : undefined : void 0; !(mask === undefined || typeof mask === 'boolean') ? true ? invariant(false, 'RelayDirectiveTransform: Expected the "mask" argument to @relay ' + 'to be a boolean literal if specified.') : undefined : void 0; return { mask: mask, plural: plural }; } function fragmentSpreadMetadata(_ref3) { var mask = _ref3.mask; !(mask === undefined || typeof mask === 'boolean') ? true ? invariant(false, 'RelayDirectiveTransform: Expected the "mask" argument to @relay ' + 'to be a boolean literal if specified.') : undefined : void 0; return { mask: mask }; } module.exports = { RELAY: RELAY, SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: relayDirectiveTransform }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var ConnectionFieldTransform = __webpack_require__(34); var FlattenTransform = __webpack_require__(36); var IRVisitor = __webpack_require__(15); var MaskTransform = __webpack_require__(39); var MatchTransform = __webpack_require__(40); var Profiler = __webpack_require__(6); var RefetchableFragmentTransform = __webpack_require__(42); var RelayDirectiveTransform = __webpack_require__(43); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(45), anyTypeAlias = _require2.anyTypeAlias, declareExportOpaqueType = _require2.declareExportOpaqueType, exactObjectTypeAnnotation = _require2.exactObjectTypeAnnotation, exportType = _require2.exportType, exportTypes = _require2.exportTypes, importTypes = _require2.importTypes, intersectionTypeAnnotation = _require2.intersectionTypeAnnotation, lineComments = _require2.lineComments, readOnlyArrayOfType = _require2.readOnlyArrayOfType, readOnlyObjectTypeProperty = _require2.readOnlyObjectTypeProperty, unionTypeAnnotation = _require2.unionTypeAnnotation; var _require3 = __webpack_require__(91), transformInputType = _require3.transformInputType, transformScalarType = _require3.transformScalarType; var _require4 = __webpack_require__(9), ConnectionInterface = _require4.ConnectionInterface; var babelGenerator = __webpack_require__(92)["default"]; var t = __webpack_require__(22); var invariant = __webpack_require__(4); var nullthrows = __webpack_require__(20); function generate(schema, node, options) { var ast = IRVisitor.visit(node, createVisitor(schema, options)); return babelGenerator(ast).code; } function makeProp(schema, _ref, state, unmasked, concreteType) { var key = _ref.key, schemaName = _ref.schemaName, value = _ref.value, conditional = _ref.conditional, nodeType = _ref.nodeType, nodeSelections = _ref.nodeSelections; if (schemaName === '__typename' && concreteType) { value = t.stringLiteralTypeAnnotation(concreteType); } else if (nodeType) { value = transformScalarType(schema, nodeType, state, selectionsToBabel(schema, [Array.from(nullthrows(nodeSelections).values())], state, unmasked)); } var typeProperty = readOnlyObjectTypeProperty(key, value); if (conditional) { typeProperty.optional = true; } return typeProperty; } var isTypenameSelection = function isTypenameSelection(selection) { return selection.schemaName === '__typename'; }; var hasTypenameSelection = function hasTypenameSelection(selections) { return selections.some(isTypenameSelection); }; var onlySelectsTypename = function onlySelectsTypename(selections) { return selections.every(isTypenameSelection); }; function selectionsToBabel(schema, selections, state, unmasked, fragmentTypeName) { var baseFields = new Map(); var byConcreteType = {}; flattenArray(selections).forEach(function (selection) { var concreteType = selection.concreteType; if (concreteType) { var _byConcreteType$concr; byConcreteType[concreteType] = (_byConcreteType$concr = byConcreteType[concreteType]) !== null && _byConcreteType$concr !== void 0 ? _byConcreteType$concr : []; byConcreteType[concreteType].push(selection); } else { var previousSel = baseFields.get(selection.key); baseFields.set(selection.key, previousSel ? mergeSelection(selection, previousSel) : selection); } }); var types = []; if (Object.keys(byConcreteType).length > 0 && onlySelectsTypename(Array.from(baseFields.values())) && (hasTypenameSelection(Array.from(baseFields.values())) || Object.keys(byConcreteType).every(function (type) { return hasTypenameSelection(byConcreteType[type]); }))) { (function () { var typenameAliases = new Set(); var _loop = function _loop(concreteType) { types.push(groupRefs([].concat((0, _toConsumableArray2["default"])(Array.from(baseFields.values())), (0, _toConsumableArray2["default"])(byConcreteType[concreteType]))).map(function (selection) { if (selection.schemaName === '__typename') { typenameAliases.add(selection.key); } return makeProp(schema, selection, state, unmasked, concreteType); })); }; for (var concreteType in byConcreteType) { _loop(concreteType); } // It might be some other type then the listed concrete types. Ideally, we // would set the type to diff(string, set of listed concrete types), but // this doesn't exist in Flow at the time. types.push(Array.from(typenameAliases).map(function (typenameAlias) { var otherProp = readOnlyObjectTypeProperty(typenameAlias, t.stringLiteralTypeAnnotation('%other')); otherProp.leadingComments = lineComments("This will never be '%other', but we need some", 'value in case none of the concrete values match.'); return otherProp; })); })(); } else { var selectionMap = selectionsToMap(Array.from(baseFields.values())); for (var concreteType in byConcreteType) { selectionMap = mergeSelections(selectionMap, selectionsToMap(byConcreteType[concreteType].map(function (sel) { return (0, _objectSpread2["default"])({}, sel, { conditional: true }); }))); } var selectionMapValues = groupRefs(Array.from(selectionMap.values())).map(function (sel) { return isTypenameSelection(sel) && sel.concreteType ? makeProp(schema, (0, _objectSpread2["default"])({}, sel, { conditional: false }), state, unmasked, sel.concreteType) : makeProp(schema, sel, state, unmasked); }); types.push(selectionMapValues); } return unionTypeAnnotation(types.map(function (props) { if (fragmentTypeName) { props.push(readOnlyObjectTypeProperty('$refType', t.genericTypeAnnotation(t.identifier(fragmentTypeName)))); } return unmasked ? t.objectTypeAnnotation(props) : exactObjectTypeAnnotation(props); })); } function mergeSelection(a, b) { var shouldSetConditional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (!a) { if (shouldSetConditional) { return (0, _objectSpread2["default"])({}, b, { conditional: true }); } return b; } return (0, _objectSpread2["default"])({}, a, { nodeSelections: a.nodeSelections ? mergeSelections(a.nodeSelections, nullthrows(b.nodeSelections), shouldSetConditional) : null, conditional: a.conditional && b.conditional }); } function mergeSelections(a, b) { var shouldSetConditional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var merged = new Map(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = a.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _step.value, key = _step$value[0], value = _step$value[1]; merged.set(key, value); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = b.entries()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _step2$value = _step2.value, key = _step2$value[0], value = _step2$value[1]; merged.set(key, mergeSelection(a.get(key), value, shouldSetConditional)); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return merged; } function isPlural(node) { return Boolean(node.metadata && node.metadata.plural); } function createVisitor(schema, options) { var state = { customScalars: options.customScalars, enumsHasteModule: options.enumsHasteModule, existingFragmentNames: options.existingFragmentNames, generatedFragments: new Set(), generatedInputObjectTypes: {}, hasConnectionResolver: false, optionalInputFields: options.optionalInputFields, usedEnums: {}, usedFragments: new Set(), useHaste: options.useHaste, useSingleArtifactDirectory: options.useSingleArtifactDirectory, noFutureProofEnums: options.noFutureProofEnums, matchFields: new Map(), runtimeImports: new Set() }; return { leave: { Root: function Root(node) { var inputVariablesType = generateInputVariablesType(schema, node, state); var inputObjectTypes = generateInputObjectTypes(state); var responseType = exportType("".concat(node.name, "Response"), selectionsToBabel(schema, /* $FlowFixMe: selections have already been transformed */ node.selections, state, false)); var operationTypes = [t.objectTypeProperty(t.identifier('variables'), t.genericTypeAnnotation(t.identifier("".concat(node.name, "Variables")))), t.objectTypeProperty(t.identifier('response'), t.genericTypeAnnotation(t.identifier("".concat(node.name, "Response"))))]; // Generate raw response type var rawResponseType; var normalizationIR = options.normalizationIR; if (normalizationIR && node.directives.some(function (d) { return d.name === DIRECTIVE_NAME; })) { rawResponseType = IRVisitor.visit(normalizationIR, createRawResponseTypeVisitor(schema, state)); } var refetchableFragmentName = getRefetchableQueryParentFragmentName(state, node.metadata); if (state.hasConnectionResolver) { state.runtimeImports.add('ConnectionReference'); } if (refetchableFragmentName != null) { state.runtimeImports.add('FragmentReference'); } var babelNodes = []; if (state.runtimeImports.size) { babelNodes.push(importTypes(Array.from(state.runtimeImports).sort(), 'relay-runtime')); } babelNodes.push.apply(babelNodes, (0, _toConsumableArray2["default"])(refetchableFragmentName ? generateFragmentRefsForRefetchable(refetchableFragmentName) : getFragmentImports(state)).concat((0, _toConsumableArray2["default"])(getEnumDefinitions(schema, state)), (0, _toConsumableArray2["default"])(inputObjectTypes), [inputVariablesType, responseType])); if (rawResponseType) { var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = state.matchFields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _step3$value = _step3.value, key = _step3$value[0], ast = _step3$value[1]; babelNodes.push(t.typeAlias(t.identifier(key), null, ast)); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { _iterator3["return"](); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } operationTypes.push(t.objectTypeProperty(t.identifier('rawResponse'), t.genericTypeAnnotation(t.identifier("".concat(node.name, "RawResponse"))))); babelNodes.push(rawResponseType); } babelNodes.push(exportType(node.name, exactObjectTypeAnnotation(operationTypes))); return t.program(babelNodes); }, Fragment: function Fragment(node) { var selections = flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections); var numConecreteSelections = selections.filter(function (s) { return s.concreteType; }).length; selections = selections.map(function (selection) { if (numConecreteSelections <= 1 && isTypenameSelection(selection) && !schema.isAbstractType(node.type)) { return [(0, _objectSpread2["default"])({}, selection, { concreteType: schema.getTypeString(node.type) })]; } return [selection]; }); state.generatedFragments.add(node.name); var fragmentTypes = getFragmentTypes(node.name, getRefetchableQueryPath(state, node.directives)); var refTypeName = getRefTypeName(node.name); var refTypeDataProperty = readOnlyObjectTypeProperty('$data', t.genericTypeAnnotation(t.identifier("".concat(node.name, "$data")))); refTypeDataProperty.optional = true; var refTypeFragmentRefProperty = readOnlyObjectTypeProperty('$fragmentRefs', t.genericTypeAnnotation(t.identifier(getOldFragmentTypeName(node.name)))); var isPluralFragment = isPlural(node); var refType = t.objectTypeAnnotation([refTypeDataProperty, refTypeFragmentRefProperty]); var dataTypeName = getDataTypeName(node.name); var dataType = t.genericTypeAnnotation(t.identifier(node.name)); var unmasked = node.metadata != null && node.metadata.mask === false; var baseType = selectionsToBabel(schema, selections, state, unmasked, unmasked ? undefined : getOldFragmentTypeName(node.name)); var type = isPluralFragment ? readOnlyArrayOfType(baseType) : baseType; state.runtimeImports.add('FragmentReference'); if (state.hasConnectionResolver) { state.runtimeImports.add('ConnectionReference'); } return t.program([].concat((0, _toConsumableArray2["default"])(getFragmentImports(state)), (0, _toConsumableArray2["default"])(getEnumDefinitions(schema, state)), [importTypes(Array.from(state.runtimeImports).sort(), 'relay-runtime')], (0, _toConsumableArray2["default"])(fragmentTypes), [exportType(node.name, type), exportType(dataTypeName, dataType), exportType(refTypeName, isPluralFragment ? readOnlyArrayOfType(refType) : refType)])); }, InlineFragment: function InlineFragment(node) { return flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections).map(function (typeSelection) { return schema.isAbstractType(node.typeCondition) ? (0, _objectSpread2["default"])({}, typeSelection, { conditional: true }) : (0, _objectSpread2["default"])({}, typeSelection, { concreteType: schema.getTypeString(node.typeCondition) }); }); }, Condition: function Condition(node) { return flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections).map(function (selection) { return (0, _objectSpread2["default"])({}, selection, { conditional: true }); }); }, ScalarField: function ScalarField(node) { return visitScalarField(schema, node, state); }, Connection: function Connection(node) { return visitConnection(schema, node, state); }, ConnectionField: visitLinkedField, LinkedField: visitLinkedField, ModuleImport: function ModuleImport(node) { return [{ key: '__fragmentPropName', conditional: true, value: transformScalarType(schema, schema.expectStringType(), state) }, { key: '__module_component', conditional: true, value: transformScalarType(schema, schema.expectStringType(), state) }, { key: '__fragments_' + node.name, ref: node.name }]; }, FragmentSpread: function FragmentSpread(node) { state.usedFragments.add(node.name); return [{ key: '__fragments_' + node.name, ref: node.name }]; } } }; } function visitNodeWithSelectionsOnly(node) { return flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections); } function visitScalarField(schema, node, state) { return [{ key: node.alias, schemaName: node.name, value: transformScalarType(schema, node.type, state) }]; } function visitConnection(schema, node, state) { var _ConnectionInterface$ = ConnectionInterface.get(), EDGES = _ConnectionInterface$.EDGES; state.hasConnectionResolver = true; var edgesSelection = node.selections.find(function (selections) { var mixedSelections = selections; return Array.isArray(mixedSelections) && mixedSelections.some(function (selection) { return selection != null && typeof selection === 'object' && selection.key === EDGES && selection.schemaName === EDGES; }); }); var edgesItem = Array.isArray(edgesSelection) ? edgesSelection[0] : null; var nodeSelections = edgesItem != null && typeof edgesItem === 'object' && edgesItem.nodeSelections instanceof Map ? edgesItem.nodeSelections : null; if (nodeSelections == null) { throw createUserError('Cannot generate flow types for connection field, expected an edges ' + 'selection.', [node.loc]); } var edgesFields = Array.from(nodeSelections.values()); var edgesType = selectionsToBabel(schema, [edgesFields], state, false); return [{ key: '__connection', conditional: true, value: t.genericTypeAnnotation(t.identifier('ConnectionReference'), t.typeParameterInstantiation([edgesType])) }]; } function visitLinkedField(node) { return [{ key: node.alias, schemaName: node.name, nodeType: node.type, nodeSelections: selectionsToMap(flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections), /* * append concreteType to key so overlapping fields with different * concreteTypes don't get overwritten by each other */ true) }]; } function makeRawResponseProp(schema, _ref2, state, concreteType) { var key = _ref2.key, schemaName = _ref2.schemaName, value = _ref2.value, conditional = _ref2.conditional, nodeType = _ref2.nodeType, nodeSelections = _ref2.nodeSelections, kind = _ref2.kind; if (kind === 'ModuleImport') { return t.objectTypeSpreadProperty(t.genericTypeAnnotation(t.identifier(key))); } if (schemaName === '__typename' && concreteType) { value = t.stringLiteralTypeAnnotation(concreteType); } else if (nodeType) { value = transformScalarType(schema, nodeType, state, selectionsToRawResponseBabel(schema, [Array.from(nullthrows(nodeSelections).values())], state, schema.isAbstractType(nodeType) || schema.isWrapper(nodeType) ? null : schema.getTypeString(nodeType))); } var typeProperty = readOnlyObjectTypeProperty(key, value); if (conditional) { typeProperty.optional = true; } return typeProperty; } // Trasform the codegen IR selections into Babel flow types function selectionsToRawResponseBabel(schema, selections, state, nodeTypeName) { var baseFields = []; var byConcreteType = {}; flattenArray(selections).forEach(function (selection) { var concreteType = selection.concreteType; if (concreteType) { var _byConcreteType$concr2; byConcreteType[concreteType] = (_byConcreteType$concr2 = byConcreteType[concreteType]) !== null && _byConcreteType$concr2 !== void 0 ? _byConcreteType$concr2 : []; byConcreteType[concreteType].push(selection); } else { baseFields.push(selection); } }); var types = []; if (Object.keys(byConcreteType).length) { var baseFieldsMap = selectionsToMap(baseFields); var _loop2 = function _loop2(concreteType) { var mergedSeletions = Array.from(mergeSelections(baseFieldsMap, selectionsToMap(byConcreteType[concreteType]), false).values()); var moduleImport = mergedSeletions.find(function (sel) { return sel.kind === 'ModuleImport'; }); if (moduleImport) { types.push(exactObjectTypeAnnotation(mergedSeletions.map(function (selection) { return makeRawResponseProp(schema, selection, state, concreteType); }))); // Generate an extra opaque type for client 3D fields state.runtimeImports.add('Local3DPayload'); types.push(t.genericTypeAnnotation(t.identifier('Local3DPayload'), t.typeParameterInstantiation([t.stringLiteralTypeAnnotation(moduleImport.documentName), exactObjectTypeAnnotation(mergedSeletions.filter(function (sel) { return sel.schemaName !== 'js'; }).map(function (selection) { return makeRawResponseProp(schema, selection, state, concreteType); }))]))); } else { types.push(exactObjectTypeAnnotation(mergedSeletions.map(function (selection) { return makeRawResponseProp(schema, selection, state, concreteType); }))); } }; for (var concreteType in byConcreteType) { _loop2(concreteType); } } if (baseFields.length) { types.push(exactObjectTypeAnnotation(baseFields.map(function (selection) { return makeRawResponseProp(schema, selection, state, isTypenameSelection(selection) ? nodeTypeName : null); }))); } return unionTypeAnnotation(types); } // Visitor for generating raw response type function createRawResponseTypeVisitor(schema, state) { var visitor = { leave: { Root: function Root(node) { return exportType("".concat(node.name, "RawResponse"), selectionsToRawResponseBabel(schema, /* $FlowFixMe: selections have already been transformed */ node.selections, state, null)); }, InlineFragment: function InlineFragment(node) { var typeCondition = node.typeCondition; return flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections).map(function (typeSelection) { return schema.isAbstractType(typeCondition) ? typeSelection : (0, _objectSpread2["default"])({}, typeSelection, { concreteType: schema.getTypeString(typeCondition) }); }); }, ScalarField: function ScalarField(node) { return visitScalarField(schema, node, state); }, Connection: function Connection(node) { return visitConnection(schema, node, state); }, ClientExtension: function ClientExtension(node) { return flattenArray( /* $FlowFixMe: selections have already been transformed */ node.selections).map(function (sel) { return (0, _objectSpread2["default"])({}, sel, { conditional: true }); }); }, ConnectionField: visitLinkedField, LinkedField: visitLinkedField, Condition: visitNodeWithSelectionsOnly, Defer: visitNodeWithSelectionsOnly, Stream: visitNodeWithSelectionsOnly, ModuleImport: function ModuleImport(node) { return visitRawResposneModuleImport(schema, node, state); }, FragmentSpread: function FragmentSpread(node) { true ? true ? invariant(false, 'A fragment spread is found when traversing the AST, ' + 'make sure you are passing the codegen IR') : undefined : undefined; } } }; return visitor; } // Dedupe the generated type of module selections to reduce file size function visitRawResposneModuleImport(schema, node, state) { var selections = node.selections, key = node.name; var moduleSelections = selections.filter( // $FlowFixMe selections have already been transformed function (sel) { return sel.length && sel[0].schemaName === 'js'; }).map(function (arr) { return arr[0]; }); if (!state.matchFields.has(key)) { var ast = selectionsToRawResponseBabel(schema, /* $FlowFixMe: selections have already been transformed */ node.selections.filter(function (sel) { return sel.length > 1 || sel[0].schemaName !== 'js'; }), state, null); state.matchFields.set(key, ast); } return [].concat((0, _toConsumableArray2["default"])(moduleSelections), [{ key: key, kind: 'ModuleImport', documentName: node.documentName }]); } function selectionsToMap(selections, appendType) { var map = new Map(); selections.forEach(function (selection) { var key = appendType && selection.concreteType ? "".concat(selection.key, "::").concat(selection.concreteType) : selection.key; var previousSel = map.get(key); map.set(key, previousSel ? mergeSelection(previousSel, selection) : selection); }); return map; } function flattenArray(arrayOfArrays) { var result = []; arrayOfArrays.forEach(function (array) { result.push.apply(result, (0, _toConsumableArray2["default"])(array)); }); return result; } function generateInputObjectTypes(state) { return Object.keys(state.generatedInputObjectTypes).map(function (typeIdentifier) { var inputObjectType = state.generatedInputObjectTypes[typeIdentifier]; !(typeof inputObjectType !== 'string') ? true ? invariant(false, 'RelayCompilerFlowGenerator: Expected input object type to have been' + ' defined before calling `generateInputObjectTypes`') : undefined : void 0; return exportType(typeIdentifier, inputObjectType); }); } function generateInputVariablesType(schema, node, state) { return exportType("".concat(node.name, "Variables"), exactObjectTypeAnnotation(node.argumentDefinitions.map(function (arg) { var property = t.objectTypeProperty(t.identifier(arg.name), transformInputType(schema, arg.type, state)); if (!schema.isNonNull(arg.type)) { property.optional = true; } return property; }))); } function groupRefs(props) { var result = []; var refs = []; props.forEach(function (prop) { if (prop.ref) { refs.push(prop.ref); } else { result.push(prop); } }); if (refs.length > 0) { var value = intersectionTypeAnnotation(refs.map(function (ref) { return t.genericTypeAnnotation(t.identifier(getOldFragmentTypeName(ref))); })); result.push({ key: '$fragmentRefs', conditional: false, value: value }); } return result; } function getFragmentImports(state) { var imports = []; if (state.usedFragments.size > 0) { var usedFragments = Array.from(state.usedFragments).sort(); var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = usedFragments[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var usedFragment = _step4.value; var fragmentTypeName = getOldFragmentTypeName(usedFragment); if (!state.generatedFragments.has(usedFragment)) { if (state.useHaste && state.existingFragmentNames.has(usedFragment)) { // TODO(T22653277) support non-haste environments when importing // fragments imports.push(importTypes([fragmentTypeName], usedFragment + '.graphql')); } else if (state.useSingleArtifactDirectory && state.existingFragmentNames.has(usedFragment)) { imports.push(importTypes([fragmentTypeName], './' + usedFragment + '.graphql')); } else { imports.push(anyTypeAlias(fragmentTypeName)); } } } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) { _iterator4["return"](); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } } return imports; } function getEnumDefinitions(schema, _ref3) { var enumsHasteModule = _ref3.enumsHasteModule, usedEnums = _ref3.usedEnums, noFutureProofEnums = _ref3.noFutureProofEnums; var enumNames = Object.keys(usedEnums).sort(); if (enumNames.length === 0) { return []; } if (typeof enumsHasteModule === 'string') { return [importTypes(enumNames, enumsHasteModule)]; } if (typeof enumsHasteModule === 'function') { return enumNames.map(function (enumName) { return importTypes([enumName], enumsHasteModule(enumName)); }); } return enumNames.map(function (name) { var values = [].concat(schema.getEnumValues(usedEnums[name])); values.sort(); if (!noFutureProofEnums) { values.push('%future added value'); } return exportType(name, t.unionTypeAnnotation(values.map(function (value) { return t.stringLiteralTypeAnnotation(value); }))); }); } // If it's a @refetchable fragment, we generate the $fragmentRef in generated // query, and import it in the fragment to avoid circular dependencies function getRefetchableQueryParentFragmentName(state, metadata) { if (!(metadata === null || metadata === void 0 ? void 0 : metadata.isRefetchableQuery) || !state.useHaste && !state.useSingleArtifactDirectory) { return null; } var derivedFrom = metadata === null || metadata === void 0 ? void 0 : metadata.derivedFrom; if (derivedFrom != null && typeof derivedFrom === 'string') { return derivedFrom; } return null; } function getRefetchableQueryPath(state, directives) { var _directives$find; var refetchableQuery; if (!state.useHaste && !state.useSingleArtifactDirectory) { return; } var refetchableArgs = (_directives$find = directives.find(function (d) { return d.name === 'refetchable'; })) === null || _directives$find === void 0 ? void 0 : _directives$find.args; if (!refetchableArgs) { return; } var argument = refetchableArgs.find(function (arg) { return arg.kind === 'Argument' && arg.name === 'queryName'; }); if (argument && argument.value && argument.value.kind === 'Literal' && typeof argument.value.value === 'string') { refetchableQuery = argument.value.value; if (!state.useHaste) { refetchableQuery = './' + refetchableQuery; } refetchableQuery += '.graphql'; } return refetchableQuery; } function generateFragmentRefsForRefetchable(name) { var oldFragmentTypeName = getOldFragmentTypeName(name); var newFragmentTypeName = getNewFragmentTypeName(name); return [declareExportOpaqueType(oldFragmentTypeName, 'FragmentReference'), declareExportOpaqueType(newFragmentTypeName, oldFragmentTypeName)]; } function getFragmentTypes(name, refetchableQueryPath) { var oldFragmentTypeName = getOldFragmentTypeName(name); var newFragmentTypeName = getNewFragmentTypeName(name); if (refetchableQueryPath) { return [importTypes([oldFragmentTypeName, newFragmentTypeName], refetchableQueryPath), exportTypes([oldFragmentTypeName, newFragmentTypeName])]; } return [declareExportOpaqueType(oldFragmentTypeName, 'FragmentReference'), declareExportOpaqueType(newFragmentTypeName, oldFragmentTypeName)]; } function getOldFragmentTypeName(name) { return "".concat(name, "$ref"); } function getNewFragmentTypeName(name) { return "".concat(name, "$fragmentType"); } function getRefTypeName(name) { return "".concat(name, "$key"); } function getDataTypeName(name) { return "".concat(name, "$data"); } var FLOW_TRANSFORMS = [RelayDirectiveTransform.transform, MaskTransform.transform, ConnectionFieldTransform.transform, MatchTransform.transform, FlattenTransform.transformWithOptions({}), RefetchableFragmentTransform.transform]; var DIRECTIVE_NAME = 'raw_response_type'; module.exports = { generate: Profiler.instrument(generate, 'RelayFlowGenerator.generate'), transforms: FLOW_TRANSFORMS, SCHEMA_EXTENSION: "directive @".concat(DIRECTIVE_NAME, " on QUERY | MUTATION | SUBSCRIPTION") }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var invariant = __webpack_require__(4); var t = __webpack_require__(22); /** * type NAME = any; */ function anyTypeAlias(name) { return t.typeAlias(t.identifier(name), null, t.anyTypeAnnotation()); } /** * {| * PROPS * |} */ function exactObjectTypeAnnotation(props) { var typeAnnotation = t.objectTypeAnnotation(props); typeAnnotation.exact = true; return typeAnnotation; } /** * export type NAME = TYPE */ function exportType(name, type) { return t.exportNamedDeclaration(t.typeAlias(t.identifier(name), null, type), [], null); } /** * export type {A, B, C} */ function exportTypes(names) { var res = t.exportNamedDeclaration(null, names.map(function (name) { return t.exportSpecifier(t.identifier(name), t.identifier(name)); }), null); res.exportKind = 'type'; return res; } /** * declare export type NAME = VALUE */ function declareExportOpaqueType(name, value) { return t.declareExportDeclaration(t.declareOpaqueType(t.identifier(name), null, t.genericTypeAnnotation(t.identifier(value)))); } /** * import type {NAMES[0], NAMES[1], ...} from 'MODULE'; */ function importTypes(names, module) { var importDeclaration = t.importDeclaration(names.map(function (name) { return t.importSpecifier(t.identifier(name), t.identifier(name)); }), t.stringLiteral(module)); importDeclaration.importKind = 'type'; return importDeclaration; } /** * Create an intersection type if needed. * * TYPES[0] & TYPES[1] & ... */ function intersectionTypeAnnotation(types) { !(types.length > 0) ? true ? invariant(false, 'RelayFlowBabelFactories: cannot create an intersection of 0 types') : undefined : void 0; return types.length === 1 ? types[0] : t.intersectionTypeAnnotation(types); } function lineComments() { for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { lines[_key] = arguments[_key]; } return lines.map(function (line) { return { type: 'CommentLine', value: ' ' + line }; }); } /** * $ReadOnlyArray */ function readOnlyArrayOfType(thing) { return t.genericTypeAnnotation(t.identifier('$ReadOnlyArray'), t.typeParameterInstantiation([thing])); } /** * +KEY: VALUE */ function readOnlyObjectTypeProperty(key, value) { var prop = t.objectTypeProperty(t.identifier(key), value); prop.variance = t.variance('plus'); return prop; } function stringLiteralTypeAnnotation(value) { return t.stringLiteralTypeAnnotation(value); } /** * Create a union type if needed. * * TYPES[0] | TYPES[1] | ... */ function unionTypeAnnotation(types) { !(types.length > 0) ? true ? invariant(false, 'RelayFlowBabelFactories: cannot create a union of 0 types') : undefined : void 0; return types.length === 1 ? types[0] : t.unionTypeAnnotation(types); } module.exports = { anyTypeAlias: anyTypeAlias, declareExportOpaqueType: declareExportOpaqueType, exactObjectTypeAnnotation: exactObjectTypeAnnotation, exportType: exportType, exportTypes: exportTypes, importTypes: importTypes, intersectionTypeAnnotation: intersectionTypeAnnotation, lineComments: lineComments, readOnlyArrayOfType: readOnlyArrayOfType, readOnlyObjectTypeProperty: readOnlyObjectTypeProperty, stringLiteralTypeAnnotation: stringLiteralTypeAnnotation, unionTypeAnnotation: unionTypeAnnotation }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var invariant = __webpack_require__(4); var _require = __webpack_require__(1), eachWithCombinedError = _require.eachWithCombinedError; /** * @public * * Helper for writing AST validators that shares the same logic with * the transfomer * */ function validate(context, visitor, stateInitializer) { var validator = new Validator(context, visitor); eachWithCombinedError(context.documents(), function (prevNode) { if (stateInitializer === undefined) { validator.visit(prevNode, undefined); } else { var _state = stateInitializer(prevNode); if (_state != null) { validator.visit(prevNode, _state); } } }); } /** * @internal */ var Validator = /*#__PURE__*/ function () { function Validator(context, visitor) { this._context = context; this._states = []; this._visitor = visitor; } var _proto = Validator.prototype; _proto.getContext = function getContext() { return this._context; }; _proto.visit = function visit(node, state) { this._states.push(state); this._visit(node); this._states.pop(); }; _proto.traverse = function traverse(node, state) { this._states.push(state); this._traverse(node); this._states.pop(); }; _proto._visit = function _visit(node) { var nodeVisitor = this._visitor[node.kind]; if (nodeVisitor) { // If a handler for the kind is defined, it is responsible for calling // `traverse` to transform children as necessary. var _state2 = this._getState(); nodeVisitor.call(this, node, _state2); return; } // Otherwise traverse is called automatically. this._traverse(node); }; _proto._traverse = function _traverse(prevNode) { switch (prevNode.kind) { case 'Argument': this._traverseChildren(prevNode, null, ['value']); break; case 'Literal': case 'LocalArgumentDefinition': case 'RootArgumentDefinition': case 'Variable': break; case 'Defer': this._traverseChildren(prevNode, ['selections'], ['if']); break; case 'Stream': this._traverseChildren(prevNode, ['selections'], ['if', 'initialCount']); break; case 'ClientExtension': this._traverseChildren(prevNode, ['selections']); break; case 'Directive': this._traverseChildren(prevNode, ['args']); break; case 'ModuleImport': this._traverseChildren(prevNode, ['selections']); break; case 'FragmentSpread': case 'ScalarField': this._traverseChildren(prevNode, ['args', 'directives']); break; case 'InlineDataFragmentSpread': this._traverseChildren(prevNode, ['selections']); break; case 'ConnectionField': case 'LinkedField': this._traverseChildren(prevNode, ['args', 'directives', 'selections']); break; case 'Connection': this._traverseChildren(prevNode, ['args', 'selections']); break; case 'Condition': this._traverseChildren(prevNode, ['directives', 'selections'], ['condition']); break; case 'InlineFragment': this._traverseChildren(prevNode, ['directives', 'selections']); break; case 'Fragment': case 'Root': this._traverseChildren(prevNode, ['argumentDefinitions', 'directives', 'selections']); break; case 'Request': this._traverseChildren(prevNode, null, ['fragment', 'root']); break; case 'SplitOperation': this._traverseChildren(prevNode, ['selections']); break; default: prevNode; true ? true ? invariant(false, 'GraphQLIRValidator: Unknown kind `%s`.', prevNode.kind) : undefined : undefined; } }; _proto._traverseChildren = function _traverseChildren(prevNode, pluralKeys, singularKeys) { var _this = this; pluralKeys && pluralKeys.forEach(function (key) { var prevItems = prevNode[key]; if (!prevItems) { return; } !Array.isArray(prevItems) ? true ? invariant(false, 'GraphQLIRValidator: Expected data for `%s` to be an array, got `%s`.', key, prevItems) : undefined : void 0; prevItems.forEach(function (prevItem) { return _this._visit(prevItem); }); }); singularKeys && singularKeys.forEach(function (key) { var prevItem = prevNode[key]; if (!prevItem) { return; } _this._visit(prevItem); }); }; _proto._getState = function _getState() { !this._states.length ? true ? invariant(false, 'GraphQLIRValidator: Expected a current state to be set but found none. ' + 'This is usually the result of mismatched number of pushState()/popState() ' + 'calls.') : undefined : void 0; return this._states[this._states.length - 1]; }; return Validator; }(); module.exports = { validate: validate }; /***/ }), /* 47 */ /***/ (function(module, exports) { module.exports = require("util"); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var yargs = __webpack_require__(49); var _require = __webpack_require__(50), main = _require.main; var RelayConfig; try { // eslint-disable-next-line no-eval RelayConfig = eval('require')('relay-config'); // eslint-disable-next-line lint/no-unused-catch-bindings } catch (_) {} var options = { schema: { describe: 'Path to schema.graphql or schema.json', demandOption: true, type: 'string', array: false }, src: { describe: 'Root directory of application code', demandOption: true, type: 'string', array: false }, include: { describe: 'Directories to include under src', type: 'string', array: true, "default": ['**'] }, exclude: { describe: 'Directories to ignore under src', type: 'string', array: true, "default": ['**/node_modules/**', '**/__mocks__/**', '**/__generated__/**'] }, extensions: { array: true, describe: 'File extensions to compile (defaults to extensions provided by the ' + 'language plugin)', type: 'string' }, verbose: { describe: 'More verbose logging', type: 'boolean', "default": false }, quiet: { describe: 'No output to stdout', type: 'boolean', "default": false }, watchman: { describe: 'Use watchman when not in watch mode', type: 'boolean', "default": true }, watch: { describe: 'If specified, watches files and regenerates on changes', type: 'boolean', "default": false }, validate: { describe: 'Looks for pending changes and exits with non-zero code instead of ' + 'writing to disk', type: 'boolean', "default": false }, persistFunction: { describe: 'An async function (or path to a module exporting this function) which will persist the query text and return the id.', demandOption: false, type: 'string', array: false }, persistOutput: { describe: 'A path to a .json file where persisted query metadata should be saved. Will use the default implementation (md5 hash) if `persistFunction` is not passed.', demandOption: false, type: 'string', array: false }, noFutureProofEnums: { describe: 'This option controls whether or not a catch-all entry is added to enum type definitions ' + 'for values that may be added in the future. Enabling this means you will have to update ' + 'your application whenever the GraphQL server schema adds new enum values to prevent it ' + 'from breaking.', type: 'boolean', "default": false }, language: { describe: 'The name of the language plugin used for input files and artifacts', demandOption: false, type: 'string', array: false, "default": 'javascript' }, artifactDirectory: { describe: 'A specific directory to output all artifacts to. When enabling this ' + 'the babel plugin needs `artifactDirectory` set as well.', demandOption: false, type: 'string', array: false }, customScalars: { describe: 'Mappings from custom scalars in your schema to built-in GraphQL ' + 'types, for type emission purposes. (Uses yargs dot-notation, e.g. ' + '--customScalars.URL=String)', type: 'object' } }; // Load external config var config = RelayConfig && RelayConfig.loadConfig(); // Parse CLI args var argv = yargs.usage('Create Relay generated files\n\n' + '$0 --schema --src [--watch]') // $FlowFixMe - TODO @alloy (OSS): Fix non-existent 'object' type for parsing customScalars config .options(options) // Apply externally loaded config through the yargs API so that we can leverage yargs' defaults and have them show up // in the help banner. .config(config).help().argv; // Start the application main(argv)["catch"](function (error) { console.error(String(error.stack || error)); process.exit(1); }); /***/ }), /* 49 */ /***/ (function(module, exports) { module.exports = require("yargs"); /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _asyncToGenerator = __webpack_require__(10); var _defineProperty2 = _interopRequireDefault(__webpack_require__(23)); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var CodegenRunner = __webpack_require__(51); var ConsoleReporter = __webpack_require__(58); var DotGraphQLParser = __webpack_require__(60); var RelayFileWriter = __webpack_require__(61); var RelayIRTransforms = __webpack_require__(72); var RelayLanguagePluginJavaScript = __webpack_require__(104); var RelaySourceModuleParser = __webpack_require__(108); var WatchmanClient = __webpack_require__(18); var crypto = __webpack_require__(12); var fs = __webpack_require__(13); var invariant = __webpack_require__(4); var path = __webpack_require__(8); var _require = __webpack_require__(7), buildClientSchema = _require.buildClientSchema, Source = _require.Source, printSchema = _require.printSchema; var commonTransforms = RelayIRTransforms.commonTransforms, codegenTransforms = RelayIRTransforms.codegenTransforms, fragmentTransforms = RelayIRTransforms.fragmentTransforms, printTransforms = RelayIRTransforms.printTransforms, queryTransforms = RelayIRTransforms.queryTransforms, schemaExtensions = RelayIRTransforms.schemaExtensions; function buildWatchExpression(config) { return ['allof', ['type', 'f'], ['anyof'].concat((0, _toConsumableArray2["default"])(config.extensions.map(function (ext) { return ['suffix', ext]; }))), ['anyof'].concat((0, _toConsumableArray2["default"])(config.include.map(function (include) { return ['match', include, 'wholename']; })))].concat((0, _toConsumableArray2["default"])(config.exclude.map(function (exclude) { return ['not', ['match', exclude, 'wholename']]; }))); } function getFilepathsFromGlob(baseDir, config) { var extensions = config.extensions, include = config.include, exclude = config.exclude; var patterns = include.map(function (inc) { return "".concat(inc, "/*.+(").concat(extensions.join('|'), ")"); }); var glob = __webpack_require__(113); return glob.sync(patterns, { cwd: baseDir, ignore: exclude }); } /** * Unless the requested plugin is the builtin `javascript` one, import a * language plugin as either a CommonJS or ES2015 module. * * When importing, first check if it’s a path to an existing file, otherwise * assume it’s a package and prepend the plugin namespace prefix. * * Make sure to always use Node's `require` function, which otherwise would get * replaced with `__webpack_require__` when bundled using webpack, by using * `eval` to get it at runtime. */ function getLanguagePlugin(language) { if (language === 'javascript') { return RelayLanguagePluginJavaScript(); } else { var languagePlugin; if (typeof language === 'string') { var pluginPath = path.resolve(process.cwd(), language); var requirePath = fs.existsSync(pluginPath) ? pluginPath : "relay-compiler-language-".concat(language); try { // eslint-disable-next-line no-eval languagePlugin = eval('require')(requirePath); if (languagePlugin["default"]) { languagePlugin = languagePlugin["default"]; } } catch (err) { var e = new Error("Unable to load language plugin ".concat(requirePath, ": ").concat(err.message)); e.stack = err.stack; throw e; } } else { languagePlugin = language; } if (languagePlugin["default"] != null) { // $FlowFixMe - Flow no longer considers statics of functions as any languagePlugin = languagePlugin["default"]; } if (typeof languagePlugin === 'function') { // $FlowFixMe return languagePlugin(); } else { throw new Error('Expected plugin to be a initializer function.'); } } } function getPersistQueryFunction(config) { var configValue = config.persistFunction; if (configValue == null) { return null; } else if (typeof configValue === 'string') { try { // eslint-disable-next-line no-eval var persistFunction = eval('require')(path.resolve(process.cwd(), configValue)); if (persistFunction["default"]) { return persistFunction["default"]; } return persistFunction; } catch (err) { var e = new Error("Unable to load persistFunction ".concat(configValue, ": ").concat(err.message)); e.stack = err.stack; throw e; } } else if (typeof configValue === 'function') { return configValue; } else { throw new Error('Expected persistFunction to be a path string or a function.'); } } function main(_x) { return _main.apply(this, arguments); } function _main() { _main = _asyncToGenerator(function* (defaultConfig) { if (defaultConfig.verbose && defaultConfig.quiet) { throw new Error("I can't be quiet and verbose at the same time"); } var config = getPathBasedConfig(defaultConfig); config = yield getWatchConfig(config); // Use function from module.exports to be able to mock it for tests var codegenRunner = module.exports.getCodegenRunner(config); var result = config.watch ? yield codegenRunner.watchAll() : yield codegenRunner.compileAll(); if (result === 'ERROR') { process.exit(100); } if (config.validate && result !== 'NO_CHANGES') { process.exit(101); } }); return _main.apply(this, arguments); } function getPathBasedConfig(config) { var schema = path.resolve(process.cwd(), config.schema); if (!fs.existsSync(schema)) { throw new Error("--schema path does not exist: ".concat(schema)); } var src = path.resolve(process.cwd(), config.src); if (!fs.existsSync(src)) { throw new Error("--src path does not exist: ".concat(src)); } var persistOutput = config.persistOutput; if (typeof persistOutput === 'string') { persistOutput = path.resolve(process.cwd(), persistOutput); var persistOutputDir = path.dirname(persistOutput); if (!fs.existsSync(persistOutputDir)) { throw new Error("--persistOutput path does not exist: ".concat(persistOutput)); } } return (0, _objectSpread2["default"])({}, config, { schema: schema, src: src, persistOutput: persistOutput }); } function getWatchConfig(_x2) { return _getWatchConfig.apply(this, arguments); } function _getWatchConfig() { _getWatchConfig = _asyncToGenerator(function* (config) { var watchman = config.watchman && (yield WatchmanClient.isAvailable()); if (config.watch) { if (!watchman) { throw new Error('Watchman is required to watch for changes.'); } if (!module.exports.hasWatchmanRootFile(config.src)) { throw new Error("\n--watch requires that the src directory have a valid watchman \"root\" file.\n\nRoot files can include:\n- A .git/ Git folder\n- A .hg/ Mercurial folder\n- A .watchmanconfig file\n\nEnsure that one such file exists in ".concat(config.src, " or its parents.\n ").trim()); } } else if (watchman && !config.validate) { // eslint-disable-next-line no-console console.log('HINT: pass --watch to keep watching for changes.'); } return (0, _objectSpread2["default"])({}, config, { watchman: watchman }); }); return _getWatchConfig.apply(this, arguments); } function getCodegenRunner(config) { var _artifactDirectory, _parserConfigs; var reporter = new ConsoleReporter({ verbose: config.verbose, quiet: config.quiet }); var schema = getSchemaSource(config.schema); var languagePlugin = getLanguagePlugin(config.language); var persistQueryFunction = getPersistQueryFunction(config); var inputExtensions = config.extensions || languagePlugin.inputExtensions; var outputExtension = languagePlugin.outputExtension; var sourceParserName = inputExtensions.join('/'); var sourceWriterName = outputExtension; var sourceModuleParser = RelaySourceModuleParser(languagePlugin.findGraphQLTags); var providedArtifactDirectory = config.artifactDirectory; var artifactDirectory = providedArtifactDirectory != null ? path.resolve(process.cwd(), providedArtifactDirectory) : null; var generatedDirectoryName = (_artifactDirectory = artifactDirectory) !== null && _artifactDirectory !== void 0 ? _artifactDirectory : '__generated__'; var sourceSearchOptions = { extensions: inputExtensions, include: config.include, exclude: ['**/*.graphql.*'].concat((0, _toConsumableArray2["default"])(config.exclude)) }; var graphqlSearchOptions = { extensions: ['graphql'], include: config.include, exclude: [path.relative(config.src, config.schema)].concat(config.exclude) }; var parserConfigs = (_parserConfigs = {}, (0, _defineProperty2["default"])(_parserConfigs, sourceParserName, { baseDir: config.src, getFileFilter: sourceModuleParser.getFileFilter, getParser: sourceModuleParser.getParser, getSchemaSource: function getSchemaSource() { return schema; }, schemaExtensions: schemaExtensions, watchmanExpression: config.watchman ? buildWatchExpression(sourceSearchOptions) : null, filepaths: config.watchman ? null : getFilepathsFromGlob(config.src, sourceSearchOptions) }), (0, _defineProperty2["default"])(_parserConfigs, "graphql", { baseDir: config.src, getParser: DotGraphQLParser.getParser, getSchemaSource: function getSchemaSource() { return schema; }, schemaExtensions: schemaExtensions, watchmanExpression: config.watchman ? buildWatchExpression(graphqlSearchOptions) : null, filepaths: config.watchman ? null : getFilepathsFromGlob(config.src, graphqlSearchOptions) }), _parserConfigs); var writerConfigs = (0, _defineProperty2["default"])({}, sourceWriterName, { writeFiles: getRelayFileWriter(config.src, languagePlugin, config.noFutureProofEnums, artifactDirectory, config.persistOutput, config.customScalars, persistQueryFunction), isGeneratedFile: function isGeneratedFile(filePath) { return filePath.endsWith('.graphql.' + outputExtension) && filePath.includes(generatedDirectoryName); }, parser: sourceParserName, baseParsers: ['graphql'] }); var codegenRunner = new CodegenRunner({ reporter: reporter, parserConfigs: parserConfigs, writerConfigs: writerConfigs, onlyValidate: config.validate, // TODO: allow passing in a flag or detect? sourceControl: null }); return codegenRunner; } function defaultPersistFunction(text) { var hasher = crypto.createHash('md5'); hasher.update(text); var id = hasher.digest('hex'); return Promise.resolve(id); } function getRelayFileWriter(baseDir, languagePlugin, noFutureProofEnums, outputDir, persistedQueryPath, customScalars, persistFunction) { return ( /*#__PURE__*/ function () { var _ref2 = _asyncToGenerator(function* (_ref) { var onlyValidate = _ref.onlyValidate, schema = _ref.schema, documents = _ref.documents, baseDocuments = _ref.baseDocuments, sourceControl = _ref.sourceControl, reporter = _ref.reporter; var persistQuery; var queryMap; if (persistFunction != null || persistedQueryPath != null) { queryMap = new Map(); var persistImplmentation = persistFunction || defaultPersistFunction; persistQuery = /*#__PURE__*/ function () { var _persistQuery = _asyncToGenerator(function* (text) { var id = yield persistImplmentation(text); !(typeof id === 'string') ? true ? invariant(false, 'Expected persist function to return a string, got `%s`.', id) : undefined : void 0; queryMap.set(id, text); return id; }); function persistQuery(_x4) { return _persistQuery.apply(this, arguments); } return persistQuery; }(); } var results = yield RelayFileWriter.writeAll({ config: { baseDir: baseDir, compilerTransforms: { commonTransforms: commonTransforms, codegenTransforms: codegenTransforms, fragmentTransforms: fragmentTransforms, printTransforms: printTransforms, queryTransforms: queryTransforms }, customScalars: customScalars || {}, formatModule: languagePlugin.formatModule, optionalInputFieldsForFlow: [], schemaExtensions: schemaExtensions, useHaste: false, noFutureProofEnums: noFutureProofEnums, extension: languagePlugin.outputExtension, typeGenerator: languagePlugin.typeGenerator, outputDir: outputDir, persistQuery: persistQuery }, onlyValidate: onlyValidate, schema: schema, baseDocuments: baseDocuments, documents: documents, reporter: reporter, sourceControl: sourceControl }); if (queryMap != null && persistedQueryPath != null) { var object = {}; if (fs.existsSync(persistedQueryPath)) { try { var prevText = fs.readFileSync(persistedQueryPath, 'utf8'); var prevData = JSON.parse(prevText); if (prevData != null && typeof prevData === 'object') { object = prevData; } else { console.error("Invalid data in persisted query file '".concat(persistedQueryPath, "', expected an object.")); } } catch (error) { console.error(error); } } var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = queryMap.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _step.value, id = _step$value[0], _text = _step$value[1]; object[id] = _text; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var data = JSON.stringify(object, null, 2); fs.writeFileSync(persistedQueryPath, data, 'utf8'); } return results; }); return function (_x3) { return _ref2.apply(this, arguments); }; }() ); } function getSchemaSource(schemaPath) { var source = fs.readFileSync(schemaPath, 'utf8'); if (path.extname(schemaPath) === '.json') { source = printSchema(buildClientSchema(JSON.parse(source).data)); } source = "\n directive @include(if: Boolean) on FRAGMENT_SPREAD | FIELD | INLINE_FRAGMENT\n directive @skip(if: Boolean) on FRAGMENT_SPREAD | FIELD | INLINE_FRAGMENT\n\n ".concat(source, "\n "); return new Source(source, schemaPath); } // Ensure that a watchman "root" file exists in the given directory // or a parent so that it can be watched var WATCHMAN_ROOT_FILES = ['.git', '.hg', '.watchmanconfig']; function hasWatchmanRootFile(testPath) { while (path.dirname(testPath) !== testPath) { if (WATCHMAN_ROOT_FILES.some(function (file) { return fs.existsSync(path.join(testPath, file)); })) { return true; } testPath = path.dirname(testPath); } return false; } module.exports = { getCodegenRunner: getCodegenRunner, getLanguagePlugin: getLanguagePlugin, getWatchConfig: getWatchConfig, hasWatchmanRootFile: hasWatchmanRootFile, main: main }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _asyncToGenerator = __webpack_require__(10); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var CodegenDirectory = __webpack_require__(24); var CodegenWatcher = __webpack_require__(52); var GraphQLWatchmanClient = __webpack_require__(18); var Profiler = __webpack_require__(6); var invariant = __webpack_require__(4); var path = __webpack_require__(8); var _require = __webpack_require__(55), createSchema = _require.create; // $FlowFixMe - importing immutable, which is untyped (and flow is sad about it) var _require2 = __webpack_require__(14), ImmutableMap = _require2.Map; var CodegenRunner = /*#__PURE__*/ function () { // parser => writers that are affected by it function CodegenRunner(options) { var _this = this; this.parsers = {}; this.parserConfigs = options.parserConfigs; this.writerConfigs = options.writerConfigs; this.onlyValidate = options.onlyValidate; this.onComplete = options.onComplete; this._reporter = options.reporter; this._sourceControl = options.sourceControl; this.parserWriters = {}; for (var _parser in options.parserConfigs) { this.parserWriters[_parser] = new Set(); } var _loop = function _loop(_writer) { var config = options.writerConfigs[_writer]; config.baseParsers && config.baseParsers.forEach(function (parser) { return _this.parserWriters[parser].add(_writer); }); _this.parserWriters[config.parser].add(_writer); }; for (var _writer in options.writerConfigs) { _loop(_writer); } } var _proto = CodegenRunner.prototype; _proto.compileAll = /*#__PURE__*/ function () { var _compileAll = _asyncToGenerator(function* () { // reset the parsers this.parsers = {}; for (var parserName in this.parserConfigs) { try { yield this.parseEverything(parserName); } catch (e) { this._reporter.reportError('CodegenRunner.compileAll', e); return 'ERROR'; } } var hasChanges = false; for (var writerName in this.writerConfigs) { var result = yield this.write(writerName); if (result === 'ERROR') { return 'ERROR'; } if (result === 'HAS_CHANGES') { hasChanges = true; } } return hasChanges ? 'HAS_CHANGES' : 'NO_CHANGES'; }); function compileAll() { return _compileAll.apply(this, arguments); } return compileAll; }(); _proto.compile = /*#__PURE__*/ function () { var _compile = _asyncToGenerator(function* (writerName) { var _this2 = this; var writerConfig = this.writerConfigs[writerName]; var parsers = [writerConfig.parser]; if (writerConfig.baseParsers) { writerConfig.baseParsers.forEach(function (parser) { return parsers.push(parser); }); } // Don't bother resetting the parsers yield Profiler.asyncContext('CodegenRunner:parseEverything', function () { return Promise.all(parsers.map(function (parser) { return _this2.parseEverything(parser); })); }); return yield this.write(writerName); }); function compile(_x) { return _compile.apply(this, arguments); } return compile; }(); _proto.getDirtyWriters = function getDirtyWriters(filePaths) { var _this3 = this; return Profiler.asyncContext('CodegenRunner:getDirtyWriters', /*#__PURE__*/ _asyncToGenerator(function* () { var dirtyWriters = new Set(); // Check if any files are in the output for (var configName in _this3.writerConfigs) { var config = _this3.writerConfigs[configName]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = filePaths[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _filePath = _step.value; if (config.isGeneratedFile(_filePath)) { dirtyWriters.add(configName); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } // Check for files in the input yield Promise.all(Object.keys(_this3.parserConfigs).map(function (parserConfigName) { return Profiler.waitFor('Watchman:query', /*#__PURE__*/ _asyncToGenerator(function* () { var client = new GraphQLWatchmanClient(); var config = _this3.parserConfigs[parserConfigName]; var dirs = yield client.watchProject(config.baseDir); var relativeFilePaths = filePaths.map(function (filePath) { return path.relative(config.baseDir, filePath); }); var query = { expression: ['allof', config.watchmanExpression, ['name', relativeFilePaths, 'wholename']], fields: ['exists'], relative_root: dirs.relativePath }; var result = yield client.command('query', dirs.root, query); client.end(); if (result.files.length > 0) { _this3.parserWriters[parserConfigName].forEach(function (writerName) { return dirtyWriters.add(writerName); }); } })); })); return dirtyWriters; })); }; _proto.parseEverything = /*#__PURE__*/ function () { var _parseEverything = _asyncToGenerator(function* (parserName) { if (this.parsers[parserName]) { // no need to parse return; } var parserConfig = this.parserConfigs[parserName]; this.parsers[parserName] = parserConfig.getParser(parserConfig.baseDir); var filter = parserConfig.getFileFilter ? parserConfig.getFileFilter(parserConfig.baseDir) : anyFileFilter; if (parserConfig.filepaths && parserConfig.watchmanExpression) { throw new Error('Provide either `watchmanExpression` or `filepaths` but not both.'); } var files; if (parserConfig.watchmanExpression) { files = yield CodegenWatcher.queryFiles(parserConfig.baseDir, parserConfig.watchmanExpression, filter); } else if (parserConfig.filepaths) { files = yield CodegenWatcher.queryFilepaths(parserConfig.baseDir, parserConfig.filepaths, filter); } else { throw new Error('Either `watchmanExpression` or `filepaths` is required to query files'); } this.parseFileChanges(parserName, files); }); function parseEverything(_x2) { return _parseEverything.apply(this, arguments); } return parseEverything; }(); _proto.parseFileChanges = function parseFileChanges(parserName, files) { var _this4 = this; return Profiler.run('CodegenRunner.parseFileChanges', function () { var parser = _this4.parsers[parserName]; // this maybe should be await parser.parseFiles(files); parser.parseFiles(files); }); } // We cannot do incremental writes right now. // When we can, this could be writeChanges(writerName, parserName, parsedDefinitions) ; _proto.write = function write(writerName) { var _this5 = this; return Profiler.asyncContext('CodegenRunner.write', /*#__PURE__*/ _asyncToGenerator(function* () { try { _this5._reporter.reportMessage("\nWriting ".concat(writerName)); var _this5$writerConfigs$ = _this5.writerConfigs[writerName], writeFiles = _this5$writerConfigs$.writeFiles, _parser2 = _this5$writerConfigs$.parser, baseParsers = _this5$writerConfigs$.baseParsers, isGeneratedFile = _this5$writerConfigs$.isGeneratedFile; var baseDocuments = ImmutableMap(); if (baseParsers) { baseParsers.forEach(function (baseParserName) { !(_this5.parsers[baseParserName] != null) ? true ? invariant(false, 'Trying to access an uncompiled base parser config: %s', baseParserName) : undefined : void 0; baseDocuments = baseDocuments.merge(_this5.parsers[baseParserName].documents()); }); } var _this5$parserConfigs$ = _this5.parserConfigs[_parser2], _baseDir = _this5$parserConfigs$.baseDir, generatedDirectoriesWatchmanExpression = _this5$parserConfigs$.generatedDirectoriesWatchmanExpression; var generatedDirectories = []; if (generatedDirectoriesWatchmanExpression) { var relativePaths = yield CodegenWatcher.queryDirectories(_baseDir, generatedDirectoriesWatchmanExpression); generatedDirectories = relativePaths.map(function (x) { return path.join(_baseDir, x); }); } // always create a new writer: we have to write everything anyways var documents = _this5.parsers[_parser2].documents(); var schema = Profiler.run('getSchema', function () { return createSchema(_this5.parserConfigs[_parser2].getSchemaSource(), baseDocuments.toArray(), _this5.parserConfigs[_parser2].schemaExtensions); }); var outputDirectories = yield writeFiles({ onlyValidate: _this5.onlyValidate, schema: schema, documents: documents, baseDocuments: baseDocuments, generatedDirectories: generatedDirectories, sourceControl: _this5._sourceControl, reporter: _this5._reporter }); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = outputDirectories.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var dir = _step2.value; var all = [].concat((0, _toConsumableArray2["default"])(dir.changes.created), (0, _toConsumableArray2["default"])(dir.changes.updated), (0, _toConsumableArray2["default"])(dir.changes.deleted), (0, _toConsumableArray2["default"])(dir.changes.unchanged)); var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = all[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var filename = _step3.value; var _filePath2 = dir.getPath(filename); !isGeneratedFile(_filePath2) ? true ? invariant(false, 'CodegenRunner: %s returned false for isGeneratedFile, ' + 'but was in generated directory', _filePath2) : undefined : void 0; } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { _iterator3["return"](); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } var onCompleteCallback = _this5.onComplete; if (onCompleteCallback != null) { onCompleteCallback(Array.from(outputDirectories.values())); } var combinedChanges = CodegenDirectory.combineChanges(Array.from(outputDirectories.values())); _this5._reporter.reportMessage(CodegenDirectory.formatChanges(combinedChanges, { onlyValidate: _this5.onlyValidate })); return CodegenDirectory.hasChanges(combinedChanges) ? 'HAS_CHANGES' : 'NO_CHANGES'; } catch (e) { _this5._reporter.reportError('CodegenRunner.write', e); return 'ERROR'; } })); }; _proto.watchAll = /*#__PURE__*/ function () { var _watchAll = _asyncToGenerator(function* () { // get everything set up for watching yield this.compileAll(); for (var parserName in this.parserConfigs) { yield this.watch(parserName); } }); function watchAll() { return _watchAll.apply(this, arguments); } return watchAll; }(); _proto.watch = /*#__PURE__*/ function () { var _watch = _asyncToGenerator(function* (parserName) { var _this6 = this; var parserConfig = this.parserConfigs[parserName]; if (!parserConfig.watchmanExpression) { throw new Error('`watchmanExpression` is required to watch files'); } // watchCompile starts with a full set of files as the changes // But as we need to set everything up due to potential parser dependencies, // we should prevent the first watch callback from doing anything. var firstChange = true; yield CodegenWatcher.watchCompile(parserConfig.baseDir, parserConfig.watchmanExpression, parserConfig.getFileFilter ? parserConfig.getFileFilter(parserConfig.baseDir) : anyFileFilter, /*#__PURE__*/ function () { var _ref4 = _asyncToGenerator(function* (files) { !(_this6.parsers[parserName] != null) ? true ? invariant(false, 'Trying to watch an uncompiled parser config: %s', parserName) : undefined : void 0; if (firstChange) { firstChange = false; return; } var dependentWriters = []; _this6.parserWriters[parserName].forEach(function (writer) { return dependentWriters.push(writer); }); try { if (!_this6.parsers[parserName]) { // have to load the parser and make sure all of its dependents are set yield _this6.parseEverything(parserName); } else { _this6.parseFileChanges(parserName, files); } yield Promise.all(dependentWriters.map(function (writer) { return _this6.write(writer); })); } catch (error) { _this6._reporter.reportError('CodegenRunner.watch', error); } _this6._reporter.reportMessage("Watching for changes to ".concat(parserName, "...")); }); return function (_x4) { return _ref4.apply(this, arguments); }; }()); this._reporter.reportMessage("Watching for changes to ".concat(parserName, "...")); }); function watch(_x3) { return _watch.apply(this, arguments); } return watch; }(); return CodegenRunner; }(); function anyFileFilter(file) { return true; } module.exports = CodegenRunner; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _asyncToGenerator = __webpack_require__(10); var GraphQLWatchmanClient = __webpack_require__(18); var Profiler = __webpack_require__(6); var crypto = __webpack_require__(12); var fs = __webpack_require__(13); var path = __webpack_require__(8); var SUBSCRIPTION_NAME = 'graphql-codegen'; var QUERY_RETRIES = 3; function queryFiles(_x, _x2, _x3) { return _queryFiles.apply(this, arguments); } function _queryFiles() { _queryFiles = _asyncToGenerator(function* (baseDir, expression, filter) { return yield Profiler.waitFor('Watchman:query', /*#__PURE__*/ _asyncToGenerator(function* () { var client = new GraphQLWatchmanClient(QUERY_RETRIES); var _ref = yield Promise.all([client.watchProject(baseDir), getFields(client)]), watchResp = _ref[0], fields = _ref[1]; var resp = yield client.command('query', watchResp.root, { expression: expression, fields: fields, relative_root: watchResp.relativePath }); client.end(); return updateFiles(new Set(), baseDir, filter, resp.files); })); }); return _queryFiles.apply(this, arguments); } function queryDirectories(_x4, _x5) { return _queryDirectories.apply(this, arguments); } function _queryDirectories() { _queryDirectories = _asyncToGenerator(function* (baseDir, expression) { return yield Profiler.waitFor('Watchman:query', /*#__PURE__*/ _asyncToGenerator(function* () { var client = new GraphQLWatchmanClient(); var watchResp = yield client.watchProject(baseDir); var resp = yield client.command('query', watchResp.root, { expression: expression, fields: ['name'], relative_root: watchResp.relativePath }); client.end(); return resp.files; })); }); return _queryDirectories.apply(this, arguments); } function getFields(_x6) { return _getFields.apply(this, arguments); } // For use when not using Watchman. function _getFields() { _getFields = _asyncToGenerator(function* (client) { var fields = ['name', 'exists']; if (yield client.hasCapability('field-content.sha1hex')) { fields.push('content.sha1hex'); } return fields; }); return _getFields.apply(this, arguments); } function queryFilepaths(_x7, _x8, _x9) { return _queryFilepaths.apply(this, arguments); } /** * Provides a simplified API to the watchman API. * Given some base directory and a list of subdirectories it calls the callback * with watchman change events on file changes. */ function _queryFilepaths() { _queryFilepaths = _asyncToGenerator(function* (baseDir, filepaths, filter) { // Construct WatchmanChange objects as an intermediate step before // calling updateFiles to produce file content. var files = filepaths.map(function (filepath) { return { name: filepath, exists: true, 'content.sha1hex': null }; }); return updateFiles(new Set(), baseDir, filter, files); }); return _queryFilepaths.apply(this, arguments); } function watch(_x10, _x11, _x12) { return _watch.apply(this, arguments); } function _watch() { _watch = _asyncToGenerator(function* (baseDir, expression, callback) { return yield Profiler.waitFor('Watchman:subscribe', /*#__PURE__*/ _asyncToGenerator(function* () { var client = new GraphQLWatchmanClient(); var watchResp = yield client.watchProject(baseDir); yield makeSubscription(client, watchResp.root, watchResp.relativePath, expression, callback); })); }); return _watch.apply(this, arguments); } function makeSubscription(_x13, _x14, _x15, _x16, _x17) { return _makeSubscription.apply(this, arguments); } /** * Further simplifies `watch` and calls the callback on every change with a * full list of files that match the conditions. */ function _makeSubscription() { _makeSubscription = _asyncToGenerator(function* (client, root, relativePath, expression, callback) { client.on('subscription', function (resp) { if (resp.subscription === SUBSCRIPTION_NAME) { callback(resp); } }); var fields = yield getFields(client); yield client.command('subscribe', root, SUBSCRIPTION_NAME, { expression: expression, fields: fields, relative_root: relativePath }); }); return _makeSubscription.apply(this, arguments); } function watchFiles(_x18, _x19, _x20, _x21) { return _watchFiles.apply(this, arguments); } /** * Similar to watchFiles, but takes an async function. The `compile` function * is awaited and not called in parallel. If multiple changes are triggered * before a compile finishes, the latest version is called after the compile * finished. * * TODO: Consider changing from a Promise to abortable, so we can abort mid * compilation. */ function _watchFiles() { _watchFiles = _asyncToGenerator(function* (baseDir, expression, filter, callback) { var files = new Set(); yield watch(baseDir, expression, function (changes) { if (!changes.files) { // Watchmen fires a change without files when a watchman state changes, // for example during an hg update. return; } files = updateFiles(files, baseDir, filter, changes.files); callback(files); }); }); return _watchFiles.apply(this, arguments); } function watchCompile(_x22, _x23, _x24, _x25) { return _watchCompile.apply(this, arguments); } function _watchCompile() { _watchCompile = _asyncToGenerator(function* (baseDir, expression, filter, compile) { var compiling = false; var needsCompiling = false; var latestFiles = null; watchFiles(baseDir, expression, filter, /*#__PURE__*/ function () { var _ref6 = _asyncToGenerator(function* (files) { needsCompiling = true; latestFiles = files; if (compiling) { return; } compiling = true; while (needsCompiling) { needsCompiling = false; yield compile(latestFiles); } compiling = false; }); return function (_x26) { return _ref6.apply(this, arguments); }; }()); }); return _watchCompile.apply(this, arguments); } function updateFiles(files, baseDir, filter, fileChanges) { var fileMap = new Map(); files.forEach(function (file) { file.exists && fileMap.set(file.relPath, file); }); fileChanges.forEach(function (_ref2) { var name = _ref2.name, exists = _ref2.exists, hash = _ref2['content.sha1hex']; var shouldRemove = !exists; if (!shouldRemove) { var _file = { exists: true, relPath: name, hash: hash || hashFile(path.join(baseDir, name)) }; if (filter(_file)) { fileMap.set(name, _file); } else { shouldRemove = true; } } shouldRemove && fileMap.set(name, { exists: false, relPath: name }); }); return new Set(fileMap.values()); } function hashFile(filename) { var content = fs.readFileSync(filename); return crypto.createHash('sha1').update(content).digest('hex'); } module.exports = { queryDirectories: queryDirectories, queryFiles: queryFiles, queryFilepaths: queryFilepaths, watch: watch, watchFiles: watchFiles, watchCompile: watchCompile }; /***/ }), /* 53 */ /***/ (function(module, exports) { module.exports = require("child_process"); /***/ }), /* 54 */ /***/ (function(module, exports) { module.exports = require("fb-watchman"); /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @emails oncall+relay */ var _interopRequireDefault = __webpack_require__(0); var _inheritsLoose2 = _interopRequireDefault(__webpack_require__(56)); var ASTConvert = __webpack_require__(25); var nullthrows = __webpack_require__(57); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError; var _require2 = __webpack_require__(7), GraphQLEnumType = _require2.GraphQLEnumType, GraphQLInputObjectType = _require2.GraphQLInputObjectType, GraphQLInterfaceType = _require2.GraphQLInterfaceType, GraphQLObjectType = _require2.GraphQLObjectType, GraphQLScalarType = _require2.GraphQLScalarType, GraphQLSchema = _require2.GraphQLSchema, GraphQLUnionType = _require2.GraphQLUnionType, buildASTSchema = _require2.buildASTSchema, extendSchema = _require2.extendSchema, parse = _require2.parse, parseType = _require2.parseType, print = _require2.print; /** * @private */ var Type = /*#__PURE__*/ function () { function Type(name) { this.name = name; } var _proto = Type.prototype; _proto.toString = function toString() { return this.name; }; _proto.toJSON = function toJSON() { return String(this); }; return Type; }(); /** * @private */ var ScalarType = /*#__PURE__*/ function (_Type) { (0, _inheritsLoose2["default"])(ScalarType, _Type); function ScalarType() { return _Type.apply(this, arguments) || this; } return ScalarType; }(Type); /** * @private */ var EnumType = /*#__PURE__*/ function (_Type2) { (0, _inheritsLoose2["default"])(EnumType, _Type2); function EnumType() { return _Type2.apply(this, arguments) || this; } return EnumType; }(Type); /** * @private */ var UnionType = /*#__PURE__*/ function (_Type3) { (0, _inheritsLoose2["default"])(UnionType, _Type3); function UnionType() { return _Type3.apply(this, arguments) || this; } return UnionType; }(Type); /** * @private */ var ObjectType = /*#__PURE__*/ function (_Type4) { (0, _inheritsLoose2["default"])(ObjectType, _Type4); function ObjectType() { return _Type4.apply(this, arguments) || this; } return ObjectType; }(Type); /** * @private */ var InputObjectType = /*#__PURE__*/ function (_Type5) { (0, _inheritsLoose2["default"])(InputObjectType, _Type5); function InputObjectType() { return _Type5.apply(this, arguments) || this; } return InputObjectType; }(Type); /** * @private */ var InterfaceType = /*#__PURE__*/ function (_Type6) { (0, _inheritsLoose2["default"])(InterfaceType, _Type6); function InterfaceType() { return _Type6.apply(this, arguments) || this; } return InterfaceType; }(Type); /** * @private */ var List = /*#__PURE__*/ function () { function List(type) { this.ofType = type; this._typeString = "[".concat(String(this.ofType), "]"); } var _proto2 = List.prototype; _proto2.toString = function toString() { return this._typeString; }; _proto2.toJSON = function toJSON() { return this.toString(); }; return List; }(); /** * @private */ var NonNull = /*#__PURE__*/ function () { function NonNull(type) { this.ofType = type; this._typeString = "".concat(String(this.ofType), "!"); } var _proto3 = NonNull.prototype; _proto3.toString = function toString() { return this._typeString; }; _proto3.toJSON = function toJSON() { return this.toString(); }; return NonNull; }(); /** * @private */ var Field = function Field(schema, name, type, belongsTo, argDefs) { this.name = name; this.type = type; this.belongsTo = belongsTo; this.args = new Map(argDefs.map(function (arg) { var _arg$astNode; return [arg.name, { name: arg.name, type: schema.assertInputType(schema.expectTypeFromAST(nullthrows((_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type))), defaultValue: arg.defaultValue }]; })); }; /** * @private */ function unwrap(type) { if (type instanceof NonNull || type instanceof List) { return unwrap(type.ofType); } return type; } /** * @private */ function hasConcreteTypeThatImplements(schema, type, interfaceType) { return _isAbstractType(type) && getConcreteTypes(schema, type).some(function (concreteType) { return schema.implementsInterface(schema.assertCompositeType(concreteType), interfaceType); }); } /** * @private */ function getConcreteTypes(schema, type) { var concreteTypes = new Set(); schema.getPossibleTypes(type).forEach(function (possibleType) { if (_isObject(possibleType)) { concreteTypes.add(possibleType); } }); return Array.from(concreteTypes); } var TYPENAME_FIELD = '__typename'; var CLIENT_ID_FIELD = '__id'; function _isScalar(type) { return type instanceof ScalarType; } function _isObject(type) { return type instanceof ObjectType; } function _isEnum(type) { return type instanceof EnumType; } function _isUnion(type) { return type instanceof UnionType; } function _isInputObject(type) { return type instanceof InputObjectType; } function _isInterface(type) { return type instanceof InterfaceType; } function _isWrapper(type) { return type instanceof List || type instanceof NonNull; } function isBaseType(type) { return type instanceof ScalarType || type instanceof ObjectType || type instanceof EnumType || type instanceof UnionType || type instanceof InputObjectType || type instanceof InterfaceType; } function _isAbstractType(type) { return type instanceof UnionType || type instanceof InterfaceType; } function _isCompositeType(type) { return type instanceof ObjectType || type instanceof UnionType || type instanceof InterfaceType; } function _isInputType(type) { return type instanceof InputObjectType || type instanceof ScalarType || type instanceof EnumType; } var Schema = /*#__PURE__*/ function () { /** * @private */ function Schema(baseSchema, extendedSchema, typeMap, fieldsMap, typeNameMap, clientIdMap, possibleTypesMap, directivesMap, QUERY_TYPE_KEY, MUTATION_TYPE_KEY, SUBSCRIPTION_TYPE_KEY) { var _this = this; var _directivesMap; this.QUERY_TYPE_KEY = QUERY_TYPE_KEY; this.MUTATION_TYPE_KEY = MUTATION_TYPE_KEY; this.SUBSCRIPTION_TYPE_KEY = SUBSCRIPTION_TYPE_KEY; this._baseSchema = baseSchema; this._extendedSchema = extendedSchema; this._typeMap = typeMap; this._fieldsMap = fieldsMap; this._typeNameMap = typeNameMap; this._clientIdMap = clientIdMap; this._possibleTypesMap = possibleTypesMap; this._directivesMap = (_directivesMap = directivesMap) !== null && _directivesMap !== void 0 ? _directivesMap : new Map(this._extendedSchema.getDirectives().map(function (directive) { return [directive.name, { clientOnlyDirective: _this._baseSchema.getDirective(directive.name) == null, name: directive.name, locations: directive.locations, args: directive.args.map(function (arg) { return { name: arg.name, type: _this.assertInputType(arg.astNode ? _this.expectTypeFromAST(arg.astNode.type) : _this.expectTypeFromString(String(arg.type))), defaultValue: arg.defaultValue }; }) }]; })); } var _proto4 = Schema.prototype; _proto4.getTypeFromAST = function getTypeFromAST(typeNode) { if (typeNode.kind === 'NonNullType') { var innerType = this.getTypeFromAST(typeNode.type); if (!innerType) { return; } if (innerType instanceof NonNull) { throw createCompilerError('Unable to wrap non-nullable type with non-null wrapper.'); } var cacheKey = "".concat(this.getTypeString(innerType), "!"); var type = this._typeMap.get(cacheKey); if (type) { return type; } type = new NonNull(innerType); this._typeMap.set(cacheKey, type); return type; } else if (typeNode.kind === 'ListType') { var _innerType = this.getTypeFromAST(typeNode.type); if (!_innerType) { return; } var _cacheKey = "[".concat(this.getTypeString(_innerType), "]"); var _type = this._typeMap.get(_cacheKey); if (_type) { return _type; } _type = new List(_innerType); this._typeMap.set(_cacheKey, _type); return _type; } else { var name = typeNode.name.value; var _type2 = this._typeMap.get(name); if (_type2) { return _type2; } var graphQLType = this._extendedSchema.getType(name); if (!graphQLType) { return; } var TypeClass = Type; if (graphQLType instanceof GraphQLScalarType) { TypeClass = ScalarType; } else if (graphQLType instanceof GraphQLInputObjectType) { TypeClass = InputObjectType; } else if (graphQLType instanceof GraphQLEnumType) { TypeClass = EnumType; } else if (graphQLType instanceof GraphQLUnionType) { TypeClass = UnionType; } else if (graphQLType instanceof GraphQLInterfaceType) { TypeClass = InterfaceType; } else if (graphQLType instanceof GraphQLObjectType) { TypeClass = ObjectType; } else { throw createCompilerError("Unknown GraphQL type: ".concat(graphQLType)); } _type2 = new TypeClass(name); this._typeMap.set(name, _type2); return _type2; } }; _proto4._getRawType = function _getRawType(typeName) { var type = this._typeMap.get(typeName); if (type) { return type; } if (typeof typeName === 'string') { return this.getTypeFromAST(parseType(typeName)); } else { var graphQLType; if (typeName === this.QUERY_TYPE_KEY) { graphQLType = this._baseSchema.getQueryType(); } else if (typeName === this.MUTATION_TYPE_KEY) { graphQLType = this._baseSchema.getMutationType(); } else if (typeName === this.SUBSCRIPTION_TYPE_KEY) { graphQLType = this._baseSchema.getSubscriptionType(); } if (graphQLType) { var operationType = new ObjectType(graphQLType.name); this._typeMap.set(typeName, operationType); this._typeMap.set(graphQLType.name, operationType); return operationType; } } }; _proto4.getTypeFromString = function getTypeFromString(typeName) { return this._getRawType(typeName); }; _proto4.expectTypeFromString = function expectTypeFromString(typeName) { var type = this.getTypeFromString(typeName); if (type == null) { throw createCompilerError("Unknown type: '".concat(typeName, "'.")); } return type; }; _proto4.expectTypeFromAST = function expectTypeFromAST(ast) { var type = this.getTypeFromAST(ast); if (type == null) { throw createCompilerError("Unknown type: '".concat(print(ast), "'."), null, [ast]); } return type; }; _proto4.getNonNullType = function getNonNullType(type) { if (type instanceof NonNull) { return type; } var cacheKey = "".concat(String(type), "!"); var nonNullType = this._typeMap.get(cacheKey); if (nonNullType) { return nonNullType; } nonNullType = new NonNull(type); this._typeMap.set(cacheKey, nonNullType); return nonNullType; }; _proto4.getRawType = function getRawType(type) { return unwrap(type); }; _proto4.getNullableType = function getNullableType(type) { if (type instanceof NonNull) { return type.ofType; } return type; }; _proto4.getListItemType = function getListItemType(type) { if (type instanceof List) { return type.ofType; } return type; }; _proto4.areEqualTypes = function areEqualTypes(typeA, typeB) { if (typeA === typeB) { return true; } if (typeA instanceof NonNull && typeB instanceof NonNull) { return this.areEqualTypes(typeA.ofType, typeB.ofType); } if (typeA instanceof List && typeB instanceof List) { return this.areEqualTypes(typeA.ofType, typeB.ofType); } if (isBaseType(typeA) && isBaseType(typeB)) { return typeA.name === typeB.name; } return false; } /** * Determine if the given type may implement the named type: * - it is the named type * - it implements the named interface * - it is an abstract type and *some* of its concrete types may * implement the named type */ ; _proto4.mayImplement = function mayImplement(type, interfaceType) { return this.areEqualTypes(type, interfaceType) || this.implementsInterface(type, interfaceType) || this.isAbstractType(type) && hasConcreteTypeThatImplements(this, type, interfaceType); }; _proto4.implementsInterface = function implementsInterface(type, interfaceType) { var _this2 = this; return this.getInterfaces(type).some(function (typeInterface) { return _this2.areEqualTypes(typeInterface, interfaceType); }); }; _proto4.canHaveSelections = function canHaveSelections(type) { return this.isObject(type) || this.isInterface(type); }; _proto4.getTypeString = function getTypeString(type) { return type.toString(); }; _proto4.isTypeSubTypeOf = function isTypeSubTypeOf(maybeSubType, superType) { // Equivalent type is a valid subtype if (maybeSubType === superType) { return true; } // If superType is non-null, maybeSubType must also be non-null. if (superType instanceof NonNull) { if (maybeSubType instanceof NonNull) { return this.isTypeSubTypeOf(maybeSubType.ofType, superType.ofType); } return false; } if (maybeSubType instanceof NonNull) { // If superType is nullable, maybeSubType may be non-null or nullable. return this.isTypeSubTypeOf(maybeSubType.ofType, superType); } // If superType type is a list, maybeSubType type must also be a list. if (superType instanceof List) { if (maybeSubType instanceof List) { return this.isTypeSubTypeOf(maybeSubType.ofType, superType.ofType); } return false; } if (maybeSubType instanceof List) { // If superType is not a list, maybeSubType must also be not a list. return false; } // If superType type is an abstract type, maybeSubType type may be a currently // possible object type. if (this.isAbstractType(superType) && this.isObject(maybeSubType) && this.isPossibleType(this.assertAbstractType(superType), this.assertObjectType(maybeSubType))) { return true; } // Otherwise, maybeSubType is not a valid subtype of the superType. return false; } /** * Provided two composite types, determine if they "overlap". Two composite * types overlap when the Sets of possible concrete types for each intersect. * * This is often used to determine if a fragment of a given type could possibly * be visited in a context of another type. * * This function is commutative. */ ; _proto4.doTypesOverlap = function doTypesOverlap(typeA, typeB) { var _this3 = this; // Equivalent types overlap if (typeA === typeB) { return true; } if (_isAbstractType(typeA)) { if (_isAbstractType(typeB)) { // If both types are abstract, then determine if there is any intersection // between possible concrete types of each. return Array.from(this.getPossibleTypes(typeA)).some(function (type) { if (_isObject(type)) { return _this3.isPossibleType(typeB, type); } }); } // Determine if the latter type is a possible concrete type of the former. return this.isPossibleType(typeA, typeB); } if (_isAbstractType(typeB)) { // Determine if the former type is a possible concrete type of the latter. return this.isPossibleType(typeB, typeA); } // Otherwise the types do not overlap. return false; }; _proto4.isPossibleType = function isPossibleType(superType, maybeSubType) { return this._getPossibleTypeSet(superType).has(maybeSubType); }; _proto4.assertScalarFieldType = function assertScalarFieldType(type) { // Scalar type fields can be wrappers / or can be scalars/enums if (_isWrapper(type) && !_isScalar(unwrap(type)) && !_isEnum(unwrap(type)) || !_isWrapper(type) && !_isScalar(type) && !_isEnum(type)) { throw createCompilerError("Expected ".concat(String(type), " to be a Scalar or Enum type.")); } return type; }; _proto4.assertLinkedFieldType = function assertLinkedFieldType(type) { // Linked Field types can be wrappers / or can be composite types if (_isWrapper(type) && !_isCompositeType(unwrap(type)) || !_isWrapper(type) && !_isCompositeType(type)) { throw createCompilerError("Expected ".concat(String(type), " to be a Object, Interface or a Union Type.")); } return type; }; _proto4.assertInputType = function assertInputType(type) { // Input type fields can be wrappers / or can be scalars/enums if (_isWrapper(type) && !_isInputType(unwrap(type)) || !_isWrapper(type) && !_isInputType(type)) { throw createCompilerError("Expected ".concat(String(type), " to be a Input, Scalar or Enum type.")); } return type; }; _proto4.asCompositeType = function asCompositeType(type) { if (_isCompositeType(type)) { return type; } }; _proto4.asInputType = function asInputType(type) { if (_isWrapper(type) && _isInputType(unwrap(type)) || !_isWrapper(type) && _isInputType(type)) { return type; } }; _proto4.asScalarFieldType = function asScalarFieldType(type) { if (_isScalar(type) || _isEnum(type)) { return type; } }; _proto4.assertScalarType = function assertScalarType(type) { if (!_isScalar(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a scalar type.")); } return type; }; _proto4.assertObjectType = function assertObjectType(type) { if (!_isObject(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be an object type.")); } return type; }; _proto4.assertInputObjectType = function assertInputObjectType(type) { if (!_isInputObject(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be an input type.")); } return type; }; _proto4.assertInterfaceType = function assertInterfaceType(type) { if (!_isInterface(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be an interface type.")); } return type; }; _proto4.assertCompositeType = function assertCompositeType(type) { if (!_isCompositeType(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a composite type.")); } return type; }; _proto4.assertAbstractType = function assertAbstractType(type) { if (!_isAbstractType(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be an abstract type.")); } return type; }; _proto4.assertLeafType = function assertLeafType(type) { if (!this.isLeafType(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a leaf type.")); } return type; }; _proto4.assertUnionType = function assertUnionType(type) { if (!_isUnion(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a union type.")); } return type; }; _proto4.assertEnumType = function assertEnumType(type) { if (!_isEnum(type)) { throw createCompilerError("Expected ".concat(String(type), " to be an enum type.")); } return type; }; _proto4.assertIntType = function assertIntType(type) { if (!_isScalar(type) || !this.isInt(type)) { throw createCompilerError("Expected ".concat(String(type), " to be an 'Int' type.")); } return type; }; _proto4.assertFloatType = function assertFloatType(type) { if (!_isScalar(type) || !this.isFloat(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a 'Float' type.")); } return type; }; _proto4.assertBooleanType = function assertBooleanType(type) { if (!_isScalar(type) || !this.isBoolean(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a 'Boolean' type.")); } return type; }; _proto4.assertStringType = function assertStringType(type) { if (!_isScalar(type) || !this.isString(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be a 'String' type.")); } return type; }; _proto4.assertIdType = function assertIdType(type) { if (!_isScalar(type) || !this.isId(type)) { throw createCompilerError("Expected ".concat(this.getTypeString(type), " to be an ID type.")); } return type; }; _proto4.expectBooleanType = function expectBooleanType() { return this.assertScalarType(this.expectTypeFromString('Boolean')); }; _proto4.expectIntType = function expectIntType() { return this.assertScalarType(this.expectTypeFromString('Int')); }; _proto4.expectFloatType = function expectFloatType() { return this.assertScalarType(this.expectTypeFromString('Float')); }; _proto4.expectStringType = function expectStringType() { return this.assertScalarType(this.expectTypeFromString('String')); }; _proto4.expectIdType = function expectIdType() { return this.assertScalarType(this.expectTypeFromString('ID')); }; _proto4.getQueryType = function getQueryType() { var queryType = this._getRawType(this.QUERY_TYPE_KEY); if (queryType && _isObject(queryType)) { return queryType; } }; _proto4.getMutationType = function getMutationType() { var mutationType = this._getRawType(this.MUTATION_TYPE_KEY); if (mutationType && _isObject(mutationType)) { return mutationType; } }; _proto4.getSubscriptionType = function getSubscriptionType() { var subscriptionType = this._getRawType(this.SUBSCRIPTION_TYPE_KEY); if (subscriptionType && _isObject(subscriptionType)) { return subscriptionType; } }; _proto4.expectQueryType = function expectQueryType() { var queryType = this.getQueryType(); if (queryType == null) { throw createCompilerError('Query type is not defined on the Schema'); } return queryType; }; _proto4.expectMutationType = function expectMutationType() { var mutationType = this.getMutationType(); if (mutationType == null) { throw createCompilerError('Mutation type is not defined the Schema'); } return mutationType; }; _proto4.expectSubscriptionType = function expectSubscriptionType() { var subscriptionType = this.getSubscriptionType(); if (subscriptionType == null) { throw createCompilerError('Subscription type is not defined the Schema'); } return subscriptionType; }; _proto4.isNonNull = function isNonNull(type) { return type instanceof NonNull; }; _proto4.isList = function isList(type) { return type instanceof List; }; _proto4.isWrapper = function isWrapper(type) { return _isWrapper(type); }; _proto4.isScalar = function isScalar(type) { return _isScalar(type); }; _proto4.isObject = function isObject(type) { return _isObject(type); }; _proto4.isEnum = function isEnum(type) { return _isEnum(type); }; _proto4.isUnion = function isUnion(type) { return _isUnion(type); }; _proto4.isInputObject = function isInputObject(type) { return _isInputObject(type); }; _proto4.isInterface = function isInterface(type) { return _isInterface(type); }; _proto4.isInputType = function isInputType(type) { // Wrappers can be input types (so it's save to check unwrapped type here) return _isInputType(type) || _isWrapper(type) && _isInputType(unwrap(type)); }; _proto4.isCompositeType = function isCompositeType(type) { return _isCompositeType(type); }; _proto4.isAbstractType = function isAbstractType(type) { return _isAbstractType(type); }; _proto4.isLeafType = function isLeafType(type) { return this.isScalar(type) || this.isEnum(type); }; _proto4.isId = function isId(type) { if (type instanceof ScalarType) { return type.name === 'ID'; } return false; }; _proto4.isInt = function isInt(type) { if (type instanceof ScalarType) { return type.name === 'Int'; } return false; }; _proto4.isFloat = function isFloat(type) { if (type instanceof ScalarType) { return type.name === 'Float'; } return false; }; _proto4.isBoolean = function isBoolean(type) { if (type instanceof ScalarType) { return type.name === 'Boolean'; } return false; }; _proto4.isString = function isString(type) { if (type instanceof ScalarType) { return type.name === 'String'; } return false; }; _proto4.hasField = function hasField(type, fieldName) { var canHaveTypename = this.isObject(type) || this.isAbstractType(type); // Special case for __typename field if (canHaveTypename && (fieldName === TYPENAME_FIELD || fieldName === CLIENT_ID_FIELD)) { return true; } var name = type.name; var gqlType = this._extendedSchema.getType(name); if (gqlType instanceof GraphQLObjectType || gqlType instanceof GraphQLInterfaceType || gqlType instanceof GraphQLInputObjectType) { return gqlType.getFields()[fieldName] != null; } throw createCompilerError('hasField(): Expected a concrete type or interface, ' + "got type ".concat(type.name)); }; _proto4.hasId = function hasId(type) { if (!this.hasField(type, 'id')) { return false; } var idField = this.expectField(type, 'id'); return this.areEqualTypes(this.getNullableType(this.getFieldType(idField)), this.expectIdType()); }; _proto4.getFields = function getFields(type) { var fieldsMap = this._getFieldsMap(type); return Array.from(fieldsMap.values()); }; _proto4._getFieldsMap = function _getFieldsMap(type) { var _this4 = this; var cachedMap = this._fieldsMap.get(type); if (cachedMap != null) { return cachedMap; } var fieldsMap = new Map(); var name = type.name; var gqlType = this._extendedSchema.getType(name); if (gqlType instanceof GraphQLObjectType || gqlType instanceof GraphQLInterfaceType) { var typeFields = gqlType.getFields(); var fieldNames = Object.keys(typeFields); fieldNames.forEach(function (fieldName) { var field = typeFields[fieldName]; if (field == null) { return; } var fieldType = field.astNode ? _this4.expectTypeFromAST(field.astNode.type) : _this4.expectTypeFromString(String(field.type)); fieldsMap.set(fieldName, new Field(_this4, fieldName, fieldType, _this4.assertCompositeType(type), field.args)); }); } else if (gqlType instanceof GraphQLInputObjectType) { var _typeFields = gqlType.getFields(); var _fieldNames = Object.keys(_typeFields); _fieldNames.forEach(function (fieldName) { var field = _typeFields[fieldName]; if (field == null) { return; } var fieldType = field.astNode ? _this4.expectTypeFromAST(field.astNode.type) : _this4.expectTypeFromString(String(field.type)); fieldsMap.set(fieldName, new Field(_this4, fieldName, fieldType, type, [])); }); } this._fieldsMap.set(type, fieldsMap); return fieldsMap; }; _proto4.getFieldByName = function getFieldByName(type, fieldName) { if (!this.hasField(type, fieldName)) { return; } // A "special" case for __typename and __id fields - which should // not be in the list of type fields, but should be fine to select if (fieldName === TYPENAME_FIELD) { var typename = this._typeNameMap.get(type); if (!typename) { typename = new Field(this, TYPENAME_FIELD, this.getNonNullType(this.expectStringType()), type, []); this._typeNameMap.set(type, typename); } return typename; } if (fieldName === CLIENT_ID_FIELD) { var clientId = this._clientIdMap.get(type); if (!clientId) { clientId = new Field(this, CLIENT_ID_FIELD, this.getNonNullType(this.expectIdType()), type, []); this._clientIdMap.set(type, clientId); } return clientId; } if (_isUnion(type)) { throw createCompilerError("Unexpected union type '".concat(this.getTypeString(type), "' in the 'getFieldByName(...)'. Expected type with fields")); } var fieldsMap = this._getFieldsMap(type); return fieldsMap.get(fieldName); }; _proto4.expectField = function expectField(type, fieldName) { var field = this.getFieldByName(type, fieldName); if (!field) { throw createCompilerError("Unknown field '".concat(fieldName, "' on type '").concat(this.getTypeString(type), "'.")); } return field; }; _proto4.getFieldConfig = function getFieldConfig(field) { return { type: field.type, args: Array.from(field.args.values()) }; }; _proto4.getFieldName = function getFieldName(field) { return field.name; }; _proto4.getFieldType = function getFieldType(field) { return field.type; }; _proto4.getFieldParentType = function getFieldParentType(field) { return field.belongsTo; }; _proto4.getFieldArgs = function getFieldArgs(field) { return Array.from(field.args.values()); }; _proto4.getFieldArgByName = function getFieldArgByName(field, argName) { return field.args.get(argName); }; _proto4.getEnumValues = function getEnumValues(type) { var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLEnumType) { return gqlType.getValues().map(function (_ref) { var value = _ref.value; return String(value); }); } throw createCompilerError("Expected '".concat(type.name, "' to be an enum.")); }; _proto4.getUnionTypes = function getUnionTypes(type) { var _this5 = this; var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLUnionType) { return gqlType.getTypes().map(function (typeFromUnion) { return _this5.expectTypeFromString(typeFromUnion.name); }); } throw createCompilerError("Unable to get union types for type '".concat(this.getTypeString(type), "'.")); }; _proto4.getInterfaces = function getInterfaces(type) { var _this6 = this; var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLObjectType) { return gqlType.getInterfaces().map(function (typeInterface) { return _this6.expectTypeFromString(typeInterface.name); }); } return []; }; _proto4._getPossibleTypeSet = function _getPossibleTypeSet(type) { var _this7 = this; var possibleTypes = this._possibleTypesMap.get(type); if (!possibleTypes) { var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLUnionType || gqlType instanceof GraphQLInterfaceType) { possibleTypes = new Set(this._extendedSchema.getPossibleTypes(gqlType).map(function (possibleType) { return _this7.assertObjectType(_this7.expectTypeFromString(possibleType.name)); })); this._possibleTypesMap.set(type, possibleTypes); } else { throw createCompilerError("Expected \"".concat(this.getTypeString(type), "\" to be an Abstract type.")); } } return possibleTypes; }; _proto4.getPossibleTypes = function getPossibleTypes(type) { return this._getPossibleTypeSet(type); }; _proto4.parseLiteral = function parseLiteral(type, valueNode) { var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLEnumType || gqlType instanceof GraphQLScalarType) { return gqlType.parseLiteral(valueNode); } throw createCompilerError("parseLiteral(...) is used with invalid type: ".concat(this.getTypeString(type), ".")); }; _proto4.parseValue = function parseValue(type, value) { var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLEnumType || gqlType instanceof GraphQLScalarType) { return gqlType.parseValue(value); } throw createCompilerError("parseValue(...) is used with invalid type: ".concat(this.getTypeString(type), ".")); }; _proto4.serialize = function serialize(type, value) { var gqlType = this._extendedSchema.getType(type.name); if (gqlType instanceof GraphQLEnumType || gqlType instanceof GraphQLScalarType) { return gqlType.serialize(value); } throw createCompilerError("parseValue(...) is used with invalid type: ".concat(this.getTypeString(type), ".")); }; _proto4.getDirectives = function getDirectives() { return Array.from(this._directivesMap.values()); }; _proto4.getDirective = function getDirective(directiveName) { return this._directivesMap.get(directiveName); }; _proto4.isServerType = function isServerType(type) { var name = this.getTypeString(type); return this._baseSchema.getType(name) != null; }; _proto4.isServerField = function isServerField(field) { var fieldName = field.name; // Allow metadata fields and fields defined on classic "fat" interfaces if (['__typename'].includes(fieldName)) { return true; } var fieldRawTypeName = this.getTypeString(unwrap(field.type)); var fieldParentTypeName = this.getTypeString(unwrap(field.belongsTo)); // Field type is client-only if (!this._baseSchema.getType(fieldRawTypeName)) { return false; } var serverType = this._baseSchema.getType(fieldParentTypeName); // Parent type is client-only if (serverType == null) { return false; } else { if (serverType instanceof GraphQLObjectType || serverType instanceof GraphQLInterfaceType || serverType instanceof GraphQLInputObjectType) { // Field is not available in the server schema if (!serverType.getFields()[fieldName]) { return false; } } else { return false; } } return true; }; _proto4.isServerDirective = function isServerDirective(directiveName) { var directive = this._directivesMap.get(directiveName); return (directive === null || directive === void 0 ? void 0 : directive.clientOnlyDirective) === false; }; _proto4.isServerDefinedField = function isServerDefinedField(type, field) { return this.isAbstractType(type) && field.directives.some(function (_ref2) { var name = _ref2.name; return name === 'fixme_fat_interface'; }) || this.hasField(type, field.name) && this.isServerField(this.expectField(type, field.name)); }; _proto4.isClientDefinedField = function isClientDefinedField(type, field) { return !this.isServerDefinedField(type, field); } /** * The only consumer of this is RelayParser.parse(...) * We should either refactor RelayParser.parse(...) to not-rely on the ` * extendSchema` method. Or actually implement it here. */ ; _proto4.DEPRECATED__extend = function DEPRECATED__extend(document) { var extendedSchema = extendSchema(this._extendedSchema, document, { assumeValid: true }); return new Schema(this._baseSchema, extendedSchema, this._typeMap, this._fieldsMap, this._typeNameMap, this._clientIdMap, this._possibleTypesMap, this._directivesMap, this.QUERY_TYPE_KEY, this.MUTATION_TYPE_KEY, this.SUBSCRIPTION_TYPE_KEY); }; return Schema; }(); var localGraphQLSchemaCache = new Map(); function DEPRECATED__buildGraphQLSchema(source) { var schema = localGraphQLSchemaCache.get(source); if (schema != null) { return schema; } try { schema = buildASTSchema(parse(source), { assumeValid: true }); localGraphQLSchemaCache.set(source, schema); return schema; } catch (error) { throw Object.assign(error, { message: "Caught an error \"".concat(error.message, "\" while loading and parsing schema file: ").concat(source.name, ". Please make sure that schema is valid.") }); } } /** * We need this in order to make unit-test works * In most of the unit-tests the schema is created from the instance of the * GraphQLSchema. */ function DEPRECATED__create(baseSchema, extendedSchema) { var _extendedSchema; return new Schema(baseSchema, (_extendedSchema = extendedSchema) !== null && _extendedSchema !== void 0 ? _extendedSchema : baseSchema, new Map(), new Map(), new Map(), new Map(), new Map(), null, Symbol('Query'), Symbol('Mutation'), Symbol('Subsription')); } function create(baseSchema, schemaExtensionDocuments, schemaExtensions) { var _schemaExtensions, _schemaExtensionDocum; var schema = DEPRECATED__buildGraphQLSchema(baseSchema); var transformedSchema = ASTConvert.transformASTSchema(schema, (_schemaExtensions = schemaExtensions) !== null && _schemaExtensions !== void 0 ? _schemaExtensions : []); var extendedSchema = ASTConvert.extendASTSchema(transformedSchema, (_schemaExtensionDocum = schemaExtensionDocuments) !== null && _schemaExtensionDocum !== void 0 ? _schemaExtensionDocum : []); return new Schema(schema, extendedSchema, new Map(), new Map(), new Map(), new Map(), new Map(), null, Symbol('Query'), Symbol('Mutation'), Symbol('Subsription')); } module.exports = { DEPRECATED__buildGraphQLSchema: DEPRECATED__buildGraphQLSchema, DEPRECATED__create: DEPRECATED__create, create: create }; /***/ }), /* 56 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/helpers/inheritsLoose"); /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ function nullthrows(x) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Got unexpected null or undefined'; if (x == null) { throw new Error(message); } return x; } module.exports = nullthrows; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var chalk = __webpack_require__(59); function getMemoryUsageString() { return chalk.blue(Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + 'Mb'); } var ConsoleReporter = /*#__PURE__*/ function () { function ConsoleReporter(options) { this._verbose = options.verbose; this._quiet = options.quiet; } var _proto = ConsoleReporter.prototype; _proto.reportMessage = function reportMessage(message) { if (!this._quiet) { process.stdout.write(message + '\n'); } }; _proto.reportTime = function reportTime(name, ms) { if (this._verbose && !this._quiet) { var time = ms === 0 ? chalk.gray(' <1ms') : ms < 1000 ? chalk.blue(leftPad(5, ms + 'ms')) : chalk.red(Math.floor(ms / 10) / 100 + 's'); process.stdout.write(' ' + time + ' ' + chalk.gray(name) + ' [' + getMemoryUsageString() + ']\n'); } }; _proto.reportError = function reportError(caughtLocation, error) { if (!this._quiet) { process.stdout.write(chalk.red('ERROR:\n' + error.message + '\n')); if (this._verbose) { var frames = error.stack.match(/^ {4}at .*$/gm); if (frames) { process.stdout.write(chalk.gray('From: ' + caughtLocation + '\n' + frames.join('\n') + '\n')); } } } }; return ConsoleReporter; }(); function leftPad(len, str) { return new Array(len - str.length + 1).join(' ') + str; } module.exports = ConsoleReporter; /***/ }), /* 59 */ /***/ (function(module, exports) { module.exports = require("chalk"); /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var ASTCache = __webpack_require__(26); var fs = __webpack_require__(13); var path = __webpack_require__(8); var _require = __webpack_require__(7), parse = _require.parse, Source = _require.Source; function parseFile(baseDir, file) { var text = fs.readFileSync(path.join(baseDir, file.relPath), 'utf8'); return parse(new Source(text, file.relPath), { experimentalFragmentVariables: true }); } function getParser(baseDir) { return new ASTCache({ baseDir: baseDir, parse: parseFile }); } module.exports = { parseFile: parseFile, getParser: getParser }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _asyncToGenerator = __webpack_require__(10); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var ASTConvert = __webpack_require__(25); var CodegenDirectory = __webpack_require__(24); var CompilerContext = __webpack_require__(19); var Profiler = __webpack_require__(6); var RelayParser = __webpack_require__(27); var compileRelayArtifacts = __webpack_require__(63); var crypto = __webpack_require__(12); var graphql = __webpack_require__(7); var invariant = __webpack_require__(4); var nullthrows = __webpack_require__(20); var path = __webpack_require__(8); var writeRelayGeneratedFile = __webpack_require__(68); var _require = __webpack_require__(71), getReaderSourceDefinitionName = _require.getReaderSourceDefinitionName; var _require2 = __webpack_require__(11), isExecutableDefinitionAST = _require2.isExecutableDefinitionAST; var _require3 = __webpack_require__(14), ImmutableMap = _require3.Map; function compileAll(_ref) { var baseDir = _ref.baseDir, baseDocuments = _ref.baseDocuments, schema = _ref.schema, compilerTransforms = _ref.compilerTransforms, documents = _ref.documents, reporter = _ref.reporter, typeGenerator = _ref.typeGenerator; var definitions = ASTConvert.convertASTDocumentsWithBase(schema, baseDocuments, documents, RelayParser.transform); var compilerContext = new CompilerContext(schema).addAll(definitions); var transformedTypeContext = compilerContext.applyTransforms(typeGenerator.transforms, reporter); var transformedQueryContext = compilerContext.applyTransforms([].concat((0, _toConsumableArray2["default"])(compilerTransforms.commonTransforms), (0, _toConsumableArray2["default"])(compilerTransforms.queryTransforms)), reporter); var artifacts = compileRelayArtifacts(compilerContext, compilerTransforms, reporter); return { artifacts: artifacts, definitions: definitions, transformedQueryContext: transformedQueryContext, transformedTypeContext: transformedTypeContext }; } function writeAll(_ref2) { var writerConfig = _ref2.config, onlyValidate = _ref2.onlyValidate, baseDocuments = _ref2.baseDocuments, documents = _ref2.documents, schema = _ref2.schema, reporter = _ref2.reporter, sourceControl = _ref2.sourceControl; return Profiler.asyncContext('RelayFileWriter.writeAll', /*#__PURE__*/ _asyncToGenerator(function* () { var _compileAll = compileAll({ schema: schema, baseDir: writerConfig.baseDir, baseDocuments: baseDocuments.valueSeq().toArray(), compilerTransforms: writerConfig.compilerTransforms, documents: documents.valueSeq().toArray(), reporter: reporter, typeGenerator: writerConfig.typeGenerator }), artifactsWithBase = _compileAll.artifacts, definitions = _compileAll.definitions, transformedTypeContext = _compileAll.transformedTypeContext, transformedQueryContext = _compileAll.transformedQueryContext; // Build a context from all the documents var baseDefinitionNames = new Set(); baseDocuments.forEach(function (doc) { doc.definitions.forEach(function (def) { if (isExecutableDefinitionAST(def) && def.name) { baseDefinitionNames.add(def.name.value); } }); }); // remove nodes that are present in the base or that derive from nodes // in the base var artifacts = artifactsWithBase.filter(function (_ref3) { var _definition = _ref3[0], node = _ref3[1]; var sourceName = getReaderSourceDefinitionName(node); return !baseDefinitionNames.has(sourceName); }); var artifactMap = new Map(artifacts.map(function (_ref4) { var _definition = _ref4[0], node = _ref4[1]; return [node.kind === 'Request' ? node.params.name : node.name, node]; })); var existingFragmentNames = new Set(definitions.map(function (definition) { return definition.name; })); var definitionsMeta = new Map(); var getDefinitionMeta = function getDefinitionMeta(definitionName) { var artifact = nullthrows(artifactMap.get(definitionName)); var sourceName = getReaderSourceDefinitionName(artifact); var definitionMeta = definitionsMeta.get(sourceName); !definitionMeta ? true ? invariant(false, 'RelayFileWriter: Could not determine source for definition: `%s`.', definitionName) : undefined : void 0; return definitionMeta; }; documents.forEach(function (doc, filePath) { doc.definitions.forEach(function (def) { if (def.name) { definitionsMeta.set(def.name.value, { dir: path.join(writerConfig.baseDir, path.dirname(filePath)), ast: def }); } }); }); // TODO(T22651734): improve this to correctly account for fragments that // have generated flow types. baseDefinitionNames.forEach(function (baseDefinitionName) { existingFragmentNames["delete"](baseDefinitionName); }); var allOutputDirectories = new Map(); var addCodegenDir = function addCodegenDir(dirPath) { var codegenDir = new CodegenDirectory(dirPath, { onlyValidate: onlyValidate, filesystem: writerConfig.filesystem }); allOutputDirectories.set(dirPath, codegenDir); return codegenDir; }; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (writerConfig.generatedDirectories || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var existingDirectory = _step.value; addCodegenDir(existingDirectory); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var configOutputDirectory; if (writerConfig.outputDir) { configOutputDirectory = addCodegenDir(writerConfig.outputDir); } var getGeneratedDirectory = function getGeneratedDirectory(definitionName) { if (configOutputDirectory) { return configOutputDirectory; } var generatedPath = path.join(getDefinitionMeta(definitionName).dir, '__generated__'); var cachedDir = allOutputDirectories.get(generatedPath); if (!cachedDir) { cachedDir = addCodegenDir(generatedPath); } return cachedDir; }; var formatModule = Profiler.instrument(writerConfig.formatModule, 'RelayFileWriter:formatModule'); var persistQuery = writerConfig.persistQuery ? Profiler.instrumentWait(writerConfig.persistQuery, 'RelayFileWriter:persistQuery') : null; try { yield Promise.all(artifacts.map( /*#__PURE__*/ function () { var _ref7 = _asyncToGenerator(function* (_ref5) { var _writerConfig$repersi; var definition = _ref5[0], node = _ref5[1]; var nodeName = node.kind === 'Request' ? node.params.name : node.name; if (baseDefinitionNames.has(nodeName)) { // don't add definitions that were part of base context return; } var typeNode = transformedTypeContext.get(nodeName); var typeText = typeNode ? writerConfig.typeGenerator.generate(schema, typeNode, { customScalars: writerConfig.customScalars, enumsHasteModule: writerConfig.enumsHasteModule, existingFragmentNames: existingFragmentNames, optionalInputFields: writerConfig.optionalInputFieldsForFlow, useHaste: writerConfig.useHaste, useSingleArtifactDirectory: !!writerConfig.outputDir, noFutureProofEnums: writerConfig.noFutureProofEnums, normalizationIR: definition.kind === 'Request' ? definition.root : undefined }) : ''; var sourceHash = Profiler.run('hashGraphQL', function () { return md5(graphql.print(getDefinitionMeta(nodeName).ast)); }); yield writeRelayGeneratedFile(schema, getGeneratedDirectory(nodeName), definition, node, formatModule, typeText, persistQuery, writerConfig.platform, sourceHash, writerConfig.extension, writerConfig.printModuleDependency, (_writerConfig$repersi = writerConfig.repersist) !== null && _writerConfig$repersi !== void 0 ? _writerConfig$repersi : false); }); return function (_x) { return _ref7.apply(this, arguments); }; }())); var generateExtraFiles = writerConfig.generateExtraFiles; if (generateExtraFiles) { Profiler.run('RelayFileWriter:generateExtraFiles', function () { var configDirectory = writerConfig.outputDir; generateExtraFiles(function (dir) { var outputDirectory = dir || configDirectory; !outputDirectory ? true ? invariant(false, 'RelayFileWriter: cannot generate extra files without specifying ' + 'an outputDir in the config or passing it in.') : undefined : void 0; var outputDir = allOutputDirectories.get(outputDirectory); if (!outputDir) { outputDir = addCodegenDir(outputDirectory); } return outputDir; }, transformedQueryContext, getGeneratedDirectory); }); } allOutputDirectories.forEach(function (dir) { dir.deleteExtraFiles(); }); if (sourceControl && !onlyValidate) { yield CodegenDirectory.sourceControlAddRemove(sourceControl, Array.from(allOutputDirectories.values())); } } catch (error) { var details; try { details = JSON.parse(error.message); } catch (_) {} // eslint-disable-line lint/no-unused-catch-bindings if (details && details.name === 'GraphQL2Exception' && details.message) { throw new Error('GraphQL error writing modules:\n' + details.message); } throw new Error('Error writing modules:\n' + String(error.stack || error)); } return allOutputDirectories; })); } function md5(x) { return crypto.createHash('md5').update(x, 'utf8').digest('hex'); } module.exports = { writeAll: writeAll }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var OR_LIST_MAX_LENGTH = 5; var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError; function orList(items) { if (items.length === 0) { throw createCompilerError('Expected an array of strings. Got empty array'); } if (items.length === 1) { return items[0]; } if (items.length > OR_LIST_MAX_LENGTH) { return items.slice(0, OR_LIST_MAX_LENGTH).join(', ') + ', ...'; } var selected = items.slice(); var lastItem = selected.pop(); return selected.join(', ') + ' or ' + lastItem; } module.exports = orList; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var Printer = __webpack_require__(31); var Profiler = __webpack_require__(6); var RelayCodeGenerator = __webpack_require__(64); var filterContextForNode = __webpack_require__(67); function createFragmentContext(context, transforms, reporter) { // The fragment is used for reading data from the normalized store. return context.applyTransforms([].concat((0, _toConsumableArray2["default"])(transforms.commonTransforms), (0, _toConsumableArray2["default"])(transforms.fragmentTransforms)), reporter); } function createPrintContext(context, transforms, reporter) { // The unflattened query is used for printing, since flattening creates an // invalid query. return context.applyTransforms([].concat((0, _toConsumableArray2["default"])(transforms.commonTransforms), (0, _toConsumableArray2["default"])(transforms.queryTransforms), (0, _toConsumableArray2["default"])(transforms.printTransforms)), reporter); } function createCodeGenContext(context, transforms, reporter) { // The flattened query is used for codegen in order to reduce the number of // duplicate fields that must be processed during response normalization. return context.applyTransforms([].concat((0, _toConsumableArray2["default"])(transforms.commonTransforms), (0, _toConsumableArray2["default"])(transforms.queryTransforms), (0, _toConsumableArray2["default"])(transforms.codegenTransforms)), reporter); } function compile(context, fragmentContext, printContext, codeGenContext) { var results = []; var schema = context.getSchema(); // Add everything from codeGenContext, these are the operations as well as // SplitOperations from @match. var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = codeGenContext.documents()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var node = _step.value; if (node.kind === 'Root') { var fragment = fragmentContext.getRoot(node.name); var request = { kind: 'Request', fragment: { kind: 'Fragment', argumentDefinitions: fragment.argumentDefinitions, directives: fragment.directives, loc: { kind: 'Derived', source: node.loc }, metadata: null, name: fragment.name, selections: fragment.selections, type: fragment.type }, id: null, loc: node.loc, metadata: node.metadata || {}, name: fragment.name, root: node, text: printOperation(printContext, fragment.name) }; results.push([request, RelayCodeGenerator.generate(schema, request)]); } else { results.push([node, RelayCodeGenerator.generate(schema, node)]); } } // Add all the Fragments from the fragmentContext for the reader ASTs. } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = fragmentContext.documents()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _node = _step2.value; if (_node.kind === 'Fragment') { results.push([_node, RelayCodeGenerator.generate(schema, _node)]); } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return results; } var OPERATION_ORDER = { Root: 0, SplitOperation: 1, Fragment: 2 }; function printOperation(printContext, name) { var printableRoot = printContext.getRoot(name); return filterContextForNode(printableRoot, printContext).documents().sort(function (a, b) { if (a.kind !== b.kind) { return OPERATION_ORDER[a.kind] - OPERATION_ORDER[b.kind]; } return a.name < b.name ? -1 : 1; }).map(function (doc) { return Printer.print(printContext.getSchema(), doc); }).join('\n'); } /** * Transforms the provided compiler context * * compileRelayArtifacts generates artifacts for Relay's runtime as a result of * applying a series of transforms. Each kind of artifact is dependent on * transforms being applied in the following order: * * - Fragment Readers: commonTransforms, fragmentTransforms * - Operation Writers: commonTransforms, queryTransforms, codegenTransforms * - GraphQL Text: commonTransforms, queryTransforms, printTransforms * * The order of the transforms applied for each artifact below is important. * CompilerContext will memoize applying each transform, so while * `commonTransforms` appears in each artifacts' application, it will not result * in repeated work as long as the order remains consistent across each context. */ function compileRelayArtifacts(context, transforms, reporter) { return Profiler.run('GraphQLCompiler.compile', function () { var fragmentContext = createFragmentContext(context, transforms, reporter); var printContext = createPrintContext(context, transforms, reporter); var codeGenContext = createCodeGenContext(context, transforms, reporter); return compile(context, fragmentContext, printContext, codeGenContext); }); } module.exports = compileRelayArtifacts; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var NormalizationCodeGenerator = __webpack_require__(65); var ReaderCodeGenerator = __webpack_require__(66); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError; function generate(schema, node) { var _node$metadata; switch (node.kind) { case 'Fragment': if (((_node$metadata = node.metadata) === null || _node$metadata === void 0 ? void 0 : _node$metadata.inlineData) === true) { return { kind: 'InlineDataFragment', name: node.name }; } return ReaderCodeGenerator.generate(schema, node); case 'Request': return { kind: 'Request', fragment: ReaderCodeGenerator.generate(schema, node.fragment), operation: NormalizationCodeGenerator.generate(schema, node.root), params: { operationKind: node.root.operation, name: node.name, id: node.id, text: node.text, metadata: node.metadata } }; case 'SplitOperation': return NormalizationCodeGenerator.generate(schema, node); } throw createCompilerError("RelayCodeGenerator: Unknown AST kind '".concat(node.kind, "'."), [node.loc]); } module.exports = { generate: generate }; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createUserError = _require.createUserError; var _require2 = __webpack_require__(9), ConnectionInterface = _require2.ConnectionInterface, getStorageKey = _require2.getStorageKey, stableCopy = _require2.stableCopy; function generate(schema, node) { switch (node.kind) { case 'Root': return generateRoot(schema, node); case 'SplitOperation': return generateSplitOperation(schema, node); default: throw createCompilerError("NormalizationCodeGenerator: Unsupported AST kind '".concat(node.kind, "'."), [node.loc]); } } function generateRoot(schema, node) { return { kind: 'Operation', name: node.name, argumentDefinitions: generateArgumentDefinitions(schema, node.argumentDefinitions), selections: generateSelections(schema, node.selections) }; } function generateSplitOperation(schema, node) { return { kind: 'SplitOperation', name: node.name, metadata: node.metadata, selections: generateSelections(schema, node.selections) }; } function generateSelections(schema, selections) { var normalizationSelections = []; selections.forEach(function (selection) { switch (selection.kind) { case 'Condition': normalizationSelections.push(generateCondition(schema, selection)); break; case 'ClientExtension': normalizationSelections.push(generateClientExtension(schema, selection)); break; case 'ScalarField': normalizationSelections.push.apply(normalizationSelections, (0, _toConsumableArray2["default"])(generateScalarField(selection))); break; case 'ModuleImport': normalizationSelections.push(generateModuleImport(selection)); break; case 'InlineFragment': normalizationSelections.push(generateInlineFragment(schema, selection)); break; case 'LinkedField': normalizationSelections.push.apply(normalizationSelections, (0, _toConsumableArray2["default"])(generateLinkedField(schema, selection))); break; case 'ConnectionField': normalizationSelections.push.apply(normalizationSelections, (0, _toConsumableArray2["default"])(generateConnectionField(schema, selection))); break; case 'Connection': normalizationSelections.push(generateConnection(schema, selection)); break; case 'Defer': normalizationSelections.push(generateDefer(schema, selection)); break; case 'Stream': normalizationSelections.push(generateStream(schema, selection)); break; case 'InlineDataFragmentSpread': case 'FragmentSpread': throw new createCompilerError("NormalizationCodeGenerator: Unexpected IR node ".concat(selection.kind, "."), [selection.loc]); default: selection; throw new Error(); } }); return normalizationSelections; } function generateArgumentDefinitions(schema, nodes) { return nodes.map(function (node) { return { kind: 'LocalArgument', name: node.name, type: schema.getTypeString(node.type), defaultValue: node.defaultValue }; }); } function generateClientExtension(schema, node) { return { kind: 'ClientExtension', selections: generateSelections(schema, node.selections) }; } function generateCondition(schema, node) { if (node.condition.kind !== 'Variable') { throw createCompilerError("NormalizationCodeGenerator: Expected 'Condition' with static " + 'value to be pruned or inlined', [node.condition.loc]); } return { kind: 'Condition', passingValue: node.passingValue, condition: node.condition.variableName, selections: generateSelections(schema, node.selections) }; } function generateDefer(schema, node) { if (!(node["if"] == null || node["if"].kind === 'Variable' || node["if"].kind === 'Literal' && node["if"].value === true)) { var _ref, _node$if; throw createCompilerError('NormalizationCodeGenerator: Expected @defer `if` condition to be ' + 'a variable, unspecified, or the literal `true`.', [(_ref = (_node$if = node["if"]) === null || _node$if === void 0 ? void 0 : _node$if.loc) !== null && _ref !== void 0 ? _ref : node.loc]); } return { "if": node["if"] != null && node["if"].kind === 'Variable' ? node["if"].variableName : null, kind: 'Defer', label: node.label, metadata: node.metadata, selections: generateSelections(schema, node.selections) }; } function generateInlineFragment(schema, node) { return { kind: 'InlineFragment', type: schema.getTypeString(node.typeCondition), selections: generateSelections(schema, node.selections) }; } function generateLinkedField(schema, node) { // Note: it is important that the arguments of this field be sorted to // ensure stable generation of storage keys for equivalent arguments // which may have originally appeared in different orders across an app. var handles = node.handles && node.handles.map(function (handle) { var handleNode = { kind: 'LinkedHandle', alias: node.alias === node.name ? null : node.alias, name: node.name, args: generateArgs(node.args), handle: handle.name, key: handle.key, filters: handle.filters }; // T45504512: new connection model // NOTE: this intentionally adds a dynamic key in order to avoid // triggering updates to existing queries that do not use dynamic // keys. if (handle.dynamicKey != null) { var dynamicKeyArgName = '__dynamicKey'; handleNode = (0, _objectSpread2["default"])({}, handleNode, { dynamicKey: { kind: 'Variable', name: dynamicKeyArgName, variableName: handle.dynamicKey.variableName } }); } return handleNode; }) || []; var type = schema.getRawType(node.type); var field = { kind: 'LinkedField', alias: node.alias === node.name ? null : node.alias, name: node.name, storageKey: null, args: generateArgs(node.args), concreteType: !schema.isAbstractType(type) ? schema.getTypeString(type) : null, plural: isPlural(schema, node.type), selections: generateSelections(schema, node.selections) }; // Precompute storageKey if possible var storageKey = getStaticStorageKey(field, node.metadata); if (storageKey != null) { field = (0, _objectSpread2["default"])({}, field, { storageKey: storageKey }); } return [field].concat(handles); } function generateConnectionField(schema, node) { return generateLinkedField(schema, { name: node.name, alias: node.alias, loc: node.loc, directives: node.directives, metadata: node.metadata, selections: node.selections, type: node.type, handles: null, connection: false, // this is only on the linked fields with @conneciton args: node.args.filter(function (arg) { return !ConnectionInterface.isConnectionCall({ name: arg.name, value: null }); }), kind: 'LinkedField' }); } function generateConnection(schema, node) { var _ConnectionInterface$ = ConnectionInterface.get(), EDGES = _ConnectionInterface$.EDGES, PAGE_INFO = _ConnectionInterface$.PAGE_INFO; var selections = generateSelections(schema, node.selections); var edges; var pageInfo; selections.forEach(function (selection) { if (selection.kind === 'LinkedField') { if (selection.name === EDGES) { edges = selection; } else if (selection.name === PAGE_INFO) { pageInfo = selection; } } else if (selection.kind === 'Stream') { selection.selections.forEach(function (subselection) { if (subselection.kind === 'LinkedField' && subselection.name === EDGES) { edges = subselection; } }); } else if (selection.kind === 'Defer') { selection.selections.forEach(function (subselection) { if (subselection.kind === 'LinkedField' && subselection.name === PAGE_INFO) { pageInfo = subselection; } }); } }); if (edges == null || pageInfo == null) { throw createUserError("Invalid connection, expected the '".concat(EDGES, "' and '").concat(PAGE_INFO, "' fields ") + 'to exist.', [node.loc]); } var stream = null; if (node.stream != null) { var _generateArgumentValu; var trueLiteral = { kind: 'Literal', name: 'if', value: true }; stream = { "if": node.stream["if"] != null ? (_generateArgumentValu = generateArgumentValue('if', node.stream["if"])) !== null && _generateArgumentValu !== void 0 ? _generateArgumentValu : trueLiteral : trueLiteral, deferLabel: node.stream.deferLabel, streamLabel: node.stream.streamLabel }; } return { kind: 'Connection', label: node.label, name: node.name, args: generateArgs(node.args), edges: edges, pageInfo: pageInfo, stream: stream }; } function generateModuleImport(node, key) { var fragmentName = node.name; var regExpMatch = fragmentName.match(/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/); if (!regExpMatch) { throw createCompilerError('NormalizationCodeGenerator: @module fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [node.loc]); } var fragmentPropName = regExpMatch[2]; if (typeof fragmentPropName !== 'string') { throw createCompilerError('NormalizationCodeGenerator: @module fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [node.loc]); } return { kind: 'ModuleImport', documentName: node.documentName, fragmentName: fragmentName, fragmentPropName: fragmentPropName }; } function generateScalarField(node) { var _node$metadata; if ((_node$metadata = node.metadata) === null || _node$metadata === void 0 ? void 0 : _node$metadata.skipNormalizationNode) { return []; } // Note: it is important that the arguments of this field be sorted to // ensure stable generation of storage keys for equivalent arguments // which may have originally appeared in different orders across an app. var handles = node.handles && node.handles.map(function (handle) { if (handle.dynamicKey != null) { throw createUserError('Dynamic key values are not supported on scalar fields.', [handle.dynamicKey.loc]); } return { kind: 'ScalarHandle', alias: node.alias === node.name ? null : node.alias, name: node.name, args: generateArgs(node.args), handle: handle.name, key: handle.key, filters: handle.filters }; }) || []; var field = { kind: 'ScalarField', alias: node.alias === node.name ? null : node.alias, name: node.name, args: generateArgs(node.args), storageKey: null }; // Precompute storageKey if possible var storageKey = getStaticStorageKey(field, node.metadata); if (storageKey != null) { field = (0, _objectSpread2["default"])({}, field, { storageKey: storageKey }); } return [field].concat(handles); } function generateStream(schema, node) { if (!(node["if"] == null || node["if"].kind === 'Variable' || node["if"].kind === 'Literal' && node["if"].value === true)) { var _ref2, _node$if2; throw createCompilerError('NormalizationCodeGenerator: Expected @stream `if` condition to be ' + 'a variable, unspecified, or the literal `true`.', [(_ref2 = (_node$if2 = node["if"]) === null || _node$if2 === void 0 ? void 0 : _node$if2.loc) !== null && _ref2 !== void 0 ? _ref2 : node.loc]); } return { "if": node["if"] != null && node["if"].kind === 'Variable' ? node["if"].variableName : null, kind: 'Stream', label: node.label, metadata: node.metadata, selections: generateSelections(schema, node.selections) }; } function generateArgumentValue(name, value) { switch (value.kind) { case 'Variable': return { kind: 'Variable', name: name, variableName: value.variableName }; case 'Literal': return value.value === null ? null : { kind: 'Literal', name: name, value: stableCopy(value.value) }; default: throw createUserError('NormalizationCodeGenerator: Complex argument values (Lists or ' + 'InputObjects with nested variables) are not supported.', [value.loc]); } } function generateArgs(args) { var concreteArguments = []; args.forEach(function (arg) { var concreteArgument = generateArgumentValue(arg.name, arg.value); if (concreteArgument !== null) { concreteArguments.push(concreteArgument); } }); return concreteArguments.length === 0 ? null : concreteArguments.sort(nameComparator); } function nameComparator(a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; } /** * Pre-computes storage key if possible and advantageous. Storage keys are * generated for fields with supplied arguments that are all statically known * (ie. literals, no variables) at build time. */ function getStaticStorageKey(field, metadata) { var metadataStorageKey = metadata === null || metadata === void 0 ? void 0 : metadata.storageKey; if (typeof metadataStorageKey === 'string') { return metadataStorageKey; } if (!field.args || field.args.length === 0 || field.args.some(function (arg) { return arg.kind !== 'Literal'; })) { return null; } return getStorageKey(field, {}); } function isPlural(schema, type) { return schema.isList(schema.getNullableType(type)); } module.exports = { generate: generate }; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var CodeMarker = __webpack_require__(32); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createUserError = _require.createUserError; var _require2 = __webpack_require__(9), ConnectionInterface = _require2.ConnectionInterface, getStorageKey = _require2.getStorageKey, stableCopy = _require2.stableCopy; /** * @public * * Converts a GraphQLIR node into a plain JS object representation that can be * used at runtime. */ function generate(schema, node) { if (node == null) { return node; } var metadata = null; if (node.metadata != null) { var _node$metadata = node.metadata, mask = _node$metadata.mask, plural = _node$metadata.plural, connection = _node$metadata.connection, refetch = _node$metadata.refetch; if (Array.isArray(connection)) { var _metadata; metadata = (_metadata = metadata) !== null && _metadata !== void 0 ? _metadata : {}; metadata.connection = connection; } if (typeof mask === 'boolean') { var _metadata2; metadata = (_metadata2 = metadata) !== null && _metadata2 !== void 0 ? _metadata2 : {}; metadata.mask = mask; } if (typeof plural === 'boolean') { var _metadata3; metadata = (_metadata3 = metadata) !== null && _metadata3 !== void 0 ? _metadata3 : {}; metadata.plural = plural; } if (typeof refetch === 'object') { var _metadata4; metadata = (_metadata4 = metadata) !== null && _metadata4 !== void 0 ? _metadata4 : {}; metadata.refetch = { // $FlowFixMe connection: refetch.connection, // $FlowFixMe operation: CodeMarker.moduleDependency(refetch.operation + '.graphql'), // $FlowFixMe fragmentPathInResult: refetch.fragmentPathInResult }; } } return { kind: 'Fragment', name: node.name, type: schema.getTypeString(node.type), // $FlowFixMe metadata: metadata, argumentDefinitions: generateArgumentDefinitions(schema, node.argumentDefinitions), selections: generateSelections(schema, node.selections) }; } function generateSelections(schema, selections) { return selections.map(function (selection) { switch (selection.kind) { case 'ClientExtension': return generateClientExtension(schema, selection); case 'FragmentSpread': return generateFragmentSpread(schema, selection); case 'Condition': return generateCondition(schema, selection); case 'ScalarField': return generateScalarField(schema, selection); case 'ModuleImport': return generateModuleImport(schema, selection); case 'InlineDataFragmentSpread': return generateInlineDataFragmentSpread(schema, selection); case 'InlineFragment': return generateInlineFragment(schema, selection); case 'LinkedField': return generateLinkedField(schema, selection); case 'ConnectionField': return generateConnectionField(schema, selection); case 'Connection': return generateConnection(schema, selection); case 'Defer': return generateDefer(schema, selection); case 'Stream': return generateStream(schema, selection); default: selection; throw new Error(); } }).filter(Boolean); } function generateArgumentDefinitions(schema, nodes) { return nodes.map(function (node) { switch (node.kind) { case 'LocalArgumentDefinition': return { kind: 'LocalArgument', name: node.name, type: schema.getTypeString(node.type), defaultValue: node.defaultValue }; case 'RootArgumentDefinition': return { kind: 'RootArgument', name: node.name, type: node.type ? schema.getTypeString(node.type) : null }; default: throw new Error(); } }); } function generateClientExtension(schema, node) { return { kind: 'ClientExtension', selections: generateSelections(schema, node.selections) }; } function generateDefer(schema, node) { return { kind: 'Defer', selections: generateSelections(schema, node.selections) }; } function generateStream(schema, node) { return { kind: 'Stream', selections: generateSelections(schema, node.selections) }; } function generateCondition(schema, node) { if (node.condition.kind !== 'Variable') { throw createCompilerError("ReaderCodeGenerator: Expected 'Condition' with static value to be " + 'pruned or inlined', [node.condition.loc]); } return { kind: 'Condition', passingValue: node.passingValue, condition: node.condition.variableName, selections: generateSelections(schema, node.selections) }; } function generateFragmentSpread(schema, node) { return { kind: 'FragmentSpread', name: node.name, args: generateArgs(node.args) }; } function generateInlineFragment(schema, node) { return { kind: 'InlineFragment', type: schema.getTypeString(node.typeCondition), selections: generateSelections(schema, node.selections) }; } function generateInlineDataFragmentSpread(schema, node) { return { kind: 'InlineDataFragmentSpread', name: node.name, selections: generateSelections(schema, node.selections) }; } function generateLinkedField(schema, node) { // Note: it is important that the arguments of this field be sorted to // ensure stable generation of storage keys for equivalent arguments // which may have originally appeared in different orders across an app. // TODO(T37646905) enable this invariant after splitting the // RelayCodeGenerator-test and running the FieldHandleTransform on // Reader ASTs. // // invariant( // node.handles == null, // 'ReaderCodeGenerator: unexpected handles', // ); var rawType = schema.getRawType(node.type); var field = { kind: 'LinkedField', alias: node.alias === node.name ? null : node.alias, name: node.name, storageKey: null, args: generateArgs(node.args), concreteType: !schema.isAbstractType(rawType) ? schema.getTypeString(rawType) : null, plural: isPlural(schema, node.type), selections: generateSelections(schema, node.selections) }; // Precompute storageKey if possible var storageKey = getStaticStorageKey(field, node.metadata); if (storageKey) { field = (0, _objectSpread2["default"])({}, field, { storageKey: storageKey }); } return field; } function generateConnectionField(schema, node) { return generateLinkedField(schema, { name: node.name, alias: node.alias, loc: node.loc, directives: node.directives, metadata: node.metadata, selections: node.selections, type: node.type, connection: false, // this is only on the linked fields with @conneciton handles: null, args: node.args.filter(function (arg) { return !ConnectionInterface.isConnectionCall({ name: arg.name, value: null }); }), kind: 'LinkedField' }); } function generateConnection(schema, node) { var _ConnectionInterface$ = ConnectionInterface.get(), EDGES = _ConnectionInterface$.EDGES, PAGE_INFO = _ConnectionInterface$.PAGE_INFO; var selections = generateSelections(schema, node.selections); var edges; var pageInfo; selections.forEach(function (selection) { if (selection.kind === 'LinkedField') { if (selection.name === EDGES) { edges = selection; } else if (selection.name === PAGE_INFO) { pageInfo = selection; } } else if (selection.kind === 'Stream') { selection.selections.forEach(function (subselection) { if (subselection.kind === 'LinkedField' && subselection.name === EDGES) { edges = subselection; } }); } else if (selection.kind === 'Defer') { selection.selections.forEach(function (subselection) { if (subselection.kind === 'LinkedField' && subselection.name === PAGE_INFO) { pageInfo = subselection; } }); } }); if (edges == null || pageInfo == null) { throw createUserError("Invalid connection, expected the '".concat(EDGES, "' and '").concat(PAGE_INFO, "' fields ") + 'to exist.', [node.loc]); } return { kind: 'Connection', label: node.label, name: node.name, args: generateArgs(node.args), edges: edges, pageInfo: pageInfo }; } function generateModuleImport(schema, node) { var fragmentName = node.name; var regExpMatch = fragmentName.match(/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/); if (!regExpMatch) { throw createCompilerError('ReaderCodeGenerator: @match fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [node.loc]); } var fragmentPropName = regExpMatch[2]; if (typeof fragmentPropName !== 'string') { throw createCompilerError('ReaderCodeGenerator: @module fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [node.loc]); } return { kind: 'ModuleImport', documentName: node.documentName, fragmentName: fragmentName, fragmentPropName: fragmentPropName }; } function generateScalarField(schema, node) { // Note: it is important that the arguments of this field be sorted to // ensure stable generation of storage keys for equivalent arguments // which may have originally appeared in different orders across an app. // TODO(T37646905) enable this invariant after splitting the // RelayCodeGenerator-test and running the FieldHandleTransform on // Reader ASTs. // // invariant( // node.handles == null, // 'ReaderCodeGenerator: unexpected handles', // ); var field = { kind: 'ScalarField', alias: node.alias === node.name ? null : node.alias, name: node.name, args: generateArgs(node.args), storageKey: null }; // Precompute storageKey if possible var storageKey = getStaticStorageKey(field, node.metadata); if (storageKey) { field = (0, _objectSpread2["default"])({}, field, { storageKey: storageKey }); } return field; } function generateArgument(node) { var value = node.value; switch (value.kind) { case 'Variable': return { kind: 'Variable', name: node.name, variableName: value.variableName }; case 'Literal': return value.value === null ? null : { kind: 'Literal', name: node.name, value: stableCopy(value.value) }; default: throw createUserError('ReaderCodeGenerator: Complex argument values (Lists or ' + 'InputObjects with nested variables) are not supported.', [node.value.loc]); } } function generateArgs(args) { var concreteArguments = []; args.forEach(function (arg) { var concreteArgument = generateArgument(arg); if (concreteArgument !== null) { concreteArguments.push(concreteArgument); } }); return concreteArguments.length === 0 ? null : concreteArguments.sort(nameComparator); } function nameComparator(a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; } /** * Pre-computes storage key if possible and advantageous. Storage keys are * generated for fields with supplied arguments that are all statically known * (ie. literals, no variables) at build time. */ function getStaticStorageKey(field, metadata) { var metadataStorageKey = metadata === null || metadata === void 0 ? void 0 : metadata.storageKey; if (typeof metadataStorageKey === 'string') { return metadataStorageKey; } if (!field.args || field.args.length === 0 || field.args.some(function (arg) { return arg.kind !== 'Literal'; })) { return null; } return getStorageKey(field, {}); } function isPlural(schema, type) { return schema.isList(schema.getNullableType(type)); } module.exports = { generate: generate }; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLCompilerContext = __webpack_require__(19); var _require = __webpack_require__(15), visit = _require.visit; /** * Returns a GraphQLCompilerContext containing only the documents referenced * by and including the provided node. */ function filterContextForNode(node, context) { var queue = [node]; var filteredContext = new GraphQLCompilerContext(context.getSchema()).add(node); var visitFragmentSpread = function visitFragmentSpread(fragmentSpread) { var name = fragmentSpread.name; if (!filteredContext.get(name)) { var fragment = context.getFragment(name); filteredContext = filteredContext.add(fragment); queue.push(fragment); } }; var visitorConfig = { FragmentSpread: function FragmentSpread(fragmentSpread) { visitFragmentSpread(fragmentSpread); } }; while (queue.length) { visit(queue.pop(), visitorConfig); } return filteredContext; } module.exports = filterContextForNode; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _asyncToGenerator = __webpack_require__(10); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var CodeMarker = __webpack_require__(32); var Profiler = __webpack_require__(6); var createPrintRequireModuleDependency = __webpack_require__(69); var crypto = __webpack_require__(12); var dedupeJSONStringify = __webpack_require__(70); var invariant = __webpack_require__(4); var _require = __webpack_require__(9), RelayConcreteNode = _require.RelayConcreteNode; function getConcreteType(node) { switch (node.kind) { case RelayConcreteNode.FRAGMENT: return 'ReaderFragment'; case RelayConcreteNode.REQUEST: return 'ConcreteRequest'; case RelayConcreteNode.SPLIT_OPERATION: return 'NormalizationSplitOperation'; case RelayConcreteNode.INLINE_DATA_FRAGMENT: return 'ReaderInlineDataFragment'; default: node; true ? true ? invariant(false, 'Unexpected GeneratedNode kind: `%s`.', node.kind) : undefined : undefined; } } function writeRelayGeneratedFile(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9, _x10) { return _writeRelayGeneratedFile.apply(this, arguments); } function _writeRelayGeneratedFile() { _writeRelayGeneratedFile = _asyncToGenerator(function* (schema, codegenDir, definition, _generatedNode, formatModule, typeText, _persistQuery, platform, sourceHash, extension) { var printModuleDependency = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : createPrintRequireModuleDependency(extension); var shouldRepersist = arguments.length > 11 ? arguments[11] : undefined; var generatedNode = _generatedNode; // Copy to const so Flow can refine. var persistQuery = _persistQuery; var moduleName = (generatedNode.kind === 'Request' ? generatedNode.params.name : generatedNode.name) + '.graphql'; var platformName = platform != null && platform.length > 0 ? moduleName + '.' + platform : moduleName; var filename = platformName + '.' + extension; var typeName = getConcreteType(generatedNode); var docText; if (generatedNode.kind === RelayConcreteNode.REQUEST) { docText = generatedNode.params.text; } var hash = null; if (generatedNode.kind === RelayConcreteNode.REQUEST) { var oldContent; var oldHash = Profiler.run('RelayFileWriter:compareHash', function () { oldContent = codegenDir.read(filename); // Hash the concrete node including the query text. var hasher = crypto.createHash('md5'); hasher.update('cache-breaker-9'); hasher.update(JSON.stringify(generatedNode)); hasher.update(sourceHash); if (typeText) { hasher.update(typeText); } if (persistQuery) { hasher.update('persisted'); } hash = hasher.digest('hex'); return extractHash(oldContent); }); var oldRequestParameters = extractRelayRequestParams(oldContent); if (!shouldRepersist && hash === oldHash) { codegenDir.markUnchanged(filename); return oldRequestParameters ? (0, _objectSpread2["default"])({}, generatedNode, { params: oldRequestParameters }) : null; } if (codegenDir.onlyValidate) { codegenDir.markUpdated(filename); return null; } if (persistQuery) { switch (generatedNode.kind) { case RelayConcreteNode.REQUEST: var _text = generatedNode.params.text; !(_text != null) ? true ? invariant(false, 'writeRelayGeneratedFile: Expected `text` in order to persist query') : undefined : void 0; generatedNode = (0, _objectSpread2["default"])({}, generatedNode, { params: { operationKind: generatedNode.params.operationKind, name: generatedNode.params.name, id: yield persistQuery(_text), text: null, metadata: generatedNode.params.metadata } }); break; case RelayConcreteNode.FRAGMENT: // Do not persist fragments. break; default: generatedNode.kind; } } } var moduleText = formatModule({ moduleName: moduleName, documentType: typeName, definition: definition, kind: generatedNode.kind, docText: docText, typeText: typeText, hash: hash ? "@relayHash ".concat(hash) : null, concreteText: CodeMarker.postProcess(dedupeJSONStringify(generatedNode), printModuleDependency), sourceHash: sourceHash, node: generatedNode, schema: schema }); codegenDir.writeFile(filename, moduleText, shouldRepersist); return generatedNode; }); return _writeRelayGeneratedFile.apply(this, arguments); } function extractHash(text) { if (text == null || text.length === 0) { return null; } if (/<<<<<|>>>>>/.test(text)) { // looks like a merge conflict return null; } var match = text.match(/@relayHash (\w{32})\b/m); return match && match[1]; } function extractRelayRequestParams(text) { if (text == null || text.length === 0) { return null; } if (/<<<<<|>>>>>/.test(text)) { // looks like a merge conflict return null; } var match = text.match(/@relayRequestParams (.+)/); var requestParams; try { var _ref; requestParams = JSON.parse((_ref = match === null || match === void 0 ? void 0 : match[1]) !== null && _ref !== void 0 ? _ref : ''); } catch (_unused) {} return requestParams; } module.exports = writeRelayGeneratedFile; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ function createPrintRequireModuleDependency(extension) { return function (moduleName) { return "require('./".concat(moduleName, ".").concat(extension, "')"); }; } module.exports = createPrintRequireModuleDependency; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /** * This function works similar to JSON.stringify except that for the case there * are multiple common subtrees, it generates a string for a IIFE that re-uses * the same objects for the duplicate subtrees. */ function dedupeJSONStringify(jsonValue) { // Clone the object to convert references to the same object instance into // copies. This is needed for the WeakMap/Map to recognize them as duplicates. // $FlowFixMe(>=0.95.0) JSON.stringify can return undefined jsonValue = JSON.parse(JSON.stringify(jsonValue)); var metadataForHash = new Map(); var metadataForVal = new WeakMap(); var varDefs = []; collectMetadata(jsonValue); collectDuplicates(jsonValue); var code = printJSCode(false, '', jsonValue); return varDefs.length === 0 ? code : "(function(){\nvar ".concat(varDefs.join(',\n'), ";\nreturn ").concat(code, ";\n})()"); // Collect common metadata for each object in the value tree, ensuring that // equivalent values have the *same reference* to the same metadata. Note that // the hashes generated are not exactly JSON, but still identify equivalent // values. Runs in linear time due to hashing in a bottom-up recursion. function collectMetadata(value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } var hash; if (Array.isArray(value)) { hash = '['; for (var i = 0; i < value.length; i++) { hash += collectMetadata(value[i]) + ','; } } else { hash = '{'; for (var k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { hash += k + ':' + collectMetadata(value[k]) + ','; } } } var metadata = metadataForHash.get(hash); if (!metadata) { metadata = { value: value, hash: hash, isDuplicate: false }; metadataForHash.set(hash, metadata); } metadataForVal.set(value, metadata); return hash; } // Using top-down recursion, linearly scan the JSON tree to determine which // values should be deduplicated. function collectDuplicates(value) { if (value == null || typeof value !== 'object') { return; } var metadata = metadataForVal.get(value); // Only consider duplicates with hashes longer than 2 (excludes [] and {}). if (metadata && metadata.value !== value && metadata.hash.length > 2) { metadata.isDuplicate = true; return; } if (Array.isArray(value)) { for (var i = 0; i < value.length; i++) { collectDuplicates(value[i]); } } else { for (var k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { collectDuplicates(value[k]); } } } } // Stringify JS, replacing duplicates with variable references. function printJSCode(isDupedVar, depth, value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } // Only use variable references at depth beyond the top level. if (depth !== '') { var metadata = metadataForVal.get(value); if (metadata && metadata.isDuplicate) { if (!metadata.varName) { var refCode = printJSCode(true, '', value); metadata.varName = 'v' + varDefs.length; varDefs.push(metadata.varName + ' = ' + refCode); } return '(' + metadata.varName + '/*: any*/)'; } } var str; var isEmpty = true; var depth2 = depth + ' '; if (Array.isArray(value)) { // Empty arrays can only have one inferred flow type and then conflict if // used in different places, this is unsound if we would write to them but // this whole module is based on the idea of a read only JSON tree. if (isDupedVar && value.length === 0) { return '([]/*: any*/)'; } str = '['; for (var i = 0; i < value.length; i++) { str += (isEmpty ? '\n' : ',\n') + depth2 + printJSCode(isDupedVar, depth2, value[i]); isEmpty = false; } str += isEmpty ? ']' : "\n".concat(depth, "]"); } else { str = '{'; for (var k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { str += (isEmpty ? '\n' : ',\n') + depth2 + JSON.stringify(k) + ': ' + printJSCode(isDupedVar, depth2, value[k]); isEmpty = false; } } str += isEmpty ? '}' : "\n".concat(depth, "}"); } return str; } } module.exports = dedupeJSONStringify; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /** * Helpers to retieve the name of the document from which the input derives: * this is either the name of the input itself (if it is not a derived node) * or the metadata.derivedFrom property for derived nodes. */ // Version for generated nodes function getReaderSourceDefinitionName(node) { var _node$params$metadata, _node$metadata; var _ref = node.kind === 'Request' ? [node.params.name, (_node$params$metadata = node.params.metadata) === null || _node$params$metadata === void 0 ? void 0 : _node$params$metadata.derivedFrom] : node.kind === 'SplitOperation' ? [node.name, (_node$metadata = node.metadata) === null || _node$metadata === void 0 ? void 0 : _node$metadata.derivedFrom] : [node.name, null], name = _ref[0], derivedFrom = _ref[1]; return typeof derivedFrom === 'string' ? derivedFrom : name; } // Version for IR function getSourceDefinitionName(node) { var _node$metadata2; var derivedFrom = node.kind === 'Request' || node.kind === 'Root' || node.kind === 'SplitOperation' ? (_node$metadata2 = node.metadata) === null || _node$metadata2 === void 0 ? void 0 : _node$metadata2.derivedFrom : null; return typeof derivedFrom === 'string' ? derivedFrom : node.name; } module.exports = { getReaderSourceDefinitionName: getReaderSourceDefinitionName, getSourceDefinitionName: getSourceDefinitionName }; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var ApplyFragmentArgumentTransform = __webpack_require__(73); var ClientExtensionsTransform = __webpack_require__(76); var ConnectionFieldTransform = __webpack_require__(34); var ConnectionTransform = __webpack_require__(35); var DeferStreamTransform = __webpack_require__(77); var DisallowIdAsAlias = __webpack_require__(78); var FieldHandleTransform = __webpack_require__(79); var FilterDirectivesTransform = __webpack_require__(80); var FlattenTransform = __webpack_require__(36); var GenerateIDFieldTransform = __webpack_require__(82); var GenerateTypeNameTransform = __webpack_require__(83); var InlineDataFragmentTransform = __webpack_require__(84); var InlineFragmentsTransform = __webpack_require__(85); var MaskTransform = __webpack_require__(39); var MatchTransform = __webpack_require__(40); var RefetchableFragmentTransform = __webpack_require__(42); var RelayDirectiveTransform = __webpack_require__(43); var RelayFlowGenerator = __webpack_require__(44); var SkipClientExtensionsTransform = __webpack_require__(93); var SkipHandleFieldTransform = __webpack_require__(94); var SkipRedundantNodesTransform = __webpack_require__(95); var SkipUnreachableNodeTransform = __webpack_require__(96); var SkipUnusedVariablesTransform = __webpack_require__(97); var SplitModuleImportTransform = __webpack_require__(98); var TestOperationTransform = __webpack_require__(99); var ValidateGlobalVariablesTransform = __webpack_require__(100); var ValidateRequiredArgumentsTransform = __webpack_require__(101); var ValidateServerOnlyDirectivesTransform = __webpack_require__(102); var ValidateUnusedVariablesTransform = __webpack_require__(103); // Transforms applied to the code used to process a query response. var relaySchemaExtensions = [ConnectionTransform.SCHEMA_EXTENSION, MatchTransform.SCHEMA_EXTENSION, ConnectionFieldTransform.SCHEMA_EXTENSION, RelayDirectiveTransform.SCHEMA_EXTENSION, RefetchableFragmentTransform.SCHEMA_EXTENSION, TestOperationTransform.SCHEMA_EXTENSION, InlineDataFragmentTransform.SCHEMA_EXTENSION, RelayFlowGenerator.SCHEMA_EXTENSION, ValidateUnusedVariablesTransform.SCHEMA_EXTENSION]; // Transforms applied to both operations and fragments for both reading and // writing from the store. var relayCommonTransforms = [DisallowIdAsAlias.transform, ConnectionTransform.transform, RelayDirectiveTransform.transform, MaskTransform.transform, MatchTransform.transform, ConnectionFieldTransform.transform, RefetchableFragmentTransform.transform, DeferStreamTransform.transform]; // Transforms applied to fragments used for reading data from a store var relayFragmentTransforms = [ClientExtensionsTransform.transform, FieldHandleTransform.transform, InlineDataFragmentTransform.transform, FlattenTransform.transformWithOptions({ flattenAbstractTypes: true }), SkipRedundantNodesTransform.transform]; // Transforms applied to queries/mutations/subscriptions that are used for // fetching data from the server and parsing those responses. var relayQueryTransforms = [ValidateUnusedVariablesTransform.transform, ApplyFragmentArgumentTransform.transform, ValidateGlobalVariablesTransform.transform, GenerateIDFieldTransform.transform, TestOperationTransform.transform]; // Transforms applied to the code used to process a query response. var relayCodegenTransforms = [SkipUnreachableNodeTransform.transform, SplitModuleImportTransform.transform, InlineFragmentsTransform.transform, // NOTE: For the codegen context, we make sure to run ClientExtensions // transform after we've inlined fragment spreads (i.e. InlineFragmentsTransform) // This will ensure that we don't generate nested ClientExtension nodes ClientExtensionsTransform.transform, FlattenTransform.transformWithOptions({ flattenAbstractTypes: true }), SkipRedundantNodesTransform.transform, GenerateTypeNameTransform.transform, ValidateServerOnlyDirectivesTransform.transform]; // Transforms applied before printing the query sent to the server. var relayPrintTransforms = [// NOTE: Skipping client extensions might leave empty selections, which we // skip by running SkipUnreachableNodeTransform immediately after. ClientExtensionsTransform.transform, SkipClientExtensionsTransform.transform, SkipUnreachableNodeTransform.transform, FlattenTransform.transformWithOptions({}), GenerateTypeNameTransform.transform, SkipHandleFieldTransform.transform, FilterDirectivesTransform.transform, SkipUnusedVariablesTransform.transform, ValidateRequiredArgumentsTransform.transform]; module.exports = { commonTransforms: relayCommonTransforms, codegenTransforms: relayCodegenTransforms, fragmentTransforms: relayFragmentTransforms, printTransforms: relayPrintTransforms, queryTransforms: relayQueryTransforms, schemaExtensions: relaySchemaExtensions }; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var RelayCompilerScope = __webpack_require__(74); var getIdentifierForArgumentValue = __webpack_require__(75); var murmurHash = __webpack_require__(33); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createNonRecoverableUserError = _require.createNonRecoverableUserError; var getFragmentScope = RelayCompilerScope.getFragmentScope, getRootScope = RelayCompilerScope.getRootScope; /** * A transform that converts a set of documents containing fragments/fragment * spreads *with* arguments to one where all arguments have been inlined. This * is effectively static currying of functions. Nodes are changed as follows: * - Fragment spreads with arguments are replaced with references to an inlined * version of the referenced fragment. * - Fragments with argument definitions are cloned once per unique set of * arguments, with the name changed to original name + hash and all nested * variable references changed to the value of that variable given its * arguments. * - Field & directive argument variables are replaced with the value of those * variables in context. * - All nodes are cloned with updated children. * * The transform also handles statically passing/failing Condition nodes: * - Literal Conditions with a passing value are elided and their selections * inlined in their parent. * - Literal Conditions with a failing value are removed. * - Nodes that would become empty as a result of the above are removed. * * Note that unreferenced fragments are not added to the output. */ function applyFragmentArgumentTransform(context) { var fragments = new Map(); var nextContext = IRTransformer.transform(context, { Root: function Root(node) { var scope = getRootScope(node.argumentDefinitions); return transformNode(context, fragments, scope, node, [node]); }, // Fragments are included below where referenced. // Unreferenced fragments are not included. Fragment: function Fragment() { return null; } }); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fragments.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var pendingFragment = _step.value; if (pendingFragment.kind === 'resolved' && pendingFragment.value) { nextContext = nextContext.add(pendingFragment.value); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return nextContext; } function transformNode(context, fragments, scope, node, errorContext) { var selections = transformSelections(context, fragments, scope, node.selections, errorContext); if (!selections) { return null; } if (node.hasOwnProperty('directives')) { var directives = transformDirectives(scope, node.directives, errorContext); // $FlowIssue: this is a valid `Node`: return (0, _objectSpread2["default"])({}, node, { directives: directives, selections: selections }); } return (0, _objectSpread2["default"])({}, node, { selections: selections }); } function transformFragmentSpread(context, fragments, scope, spread, errorContext) { var directives = transformDirectives(scope, spread.directives, errorContext); var appliedFragment = transformFragment(context, fragments, scope, spread, spread.args, [].concat((0, _toConsumableArray2["default"])(errorContext), [spread])); if (!appliedFragment) { return null; } var transformed = (0, _objectSpread2["default"])({}, spread, { kind: 'FragmentSpread', args: [], directives: directives, name: appliedFragment.name }); return transformed; } function transformField(context, fragments, scope, field, errorContext) { var args = transformArguments(scope, field.args, errorContext); var directives = transformDirectives(scope, field.directives, errorContext); if (field.kind === 'LinkedField' || field.kind === 'ConnectionField') { var selections = transformSelections(context, fragments, scope, field.selections, errorContext); if (!selections) { return null; } return (0, _objectSpread2["default"])({}, field, { args: args, directives: directives, selections: selections }); } else { return (0, _objectSpread2["default"])({}, field, { args: args, directives: directives }); } } function transformConnection(context, fragments, scope, connection, errorContext) { var args = transformArguments(scope, connection.args, errorContext); var stream = connection.stream; if (stream != null) { stream = (0, _objectSpread2["default"])({}, stream, { "if": stream["if"] != null ? transformValue(scope, stream["if"], errorContext) : null, initialCount: transformValue(scope, stream.initialCount, errorContext) }); } var selections = transformSelections(context, fragments, scope, connection.selections, errorContext); if (!selections) { return null; } return (0, _objectSpread2["default"])({}, connection, { args: args, selections: selections, stream: stream }); } function transformCondition(context, fragments, scope, node, errorContext) { var condition = transformValue(scope, node.condition, errorContext); if (!(condition.kind === 'Literal' || condition.kind === 'Variable')) { // This transform does whole-program optimization, errors in // a single document could break invariants and/or cause // additional spurious errors. throw createNonRecoverableUserError('A non-scalar value was applied to an @include or @skip directive, ' + 'the `if` argument value must be a ' + 'variable or a literal Boolean.', [condition.loc]); } if (condition.kind === 'Literal' && condition.value !== node.passingValue) { // Dead code, no need to traverse further. return null; } var selections = transformSelections(context, fragments, scope, node.selections, errorContext); if (!selections) { return null; } if (condition.kind === 'Literal' && condition.value === node.passingValue) { // Always passes, return inlined selections return selections; } return [(0, _objectSpread2["default"])({}, node, { condition: condition, selections: selections })]; } function transformSelections(context, fragments, scope, selections, errorContext) { var nextSelections = null; selections.forEach(function (selection) { var nextSelection; if (selection.kind === 'ClientExtension' || selection.kind === 'InlineDataFragmentSpread' || selection.kind === 'InlineFragment' || selection.kind === 'ModuleImport' || selection.kind === 'Defer' || selection.kind === 'Stream') { nextSelection = transformNode(context, fragments, scope, selection, errorContext); } else if (selection.kind === 'FragmentSpread') { nextSelection = transformFragmentSpread(context, fragments, scope, selection, errorContext); } else if (selection.kind === 'Condition') { var conditionSelections = transformCondition(context, fragments, scope, selection, errorContext); if (conditionSelections) { var _nextSelections; nextSelections = nextSelections || []; (_nextSelections = nextSelections).push.apply(_nextSelections, (0, _toConsumableArray2["default"])(conditionSelections)); } } else if (selection.kind === 'Connection') { nextSelection = transformConnection(context, fragments, scope, selection, errorContext); } else if (selection.kind === 'LinkedField' || selection.kind === 'ScalarField' || selection.kind === 'ConnectionField') { nextSelection = transformField(context, fragments, scope, selection, errorContext); } else { selection; throw createCompilerError("ApplyFragmentArgumentTransform: Unsupported kind '".concat(selection.kind, "'."), [selection.loc]); } if (nextSelection) { nextSelections = nextSelections || []; nextSelections.push(nextSelection); } }); return nextSelections; } function transformDirectives(scope, directives, errorContext) { return directives.map(function (directive) { var args = transformArguments(scope, directive.args, errorContext); return (0, _objectSpread2["default"])({}, directive, { args: args }); }); } function transformArguments(scope, args, errorContext) { return args.map(function (arg) { var value = transformValue(scope, arg.value, errorContext); return value === arg.value ? arg : (0, _objectSpread2["default"])({}, arg, { value: value }); }); } function transformValue(scope, value, errorContext) { if (value.kind === 'Variable') { var scopeValue = scope[value.variableName]; if (scopeValue == null) { var _errorContext$; // This transform does whole-program optimization, errors in // a single document could break invariants and/or cause // additional spurious errors. throw createNonRecoverableUserError("Variable '$".concat(value.variableName, "' is not in scope."), [(_errorContext$ = errorContext[0]) === null || _errorContext$ === void 0 ? void 0 : _errorContext$.loc, value.loc].filter(Boolean)); } return scopeValue; } return value; } /** * Apply arguments to a fragment, creating a new fragment (with the given name) * with all values recursively applied. */ function transformFragment(context, fragments, parentScope, spread, args, errorContext) { var schema = context.getSchema(); var fragment = context.getFragment(spread.name, spread.loc); var argumentsHash = hashArguments(args, parentScope, errorContext); var fragmentName = argumentsHash ? "".concat(fragment.name, "_").concat(argumentsHash) : fragment.name; var appliedFragment = fragments.get(fragmentName); if (appliedFragment) { if (appliedFragment.kind === 'resolved') { return appliedFragment.value; } else { // This transform does whole-program optimization, errors in // a single document could break invariants and/or cause // additional spurious errors. throw createNonRecoverableUserError("Found a circular reference from fragment '".concat(fragment.name, "'."), errorContext.map(function (node) { return node.loc; })); } } var fragmentScope = getFragmentScope(schema, fragment.argumentDefinitions, args, parentScope, spread); // record that this fragment is pending to detect circular references fragments.set(fragmentName, { kind: 'pending' }); var transformedFragment = null; var selections = transformSelections(context, fragments, fragmentScope, fragment.selections, errorContext); if (selections) { transformedFragment = (0, _objectSpread2["default"])({}, fragment, { selections: selections, name: fragmentName, argumentDefinitions: [] }); } fragments.set(fragmentName, { kind: 'resolved', value: transformedFragment }); return transformedFragment; } function hashArguments(args, scope, errorContext) { if (!args.length) { return null; } var sortedArgs = (0, _toConsumableArray2["default"])(args).sort(function (a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }); var printedArgs = JSON.stringify(sortedArgs.map(function (arg) { var value; if (arg.value.kind === 'Variable') { value = scope[arg.value.variableName]; if (value == null) { var _errorContext$2; // This transform does whole-program optimization, errors in // a single document could break invariants and/or cause // additional spurious errors. throw createNonRecoverableUserError("Variable '$".concat(arg.value.variableName, "' is not in scope."), [(_errorContext$2 = errorContext[0]) === null || _errorContext$2 === void 0 ? void 0 : _errorContext$2.loc, arg.value.loc].filter(Boolean)); } } else { value = arg.value; } return { name: arg.name, value: getIdentifierForArgumentValue(value) }; })); return murmurHash(printedArgs); } module.exports = { transform: applyFragmentArgumentTransform }; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(1), createUserError = _require.createUserError, eachWithCombinedError = _require.eachWithCombinedError; /** * Creates a scope for a `Root`, with each argument mapped to a variable of the * same name. Example: * * Query: * query Foo($id: ID, $size: Int = 42) { ... } * * Scope: * { * id: $id, * size: $size, * } * * Note that even though a default value is defined for $size, the scope must * assume that this could be overridden at runtime. The value cannot be decided * statically and therefore is set to a variable. */ function getRootScope(definitions) { var scope = {}; definitions.forEach(function (definition) { scope[definition.name] = { kind: 'Variable', loc: definition.loc, variableName: definition.name, type: definition.type }; }); return scope; } /** * Creates a scope for a `Fragment` by translating fragment spread arguments in * the context of a parent scope into a new scope and validating them against * the argument definitions. * * * Parent Scope: * { * active: $parentActive * } * * Fragment Spread: * ...Bar(size: 42, enabled: $active) * * Fragment: * fragment Bar on Foo @argumentDefinitions( * id: {type: "ID"} * size: {type: "Int"} * enabled: {type: "Boolean} * scale: {type: "Int", imports: "pixelRatio"} * ) * * Scope: * { * // No argument is provided for $id, it gets the default value which in this * // case is `null`: * id: null, * * // The parent passes 42 as a literal value for $size: * size: 42, * * // The parent passes a variable as the value of $enabled. This variable is * // resolved in the parent scope to the value $parentActive, which becomes * // the value of $enabled: * $enabled: $parentActive, * * // $scale imports pixelRatio from the root scope. Since any argument in a * // root scope maps to a variable of the same name, that means the value of * // pixelRatio in the root is $pixelRatio: * $scale: $pixelRatio, * } */ function getFragmentScope(schema, definitions, args, parentScope, spread) { var argMap = new Map(); args.forEach(function (arg) { if (arg.value.kind === 'Literal') { argMap.set(arg.name, arg.value); } else if (arg.value.kind === 'Variable') { argMap.set(arg.name, parentScope[arg.value.variableName]); } }); var fragmentScope = {}; eachWithCombinedError(definitions, function (definition) { if (definition.kind === 'RootArgumentDefinition') { if (argMap.has(definition.name)) { var _ref; var argNode = args.find(function (a) { return a.name === definition.name; }); throw createUserError("Unexpected argument '".concat(definition.name, "' supplied to fragment '").concat(spread.name, "'. @arguments may only be provided for variables defined in the fragment's @argumentDefinitions."), [(_ref = argNode === null || argNode === void 0 ? void 0 : argNode.loc) !== null && _ref !== void 0 ? _ref : spread.loc]); } fragmentScope[definition.name] = { kind: 'Variable', loc: definition.loc, variableName: definition.name, type: definition.type }; } else { var arg = argMap.get(definition.name); if (arg == null || arg.kind === 'Literal' && arg.value == null) { // No variable or literal null was passed, fall back to default // value. if (definition.defaultValue == null && schema.isNonNull(definition.type)) { var _ref2; var _argNode = args.find(function (a) { return a.name === definition.name; }); throw createUserError("No value found for required argument '".concat(definition.name, ": ").concat(schema.getTypeString(definition.type), "' on fragment '").concat(spread.name, "'."), [(_ref2 = _argNode === null || _argNode === void 0 ? void 0 : _argNode.loc) !== null && _ref2 !== void 0 ? _ref2 : spread.loc]); } fragmentScope[definition.name] = { kind: 'Literal', value: definition.defaultValue }; } else { // Variable or non-null literal. fragmentScope[definition.name] = arg; } } }); return fragmentScope; } module.exports = { getFragmentScope: getFragmentScope, getRootScope: getRootScope }; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var invariant = __webpack_require__(4); /** * Generates an identifier for an argument value. The identifier is based on the * structure/order of items and keys in the value. */ function getIdentifierForArgumentValue(value) { switch (value.kind) { case 'Variable': return { variable: value.variableName }; case 'Literal': return { value: value.value }; default: true ? true ? invariant(false, 'getIdentifierForArgumentValue(): Unsupported AST kind `%s`.', value.kind) : undefined : undefined; } } module.exports = getIdentifierForArgumentValue; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var GraphQLIRTransformer = __webpack_require__(3); var _require = __webpack_require__(1), createCompilerError = _require.createCompilerError, createUserError = _require.createUserError; var cachesByNode = new Map(); function clientExtensionTransform(context) { cachesByNode = new Map(); return GraphQLIRTransformer.transform(context, { Fragment: traverseDefinition, Root: traverseDefinition, SplitOperation: traverseDefinition }); } function traverseDefinition(node) { var compilerContext = this.getContext(); var schema = compilerContext.getSchema(); var rootType; switch (node.kind) { case 'Root': switch (node.operation) { case 'query': rootType = schema.getQueryType(); break; case 'mutation': rootType = schema.getMutationType(); break; case 'subscription': rootType = schema.getSubscriptionType(); break; default: node.operation; } break; case 'SplitOperation': if (!schema.isServerType(node.type)) { throw createUserError('ClientExtensionTransform: SplitOperation (@module) can be created ' + 'only for fragments that defined on a server type', [node.loc]); } rootType = node.type; break; case 'Fragment': rootType = node.type; break; default: node; } if (rootType == null) { throw createUserError("ClientExtensionTransform: Expected the type of `".concat(node.name, "` to have been defined in the schema. Make sure both server and ") + 'client schema are up to date.', [node.loc]); } return traverseSelections(node, compilerContext, rootType); } function traverseSelections(node, compilerContext, parentType) { var nodeCache = cachesByNode.get(node); if (nodeCache == null) { nodeCache = new Map(); cachesByNode.set(node, nodeCache); } var result = nodeCache.get(parentType); if (result != null) { // $FlowFixMe - TODO: type IRTransformer to allow changing result type return result; } var schema = compilerContext.getSchema(); var clientSelections = []; var serverSelections = cowMap(node.selections, function (selection) { switch (selection.kind) { case 'ClientExtension': throw createCompilerError('Unexpected ClientExtension node before ClientExtensionTransform', [selection.loc]); case 'Condition': case 'Connection': case 'Defer': case 'InlineDataFragmentSpread': case 'ModuleImport': case 'Stream': return traverseSelections(selection, compilerContext, parentType); case 'ScalarField': if (schema.isClientDefinedField(schema.assertCompositeType(schema.getRawType(parentType)), selection)) { clientSelections.push(selection); return null; } else { return selection; } case 'ConnectionField': case 'LinkedField': { if (schema.isClientDefinedField(schema.assertCompositeType(schema.getRawType(parentType)), selection)) { clientSelections.push(selection); return null; } return traverseSelections(selection, compilerContext, selection.type); } case 'InlineFragment': { var isClientType = !schema.isServerType(selection.typeCondition); if (isClientType) { clientSelections.push(selection); return null; } return traverseSelections(selection, compilerContext, selection.typeCondition); } case 'FragmentSpread': { var fragment = compilerContext.getFragment(selection.name, selection.loc); var _isClientType = !schema.isServerType(fragment.type); if (_isClientType) { clientSelections.push(selection); return null; } return selection; } default: selection; throw createCompilerError("ClientExtensionTransform: Unexpected selection of kind `".concat(selection.kind, "`."), [selection.loc]); } }); if (clientSelections.length === 0) { if (serverSelections === node.selections) { result = node; } else { result = (0, _objectSpread2["default"])({}, node, { selections: serverSelections }); } } else { result = (0, _objectSpread2["default"])({}, node, { selections: [].concat((0, _toConsumableArray2["default"])(serverSelections), [// Group client fields under a single ClientExtension node { kind: 'ClientExtension', loc: node.loc, metadata: null, selections: clientSelections }]) }); } nodeCache.set(parentType, result); // $FlowFixMe - TODO: type IRTransformer to allow changing result type return result; } /** * Maps an array with copy-on-write semantics. * `null` return values from the map function are removals. */ function cowMap(selections, f) { for (var i = 0; i < selections.length; i++) { var prevSelection = selections[i]; var nextSelection = f(prevSelection); if (prevSelection !== nextSelection) { var result = selections.slice(0, i); if (nextSelection != null) { result.push(nextSelection); } for (var j = i + 1; j < selections.length; j++) { var innerNextSelection = f(selections[j]); if (innerNextSelection != null) { result.push(innerNextSelection); } } return result; } } // nothing changed, return original return selections; } module.exports = { transform: clientExtensionTransform }; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var murmurHash = __webpack_require__(33); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(9), ConnectionInterface = _require2.ConnectionInterface; /** * This transform finds usages of @defer and @stream, validates them, and * converts the using node to specialized IR nodes (Defer/Stream). */ function deferStreamTransform(context) { return IRTransformer.transform(context, { Connection: visitConnection, // TODO: type IRTransformer to allow changing result type FragmentSpread: visitFragmentSpread, // TODO: type IRTransformer to allow changing result type InlineFragment: visitInlineFragment, // TODO: type IRTransformer to allow changing result type LinkedField: visitLinkedField, ScalarField: visitScalarField }, function (sourceNode) { var labels = new Map(); return { documentName: sourceNode.name, recordLabel: function recordLabel(label, directive) { var prevDirective = labels.get(label); if (prevDirective) { var _ref; var labelArg = directive.args.find(function (_ref4) { var name = _ref4.name; return name === 'label'; }); var prevLabelArg = prevDirective.args.find(function (_ref5) { var name = _ref5.name; return name === 'label'; }); var previousLocation = (_ref = prevLabelArg === null || prevLabelArg === void 0 ? void 0 : prevLabelArg.loc) !== null && _ref !== void 0 ? _ref : prevDirective.loc; if (labelArg) { throw createUserError("Invalid use of @".concat(directive.name, ", the provided label is ") + "not unique. Specify a unique 'label' as a literal string.", [labelArg === null || labelArg === void 0 ? void 0 : labelArg.loc, previousLocation]); } else { throw createUserError("Invalid use of @".concat(directive.name, ", could not generate a ") + "default label that is unique. Specify a unique 'label' " + 'as a literal string.', [directive.loc, previousLocation]); } } labels.set(label, directive); } }; }); } function visitConnection(connection, state) { var transformed = this.traverse(connection, state); var stream = transformed.stream; if (stream == null) { return transformed; } var _ConnectionInterface$ = ConnectionInterface.get(), EDGES = _ConnectionInterface$.EDGES, PAGE_INFO = _ConnectionInterface$.PAGE_INFO; var edges = transformed.selections.find(function (selection) { return selection.kind === 'LinkedField' && selection.name === EDGES; }); var pageInfo = transformed.selections.find(function (selection) { return selection.kind === 'LinkedField' && selection.name === PAGE_INFO; }); if (edges == null || pageInfo == null) { throw createUserError("Invalid connection, expected the '".concat(EDGES, "' and '").concat(PAGE_INFO, "' fields ") + 'to exist.', [transformed.loc]); } var derivedLocation = { kind: 'Derived', source: transformed.loc }; var streamLabel = transformLabel(state.documentName, 'stream', transformed.label); var deferLabel = transformLabel(state.documentName, 'defer', transformed.label); return (0, _objectSpread2["default"])({}, connection, { selections: [{ kind: 'Stream', loc: derivedLocation, metadata: null, selections: [edges], label: streamLabel, "if": stream["if"], initialCount: stream.initialCount }, { kind: 'Defer', loc: derivedLocation, metadata: null, selections: [pageInfo], label: deferLabel, "if": stream["if"] }], stream: (0, _objectSpread2["default"])({}, stream, { streamLabel: streamLabel, deferLabel: deferLabel }) }); } function visitLinkedField(field, state) { var _getLiteralStringArgu, _ref2; var context = this.getContext(); var schema = context.getSchema(); var transformedField = this.traverse(field, state); var streamDirective = transformedField.directives.find(function (directive) { return directive.name === 'stream'; }); if (streamDirective == null) { return transformedField; } var type = schema.getNullableType(field.type); if (!schema.isList(type)) { throw createUserError("Invalid use of @stream on non-plural field '".concat(field.name, "'"), [streamDirective.loc]); } transformedField = (0, _objectSpread2["default"])({}, transformedField, { directives: transformedField.directives.filter(function (directive) { return directive.name !== 'stream'; }) }); var ifArg = streamDirective.args.find(function (arg) { return arg.name === 'if'; }); if (isLiteralFalse(ifArg)) { return transformedField; } var initialCount = streamDirective.args.find(function (arg) { return arg.name === 'initial_count'; }); if (initialCount == null) { throw createUserError("Invalid use of @stream, the 'initial_count' argument is required.", [streamDirective.loc]); } var label = (_getLiteralStringArgu = getLiteralStringArgument(streamDirective, 'label')) !== null && _getLiteralStringArgu !== void 0 ? _getLiteralStringArgu : field.alias; var transformedLabel = transformLabel(state.documentName, 'stream', label); state.recordLabel(transformedLabel, streamDirective); return { "if": (_ref2 = ifArg === null || ifArg === void 0 ? void 0 : ifArg.value) !== null && _ref2 !== void 0 ? _ref2 : null, initialCount: initialCount.value, kind: 'Stream', label: transformedLabel, loc: { kind: 'Derived', source: streamDirective.loc }, metadata: null, selections: [transformedField] }; } function visitScalarField(field, state) { var streamDirective = field.directives.find(function (directive) { return directive.name === 'stream'; }); if (streamDirective != null) { throw createUserError("Invalid use of @stream on scalar field '".concat(field.name, "'"), [streamDirective.loc]); } return this.traverse(field, state); } function visitInlineFragment(fragment, state) { var deferDirective = fragment.directives.find(function (directive) { return directive.name === 'defer'; }); if (deferDirective != null) { throw createUserError('Invalid use of @defer on an inline fragment, @defer is only supported on fragment spreads.', [fragment.loc]); } return this.traverse(fragment, state); } function visitFragmentSpread(spread, state) { var _getLiteralStringArgu2, _ref3; var transformedSpread = this.traverse(spread, state); var deferDirective = transformedSpread.directives.find(function (directive) { return directive.name === 'defer'; }); if (deferDirective == null) { return transformedSpread; } transformedSpread = (0, _objectSpread2["default"])({}, transformedSpread, { directives: transformedSpread.directives.filter(function (directive) { return directive.name !== 'defer'; }) }); var ifArg = deferDirective.args.find(function (arg) { return arg.name === 'if'; }); if (isLiteralFalse(ifArg)) { return transformedSpread; } var label = (_getLiteralStringArgu2 = getLiteralStringArgument(deferDirective, 'label')) !== null && _getLiteralStringArgu2 !== void 0 ? _getLiteralStringArgu2 : getFragmentSpreadName(spread); var transformedLabel = transformLabel(state.documentName, 'defer', label); state.recordLabel(transformedLabel, deferDirective); return { "if": (_ref3 = ifArg === null || ifArg === void 0 ? void 0 : ifArg.value) !== null && _ref3 !== void 0 ? _ref3 : null, kind: 'Defer', label: transformedLabel, loc: { kind: 'Derived', source: deferDirective.loc }, metadata: null, selections: [transformedSpread] }; } function getLiteralStringArgument(directive, argName) { var arg = directive.args.find(function (_ref6) { var name = _ref6.name; return name === argName; }); if (arg == null) { return null; } var value = arg.value.kind === 'Literal' ? arg.value.value : null; if (value == null || typeof value !== 'string') { throw createUserError("Expected the '".concat(argName, "' value to @").concat(directive.name, " to be a string literal if provided."), [arg.value.loc]); } return value; } function transformLabel(parentName, directive, label) { return "".concat(parentName, "$").concat(directive, "$").concat(label); } function isLiteralFalse(arg) { return arg != null && arg.value.kind === 'Literal' && arg.value.value === false; } function getFragmentSpreadName(fragmentSpread) { if (fragmentSpread.args.length === 0) { return fragmentSpread.name; } var sortedArgs = (0, _toConsumableArray2["default"])(fragmentSpread.args).sort(function (a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }); var hash = murmurHash(JSON.stringify(sortedArgs)); return "".concat(fragmentSpread.name, "_").concat(hash); } module.exports = { transform: deferStreamTransform }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRTransformer = __webpack_require__(3); var _require = __webpack_require__(1), createUserError = _require.createUserError; function visitField(field) { if (field.alias === 'id' && field.name !== 'id') { throw createUserError('Relay does not allow aliasing fields to `id`. ' + 'This name is reserved for the globally unique `id` field on ' + '`Node`.', [field.loc]); } return field; } /** * This is not an actual transform (but more a validation) * Relay does not allow aliasing fields to `id`. */ function disallowIdAsAlias(context) { return GraphQLIRTransformer.transform(context, { ScalarField: visitField, LinkedField: visitField }); } module.exports = { transform: disallowIdAsAlias }; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var IRTransformer = __webpack_require__(3); var SchemaUtils = __webpack_require__(11); var invariant = __webpack_require__(4); var nullthrows = __webpack_require__(20); var _require = __webpack_require__(9), getRelayHandleKey = _require.getRelayHandleKey; function fieldHandleTransform(context) { return IRTransformer.transform(context, { LinkedField: visitField, ScalarField: visitField }); } /** * @internal */ function visitField(field) { var nextField = field.kind === 'LinkedField' ? this.traverse(field) : field; var handles = nextField.handles; if (!handles || !handles.length) { return nextField; } // ensure exactly one handle !(handles.length === 1) ? true ? invariant(false, 'FieldHandleTransform: Expected fields to have at most one ' + '"handle" property, got `%s`.', handles.join(', ')) : undefined : void 0; var context = this.getContext(); var schema = context.getSchema(); var alias = nextField.alias; var handle = handles[0]; var name = getRelayHandleKey(handle.name, handle.key, nextField.name); var filters = handle.filters; var args = filters ? nextField.args.filter(function (arg) { return filters.indexOf(arg.name) !== -1; }) : []; // T45504512: new connection model if (handle.dynamicKey != null) { args.push({ kind: 'Argument', loc: handle.dynamicKey.loc, name: '__dynamicKey', type: SchemaUtils.getNullableStringInput(schema), value: nullthrows(handle.dynamicKey) }); } return (0, _objectSpread2["default"])({}, nextField, { args: args, alias: alias, name: name, handles: null }); } module.exports = { transform: fieldHandleTransform }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRTransformer = __webpack_require__(3); /** * A transform that removes any directives that were not present in the * server schema. */ function filterDirectivesTransform(context) { var schemaDirectives = new Set(context.getSchema().getDirectives().filter(function (directive) { return !directive.clientOnlyDirective; }).map(function (schemaDirective) { return schemaDirective.name; })); var visitDirective = function visitDirective(directive) { if (schemaDirectives.has(directive.name)) { return directive; } return null; }; return GraphQLIRTransformer.transform(context, { Directive: visitDirective }); } module.exports = { transform: filterDirectivesTransform }; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var aStackPool = []; var bStackPool = []; /** * Checks if two values are equal. Values may be primitives, arrays, or objects. * Returns true if both arguments have the same keys and values. * * @see http://underscorejs.org * @copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. * @license MIT */ function areEqual(a, b) { var aStack = aStackPool.length ? aStackPool.pop() : []; var bStack = bStackPool.length ? bStackPool.pop() : []; var result = eq(a, b, aStack, bStack); aStack.length = 0; bStack.length = 0; aStackPool.push(aStack); bStackPool.push(bStack); return result; } function eq(a, b, aStack, bStack) { if (a === b) { // Identical objects are equal. `0 === -0`, but they aren't identical. return a !== 0 || 1 / a === 1 / b; } if (a == null || b == null) { // a or b can be `null` or `undefined` return false; } if (typeof a !== 'object' || typeof b !== 'object') { return false; } var objToStr = Object.prototype.toString; var className = objToStr.call(a); if (className !== objToStr.call(b)) { return false; } switch (className) { case '[object String]': return a === String(b); case '[object Number]': return isNaN(a) || isNaN(b) ? false : a === Number(b); case '[object Date]': case '[object Boolean]': return +a === +b; case '[object RegExp]': return a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase; } // Assume equality for cyclic structures. var length = aStack.length; while (length--) { if (aStack[length] === a) { return bStack[length] === b; } } aStack.push(a); bStack.push(b); var size = 0; // Recursively compare objects and arrays. if (className === '[object Array]') { size = a.length; if (size !== b.length) { return false; } // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!eq(a[size], b[size], aStack, bStack)) { return false; } } } else { if (a.constructor !== b.constructor) { return false; } if (a.hasOwnProperty('valueOf') && b.hasOwnProperty('valueOf')) { return a.valueOf() === b.valueOf(); } var keys = Object.keys(a); if (keys.length !== Object.keys(b).length) { return false; } for (var i = 0; i < keys.length; i++) { if (keys[i] === '_owner') { // HACK: Comparing deeply nested React trees is slow since you end up // comparing the entire tree (all ancestors and all children) and // likely not what you want if you're comparing two elements with // areEqual. We bail out here for now. continue; } if (!b.hasOwnProperty(keys[i]) || !eq(a[keys[i]], b[keys[i]], aStack, bStack)) { return false; } } } aStack.pop(); bStack.pop(); return true; } module.exports = areEqual; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var SchemaUtils = __webpack_require__(11); var _require = __webpack_require__(38), hasUnaliasedSelection = _require.hasUnaliasedSelection; var generateIDField = SchemaUtils.generateIDField; var ID = 'id'; var NODE_TYPE = 'Node'; /** * A transform that adds an `id` field on any type that has an id field but * where there is no unaliased `id` selection. */ function generateIDFieldTransform(context) { var schema = context.getSchema(); var idType = schema.expectIdType(); var idField = generateIDField(idType); var state = { idField: idField }; return IRTransformer.transform(context, { LinkedField: visitLinkedField }, function () { return state; }); } function visitLinkedField(field, state) { var transformedNode = this.traverse(field, state); // If the field already has an unaliased `id` field, do nothing if (hasUnaliasedSelection(field, ID)) { return transformedNode; } var context = this.getContext(); var schema = context.getSchema(); var unmodifiedType = schema.assertCompositeType(schema.getRawType(field.type)); // If the field type has an `id` subfield add an `id` selection if (schema.canHaveSelections(unmodifiedType) && schema.hasId(unmodifiedType)) { return (0, _objectSpread2["default"])({}, transformedNode, { selections: [].concat((0, _toConsumableArray2["default"])(transformedNode.selections), [state.idField]) }); } // If the field type is abstract, then generate a `... on Node { id }` // fragment if *any* concrete type implements Node. Then generate a // `... on PossibleType { id }` for every concrete type that does *not* // implement `Node` var nodeType = schema.getTypeFromString(NODE_TYPE); if (!nodeType) { return transformedNode; } var nodeInterface = schema.assertInterfaceType(nodeType); if (schema.isAbstractType(unmodifiedType)) { var selections = (0, _toConsumableArray2["default"])(transformedNode.selections); if (schema.mayImplement(unmodifiedType, nodeInterface)) { selections.push(buildIDFragment(nodeInterface, state.idField)); } schema.getPossibleTypes(schema.assertAbstractType(unmodifiedType)).forEach(function (possibleType) { if (!schema.implementsInterface(schema.assertCompositeType(possibleType), nodeInterface) && schema.hasId(possibleType)) { selections.push(buildIDFragment(possibleType, state.idField)); } }); return (0, _objectSpread2["default"])({}, transformedNode, { selections: selections }); } return transformedNode; } /** * @internal * * Returns IR for `... on FRAGMENT_TYPE { id }` */ function buildIDFragment(fragmentType, idField) { return { kind: 'InlineFragment', directives: [], loc: { kind: 'Generated' }, metadata: null, selections: [idField], typeCondition: fragmentType }; } module.exports = { transform: generateIDFieldTransform }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var IRTransformer = __webpack_require__(3); var _require = __webpack_require__(38), hasUnaliasedSelection = _require.hasUnaliasedSelection; var TYPENAME_KEY = '__typename'; var cache = new Map(); /** * A transform that adds `__typename` field on any `LinkedField` of a union or * interface type where there is no unaliased `__typename` selection. */ function generateTypeNameTransform(context) { cache = new Map(); var schema = context.getSchema(); var typenameField = { kind: 'ScalarField', alias: TYPENAME_KEY, args: [], directives: [], handles: null, loc: { kind: 'Generated' }, metadata: null, name: TYPENAME_KEY, type: schema.expectStringType() }; var state = { typenameField: typenameField }; return IRTransformer.transform(context, { LinkedField: visitLinkedField }, function () { return state; }); } function visitLinkedField(field, state) { var schema = this.getContext().getSchema(); var transformedNode = cache.get(field); if (transformedNode != null) { return transformedNode; } transformedNode = this.traverse(field, state); if (schema.isAbstractType(schema.getRawType(transformedNode.type)) && !hasUnaliasedSelection(transformedNode, TYPENAME_KEY)) { transformedNode = (0, _objectSpread2["default"])({}, transformedNode, { selections: [state.typenameField].concat((0, _toConsumableArray2["default"])(transformedNode.selections)) }); } cache.set(field, transformedNode); return transformedNode; } module.exports = { transform: generateTypeNameTransform }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var GraphQLIRTransformer = __webpack_require__(3); var _require = __webpack_require__(1), createUserError = _require.createUserError; var SCHEMA_EXTENSION = "\ndirective @inline on FRAGMENT_DEFINITION\n"; /** * A transform that converts fragment spreads where the referenced fragment * is annotated with @inline to a InlineDataFragmentSpread. * InlineDataFragmentSpreads have the selections of the referenced fragment inlined. */ function inlineDataFragmentTransform(context) { return GraphQLIRTransformer.transform(context, { // $FlowFixMe - this visitor intentionally changes node types FragmentSpread: visitFragmentSpread, Fragment: visitFragment }); } function visitFragment(fragment) { var transformedFragment = this.traverse(fragment); var inlineDirective = transformedFragment.directives.find(function (directive) { return directive.name === 'inline'; }); if (inlineDirective == null) { return transformedFragment; } return (0, _objectSpread2["default"])({}, transformedFragment, { directives: transformedFragment.directives.filter(function (directive) { return directive !== inlineDirective; }), metadata: (0, _objectSpread2["default"])({}, transformedFragment.metadata || {}, { inlineData: true }) }); } function visitFragmentSpread(fragmentSpread) { var transformedFragmentSpread = this.traverse(fragmentSpread); var context = this.getContext(); var fragment = context.get(transformedFragmentSpread.name); if (!fragment || fragment.kind !== 'Fragment' || !fragment.directives.some(function (directive) { return directive.name === 'inline'; })) { return transformedFragmentSpread; } if (fragment.argumentDefinitions.length > 0 || transformedFragmentSpread.args.length > 0) { throw createUserError('Variables are not yet supported inside @inline fragments.', [fragment.argumentDefinitions[0].loc]); } if (transformedFragmentSpread.directives.length > 0) { throw createUserError('Directives on fragment spreads for @inline fragments are not yet ' + 'supported', [transformedFragmentSpread.loc]); } var transformedFragment = this.visit(fragment); return { kind: 'InlineDataFragmentSpread', loc: transformedFragmentSpread.loc, metadata: transformedFragmentSpread.metadata, name: transformedFragmentSpread.name, selections: [{ directives: [], kind: 'InlineFragment', loc: { kind: 'Derived', source: transformedFragmentSpread.loc }, metadata: null, selections: transformedFragment.selections, typeCondition: transformedFragment.type }] }; } module.exports = { SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: inlineDataFragmentTransform }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRTransformer = __webpack_require__(3); var invariant = __webpack_require__(4); /** * A transform that inlines all fragments and removes them. */ function inlineFragmentsTransform(context) { var visitFragmentSpread = fragmentSpreadVisitor(new Map()); return GraphQLIRTransformer.transform(context, { Fragment: visitFragment, FragmentSpread: visitFragmentSpread }); } function visitFragment(fragment) { return null; } function fragmentSpreadVisitor(cache) { return function visitFragmentSpread(fragmentSpread) { var traverseResult = cache.get(fragmentSpread); if (traverseResult != null) { return traverseResult; } !(fragmentSpread.args.length === 0) ? true ? invariant(false, 'InlineFragmentsTransform: Cannot flatten fragment spread `%s` with ' + 'arguments. Use the `ApplyFragmentArgumentTransform` before flattening', fragmentSpread.name) : undefined : void 0; var fragment = this.getContext().getFragment(fragmentSpread.name, fragmentSpread.loc); var result = { kind: 'InlineFragment', directives: fragmentSpread.directives, loc: { kind: 'Derived', source: fragmentSpread.loc }, metadata: fragmentSpread.metadata, selections: fragment.selections, typeCondition: fragment.type }; traverseResult = this.traverse(result); cache.set(fragmentSpread, traverseResult); return traverseResult; }; } module.exports = { transform: inlineFragmentsTransform }; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(1), createUserError = _require.createUserError; /** * Attempts to join the argument definitions for a root fragment * and any unmasked fragment spreads reachable from that root fragment, * returning a combined list of arguments or throwing if the same * variable(s) are used in incompatible ways in different fragments. */ function joinArgumentDefinitions(schema, fragment, reachableArguments, directiveName) { var joinedArgumentDefinitions = new Map(); fragment.argumentDefinitions.forEach(function (prevArgDef) { joinedArgumentDefinitions.set(prevArgDef.name, prevArgDef); }); reachableArguments.forEach(function (nextArgDef) { var prevArgDef = joinedArgumentDefinitions.get(nextArgDef.name); var joinedArgDef = prevArgDef == null ? nextArgDef : joinArgumentDefinition(schema, prevArgDef, nextArgDef, directiveName); joinedArgumentDefinitions.set(joinedArgDef.name, joinedArgDef); }); return Array.from(joinedArgumentDefinitions.values()); } /** * @private * * Attempts to join two argument definitions, returning a single argument * definition that is compatible with both of the inputs: * - If the kind, name, or defaultValue is different then the arguments * cannot be joined, indicated by returning null. * - If either of next/prev is a subtype of the other, return the one * that is the subtype: a more narrow type can flow into a more general * type but not the inverse. * - Otherwise there is no subtyping relation between prev/next, so return * null to indicate they cannot be joined. */ function joinArgumentDefinition(schema, prevArgDef, nextArgDef, directiveName) { if (prevArgDef.kind !== nextArgDef.kind) { throw createUserError('Cannot combine global and local variables when applying ' + "".concat(directiveName, "."), [prevArgDef.loc, nextArgDef.loc]); } else if (prevArgDef.kind === 'LocalArgumentDefinition' && nextArgDef.kind === 'LocalArgumentDefinition' && prevArgDef.defaultValue !== nextArgDef.defaultValue) { throw createUserError('Cannot combine local variables with different defaultValues when ' + "applying ".concat(directiveName, "."), [prevArgDef.loc, nextArgDef.loc]); } else if (schema.isTypeSubTypeOf(nextArgDef.type, prevArgDef.type)) { // prevArgDef is less strict than nextArgDef return nextArgDef; } else if (schema.isTypeSubTypeOf(prevArgDef.type, nextArgDef.type)) { return prevArgDef; } else { throw createUserError('Cannot combine variables with incompatible types ' + "".concat(schema.getTypeString(prevArgDef.type), " and ").concat(schema.getTypeString(nextArgDef.type), " ") + "when applying ".concat(directiveName, "."), [prevArgDef.loc, nextArgDef.loc]); } } module.exports = joinArgumentDefinitions; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var NodeQueryGenerator = __webpack_require__(88); var QueryQueryGenerator = __webpack_require__(89); var ViewerQueryGenerator = __webpack_require__(90); var _require = __webpack_require__(1), createUserError = _require.createUserError; var GENERATORS = [ViewerQueryGenerator, QueryQueryGenerator, NodeQueryGenerator]; /** * Builds a query to refetch the given fragment or throws if we have not way to * generate one. */ function buildRefetchOperation(schema, fragment, queryName) { for (var _i = 0, _GENERATORS = GENERATORS; _i < _GENERATORS.length; _i++) { var generator = _GENERATORS[_i]; var refetchRoot = generator.buildRefetchOperation(schema, fragment, queryName); if (refetchRoot != null) { return refetchRoot; } } throw createUserError("Invalid use of @refetchable on fragment '".concat(fragment.name, "', only ") + 'supported are fragments on:\n' + GENERATORS.map(function (generator) { return " - ".concat(generator.description); }).join('\n'), [fragment.loc]); } module.exports = { buildRefetchOperation: buildRefetchOperation }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var SchemaUtils = __webpack_require__(11); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(21), buildFragmentSpread = _require2.buildFragmentSpread, buildOperationArgumentDefinitions = _require2.buildOperationArgumentDefinitions; var NODE_TYPE_NAME = 'Node'; var NODE_FIELD_NAME = 'node'; function buildRefetchOperation(schema, fragment, queryName) { var eligible = schema.getTypeString(fragment.type) === NODE_TYPE_NAME || schema.isObject(fragment.type) && schema.getInterfaces(schema.assertCompositeType(fragment.type)).some(function (interfaceType) { return schema.areEqualTypes(interfaceType, schema.expectTypeFromString(NODE_TYPE_NAME)); }) || schema.isAbstractType(fragment.type) && Array.from(schema.getPossibleTypes(schema.assertAbstractType(fragment.type))).every(function (possibleType) { return schema.implementsInterface(schema.assertCompositeType(possibleType), schema.assertInterfaceType(schema.expectTypeFromString(NODE_TYPE_NAME))); }); if (!eligible) { return null; } var queryType = schema.expectQueryType(); var nodeType = schema.getTypeFromString(NODE_TYPE_NAME); var nodeField = schema.getFieldConfig(schema.expectField(queryType, NODE_FIELD_NAME)); if (!(nodeType && schema.isInterface(nodeType) && schema.isInterface(nodeField.type) && schema.areEqualTypes(nodeField.type, nodeType) && nodeField.args.length === 1 && schema.areEqualTypes(schema.getNullableType(nodeField.args[0].type), schema.expectIdType()) && ( // the fragment must be on Node or on a type that implements Node schema.isObject(fragment.type) && schema.getInterfaces(schema.assertCompositeType(fragment.type)).some(function (interfaceType) { return schema.areEqualTypes(interfaceType, nodeType); }) || schema.isAbstractType(fragment.type) && Array.from(schema.getPossibleTypes(schema.assertAbstractType(fragment.type))).every(function (possibleType) { return schema.getInterfaces(schema.assertCompositeType(possibleType)).some(function (interfaceType) { return schema.areEqualTypes(interfaceType, nodeType); }); })))) { throw createUserError("Invalid use of @refetchable on fragment '".concat(fragment.name, "', check ") + 'that your schema defines a `Node { id: ID }` interface and has a ' + '`node(id: ID): Node` field on the query type (the id argument may ' + 'also be non-null).', [fragment.loc]); } // name and type of the node(_: ID) field parameter var idArgName = nodeField.args[0].name; var idArgType = nodeField.args[0].type; // name and type of the query variable var idVariableType = SchemaUtils.getNonNullIdInput(schema); var idVariableName = 'id'; var argumentDefinitions = buildOperationArgumentDefinitions(fragment.argumentDefinitions); var idArgument = argumentDefinitions.find(function (argDef) { return argDef.name === idVariableName; }); if (idArgument != null) { throw createUserError("Invalid use of @refetchable on fragment `".concat(fragment.name, "`, this ") + 'fragment already has an `$id` variable in scope.', [idArgument.loc]); } var argumentDefinitionsWithId = [].concat((0, _toConsumableArray2["default"])(argumentDefinitions), [{ defaultValue: null, kind: 'LocalArgumentDefinition', loc: { kind: 'Derived', source: fragment.loc }, name: idVariableName, type: idVariableType }]); return { path: [NODE_FIELD_NAME], node: { argumentDefinitions: argumentDefinitionsWithId, directives: [], kind: 'Root', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: queryName, operation: 'query', selections: [{ alias: NODE_FIELD_NAME, args: [{ kind: 'Argument', loc: { kind: 'Derived', source: fragment.loc }, name: idArgName, type: schema.assertInputType(idArgType), value: { kind: 'Variable', loc: { kind: 'Derived', source: fragment.loc }, variableName: idVariableName, type: idVariableType } }], connection: false, directives: [], handles: null, kind: 'LinkedField', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: NODE_FIELD_NAME, selections: [buildFragmentSpread(fragment)], type: schema.assertLinkedFieldType(nodeType) }], type: queryType }, transformedFragment: enforceIDField(schema, fragment) }; } function enforceIDField(schema, fragment) { var idSelection = fragment.selections.find(function (selection) { return selection.kind === 'ScalarField' && selection.name === 'id' && selection.alias === 'id' && schema.areEqualTypes(schema.getNullableType(selection.type), schema.expectIdType()); }); if (idSelection) { return fragment; } return (0, _objectSpread2["default"])({}, fragment, { selections: [].concat((0, _toConsumableArray2["default"])(fragment.selections), [SchemaUtils.generateIDField(schema.expectIdType())]) }); } module.exports = { description: 'the Node interface or types implementing the Node interface', buildRefetchOperation: buildRefetchOperation }; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(21), buildFragmentSpread = _require.buildFragmentSpread, buildOperationArgumentDefinitions = _require.buildOperationArgumentDefinitions; function buildRefetchOperation(schema, fragment, queryName) { var queryType = schema.expectQueryType(); if (!schema.areEqualTypes(fragment.type, queryType)) { return null; } return { path: [], node: { argumentDefinitions: buildOperationArgumentDefinitions(fragment.argumentDefinitions), directives: [], kind: 'Root', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: queryName, operation: 'query', selections: [buildFragmentSpread(fragment)], type: queryType }, transformedFragment: fragment }; } module.exports = { description: 'the query type', buildRefetchOperation: buildRefetchOperation }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(21), buildFragmentSpread = _require2.buildFragmentSpread, buildOperationArgumentDefinitions = _require2.buildOperationArgumentDefinitions; var VIEWER_TYPE_NAME = 'Viewer'; var VIEWER_FIELD_NAME = 'viewer'; function buildRefetchOperation(schema, fragment, queryName) { if (schema.getTypeString(fragment.type) !== VIEWER_TYPE_NAME) { return null; } // Handle fragments on viewer var queryType = schema.expectQueryType(); var viewerType = schema.getTypeFromString(VIEWER_TYPE_NAME); var viewerField = schema.getFieldConfig(schema.expectField(queryType, VIEWER_FIELD_NAME)); if (!(viewerType && schema.isObject(viewerType) && schema.isObject(viewerField.type) && schema.areEqualTypes(viewerField.type, viewerType) && viewerField.args.length === 0 && schema.areEqualTypes(fragment.type, viewerType))) { throw createUserError("Invalid use of @refetchable on fragment '".concat(fragment.name, "', check ") + "that your schema defines a 'Viewer' object type and has a " + "'viewer: Viewer' field on the query type.", [fragment.loc]); } return { path: [VIEWER_FIELD_NAME], node: { argumentDefinitions: buildOperationArgumentDefinitions(fragment.argumentDefinitions), directives: [], kind: 'Root', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: queryName, operation: 'query', selections: [{ alias: VIEWER_FIELD_NAME, args: [], connection: false, directives: [], handles: null, kind: 'LinkedField', loc: { kind: 'Derived', source: fragment.loc }, metadata: null, name: VIEWER_FIELD_NAME, selections: [buildFragmentSpread(fragment)], type: schema.assertLinkedFieldType(viewerType) }], type: queryType }, transformedFragment: fragment }; } module.exports = { description: 'the Viewer type', buildRefetchOperation: buildRefetchOperation }; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var t = __webpack_require__(22); var _require = __webpack_require__(45), exactObjectTypeAnnotation = _require.exactObjectTypeAnnotation, readOnlyArrayOfType = _require.readOnlyArrayOfType; function getInputObjectTypeIdentifier(schema, typeID) { return schema.getTypeString(typeID); } function transformScalarType(schema, type, state, objectProps) { if (schema.isNonNull(type)) { return transformNonNullableScalarType(schema, schema.getNullableType(type), state, objectProps); } else { return t.nullableTypeAnnotation(transformNonNullableScalarType(schema, type, state, objectProps)); } } function transformNonNullableScalarType(schema, type, state, objectProps) { if (schema.isList(type)) { return readOnlyArrayOfType(transformScalarType(schema, schema.getListItemType(type), state, objectProps)); } else if (schema.isObject(type) || schema.isUnion(type) || schema.isInterface(type)) { return objectProps; } else if (schema.isScalar(type)) { return transformGraphQLScalarType(schema.getTypeString(type), state); } else if (schema.isEnum(type)) { return transformGraphQLEnumType(schema, schema.assertEnumType(type), state); } else { throw new Error("Could not convert from GraphQL type ".concat(String(type))); } } function transformGraphQLScalarType(typeName, state) { var _customType; var customType = state.customScalars[typeName]; if (typeof customType === 'function') { return customType(t); } switch ((_customType = customType) !== null && _customType !== void 0 ? _customType : typeName) { case 'ID': case 'String': return t.stringTypeAnnotation(); case 'Float': case 'Int': return t.numberTypeAnnotation(); case 'Boolean': return t.booleanTypeAnnotation(); default: return customType == null ? t.anyTypeAnnotation() : t.genericTypeAnnotation(t.identifier(customType)); } } function transformGraphQLEnumType(schema, type, state) { state.usedEnums[schema.getTypeString(type)] = type; return t.genericTypeAnnotation(t.identifier(schema.getTypeString(type))); } function transformInputType(schema, type, state) { if (schema.isNonNull(type)) { return transformNonNullableInputType(schema, schema.getNullableType(type), state); } else { return t.nullableTypeAnnotation(transformNonNullableInputType(schema, type, state)); } } function transformNonNullableInputType(schema, type, state) { if (schema.isList(type)) { return readOnlyArrayOfType(transformInputType(schema, schema.getListItemType(type), state)); } else if (schema.isScalar(type)) { return transformGraphQLScalarType(schema.getTypeString(type), state); } else if (schema.isEnum(type)) { return transformGraphQLEnumType(schema, schema.assertEnumType(type), state); } else if (schema.isInputObject(type)) { var typeIdentifier = getInputObjectTypeIdentifier(schema, type); if (state.generatedInputObjectTypes[typeIdentifier]) { return t.genericTypeAnnotation(t.identifier(typeIdentifier)); } state.generatedInputObjectTypes[typeIdentifier] = 'pending'; var fields = schema.getFields(schema.assertInputObjectType(type)); var props = fields.map(function (fieldID) { var fieldType = schema.getFieldType(fieldID); var fieldName = schema.getFieldName(fieldID); var property = t.objectTypeProperty(t.identifier(fieldName), transformInputType(schema, fieldType, state)); if (state.optionalInputFields.indexOf(fieldName) >= 0 || !schema.isNonNull(fieldType)) { property.optional = true; } return property; }); state.generatedInputObjectTypes[typeIdentifier] = exactObjectTypeAnnotation(props); return t.genericTypeAnnotation(t.identifier(typeIdentifier)); } else { throw new Error("Could not convert from GraphQL type ".concat(schema.getTypeString(type))); } } module.exports = { transformInputType: transformInputType, transformScalarType: transformScalarType }; /***/ }), /* 92 */ /***/ (function(module, exports) { module.exports = require("@babel/generator"); /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRTransformer = __webpack_require__(3); function skipClientExtensionTransform(context) { return GraphQLIRTransformer.transform(context, { Fragment: visitFragment, ClientExtension: visitClientExtension }); } function visitFragment(node) { var context = this.getContext(); if (context.getSchema().isServerType(node.type)) { return this.traverse(node); } return null; } function visitClientExtension(node, state) { return null; } module.exports = { transform: skipClientExtensionTransform }; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var IRTransformer = __webpack_require__(3); /** * A transform that removes field `handles`. Intended for use when e.g. * printing queries to send to a GraphQL server. */ function skipHandleFieldTransform(context) { return IRTransformer.transform(context, { LinkedField: visitField, ScalarField: visitField }); } function visitField(field) { var transformedNode = this.traverse(field); if (transformedNode.handles) { return (0, _objectSpread2["default"])({}, transformedNode, { handles: null }); } return transformedNode; } module.exports = { transform: skipHandleFieldTransform }; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var GraphQLIRTransformer = __webpack_require__(3); var IMap = __webpack_require__(14).Map; var partitionArray = __webpack_require__(28); var getIdentifierForSelection = __webpack_require__(37); var invariant = __webpack_require__(4); /** * A transform that removes redundant fields and fragment spreads. Redundancy is * defined in this context as any selection that is guaranteed to already be * fetched by an ancestor selection. This can occur in two cases: * * 1. Simple duplicates at the same level of the document can always be skipped: * * ``` * fragment Foo on FooType { * id * id * ...Bar * ...Bar * } * ``` * * Becomes * * ``` * fragment Foo on FooType { * id * ...Bar * } * ``` * * 2. Inline fragments and conditions introduce the possibility for duplication * at different levels of the tree. Whenever a selection is fetched in a parent, * it is redundant to also fetch it in a child: * * ``` * fragment Foo on FooType { * id * ... on OtherType { * id # 1 * } * ... on FooType @include(if: $cond) { * id # 2 * } * } * ``` * * Becomes: * * ``` * fragment Foo on FooType { * id * } * ``` * * In this example: * - 1 can be skipped because `id` is already fetched by the parent. Even * though the type is different (FooType/OtherType), the inline fragment * cannot match without the outer fragment matching so the outer `id` is * guaranteed to already be fetched. * - 2 can be skipped for similar reasons: it doesn't matter if the condition * holds, `id` is already fetched by the parent regardless. * * This transform also handles more complicated cases in which selections are * nested: * * ``` * fragment Foo on FooType { * a { * bb * } * ... on OtherType { * a { * bb # 1 * cc * } * } * } * ``` * * Becomes * * ``` * fragment Foo on FooType { * a { * bb * } * ... on OtherType { * a { * cc * } * } * } * ``` * * 1 can be skipped because it is already fetched at the outer level. */ function skipRedundantNodesTransform(context) { return GraphQLIRTransformer.transform(context, { Root: visitNode, Fragment: visitNode }); } var cache = new Map(); function visitNode(node) { cache = new Map(); var context = this.getContext(); return transformNode(context.getSchema(), node, new IMap()).node; } /** * The most straightforward approach would be two passes: one to record the * structure of the document, one to prune duplicates. This implementation uses * a single pass. Selections are sorted with fields first, "conditionals" * (inline fragments & conditions) last. This means that all fields that are * guaranteed to be fetched are encountered prior to any duplicates that may be * fetched within a conditional. * * Because selections fetched within a conditional are not guaranteed to be * fetched in the parent, a fork of the selection map is created when entering a * conditional. The sort ensures that guaranteed fields have already been seen * prior to the clone. */ function transformNode(schema, node, selectionMap) { // This will optimize a traversal of the same subselections. // If it's the same node, and selectionMap is empty // result of transformNode has to be the same. var isEmptySelectionMap = selectionMap.size === 0; var result; if (isEmptySelectionMap) { result = cache.get(node); if (result != null) { return result; } } var selections = []; sortSelections(node.selections).forEach(function (selection) { var identifier = getIdentifierForSelection(schema, selection); switch (selection.kind) { case 'ScalarField': case 'FragmentSpread': { if (!selectionMap.has(identifier)) { selections.push(selection); selectionMap = selectionMap.set(identifier, null); } break; } case 'Defer': case 'Stream': case 'ModuleImport': case 'ClientExtension': case 'InlineDataFragmentSpread': case 'Connection': case 'ConnectionField': case 'LinkedField': { var transformed = transformNode(schema, selection, selectionMap.get(identifier) || new IMap()); if (transformed.node) { selections.push(transformed.node); selectionMap = selectionMap.set(identifier, transformed.selectionMap); } break; } case 'InlineFragment': case 'Condition': { // Fork the selection map to prevent conditional selections from // affecting the outer "guaranteed" selections. var _transformed = transformNode(schema, selection, selectionMap.get(identifier) || selectionMap); if (_transformed.node) { selections.push(_transformed.node); selectionMap = selectionMap.set(identifier, _transformed.selectionMap); } break; } default: selection; true ? true ? invariant(false, 'SkipRedundantNodesTransform: Unexpected node kind `%s`.', selection.kind) : undefined : undefined; } }); var nextNode = selections.length ? (0, _objectSpread2["default"])({}, node, { selections: selections }) : null; result = { selectionMap: selectionMap, node: nextNode }; if (isEmptySelectionMap) { cache.set(node, result); } return result; } /** * Sort inline fragments and conditions after other selections. */ function sortSelections(selections) { var isScalarOrLinkedField = function isScalarOrLinkedField(selection) { return selection.kind === 'ScalarField' || selection.kind === 'LinkedField'; }; var _partitionArray = partitionArray(selections, isScalarOrLinkedField), scalarsAndLinkedFields = _partitionArray[0], rest = _partitionArray[1]; return [].concat((0, _toConsumableArray2["default"])(scalarsAndLinkedFields), (0, _toConsumableArray2["default"])(rest)); } module.exports = { transform: skipRedundantNodesTransform }; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var GraphQLIRTransformer = __webpack_require__(3); var invariant = __webpack_require__(4); var FAIL = 'fail'; var PASS = 'pass'; var VARIABLE = 'variable'; /** * A tranform that removes unreachable IR nodes from all documents in a corpus. * The following nodes are removed: * - Any node with `@include(if: false)` * - Any node with `@skip(if: true)` * - Any node with empty `selections` */ function skipUnreachableNodeTransform(context) { var fragments = new Map(); var nextContext = GraphQLIRTransformer.transform(context, { Root: function Root(node) { return transformNode(context, fragments, node); }, // Fragments are included below where referenced. // Unreferenced fragments are not included. Fragment: function Fragment(id) { return null; } }); return Array.from(fragments.values()).reduce(function (ctx, fragment) { return fragment ? ctx.add(fragment) : ctx; }, nextContext); } function transformNode(context, fragments, node) { var queue = (0, _toConsumableArray2["default"])(node.selections); var selections; while (queue.length) { var selection = queue.shift(); var nextSelection = void 0; switch (selection.kind) { case 'Condition': var match = testCondition(selection); if (match === PASS) { queue.unshift.apply(queue, (0, _toConsumableArray2["default"])(selection.selections)); } else if (match === VARIABLE) { nextSelection = transformNode(context, fragments, selection); } break; case 'FragmentSpread': { // Skip fragment spreads if the referenced fragment is empty if (!fragments.has(selection.name)) { var fragment = context.getFragment(selection.name); var nextFragment = transformNode(context, fragments, fragment); fragments.set(selection.name, nextFragment); } if (fragments.get(selection.name)) { nextSelection = selection; } break; } case 'ClientExtension': nextSelection = transformNode(context, fragments, selection); break; case 'ModuleImport': nextSelection = transformNode(context, fragments, selection); break; case 'LinkedField': nextSelection = transformNode(context, fragments, selection); break; case 'ConnectionField': nextSelection = transformNode(context, fragments, selection); break; case 'Connection': nextSelection = transformNode(context, fragments, selection); break; case 'InlineFragment': // TODO combine with the LinkedField case when flow supports this nextSelection = transformNode(context, fragments, selection); break; case 'Defer': nextSelection = transformNode(context, fragments, selection); break; case 'Stream': nextSelection = transformNode(context, fragments, selection); break; case 'ScalarField': nextSelection = selection; break; case 'InlineDataFragmentSpread': true ? true ? invariant(false, 'SkipUnreachableNodeTransform: Did not expect an ' + 'InlineDataFragmentSpread here. Only expecting ' + 'InlineDataFragmentSpread in reader ASTs and this transform to ' + 'run only on normalization ASTs.') : undefined : undefined; // fallthrough default: selection.kind; true ? true ? invariant(false, 'SkipUnreachableNodeTransform: Unexpected selection kind `%s`.', selection.kind) : undefined : undefined; } if (nextSelection) { selections = selections || []; selections.push(nextSelection); } } if (selections) { return (0, _objectSpread2["default"])({}, node, { selections: selections }); } return null; } /** * Determines whether a condition statically passes/fails or is unknown * (variable). */ function testCondition(condition) { if (condition.condition.kind === 'Variable') { return VARIABLE; } return condition.condition.value === condition.passingValue ? PASS : FAIL; } module.exports = { transform: skipUnreachableNodeTransform }; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var inferRootArgumentDefinitions = __webpack_require__(17); /** * Refines the argument definitions for operations to remove unused arguments * due to statically pruned conditional branches (e.g. because of overriding * a variable used in `@include()` to be false). */ function skipUnusedVariablesTransform(context) { var contextWithUsedArguments = inferRootArgumentDefinitions(context); return context.withMutations(function (ctx) { var nextContext = ctx; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { var _loop = function _loop() { var node = _step.value; if (node.kind !== 'Root') { return "continue"; } var usedArguments = new Set(contextWithUsedArguments.getRoot(node.name).argumentDefinitions.map(function (argDef) { return argDef.name; })); // Remove unused argument definitions var usedArgumentDefinitions = node.argumentDefinitions.filter(function (argDef) { return usedArguments.has(argDef.name); }); if (usedArgumentDefinitions.length !== node.argumentDefinitions.length) { nextContext = nextContext.replace((0, _objectSpread2["default"])({}, node, { argumentDefinitions: usedArgumentDefinitions })); } }; for (var _iterator = nextContext.documents()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _ret = _loop(); if (_ret === "continue") continue; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return nextContext; }); } module.exports = { transform: skipUnusedVariablesTransform }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var IRTransformer = __webpack_require__(3); var getNormalizationOperationName = __webpack_require__(41); /** * This transform creates a SplitOperation root for every ModuleImport. */ function splitMatchTransform(context) { var splitOperations = new Map(); var transformedContext = IRTransformer.transform(context, { LinkedField: visitLinkedField, InlineFragment: visitInlineFragment, ModuleImport: visitModuleImport }, function (node) { return { parentType: node.type, splitOperations: splitOperations }; }); return transformedContext.addAll(Array.from(splitOperations.values())); } function visitLinkedField(field, state) { return this.traverse(field, { parentType: field.type, splitOperations: state.splitOperations }); } function visitInlineFragment(fragment, state) { return this.traverse(fragment, { parentType: fragment.typeCondition, splitOperations: state.splitOperations }); } function visitModuleImport(node, state) { // It's possible for the same fragment to be selected in multiple usages // of @module: skip processing a node if its SplitOperation has already // been generated var normalizationName = getNormalizationOperationName(node.name); var createdSplitOperation = state.splitOperations.get(normalizationName); if (createdSplitOperation) { createdSplitOperation.parentSources.add(node.documentName); return node; } var transformedNode = this.traverse(node, state); var splitOperation = { kind: 'SplitOperation', name: normalizationName, selections: transformedNode.selections, loc: { kind: 'Derived', source: node.loc }, parentSources: new Set([node.documentName]), metadata: { derivedFrom: transformedNode.name }, type: state.parentType }; state.splitOperations.set(normalizationName, splitOperation); return transformedNode; } module.exports = { transform: splitMatchTransform }; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @emails oncall+relay */ var _interopRequireDefault = __webpack_require__(0); var _objectSpread2 = _interopRequireDefault(__webpack_require__(2)); var IRTransformer = __webpack_require__(3); // The purpose of this directive is to add GraphQL type inform for fields in // the operation selection in order to use in in RelayMockPayloadGenerator // to generate better mock values, and expand the API of MockResolvers var SCHEMA_EXTENSION = 'directive @relay_test_operation on QUERY | MUTATION | SUBSCRIPTION'; function testOperationDirective(context) { return IRTransformer.transform(context, { Fragment: function Fragment(node) { return node; }, Root: visitRoot, SplitOperation: function SplitOperation(node) { return node; } }); } function getTypeDetails(schema, fieldType) { var nullableType = schema.getNullableType(fieldType); var isNullable = !schema.isNonNull(fieldType); var isPlural = schema.isList(nullableType); var type = schema.getRawType(nullableType); return { type: schema.getTypeString(type), enumValues: schema.isEnum(type) ? schema.getEnumValues(schema.assertEnumType(type)) : null, plural: isPlural, nullable: isNullable }; } function visitRoot(node) { var schema = this.getContext().getSchema(); var testDirective = node.directives.find(function (directive) { return directive.name === 'relay_test_operation'; }); if (testDirective == null) { return node; } var context = this.getContext(); var queue = [{ selections: node.selections, path: null }]; var selectionsTypeInfo = {}; var _loop = function _loop() { var _queue$pop = queue.pop(), currentSelections = _queue$pop.selections, path = _queue$pop.path; currentSelections.forEach(function (selection) { switch (selection.kind) { case 'FragmentSpread': var fragment = context.get(selection.name); if (fragment != null) { queue.unshift({ selections: fragment.selections, path: path }); } break; case 'ScalarField': { var nextPath = path === null ? selection.alias : "".concat(path, ".").concat(selection.alias); selectionsTypeInfo[nextPath] = getTypeDetails(schema, selection.type); break; } case 'ConnectionField': case 'LinkedField': { var _nextPath = path === null ? selection.alias : "".concat(path, ".").concat(selection.alias); selectionsTypeInfo[_nextPath] = getTypeDetails(schema, selection.type); queue.unshift({ selections: selection.selections, path: _nextPath }); break; } case 'Condition': case 'Connection': case 'ClientExtension': case 'Defer': case 'InlineDataFragmentSpread': case 'InlineFragment': case 'ModuleImport': case 'Stream': queue.unshift({ selections: selection.selections, path: path }); break; default: selection; break; } }); }; while (queue.length > 0) { _loop(); } return (0, _objectSpread2["default"])({}, node, { directives: node.directives.filter(function (directive) { return directive !== testDirective; }), metadata: (0, _objectSpread2["default"])({}, node.metadata || {}, { relayTestingSelectionTypeInfo: selectionsTypeInfo }) }); } module.exports = { SCHEMA_EXTENSION: SCHEMA_EXTENSION, transform: testOperationDirective }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var inferRootArgumentDefinitions = __webpack_require__(17); var _require = __webpack_require__(1), createUserError = _require.createUserError, eachWithCombinedError = _require.eachWithCombinedError; /** * Validates that all global variables used in operations are defined at the * root. This isn't a real transform as it returns the original context, but * has to happen before other transforms strip certain variable usages. */ function validateGlobalVariablesTransform(context) { var contextWithUsedArguments = inferRootArgumentDefinitions(context); eachWithCombinedError(context.documents(), function (node) { if (node.kind !== 'Root') { return; } var nodeWithUsedArguments = contextWithUsedArguments.getRoot(node.name); var definedArguments = argumentDefinitionsToMap(node.argumentDefinitions); var usedArguments = argumentDefinitionsToMap(nodeWithUsedArguments.argumentDefinitions); // All used arguments must be defined var undefinedVariables = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = usedArguments.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var argDef = _step.value; if (!definedArguments.has(argDef.name)) { undefinedVariables.push(argDef); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (undefinedVariables.length !== 0) { throw createUserError("Operation '".concat(node.name, "' references undefined variable(s):\n").concat(undefinedVariables.map(function (argDef) { return "- $".concat(argDef.name, ": ").concat(context.getSchema().getTypeString(argDef.type)); }).join('\n'), "."), undefinedVariables.map(function (argDef) { return argDef.loc; })); } }); return context; } function argumentDefinitionsToMap(argDefs) { var map = new Map(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = argDefs[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var argDef = _step2.value; map.set(argDef.name, argDef); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return map; } module.exports = { transform: validateGlobalVariablesTransform }; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRValidator = __webpack_require__(46); var _require = __webpack_require__(1), createUserError = _require.createUserError; var _require2 = __webpack_require__(30), getFieldDefinitionStrict = _require2.getFieldDefinitionStrict; /* * Validate required arguments are provided after transforms filling in arguments */ function validateRequiredArguments(context) { GraphQLIRValidator.validate(context, { Directive: visitDirective, ConnectionField: visitField, InlineFragment: visitInlineFragment, LinkedField: visitField, ScalarField: visitField // FragmentSpread validation is done in ApplyFragmentArgumentTransform }, function (node) { return { rootNode: node, parentType: node.type }; }); return context; } function visitDirective(node, _ref) { var rootNode = _ref.rootNode; var context = this.getContext(); var directiveDef = context.getSchema().getDirective(node.name); if (directiveDef == null) { return; } validateRequiredArgumentsOnNode(context.getSchema(), node, directiveDef.args, rootNode); } function visitInlineFragment(fragment, _ref2) { var rootNode = _ref2.rootNode; this.traverse(fragment, { rootNode: rootNode, parentType: fragment.typeCondition }); } function visitField(node, _ref3) { var parentType = _ref3.parentType, rootNode = _ref3.rootNode; var context = this.getContext(); var schema = context.getSchema(); var definition = getFieldDefinitionStrict(schema, parentType, node.name); if (definition == null) { var isLegacyFatInterface = node.directives.some(function (directive) { return directive.name === 'fixme_fat_interface'; }); if (!isLegacyFatInterface) { throw createUserError("Unknown field '".concat(node.name, "' on type ") + "'".concat(schema.getTypeString(parentType), "'."), [node.loc]); } } else { validateRequiredArgumentsOnNode(schema, node, schema.getFieldConfig(definition).args, rootNode); } this.traverse(node, { rootNode: rootNode, parentType: node.type }); } function validateRequiredArgumentsOnNode(schema, node, definitionArgs, rootNode) { var nodeArgsSet = new Set(node.args.map(function (arg) { return arg.name; })); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = definitionArgs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var arg = _step.value; if (schema.isNonNull(arg.type) && !nodeArgsSet.has(arg.name)) { throw createUserError("Required argument '".concat(arg.name, ": ").concat(schema.getTypeString(arg.type), "' ") + "is missing on '".concat(node.name, "' in '").concat(rootNode.name, "'."), [node.loc, rootNode.loc]); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } module.exports = { transform: validateRequiredArguments }; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var GraphQLIRValidator = __webpack_require__(46); var _require = __webpack_require__(1), createUserError = _require.createUserError; var NODEKIND_DIRECTIVE_MAP = { Defer: 'defer', Stream: 'stream' }; /* * Validate that server-only directives are not used inside client fields */ function validateServerOnlyDirectives(context) { GraphQLIRValidator.validate(context, { ClientExtension: visitClientExtension, Defer: visitTransformedDirective, Stream: visitTransformedDirective, LinkedField: visitLinkedField, ScalarField: stopVisit }, function () { return { rootClientSelection: null }; }); return context; } // If an empty visitor is defined, we no longer automatically visit child nodes // such as arguments. function stopVisit() {} // Only visits selections as an optimization to not look at arguments function visitLinkedField(node, state) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = node.selections[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var selection = _step.value; this.visit(selection, state); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } function visitClientExtension(node, state) { var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = node.selections[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var selection = _step2.value; this.visit(selection, { rootClientSelection: selection }); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } function visitTransformedDirective(node, state) { if (state.rootClientSelection) { throwError("@".concat(NODEKIND_DIRECTIVE_MAP[node.kind]), node.loc, state.rootClientSelection.loc); } // directive used only on client fields if (node.selections.every(function (sel) { return sel.kind === 'ClientExtension'; })) { var _clientExtension$sele; var clientExtension = node.selections[0]; throwError("@".concat(NODEKIND_DIRECTIVE_MAP[node.kind]), node.loc, clientExtension && clientExtension.kind === 'ClientExtension' ? (_clientExtension$sele = clientExtension.selections[0]) === null || _clientExtension$sele === void 0 ? void 0 : _clientExtension$sele.loc : null); } this.traverse(node, state); } function throwError(directiveName, directiveLoc, clientExtensionLoc) { throw createUserError("Unexpected directive: ".concat(directiveName, ". ") + 'This directive can only be used on fields/fragments that are ' + 'fetched from the server schema, but it is used ' + 'inside a client-only selection.', clientExtensionLoc == null || directiveLoc === clientExtensionLoc ? [directiveLoc] : [directiveLoc, clientExtensionLoc]); } module.exports = { transform: validateServerOnlyDirectives }; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var inferRootArgumentDefinitions = __webpack_require__(17); var _require = __webpack_require__(1), createUserError = _require.createUserError, eachWithCombinedError = _require.eachWithCombinedError; var SCHEMA_EXTENSION = 'directive @DEPRECATED__relay_ignore_unused_variables_error on QUERY | MUTATION | SUBSCRIPTION'; /** * Validates that there are no unused variables in the operation. * former `graphql-js`` NoUnusedVariablesRule */ function validateUnusedVariablesTransform(context) { var contextWithUsedArguments = inferRootArgumentDefinitions(context); eachWithCombinedError(context.documents(), function (node) { if (node.kind !== 'Root') { return; } var rootArgumentLocations = new Map(node.argumentDefinitions.map(function (arg) { return [arg.name, arg.loc]; })); var nodeWithUsedArguments = contextWithUsedArguments.getRoot(node.name); var usedArguments = argumentDefinitionsToMap(nodeWithUsedArguments.argumentDefinitions); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = usedArguments.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var usedArgumentName = _step.value; rootArgumentLocations["delete"](usedArgumentName); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var ignoreErrorDirective = node.directives.find(function (_ref) { var name = _ref.name; return name === 'DEPRECATED__relay_ignore_unused_variables_error'; }); if (rootArgumentLocations.size > 0 && !ignoreErrorDirective) { var isPlural = rootArgumentLocations.size > 1; throw createUserError("Variable".concat(isPlural ? 's' : '', " '$").concat(Array.from(rootArgumentLocations.keys()).join("', '$"), "' ").concat(isPlural ? 'are' : 'is', " never used in operation '").concat(node.name, "'."), Array.from(rootArgumentLocations.values())); } if (rootArgumentLocations.size === 0 && ignoreErrorDirective) { throw createUserError("Invalid usage of '@DEPRECATED__relay_ignore_unused_variables_error.'" + "No unused variables found in the query '".concat(node.name, "'"), [ignoreErrorDirective.loc]); } }); return context; } function argumentDefinitionsToMap(argDefs) { var map = new Map(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = argDefs[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var argDef = _step2.value; map.set(argDef.name, argDef); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return map; } module.exports = { transform: validateUnusedVariablesTransform, SCHEMA_EXTENSION: SCHEMA_EXTENSION }; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var RelayFlowGenerator = __webpack_require__(44); var formatGeneratedModule = __webpack_require__(105); var _require = __webpack_require__(106), find = _require.find; module.exports = function () { return { inputExtensions: ['js', 'jsx'], outputExtension: 'js', typeGenerator: RelayFlowGenerator, formatModule: formatGeneratedModule, findGraphQLTags: find }; }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var formatGeneratedModule = function formatGeneratedModule(_ref) { var moduleName = _ref.moduleName, documentType = _ref.documentType, docText = _ref.docText, concreteText = _ref.concreteText, typeText = _ref.typeText, hash = _ref.hash, sourceHash = _ref.sourceHash; var documentTypeImport = documentType ? "import type { ".concat(documentType, " } from 'relay-runtime';") : ''; var docTextComment = docText ? '\n/*\n' + docText.trim() + '\n*/\n' : ''; var hashText = hash ? "\n * ".concat(hash) : ''; return "/**\n * ".concat('@', "flow", hashText, "\n */\n\n/* eslint-disable */\n\n'use strict';\n\n/*::\n").concat(documentTypeImport, "\n").concat(typeText || '', "\n*/\n\n").concat(docTextComment, "\nconst node/*: ").concat(documentType || 'empty', "*/ = ").concat(concreteText, ";\n// prettier-ignore\n(node/*: any*/).hash = '").concat(sourceHash, "';\nmodule.exports = node;\n"); }; module.exports = formatGeneratedModule; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var Profiler = __webpack_require__(6); var babylon = __webpack_require__(107); var util = __webpack_require__(47); // Attempt to be as inclusive as possible of source text. var BABYLON_OPTIONS = { allowImportExportEverywhere: true, allowReturnOutsideFunction: true, allowSuperOutsideMethod: true, sourceType: 'module', plugins: [// Previously "*" 'asyncGenerators', 'classProperties', ['decorators', { decoratorsBeforeExport: true }], 'doExpressions', 'dynamicImport', 'exportExtensions', 'flow', 'functionBind', 'functionSent', 'jsx', 'nullishCoalescingOperator', 'objectRestSpread', 'optionalChaining', 'optionalCatchBinding'], strictMode: false }; function find(text) { var result = []; var ast = babylon.parse(text, BABYLON_OPTIONS); var visitors = { CallExpression: function CallExpression(node) { var callee = node.callee; if (!(callee.type === 'Identifier' && CREATE_CONTAINER_FUNCTIONS[callee.name] || callee.kind === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.value === 'Relay' && callee.property.type === 'Identifier' && CREATE_CONTAINER_FUNCTIONS[callee.property.name])) { traverse(node, visitors); return; } var fragments = node.arguments[1]; if (fragments.type === 'ObjectExpression') { fragments.properties.forEach(function (property) { !(property.type === 'ObjectProperty' && property.key.type === 'Identifier' && property.value.type === 'TaggedTemplateExpression') ? true ? invariant(false, 'FindGraphQLTags: `%s` expects fragment definitions to be ' + '`key: graphql`.', node.callee.name) : undefined : void 0; !isGraphQLModernOrDeprecatedTag(property.value.tag) ? true ? invariant(false, 'FindGraphQLTags: `%s` expects fragment definitions to be tagged ' + 'with `graphql`, got `%s`.', node.callee.name, getSourceTextForLocation(text, property.value.tag.loc)) : undefined : void 0; if (isGraphQLTag(property.value.tag)) { result.push({ keyName: property.key.name, template: getGraphQLText(property.value.quasi), sourceLocationOffset: getSourceLocationOffset(property.value.quasi) }); } }); } else { !(fragments && fragments.type === 'TaggedTemplateExpression') ? true ? invariant(false, 'FindGraphQLTags: `%s` expects a second argument of fragment ' + 'definitions.', node.callee.name) : undefined : void 0; !isGraphQLModernOrDeprecatedTag(fragments.tag) ? true ? invariant(false, 'FindGraphQLTags: `%s` expects fragment definitions to be tagged ' + 'with `graphql`, got `%s`.', node.callee.name, getSourceTextForLocation(text, fragments.tag.loc)) : undefined : void 0; result.push({ keyName: null, template: getGraphQLText(fragments.quasi), sourceLocationOffset: getSourceLocationOffset(fragments.quasi) }); } // Visit remaining arguments for (var ii = 2; ii < node.arguments.length; ii++) { visit(node.arguments[ii], visitors); } }, TaggedTemplateExpression: function TaggedTemplateExpression(node) { if (isGraphQLTag(node.tag)) { result.push({ keyName: null, template: node.quasi.quasis[0].value.raw, sourceLocationOffset: getSourceLocationOffset(node.quasi) }); } } }; visit(ast, visitors); return result; } var CREATE_CONTAINER_FUNCTIONS = Object.create(null, { createFragmentContainer: { value: true }, createPaginationContainer: { value: true }, createRefetchContainer: { value: true } }); var IGNORED_KEYS = { comments: true, end: true, leadingComments: true, loc: true, name: true, start: true, trailingComments: true, type: true }; function isGraphQLTag(tag) { return tag.type === 'Identifier' && tag.name === 'graphql'; } function isGraphQLModernOrDeprecatedTag(tag) { return tag.type === 'Identifier' && (tag.name === 'graphql' || tag.name === 'graphql_DEPRECATED'); } function getTemplateNode(quasi) { var quasis = quasi.quasis; !(quasis && quasis.length === 1) ? true ? invariant(false, 'FindGraphQLTags: Substitutions are not allowed in graphql tags.') : undefined : void 0; return quasis[0]; } function getGraphQLText(quasi) { return getTemplateNode(quasi).value.raw; } function getSourceLocationOffset(quasi) { var loc = getTemplateNode(quasi).loc.start; return { line: loc.line, column: loc.column + 1 // babylon is 0-indexed, graphql expects 1-indexed }; } function getSourceTextForLocation(text, loc) { if (loc == null) { return '(source unavailable)'; } var lines = text.split('\n').slice(loc.start.line - 1, loc.end.line); lines[0] = lines[0].slice(loc.start.column); lines[lines.length - 1] = lines[lines.length - 1].slice(0, loc.end.column); return lines.join('\n'); } function invariant(condition, msg) { if (!condition) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } throw new Error(util.format.apply(util, [msg].concat(args))); } } function visit(node, visitors) { var fn = visitors[node.type]; if (fn != null) { fn(node); return; } traverse(node, visitors); } function traverse(node, visitors) { for (var key in node) { if (IGNORED_KEYS[key]) { continue; } var prop = node[key]; if (prop && typeof prop === 'object' && typeof prop.type === 'string') { visit(prop, visitors); } else if (Array.isArray(prop)) { prop.forEach(function (item) { if (item && typeof item === 'object' && typeof item.type === 'string') { visit(item, visitors); } }); } } } module.exports = { find: Profiler.instrument(find, 'FindGraphQLTags.find') }; /***/ }), /* 107 */ /***/ (function(module, exports) { module.exports = require("@babel/parser"); /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(5)); var ASTCache = __webpack_require__(26); var GraphQL = __webpack_require__(7); var Profiler = __webpack_require__(6); var fs = __webpack_require__(13); var invariant = __webpack_require__(4); var path = __webpack_require__(8); var _require = __webpack_require__(109), memoizedFind = _require.memoizedFind; var parseGraphQL = Profiler.instrument(GraphQL.parse, 'GraphQL.parse'); module.exports = function (tagFinder) { var memoizedTagFinder = memoizedFind.bind(null, tagFinder); function parseFile(baseDir, file) { var result = parseFileWithSources(baseDir, file); if (result) { return result.document; } } // Throws an error if parsing the file fails function parseFileWithSources(baseDir, file) { var filePath = path.join(baseDir, file.relPath); var text = ''; try { text = fs.readFileSync(filePath, 'utf8'); } catch (_unused) { true ? true ? invariant(false, 'RelaySourceModuleParser: Files should be filtered before passed to the ' + 'parser, got unfiltered file `%s`.', file.relPath) : undefined : undefined; } var astDefinitions = []; var sources = []; memoizedTagFinder(text, baseDir, file).forEach(function (template) { var source = new GraphQL.Source(template, file.relPath); var ast = parseGraphQL(source); !ast.definitions.length ? true ? invariant(false, 'RelaySourceModuleParser: Expected GraphQL text to contain at least one ' + 'definition (fragment, mutation, query, subscription), got `%s`.', template) : undefined : void 0; sources.push(source.body); astDefinitions.push.apply(astDefinitions, (0, _toConsumableArray2["default"])(ast.definitions)); }); return { document: { kind: 'Document', definitions: astDefinitions }, sources: sources }; } function getParser(baseDir) { return new ASTCache({ baseDir: baseDir, parse: parseFile }); } function getFileFilter(baseDir) { return function (file) { var filePath = path.join(baseDir, file.relPath); var text = ''; try { text = fs.readFileSync(filePath, 'utf8'); } catch (_unused2) { // eslint-disable no-console console.warn("RelaySourceModuleParser: Unable to read the file \"".concat(filePath, "\". Looks like it was removed.")); return false; } return text.indexOf('graphql') >= 0; }; } return { getParser: getParser, getFileFilter: getFileFilter, parseFile: parseFile, parseFileWithSources: parseFileWithSources }; }; /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var RelayCompilerCache = __webpack_require__(110); var getModuleName = __webpack_require__(112); var graphql = __webpack_require__(7); var path = __webpack_require__(8); var util = __webpack_require__(47); var cache = new RelayCompilerCache('RelayFindGraphQLTags', 'v1'); function memoizedFind(tagFinder, text, baseDir, file) { !file.exists ? true ? invariant(false, 'RelayFindGraphQLTags: Called with non-existent file `%s`', file.relPath) : undefined : void 0; return cache.getOrCompute(file.hash, find.bind(null, tagFinder, text, path.join(baseDir, file.relPath))); } function find(tagFinder, text, absPath) { var tags = tagFinder(text, absPath); var moduleName = getModuleName(absPath); tags.forEach(function (tag) { return validateTemplate(tag, moduleName, absPath); }); return tags.map(function (tag) { return tag.template; }); } function validateTemplate(_ref, moduleName, filePath) { var template = _ref.template, keyName = _ref.keyName, sourceLocationOffset = _ref.sourceLocationOffset; var ast = graphql.parse(new graphql.Source(template, filePath, sourceLocationOffset)); ast.definitions.forEach(function (def) { if (def.kind === 'OperationDefinition') { !(def.name != null) ? true ? invariant(false, 'RelayFindGraphQLTags: In module `%s`, an operation requires a name.', moduleName, def.kind) : undefined : void 0; var definitionName = def.name.value; var operationNameParts = definitionName.match(/^(.*)(Mutation|Query|Subscription)$/); !(operationNameParts && definitionName.startsWith(moduleName)) ? true ? invariant(false, 'RelayFindGraphQLTags: Operation names in graphql tags must be prefixed ' + 'with the module name and end in "Mutation", "Query", or ' + '"Subscription". Got `%s` in module `%s`.', definitionName, moduleName) : undefined : void 0; } else if (def.kind === 'FragmentDefinition') { var _definitionName = def.name.value; if (keyName != null) { !(_definitionName === moduleName + '_' + keyName) ? true ? invariant(false, 'RelayFindGraphQLTags: Container fragment names must be ' + '`_`. Got `%s`, expected `%s`.', _definitionName, moduleName + '_' + keyName) : undefined : void 0; } else { !_definitionName.startsWith(moduleName) ? true ? invariant(false, 'RelayFindGraphQLTags: Fragment names in graphql tags must be prefixed ' + 'with the module name. Got `%s` in module `%s`.', _definitionName, moduleName) : undefined : void 0; } } }); } // TODO: Not sure why this is defined here rather than imported, is it so that it doesn’t get stripped in prod? function invariant(condition, msg) { if (!condition) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } throw new Error(util.format.apply(util, [msg].concat(args))); } } module.exports = { find: find, // Exported for testing only. memoizedFind: memoizedFind }; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var _interopRequireDefault = __webpack_require__(0); var _defineProperty2 = _interopRequireDefault(__webpack_require__(23)); var Profiler = __webpack_require__(6); var crypto = __webpack_require__(12); var fs = __webpack_require__(13); var os = __webpack_require__(111); var path = __webpack_require__(8); /** * A file backed cache. Values are JSON encoded on disk, so only JSON * serializable values should be used. */ var RelayCompilerCache = /*#__PURE__*/ function () { /** * @param name Human readable identifier for the cache * @param cacheBreaker This should be changed in order to invalidate existing * caches. */ function RelayCompilerCache(name, cacheBreaker) { (0, _defineProperty2["default"])(this, "_dir", null); this._name = name; this._cacheBreaker = cacheBreaker; } var _proto = RelayCompilerCache.prototype; _proto._getFile = function _getFile(key) { if (this._dir == null) { // Include username in the cache dir to avoid issues with directories being // owned by a different user. var username = os.userInfo().username; var cacheID = crypto.createHash('md5').update(this._cacheBreaker).update(username).digest('hex'); var dir = path.join(os.tmpdir(), "".concat(this._name, "-").concat(cacheID)); if (!fs.existsSync(dir)) { try { fs.mkdirSync(dir); } catch (error) { if (error.code !== 'EEXIST') { throw error; } } } this._dir = dir; } return path.join(this._dir, key); }; _proto.getOrCompute = function getOrCompute(key, compute) { var _this = this; return Profiler.run('RelayCompilerCache.getOrCompute', function () { var cacheFile = _this._getFile(key); if (fs.existsSync(cacheFile)) { try { return JSON.parse(fs.readFileSync(cacheFile, 'utf8')); } catch (_unused) {// ignore } } var value = compute(); try { // $FlowFixMe(>=0.95.0) JSON.stringify can return undefined fs.writeFileSync(cacheFile, JSON.stringify(value), 'utf8'); } catch (_unused2) {// ignore } return value; }); }; return RelayCompilerCache; }(); module.exports = RelayCompilerCache; /***/ }), /* 111 */ /***/ (function(module, exports) { module.exports = require("os"); /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ var path = __webpack_require__(8); function getModuleName(filePath) { // index.js -> index // index.js.flow -> index.js var filename = path.basename(filePath, path.extname(filePath)); // index.js -> index (when extension has multiple segments) filename = filename.replace(/(?:\.\w+)+/, ''); // /path/to/button/index.js -> button var moduleName = filename === 'index' ? path.basename(path.dirname(filePath)) : filename; // Example.ios -> Example // Example.product.android -> Example moduleName = moduleName.replace(/(?:\.\w+)+/, ''); // foo-bar -> fooBar // Relay compatibility mode splits on _, so we can't use that here. moduleName = moduleName.replace(/[^a-zA-Z0-9]+(\w?)/g, function (match, next) { return next.toUpperCase(); }); return moduleName; } module.exports = getModuleName; /***/ }), /* 113 */ /***/ (function(module, exports) { module.exports = require("fast-glob"); /***/ }) /******/ ]);