vango

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 42 Imported by: 0

README

Vango

Full Stack Go.
Build modern web apps with a single language, a single binary, and no client/server state synchronization. Solid's reactivity meets LiveView's architecture—in Go.

Go Reference Go Report Card License Discord

DocumentationExamplesV1 Beta NotesDiscord


Vango [BETA]

Server-driven UI for Go. One language. One binary. Full interactivity.

Go Version License Documentation

Vango is a web framework that keeps your state and rendering on the server while delivering SPA-like interactivity to the browser. Write Go. Ship a single binary. Get modern web UX without the JavaScript build complexity.

Vango V1 Beta is production-ready under the Portable Vango Production Beta definition: standalone teams can build, verify, diagnose, and ship serious beta apps without depending on Rhone Code or Rhone Cloud. Vango emits portable framework facts; hosts attach operational authority.

func Counter(p CounterProps) vango.Component {
    return vango.Setup(p, func(s vango.SetupCtx[CounterProps]) vango.RenderFn {
        count := setup.Signal(&s, 0)

        return func() *vango.VNode {
            return Div(
                Button(OnClick(count.Dec), Text("-")),
                Span(Textf("%d", count.Get())),
                Button(OnClick(count.Inc), Text("+")),
            )
        }
    })
}

Why Vango?

If you've ever shipped a React app where a refactor silently broke user sessions, spent days debugging hydration mismatches, or wished you could just write Go instead of maintaining two codebases—Vango is designed to make those problems disappear.

🎯 One Language, Full Stack — Write your entire web app in Go. No separate frontend codebase, no client/server state sync, no hydration bugs.

⚡ Server State, Client Feel — State lives on the server. The browser runs a thin client that captures events and applies binary patches. Sub-50ms interactions feel instant.

🔒 Deploy-Safe by Default — Refactor fearlessly. Tooling tracks state identity so sessions survive deploys. Warm vs cold deploy impact is computed and CI-enforced—no silent user state loss.

🎨 Client Capabilities When You Need Them — Hooks for drag-and-drop, islands for rich editors, WASM for offline. First-class, not escape hatches.

Quick Start

go install github.com/vango-go/vango/cmd/vango@v0.2.0
vango create myapp && cd myapp
vango dev

Open http://localhost:8080.

Production Posture

Vango is ready for production-bound V1 Beta apps when teams follow the blessed app model and run the release gates. The framework provides:

  • generated artifact ownership, verification, repair guidance, and stale-output detection
  • route, state, runtime service, host manifest, operation readiness, native bridge, compatibility, and release-note facts
  • secure production defaults for CSRF, origin/host/proxy handling, cookies, upload limits, panic recovery, health probes, raw HTML hardening, and shutdown/drain behavior
  • client-boundary governance for hooks, islands, WASM, raw HTML, lifecycle cleanup, and ownership violations
  • runtime log event and metric catalogs, redaction guidance, and OpenTelemetry middleware proof
  • conformance and smoke fixtures any host can run to validate Vango semantics

Before promoting an app, run:

vango generated verify --json
vango lint --strict ci
vango readiness check --profile release --json
scripts/release_readiness.sh

For deployed hosts, also run vango conformance run against the target runtime. For provider-backed, native, compliance, billing, quota, support, or human approval concerns, attach release-target evidence outside Vango. Vango proves framework facts; it does not create provider resources, sign native artifacts, approve production traffic, or replace operational review.

See VANGO_V1_BETA_RELEASE_NOTES.md for the current known limits and proof posture.

Native iPhone Apps

Vango has a scaffoldable iOS target with vango create --with ios, vango create --with ios --with storekit, vango run ios, vango build ios, vango archive ios, vango export ios, and vango audit ios --testflight, backed by a SwiftUI + WKWebView host and a Go mobile bridge. vango archive ios --unsigned remains available for CI/package-shape validation without signing credentials.

Current iOS capability baseline:

  • vango create --with ios scaffolds mobile/ios, mobile/ios/bridge, and shared app bootstrap wiring
  • embedded and constrained hosted topologies
  • generated entitlements from platform.ios.capabilities
  • scaffolded mobile/ios/PrivacyInfo.xcprivacy baseline
  • APNs registration and device-token handoff when push capability is enabled
  • remote push received/opened lifecycle events with normalized route and URL payloads
  • Universal Links runtime delivery through the native deep-link bridge when Associated Domains are configured correctly
  • document import/export dialogs
  • clipboard read/write
  • deep-link receive
  • local notifications
  • native StoreKit product query, purchase, restore, current-entitlement refresh, and subscription-management handoff when platform.ios.capabilities.storeKit.enabled is enabled

Current iOS limitations:

  • APNs registration and push lifecycle support now exist, but app teams still own their push provider/backend pipeline and product-specific notification semantics
  • Sign in with Apple runtime support exists for native Apple credential collection, and the scaffold now includes an app-owned Apple exchange hook. App teams still need a real backend/provider exchange plus final session-auth wiring
  • StoreKit runtime support and scaffolding now exist, but app teams still own real entitlement verification, App Store Connect product setup, and production billing policy

The intended App Store posture is embedded first. Hosted iPhone mode is for trusted first-party product surfaces only, not generic website wrappers or remote app containers. Hosted allowlists should stay on the same product-owned registrable domain as the hosted base URL.

The safest non-IAP Vango posture is a login-only companion app that fits Apple Guideline 3.1.3(f): existing paid web customers can sign in and use the service, but the iPhone app does not sell, upsell, or link out to buy digital unlocks from inside the app. If the iPhone app unlocks digital usage itself, treat it as a 3.1.1 StoreKit problem.

The current iPhone launch claim is backed by three repo proof paths: ./scripts/ios_scaffold_smoke.sh validates fresh plain iOS, iOS+auth, and iOS+StoreKit scaffolds through Go tests, native Swift tests, privacy-manifest lint, vango audit ios --archive, vango build ios, and optional unsigned archive smoke; inspectapp is the canonical internal App Review dry-run and TestFlight-ready release-candidate app, with /ios-review, /login, and /account covering shell, auth, deletion, and release-packet review; and examples/mobile-ios-storekit/app/app.go is the canonical embedded monetized example proving the first-party StoreKit bridge. Signed vango archive ios plus vango export ios is the release path.

The Programming Model

Setup/Closure: One Way to Write Components

Every stateful component follows the same pattern: Setup allocates state once, Render computes UI purely.

func TodoList(p TodoListProps) vango.Component {
    return vango.Setup(p, func(s vango.SetupCtx[TodoListProps]) vango.RenderFn {
        // Setup: allocate state (runs once per mount)
        items := setup.Signal(&s, []Todo{})
        newText := setup.Signal(&s, "")

        addTodo := setup.Action(&s,
            func(ctx context.Context, text string) (Todo, error) {
                return db.CreateTodo(ctx, text)
            },
            vango.DropWhileRunning(),
        )

        return func() *vango.VNode {
            // Render: pure function of state (runs on every update)
            return Div(
                Input(Value(newText.Get()), OnInput(newText.Set)),
                Button(OnClick(func() { addTodo.Run(newText.Get()) }), Text("Add")),
                RangeKeyed(items.Get(),
                    func(t Todo) string { return t.ID },
                    func(t Todo) *vango.VNode { return Li(Text(t.Text)) },
                ),
            )
        }
    })
}

No hook order rules. No accidental re-renders. No "stale closure" bugs.

Resources & Actions

Resources load data. Actions mutate it. Both run off the session loop so renders stay fast.

user := setup.ResourceKeyed(&s,
    func() int { return props.Get().UserID },
    func(ctx context.Context, id int) (*User, error) {
        return db.GetUser(ctx, id)
    },
)

return user.Match(
    vango.OnLoading(func() *vango.VNode { return Div(Text("Loading...")) }),
    vango.OnError(func(err error) *vango.VNode { return Div(Text(err.Error())) }),
    vango.OnReady(func(u *User) *vango.VNode { return Div(Text(u.Name)) }),
)

Full guide: Resources & Actions →

Deploy-Safe Persistence

Session state survives refreshes and deploys. You don't manage keys—tooling assigns stable IDs and tracks schema compatibility.

cartItems := setup.SharedSignal(&s, []CartItem{})  // Persisted per session
announcement := setup.GlobalSignal(&s, "")         // Shared across all sessions

Before shipping, you know exactly what will happen:

$ vango state plan
Added persisted IDs: 1
Classification: ✅ WARM DEPLOY

Cold deploys require explicit CI acknowledgment. No silent user state loss.

Full guide: Deploy-Safe State →

Client Hooks (Optional)

When server-driven isn't enough—drag-and-drop, focus management, third-party widgets—attach client behavior while keeping the server authoritative.

Ul(
    Hook("Sortable", map[string]any{"handle": ".drag-handle"}),
    OnEvent("reorder", func(e vango.HookEvent) {
        from, to := e.Int("fromIndex"), e.Int("toIndex")
        items.Set(reorder(items.Get(), from, to))
    }),
    RangeKeyed(items.Get(), ...),
)

Full guide: Client Capabilities →

Project Structure

myapp/
├── cmd/server/main.go          # Entry point
├── app/
│   ├── routes/                 # File-based routing
│   ├── components/             # Shared UI components
│   └── stores/                 # SessionKeys and state roots
├── internal/                   # Business logic
├── public/                     # Static assets
├── vango_state_manifest.json   # Commit this
└── vango_state_schema.json     # Commit this

What Vango Is Not

  • Not a SPA framework that pushes state to the browser
  • Not a template engine with ad hoc JavaScript sprinkled in
  • Not best-effort — deploy impact is computed, not guessed

Who Is Vango For?

  • Go developers who want a single-language web stack
  • React/Next refugees who want the UX without the complexity
  • LiveView fans who want Go performance and ecosystem
  • Teams shipping fast who can't afford silent state bugs

Documentation

Requirements

  • Go 1.26.3+ (repo pins this production-safe toolchain in go.mod)
  • Modern browser (ES2020+)

Contributing

See CONTRIBUTING.md.

License

MIT. See LICENSE.


DocsDiscussionsDiscord

Documentation

Overview

Package vango provides the public API for the Vango web framework.

This is the recommended import for most applications:

import "github.com/vango-go/vango"

Usage:

return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
    count := setup.Signal(&s, 0)
    form := setup.Form(&s, MyFormData{})
    search := setup.URLParam(&s, "q", "", vango.Replace, vango.URLDebounce(300*time.Millisecond))
    return func() *vango.VNode {
        _ = count
        _ = form
        _ = search
        return Div()
    }
})

Index

Constants

View Source
const (
	// EvictionLRU evicts the least recently accessed detached sessions first.
	EvictionLRU = server.EvictionLRU
	// EvictionOldest evicts the oldest sessions first (by creation time).
	EvictionOldest = server.EvictionOldest
	// EvictionRandom evicts sessions randomly (faster but less fair).
	EvictionRandom = server.EvictionRandom
)
View Source
const (
	// Failure modes
	FailOpenWithGrace = server.FailOpenWithGrace
	FailClosed        = server.FailClosed

	// Expiry actions
	ForceReload = server.ForceReload
	NavigateTo  = server.NavigateTo
	AuthCustom  = server.Custom

	// Expiry reasons
	AuthExpiredUnknown                  = server.AuthExpiredUnknown
	AuthExpiredPassiveExpiry            = server.AuthExpiredPassiveExpiry
	AuthExpiredResumeRehydrateFailed    = server.AuthExpiredResumeRehydrateFailed
	AuthExpiredActiveRevalidateFailed   = server.AuthExpiredActiveRevalidateFailed
	AuthExpiredOnDemandRevalidateFailed = server.AuthExpiredOnDemandRevalidateFailed
	AuthExpiredNoRevalidationHooks      = server.AuthExpiredNoRevalidationHooks

	// Auth resume policies
	AuthResumePolicyStrict                 = server.AuthResumePolicyStrict
	AuthResumePolicyTrustSessionID         = server.AuthResumePolicyTrustSessionID
	UnsafeConfigCodeDevMode                = server.UnsafeConfigCodeDevMode
	UnsafeConfigCodeTrustSessionID         = server.UnsafeConfigCodeTrustSessionID
	UnsafeConfigCodeUnsafeRawHTML          = server.UnsafeConfigCodeUnsafeRawHTML
	UnsafeConfigCodeInsecureModuleOrigins  = server.UnsafeConfigCodeInsecureModuleOrigins
	UnsafeConfigCodeHeuristicEventPayloads = server.UnsafeConfigCodeHeuristicEventPayloads
	UnsafeConfigStateActive                = server.UnsafeConfigStateActive
	UnsafeConfigStatePermission            = server.UnsafeConfigStatePermission
	UnsafeConfigSeverityCritical           = server.UnsafeConfigSeverityCritical
	UnsafeConfigSeverityHigh               = server.UnsafeConfigSeverityHigh
	UnsafeConfigSeverityModerate           = server.UnsafeConfigSeverityModerate
	DevModeRiskAcceptanceV1                = server.DevModeRiskAcceptanceV1
	TrustSessionIDRiskAcceptanceV1         = server.TrustSessionIDRiskAcceptanceV1
	UnsafeRawHTMLRiskAcceptanceV1          = server.UnsafeRawHTMLRiskAcceptanceV1
	InsecureModuleOriginsRiskAcceptanceV1  = server.InsecureModuleOriginsRiskAcceptanceV1
	HeuristicEventPayloadRiskAcceptanceV1  = server.HeuristicEventPayloadRiskAcceptanceV1
)
View Source
const (
	// HostedSurfaceProofSecretEnv is the environment variable read by hosted
	// macOS native hosts and app servers for signed surface proof verification.
	HostedSurfaceProofSecretEnv = envHostedSurfaceProofSecret
	// HostedSurfaceTokenSecretEnv is the server-only environment variable used
	// to sign hosted auth bootstrap tokens.
	HostedSurfaceTokenSecretEnv = envHostedSurfaceTokenSecret
	// HostedSurfaceAllowedOriginsEnv lists comma-separated trusted hosted origins.
	HostedSurfaceAllowedOriginsEnv = envHostedSurfaceOrigins
)
View Source
const (
	ActionRejectQueueFull        = corevango.ActionRejectQueueFull
	ActionRejectDropWhileRunning = corevango.ActionRejectDropWhileRunning
)
View Source
const (
	Ctrl  = corevango.Ctrl
	Shift = corevango.Shift
	Alt   = corevango.Alt
	Meta  = corevango.Meta
)
View Source
const (
	ActionIdle    = corevango.ActionIdle
	ActionRunning = corevango.ActionRunning
	ActionSuccess = corevango.ActionSuccess
	ActionError   = corevango.ActionError
)

ActionState constants

View Source
const (
	KindElement   = vdom.KindElement
	KindText      = vdom.KindText
	KindFragment  = vdom.KindFragment
	KindComponent = vdom.KindComponent
	KindRaw       = vdom.KindRaw
)

VKind constants

View Source
const DefaultFormMaxBytes int64 = 1 << 20

DefaultFormMaxBytes is the default maximum size for form bodies parsed by ParseForm. 1 MiB is a safe baseline for typical form submissions.

Variables

View Source
var ActionOnError = corevango.ActionOnError
View Source
var ActionOnStart = corevango.OnActionStart
View Source
var ActionOnSuccess = corevango.ActionOnSuccess
View Source
var ActionTxName = corevango.ActionTxName
View Source
var BadRequest = corevango.BadRequest
View Source
var BadRequestf = corevango.BadRequestf

Batch groups multiple signal updates into a single notification.

View Source
var CSRFCtxToken = server.CSRFCtxToken
View Source
var CancelLatest = corevango.CancelLatest
View Source
var Conflict = corevango.Conflict
View Source
var DevMode = &corevango.DevMode

DevMode enables development-time validation. When true, write violations panic with descriptive messages. When false (production), invalid writes are logged and dropped. DevMode is automatically enabled for test binaries.

View Source
var DropWhileRunning = corevango.DropWhileRunning
View Source
var ErrActionRunning = corevango.ErrActionRunning
View Source
var ErrAuthCheckPanicked = server.ErrAuthCheckPanicked
View Source
var ErrBudgetExceeded = corevango.ErrBudgetExceeded
View Source
var ErrQueueFull = corevango.ErrQueueFull
View Source
var Forbidden = corevango.Forbidden
View Source
var InternalError = corevango.InternalError
View Source
var Interval = corevango.Interval
View Source
var Invalid = corevango.Invalid
View Source
var NotFound = corevango.NotFound
View Source
var OnActionRejected = corevango.OnActionRejected
View Source
var RedirectTo = corevango.RedirectTo
View Source
var ServiceUnavailable = corevango.ServiceUnavailable
View Source
var StrictConcurrency = &corevango.StrictConcurrency

StrictConcurrency forces session-loop-only write enforcement to panic even when DevMode is false. Useful for staging/canary environments.

View Source
var Timeout = corevango.Timeout

Tx is an alias for Batch.

View Source
var TxNamed = corevango.TxNamed

TxNamed is a named transaction for observability.

View Source
var Unauthorized = corevango.Unauthorized
View Source
var UnprocessableEntity = corevango.UnprocessableEntity
View Source
var Untracked = corevango.Untracked

Untracked reads signals without creating subscriptions.

View Source
var WithNavigateParams = server.WithNavigateParams

WithNavigateParams adds query parameters to the navigation URL.

View Source
var WithReplace = server.WithReplace

WithReplace replaces the current history entry instead of pushing.

View Source
var WithoutScroll = server.WithoutScroll

WithoutScroll disables scrolling to top after navigation.

Functions

func Async

func Async(fn func(value any) (error, bool)) *form.AsyncValidator

Async creates an async validator for server-side checks.

func DecodeHookPayload

func DecodeHookPayload[T any](event HookEvent) (T, error)

DecodeHookPayload decodes hook payload data into a typed schema using strict JSON rules (unknown fields are rejected).

func DecodeIslandPayload

func DecodeIslandPayload[T any](msg IslandMessage) (T, error)

DecodeIslandPayload decodes island payload data into a typed schema using strict JSON rules (unknown fields are rejected).

func DecodeWasmPayload

func DecodeWasmPayload[T any](msg WasmMessage) (T, error)

DecodeWasmPayload decodes WASM payload data into a typed schema using strict JSON rules (unknown fields are rejected).

func DisableGlobalSignalRefresh

func DisableGlobalSignalRefresh() *time.Duration

DisableGlobalSignalRefresh disables periodic anti-entropy refresh for global signals.

func EqualTo

func EqualTo(field string, msg string) *form.EqualToField

EqualTo returns a validator that checks if the value equals another field.

func Func

func Func(render func() *vdom.VNode) vdom.Component

Func wraps a render function as a Component. Deprecated: Use vango.Setup for all stateful components.

Example:

func Counter(initial int) vango.Component {
    return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
        count := setup.Signal(&s, initial)
        return func() *vango.VNode {
            return Div(
                H1(Textf("Count: %d", count.Get())),
                Button(OnClick(count.Inc), Text("+")),
            )
        }
    })
}

func GlobalSignalRefreshInterval

func GlobalSignalRefreshInterval(d time.Duration) *time.Duration

GlobalSignalRefreshInterval configures the periodic anti-entropy refresh cadence for global signals from persistence.

func Hook

func Hook(name string, config any) vdom.Attr

func InSessionLoop added in v0.2.0

func InSessionLoop() bool

InSessionLoop reports whether the current goroutine is executing on the single-writer session loop.

func NoResume

func NoResume() *time.Duration

NoResume disables session resumption (ResumeWindow=0).

func NotEqualTo

func NotEqualTo(field string, msg string) *form.NotEqualToField

NotEqualTo returns a validator that ensures the value differs from another field.

func OnEvent

func OnEvent(name string, handler func(HookEvent)) vdom.Attr

OnEvent attaches a hook event handler to an element. This is spec-aligned: the handler receives `vango.HookEvent`.

func OnEventValidated added in v0.2.0

func OnEventValidated(name string, validate HookEventValidator, handler func(HookEvent)) vdom.Attr

OnEventValidated attaches a hook event handler plus exact-sink validation metadata for the named hook event.

func ParseForm

func ParseForm(r *http.Request, dst any) error

ParseForm parses an HTTP form submission into the provided struct pointer. It returns form.ParseErrors when any fields fail to parse. ParseForm enforces DefaultFormMaxBytes to prevent memory DoS from large bodies.

func ParseFormData

func ParseFormData(fd FormData, dst any) error

ParseFormData parses a Vango FormData submission into the provided struct pointer. It returns form.ParseErrors when any fields fail to parse.

func ParseFormWithLimit

func ParseFormWithLimit(r *http.Request, dst any, maxBytes int64) error

