engine

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: BSD-3-Clause Imports: 34 Imported by: 119

README

Engine

A javascript Engine base on Goja inspired by k6

Limitations and modifications

  • Top level async/await not supported by Goja
  • ES6+ partially implemented by Goja
  • Async operations should wait for ends with engine.StopEventLoopXXX
  • Module includes remote/local/GoModule support by translate to CommonJs (EsBuild)

Sample

no time limit

package main

import (
   "github.com/ZenLiuCN/engine"
)
func main() {
   vm := engine.Get()
   defer vm.Free()
   v, err := vm.RunJs(
      `
console.log("Begin "+"For timeout")
new Promise((r, j) => {
    console.log("job 0")
    setTimeout(()=>r(1),1000)
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
        setTimeout(()=>r(v+1),1000)
    })}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
        setTimeout(()=>r(v+1),1000)
    })
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
       setTimeout(()=>r(v+1),2000)
    })
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
       setTimeout(()=>r(v+1),2000)
    })
})`)
   halts := vm.Await() //manual await task done
   if !halts.IsZero(){
	   panic("task not done")
   }
   if err!=nil{
      panic(err)
   }
   println(v)
}
manual
package main

import (
   "github.com/ZenLiuCN/engine"
   "time"
)
func main() {
   vm := engine.Get()
   defer vm.Free()
   v, err := vm.RunJs(
      `
console.log("Begin "+"For timeout")
new Promise((r, j) => {
    console.log("job 0")
    setTimeout(()=>r(1),1000)
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
        setTimeout(()=>r(v+1),1000)
    })}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
        setTimeout(()=>r(v+1),1000)
    })
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
       setTimeout(()=>r(v+1),2000)
    })
}).then(v => {
    console.log("job",v)
    return new Promise((r, j) => {
       setTimeout(()=>r(v+1),2000)
    })
})`)
   halts := vm.AwaitTimeout(time.Second * 5) //manual await task done for limited time
   if !halts.IsZero(){
	   panic("task not done within 5 seconds")
   }
   if err!=nil{
      panic(err)
   }
   println(v)
}

automatic
package main

import (
	"github.com/ZenLiuCN/engine"
	"time"
)

func main() {
	vm := engine.Get()
	defer vm.Free()
	v, err := vm.RunJsTimeout(`import {Second, sleep} from 'go/time'

new Promise((r, j) => {
    sleep(Second)
    r(1)
}).then(v => {
    console.log(v)
    return new Promise((r, j) => {
        sleep(Second)
        r(v+1)
    })
}).then(v => {
    console.log(v)
    return new Promise((r, j) => {
        sleep(Second)
        r(v+1)
    })
}).then(v => {
    console.log(v)
    return new Promise((r, j) => {
        sleep(Second*2)
        r(v+1)
    })
}).then(v => {
    console.log(v)
    return new Promise((r, j) => {
        sleep(Second*2)
        r(v+1)
    })
})
`, time.Second*8)
	if err != nil {
		panic(err) // if error is ErrTimeout, the value is HaltJobs
	}
	println(v)
}

Extensions

Engine

Simple wrapper for goja.Runtime with extended abilities.

Code

Simple wrapper for goja.Program

Naming
  1. use struct tag js:"name" to mapping fields to js property
  2. use struct tag js:"-" to ignore export field
  3. default strategy for both functions methods and fields
    • UUUlllUll => uuUllUll
    • UlllUll => ullUll
    • XlllUll => llUll
    • XUllUll => UllUll
Resolver with require

Simple support for CommonJs, ES script and TypeScript also compiled as CJS script, inspire by k6

Module System
  1. Module: a simple global instance
  2. InitializeModule: a module instanced when register to an Engine
  3. TopModule: a module register some top level function or objects
  4. TypeDefined: a module contains d.ts data
  5. GoModule: a module for expose golang into js (use by import module)
compiler module
  • go/compiler built-in compiler for both typescript and javascript
  • go/esbuild expose esbuild to js

components

engine module
  • go/engine: use engine in scripts, maybe not to use too many russian dolls
console module
  • global : slog console or byte buffer console
buffer module
  • go/buffer: golang byte slice and bytes.Buffer
hash module
  • go/hash:golang hash functions
  • go/codec:golang codec functions, include base64 ...
crypto module
  • go/crypto : golang crypto
os module
  • go/os : golang os , not full functions
io module
  • go/io : golang io module
chan module
  • go/chan : golang chan type only

Modules

pluggable modules

sqlx
  • go/sqlx: sqlx with pgx mysql and sqlite driver

components

Excelize
  • go/excel: excel reading or generate

components

fetch
  • go/fetch: base function done, improve for compact with browser fetch.
pug
  • go/pug: jade(pug) compiler

components

minify
  • go/minify: file minify

components

pdf

dev

jose

draft

http

draft

Documentation

Index

Constants

View Source
const ModuleRequireConstKey = "_$require"

Variables

View Source
var (
	TextEncoder = &EsTextEncoder{"utf-8"}
	TextDecoder = &EsTextDecoder{"utf-8"}
)
View Source
var (
	TypeRegistry map[TypeId]TypeInfo
	TypeAlias    map[TypeId]TypeId
)
View Source
var (
	ColumnMarker = "♦"
)
View Source
var (
	DumpFrameLastN = 5
)
View Source
var (
	Encoding encoding.Encoding
)
View Source
var (
	ErrDisabled = errors.New("required module is disabled")
)
View Source
var (
	ErrTimeout = errors.New("execution timeout")
)

Functions

func BuildCommand

