grafana/pkg/codegen/generators/ts_generator.go
Selene 473898e47c
Core: Remove thema and kindsys dependencies (#84499)
* Move some thema code inside grafana

* Use new codegen instead of thema for core kinds

* Replace TS generator

* Use new generator for go types

* Remove thema from oapi generator

* Remove thema from generators

* Don't use kindsys/thema for core kinds

* Remove kindsys/thema from plugins

* Remove last thema related

* Remove most of cuectx and move utils_ts into codegen. It also deletes wire dependency

* Merge plugins generators

* Delete thema dependency 🎉

* Fix CODEOWNERS

* Fix package name

* Fix TS output names

* More path fixes

* Fix mod codeowners

* Use original plugin's name

* Remove kindsys dependency 🎉

* Modify oapi schema and create an apply function to fix elasticsearch errors

* cue.mod was deleted by mistake

* Fix TS panels

* sort imports

* Fixing elasticsearch output

* Downgrade oapi-codegen library

* Update output ts files

* More fixes

* Restore old elasticsearch generated file and skip its generation. Remove core imports into plugins

* More lint fixes

* Add codeowners

* restore embed.go file

* Fix embed.go
2024-03-21 11:11:29 +01:00

57 lines
1.4 KiB
Go

package generators
import (
"fmt"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"github.com/grafana/cuetsy"
"github.com/grafana/cuetsy/ts"
"github.com/grafana/cuetsy/ts/ast"
)
type TSConfig struct {
CuetsyConfig *cuetsy.Config
IsGroup bool
RootName string
}
// GenerateTypesTS generates native TypeScript types and defaults corresponding to
// the provided Schema.
func GenerateTypesTS(v cue.Value, cfg *TSConfig) (*ast.File, error) {
if cfg == nil {
return nil, fmt.Errorf("configuration cannot be empty")
}
if cfg.CuetsyConfig == nil {
cfg.CuetsyConfig = &cuetsy.Config{
Export: true,
}
}
// Thema #schema was a unification between the schema and cue.TopKind(_). For any reason, without this unification,
// cuetsy fails finding some enums ¯\_(ツ)_/¯.
oldSchema := cuecontext.New().CompileBytes([]byte("_"))
schdef := v.LookupPath(cue.ParsePath("lineage.schemas[0].schema")).Unify(oldSchema)
tf, err := cuetsy.GenerateAST(schdef, *cfg.CuetsyConfig)
if err != nil {
return nil, fmt.Errorf("generating TS for child elements of schema failed: %w", err)
}
file := &ts.File{
Nodes: tf.Nodes,
}
if !cfg.IsGroup {
top, err := cuetsy.GenerateSingleAST(cfg.RootName, schdef, cuetsy.TypeInterface)
if err != nil {
return nil, fmt.Errorf("generating TS for schema root failed: %w", err)
}
file.Nodes = append(file.Nodes, top.T)
if top.D != nil {
file.Nodes = append(file.Nodes, top.D)
}
}
return file, nil
}