ParseFormWithLimit parses an HTTP form submission into the provided struct pointer, enforcing a maximum body size. It returns form.ParseErrors when fields fail to parse and *http.MaxBytesError when the size limit is exceeded.

func ResumeWindow

func ResumeWindow(d time.Duration) *time.Duration

ResumeWindow returns a pointer for configuring session resumption duration. Use NoResume() to disable resumption explicitly.

func Setup

func Setup[P any](p P, fn func(corevango.SetupCtx[P]) corevango.RenderFn) corevango.Component

Setup creates a stateful component with explicit props binding.

func UntrackedGet

func UntrackedGet[T any](s *Signal[T]) T

UntrackedGet reads a signal's value without subscribing.

func UserFromContext

func UserFromContext(ctx context.Context) any

UserFromContext retrieves an authenticated user stored by WithUser. Returns nil when no user is present.

func UserFromContextAs added in v0.1.0

func UserFromContextAs[T any](ctx context.Context) (T, bool)

UserFromContextAs retrieves and type-asserts an authenticated user stored by WithUser. It returns the zero value of T and false when no user is present or the value has a different type.

func WithUser

func WithUser(ctx context.Context, user any) context.Context

WithUser stores an authenticated user in a stdlib context for SSR and session bridging. Pair with UserFromContext and Config.OnSessionStart.

Types

type APIConfig

type APIConfig struct {
	// MaxBodyBytes is the maximum number of bytes read from the HTTP request body
	// when an API handler declares a typed body parameter.
	//
	// Default: 1 MiB.
	MaxBodyBytes int64

	// RequireJSONContentType enforces that requests with a non-empty body specify a
	// JSON Content-Type (application/json or application/*+json) when an API handler
	// declares a structured (non-[]byte, non-string) body parameter.
	//
	// When false (default), missing Content-Type is accepted, but explicit non-JSON
	// Content-Type is rejected.
	RequireJSONContentType bool
}

APIConfig configures JSON API routes registered via app.API.

func DefaultAPIConfig

func DefaultAPIConfig() APIConfig

DefaultAPIConfig returns an APIConfig with sensible defaults.

type APIHandler

type APIHandler = any

APIHandler handles API requests and returns JSON responses. Multiple signatures are supported:

  • func(ctx Ctx) (R, error) - no params or body
  • func(ctx Ctx, params P) (R, error) - with route params
  • func(ctx Ctx, body B) (R, error) - with request body
  • func(ctx Ctx, params P, body B) (R, error) - with both

The framework inspects the handler signature to determine how to decode.

type Action

type Action[A any, R any] = corevango.Action[A, R]

type ActionCtx added in v0.1.0

type ActionCtx = corevango.ActionCtx

type ActionHandler

type ActionHandler = corevango.ActionHandler

func OnActionError

func OnActionError(fn func(error) *vdom.VNode) ActionHandler

func OnActionIdle

func OnActionIdle(fn func() *vdom.VNode) ActionHandler

Action match helpers

func OnActionRunning

func OnActionRunning(fn func() *vdom.VNode) ActionHandler

func OnActionSuccess

func OnActionSuccess[R any](fn func(R) *vdom.VNode) ActionHandler

type ActionOption

type ActionOption = corevango.ActionOption

type ActionRejection

type ActionRejection = corevango.ActionRejection

type ActionRejectionReason

type ActionRejectionReason = corevango.ActionRejectionReason

type ActionState

type ActionState = corevango.ActionState

ActionState represents the current state of an action.

type AnimationEvent

type AnimationEvent = corevango.AnimationEvent

type App

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

App is the main Vango application entry point. It wraps the server, router, and static file serving into a single http.Handler.

func MustNew

func MustNew(cfg Config) *App

MustNew creates a new Vango application and panics if the configuration is invalid.

func New

func New(cfg Config) (*App, error)

New creates a new Vango application with the given configuration. Returns an error when the configuration is invalid for non-DevMode environments.

func (*App) API

func (a *App) API(method, path string, handler APIHandler)

API registers an API handler for the given HTTP method and path. API handlers return JSON responses.

Multiple handler signatures are supported:

// Simple handler (no params or body)
func HealthGET(ctx vango.Ctx) (*HealthResponse, error)

// With route parameters
func UserGET(ctx vango.Ctx, p UserParams) (*User, error)

// With request body
func UserPOST(ctx vango.Ctx, body CreateUserRequest) (*User, error)

// With both parameters and body
func UserPUT(ctx vango.Ctx, p UserParams, body UpdateRequest) (*User, error)

func (*App) Config

func (a *App) Config() Config

Config returns the app configuration.

func (*App) HandleUpload

func (a *App) HandleUpload(path string, store upload.Store)

HandleUpload registers a CSRF-protected upload handler at the given path. This is the recommended way to mount upload handlers in Vango applications.

The handler is automatically wrapped with CSRF middleware when CSRF is enabled. Clients must include the CSRF token in the X-CSRF-Token header. Route middleware from app.Use/app.Middleware also applies to uploads.

Example:

store, _ := upload.NewDiskStore("/tmp/uploads", 10*1024*1024)
app.HandleUpload("/api/upload", store)

For custom configuration (max file size, allowed types, etc.), use HandleUploadWithConfig.

func (*App) HandleUploadWithConfig

func (a *App) HandleUploadWithConfig(path string, store upload.Store, config *upload.Config)

HandleUploadWithConfig registers a CSRF-protected upload handler with custom configuration.

The handler is automatically wrapped with CSRF middleware when CSRF is enabled. Clients must include the CSRF token in the X-CSRF-Token header. Route middleware from app.Use/app.Middleware also applies to uploads.

Example:

store, _ := upload.NewDiskStore("/tmp/uploads", 50*1024*1024)
app.HandleUploadWithConfig("/api/upload", store, &upload.Config{
    MaxFileSize:  5 * 1024 * 1024,  // 5MB
    AllowedTypes: []string{"image/png", "image/jpeg"},
})

func (*App) Handler

func (a *App) Handler() http.Handler

Handler returns the App as an http.Handler. This is useful for explicit type conversion or middleware wrapping.

func (*App) Layout

func (a *App) Layout(path string, handler LayoutHandler)

Layout registers a layout handler for a path. Layouts registered separately apply to all pages under that path.

app.Layout("/admin", AdminLayout)
app.Page("/admin/dashboard", DashboardPage) // Uses AdminLayout
app.Page("/admin/users", UsersPage)         // Uses AdminLayout

func (*App) Middleware

func (a *App) Middleware(path string, mw ...RouteMiddleware)

Middleware registers route middleware for a path. Middleware runs before page/API/upload handlers and can:

  • Redirect (e.g., authentication checks)

  • Add data to context

  • Short-circuit the request

    app.Middleware("/admin", authMiddleware)

func (*App) Page

func (a *App) Page(path string, handler PageHandler, layouts ...LayoutHandler)

Page registers a page handler with optional layouts. The handler is called when a user navigates to the path.

Two handler signatures are supported:

// Static page (no route parameters)
func IndexPage(ctx vango.Ctx) *vango.VNode

// Dynamic page (with typed parameters)
type ShowParams struct {
    ID int `param:"id"`
}
func ShowPage(ctx vango.Ctx, p ShowParams) *vango.VNode

Layouts wrap the page content. They are applied in order (root to leaf):

app.Page("/projects/:id", projects.ShowPage, RootLayout, ProjectsLayout)

func (*App) PageAction added in v0.1.0

func (a *App) PageAction(path string, handler any)

PageAction registers a progressive page action for the given page route.

func (*App) Router

func (a *App) Router() *router.Router

Router returns the underlying router for advanced configuration. Most apps won't need this.

func (*App) Run

func (a *App) Run(ctx context.Context, addr string) error

Run starts the server and blocks until shutdown. This is a convenience method equivalent to http.ListenAndServe with graceful shutdown.

app, err := vango.New(cfg)
if err != nil {
    log.Fatal(err)
}
routes.Register(app)
app.Run(":8080")

func (*App) RunAddr

func (a *App) RunAddr(addr string) error

RunAddr starts the server and blocks until shutdown. This uses OS signals (SIGINT/SIGTERM) for graceful shutdown.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler. It routes requests to static files, the WebSocket endpoint, or page routes.

func (*App) Server

func (a *App) Server() *server.Server

Server returns the underlying server for advanced configuration. Most apps won't need this.

func (*App) SetErrorPage

func (a *App) SetErrorPage(handler func(Ctx, error) *VNode)

SetErrorPage sets the handler for error pages.

app.SetErrorPage(func(ctx vango.Ctx, err error) *vango.VNode {
    return Div(H1(Textf("Error: %v", err)))
})

func (*App) SetNotFound

func (a *App) SetNotFound(handler PageHandler)

SetNotFound sets the handler for 404 pages.

app.SetNotFound(func(ctx vango.Ctx) *vango.VNode {
    return Div(H1(Text("Page Not Found")))
})

func (*App) UnsafeConfigReport added in v0.2.0

func (a *App) UnsafeConfigReport() server.UnsafeConfigReport

func (*App) Use

func (a *App) Use(mw ...RouteMiddleware)

Use adds global middleware that applies to all routes. This includes page, API, and upload routes.

app.Use(loggingMiddleware, rateLimitMiddleware)

type AssetManifest

type AssetManifest = assets.Manifest

AssetManifest holds the mapping from source asset paths to fingerprinted paths. Use LoadAssetManifest to load from a manifest.json file.

func LoadAssetManifest

func LoadAssetManifest(path string) (*AssetManifest, error)

LoadAssetManifest loads a manifest.json file generated by the build process. The manifest maps source paths to fingerprinted paths:

{"vango.js": "vango.a1b2c3d4.min.js", "styles.css": "styles.e5f6g7h8.css"}

Example:

manifest, err := vango.LoadAssetManifest("dist/manifest.json")
if err != nil {
    // In dev mode, this is expected - use passthrough resolver
    log.Println("No manifest found, using passthrough resolver")
}

type AssetResolver

type AssetResolver = assets.Resolver

AssetResolver provides asset path resolution with prefix support.

func NewAssetResolver

func NewAssetResolver(m *AssetManifest, prefix string) AssetResolver

NewAssetResolver creates a resolver from a manifest with a path prefix. The prefix is prepended to all resolved paths.

Example:

manifest, _ := vango.LoadAssetManifest("dist/manifest.json")
resolver := vango.NewAssetResolver(manifest, "/public/")