func BuildCommand(opt *ProcOption) (cmd *exec.Cmd, err error)

func Chdir

func Chdir(path string) error

func CompileFileSourceWithMapping

func CompileFileSourceWithMapping(path, source string, ts, entry bool) (*Code, SourceMapping)

func CompileFileWithMapping

func CompileFileWithMapping(path string, entry bool) (*Code, SourceMapping)

func CompileJs

func CompileJs(js string, entry bool) string

func CompileSourceWithMapping

func CompileSourceWithMapping(name, source string, ts, entry bool) (*Code, SourceMapping)

func CompileTs

func CompileTs(ts string, entry bool) string
func CreateSymlink(src, dest string) error

func DumpDefines

func DumpDefines(path string)

DumpDefines to path, global.d.ts contains top level types , pkg/name.d.ts contains go modules

func Empty

func Empty[T any]() (v T)

func EmptyRefer

func EmptyRefer[T any]() *T

func EnvAppend

func EnvAppend(key string, value ...string) error

func EnvAppendPath

func EnvAppendPath(key string, value ...string) error

func EnvExpand

func EnvExpand(path string) string

func EnvPrepend

func EnvPrepend(key string, value ...string) error

func EnvPrependPath

func EnvPrependPath(key string, value ...string) error

func EnvPut

func EnvPut(key string, value ...string) error

func EnvPutPath

func EnvPutPath(key string, value ...string)

func EnvSet

func EnvSet(key string, value ...string) error

func EnvSetPath

func EnvSetPath(key string, value ...string) error

func EnvVar

func EnvVar(key string) string

func EvalFile

func EvalFile(e *Engine, path string) any

func EvalFiles

func EvalFiles(e *Engine, paths ...string) (r []any)

func Execute

func Execute(opt *ExecOption) (err error)

func FieldName

func FieldName(_ reflect.Type, f reflect.StructField) string

func FileCopy

func FileCopy(src, dest string, force *bool) error

func FileExists

func FileExists(path string) bool

func FileMove

func FileMove(src, dest string, force *bool) error

func FromNativeConsole

func FromNativeConsole(b *bytes.Buffer) error

func GetBytesBuffer

func GetBytesBuffer() *bytes.Buffer

func GetExecPath

func GetExecPath() string

func GetExecutable

func GetExecutable() string

func GetExt

func GetExt() string

func GetName

func GetName() string

func GetPathListSeparator

func GetPathListSeparator() string

func GetPathSeparator

func GetPathSeparator() string

func GetRoot

func GetRoot() string

func IsAsyncFunction

func IsAsyncFunction(rt *goja.Runtime, val goja.Value) bool

func IsDir

func IsDir(path string) bool

func IsFile

func IsFile(path string) bool

func IsNullish

func IsNullish(v goja.Value) bool
func IsSymlink(path string) bool

func Locate

func Locate(pth string) (string, error)

func Lookup

func Lookup(cmd string) (p string, err error)

func MethodName

func MethodName(_ reflect.Type, m reflect.Method) string

MethodName Returns the JS name for an exported method.

func Mkdir

func Mkdir(path string)

func MkdirAll

func MkdirAll(path string)

func ModDefines

func ModDefines() []byte

ModDefines dump all possible type define (d.ts format) in registry

func ModuleDefines

func ModuleDefines() map[string][]byte

ModuleDefines exports Module define as moduleName=>ModuleTypeDefine

func ModuleNames

func ModuleNames() []string

func NoWindow

func NoWindow(cmd *exec.Cmd) *exec.Cmd

func PathToUrl

func PathToUrl(path string) *url.URL

func Put

func Put(e *Engine)

func PutBytesBuffer

func PutBytesBuffer(buf *bytes.Buffer)

func Pwd

func Pwd() (string, error)

func ReadBinaryFile

func ReadBinaryFile(path string) []byte
func ReadSymlink(path string) (string, error)

func ReadTextFile

func ReadTextFile(path string) string

func Reader

func Reader[V any, K any](fieldIndex int) func(*V) K

func ReferOf

func ReferOf[T any](v T, x *T)

func RegisterMod

func RegisterMod(module Mod) bool

RegisterMod a default global module , returns false if already exists

func RegisterModule

func RegisterModule(module Module) bool

RegisterModule as import able module

func RegisterResource

func RegisterResource[T io.Closer](e *Engine, v T) T

func RegisterType

func RegisterType[T any]() bool

func RegisterTypeAlias

func RegisterTypeAlias(src any, target any)

func RemoveMod

func RemoveMod(mod string)

RemoveMod preloaded module

func RemoveModule

func RemoveModule(module string)

func RemoveResource

func RemoveResource[T io.Closer](e *Engine, v T) T

func Stat

func Stat(path string) map[string]any

func Throw

func Throw(rt *goja.Runtime, err error)

func ToBytes

func ToBytes(data any) ([]byte, error)

func ToNativeConsole

func ToNativeConsole(b *bytes.Buffer) error

func ToString

func ToString(data any) (string, error)

func Transform01

func Transform01[B0, C any](f func() B0, t func(B0) C) func() C

func Transform02

func Transform02[B0, B1, C any](f func() (B0, B1), t func(B0, B1) C) func() C

func Transform03

func Transform03[B0, B1, B2, C any](f func() (B0, B1, B2), t func(B0, B1, B2) C) func() C

func Transform04

func Transform04[B0, B1, B2, B3, C any](f func() (B0, B1, B2, B3), t func(B0, B1, B2, B3) C) func() C

func Transform11

