Relay Modern creates separate generated files, so Babel transforms graphql
definitions to lazy require function calls.
194129
function createModernNode(
  t: $FlowFixMe,
  graphqlDefinition: OperationDefinitionNode | FragmentDefinitionNode,
  state: BabelState,
  options: {
    // If an output directory is specified when running relay-compiler this should point to that directory
    artifactDirectory: ?string,
    // The command to run to compile Relay files, used for error messages.
    buildCommand: string,
    // Generate extra validation, defaults to true.
    isDevelopment: boolean,
    // Wrap the validation code in a conditional checking this variable.
    isDevVariable: ?string,
    // Use haste style global requires, defaults to false.
    isHasteMode: boolean,
  },
): Object {
  const definitionName = graphqlDefinition.name && graphqlDefinition.name.value;
  if (!definitionName) {
    throw new Error('GraphQL operations and fragments must contain names');
  }
  const requiredFile = definitionName + '.graphql';
  const requiredPath = options.isHasteMode
    ? requiredFile
    : options.artifactDirectory
    ? getRelativeImportPath(state, options.artifactDirectory, requiredFile)
    : GENERATED + requiredFile;

  const hash = crypto
    .createHash('md5')
    .update(print(graphqlDefinition), 'utf8')
    .digest('hex');

  const requireGraphQLModule = t.callExpression(t.identifier('require'), [
    t.stringLiteral(requiredPath),
  ]);

  const bodyStatements = [t.returnStatement(requireGraphQLModule)];
  if (options.isDevVariable != null || options.isDevelopment) {
    const nodeVariable = t.identifier('node');
    const nodeDotHash = t.memberExpression(nodeVariable, t.identifier('hash'));
    let checkStatements = [
      t.variableDeclaration('const', [
        t.variableDeclarator(nodeVariable, requireGraphQLModule),
      ]),
      t.ifStatement(
        t.logicalExpression(
          '&&',
          nodeDotHash,
          t.binaryExpression('!==', nodeDotHash, t.stringLiteral(hash)),
        ),
        t.blockStatement([
          t.expressionStatement(
            warnNeedsRebuild(t, definitionName, options.buildCommand),
          ),
        ]),
      ),
    ];
    if (options.isDevVariable != null) {
      checkStatements = [
        t.ifStatement(
          t.identifier(options.isDevVariable),
          t.blockStatement(checkStatements),
        ),
      ];
    }
    bodyStatements.unshift(...checkStatements);
  }
  return t.functionExpression(null, [], t.blockStatement(bodyStatements));
}
1263146
function createWrapper(fn, ctx) {
  return function() {
    return new Promise(function(resolve, reject) {
      var start = Date.now();

      var cb = function(err) {
        if (err) return reject(err);
        resolve(Date.now() - start);
      };

      // Wrap generator functions
      if (fn && fn.constructor.name === 'GeneratorFunction') {
        fn = Promise.coroutine(fn);
      }

      var res = fn.call(ctx || this, cb);

      // Synchronous spec, or using promises rather than callbacks
      if (!fn.length || (res && res.then)) {
        Promise.resolve(res).then(function() {
          resolve(Date.now() - start);
        }, reject);
      }
    });
  };
}
595592
function onJSChanged() {
  if (typeof this.jsh === 'undefined') {
    var JSH = require('./helpers/JsHelper');
    this.jsh = new JSH(this.directory);
  }

  var that = this;
  // Cases to recompute:
  //    a root file changes: index.js could remove require of lib/index making index.js a root and lib/index a root
  //    a non-root file changes: b.js is the root and a.js changes to require b.js making it the new root
  return this.jsh.getRoots().then(function (roots) {
    return that.jsh.haveRootsChanged(roots);
  })
  .then(function (haveRootsChanged) {

    if (! haveRootsChanged) {
      console.log('roots haven\'t changed');
      return;
    }

    console.log('An app root has changed');

    // Need all of the targets to regenerate the gruntfile
    return that.getAllSettings().then(function (targets) {
      return that.engine.getConfig(targets, that.extensions);
    })
    .then(function (config) {
      // Grab the targets for the apps and merge with the existing targets
      return that.jsh.getSettings().then(function (settings) {
        utils.shallowExtend(config, settings.target);

        return config;
      });
    })
    .then(function (config) {
      // console.log('Config: ', config)
      return that.engine.flushConfig(config)
        .then(function () {
          return that.engine.compileTasks(config);
        });
    });
  });
}
617210
function buildNode(file, watch) {
  if (watch) {
    return gulp.watch(paths.src + file + '.js')
      .on('change', function(file) {
        $.util.log('Copying to lib...');
        gulp.src(file.path)
          .pipe($.plumber())
          .pipe($.babel())
          .pipe(gulp.dest(paths.dist));
      });
  } else {
    return gulp.src(paths.src + file + '.js')
      .pipe($.plumber())
      .pipe($.babel())
      .pipe(gulp.dest(paths.dist));
  }
}
304318
function relayRelayDirectiveTransform(
  context: CompilerContext,
): CompilerContext {
  return IRTransformer.transform(context, {
    Fragment: visitRelayMetadata(fragmentMetadata),
    FragmentSpread: visitRelayMetadata(fragmentSpreadMetadata),
  });
}
404511
function Transformer( file, res ) {
			stream.Transform.call( this );

			this.file = file;
			this.res = res;
			this.chunks = [];
		}