// Configure server
config := server.DefaultServerConfig()
config.AssetResolver = resolver

func NewPassthroughResolver

func NewPassthroughResolver(prefix string) AssetResolver

NewPassthroughResolver creates a resolver that returns paths unchanged. Use this in development mode where fingerprinting is disabled.

Example:

resolver := vango.NewPassthroughResolver("/public/")
resolver.Asset("vango.js") // "/public/vango.js"

type Attr

type Attr = vdom.Attr

Attr represents a single attribute in the VDOM. It is returned by the el DSL helpers (e.g. Class, ID, Attr) and can be used as a concrete type in user code (e.g. func TestID(string) vango.Attr).

type AuthCheckConfig

type AuthCheckConfig = server.AuthCheckConfig

AuthCheckConfig configures periodic active revalidation. Use vango.Principal in AuthCheckConfig.Check callback signatures.

type AuthExpiredAction

type AuthExpiredAction = server.AuthExpiredAction

AuthExpiredAction defines the action type for auth expiry.

type AuthExpiredConfig

type AuthExpiredConfig = server.AuthExpiredConfig

AuthExpiredConfig defines behavior when auth expires.

type AuthExpiredReason

type AuthExpiredReason = server.AuthExpiredReason

AuthExpiredReason provides structured context for auth expiry.

type AuthFailureMode

type AuthFailureMode = server.AuthFailureMode

AuthFailureMode controls what happens when active checks fail.

type AuthResumePolicy

type AuthResumePolicy = server.AuthResumePolicy

AuthResumePolicy controls how authenticated session resumes are validated.

type CacheControlStrategy

type CacheControlStrategy int

CacheControlStrategy determines caching behavior for static files.

const (
	// CacheControlNone adds no caching headers.
	// Use in development for instant updates.
	CacheControlNone CacheControlStrategy = iota

	// CacheControlProduction uses appropriate caching:
	// - Fingerprinted files (*.abc123.css): immutable, 1 year max-age
	// - Other files: short cache with revalidation
	CacheControlProduction
)

type Cleanup

type Cleanup = corevango.Cleanup

func GoLatest

func GoLatest[K comparable, R any](
	key K,
	work func(ctx context.Context, key K) (R, error),
	apply func(result R, err error),
	opts ...corevango.GoLatestOption,
) Cleanup

func Subscribe

func Subscribe[T any](stream corevango.Stream[T], fn func(T), opts ...corevango.SubscribeOption) Cleanup

type Component

type Component = vdom.Component

Component is anything that can render to a VNode.

type Config

type Config struct {
	// Session configures session behavior including durability and limits.
	Session SessionConfig

	// Static configures static file serving.
	Static StaticConfig

	// API configures JSON API routes (app.API).
	API APIConfig

	// Security configures security features (CSRF, origin checking, cookies).
	Security SecurityConfig

	// GlobalSignalPubSub is the broadcast backend for global signals.
	// When nil, global signals update via eventual consistency only.
	GlobalSignalPubSub GlobalBroadcastBackend

	// GlobalSignalRefreshInterval controls the periodic anti-entropy refresh
	// cadence for global signals from persistence.
	// When persistence is available, this still runs with pubsub enabled so
	// instances converge after missed broadcasts.
	// nil means use the default (30 seconds).
	// 0 disables refresh entirely.
	GlobalSignalRefreshInterval *time.Duration

	// DevMode enables development mode which disables security checks.
	// SECURITY: NEVER use in production - this disables:
	//   - Origin checking (allows all origins)
	//   - CSRF validation
	//   - Secure cookie requirements
	DevMode bool

	// Logger is the structured logger for the application.
	// If nil, slog.Default() is used.
	Logger *slog.Logger

	// Observability configures optional logging for mutations.
	// All fields are opt-in and default to false.
	Observability ObservabilityConfig

	// Metrics configures the runtime metrics sink.
	// When nil, metrics emission defaults to the internal collector.
	Metrics MetricsSink

	// StrictConcurrency forces session-loop-only write enforcement (signals,
	// session keys) to panic even when pkg/vango.DevMode is false.
	//
	// Default: false (production-safe: drop + warn + metric).
	//
	// Useful for staging/canary environments to catch concurrency violations
	// before they reach production.
	StrictConcurrency bool

	// OnSessionStart is called when a new WebSocket session is established.
	// Use this to transfer data from the HTTP context (e.g., authenticated user)
	// to the Vango session before the handshake completes.
	//
	// Example:
	//   OnSessionStart: func(httpCtx context.Context, s *vango.Session) {
	//       if user := myauth.UserFromContext(httpCtx); user != nil {
	//           auth.Set(s, user)  // Use auth.Set to set presence flag
	//       }
	//   }
	OnSessionStart func(httpCtx context.Context, s *Session)

	// OnSessionResume is called when resuming an existing WebSocket session.
	// Use this to rehydrate session data from the HTTP context (e.g., re-validate auth).
	//
	// Unlike OnSessionStart, this is called when resuming after disconnect.
	// Return nil to allow the resume, or an error to reject it.
	//
	// Example:
	//   OnSessionResume: func(httpCtx context.Context, s *vango.Session) error {
	//       user, err := myauth.ValidateFromContext(httpCtx)
	//       if err != nil {
	//           return err  // Reject resume if previously authenticated
	//       }
	//       if user != nil {
	//           auth.Set(s, user)
	//       }
	//       return nil
	//   }
	OnSessionResume func(httpCtx context.Context, s *Session) error

	// SSR configures server-side rendering behavior.
	SSR SSRConfig
}

Config is the main application configuration. This is the user-friendly entry point for configuring a Vango app.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

type CookieOption

type CookieOption = server.CookieOption

CookieOption configures cookie policy application.

func WithCookieHTTPOnly

func WithCookieHTTPOnly(enabled bool) CookieOption

WithCookieHTTPOnly overrides the default HttpOnly behavior for a cookie.

type Ctx

type Ctx = server.Ctx

Ctx is the runtime context with full HTTP/navigation/session access. This is server.Ctx - the rich context that includes Path(), Param(), Query(), QueryParam(), Navigate(), User(), Session(), etc.

func UseCtx

func UseCtx() Ctx

UseCtx returns the current runtime context. Returns nil if called outside of a render/effect/handler context.

Example:

func MyComponent() vango.Component {
    return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
        return func() *vango.VNode {
            ctx := vango.UseCtx()
            path := ctx.Path()
            userId := ctx.Param("id")
            search := ctx.QueryParam("q")
            return Div(Text(path))
        }
    })
}

type DragEvent

type DragEvent = corevango.DragEvent

type DropEvent

type DropEvent = corevango.DropEvent

type EventRateLimitConfig

type EventRateLimitConfig = corevango.EventRateLimitConfig

EventRateLimitConfig configures token bucket rate limiting for events.

func DefaultDOMEventRateLimitConfig

func DefaultDOMEventRateLimitConfig() *EventRateLimitConfig

DefaultDOMEventRateLimitConfig returns a default rate limit for standard DOM events.

func DefaultEventRateLimitConfig

func DefaultEventRateLimitConfig() *EventRateLimitConfig

DefaultEventRateLimitConfig returns a conservative default rate limit.

type Form

type Form[T any] = form.Form[T]

Form is a type-safe form handler with validation support.

type FormData

type FormData = corevango.FormData

func NewFormData

func NewFormData(values map[string][]string) FormData

func NewFormDataFromSingle

func NewFormDataFromSingle(values map[string]string) FormData

type FormErrors added in v0.1.0

type FormErrors = corevango.FormErrors

type FormResult added in v0.1.0

type FormResult = corevango.FormResult

type GlobalBroadcastBackend

type GlobalBroadcastBackend = corevango.GlobalBroadcastBackend

GlobalBroadcastBackend broadcasts updates to other instances.

func NewMemoryPubSub

func NewMemoryPubSub() GlobalBroadcastBackend

NewMemoryPubSub creates an in-memory broadcast backend.

func NewRedisPubSub

func NewRedisPubSub(client *redis.Client) GlobalBroadcastBackend

NewRedisPubSub creates a Redis-backed broadcast backend.

func ParsePubSubURL

func ParsePubSubURL(raw string) (GlobalBroadcastBackend, error)

ParsePubSubURL creates a GlobalBroadcastBackend from a URL.

type HTTPError

type HTTPError = corevango.HTTPError

type Handler

type Handler = corevango.Handler

Handler handles a specific resource state in Match().

func OnError

func OnError(fn func(error) *vdom.VNode) Handler

OnError handles the Error state in Resource.Match(). Error is when the fetch failed.

Example:

users.Match(
    vango.OnError(func(err error) *vango.VNode {
        return Div(Class("error"), Textf("Failed: %v", err))
    }),
    // ...
)

func OnLoading

func OnLoading(fn func() *vdom.VNode) Handler

OnLoading handles the Loading state in Resource.Match(). Loading is when a fetch is in progress.

Example:

users.Match(
    vango.OnLoading(func() *vango.VNode {
        return Div(Class("spinner"), Text("Loading..."))
    }),
    // ...
)

func OnLoadingOrPending

func OnLoadingOrPending(fn func() *vdom.VNode) Handler

OnLoadingOrPending handles both Loading and Pending states in Resource.Match(). This is a convenience handler for showing a spinner during any waiting state.

Example:

users.Match(
    vango.OnLoadingOrPending(func() *vango.VNode {
        return Spinner() // Show spinner for both pending and loading
    }),
    vango.OnError(handleError),
    vango.OnReady(renderUsers),
)

func OnPending

func OnPending(fn func() *vdom.VNode) Handler

OnPending handles the Pending state in Resource.Match(). Pending is the initial state before the first fetch begins.

Example:

users.Match(
    vango.OnPending(func() *vango.VNode {
        return Div(Text("Initializing..."))
    }),
    // ...
)

func OnReady

func OnReady[T any](fn func(T) *vdom.VNode) Handler

OnReady handles the Ready state in Resource.Match(). Ready is when data has been successfully loaded.

Example:

users.Match(
    vango.OnReady(func(users []User) *vango.VNode {
        return Ul(mapUsers(users)...)
    }),
)

type HookEvent

type HookEvent = corevango.HookEvent

type HookEventValidator

type HookEventValidator = corevango.HookEventValidator

HookEventValidator validates a hook event payload.

func HookSchemaValidator

func HookSchemaValidator[T any](validate func(HookEvent, T) error) HookEventValidator

HookSchemaValidator builds a HookEventValidator that decodes hook payload data into a typed schema using strict JSON rules.

func HookValidatorMap added in v0.2.0

func HookValidatorMap(validators map[string]HookEventValidator) HookEventValidator

HookValidatorMap dispatches hook validation by exact event name.

type HostedSurfaceSecurityConfig added in v0.2.0

type HostedSurfaceSecurityConfig struct {
	Enabled bool

	// ProofSecret verifies X-Vango-Surface-Proof-* headers sent by the native
	// host. Use 32+ random bytes and keep it separate from TokenSecret.
	ProofSecret []byte

	// TokenSecret signs server-minted hosted auth bootstrap tokens. It must be
	// stable and server-only in non-dev mode.
	TokenSecret []byte

	// AllowedOrigins lists the trusted hosted web origins that may receive
	// native hosted surface bootstrap.
	AllowedOrigins []string
}

HostedSurfaceSecurityConfig configures signed hosted/native surface verification for first-party hosted native targets.

func HostedSurfaceSecurityFromEnv added in v0.2.0

func HostedSurfaceSecurityFromEnv(allowedOrigins ...string) HostedSurfaceSecurityConfig

HostedSurfaceSecurityFromEnv returns declarative hosted surface security using Vango's standard hosted macOS environment variables.

type InputEvent

type InputEvent = corevango.InputEvent

type IslandMessage

type IslandMessage = corevango.IslandMessage

IslandMessage is a message sent between an island and the server.

type IslandMessageValidator

type IslandMessageValidator = corevango.IslandMessageValidator

IslandMessageValidator validates an island message payload.

func IslandSchemaValidator

func IslandSchemaValidator[T any](validate func(IslandMessage, T) error) IslandMessageValidator

IslandSchemaValidator builds an IslandMessageValidator that decodes island payloads into a typed schema using strict JSON rules.

func IslandValidatorMap added in v0.2.0

func IslandValidatorMap(validators map[string]IslandMessageValidator) IslandMessageValidator

IslandValidatorMap dispatches island validation by exact island ID.

type KeyMod added in v0.1.0

type KeyMod = corevango.KeyMod

type KeyboardEvent

type KeyboardEvent = corevango.KeyboardEvent

type LayoutHandler

type LayoutHandler = func(Ctx, Slot) *VNode

LayoutHandler wraps child content in a layout. Receives the render context and the slot containing child content.

func Layout(ctx vango.Ctx, children vango.Slot) *vango.VNode {
    return Html(
        Head(...),
        Body(children),
    )
}

type Memo

type Memo[T any] = corevango.Memo[T]

type MetricsSink

type MetricsSink = corevango.MetricsSink

MetricsSink is the interface used for runtime metric emission.

type ModifiedHandler

type ModifiedHandler = corevango.ModifiedHandler

func Capture added in v0.1.0

func Capture(handler any) ModifiedHandler

func Debounce added in v0.1.0

func Debounce(duration time.Duration, handler any) ModifiedHandler

func Hotkey added in v0.1.0

func Hotkey(key string, handler any) ModifiedHandler

func KeyWithModifiers added in v0.1.0

func KeyWithModifiers(key string, mods KeyMod, handler any) ModifiedHandler

func Keys added in v0.1.0

func Keys(keys []string, handler any) ModifiedHandler

func Once added in v0.1.0

func Once(handler any) ModifiedHandler

func Passive added in v0.1.0

func Passive(handler any) ModifiedHandler

func PreventDefault

func PreventDefault(handler any) ModifiedHandler

func Self added in v0.1.0

func Self(handler any) ModifiedHandler

func StopPropagation added in v0.1.0

func StopPropagation(handler any) ModifiedHandler

func Throttle added in v0.1.0

func Throttle(duration time.Duration, handler any) ModifiedHandler

type MouseEvent

type MouseEvent = corevango.MouseEvent
type NavigateEvent = corevango.NavigateEvent
type NavigateOption = server.NavigateOption

NavigateOption configures programmatic navigation.

type NoProps

type NoProps = corevango.NoProps

NoProps is the canonical empty-props type.

type ObservabilityConfig

type ObservabilityConfig = corevango.ObservabilityConfig

ObservabilityConfig configures optional observability features.

type PageHandler

type PageHandler = any

PageHandler is a function that renders a page. Two signatures are supported:

  • func(ctx Ctx) *VNode - static page with no route params
  • func(ctx Ctx, params P) *VNode - dynamic page with typed params struct

For dynamic pages, the params struct uses `param` tags to map route parameters:

type ShowParams struct {
    ID int `param:"id"`
}
func ShowPage(ctx vango.Ctx, p ShowParams) *vango.VNode { ... }

type PagedResponse

type PagedResponse[T any] = corevango.PagedResponse[T]

PagedResponse is the standard paginated response payload wrapper.

type Principal added in v0.0.2

type Principal = auth.Principal

Principal is the authenticated principal type used by AuthCheck callbacks and Ctx principal accessors.

type Props

type Props = vdom.Props

Props holds attributes and event handlers.

type PropsCell

type PropsCell[P any] = corevango.PropsCell[P]

PropsCell provides access to props with tracked and untracked reads.

type RenderFn

type RenderFn = corevango.RenderFn

RenderFn is the render closure returned by Setup callbacks.

type ResizeEvent

type ResizeEvent = corevango.ResizeEvent

type Resource

type Resource[T any] = corevango.Resource[T]

Resource manages asynchronous data fetching and state. It provides reactive state tracking (Pending → Loading → Ready | Error) and methods for matching state in templates.

Allocate resources in Setup using setup.Resource or setup.ResourceKeyed.

Example:

return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
    users := setup.Resource(&s, func(ctx context.Context) ([]User, error) {
        return api.FetchUsers(ctx)
    })
    return func() *vango.VNode {
        return users.Match(
            vango.OnLoading(func() *vango.VNode {
                return Div(Text("Loading..."))
            }),
            vango.OnError(func(err error) *vango.VNode {
                return Div(Textf("Error: %v", err))
            }),
            vango.OnReady(func(users []User) *vango.VNode {
                return Ul(mapUsers(users)...)
            }),
        )
    }
})

type ResourceOption

type ResourceOption = corevango.ResourceOption

ResourceOption configures Resource behavior in Setup helpers.

func OnResourceError

func OnResourceError(fn func(error)) ResourceOption

OnResourceError registers an error callback for resource loads.

func OnResourceSuccess

func OnResourceSuccess(fn func(any)) ResourceOption

OnResourceSuccess registers a success callback for resource loads.

func RetryOnError

func RetryOnError(count int, delay time.Duration) ResourceOption

RetryOnError configures retry count and delay.

func StaleTime

func StaleTime(d time.Duration) ResourceOption

StaleTime sets the duration before data is considered stale.

type ResourceState

type ResourceState = corevango.State

ResourceState represents the current state of a resource.

const (
	Pending ResourceState = corevango.Pending // Initial state, before first fetch
	Loading ResourceState = corevango.Loading // Fetch in progress
	Ready   ResourceState = corevango.Ready   // Data successfully loaded
	Error   ResourceState = corevango.Error   // Fetch failed (distinct from vango.Error)
)

State constants for Resource. These are spec-aligned exports: use vango.Pending, vango.Loading, etc.

type Response

type Response[T any] = corevango.Response[T]

Response wraps an API payload with optional metadata and HTTP status.

func Accepted

func Accepted[T any](data T) *Response[T]

Accepted creates a 202 Accepted typed API response.

func Created

func Created[T any](data T) *Response[T]

Created creates a 201 Created typed API response.

func NoContent

func NoContent[T any]() *Response[T]

NoContent creates a 204 No Content typed API response.

func OK

func OK[T any](data T) *Response[T]

OK creates a 200 OK typed API response.

func Paginated

func Paginated[T any](items []T, page, perPage, total int) *Response[PagedResponse[T]]

Paginated creates a paginated 200 OK typed API response.

type RouteMiddleware

type RouteMiddleware = router.Middleware

RouteMiddleware processes requests before they reach handlers.

type RouteMiddlewareFunc

type RouteMiddlewareFunc = router.MiddlewareFunc

RouteMiddlewareFunc is a function adapter for RouteMiddleware.

Prefer this over importing github.com/vango-go/vango/pkg/router directly.

type RuntimeUnsafePermissions added in v0.2.0

type RuntimeUnsafePermissions = vdom.RuntimeUnsafePermissions

type SSRConfig

type SSRConfig struct {
	// EnableResourcePreload controls whether Resources are executed during SSR renders.
	//
	// When enabled, Setup component one-shot renders will:
	//   - run setup-registered pending effects (on an SSR single-writer loop)
	//   - wait for Resources to reach Ready/Error (bounded by ResourceTimeout)
	//
	// This improves progressive enhancement: SSR output can include loaded data
	// even before a WebSocket session mounts.
	//
	// Default: true.
	EnableResourcePreload *bool

	// PageTimeout bounds the total SSR page render budget.
	//
	// This deadline flows through ctx.StdContext() during SSR and therefore caps:
	//   - route middleware
	//   - page handlers
	//   - layout assembly
	//   - HTML rendering
	//
	// 0 disables the framework-level SSR page deadline.
	//
	// Default: 5s.
	PageTimeout *time.Duration

	// ResourceTimeout bounds SSR resource preloading time only.
	//
	// When > 0, SSR-started resource fetches use a child context derived from
	// the page context and capped by this timeout. SSR waits on that same
	// preload budget.
	//
	// 0 disables waiting, but resources may still start opportunistically
	// during SSR against the page context.
	//
	// Default: 300ms.
	ResourceTimeout *time.Duration
}

SSRConfig configures server-side rendering behavior (HTTP GET renders).

type ScriptsOption added in v0.0.3

type ScriptsOption = vdom.ScriptsOption

ScriptsOption configures runtime script rendering helpers.

func WithAllowInsecureModuleOrigins added in v0.0.3

func WithAllowInsecureModuleOrigins() ScriptsOption

WithAllowInsecureModuleOrigins allows http: module imports on https: pages.

func WithAllowInsecureModuleOriginsAcknowledged added in v0.2.0

func WithAllowInsecureModuleOriginsAcknowledged(token string) ScriptsOption

WithAllowInsecureModuleOriginsAcknowledged allows insecure module origins with an explicit acknowledgement token.

func WithAllowSrcdoc added in v0.0.3

