build

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package build turns the TypeScript source of an applet into a WebAssembly module that package runner can run.

Building has three steps, which can also be done separately:

  • Check type-checks the source with tsc, against declarations of the caller.
  • Bundle strips the types and bundles the source with a prelude, which implements the protocol of package runner, into a single script. The applet cannot import anything.
  • Compile compiles the script to QuickJS bytecode with the Javy plugin, and wraps it in a small module that runs it. That module imports its JavaScript engine from the Javy plugin; see Builder.Dependencies.

Type checking in an editor

To have an editor type-check applets as Check does, copy runtime.d.ts and tsconfig.json from this package's directory into the directory where you keep your applets, together with your declarations (Env.Declarations) as a .d.ts file. That tsconfig.json lists no files, so the editor checks every TypeScript file in the directory with them. Copy both files again when you upgrade this module, as they may change.

The editor does not check the default export against Env.Signature. Giving the export that type has the same effect:

import type { Applet } from "go-applets";
import type { Order } from "shop";

const applet: Applet<Order> = function* (input) { ... };
export default applet;
Example

This example builds an applet that reverses the text of each object it receives, and runs it over three objects.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/skybitsnl/go-applets/build"
	"github.com/skybitsnl/go-applets/runner"
)

func main() {
	ctx := context.Background()

	builder, err := build.NewBuilder(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer builder.Close(ctx)

	// The applet may use the types in Declarations, and its default export
	// must match Signature.
	env := build.Env{
		Declarations: `declare module "messages" {
  export interface Message { text: string }
}`,
		Signature: `import("go-applets").Applet<import("messages").Message>`,
	}

	// The applet reads each incoming message, reverses it, then yields it.
	appletSource := `
import type { Applet } from "go-applets";
import type { Message } from "messages";

const applet: Applet<Message> = function* (input) {
  for (const message of input) {
    yield { text: [...message.text].reverse().join("") };
  }
};
export default applet;
`

	// Build the applet to a WASM module.
	wasm, err := builder.Build(ctx, appletSource, env)
	if err != nil {
		log.Fatal(err)
	}

	// Create an engine to run the WASM module, including the dependencies it requires.
	engine, err := runner.NewEngine(ctx, builder.Dependencies(), runner.Limits{})
	if err != nil {
		log.Fatal(err)
	}
	defer engine.Close(ctx)

	// Load and run the applet WASM module in the engine.
	applet, err := engine.Load(ctx, wasm)
	if err != nil {
		log.Fatal(err)
	}
	defer applet.Close(ctx)

	outputs, err := applet.RunAll(ctx, nil, []json.RawMessage{
		json.RawMessage(`{"text": "hello"}`),
		json.RawMessage(`{"text": "world"}`),
		json.RawMessage(`{"text": "applets"}`),
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	for _, obj := range outputs {
		fmt.Println(string(obj))
	}
}
Output:
{"text":"olleh"}
{"text":"dlrow"}
{"text":"stelppa"}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bundle

func Bundle(source string) (string, error)

Bundle turns the applet's TypeScript source into one self-contained JavaScript script, with the prelude around it. It uses the esbuild Go library for this. Types are stripped, not checked. The applet may not import anything at runtime; type-only imports are removed. It returns an InvalidSourceError if the source is invalid.

Types

type Builder

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

Builder builds applets. It is safe for concurrent use.

func NewBuilder

func NewBuilder(ctx context.Context) (*Builder, error)

NewBuilder creates a new empty builder. When used, it may create temporary directories. Ensure that `Close()` is called when you're done with a Builder so they don't leak.

func (*Builder) Build

func (b *Builder) Build(ctx context.Context, source string, env Env) ([]byte, error)

Build typechecks, bundles and compiles an applet. If the source is invalid, it returns the InvalidSourceError of the step that found out.

The returned module is small: it contains the bytecode, and imports the JavaScript engine from the modules returned by Dependencies. To run it, create a runner.Engine with those dependencies, and load the module into it:

engine, err := runner.NewEngine(ctx, b.Dependencies(), runner.Limits{})
...
applet, err := engine.Load(ctx, wasm)

The bytecode only works with the plugin that compiled it. A module kept for later must therefore run with the Dependencies of the same version of this package.

func (*Builder) Check

func (b *Builder) Check(ctx context.Context, source string, env Env) error

Check type-checks the applet source with tsc. It returns an InvalidSourceError if the source has type errors.

TODO: run tsc with resource limits, so that hostile source can't take infinite time and memory.

func (*Builder) Close

func (b *Builder) Close(ctx context.Context) error

Close releases the builder, and removes the temporary directory with tsc if Check created one. It must not be called while the builder is in use.

func (*Builder) Compile

func (b *Builder) Compile(ctx context.Context, js string) ([]byte, error)

Compile compiles a single Javascript file, as returned by Bundle, to a WebAssembly module that runs it. This, itself, is done within a WASM sandbox (running QuickJS). It returns an InvalidSourceError if the script does not compile.

See Build for usage instructions.

func (*Builder) Dependencies

func (b *Builder) Dependencies() map[string][]byte

Dependencies returns the dependencies of every applet built by this builder. These are used to make them available under the correct name by the runner. Today that is one module: the Javy plugin, which contains the JavaScript engine. The applet modules themselves only contain bytecode, and cannot run without it.

The dependencies are the same for every applet, so pass them once to runner.NewEngine and load all applets into that Engine; see Build.

type Env

type Env struct {
	// Declarations is the content of a .d.ts file with the ambient modules
	// an applet may import types from, e.g. `declare module "invoice" {...}`.
	Declarations string
	// Signature is a type the default export of the applet must be
	// assignable to, e.g. `import("go-applets").Applet<import("invoice").Shipment>`.
	// See runtime.d.ts for the Applet type.
	Signature string
}

Env describes what an applet is checked against.

type InvalidSourceError

type InvalidSourceError struct {
	Step   Step
	Errors []SourceError
}

InvalidSourceError is returned when the applet source is invalid. Step is the step that found out, and Errors are the problems it found, in the order the step reported them.

func (*InvalidSourceError) Error

func (e *InvalidSourceError) Error() string

type SourceError

type SourceError struct {
	// If zero: not on a particular line. Otherwise, this is the 1-indexed line number.
	Line int
	// The 1-indexed column number.
	Column int
	// If the error is a typecheck error, Code contains the tsc error code, e.g. "TS2332".
	Code    string
	Message string
}

SourceError is one problem in the applet source, such as a type error or a syntax error.

func (SourceError) String

func (e SourceError) String() string

String formats the error as "line:column: code: message", leaving out what it does not have.

type Step

type Step int

Step is a step of building an applet.

const (
	StepTypecheck Step = iota + 1 // Builder.Check
	StepBundle                    // Bundle
	StepCompile                   // Builder.Compile
)

Jump to

Keyboard shortcuts

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