func Transform11[A0, B0, C any](f func(A0) B0, t func(B0) C) func(A0) C

func Transform12

func Transform12[A0, B0, B1, C any](f func(A0) (B0, B1), t func(B0, B1) C) func(A0) C

func Transform13

func Transform13[A0, B0, B1, B2, C any](f func(A0) (B0, B1, B2), t func(B0, B1, B2) C) func(A0) C

func Transform14

func Transform14[A0, B0, B1, B2, B3, C any](f func(A0) (B0, B1, B2, B3), t func(B0, B1, B2, B3) C) func(A0) C

func Transform21

func Transform21[A0, A1, B0, C any](f func(A0, A1) B0, t func(B0) C) func(A0, A1) C

func Transform22

func Transform22[A0, A1, B0, B1, C any](f func(A0, A1) (B0, B1), t func(B0, B1) C) func(A0, A1) C

func Transform23

func Transform23[A0, A1, B0, B1, B2, C any](f func(A0, A1) (B0, B1, B2), t func(B0, B1, B2) C) func(A0, A1) C

func Transform24

func Transform24[A0, A1, B0, B1, B2, B3, C any](f func(A0, A1) (B0, B1, B2, B3), t func(B0, B1, B2, B3) C) func(A0, A1) C

func Transform31

func Transform31[A0, A1, A2, B0, C any](f func(A0, A1, A2) B0, t func(B0) C) func(A0, A1, A2) C

func Transform32

func Transform32[A0, A1, A2, B0, B1, C any](f func(A0, A1, A2) (B0, B1), t func(B0, B1) C) func(A0, A1, A2) C

func Transform33

func Transform33[A0, A1, A2, B0, B1, B2, C any](f func(A0, A1, A2) (B0, B1, B2), t func(B0, B1, B2) C) func(A0, A1, A2) C

func Transform34

func Transform34[A0, A1, A2, B0, B1, B2, B3, C any](f func(A0, A1, A2) (B0, B1, B2, B3), t func(B0, B1, B2, B3) C) func(A0, A1, A2) C

func Transform41

func Transform41[A0, A1, A2, A3, B0, C any](f func(A0, A1, A2, A3) B0, t func(B0) C) func(A0, A1, A2, A3) C

func Transform42

func Transform42[A0, A1, A2, A3, B0, B1, C any](f func(A0, A1, A2, A3) (B0, B1), t func(B0, B1) C) func(A0, A1, A2, A3) C

func Transform43

func Transform43[A0, A1, A2, A3, B0, B1, B2, C any](f func(A0, A1, A2, A3) (B0, B1, B2), t func(B0, B1, B2) C) func(A0, A1, A2, A3) C

func Transform44

func Transform44[A0, A1, A2, A3, B0, B1, B2, B3, C any](f func(A0, A1, A2, A3) (B0, B1, B2, B3), t func(B0, B1, B2, B3) C) func(A0, A1, A2, A3) C

func TransformErr01

func TransformErr01[B0, C any](f func() (B0, error), t func(B0, error) (C, error)) func() (C, error)

func TransformErr02

func TransformErr02[B0, B1, C any](f func() (B0, B1, error), t func(B0, B1, error) (C, error)) func() (C, error)

func TransformErr03

func TransformErr03[B0, B1, B2, C any](f func() (B0, B1, B2, error), t func(B0, B1, B2, error) (C, error)) func() (C, error)

func TransformErr04

func TransformErr04[B0, B1, B2, B3, C any](f func() (B0, B1, B2, B3, error), t func(B0, B1, B2, B3, error) (C, error)) func() (C, error)

func TransformErr11

func TransformErr11[A0, B0, C any](f func(A0) (B0, error), t func(B0, error) (C, error)) func(A0) (C, error)

func TransformErr12

func TransformErr12[A0, B0, B1, C any](f func(A0) (B0, B1, error), t func(B0, B1, error) (C, error)) func(A0) (C, error)

func TransformErr13

func TransformErr13[A0, B0, B1, B2, C any](f func(A0) (B0, B1, B2, error), t func(B0, B1, B2, error) (C, error)) func(A0) (C, error)

func TransformErr14

func TransformErr14[A0, B0, B1, B2, B3, C any](f func(A0) (B0, B1, B2, B3, error), t func(B0, B1, B2, B3, error) (C, error)) func(A0) (C, error)

func TransformErr21

func TransformErr21[A0, A1, B0, C any](f func(A0, A1) (B0, error), t func(B0, error) (C, error)) func(A0, A1) (C, error)

func TransformErr22

func TransformErr22[A0, A1, B0, B1, C any](f func(A0, A1) (B0, B1, error), t func(B0, B1, error) (C, error)) func(A0, A1) (C, error)

func TransformErr23

func TransformErr23[A0, A1, B0, B1, B2, C any](f func(A0, A1) (B0, B1, B2, error), t func(B0, B1, B2, error) (C, error)) func(A0, A1) (C, error)

func TransformErr24

func TransformErr24[A0, A1, B0, B1, B2, B3, C any](f func(A0, A1) (B0, B1, B2, B3, error), t func(B0, B1, B2, B3, error) (C, error)) func(A0, A1) (C, error)

func TransformErr31

func TransformErr31[A0, A1, A2, B0, C any](f func(A0, A1, A2) (B0, error), t func(B0, error) (C, error)) func(A0, A1, A2) (C, error)

func TransformErr32

func TransformErr32[A0, A1, A2, B0, B1, C any](f func(A0, A1, A2) (B0, B1, error), t func(B0, B1, error) (C, error)) func(A0, A1, A2) (C, error)