func WithAllowSrcdoc() ScriptsOption

WithAllowSrcdoc permits srcdoc updates on the thin client.

func WithAllowUnsafeRawHTML added in v0.0.3

func WithAllowUnsafeRawHTML() ScriptsOption

WithAllowUnsafeRawHTML disables raw HTML sanitization on the thin client.

func WithAllowUnsafeRawHTMLAcknowledged added in v0.2.0

func WithAllowUnsafeRawHTMLAcknowledged(token string) ScriptsOption

WithAllowUnsafeRawHTMLAcknowledged disables thin-client raw HTML sanitization with an explicit acknowledgement token.

func WithCSRFToken added in v0.0.3

func WithCSRFToken(token string) ScriptsOption

WithCSRFToken injects a CSRF token on the runtime script tag.

func WithDebug added in v0.0.3

func WithDebug() ScriptsOption

WithDebug enables client debug mode when rendering runtime scripts.

func WithModuleOrigins added in v0.0.3

func WithModuleOrigins(origins ...string) ScriptsOption

WithModuleOrigins sets allowed cross-origin module import origins.

func WithRuntimeUnsafePermissions added in v0.2.0

func WithRuntimeUnsafePermissions(perms RuntimeUnsafePermissions) ScriptsOption

WithRuntimeUnsafePermissions injects validated runtime unsafe permissions.

func WithScriptPath added in v0.0.3

func WithScriptPath(path string) ScriptsOption

WithScriptPath sets a custom thin-client script path.

func WithoutDefer added in v0.0.3

func WithoutDefer() ScriptsOption

WithoutDefer removes the defer attribute from the runtime script tag.

type ScrollEvent

type ScrollEvent = corevango.ScrollEvent

type SecurityConfig

type SecurityConfig struct {
	// CSRFSecret is the secret key for CSRF token generation.
	// If nil and CSRF is enabled in non-DevMode, a random secret is generated
	// at startup (tokens won't survive server restarts).
	// To disable CSRF protection entirely, set CSRFEnabled = false explicitly.
	// For production, prefer a stable 32+ byte secret generated with crypto/rand and stored securely.
	CSRFSecret []byte

	// CSRFEnabled enables CSRF protection for state-changing HTTP endpoints.
	// Default: true.
	CSRFEnabled bool

	// AllowedOrigins lists allowed WebSocket origins (scheme + host + optional port).
	// Entries must not include path, query, or fragment.
	// If empty and AllowSameOrigin is true, only same-origin requests are allowed.
	// Example: []string{"https://myapp.com", "https://www.myapp.com"}
	AllowedOrigins []string

	// CustomOriginCheck allows a custom WebSocket origin validation function.
	// Requires AllowCustomOriginPolicy to be true in production.
	CustomOriginCheck func(r *http.Request) bool

	// AllowedRedirectHosts lists hostnames (and optional ports) allowed for
	// external redirects.
	// Hostname-only entries authorize only the default ports (80 for http, 443
	// for https). Use host:port for non-default ports.
	// When empty, external redirects are rejected.
	// Example: []string{"accounts.google.com", "auth.mycompany.com", "auth.mycompany.com:8443"}
	AllowedRedirectHosts []string

	// HostedSurfaceVerifier validates trusted hosted/native surface identity for
	// page requests. When nil, raw hosted headers/query metadata are treated as
	// untrusted hints only.
	HostedSurfaceVerifier server.HostedSurfaceVerifyFunc

	// HostedSurfaceTokenSecret signs short-lived hosted-auth bootstrap tokens for
	// verified hosted surfaces. Use 32+ random bytes in non-dev mode.
	HostedSurfaceTokenSecret []byte

	// HostedSurface declaratively wires signed first-party hosted/native
	// surface verification. This is the preferred setup for hosted native
	// macOS and iOS targets; HostedSurfaceVerifier remains available for custom
	// verification.
	HostedSurface HostedSurfaceSecurityConfig

	// AllowDevModeInNonLocalEnvironment acknowledges the security tradeoff of
	// enabling DevMode alongside non-local / production-like server settings.
	AllowDevModeInNonLocalEnvironment bool

	// DevModeRiskAcceptance is a required explicit acknowledgement token for
	// DevMode with non-local / production-like config.
	DevModeRiskAcceptance string

	// AllowedHosts lists hostnames (and optional ports) that are valid for this
	// server.
	// Hostname-only entries authorize only the request scheme's default port
	// (80 for insecure requests, 443 for secure requests). Use host:port for
	// non-default ports.
	// When configured outside DevMode, App.ServeHTTP rejects requests with
	// unapproved Host headers before routing to pages, APIs, uploads, static
	// files, or runtime endpoints. Also used by WebSocketURL() and default CSP
	// websocket-origin injection to prevent Host header poisoning attacks. If
	// empty in production (non-DevMode), WebSocketURL() returns empty (fail
	// secure), and app-level request routing remains compatible with deployments
	// that enforce hosts at an external proxy.
	// Example: []string{"myapp.com", "www.myapp.com", "myapp.com:8443"}
	AllowedHosts []string

	// CanonicalHost is the preferred hostname for URL generation.
	// This must be host or host:port.
	// When set, WebSocketURL() and default CSP websocket-origin injection use
	// this host instead of the request host.
	// Useful for normalizing "www" vs non-"www" variants.
	CanonicalHost string

	// PublicRuntimePrefix is the public mount prefix used when generating thin-client
	// runtime endpoint URLs such as the live websocket path and client script URL.
	//
	// Examples:
	//   ""     -> /_vango/live and /_vango/client.js
	//   "/app" -> /app/_vango/live and /app/_vango/client.js
	//
	// This affects generated public URLs only. If you mount Vango under a subpath,
	// your external router or reverse proxy is still responsible for applying or
	// stripping that prefix before requests reach the app.
	PublicRuntimePrefix string

	// AllowSameOrigin enables automatic same-origin validation.
	// When true and AllowedOrigins is empty, validates that Origin header
	// matches the request Host header.
	// Default: true.
	AllowSameOrigin bool

	// AllowCustomOriginPolicy permits CustomOriginCheck without AllowedOrigins or AllowSameOrigin.
	// SECURITY: avoid this in production unless you fully understand your policy.
	AllowCustomOriginPolicy bool

	// TrustedProxies lists reverse proxy IPs trusted for X-Forwarded-* headers.
	// When set, forwarded proto headers are honored for secure cookie decisions.
	// Default: nil (do not trust forwarded headers).
	TrustedProxies []string

	// CookieSecure sets the Secure flag on cookies set by the server.
	// Should be true when using HTTPS.
	// Default: true.
	CookieSecure bool

	// CookieHttpOnly sets the HttpOnly flag on cookies set by the server.
	// Prevents JavaScript access to cookies that should not be read by JS.
	// Default: true (except for CSRF cookies which need JS access).
	CookieHttpOnly bool

	// CookieSameSite sets the SameSite attribute for cookies set by the server.
	// Lax is safe for most use cases and allows OAuth redirect flows.
	// Default: http.SameSiteLaxMode.
	CookieSameSite http.SameSite

	// CookieDomain sets the Domain attribute for cookies.
	// Empty string uses the current domain (most secure).
	// Default: "".
	CookieDomain string

	// SecurityHeaders configures default HTTP security headers.
	SecurityHeaders SecurityHeadersConfig

	// URLPolicy controls scheme allowlists for URL-bearing attributes rendered by the server.
	// If nil, defaults are used (href: http/https/mailto/tel/sms; resource/action: http/https).
	// AllowSrcdoc and AllowUnsafeRawHTML are false by default and must be explicitly enabled.
	URLPolicy *URLPolicyConfig

	// AllowUnsafeRawHTMLInProduction acknowledges the security tradeoff of disabling
	// framework raw-HTML sink sanitization in non-DevMode.
	//
	// When false (default), non-Dev configs that set URLPolicy.AllowUnsafeRawHTML are rejected.
	//
	// SECURITY: AllowUnsafeRawHTML can enable "gadget injection" of Vango runtime attributes
	// (hooks/islands/WASM) when attacker-controlled HTML reaches a raw sink. Use only for
	// fully trusted HTML with a strong CSP.
	AllowUnsafeRawHTMLInProduction bool

	// UnsafeRawHTMLRiskAcceptance is a required explicit acknowledgement token for
	// non-dev raw HTML sink sanitization bypass.
	UnsafeRawHTMLRiskAcceptance string

	// AllowInsecureModuleOriginsInProduction acknowledges the security tradeoff of
	// allowing insecure http: cross-origin island/WASM module imports on https:
	// pages in non-dev mode.
	AllowInsecureModuleOriginsInProduction bool

	// InsecureModuleOriginsRiskAcceptance is a required explicit acknowledgement
	// token for non-dev insecure cross-origin module origin allowance.
	InsecureModuleOriginsRiskAcceptance string
}

SecurityConfig configures security features.

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	Enabled bool

	// CSP controls Content-Security-Policy headers.
	CSPEnabled    bool
	CSPReportOnly bool
	CSP           string
	CSPOptions    *server.CSPOptions

	// HSTS controls Strict-Transport-Security headers.
	HSTSMaxAge            time.Duration
	HSTSIncludeSubdomains bool
	HSTSPreload           bool

	// FrameOptions controls the X-Frame-Options header ("DENY" or "SAMEORIGIN").
	FrameOptions string

	// ContentTypeNosniff controls the X-Content-Type-Options header.
	ContentTypeNosniff bool

	// ReferrerPolicy controls the Referrer-Policy header.
	ReferrerPolicy string

	// PermissionsPolicy controls the Permissions-Policy header.
	PermissionsPolicy string
}

SecurityHeadersConfig configures default HTTP security headers. When Enabled is true, headers are applied unless explicitly set elsewhere.

func DefaultSecurityHeadersConfig

func DefaultSecurityHeadersConfig() SecurityHeadersConfig

DefaultSecurityHeadersConfig returns secure default HTTP header settings.

func HardenedSecurityHeadersConfig

func HardenedSecurityHeadersConfig() SecurityHeadersConfig

HardenedSecurityHeadersConfig returns a stricter security header profile. Compared to DefaultSecurityHeadersConfig, it disables inline styles in CSP.

type Session

type Session = server.Session

Session represents a client session.

type SessionConfig