1183348
function generateModelFiles(db, next) {
    var q, templateTable, allNamingErrors = [];

    q = async.queue(function (task, workerCallback) {
        var output = getConfig('output.beautify') ? beautify(task.content, { indent_size: getConfig('output.indent'), preserve_newlines: getConfig('output.preserveNewLines') }) : task.content;
        fs.writeFile(path.join(getConfig('output.folder'), 'definition-files', getFileName(task.table)), output, workerCallback);
        if (getConfig('output.log')) { logger.info('(Created) File \'' + getFileName(task.table) + '\' is created for model \'' + getModelNameFor(task.table) + '\''); }
    }, 4);

    db.schemas(function (schema) {
        schema.tables(function (table) {
            var namingError = '';
            logger.debug('Now parsing table: %s', table.name());
            if (getSpecificConfig(table.name(), 'generate.hasManyThrough') && getSpecificConfig(table.name(), 'generate.belongsToMany')) {
                next(new Error('Configuration error: Both "generate.hasManyThrough" and "generate.belongsToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
            }

            if (shouldSkip(table, 'table')) { return; }
            templateTable           = getTableOptions(table);
            table.columns(function (column) {
                templateTable.columns.push(getColumnDetails(column));
            });
            table.hasManies(function (hasMany) {
                if (shouldSkip(hasMany.referencesTable(), 'relation')) { return; }
                templateTable.hasManies.push(getHasManyDetails(hasMany));
            });
            table.hasManyThroughs(function (hasManyThrough) {
                if (getSpecificConfig(table.name(), 'generate.addRelationNameToManyToMany') && getSpecificConfig(table.name(), 'generate.addTableNameToManyToMany')) {
                    next(new Error('Configuration error: Both "generate.addRelationNameToManyToMany" and "generate.addTableNameToManyToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
                }

                if (shouldSkip(hasManyThrough.referencesTable(), 'relation') || shouldSkip(hasManyThrough.through(), 'relation')) { return; }
                if (getSpecificConfig(table.name(), 'generate.hasManyThrough')) {
                    templateTable.hasManies.push(getHasManyDetails(hasManyThrough)); // has many throughs are deprecated after Sequelize 2.0 RC3
                }
                if (getSpecificConfig(table.name(), 'generate.belongsToMany')) {
                    templateTable.belongsToManies.push(getBelongsToManyDetails(hasManyThrough));
                }
            });
            table.foreignKeyConstraints(function (fkc) {
                if (shouldSkip(fkc.referencesTable(), 'relation')) { return; }
                templateTable.belongsTos.push(getBelongsToDetails(fkc));
            });
            templateTable.relations = templateTable.hasManies.concat(templateTable.belongsTos, templateTable.belongsToManies);

            namingError = validateNaming(templateTable);

            if (namingError) {
                allNamingErrors.push(namingError);
            }

            template('index', {
                table: templateTable,
                mainScript: path.join(getConfig('output.folder'), 'index.js'),
                warning: getConfig('output.warning'),
                dataTypeVariable: getSpecificConfig(table.name(), 'generate.dataTypeVariable')
            }, function (err, result) {
                if (err) { next(err); }
                q.push({content: result, table: table}, function (err) { if (err) { next(err); } });
            });
        });
    });

    q.drain = function () {
        if (allNamingErrors.length > 0) {
            next(new Error('There are naming errors. Either set "generate.addRelationNameToManyToMany" true in configuration or rename your relations.\n' + allNamingErrors.join('\n')));
        } else {
            next(null);
        }
    };
}
1264358
function transformPlugins(path) {
    if (!/_generator-plugins/.test(path)) return through();
    return through(
      function tform(chunk, enc, cb) { cb(); }, // ignore input
      function flush(cb) {
        this.push(requirePlugins());
        cb();
      }
    );
  }
663626
function transform (stream, target) {
  const filter = {
    scripts: $.filter((file) => /\.jsx?$/.test(file.path), { restore: true }),
    styles: $.filter((file) => /\.styl$/.test(file.path), { restore: true })
  }

  return stream
  .pipe($.plumber(::console.error))

  // scripts
  .pipe(filter.scripts)
    .pipe($.sourcemaps.init())
      // include inline styles
      .pipe($.replaceRelative(/require\('\.\/(.*?\.styl')\)/g, (file, match, callback) => {
        const includePath = match.match(/\('(.*?\.styl)'\)/)[1]
        readFile(path.resolve(path.dirname(file.path), includePath), (error, data) => {
          const css = stylus(data.toString()).render()
          postcss([
            autoprefixer({
              browsers: ['last 2 versions']
            }),
            cssnano
          ])
          .process(css)
          .then(function (result) {
            return callback(`"${result.css}"`)
          })
        })
      }))
      .pipe($.babel({/** see .babelrc **/}))
    .pipe($.sourcemaps.write())
  .pipe(filter.scripts.restore)

  // styles
  .pipe(filter.styles)
    .pipe($.stylus())
    .pipe($.postcss([
      autoprefixer({
        browsers: ['last 2 versions']
      })
    ]))
  .pipe(filter.styles.restore)

  .pipe($.plumber.stop())
  .pipe(gulp.dest(target))
}
1179471
function compile (definition = {}, options = {}) {
  const { plugin } = options
  if (definition instanceof GraphQLFactoryDefinition) {
    return definition.registerPlugin(plugin).compile()
  }
  return define(definition, options).compile()
}
604605
function babelTransform(srcFile, destFile) {
    return new Promise((resolve, reject) => {
        // copy src file to local first
        const localSrcFile = `${destFile}.local`;

        // if file exist, then delete it
        Promise.resolve(existsFile(localSrcFile, READ_WRITE_PERMISSION))
          .then((value) => {
              if (!value) {
                  return true;
              }

              return fsPromise.unlinkAsync(localSrcFile);
          })
          .then(() => fsPromise.linkAsync(srcFile, localSrcFile))
          .then(() => {
              babel.transformFile(localSrcFile, (error, result) => {
                  if (error) {
                      console.error(`Error in babel compiling ${srcFile} - ${error}`);
                      reject(error);
                      return;
                  }

                  // if file exist, then delete it
                  Promise.resolve(existsFile(destFile, READ_WRITE_PERMISSION))
                    .then((value) => {
                        if (!value) {
                            return true;
                        }

                        return fsPromise.unlinkAsync(destFile);
                    })
                    .then(() => {
                        const stream = FS.createWriteStream(destFile);

                        stream.on('finish', () => {
                            resolve(true);
                        });

                        stream.write(result.code);
                        stream.end();
                    });
              });
          });
    });
}
846515
function bundleRelease(minify) {
  var bundler = browserify({
    entries: ['./src/' + entryFileName],
    standalone: standaloneName,
    debug: !minify
  });

  if(minify) {
    bundler = bundler.plugin(collapse);
  }

  var stream = bundler.bundle()
    .on('error', logError);

  if(!minify) {
    stream = stream.pipe(exorcist('./dist/' + bundleFileName + '.map'));
  }

  stream = stream.pipe(source(bundleFileName))
    .pipe(buffer())
    .pipe(derequire())
    .pipe(strip());

  if(minify) {
    return stream.pipe(rename({extname: '.min.js'}))
      .pipe(uglify())
      .pipe(gulp.dest('./dist/'));
  } else {
    return stream.pipe(gulp.dest('./dist/'));
  }
}
1007748
function useSchema(
  definition: SchemaDefinition,
  schema: GraphQLSchema,
  prefix?: ?string
) {
  const factoryDef = deconstructSchema(schema, prefix);
  return definition.merge(factoryDef);
}
1332161
function assertFragmentMap(
  componentName: string,
  fragmentSpec: GeneratedNodeMap,
): void {
  invariant(
    fragmentSpec && typeof fragmentSpec === 'object',
    'Could not create Relay Container for `%s`. ' +
      'Expected a set of GraphQL fragments, got `%s` instead.',
    componentName,
    fragmentSpec,
  );

  for (const key in fragmentSpec) {
    if (fragmentSpec.hasOwnProperty(key)) {
      const fragment = fragmentSpec[key];
      invariant(
        fragment &&
          (typeof fragment === 'object' || typeof fragment === 'function'),
        'Could not create Relay Container for `%s`. ' +
          'The value of fragment `%s` was expected to be a fragment, got `%s` instead.',
        componentName,
        key,
        fragment,
      );
    }
  }
}
135619
function relayViewerHandleTransform(context: CompilerContext): CompilerContext {
  const viewerType = context.serverSchema.getType(VIEWER_TYPE);
  if (
    viewerType == null ||
    !(viewerType instanceof GraphQLObjectType) ||
    viewerType.getFields()[ID] != null
  ) {
    return context;
  }
  return IRTransformer.transform(context, {
    LinkedField: visitLinkedField,
  });
}
338849
function generateFunctionsFiles ({ suffix, factories, entryFolder }) {
  const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars

  const sortedFactories = sortFactories(values(factories))

  // sort the factories, and split them in three groups:
  // - transform: the transform functions
  // - impure: the functions that depend on `math` or `mathWithTransform` (directly or indirectly),
  // - pure: the rest
  const pureFactories = []
  const impureFactories = []
  const transformFactories = []
  sortedFactories
    .filter(factory => !DEPRECATED_FACTORIES[factory.fn])
    .forEach(factory => {
      if (isTransform(factory)) {
        transformFactories.push(factory)
      } else if (
        contains(factory.dependencies, 'math') ||
        contains(factory.dependencies, 'mathWithTransform') ||
        contains(factory.dependencies, 'classes') ||
        isTransform(factory) ||
        factory.dependencies.some(dependency => {
          return impureFactories.find(f => f.fn === stripOptionalNotation(dependency))
        })
      ) {
        impureFactories.push(factory)
      } else {
        pureFactories.push(factory)
      }
    })

  // a map containing:
  // {
  //   'sqrt': true,
  //   'subset': true,
  //   ...
  // }
  const pureExists = {
    config: true
  }
  pureFactories.forEach(factory => {
    pureExists[factory.fn] = true
  })

  const impureExists = {
    ...pureExists
  }
  impureFactories.forEach(factory => {
    impureExists[factory.fn] = true
  })

  const math = sortedFactories
    .filter(factory => !isClass(factory))
    .filter(factory => !isTransform(factory))
    .map(factory => {
      return {
        name: factory.fn,
        renamed: DEPRECATED_FACTORIES[factory.fn],
        mappedName: FACTORY_NAMES_ES6_MAPPING[factory.fn]
      }
    })

  const classes = sortedFactories
    .filter(factory => isClass(factory))
    .map(factory => ({ name: factory.fn }))

  const data = {
    suffix,
    pureFactories: pureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            // TODO: this code is duplicated. extract it in a separate function
            if (!pureExists[dependency]) {
              if (factory.dependencies.indexOf(dependency) !== -1) {
                throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    impureFactories: impureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    transformFactories: transformFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    math,
    classes
  }

  // create file with all functions: functionsAny.generated.js, functionsNumber.generated.js
  fs.writeFileSync(path.join(entryFolder, 'pureFunctions' + suffix + '.generated.js'), pureFunctionsTemplate(data))

  // create file with all functions: impureFunctions.generated.js, impureFunctions.generated.js
  fs.writeFileSync(path.join(entryFolder, 'impureFunctions' + suffix + '.generated.js'), impureFunctionsTemplate(data))
}
772322
function createPartialTree (currentFile, partials, visitedFiles) {
  if (visitedFiles[currentFile.name]) {
    return {
      label: '*' + currentFile.name + '*',
      name: currentFile.name
    }
  }
  visitedFiles[currentFile.name] = true

  var result = {
    label: currentFile.name,
    name: currentFile.name,
    summary: _.trunc(chainOrUndefined(currentFile, 'apidocs', 0, 'parsed', 'description'), {
      separator: ' ',
      length: 50
    })
  }
  if (currentFile.children.length > 0) {
    _.merge(result, {
      children: currentFile.children.map(function (child) {
        return createPartialTree(partials[child], partials, visitedFiles)
      })
    })
  }
  return result
}