func TransformErr33

func TransformErr33[A0, A1, A2, B0, B1, B2, C any](f func(A0, A1, A2) (B0, B1, B2, error), t func(B0, B1, B2, error) (C, error)) func(A0, A1, A2) (C, error)

func TransformErr34

func TransformErr34[A0, A1, A2, B0, B1, B2, B3, C any](f func(A0, A1, A2) (B0, B1, B2, B3, error), t func(B0, B1, B2, B3, error) (C, error)) func(A0, A1, A2) (C, error)

func TransformErr41

func TransformErr41[A0, A1, A2, A3, B0, C any](f func(A0, A1, A2, A3) (B0, error), t func(B0, error) (C, error)) func(A0, A1, A2, A3) (C, error)

func TransformErr42

func TransformErr42[A0, A1, A2, A3, B0, B1, C any](f func(A0, A1, A2, A3) (B0, B1, error), t func(B0, B1, error) (C, error)) func(A0, A1, A2, A3) (C, error)

func TransformErr43

func TransformErr43[A0, A1, A2, A3, B0, B1, B2, C any](f func(A0, A1, A2, A3) (B0, B1, B2, error), t func(B0, B1, B2, error) (C, error)) func(A0, A1, A2, A3) (C, error)

func TransformErr44

func TransformErr44[A0, A1, A2, A3, B0, B1, B2, B3, C any](f func(A0, A1, A2, A3) (B0, B1, B2, B3, error), t func(B0, B1, B2, B3, error) (C, error)) func(A0, A1, A2, A3) (C, error)

func UnRefer

func UnRefer[T any](v *T) T

func ValueString

func ValueString(v goja.Value) string

func ValuesString

func ValuesString(args ...goja.Value) string

func WdToUrl

func WdToUrl() *url.URL

func WriteBinaryFile

func WriteBinaryFile(path string, data []byte)

func WriteTextFile

func WriteTextFile(path string, data string)

Types

type AsyncContext

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

func (*AsyncContext) String

func (s *AsyncContext) String() string

type AsyncTracker

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

func (*AsyncTracker) Exited

func (s *AsyncTracker) Exited()

func (*AsyncTracker) Grab

func (s *AsyncTracker) Grab() (trackingObject any)

func (*AsyncTracker) Resumed

func (s *AsyncTracker) Resumed(trackingObject any)

type BaseInitializeModule

type BaseInitializeModule struct {
}

func (*BaseInitializeModule) Exports

func (s *BaseInitializeModule) Exports() map[string]any

type BaseModResolver

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

func (*BaseModResolver) Resolve

func (s *BaseModResolver) Resolve(basePWD *url.URL, arg string, debug bool) (JsModule, error)

type BaseResolver

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

func (*BaseResolver) Dir

func (s *BaseResolver) Dir(old *url.URL) *url.URL

func (*BaseResolver) Fetch

func (s *BaseResolver) Fetch(u *url.URL) (*Source, error)

func (*BaseResolver) Load

func (s *BaseResolver) Load(specifier *url.URL, originalModuleSpecifier string) (*Source, error)

func (*BaseResolver) LoadFile

func (s *BaseResolver) LoadFile(u *url.URL) (*Source, error)

func (*BaseResolver) Resolve

func (s *BaseResolver) Resolve(pwd *url.URL, specifier string) (*url.URL, error)

func (*BaseResolver) ResolveFilePath

func (s *BaseResolver) ResolveFilePath(pwd *url.URL, moduleSpecifier string) (*url.URL, error)

type BufferConsole

type BufferConsole struct {
	*bytes.Buffer
	// contains filtered or unexported fields
}

func NewBufferConsole

func NewBufferConsole() *BufferConsole

func NewBufferConsoleOf

func NewBufferConsoleOf(buf *bytes.Buffer) *BufferConsole

func (*BufferConsole) Assert

func (s *BufferConsole) Assert(cond bool, args ...goja.Value)

func (*BufferConsole) Clear

func (s *BufferConsole) Clear()

func (BufferConsole) Count

func (s BufferConsole) Count(label string)

func (BufferConsole) CountReset

func (s BufferConsole) CountReset(label string)

func (*BufferConsole) Debug

func (s *BufferConsole) Debug(args ...goja.Value)

func (BufferConsole) Dir

func (s BufferConsole) Dir(v goja.Value)

func (*BufferConsole) Error

func (s *BufferConsole) Error(args ...goja.Value)

func (BufferConsole) Group

func (s BufferConsole) Group(label string)

func (BufferConsole) GroupCollapsed

func (s BufferConsole) GroupCollapsed(label string)

func (BufferConsole) GroupEnd

func (s BufferConsole) GroupEnd()

func (*BufferConsole) Info

func (s *BufferConsole) Info(args ...goja.Value)

func (*BufferConsole) Log

func (s *BufferConsole) Log(args ...goja.Value)

func (*BufferConsole) Name

func (s *BufferConsole) Name() string

func (*BufferConsole) Print

func (s *BufferConsole) Print(v ...any)

func (BufferConsole) Table

func (s BufferConsole) Table(value goja.Value, columns []string)

func (BufferConsole) Time

func (s BufferConsole) Time(label string)

func (BufferConsole) TimeEnd

func (s BufferConsole) TimeEnd(label string)

func (BufferConsole) TimeLog

func (s BufferConsole) TimeLog(label string, val ...goja.Value)

func (*BufferConsole) Trace

func (s *BufferConsole) Trace(args ...goja.Value)

func (*BufferConsole) Warn

