modules

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 16 Imported by: 0

README

jsmodule

github.com/OptLTD/library/jsmodule

jsrunner 提供的 JavaScript 内置模块集合,在运行时注入 Web / Node 风格 API(fetch、Buffer、timers 等)。

用途

  • 注册可被 JS import 或全局访问的内置模块(modules.Register
  • 提供模块加载器(CJS / ESM、requireimport()
  • 按需 blank import 子包即可启用对应能力

内置模块

模块 说明
fetch HTTP 请求 / 响应、Headers、Cookie
http/server 轻量 HTTP Server(serve
node:buffer Buffer、Blob、File
node:stream/web ReadableStream 等
node:url URL、URLSearchParams
node:encoding TextEncoder / TextDecoder
base64 Base64 编解码
timers setTimeout、setInterval
signal AbortController / AbortSignal
crypto 摘要与对称加密
cache 内存缓存
dom 简易 DOM 事件
html HTML 解析
ext 扩展工具

快速开始

import (
    js "github.com/OptLTD/library/jsrunner"
    _ "github.com/OptLTD/library/jsmodule/fetch"
    _ "github.com/OptLTD/library/jsmodule/timers"
)

// VM 创建后,JS 中可直接使用 fetch、setTimeout 等
val, err := js.RunString(ctx, `
    const res = await fetch("https://example.com");
    return res.status;
`)

自定义模块可调用 modules.Register 注册,参见 modules.go 中的示例。

完整示例见 example/demo/jsmodule.go

依赖说明

jsrunner 存在循环依赖,本仓库内通过 go.workrequire + replace 联调;发版时需保持两边版本号一致,详见 deploy.md

致谢

本模块源自 shiroyk/ski

测试

cd jsmodule && go test ./...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidModule module is invalid
	ErrInvalidModule = errors.New("invalid module")
	// ErrIllegalModuleName module name is illegal
	ErrIllegalModuleName = errors.New("illegal module name")
	// ErrNotFoundModule not found module
	ErrNotFoundModule = errors.New("cannot found module")
)

Functions

func All

func All() map[string]Module

All get all module

func Register

func Register(name string, mod Module)

Register registers a Module with the given name and implementation. If the module is not a Global module, the name will be prefixed with "ski/". The registered modules can later be imported in JavaScript code by name.

Example:

// Register a regular module that must be imported as "ski/mymodule"
modules.Register("mymodule", new(MyModule))

// Register a global module that can be lazily instantiated
modules.Register("sleep", modules.Global{
	"sleep": modules.ModuleFunc(func(call sobek.FunctionCall, rt *sobek.Runtime) sobek.Value {
		time.Sleep(time.Duration(call.Argument(0).ToInteger()))
		return sobek.Undefined()
	}),
})

func RegisterExact

func RegisterExact(name string, mod Module)

RegisterExact registers under exactly name (no ski/ prefix). For app-specific specifiers e.g. superuser/…

func Remove

func Remove(names ...string)

Remove the modules

Types

type FileLoader

type FileLoader func(specifier *url.URL, name string) ([]byte, error)

FileLoader is a type alias for a function that returns the contents of the referenced file.

func DefaultFileLoader

func DefaultFileLoader(fetch func(*http.Request) (*http.Response, error)) FileLoader

DefaultFileLoader the default file loader. Supports file and HTTP scheme loading.

type Global

type Global map[string]Module

Global represents a collection of related modules grouped under a namespace. It maps module names to their Module implementations. Global modules are instantiated lazily when first accessed through the global object.

func (Global) Instantiate

func (g Global) Instantiate(rt *sobek.Runtime) (sobek.Value, error)

type Loader

type Loader interface {
	// CompileModule compile module from source string (cjs/esm).
	CompileModule(name, source string) (sobek.CyclicModuleRecord, error)
	// ResolveModule resolve the module returns the sobek.ModuleRecord.
	ResolveModule(any, string) (sobek.ModuleRecord, error)
	// EnableRequire enable the global function require to the sobek.Runtime.
	EnableRequire(*sobek.Runtime) Loader
	// EnableImportModuleDynamically sobek runtime SetImportModuleDynamically
	EnableImportModuleDynamically(*sobek.Runtime) Loader
	// EnableImportMeta sobek runtime SetFinalImportMeta
	EnableImportMeta(*sobek.Runtime) Loader
	// InitGlobal instantiates global objects for the runtime. It creates a proxy around the global object
	// to lazily load global modules when they are first accessed.
	//
	// This allows for automatic loading of global modules like fetch, TextEncoder, etc.
	// when they are referenced in code.
	InitGlobal(*sobek.Runtime) Loader
	// SetFileLoader set the FileLoader.
	SetFileLoader(fl FileLoader)
}

Loader the js module loader.

func NewLoader

func NewLoader(opts ...Option) Loader

NewLoader returns a new module resolver if the fileLoader option not provided, uses the default DefaultFileLoader.

type Module

type Module interface {
	Instantiate(*sobek.Runtime) (sobek.Value, error)
}

Module is the interface that must be implemented by JavaScript modules. It defines how a module is instantiated and made available to the JavaScript runtime.

Example implementation:

func init() {
	// register a new module named "process"
	modules.Register("process", new(Process))
}

type Process struct{}

func (Process) Instantiate(rt *sobek.Runtime) (sobek.Value, error) {
	environ := os.Environ()
	env := make(map[string]string, len(environ))
	for _, kv := range environ {
		k, v, _ := strings.Cut(kv, "=")
		env[k] = v
	}
	ret := rt.NewObject()
	_ = ret.Set("env", env)
	return ret, nil
}

func Get

func Get(name string) (Module, bool)

Get the module

type ModuleFunc

type ModuleFunc func(sobek.FunctionCall, *sobek.Runtime) sobek.Value

ModuleFunc type is an adapter to allow the use of ordinary functions as Module.

func (ModuleFunc) Instantiate

func (m ModuleFunc) Instantiate(rt *sobek.Runtime) (sobek.Value, error)

type Option

type Option func(*loader)

Option the new Loader options.

func WithBase

func WithBase(base *url.URL) Option

WithBase the base directory of module loader.

func WithFileLoader

func WithFileLoader(fl FileLoader) Option

WithFileLoader the file loader of module loader.

func WithSourceMapLoader

func WithSourceMapLoader(fn func(path string) ([]byte, error)) Option

WithSourceMapLoader the source map loader of module loader.

Directories

Path Synopsis
Package cache the cache JS implementation
Package cache the cache JS implementation
Package crypto the crypto JS implementation
Package crypto the crypto JS implementation

Jump to

Keyboard shortcuts

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