tygoja

package module
v0.0.0-...-b28abe4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 4, 2024 License: MIT Imports: 12 Imported by: 0

README

(EXP) tygoja GoDoc

tygoja is a small helper library for generating TypeScript declarations from Go code.

The generated typings are intended to be used as import helpers to provide ambient TypeScript declarations (aka. .d.ts) for goja bindings.

⚠️ Don't use it directly in production! It is not tagged and may change without notice.

It was created to semi-automate the documentation of the goja integration for PocketBase.

Use it only as a reference or as a non-critical step in your dev pipeline.

tygoja is a heavily modified fork of tygo and extends its scope with:

  • custom field and method names formatters
  • types for interfaces (exported and unexported)
  • types for exported interface methods
  • types for exported struct methods
  • types for exported package level functions (must enable PackageConfig.WithPackageFunctions)
  • inheritance declarations for embeded structs (embedded pointers are treated as values)
  • autoloading all unmapped argument and return types (when possible)
  • applying the same goja's rules when resolving the return types of exported function and methods
  • combining multiple packages typings in a single output
  • generating all declarations in namespaces with the packages name (both unmapped and mapped)
  • preserving comment block new lines
  • converting Go comment code blocks to Markdown code blocks
  • and others...

Note that by default the generated typings are not generated with export since the intended usage is to map them to your custom goja bindings. This mapping could be defined in the Config.Heading field usually with the declare keyword (eg. declare let someGojaProp: app.Cache).

Example

package main

import (
    "log"
    "os"

    "github.com/pocketbase/tygoja"
)

func main() {
    gen := tygoja.New(tygoja.Config{
        Packages: map[string][]string{
            "github.com/pocketbase/tygoja/test/a": {"*"},
            "github.com/pocketbase/tygoja/test/b": {"*"},
            "github.com/pocketbase/tygoja/test/c": {"Example2", "Handler"},
        },
        Heading:              `declare var $app: c.Handler; // bind other fields `,
        WithPackageFunctions: true,
    })

    result, err := gen.Generate()
    if err != nil {
        log.Fatal(err)
    }

    if err := os.WriteFile("./types.d.ts", []byte(result), 0644); err != nil {
        log.Fatal(err)
    }
}

You can also combine it with typedoc to create HTML/JSON docs from the generated declaration(s).

See the package /test directory for example output.

For a more detailed example you can also explore the PocketBase's jsvm plugin.

Known issues and limitations

  • Multiple versions of the same package may have unexpected declaration since all versions will be under the same namespace.
  • For easier generation, it relies on TypeScript declarations merging, meaning that the generated types may not be very compact.
  • Package level functions and constants, that are reserved JS identifier, are prefixed with underscore (eg. _in()).

Documentation

Index

Constants

View Source
const (

	// custom base types that every package has access to
	BaseTypeDict = "_TygojaDict" // Record type alternative as a more generic map-like type
	BaseTypeAny  = "_TygojaAny"  // any type alias to allow easier extends generation
)

Variables

This section is empty.

Functions

func PseudorandomString

func PseudorandomString(length int) string

PseudorandomString generates a pseudorandom string from the default alphabet with the specified length.

func PseudorandomStringWithAlphabet

func PseudorandomStringWithAlphabet(length int, alphabet string) string

PseudorandomStringWithAlphabet generates a pseudorandom string with the specified length and characters set.

Types

type Config

type Config struct {
	// Packages is a list of package paths just like you would import them in Go.
	// Use "*" to generate all package types.
	//
	// Example:
	//
	// 	Packages: map[string][]string{
	// 		"time": {"Time"},
	// 		"github.com/pocketbase/pocketbase/core": {"*"},
	// 	}
	Packages map[string][]string

	// Heading specifies a content that will be put at the top of the output declaration file.
	//
	// You would generally use this to import custom types or some custom TS declarations.
	Heading string

	// TypeMappings specifies custom type translations.
	//
	// Useful for for mapping 3rd party package types, eg "unsafe.Pointer" => "CustomType".
	//
	// Be default unrecognized types will be recursively generated by
	// traversing their import package (when possible).
	TypeMappings map[string]string

	// WithConstants indicates whether to generate types for constants
	// ("false" by default).
	WithConstants bool

	// WithPackageFunctions indicates whether to generate types
	// for package level functions ("false" by default).
	WithPackageFunctions bool

	// FieldNameFormatter allows specifying a custom struct field name formatter.
	FieldNameFormatter FieldNameFormatterFunc

	// MethodNameFormatter allows specifying a custom method name formatter.
	MethodNameFormatter MethodNameFormatterFunc

	// StartModifier usually should be "export" or declare but as of now prevents
	// the LSP autocompletion so we keep it empty.
	//
	// See also:
	// https://github.com/microsoft/TypeScript/issues/54330
	// https://github.com/microsoft/TypeScript/pull/49644
	StartModifier string

	// Indent allow customizing the default indentation (use \t if you want tabs).
	Indent string
}

func (*Config) InitDefaults

func (c *Config) InitDefaults()

Initializes the defaults (if not already) of the current config.

type FieldNameFormatterFunc

type FieldNameFormatterFunc func(string) string

FieldNameFormatterFunc defines a function for formatting a field name.

type MethodNameFormatterFunc

type MethodNameFormatterFunc func(string) string

MethodNameFormatterFunc defines a function for formatting a method name.

type PackageGenerator

type PackageGenerator struct {
	// contains filtered or unexported fields
}

PackageGenerator is responsible for generating the code for a single input package.

func (*PackageGenerator) Generate

func (g *PackageGenerator) Generate() (string, error)

Generate generates the typings for a single package.

type Tygoja

type Tygoja struct {
	// contains filtered or unexported fields
}

Tygoja is a generator for one or more input packages, responsible for linking them together if necessary.

func New

func New(config Config) *Tygoja

New initializes a new Tygoja generator from the specified config.

func (*Tygoja) Generate

func (g *Tygoja) Generate() (string, error)

Generate executes the generator and produces the related TS files.

Directories

Path Synopsis
a
package a docs lorem ipsum dolor...
package a docs lorem ipsum dolor...
b
package b
package b
c

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL