func Generate(config *Config) (map[string][]byte, error) {
	schema, err := getSchema(config.Schema)
	if err != nil {
		return nil, err
	}
	document, err := getAndValidateQueries(config.baseDir, config.Operations, schema)
	if err != nil {
		return nil, err
	}
	if len(document.Operations) == 0 {
		return nil, errorf(nil,
			"no queries found, looked in: %v (configure this in genqlient.yaml)",
			strings.Join(config.Operations, ", "))
	}
	g := newGenerator(config, schema, document.Fragments)
	for _, op := range document.Operations {
		if err = g.addOperation(op); err != nil {
			return nil, err
		}
	}
	var bodyBuf bytes.Buffer
	err = g.WriteTypes(&bodyBuf)
	if err != nil {
		return nil, err
	}
	for _, operation := range g.Operations {
		err = g.render("operation.go.tmpl", &bodyBuf, operation)
		if err != nil {
			return nil, err
		}
	}
	if g.Config.ContextType != "-" {
		_, err = g.ref("context.Context")
		if err != nil {
			return nil, err
		}
		if g.Config.ContextType != "context.Context" {
			_, err = g.ref(g.Config.ContextType)
			if err != nil {
				return nil, err
			}
		}
	}
	var buf bytes.Buffer
	err = g.render("header.go.tmpl", &buf, g)
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(&buf, &bodyBuf)
	if err != nil {
		return nil, err
	}
	unformatted := buf.Bytes()
	formatted, err := format.Source(unformatted)
	if err != nil {
		return nil, goSourceError("gofmt", unformatted, err)
	}
	importsed, err := imports.Process(config.Generated, formatted, nil)
	if err != nil {
		return nil, goSourceError("goimports", formatted, err)
	}
	retval := map[string][]byte{
		config.Generated: importsed,
	}
	if config.ExportOperations != "" {
		retval[config.ExportOperations], err = json.MarshalIndent(
			exportedOperations{Operations: g.Operations}, "", "  ")
		if err != nil {
			return nil, errorf(nil, "unable to export queries: %v", err)
		}
	}
	return retval, nil
}
Generate is the main programmatic entrypoint to genqlient, and generates and
returns Go source code based on the given configuration.

