ski

package module
v0.0.0-...-659b40f Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 10 Imported by: 1

README

ski

GitHub go.mod Go version Go Report Card GitHub
ski is a JavaScript runtime environment for Go powered by Goja.

Description

ski provides a collection of built-in modules that implement partial Node.js compatibility and Web APIs, allowing you to write JavaScript code that can seamlessly interact with Go.

The modules include essential functionality like Buffer manipulation, encoding/decoding, HTTP client (fetch), streams, timers, and URL handling.

Modules

Partial Node.js compatibility and web standard implementations.

buffer

buffer module implements.

  • Buffer
  • Blob
  • File
export default async function () {
  console.log(Buffer.from("Y2lhbGxv", "base64").toString());
  const blob = new Blob(["hello world"], { type: "text/plain" });
  console.log(await blob.text());
}
encoding

encoding module provides base64 decode/encode and TextDecoder/TextEncoder.

  • base64
  • TextDecoder
  • TextEncoder
export default function () {
  const encoder = new TextEncoder();
  const data = encoder.encode("hello");
  console.log(Array.from(new Uint8Array(data)));
}
fetch

fetch module provides HTTP client functionality. Web API implementations:

  • fetch
  • FormData
  • Headers
  • Request
  • Response
  • AbortController
  • AbortSignal

Other:

  • cookieJar
export default async () => {
  const res = await fetch("http://example.com", {
    headers: {
      "X-Custom": "custom value"
    }
  });
  console.log(await response.text());
}
stream

stream module implements.

  • ReadableStream
export default async () => {
  const res = new Response("test");
  const reader = await res.body.getReader();
  // ...
}
timers

timers module provides JavaScript timer functions.

export default async () => {
  return await new Promise((resolve) => {
    let count = 0;
    const id = setInterval(() => {
      count++;
    }, 100);

    setTimeout(() => {
      clearInterval(id);
      resolve(count);
    }, 250);
  });
}
url

url module implements WHATWG URL Standard.

  • URL
  • URLSearchParams
export default async () => {
  console.log(new URL('http://example.com'));
}
http

http/server module provides an HTTP server implementation that follows the Fetch API standard.

It allows you to create HTTP servers that can handle requests and send responses using the familiar Request and Response objects.

import serve from "ski/http/server";

serve(async (req) => {
  console.log("Method:", req.method);

  const url = new URL(req.url);
  console.log("Path:", url.pathname);
  console.log("Query parameters:", url.searchParams);

  console.log("Headers:", req.headers);

  if (req.method === "POST") {
    const body = await req.text();
    console.log("Body:", body);
  }

  return new Response("Hello, World!");
});
cache

cache module provides for store string or bytes.

import cache from "ski/cache";

export default function () {
  cache.set("hello", "world");
}
crypto

crypto module provides cryptographic functionality including hashing and encryption/decryption.

Supported algorithms:

  • aes
  • des
  • md5
  • hmac
  • ripemd160
  • tripleDes
  • sha1
  • sha256
  • sha384
  • sha512
  • sha512_224
  • sha512_256
import crypto from "ski/crypto";

export default function () {
  return crypto.md5('hello').hex();
}

Example

Vue.js Server side rendering.
See more examples in examples.

package main

import (
	"context"

	"github.com/shiroyk/ski"
	"github.com/shiroyk/ski/js"
	_ "github.com/shiroyk/ski/modules/http"
)

const app = `
const app = createSSRApp({
	data: () => ({ count: 1 }),
	render() {
		return h('h1', { onClick: () => this.count++ }, "Count: " + this.count) 
	}
});
`

const index = `<!DOCTYPE html>
<html>
  <head>
	<title>Vue SSR Example</title>
	<style>
	#app {
	  display: flex; align-items: center; justify-content: center; 
	}
	</style>
	<script type="importmap">
	  {"imports":{"vue":"https://esm.sh/vue@3"}}
	</script>
	<script type="module">
		import { h, createSSRApp } from 'vue';
		` + app + `
		app.mount('#app');
	</script>
  </head>
  <body>
	<div id="app">${html}</div>
  </body>
</html>`

func main() {
	module, err := js.CompileModule(`module`, `
	import { h, createSSRApp } from "https://esm.sh/vue@3";
	import { renderToString } from "https://esm.sh/@vue/server-renderer@3";
	import serve from "ski/http/server";

        serve(8000, async (req) => {
		`+app+`
		const html = await renderToString(app);
		return new Response(`+"`"+index+"`"+`);
	});
    	`)
	if err != nil {
		panic(err)
	}

	_, err = ski.RunModule(context.Background(), module)
	if err != nil {
		panic(err)
	}
}

