typescript

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2021 License: GPL-3.0 Imports: 14 Imported by: 2

README

Goja Typescript Transpiler and Evaluator (with AMD module support)

This package provides a simple interface using github.com/dop251/goja under the hood to allow you to transpile Typescript to Javascript in Go. In addition it provides an evaluator with a built-in AMD module loader which allows you to run Typescript code against a compiled typescript bundle. This package has no direct dependencies besides testing utilities and has a 95% test coverage rate.

Feel free to contribute. This package is fresh and may experience some changes before it's first tagged release.

Transpiling Examples

Transpile Strings
output, err := typescript.TranspileString("let a: number = 10;", nil)
// output: var a = 10;
Transpile Reader
output, err := typescript.Transpile(reader, nil)
Custom Typescript Compile Options

You can optionally specify alternative compiler options that are used by Typescript. Any of the options https://www.typescriptlang.org/docs/handbook/compiler-options.html can be added.

output, err = typescript.TranspileString(script, typescript.WithCompileOptions(map[string]interface{}{
    "module": "none",
    "strict": true,
}))
Custom Typescript Version

You can optionally specify which typescript version you want to compile using. These versions are based on the Git tags from the Typescript repository. If you're using a version that is supported in this package, you'll need to import the version package as a side-effect and will automatically be registered to the default registry.

import _ "github.com/clarkmcc/go-typescript/versions/v4.2.2"

func main() {
    output, err := typescript.Transpile(reader, typescript.WithVersion("v4.2.2"))
}
Custom Typescript Source

You may want to use a custom typescript version.

func main() {
    output, err := typescript.TranspileString("let a:number = 10;", 
    	WithTypescriptSource("/* source code for typescript*/"))
}

Evaluate Examples

Basic Evaluation

You can evaluate pure Javascript code with:

result, err := Evaluate(strings.NewReader("var a = 10;")) // returns 10;
Transpile and Evaluate

Or you can transpile first:

result, err := Evaluate(strings.NewReader("let a: number = 10;"), WithTranspile()) // returns 10;
Run Script with AMD Modules

You can load in an AMD module bundle, then execute a Typescript script with access to the modules.

// This is the module we're going to import
modules := strings.TrimSpace(`
    define("myModule", ["exports"], function (exports, core_1) {
        Object.defineProperty(exports, "__esModule", { value: true });
        exports.multiply = void 0;
        var multiply = function (a, b) { return a * b; };
        exports.multiply = multiply;
    });
`)

// This is the script we're going to transpile and evaluate
script := "import { multiply } from 'myModule'; multiply(5, 5)"

// Returns 25
result, err := EvaluateCtx(context.Background(), strings.NewReader(script),
    WithAlmondModuleLoader(),
    WithTranspile(),
    WithEvaluateBefore(strings.NewReader(amdModuleScript)))

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Evaluate added in v0.3.0

func Evaluate(src io.Reader, opts ...EvaluateOptionFunc) (goja.Value, error)

Evaluate calls EvaluateCtx using the default background context

func EvaluateCtx added in v0.3.0

func EvaluateCtx(ctx context.Context, src io.Reader, opts ...EvaluateOptionFunc) (result goja.Value, err error)

EvaluateCtx evaluates the provided src using the specified options and returns the goja value result or an error.

func Transpile

func Transpile(reader io.Reader, opts ...TranspileOptionFunc) (string, error)

Transpile transpiles the bytes read from reader using the provided config and options

func TranspileCtx

func TranspileCtx(ctx context.Context, script io.Reader, opts ...TranspileOptionFunc) (string, error)

TranspileCtx compiles the bytes read from script using the provided context. Note that due to a limitation in goja, context cancellation only works while in JavaScript code, it does not interrupt native Go functions.

func TranspileString

func TranspileString(script string, opts ...TranspileOptionFunc) (string, error)

TranspileString compiles the provided typescript string and returns the

Types

type Config

type Config struct {
	CompileOptions   map[string]interface{}
	TypescriptSource *goja.Program
	Runtime          *goja.Runtime

	// If a module is exported by the typescript compiler, this is the name the module will be called
	ModuleName string

	// Verbose enables built-in verbose logging for debugging purposes.
	Verbose bool

	// PreventCancellation indicates that the transpiler should not handle context cancellation. This
	// should be used when external runtimes are configured AND cancellation is handled by those runtimes.
	PreventCancellation bool
	// contains filtered or unexported fields
}

Config defines the behavior of the typescript compiler.

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig creates a new instance of the Config struct with default values and the latest typescript source code.s