type SessionConfig struct {
	// ResumeWindow is how long a disconnected session remains resumable.
	// Within this window, a reconnecting client restores full session state.
	// After this window, the session is permanently expired.
	// nil means use the default (5 minutes).
	// 0 disables resumption entirely (None tier).
	ResumeWindow *time.Duration

	// Store is the persistence backend for sessions.
	// If nil, sessions are only stored in memory (lost on server restart).
	// Use vango.NewMemoryStore(), vango.NewRedisStore(), or vango.NewSQLStore().
	Store SessionStore

	// MaxDetachedSessions is the maximum number of disconnected sessions
	// to keep in memory. When exceeded, least recently used sessions are evicted.
	// Default: 10000.
	MaxDetachedSessions int

	// MaxMemoryPerSessionBytes is the approximate in-memory cap per session.
	// Sessions exceeding this may be evicted under memory pressure.
	// 0 uses the server default.
	MaxMemoryPerSessionBytes int64

	// MaxSessionsPerIP is the maximum concurrent sessions from a single IP.
	// Helps prevent DoS attacks. 0 means no limit.
	// Default: 100.
	MaxSessionsPerIP int

	// MaxHandshakePathBytes limits the size of the `?path=` query parameter
	// used during WebSocket handshake (decoded bytes, includes query string).
	// 0 means no limit (not recommended).
	// Default: 8KB.
	MaxHandshakePathBytes int

	// EvictionPolicy determines how detached sessions are evicted when limits are exceeded.
	// Default: EvictionLRU.
	EvictionPolicy SessionEvictionPolicy

	// EvictOnIPLimit controls whether hitting MaxSessionsPerIP evicts the oldest
	// detached session for that IP instead of rejecting the new session.
	// Default: true when MaxSessionsPerIP > 0.
	EvictOnIPLimit bool

	// StormBudget configures rate limits for async primitives to prevent
	// amplification bugs (e.g., effect triggers resource refetch triggers effect).
	StormBudget *StormBudgetConfig

	// AuthCheck configures authentication freshness checks for the session.
	// When nil, no passive or active auth checks are performed.
	AuthCheck *AuthCheckConfig

	// AuthResumePolicy controls how authenticated session resumes are validated.
	//
	// Default: AuthResumePolicyStrict (requires authFunc or OnSessionResume for
	// authenticated sessions to resume).
	//
	// Set to AuthResumePolicyTrustSessionID only if you understand the security
	// implications. See server.AuthResumePolicy documentation for details.
	AuthResumePolicy AuthResumePolicy

	// AllowTrustSessionIDInProduction acknowledges the security tradeoff of
	// AuthResumePolicyTrustSessionID in non-DevMode.
	//
	// When false (default), non-Dev configs that set TrustSessionID are rejected.
	// TrustSessionID also requires:
	//   - TrustSessionIDRiskAcceptance = TrustSessionIDRiskAcceptanceV1
	//   - ResumeWindow <= 10s
	//   - Session.AuthCheck hardening:
	//     * Check configured
	//     * Interval > 0 and <= ResumeWindow
	//     * FailureMode = FailClosed
	//     * MaxStale <= ResumeWindow
	AllowTrustSessionIDInProduction bool

	// TrustSessionIDRiskAcceptance is a required explicit acknowledgement token
	// for non-Dev AuthResumePolicyTrustSessionID usage.
	//
	// Set to TrustSessionIDRiskAcceptanceV1 when you intentionally accept the
	// weaker logout/revocation semantics of TrustSessionID.
	// Default: "" (not acknowledged).
	TrustSessionIDRiskAcceptance string

	// StateBudget configures limits on persisted state size.
	// If nil, default limits are used.
	StateBudget *StateBudgetConfig

	// PersistenceSecret signs persisted blobs.
	// This includes session persistence and global-signal blobs when
	// global persistence/pubsub paths are enabled.
	// Must be 32+ bytes of cryptographically random data.
	PersistenceSecret []byte

	// PersistenceSecretPrevious allows secret rotation.
	// If set, blobs signed with this secret are accepted on resume.
	PersistenceSecretPrevious []byte

	// MaxBlobAge sets the maximum age for persisted session resume blobs.
	// Blobs older than this are rejected during resume, triggering a fresh session.
	// This applies to session resume only (not global signals).
	// It helps prevent replay attacks with stale session data.
	// 0 means no limit (default).
	MaxBlobAge time.Duration

	// HookEventValidator validates client hook event payloads.
	// Return an error to reject the event.
	// In production, startup warnings are emitted when this is unset.
	HookEventValidator HookEventValidator

	// DOMEventRateLimit applies per-session rate limiting to standard DOM events
	// (click/input/scroll/etc., including navigation).
	// RatePerSecond <= 0 disables rate limiting.
	DOMEventRateLimit *EventRateLimitConfig

	// HookEventRateLimit applies per-session rate limiting to hook events.
	// RatePerSecond <= 0 disables rate limiting.
	HookEventRateLimit *EventRateLimitConfig

	// HookEventMaxPayloadBytes limits JSON size of hook event payloads.
	// 0 means no limit.
	HookEventMaxPayloadBytes int

	// IslandMessageValidator validates island message payloads.
	// Return an error to reject the message.
	// In production, startup warnings are emitted when this is unset.
	IslandMessageValidator IslandMessageValidator

	// IslandEventRateLimit applies per-session rate limiting to island messages.
	// RatePerSecond <= 0 disables rate limiting.
	IslandEventRateLimit *EventRateLimitConfig

	// IslandEventMaxPayloadBytes limits JSON size of island message payloads.
	// 0 means no limit.
	IslandEventMaxPayloadBytes int

	// WasmMessageValidator validates WASM message payloads.
	// Return an error to reject the message.
	// In production, startup warnings are emitted when this is unset.
	WasmMessageValidator WasmMessageValidator

	// WasmEventRateLimit applies per-session rate limiting to WASM messages.
	// RatePerSecond <= 0 disables rate limiting.
	WasmEventRateLimit *EventRateLimitConfig

	// WasmEventMaxPayloadBytes limits JSON size of WASM message payloads.
	// 0 means no limit.
	WasmEventMaxPayloadBytes int

	// AllowRawHTMLInEventPayloads permits raw HTML or executable strings in
	// hook/island/WASM payloads. Default: false.
	// NOTE: Vango's unsafe-payload check is a heuristic substring filter,
	// not a sanitizer. Always validate and/or sanitize untrusted payloads.
	AllowRawHTMLInEventPayloads bool

	// AllowHeuristicEventPayloadsInProduction keeps hook/island/WASM payload
	// handling in heuristic-only mode in non-dev environments.
	//
	// This is a break-glass escape hatch. When false (default), non-dev sessions
	// reject reachable hook/island/WASM sinks unless they are covered by a
	// session-level validator or an exact-sink validated helper.
	AllowHeuristicEventPayloadsInProduction bool

	// HeuristicEventPayloadRiskAcceptance is a required explicit acknowledgement
	// token for non-dev heuristic-only hook/island/WASM payload handling.
	//
	// Set to HeuristicEventPayloadRiskAcceptanceV1 when you intentionally accept
	// heuristic-only event payload screening for reachable sinks in non-dev mode.
	HeuristicEventPayloadRiskAcceptance string
}

SessionConfig configures session behavior.

func DefaultSessionConfig

func DefaultSessionConfig() SessionConfig

DefaultSessionConfig returns a SessionConfig with sensible defaults.

type SessionEvictionPolicy

type SessionEvictionPolicy = server.SessionEvictionPolicy

SessionEvictionPolicy determines which detached sessions are evicted first.

type SessionKey

type SessionKey[T any] = corevango.SessionKey[T]

SessionKey is a typed, schema-safe session key.

func NewSessionKey

func NewSessionKey[T any](name string, opts ...SessionKeyOption[T]) *SessionKey[T]

NewSessionKey creates a typed session key with a literal name.

type SessionKeyOption

type SessionKeyOption[T any] = corevango.SessionKeyOption[T]

SessionKeyOption configures a SessionKey.

func Default

func Default[T any](v T) SessionKeyOption[T]

Default sets the default value for a SessionKey.

type SessionStore

type SessionStore = session.SessionStore

SessionStore is the interface for session persistence backends.

type SetupCtx

type SetupCtx[P any] = corevango.SetupCtx[P]

SetupCtx provides setup-time access to props and request context.

type Signal

type Signal[T any] = corevango.Signal[T]

Signal type aliases

type Slot

type Slot = corevango.Slot

Slot is an opaque container for child content.

func Children

func Children(children ...any) Slot

Children constructs a Slot from heterogeneous child inputs.

type StateBudgetConfig

type StateBudgetConfig = corevango.StateBudgetConfig

StateBudgetConfig configures limits on persisted state size.

type StaticConfig

type StaticConfig struct {
	// Dir is the directory containing static files (e.g., "public").
	// Files in this directory are served at the URL prefix.
	//
	// Vango serves static files through rooted access confined to this directory.
	// Symlinks may be followed only when they resolve within Dir. Escaping and
	// absolute-target symlinks are rejected.
	Dir string

	// Prefix is the URL path prefix for static files (e.g., "/").
	// A file at public/styles.css with Prefix="/" is served at /styles.css.
	// Default: "/".
	Prefix string

	// CacheControl determines caching behavior for static files.
	// Default: CacheControlNone (no caching headers).
	CacheControl CacheControlStrategy

	// Compression enables gzip/brotli compression for static files.
	// Default: false.
	Compression bool

	// Headers are custom headers to add to all static file responses.
	Headers map[string]string
}

StaticConfig configures static file serving.

func DefaultStaticConfig

func DefaultStaticConfig() StaticConfig

DefaultStaticConfig returns a StaticConfig with sensible defaults.

type StormBudgetConfig

type StormBudgetConfig = server.StormBudgetConfig

StormBudgetConfig configures rate limits for async primitives. These limits help prevent amplification bugs where effects cascade into more effects, potentially causing performance issues.

type Touch

type Touch = corevango.Touch

type TouchEvent

type TouchEvent = corevango.TouchEvent

type TransitionEvent

type TransitionEvent = corevango.TransitionEvent

type URLEncoding

type URLEncoding = urlparam.Encoding

URLEncoding specifies how complex types are serialized to URLs.

const (
	// URLEncodingFlat serializes structs as flat params: ?cat=tech&sort=asc
	URLEncodingFlat URLEncoding = urlparam.EncodingFlat

	// URLEncodingJSON serializes as base64-encoded JSON: ?filter=eyJjYXQiOiJ0ZWNoIn0
	URLEncodingJSON URLEncoding = urlparam.EncodingJSON

	// URLEncodingComma serializes arrays as comma-separated: ?tags=go,web,api
	URLEncodingComma URLEncoding = urlparam.EncodingComma
)