func (s *BufferConsole) Warn(args ...goja.Value)

type CacheSource

type CacheSource struct {
	Src *Source
	Err error
}

type Chan

type Chan[T any] interface {
	Recv(func(T)) *goja.Promise
	Send(v T)
	Closed() bool
	Close()
}

func NewChan

func NewChan[T any](ch chan T, e *Engine) Chan[T]

type Code

type Code struct {
	Path string
	*goja.Program
}

func CompileFile

func CompileFile(path string, entry bool) *Code

CompileFile entry for whether source is as script or library

func CompileFileSource

func CompileFileSource(path, source string, ts, entry bool) *Code

func CompileSource

func CompileSource(source string, ts, entry bool) *Code

CompileSource compile script source, ts for source is typescript or javascript. entry for whether source is as script or library

type Compiler

type Compiler struct {
}

func (Compiler) Exports

func (s Compiler) Exports() map[string]any

func (Compiler) Identity

func (s Compiler) Identity() string

func (Compiler) TypeDefine

func (s Compiler) TypeDefine() []byte

type Console

type Console struct {
	*slog.Logger
	// contains filtered or unexported fields
}

func NewConsole

func NewConsole(logger *slog.Logger) *Console

func (*Console) Assert

func (s *Console) Assert(cond bool, args ...goja.Value)

func (*Console) Clear

func (s *Console) Clear()

func (Console) Count

func (s Console) Count(label string)

func (Console) CountReset

func (s Console) CountReset(label string)

func (*Console) Debug

func (s *Console) Debug(args ...goja.Value)

func (Console) Dir

func (s Console) Dir(v goja.Value)

func (*Console) Error

func (s *Console) Error(args ...goja.Value)

func (Console) Group

func (s Console) Group(label string)

func (Console) GroupCollapsed

func (s Console) GroupCollapsed(label string)

func (Console) GroupEnd

func (s Console) GroupEnd()

func (*Console) Info

func (s *Console) Info(args ...goja.Value)

func (*Console) Log

func (s *Console) Log(args ...goja.Value)

func (*Console) Name

func (s *Console) Name() string

func (*Console) Print

func (s *Console) Print(v ...any)

func (Console) Table

func (s Console) Table(value goja.Value, columns []string)

func (Console) Time

func (s Console) Time(label string)

func (Console) TimeEnd

func (s Console) TimeEnd(label string)

func (Console) TimeLog

func (s Console) TimeLog(label string, val ...goja.Value)

func (*Console) Trace

func (s *Console) Trace(args ...goja.Value)

func (*Console) Warn

func (s *Console) Warn(args ...goja.Value)

type Context

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

func (*Context) Cancel

func (c *Context) Cancel()

func (*Context) Dispose

func (c *Context) Dispose()

func (*Context) Rebuild

func (c *Context) Rebuild() api.BuildResult

func (*Context) Serve

func (c *Context) Serve(options api.ServeOptions) (api.ServeResult, error)

func (*Context) Watch

func (c *Context) Watch(options api.WatchOptions) error

type ContextResult

type ContextResult struct {
	Context *Context
	Err     *api.ContextError
}

type Engine

type Engine struct {
	*Runtime
	*EventLoop
	Resources map[io.Closer]struct{}

	Debug     bool
	SourceMap SourceMapping
	// contains filtered or unexported fields
}

func Get

func Get() *Engine

func NewEngine

func NewEngine(modules ...Mod) (r *Engine)

func NewRawEngine

func NewRawEngine(modules ...Mod) (r *Engine)

func (*Engine) BufferConsole

func (s *Engine) BufferConsole(value *bytes.Buffer)

func (*Engine) CallConstruct

func (s *Engine) CallConstruct(fn Value, values ...any) (*Object, error)

func (*Engine) CallFunction

func (s *Engine) CallFunction(fn Value, values ...any) (v Value, err error)

CallFunction invoke a function (without this)

func (*Engine) CallMethod

func (s *Engine) CallMethod(fn Value, self Value, values ...any) (v Value, err error)

CallMethod invoke a method (with this)

func (*Engine) Callable

func (s *Engine) Callable(fn Value) Callable

func (*Engine) Compile

func (s *Engine) Compile(src string, ts, entry bool) *Code

func (*Engine) DisableModules

func (s *Engine) DisableModules(modules ...string) bool

DisableModules disable load modules for current engine, modules are the full import path

func (*Engine) Free

func (s *Engine) Free()

Free recycle this engine

func (*Engine) IsNullish

func (s *Engine) IsNullish(v Value) bool

IsNullish check if value is null or undefined

func (*Engine) LoggerConsole

func (s *Engine) LoggerConsole(value *slog.Logger)

func (*Engine) NaN

func (s *Engine) NaN() Value

func (*Engine) NegInf

func (s *Engine) NegInf() Value

func (*Engine) NewPromise

func (s *Engine) NewPromise() (promise *Promise, resolve func(any), reject func(any))

NewPromise create new Promise, must use StopEventBusAwait

func (*Engine) Null

func (s *Engine) Null() Value

func (*Engine) PosInf

func (s *Engine) PosInf() Value

func (*Engine) Register

func (s *Engine) Register(mods ...Mod)

Register register mods

func (*Engine) RegisterFunction

func (s *Engine) RegisterFunction(name string, ctor func(c FunctionCall) Value)

RegisterFunction create global function

func (*Engine) RegisterResources

func (s *Engine) RegisterResources(r io.Closer)

func (*Engine) RegisterType

func (s *Engine) RegisterType(name string, ctor func(v []Value) (any, error))