See Config for more on creating a configuration.  The return value is a map
from filename to the generated file-content (e.g. Go source).  Callers who
don't want to manage reading and writing the files should call Main.
package generate
import (
	"bytes"
	"encoding/json"
	"go/format"
	"io"
	"sort"
	"strings"
	"text/template"
	"github.com/vektah/gqlparser/v2/ast"
	"github.com/vektah/gqlparser/v2/formatter"
	"github.com/vektah/gqlparser/v2/validator"
	"golang.org/x/tools/imports"
)
type generator struct {
	Config *Config
	Operations []*operation
	typeMap map[string]goType
	imports     map[string]string
	usedAliases map[string]bool
	importsLocked bool
	templateCache map[string]*template.Template
	schema *ast.Schema
	fragments map[string]*ast.FragmentDefinition
}
type operation struct {
	Type ast.Operation `json:"-"`
	Name string `json:"operationName"`
	Doc string `json:"-"`
	Body string `json:"query"`
	Input *goStructType `json:"-"`
	ResponseName string `json:"-"`
	SourceFilename string `json:"sourceLocation"`
	Config *Config `json:"-"`
}
type exportedOperations struct {
	Operations []*operation `json:"operations"`
}
func newGenerator(
	config *Config,
	schema *ast.Schema,
	fragments ast.FragmentDefinitionList,
) *generator {
	g := generator{
		Config:        config,
		typeMap:       map[string]goType{},
		imports:       map[string]string{},
		usedAliases:   map[string]bool{},
		templateCache: map[string]*template.Template{},
		schema:        schema,
		fragments:     make(map[string]*ast.FragmentDefinition, len(fragments)),
	}
	for _, fragment := range fragments {
		g.fragments[fragment.Name] = fragment
	}
	return &g
}
func (g *generator) WriteTypes(w io.Writer) error {
	names := make([]string, 0, len(g.typeMap))
	for name := range g.typeMap {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		err := g.typeMap[name].WriteDefinition(w, g)
		if err != nil {
			return err
		}
		_, err = io.WriteString(w, "\n\n")
		if err != nil {
			return err
		}
	}
	return nil
}
func (g *generator) usedFragments(op *ast.OperationDefinition) ast.FragmentDefinitionList {
	var retval, queue ast.FragmentDefinitionList
	seen := map[string]bool{}
	var observers validator.Events
	observers.OnFragmentSpread(func(_ *validator.Walker, fragmentSpread *ast.FragmentSpread) {
		if seen[fragmentSpread.Name] {
			return
		}
		def := g.fragments[fragmentSpread.Name]
		seen[fragmentSpread.Name] = true
		retval = append(retval, def)
		queue = append(queue, def)
	})
	doc := ast.QueryDocument{Operations: ast.OperationList{op}}
	validator.Walk(g.schema, &doc, &observers)
	for len(queue) > 0 {
		doc = ast.QueryDocument{Fragments: ast.FragmentDefinitionList{queue[0]}}
		validator.Walk(g.schema, &doc, &observers)  
		queue = queue[1:]
	}
	return retval
}
func (g *generator) preprocessQueryDocument(doc *ast.QueryDocument) {
	var observers validator.Events
	observers.OnField(func(_ *validator.Walker, field *ast.Field) {
		fieldType := g.schema.Types[field.Definition.Type.Name()]
		if fieldType.Kind != ast.Interface && fieldType.Kind != ast.Union {
			return  
		}
		hasTypename := false
		for _, selection := range field.SelectionSet {
			subField, ok := selection.(*ast.Field)
			if ok && subField.Name == "__typename" {
				hasTypename = true
			}
		}
		if !hasTypename {
			field.SelectionSet = append(ast.SelectionSet{
				&ast.Field{
					Alias: "__typename", Name: "__typename",
					Definition: &ast.FieldDefinition{
						Name: "__typename",
						Type: ast.NamedType("String", nil  ),
					},
					ObjectDefinition: fieldType,
				},
			}, field.SelectionSet...)
		}
	})
	validator.Walk(g.schema, doc, &observers)
}
func (g *generator) addOperation(op *ast.OperationDefinition) error {
	if op.Name == "" {
		return errorf(op.Position, "operations must have operation-names")
	}
	queryDoc := &ast.QueryDocument{
		Operations: ast.OperationList{op},
		Fragments:  g.usedFragments(op),
	}
	g.preprocessQueryDocument(queryDoc)
	var builder strings.Builder
	f := formatter.NewFormatter(&builder)
	f.FormatQueryDocument(queryDoc)
	commentLines, directive, err := g.parsePrecedingComment(op, nil, op.Position, nil)
	if err != nil {
		return err
	}
	inputType, err := g.convertArguments(op, directive)
	if err != nil {
		return err
	}
	responseType, err := g.convertOperation(op, directive)
	if err != nil {
		return err
	}
	var docComment string
	if len(commentLines) > 0 {
		docComment = "// " + strings.ReplaceAll(commentLines, "\n", "\n// ")
	}
	sourceFilename := op.Position.Src.Name
	if i := strings.LastIndex(sourceFilename, ":"); i != -1 {
		sourceFilename = sourceFilename[:i]
	}
	g.Operations = append(g.Operations, &operation{
		Type: op.Operation,
		Name: op.Name,
		Doc:  docComment,
		Body:           "\n" + builder.String(),
		Input:          inputType,
		ResponseName:   responseType.Reference(),
		SourceFilename: sourceFilename,
		Config:         g.Config,  
	})
	return nil
}