type URLParamOption

type URLParamOption = urlparam.URLParamOption

URLParamOption configures URL parameter behavior.

var (
	// Push creates a new history entry (default behavior).
	Push URLParamOption = urlparam.Push

	// Replace updates URL without creating history entry (use for filters, search).
	Replace URLParamOption = urlparam.Replace
)

URL parameter mode options

func Encoding

func Encoding(e URLEncoding) URLParamOption

Encoding sets the URL encoding mode for complex types.

Example:

filters := setup.URLParam(&s, "", Filters{}, vango.Encoding(vango.URLEncodingFlat))

func URLDebounce

func URLDebounce(d time.Duration) URLParamOption

Debounce delays URL updates by the specified duration. Use this for search inputs to avoid spamming the history.

Example:

search := setup.URLParam(&s, "q", "", vango.Replace, vango.URLDebounce(300*time.Millisecond))

type URLPolicyConfig

type URLPolicyConfig struct {
	// AllowedHrefSchemes controls href/xlink:href schemes.
	// Empty or nil uses the defaults.
	AllowedHrefSchemes []string

	// AllowedResourceSchemes controls src/poster/srcset schemes.
	// Empty or nil uses the defaults.
	AllowedResourceSchemes []string

	// AllowedActionSchemes controls action/formaction schemes.
	// Empty or nil uses the resource schemes.
	AllowedActionSchemes []string

	// AllowSrcdoc enables server-side rendering of srcdoc attributes.
	// Client-side still requires allowSrcdoc to be enabled.
	AllowSrcdoc bool

	// AllowUnsafeRawHTML disables framework raw-HTML sanitization for
	// DangerouslySetInnerHTML/Raw and ResyncFull application on the client.
	// Default: false (sanitize raw HTML).
	//
	// SECURITY: Enabling this allows raw HTML to bypass framework sanitization.
	// Use only for fully trusted internal HTML with a strong CSP.
	AllowUnsafeRawHTML bool
}

URLPolicyConfig configures allowed schemes for URL-bearing attributes.

type UnsafeConfigCode added in v0.2.0

type UnsafeConfigCode = server.UnsafeConfigCode

type UnsafeConfigEntry added in v0.2.0

type UnsafeConfigEntry = server.UnsafeConfigEntry

type UnsafeConfigReport added in v0.2.0

type UnsafeConfigReport = server.UnsafeConfigReport

type UnsafeConfigSeverity added in v0.2.0

type UnsafeConfigSeverity = server.UnsafeConfigSeverity

type UnsafeConfigState added in v0.2.0

type UnsafeConfigState = server.UnsafeConfigState

type VKind

type VKind = vdom.VKind

VKind is the node type discriminator.

type VNode

type VNode = vdom.VNode

VNode represents a virtual DOM node.

func RuntimeScripts added in v0.0.3

func RuntimeScripts(ctx Ctx, opts ...ScriptsOption) *VNode

RuntimeScripts renders the thin-client runtime script plus canonical bootstrap JSON.

For ordinary browser requests this emits a normalized browser/web bootstrap. Adapters such as the macOS desktop runtime can inject richer bootstrap state into the request context, and this helper will carry it through automatically. When the current request has a CSRF token, RuntimeScripts also carries it onto the runtime script tag so the thin client can complete its handshake without requiring inline scripts in CSP.

type ValidationError

type ValidationError = form.ValidationError

ValidationError represents a validation failure.

type Validator

type Validator = form.Validator

Validator is an interface for form field validation.

func Alpha

func Alpha(msg string) Validator

Alpha validates that the value contains only ASCII letters.

func AlphaNumeric

func AlphaNumeric(msg string) Validator

AlphaNumeric validates that the value contains only letters and digits.

func Between

func Between(min, max any, msg string) Validator

Between validates that a numeric value is between min and max (inclusive).

func Custom

func Custom(fn func(value any) error) Validator

Custom creates a validator from a custom function.

func DateAfter

func DateAfter(t time.Time, msg string) Validator

DateAfter validates that a date/time is after the given time.

func DateBefore

func DateBefore(t time.Time, msg string) Validator

DateBefore validates that a date/time is before the given time.

func Email

func Email(msg string) Validator

Email validates that the value is a valid email address.

func Future

func Future(msg string) Validator

Future validates that a date/time is in the future.

func Max

func Max(n any, msg string) Validator

Max validates that a numeric value is <= n.

func MaxLength

func MaxLength(n int, msg string) Validator

MaxLength validates that a string has at most n characters.

func Min

func Min(n any, msg string) Validator

Min validates that a numeric value is >= n.

func MinLength

func MinLength(n int, msg string) Validator

MinLength validates that a string has at least n characters.

func NonNegative

func NonNegative(msg string) Validator

NonNegative validates that a numeric value is >= 0.

func Numeric

func Numeric(msg string) Validator

Numeric validates that the value contains only digits.

func Past

func Past(msg string) Validator

Past validates that a date/time is in the past.

func Pattern

func Pattern(pattern, msg string) Validator

Pattern validates that a string matches the given regular expression.

func Phone

func Phone(msg string) Validator

Phone validates that the value looks like a phone number.

func Positive

func Positive(msg string) Validator

Positive validates that a numeric value is > 0.

func Required

func Required(msg string) Validator

Required validates that the value is non-empty.

func URL

func URL(msg string) Validator

URL validates that the value is a valid URL.

func UUID

func UUID(msg string) Validator

UUID validates that the value is a valid UUID.

type ValidatorFunc

type ValidatorFunc = form.ValidatorFunc

ValidatorFunc is a function that implements Validator.

type WasmMessage

type WasmMessage = corevango.WasmMessage

WasmMessage is a message sent between a WASM component and the server.

type WasmMessageValidator

type WasmMessageValidator = corevango.WasmMessageValidator

WasmMessageValidator validates a WASM message payload.

func WasmSchemaValidator

func WasmSchemaValidator[T any](validate func(WasmMessage, T) error) WasmMessageValidator

WasmSchemaValidator builds a WasmMessageValidator that decodes WASM payloads into a typed schema using strict JSON rules.

func WasmValidatorMap added in v0.2.0

func WasmValidatorMap(validators map[string]WasmMessageValidator) WasmMessageValidator

WasmValidatorMap dispatches WASM validation by exact component ID.

type WheelEvent

type WheelEvent = corevango.WheelEvent

Directories

Path Synopsis
client
cmd
vango command
vango-bench command
This file re-exports vdom attribute helpers for the el package.
This file re-exports vdom attribute helpers for the el package.
examples
Package icon provides structured SVG icon rendering for Vango apps.
Package icon provides structured SVG icon rendering for Vango apps.
internal
build
Package build provides production build functionality for Vango applications.
Package build provides production build functionality for Vango applications.
config
Package config provides configuration parsing for Vango projects.
Package config provides configuration parsing for Vango projects.
dev
Package dev provides the development server and hot reload functionality.
Package dev provides the development server and hot reload functionality.
errors
Package errors provides structured, actionable error messages for Vango.
Package errors provides structured, actionable error messages for Vango.
icon/genlucide command
tailwind
Package tailwind manages the Tailwind CSS standalone binary.
Package tailwind manages the Tailwind CSS standalone binary.
templates
Package templates provides project scaffolding templates for vango create.
Package templates provides project scaffolding templates for vango create.
pkg
assets
Package assets provides runtime resolution of fingerprinted asset paths.
Package assets provides runtime resolution of fingerprinted asset paths.
auth
Package auth provides type-safe authentication helpers for Vango.
Package auth provides type-safe authentication helpers for Vango.
auth/sessionauth
Package sessionauth provides a session-first auth adapter for Vango.
Package sessionauth provides a session-first auth adapter for Vango.
authmw
Package authmw provides route-level authentication/authorization middleware.
Package authmw provides route-level authentication/authorization middleware.
features
Package features provides higher-level abstractions for building Vango applications.
Package features provides higher-level abstractions for building Vango applications.
features/context
Package context provides a type-safe dependency injection mechanism for Vango applications.
Package context provides a type-safe dependency injection mechanism for Vango applications.
features/form
Package form provides type-safe form handling with validation for Vango applications.
Package form provides type-safe form handling with validation for Vango applications.
features/hooks
Package hooks provides client-side interaction hooks for Vango components.
Package hooks provides client-side interaction hooks for Vango components.
features/islands
Package islands provides JavaScript integration for Vango components.
Package islands provides JavaScript integration for Vango components.
features/optimistic
Package optimistic provides instant visual feedback for user interactions.
Package optimistic provides instant visual feedback for user interactions.
features/wasm
Package wasm provides WASM component helpers for Vango.
Package wasm provides WASM component helpers for Vango.
middleware
Package middleware provides production-grade middleware for Vango applications.
Package middleware provides production-grade middleware for Vango applications.
pref
Package pref provides user preference management with sync capabilities.
Package pref provides user preference management with sync capabilities.
protocol
Package protocol implements the binary wire protocol for Vango V2.
Package protocol implements the binary wire protocol for Vango V2.
render
Package render provides server-side rendering (SSR) for Vango components.
Package render provides server-side rendering (SSR) for Vango components.
router
Package router implements file-based routing for Vango.
Package router implements file-based routing for Vango.
server
Package server provides the server-side runtime for Vango's server-driven architecture.
Package server provides the server-side runtime for Vango's server-driven architecture.
session
Package session provides session persistence and management for Vango.
Package session provides session persistence and management for Vango.
toast
Package toast provides feedback notifications for Vango applications.
Package toast provides feedback notifications for Vango applications.
upload
Package upload provides file upload handling for Vango.
Package upload provides file upload handling for Vango.
urlparam
Package urlparam provides enhanced URL parameter synchronization for Vango.
Package urlparam provides enhanced URL parameter synchronization for Vango.
vango
Package vango provides the reactive core for the Vango framework.
Package vango provides the reactive core for the Vango framework.
vdom
Package vdom provides the Virtual DOM implementation for Vango.
Package vdom provides the Virtual DOM implementation for Vango.
vtest
Package vtest provides a deterministic, server-side harness for testing Vango components without a browser.
Package vtest provides a deterministic, server-side harness for testing Vango components without a browser.
tools

Jump to

Keyboard shortcuts

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