RegisterType create global simple type

func (*Engine) RegisterTypeRecover

func (s *Engine) RegisterTypeRecover(name string, ctor func(v []Value) any)

func (*Engine) RemoveResources

func (s *Engine) RemoveResources(r io.Closer)

func (*Engine) RunCode

func (s *Engine) RunCode(code *Code) (v Value, err error)

RunCode execute compiled code. The execution time should control manually, for an automatic timeout control see RunCodeTimeout.

func (*Engine) RunCodeContext

func (s *Engine) RunCodeContext(code *Code, warm time.Duration, ctx cx.Context) (v Value, err error)

RunCodeContext run code with context. If context closed early, the value will be HaltJobs, the error will be ErrTimeout.

func (*Engine) RunCodeWithMapping

func (s *Engine) RunCodeWithMapping(code *Code, mapping SourceMapping) (v Value, err error)

func (*Engine) RunJs

func (s *Engine) RunJs(src string) (v Value, err error)

RunJs execute javascript code. Should manual control the execution, for a automatic timeout control see RunJsTimeout.

func (*Engine) RunJsContext

func (s *Engine) RunJsContext(src string, warm time.Duration, ctx cx.Context) (v Value, err error)

RunJsContext run js source with context. If context closed early, the value will be HaltJobs, the error will be ErrTimeout.

func (*Engine) RunString

func (s *Engine) RunString(src string) (v Value, err error)

RunString execute raw javascript (es5|es6 without import) code. this not support import and some polyfill features.

func (*Engine) RunTs

func (s *Engine) RunTs(src string) (v Value, err error)

RunTs execute typescript code. Should manually control the execution, for a automatic timeout control see RunTsTimeout.

func (*Engine) RunTsContext

func (s *Engine) RunTsContext(src string, warm time.Duration, ctx cx.Context) (v Value, err error)

RunTsContext run Ts source with context. If context closed early, the value will be HaltJobs, the error will be ErrTimeout.

func (*Engine) Set

func (s *Engine) Set(name string, value any)

Set create global value

func (*Engine) SetScriptPath

func (s *Engine) SetScriptPath(p string)

SetScriptPath define current script path to use for imports

func (*Engine) ToConstructor

func (s *Engine) ToConstructor(ct func(v []Value) (any, error)) func(ConstructorCall) *Object

func (*Engine) ToConstructorRecover

func (s *Engine) ToConstructorRecover(ct func(v []Value) any) func(ConstructorCall) *Object

func (*Engine) ToInstance

func (s *Engine) ToInstance(v any, c ConstructorCall) *Object

ToInstance create instance of a value with simple prototype, use for constructor only.

func (*Engine) ToSelfReferConstructor

func (s *Engine) ToSelfReferConstructor(ct func(ctor Value, v []Value) (any, error)) Value

ToSelfReferConstructor create a Constructor which require use itself. see [ Bytes ]

func (*Engine) ToSelfReferRawConstructor

func (s *Engine) ToSelfReferRawConstructor(ct func(ctor Value, call ConstructorCall) *Object) Value

ToSelfReferRawConstructor create a Constructor which require use itself. see [ Bytes ]

func (*Engine) ToValues

func (s *Engine) ToValues(args ...any) []Value

func (*Engine) Undefined

func (s *Engine) Undefined() Value

type EngineFieldMapper

type EngineFieldMapper struct{}

func (EngineFieldMapper) FieldName

func (EngineFieldMapper) MethodName

type EngineModule

type EngineModule struct {
}

func (EngineModule) Exports

func (e EngineModule) Exports() map[string]any

func (EngineModule) ExportsWithEngine

func (e EngineModule) ExportsWithEngine(engine *Engine) map[string]any

func (EngineModule) Identity

func (e EngineModule) Identity() string

func (EngineModule) TypeDefine

func (e EngineModule) TypeDefine() []byte

type EsBuild

type EsBuild struct {
}

func (EsBuild) Exports

func (e EsBuild) Exports() map[string]any

func (EsBuild) Identity

func (e EsBuild) Identity() string

func (EsBuild) TypeDefine

func (e EsBuild) TypeDefine() []byte

type EsTextDecoder

type EsTextDecoder struct {
	Encoding string
}

func (EsTextDecoder) Decode

func (t EsTextDecoder) Decode(v []byte) string

Decode typedArray are impl as bytes in goja

func (EsTextDecoder) EncodeInto

func (t EsTextDecoder) EncodeInto(v string, arr []byte)

type EsTextEncoder

type EsTextEncoder struct {
	Encoding string
}

func (EsTextEncoder) Encode

func (t EsTextEncoder) Encode(v string) []byte

func (EsTextEncoder) EncodeInto

func (t EsTextEncoder) EncodeInto(v string, arr []byte)

type EventLoop

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

EventLoop process all async events and also as The AsyncContextTracker there will be a background goroutine to monitor the async tasks as call StartEventLoop, or call TryStartEventLoop for not sure current EventLoop have been started. use Await to await all async tasks are finished. use AwaitTimeout to waiting for a fixed duration. use StopEventLoopNoWait to immediate shutdown EventLoop without wait tasks execution. use StopEventLoop wait EventLoop after current tasks execution.

func NewEventLoop

func NewEventLoop(engine *Engine) *EventLoop

func (*EventLoop) Await

func (e *EventLoop) Await() HaltJobs

Await all job done, see also AwaitContext, AwaitTimeout and AwaitWithContext .

func (*EventLoop) AwaitWithContext

func (e *EventLoop) AwaitWithContext(ctx context.Context) HaltJobs

