Files
zeekayandGitHub 8d4e50c665 feat(runtime): embed goja + esbuild; ZAP-over-HTTP transport (#9)
* feat(runtime): embed goja + esbuild; add ZAP-over-HTTP transport

Establish zip as the canonical Hanzo Go web framework with embedded
in-process JS execution and a native ZAP RPC HTTP transport. One Go
binary mounts native handlers, legacy TS/JS handlers, WebSocket, and
the ZAP RPC plane — no separate runtime service, no inter-service RPC,
no container-per-service.

zip/runtime/ (new):
- jsvm.go    NewJSRuntime / Eval / RegisterHostFn / LoadModule, backed
             by a pool of *goja.Runtime (pure Go, no CGO). Pool pattern
             lifted from hanzoai/base/plugins/gojavm, slimmed to run +
             forEach so late host-fn / module registration reaches warm
             VMs.
- pool.go    fixed-size goja VM pool; saturated calls fall back to a
             fully-provisioned one-off VM.
- require.go CommonJS-style require(): per-VM module sources + memoized
             exports in a Go-side side-table (never visible to JS).
- esbuild.go TranspileToES5: TS/modern-JS -> goja-ready JS via esbuild's
             pure-Go API (ES2015 target, CommonJS format).
- handler.go JSHandler / JSModule: mount an Express-shaped (req, res) JS
             function as a fiber.Handler; req mirrors method/path/query/
             headers/body, res mirrors status/set/json/send.
- json.go    encode/decode through internal/jsonenc — one wire format.

zip/zaprpc/ (new on existing Registry seam):
- envelope.go canonical ZAP RPC frame (service/method/payload) over the
              zap-proto/go wire codec.
- http.go     HTTPHandler(reg): serves the ZAP RPC plane over HTTP POST;
              binary envelope canonical, X-ZAP-* headers are a hint only.

examples/express-in-zip/ (new): legacy app.ts -> real esbuild -> real
goja -> real Fiber -> real HTTP, with an integration test proving
GET /legacy/foo and POST /legacy/bar body echo.

README: embedded-JS migration path + single-binary (HIP-0106) sections.

go build ./... and go test ./... (incl. -race) pass.

* feat(runtime): ctx-aware Eval + multi-file BundleToES2015

Two consumer-integration follow-ups so callers (base's gojavm) stop
reaching past the runtime abstraction.

EvalContext(ctx, src): interrupt a running goja VM when ctx fires.
A watcher goroutine calls vm.Interrupt(ctx.Err()) on ctx.Done(); the
resulting *goja.InterruptedError is unwrapped back to ctx.Err(). The
watcher is joined and ClearInterrupt() is called before the VM is
returned to the pool, so a borrowed VM is never left interrupted.
Eval routes through EvalContext(context.Background()). InvokeFunc(ctx,
fnName, args...) calls a named global JS function under the same
cancellation discipline. This lets base drop the goroutine+timeout race
around Invoke.

BundleToES2015(entry, files, opts): transpile + bundle a multi-file
TS/JS tree from an in-memory files map using esbuild's pure-Go Build
API with an onResolve/onLoad plugin serving a virtual namespace — no
real FS access, no CGO. Relative imports resolve against the importer's
dir; opts.External keeps bare specifiers as require()/import calls for
goja to resolve at runtime. This replaces consumers importing esbuild's
api package directly to bundle.

Tests (go test -race clean):
- EvalContext(50ms, while(true){}) returns DeadlineExceeded in ~50ms
- successful eval returns the value; VM reusable afterwards
- two-file CommonJS bundle runs in goja, entry.run() === 42
- external dep stays require("external") and resolves via host module

* feat(runtime): unified multi-language Runner over the extruntime SPI

Add Runner — a registry of language → Engine that executes arbitrary-
language source in goroutine-scoped, context.Context-bound tasks. Each
Run spawns a worker (engine.Eval) and a watcher (ctx.Done() → engine
interrupt), joining both before return so a borrowed VM is never handed
back to its pool while still interrupted. This generalizes the settled
JSRuntime.EvalContext cancellation contract (one worker, one watcher,
joined, engine-specific interrupt) across every backend a host registers.

zip ships exactly one in-tree engine: the pure-Go goja engine, surfaced
via (*JSRuntime).Engine() and registered as "js". It self-manages ctx
inside EvalContext (per-call interrupt on the exact borrowed VM), so the
Runner's watcher is a benign no-op for it. base's backends (pyvm, v8vm,
wasmvm, starkvm) plug in through the same Engine seam via thin extruntime
adapters at app startup — the registry is the seam, not an import edge.
zip never imports base; the dependency direction stays base → zip.

Engine is the zip-side projection of base's extruntime backends: any
value implementing Eval(ctx, src, args) satisfies it. Optional
Interruptible lets the watcher abort a runaway eval out-of-band.

Wire the unified runner into examples/express-in-zip: POST /runtime/:lang
reads the body as source, dispatches to the engine for :lang, returns
{result} or 404 {error:"unknown language"}.

Tests (go test -race, all green):
  - JS happy path: Run(ctx, "js", "1+2") → int64(3)
  - JS function call: define + invoke in one eval
  - JS ctx deadline: while(true){} interrupted, DeadlineExceeded, ~50ms
  - unknown language: ErrUnknownLanguage sentinel, no panic
  - concurrent: 100 goroutines, registry RWMutex + per-call VM isolation
  - example: POST /runtime/js "40+2" → {"result":42}; cobol → 404

No cgo. No base import. README documents the Runner + SPI registration.
2026-06-16 16:05:27 -07:00

117 lines
3.5 KiB
Go

// express-in-zip — the proof point: a legacy Express-shaped TypeScript
// handler running inside zip with ZERO rewrite.
//
// app.ts (TS) --esbuild--> ES2015 JS --goja--> JSHandler --> Fiber route
//
// go run ./examples/express-in-zip
// curl http://localhost:8080/legacy/foo
// curl -XPOST -d '{"x":1}' -H content-type:application/json \
// http://localhost:8080/legacy/bar
package main
import (
_ "embed"
"errors"
"log"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/hanzoai/zip"
"github.com/hanzoai/zip/middleware"
"github.com/hanzoai/zip/runtime"
)
//go:embed app.ts
var appTS []byte
// setup wires esbuild -> goja -> JSHandler and mounts the legacy handler
// at /legacy/*. Returned as a *zip.App so the integration test can drive
// it via app.Fiber().Test(...) without binding a port.
func setup() (*zip.App, error) {
// 1. Transpile the legacy TS to goja-runnable JS.
js, err := runtime.TranspileToES5(appTS, runtime.ESOptions{
Loader: "ts",
Sourcefile: "app.ts",
})
if err != nil {
return nil, err
}
// 2. Embedded JS runtime, register the module (module.exports = fn).
rt, err := runtime.NewJSRuntime(runtime.JSOptions{PoolSize: 8})
if err != nil {
return nil, err
}
if err := rt.LoadModule("app", string(js)); err != nil {
return nil, err
}
// 3. Fiber handler from the module's exported function.
h, err := runtime.JSModule(rt, "app")
if err != nil {
return nil, err
}
// 4. Mount on zip. JSModule returns a fiber.Handler, so it goes on
// the underlying Fiber router via app.Fiber(); native zip routes
// sit alongside it on the same App. stripPrefix rewrites the
// request path so the legacy handler sees /foo, not /legacy/foo —
// the same path-stripping an Express sub-router does on mount.
app := zip.New(zip.Config{AppName: "express-in-zip"})
app.Use(middleware.Recover(), middleware.RequestID())
app.Fiber().All("/legacy/*", stripPrefix("/legacy", h))
// 5. Unified multi-language runner. The request body is the source,
// :lang selects the backend. zip ships the goja "js" engine in-tree;
// a host that imports base additionally registers pyvm/v8vm/wasmvm/
// starkvm here at startup — zip never imports base (see runtime/README).
runner := runtime.NewRunner()
if err := runner.Register("js", rt.Engine()); err != nil {
return nil, err
}
app.Fiber().Post("/runtime/:lang", runtimeHandler(runner))
return app, nil
}
// runtimeHandler reads the request body as source, dispatches it to the
// engine registered for :lang, and returns {result, error} as JSON. An
// unregistered language is a 404; an evaluation error is a 200 carrying
// the error string in the body so the caller sees the engine's message.
func runtimeHandler(runner runtime.Runner) fiber.Handler {
return func(c fiber.Ctx) error {
lang := c.Params("lang")
res, err := runner.Run(c.Context(), lang, c.Body())
if err != nil {
if errors.Is(err, runtime.ErrUnknownLanguage) {
return c.Status(fiber.StatusNotFound).
JSON(fiber.Map{"error": "unknown language"})
}
return c.JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{"result": res})
}
}
// stripPrefix rewrites the request path to drop prefix before delegating
// to next, mirroring Express sub-router mount semantics.
func stripPrefix(prefix string, next fiber.Handler) fiber.Handler {
return func(c fiber.Ctx) error {
p := strings.TrimPrefix(c.Path(), prefix)
if p == "" {
p = "/"
}
c.Path(p)
return next(c)
}
}
func main() {
app, err := setup()
if err != nil {
log.Fatal(err)
}
log.Fatal(app.Listen(":8080"))
}