func (*Config) Initialize

func (c *Config) Initialize() error

type EvaluateConfig added in v0.3.0

type EvaluateConfig struct {
	// EvaluateBefore are sequentially evaluated in the Javascript runtime before evaluating the provided script.
	EvaluateBefore []io.Reader
	// ScriptHooks are called after transpiling (if applicable) with the script that will be evaluated immediately
	// before evaluation. If an error is returned from any of these functions, the evaluation process is aborted.
	// The script hook can make modifications and return them to the script if necessary.
	ScriptHooks []func(string) (string, error)
	// ScriptPreTranspileHooks are called before transpiling (if applicable) with the script that will be evaluated
	ScriptPreTranspileHooks []func(string) (string, error)
	// Transpile indicates whether the script should be transpiled before its evaluated in the runtime.
	Transpile bool
	// TranspileOptions are options passed directly to the transpiler if applicable
	TranspileOptions []TranspileOptionFunc
	// Runtime is the goja runtime used for script execution. If not specified, it defaults to an empty runtime
	Runtime *goja.Runtime
}

func (*EvaluateConfig) ApplyDefaults added in v0.3.0

func (cfg *EvaluateConfig) ApplyDefaults()

ApplyDefaults applies defaults to the configuration and is called automatically before the config is used

func (*EvaluateConfig) HasEvaluateBefore added in v0.3.0

func (cfg *EvaluateConfig) HasEvaluateBefore() bool

type EvaluateOptionFunc added in v0.3.0

type EvaluateOptionFunc func(cfg *EvaluateConfig)

func WithAlmondModuleLoader added in v0.3.0

func WithAlmondModuleLoader() EvaluateOptionFunc

WithAlmondModuleLoader adds the almond module loader to the list of scripts that should be evaluated first

func WithEvaluateBefore added in v0.3.0

func WithEvaluateBefore(sources ...io.Reader) EvaluateOptionFunc

WithEvaluateBefore adds scripts that should be evaluated before evaluating the provided script. Each provided script is evaluated in the order that it's provided.

func WithEvaluationRuntime added in v0.3.0

func WithEvaluationRuntime(runtime *goja.Runtime) EvaluateOptionFunc

WithEvaluationRuntime allows callers to use their own runtimes with the evaluator.

func WithScriptHook added in v0.3.0

func WithScriptHook(hook func(script string) (string, error)) EvaluateOptionFunc

WithScriptHook adds a script hook that should be evaluated immediately before the actual script evaluation

func WithScriptPreTranspileHook added in v0.4.0

func WithScriptPreTranspileHook(hook func(script string) (string, error)) EvaluateOptionFunc

WithScriptPreTranspileHook adds a script hook that should be evaluated immediately before transpiling the script

func WithTranspile added in v0.3.0

func WithTranspile() EvaluateOptionFunc

WithTranspile indicates whether the provided script should be transpiled before it is evaluated. This does not mean that all the evaluate before's will be transpiled as well, only the src provided to EvaluateCtx will be transpiled

func WithTranspileOptions added in v0.3.0

func WithTranspileOptions(opts ...TranspileOptionFunc) EvaluateOptionFunc

WithTranspileOptions adds options to be passed to the transpiler if the transpiler is applicable

type TranspileOptionFunc added in v0.3.0

type TranspileOptionFunc func(*Config)

TranspileOptionFunc allows for easy chaining of pre-built config modifiers such as WithVersion.

func WithCompileOptions

func WithCompileOptions(options map[string]interface{}) TranspileOptionFunc

WithCompileOptions sets the compile options that will be passed to the typescript compiler.

func WithModuleName added in v0.3.0

func WithModuleName(name string) TranspileOptionFunc

WithModuleName determines the module name applied to the typescript module if applicable. This is only needed to customize the module name if the typescript module mode is AMD or SystemJS.

func WithPreventCancellation added in v0.3.0

func WithPreventCancellation() TranspileOptionFunc

WithPreventCancellation prevents the transpiler runtime from handling its own context cancellation.

func WithRuntime

func WithRuntime(runtime *goja.Runtime) TranspileOptionFunc

WithRuntime allows you to over-ride the default runtime

func WithTypescriptSource added in v0.3.0

func WithTypescriptSource(src string) TranspileOptionFunc

WithTypescriptSource configures a Typescript source from the provided typescript source string which is compiled by goja when the config is initialized. This function will panic if the Typescript source is invalid.

func WithVersion

func WithVersion(tag string) TranspileOptionFunc

WithVersion loads the provided tagged typescript source from the default registry

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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