AwaitWithContext stop with context for a cancelable or with deadline context, see also Await, AwaitTimeout and AwaitContext. should use goroutine to execute script to avoid blocking current thread

func (*EventLoop) ClearInterval

func (e *EventLoop) ClearInterval(i *Interval)

func (*EventLoop) ClearTimeout

func (e *EventLoop) ClearTimeout(t *Timer)

func (*EventLoop) RunOnLoop

func (e *EventLoop) RunOnLoop(fn func(*Engine))

RunOnLoop run function on event loop

func (*EventLoop) SetInterval

func (e *EventLoop) SetInterval(fn func(engine *Engine), timeout time.Duration) *Interval

func (*EventLoop) SetTimeout

func (e *EventLoop) SetTimeout(fn func(engine *Engine), timeout time.Duration) *Timer

func (*EventLoop) StartEventLoop

func (e *EventLoop) StartEventLoop()

StartEventLoop fail if already started

func (*EventLoop) StopEventLoop

func (e *EventLoop) StopEventLoop() HaltJobs

StopEventLoop wait background execution quit (not all tasks) , returns job not executed

func (*EventLoop) StopEventLoopNoWait

func (e *EventLoop) StopEventLoopNoWait() HaltJobs

StopEventLoopNoWait without wait for background execution finish, the result may not accuracy values

func (*EventLoop) TryStartEventLoop

func (e *EventLoop) TryStartEventLoop()

TryStartEventLoop no effect if already started

type ExecOption

type ExecOption struct {
	Sleep    time.Duration
	Optional bool
	Await    bool
	*ProcOption
}

type GoChan

type GoChan[T any] struct {
	// contains filtered or unexported fields
}

func (*GoChan[T]) AsRecvOnly

func (g *GoChan[T]) AsRecvOnly() GoRecvChan[T]

func (*GoChan[T]) AsSendOnly

func (g *GoChan[T]) AsSendOnly() GoSendChan[T]

func (*GoChan[T]) Close

func (g *GoChan[T]) Close()

func (*GoChan[T]) Raw

func (g *GoChan[T]) Raw() chan T

func (*GoChan[T]) Recv

func (g *GoChan[T]) Recv(f func(T)) *goja.Promise

func (*GoChan[T]) Stop

func (g *GoChan[T]) Stop() bool

type GoModule

type GoModule struct {
}

func (GoModule) Exports

func (c GoModule) Exports() map[string]any

func (GoModule) ExportsWithEngine

func (c GoModule) ExportsWithEngine(e *Engine) map[string]any

func (GoModule) Identity

func (c GoModule) Identity() string

func (GoModule) TypeDefine

func (c GoModule) TypeDefine() []byte

type GoRecvChan

type GoRecvChan[T any] struct {
	// contains filtered or unexported fields
}

func (*GoRecvChan[T]) Raw

func (g *GoRecvChan[T]) Raw() <-chan T

func (*GoRecvChan[T]) Recv

func (g *GoRecvChan[T]) Recv(f func(T)) *goja.Promise

func (*GoRecvChan[T]) Stop

func (g *GoRecvChan[T]) Stop() bool

type GoSendChan

type GoSendChan[T any] struct {
	// contains filtered or unexported fields
}

func (*GoSendChan[T]) Close

func (g *GoSendChan[T]) Close()

func (*GoSendChan[T]) Raw

func (g *GoSendChan[T]) Raw() chan<- T

func (*GoSendChan[T]) Send

func (g *GoSendChan[T]) Send(v T)

type HaltJobs

type HaltJobs struct {
	Job       int // Job remains after execution, include async task
	AsyncTask int // AsyncTask remains after execution
}

func (HaltJobs) IsZero

func (s HaltJobs) IsZero() bool

IsZero dose all job are done

func (HaltJobs) RealJob

func (s HaltJobs) RealJob() int

RealJob real job in queue

func (HaltJobs) String

func (s HaltJobs) String() string

type Immediate

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

type InitializeMod

type InitializeMod interface {
	Mod
	Initialize(e *Engine) Mod // create copy of module with new Engine
}

type InitializeModule

type InitializeModule interface {
	Module
	ExportsWithEngine(eng *Engine) map[string]any
}

Module support for import by require, not a global instance as Module

type Interval

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

type JsModule

type JsModule interface {
	Instance(engine *Engine) JsModuleInstance
}

func CompileCJS

func CompileCJS(data *Source, debug bool) (m JsModule, err error)

type JsModuleInstance

type JsModuleInstance interface {
	Execute() error
	Exports() *goja.Object
}

type Maybe

type Maybe[T any] struct {
	Value T
	Error error
}

func MaybeBoth

func MaybeBoth[T any](v T, e error) Maybe[T]

func MaybeError

func MaybeError[T any](e error) Maybe[T]

func MaybeMap

func MaybeMap[T, R any](v T, e error, f func(T) R) Maybe[R]

func MaybeOk

func MaybeOk[T any](v T) Maybe[T]

func (Maybe[T]) Result

func (m Maybe[T]) Result() (T, error)

type Mod

type Mod interface {
	Name() string
}

Mod is a top level objects that not required to import

func Mods

func Mods() []Mod

Mods of global registered

type ModCache

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

type ModResolver

type ModResolver interface {
	Resolve(basePWD *url.URL, arg string, debug bool) (JsModule, error)
}
var (
	ModLoader ModResolver = &BaseModResolver{cache: map[string]ModCache{}}
)

type Module

type Module interface {
	TypeDefined
	Identity() string // Identity the full module identity
	Exports() map[string]any
}