License

ski is distributed under the MIT license.

Documentation

Index

Constants

View Source
const (
	// DefaultTimeoutGetVM default get js.VM timeout
	DefaultTimeoutGetVM = 500 * time.Millisecond
	// DefaultMaxRetriesGetVM default retries times
	DefaultMaxRetriesGetVM = 3
)

Variables

View Source
var (

	// ErrSchedulerClosed the scheduler was closed error
	ErrSchedulerClosed = errors.New("scheduler was closed")
)

Functions

func Run

func Run(ctx context.Context, fn func(*sobek.Runtime) error) error

Run executes the given function

example:

err := ski.Run(context.Background(), func(rt *sobek.Runtime) error {
	_, err := rt.RunString(`console.log('hello world')`)
	return err
})
if err != nil {
	panic(err)
}

func RunModule

func RunModule(ctx context.Context, module sobek.CyclicModuleRecord, args ...any) (sobek.Value, error)

RunModule the sobek.CyclicModuleRecord

example:

module, err := js.CompileModule("add", "export default (a, b) => a + b")
if err != nil {
	panic(err)
}
value, err := ski.RunModule(context.Background(), module, 1, 2)
if err != nil {
	panic(err)
}
fmt.Println(value.Export()) // 3

func RunProgram

func RunProgram(ctx context.Context, program *sobek.Program) (sobek.Value, error)

RunProgram executes the given sobek.Program

example:

program, err := sobek.Compile("", `1 + 1`, false)
if err != nil {
	panic(err)
}
value, err := ski.RunProgram(context.Background(), program)
if err != nil {
	panic(err)
}
fmt.Println(value.Export()) // 2

func RunString

func RunString(ctx context.Context, str string) (sobek.Value, error)

RunString executes the given string

example:

value, err := ski.RunString(context.Background(), `1 + 1`)
if err != nil {
	panic(err)
}
fmt.Println(value.Export()) // 2

func SetScheduler

func SetScheduler(s Scheduler)

SetScheduler set the default Scheduler

func WithValue

func WithValue(ctx context.Context, key, value any) context.Context

WithValue if parent exists multiple values Context then set the key/value. or returns a copy of parent in which the value associated with key is val.

Types

type Context

type Context interface {
	context.Context
	// SetValue store key with value
	SetValue(key, value any)
}

Context multiple values context

func NewContext

func NewContext(parent context.Context, values map[any]any) Context

NewContext returns a new can store multiple values context with values

type Metrics

type Metrics struct {
	Max       int `json:"max"`       // max vm size
	Idle      int `json:"idle"`      // idle vm size
	Remaining int `json:"remaining"` // remaining creatable vm size
}

Metrics contains Scheduler metrics

type Scheduler

type Scheduler interface {
	// Shrink the idle VM to initial VM size
	Shrink()
	// Metrics Scheduler metrics
	Metrics() Metrics
	// Close the scheduler
	Close() error
	// contains filtered or unexported methods
}

Scheduler the js.VM scheduler

func GetScheduler

func GetScheduler() Scheduler

GetScheduler get the default Scheduler

func NewScheduler

func NewScheduler(opt SchedulerOptions) Scheduler

NewScheduler create a new Scheduler

type SchedulerOptions

type SchedulerOptions struct {
	InitialVMs    uint          `yaml:"initial-vms" json:"initialVMs"`
	MaxVMs        uint          `yaml:"max-vms" json:"maxVMs"`
	GetMaxRetries uint          `yaml:"get-max-retries" json:"maxRetries"`
	GetTimeout    time.Duration `yaml:"get-timeout" json:"timeout"`
	VMOptions     []js.Option   `yaml:"-"` // options for NewVM
}

SchedulerOptions options

Directories

Path Synopsis
examples
echarts command
react command
vue command
js
Package js the JavaScript implementation.
Package js the JavaScript implementation.
modulestest
Package modulestest the module test vm
Package modulestest the module test vm
cache
Package cache the cache JS implementation
Package cache the cache JS implementation
crypto
Package crypto the crypto JS implementation
Package crypto the crypto JS implementation
dom
ext
url

Jump to

Keyboard shortcuts

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