Module support for import by require, not a global instance as Module

type ProcOption

type ProcOption struct {
	Cmd        string
	Args       []string
	WorkingDir string
	ShowWindow bool
	PathPatch  bool
}

type ReadChan

type ReadChan[T any] interface {
	Recv(func(T)) *goja.Promise
	Closed() bool
	Close()
}

func NewChanReadOnly

func NewChanReadOnly[T any](ch <-chan T, e *Engine) ReadChan[T]

type ReflectTypeInfo

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

func (*ReflectTypeInfo) Channel

func (t *ReflectTypeInfo) Channel() any

func (*ReflectTypeInfo) GoChannel

func (t *ReflectTypeInfo) GoChannel() any

func (*ReflectTypeInfo) Id

func (t *ReflectTypeInfo) Id() TypeId

func (*ReflectTypeInfo) Instance

func (t *ReflectTypeInfo) Instance() any

func (*ReflectTypeInfo) Slice

func (t *ReflectTypeInfo) Slice() any

type Require

type Require struct {
	*Engine
	// contains filtered or unexported fields
}

func (*Require) AddDisabled

func (r *Require) AddDisabled(spec ...string)

func (*Require) GetDisabled

func (r *Require) GetDisabled() []string

func (Require) Name

func (r Require) Name() string

func (Require) Register

func (r Require) Register(engine *Engine)

func (*Require) Require

func (r *Require) Require(specifier string) (*goja.Object, error)

type Resolver

type Resolver interface {
	Dir(old *url.URL) *url.URL
	Load(specifier *url.URL, originalModuleSpecifier string) (*Source, error)
	Resolve(pwd *url.URL, specifier string) (*url.URL, error)
}
var (
	GlobalRequiredCache          = make(map[*url.URL]*CacheSource)
	Loader              Resolver = &BaseResolver{cache: GlobalRequiredCache}
)

type ScriptError

type ScriptError struct {
	Err   error
	Stack string
}

func (ScriptError) Error

func (s ScriptError) Error() string

func (ScriptError) Unwrap

func (s ScriptError) Unwrap() error

type Source

type Source struct {
	Data []byte
	Path string
	URL  *url.URL
	// contains filtered or unexported fields
}

func (*Source) ResolvePath

func (s *Source) ResolvePath() (pth string)

type SourceMap

type SourceMap struct {
	File           string   `json:"file"`
	SourceRoot     string   `json:"sourceRoot"`
	Sources        []string `json:"sources"`
	SourcesContent []string `json:"sourcesContent"`
	// contains filtered or unexported fields
}

func (*SourceMap) Code

func (s *SourceMap) Code(src string, line, col int) string

type SourceMapping

type SourceMapping map[string]*SourceMap

func CompileJsWithMapping

func CompileJsWithMapping(name, js string, entry bool) (string, SourceMapping, []byte)

func CompileTsWithMapping

func CompileTsWithMapping(name, ts string, entry bool) (string, SourceMapping, []byte)

func NewSourceMap

func NewSourceMap(bin []byte) (v SourceMapping)

type SubProcess

type SubProcess struct {
	*exec.Cmd
}

func OpenProc

func OpenProc(opt *ProcOption) (proc *SubProcess, err error)

type Text

type Text string

func (Text) Bytes

func (t Text) Bytes() []byte

func (Text) Runes

func (t Text) Runes() []rune

func (Text) String

func (t Text) String() string

func (Text) ToString

func (t Text) ToString() string

type TextEncoders

type TextEncoders struct {
}

func (TextEncoders) Name

func (t TextEncoders) Name() string

func (TextEncoders) Register

func (t TextEncoders) Register(e *Engine)

type Timer

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

type TopMod

type TopMod interface {
	Mod
	Register(e *Engine)
}

type TypeDefined

type TypeDefined interface {
	TypeDefine() []byte
}

TypeDefined the element with typescript defines

type TypeId

type TypeId [1]reflect.Type

func ChanOf

func ChanOf(dir reflect.ChanDir, x TypeId) (v TypeId)

func ElementOf

func ElementOf(x TypeId) TypeId

func MapOf

func MapOf(k, v TypeId) (r TypeId)

func SliceOf

func SliceOf(x TypeId) (v TypeId)

func TypeOf

func TypeOf(v any) (x TypeId)

func (TypeId) Identity

func (t TypeId) Identity() string

func (TypeId) Kind

func (t TypeId) Kind() reflect.Kind

func (TypeId) String

func (t TypeId) String() string

func (TypeId) Valid

func (t TypeId) Valid() bool

type TypeInfo

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

func (TypeInfo) Channel

func (t TypeInfo) Channel() any

func (TypeInfo) GoChannel

func (t TypeInfo) GoChannel() any

func (TypeInfo) Id

func (t TypeInfo) Id() TypeId

func (TypeInfo) Instance

func (t TypeInfo) Instance() any

func (TypeInfo) Slice

func (t TypeInfo) Slice() any

type TypeUse

type TypeUse interface {
	Id() TypeId
	Slice() any
	Instance() any
	Channel() any
}

type TypeUtil

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

func (*TypeUtil) UsageOf

func (s *TypeUtil) UsageOf(t TypeId) TypeUse

type WriteChan

type WriteChan[T any] interface {
	Send(v T)
	Closed() bool
	Close()
}

func NewChanWriteOnly

func NewChanWriteOnly[T any](ch chan<- T) WriteChan[T]

Directories

Path Synopsis
modules
units

Jump to

Keyboard shortcuts

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