jsvalue

package
v0.5.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package jsvalue models JavaScript values for build-time evaluation.

The compiler folds signal-less component bodies and constant expressions at build time. Doing that with plain Go strings loses the JS type of a value (the number 0 and the string "0" both become "0", `false` renders as the text "false", and a prop string starting with "<" is mistaken for markup). Value keeps the JS type so truthiness, operators, equality and React child rendering follow JS/React semantics, and only JSX values are ever emitted as raw markup.

Index

Constants

View Source
const AwaitReason = "`await` cannot be evaluated at build time"

AwaitReason is the Unsupported reason for an `await` expression: the build-time evaluator cannot wait for a Promise. Callers report it with the dedicated server component diagnostic.

Variables

View Source
var ErrObjectChild = errors.New("objects are not valid as a JSX child")

ErrObjectChild is returned when a plain object is rendered as a JSX child (React throws "Objects are not valid as a React child").

Functions

func AttrString

func AttrString(v Value) (string, bool)

AttrString converts a value to the string an HTML attribute carries, per React: strings as-is, numbers formatted per JS, booleans as "true"/"false", arrays/objects via ToString. ok=false when React omits the attribute (null, undefined, functions) or the value is Unknown.

func BuildNowMS

func BuildNowMS() float64

BuildNowMS is the build instant as a JS time value, for hosts that hand expressions to another engine and want it to agree with this package.

func JSONGap

func JSONGap(space Value) string

JSONGap converts the third argument of JSON.stringify to its indent string: a number is that many spaces (at most ten), a string its first ten characters, anything else no indentation.

func JSONStringify

func JSONStringify(v Value) (string, bool)

JSONStringify implements JSON.stringify(v) without replacer/indent. ok=false when the result is undefined (top-level undefined or function) or the value contains Unknown parts.

func JSONStringifyGap

func JSONStringifyGap(v Value, gap string) (string, bool)

JSONStringifyGap is JSON.stringify(v, null, gap) for a gap string already reduced to at most ten characters (see JSONGap).

func JSSource

func JSSource(v Value) (string, bool)

JSSource renders a statically-known value as JavaScript source (strings single-quoted). ok=false for JSX, functions and Unknown values.

func LegacyString

func LegacyString(v Value) string

LegacyString renders a value in the compiler's historical string encoding: strings bare, numbers per JS, booleans/null/undefined as their keyword, arrays/objects as JS source, JSX as its markup, Unknown as "". It exists only for interop with string-typed APIs (attribute emission, JS codegen inputs).

func LooseEquals

func LooseEquals(a, b Value) bool

LooseEquals implements == (IsLooselyEqual).

func NumberToString

func NumberToString(f float64) string

NumberToString formats a float64 exactly like JS Number.prototype.toString() (ECMA-262 Number::toString with radix 10).

func ObjectKeySource

func ObjectKeySource(k string) string

ObjectKeySource renders an object key, quoting it unless it is a valid identifier or array index.

func ParseExprSource

func ParseExprSource(src string) ast.Expr

ParseExprSource parses a single JS expression from source text (nil on failure). Object literals are accepted without wrapping parentheses.

func ParseNumberLiteral

func ParseNumberLiteral(src string) (float64, bool)

ParseNumberLiteral parses JS numeric literal source text (as written in code): decimal, hex/octal/binary prefixes, legacy octal and numeric separators. ok=false for BigInt literals or malformed input.

func Pow

func Pow(x, y float64) float64

Pow implements ** (which differs from math.Pow for NaN and +-1 bases).

func RenderChild

func RenderChild(v Value) (string, error)

RenderChild renders a value in JSX child position with React semantics: null, undefined and booleans render nothing; strings and numbers render as escaped text; arrays render each element in order; JSX values are inserted as markup. Plain objects are an error, functions render nothing.

func RenderRawChild

func RenderRawChild(v Value) string

RenderRawChild is RenderChild without HTML escaping of text, used for content captured into raw contexts (inline <script>/<style> bodies).

func ResetBuildClock

func ResetBuildClock()

ResetBuildClock goes back to reading the live clock.

func SameValueZero

func SameValueZero(a, b Value) bool

SameValueZero is the comparison used by Array.prototype.includes.

func SetBuildClock

func SetBuildClock(t time.Time)

SetBuildClock fixes the build instant to t (tests).

func SourceDateEpoch

func SourceDateEpoch() (time.Time, bool)

SourceDateEpoch returns the time named by the SOURCE_DATE_EPOCH environment variable (integer seconds since the Unix epoch), the convention reproducible builds use. ok=false when it is unset or not an integer.

func StartBuildClock

func StartBuildClock() time.Time

StartBuildClock fixes the build instant: SOURCE_DATE_EPOCH when it is set, otherwise the current time. Call it at the start of each build.

func StrictEquals

func StrictEquals(a, b Value) bool

StrictEquals implements ===.

func StringToNumber

func StringToNumber(s string) float64

StringToNumber implements ToNumber applied to a string (StringNumericLiteral).

func ToAST

func ToAST(v Value) ast.Expr

ToAST converts a statically-known value back to a literal AST expression (nil for JSX, functions and Unknown values).

func ToInt32

func ToInt32(f float64) int32

ToInt32 implements the abstract ToInt32 operation.

func ToIntegerOrInfinity

func ToIntegerOrInfinity(f float64) float64

ToIntegerOrInfinity implements the abstract operation of the same name.

func ToUint32

func ToUint32(f float64) uint32

ToUint32 implements the abstract ToUint32 operation.

Types

type Array

type Array struct {
	Elems []Value
}

Array is a JS array.

type Collection

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

Collection is the storage of a Map or a Set: entries in insertion order with deleted ones kept as tombstones, so an iterator started earlier keeps its position when entries are added or removed (JS iteration is live).

type DateValue

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

DateValue is the state of a Date: milliseconds since the epoch, NaN when the Date is invalid.

type Function

type Function struct {
	Name string
	// Call invokes the function. It must not be nil.
	Call func(args []Value) Value
	// Props holds static members of a built-in (Number.MAX_SAFE_INTEGER).
	Props map[string]Value
	// Builtin marks a global function: a static member it does not
	// implement is unknown, not undefined.
	Builtin bool
	// Construct, when set, makes `new fn(...)` build a value (Map, Set, Date).
	Construct func(args []Value) Value
}

Function is a callable value (an arrow function closure or a built-in).

type Hooks

type Hooks struct {
	// Ident resolves an identifier that is not bound in scope.
	Ident func(name string) (Value, bool)
	// Member intercepts a member read before default evaluation.
	Member func(m *ast.MemberExpr) (Value, bool)
	// Call intercepts a call before default evaluation.
	Call func(c *ast.CallExpr) (Value, bool)
	// New intercepts a `new X(...)` expression.
	New func(n *ast.NewExpr) (Value, bool)
	// JSX renders a JSX element or fragment in the current scope.
	JSX func(expr ast.Expr) Value
}

Hooks customize evaluation for a host (the SSR evaluator, the IR const folder). Every hook is optional; a hook returning ok=false falls through to the default behavior.

type Interp

type Interp struct {
	Hooks Hooks
	// Scope is the current lexical scope. It is swapped while a closure runs,
	// so hooks that call back into Eval see the closure's bindings.
	Scope *Scope

	// Volatile lets `new Date()`, `Date.now()` and `Math.random()` evaluate to
	// the build clock and a random number. Only a host that bakes the result
	// into HTML may set it: such a value is wrong as a constant in code that
	// runs in the browser, where it is computed again. Without it these
	// expressions are unknown, as they have no value that holds at run time.
	Volatile bool

	// StrictStatements makes an expression statement whose value is unknown
	// fail the enclosing block. Without it such a statement is skipped, which
	// is right when only a result is wanted but not when the statements are
	// run for their effects (a call that pushes an unknown value onto a list
	// has done nothing the build can see).
	StrictStatements bool
	// contains filtered or unexported fields
}

Interp evaluates expressions to Values.

func New

func New(hooks Hooks) *Interp

New returns an interpreter with a fresh root scope.

func (*Interp) Args

func (in *Interp) Args(exprs []ast.Expr) ([]Value, Value)

Args evaluates call arguments, expanding spreads. A non-iterable spread returns the offending value as the second result.

func (*Interp) BindPattern

func (in *Interp) BindPattern(scope *Scope, name, pattern string, v Value) Value

BindPattern binds a parameter or declaration target (a plain name, or an object/array destructuring pattern given as source text) to v in scope. Returns Unsupported for patterns it cannot parse.

func (*Interp) Closure

func (in *Interp) Closure(name string, params []*ast.Param, body []ast.Stmt) Value

Closure builds a function value from params/body capturing the current scope. Bodies may be expression bodies (a single return) or blocks.

func (*Interp) Declare

func (in *Interp) Declare(d *ast.VarDecl) Value

Declare evaluates a variable declaration into the current scope.

func (*Interp) Eval

func (in *Interp) Eval(expr ast.Expr) Value

Eval evaluates an expression in the current scope.

func (*Interp) EvalIn

func (in *Interp) EvalIn(scope *Scope, expr ast.Expr) Value

EvalIn evaluates expr in scope (restoring the previous scope afterwards).

func (*Interp) ExecBlock

func (in *Interp) ExecBlock(stmts []ast.Stmt) (Value, bool)

ExecBlock runs statements, returning the value of the first executed return (undefined when none). returned=false when the block completed without a return statement.

func (*Interp) ExecStmt

func (in *Interp) ExecStmt(stmt ast.Stmt) (v Value, failed bool)

ExecStmt runs one statement in the current scope, for its effects on the bindings it can see. failed reports that the statement could not be run in full (an unsupported construct, an unknown value it needed, a throw), so the effects it had are not to be trusted.

type Iterator

type Iterator struct {
	// Tag is the Symbol.toStringTag: "Array Iterator", "Map Iterator", ...
	Tag string
	// contains filtered or unexported fields
}

Iterator is a stateful JS iterator (the value of arr.entries(), map.keys(), ...). It is consumed once: next advances it.

type Kind

type Kind uint8

Kind is the JS type of a Value.

const (
	// KindUndefined is the zero Kind, so a zero Value is undefined.
	KindUndefined Kind = iota
	// KindUnknown is a value that is not statically known at build time. It is
	// either dynamic (resolved at runtime, e.g. a signal read) or the result of
	// a construct the evaluator does not support; Reason says which.
	KindUnknown
	KindNull
	KindBool
	KindNumber
	KindString
	KindArray
	KindObject
	KindFunction
	// KindJSX is a rendered JSX element/fragment: a safe, already-escaped HTML
	// fragment. It is the only kind ever written to HTML unescaped.
	KindJSX
	// KindBigInt is a BigInt literal value (decimal digits in s). Only
	// rendering, comparison and conversion are supported; arithmetic is not.
	KindBigInt
	// KindIterator is a stateful iterator such as the result of
	// arr.entries() or map.keys(): `.next()` advances it and it is consumed
	// by for...of, spread, destructuring and Array.from.
	KindIterator
	// KindMap and KindSet are insertion-ordered collections.
	KindMap
	KindSet
	// KindDate is a Date. Build time evaluation runs in UTC, see date.go.
	KindDate
)

func (Kind) String

func (k Kind) String() string

type Object

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

Object is a JS plain object with insertion-ordered keys.

type Scope

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

Scope is a lexical scope of variable bindings.

func NewScope

func NewScope(parent *Scope) *Scope

NewScope returns a child scope of parent (nil for a root scope).

func (*Scope) Assign

func (s *Scope) Assign(name string, v Value) bool

Assign updates the nearest binding of name; ok=false when unbound.

func (*Scope) Define

func (s *Scope) Define(name string, v Value)

Define binds name in this scope.

func (*Scope) Lookup

func (s *Scope) Lookup(name string) (Value, bool)

Lookup resolves name through the scope chain.

func (*Scope) Names

func (s *Scope) Names() []string

Names returns the names bound directly in this scope.

type ThrownError

type ThrownError struct {
	// Name and Message come from an Error object (`new Error(msg)`) or a thrown
	// string (Message only).
	Name    string
	Message string
	// Line and Col locate the throw statement.
	Line, Col int
}

ThrownError describes a value thrown while evaluating at build time.

type UnknownChildError

type UnknownChildError struct{ Value Value }

UnknownChildError is returned by RenderChild for a value (or array element) that is not statically known.

func (*UnknownChildError) Error

func (e *UnknownChildError) Error() string

type Value

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

Value is an immutable handle to a JS value. Arrays and objects are reference types (like JS) so `arr.push(x)` in a statically evaluated loop is visible through every handle.

func Add

func Add(a, b Value) Value

Add implements the + operator.

func ArrayOf

func ArrayOf(elems []Value) Value

ArrayOf returns an array value holding a copy of elems.

func BigInt

func BigInt(decimal string) Value

BigInt returns a BigInt value from its decimal digits.

func BinaryOp

func BinaryOp(op string, a, b Value) Value

BinaryOp applies a non-short-circuit binary operator. Unknown operands yield Unknown; unsupported operators yield Unsupported.

func Bool

func Bool(b bool) Value

Bool returns a boolean value.

func Dynamic

func Dynamic(reason string) Value

Dynamic returns an Unknown value for something only known at runtime.

func FromJSON

func FromJSON(text string) (Value, bool)

FromJSON decodes JSON text into a Value, preserving object key order.

func FromLegacy

func FromLegacy(s string) Value

FromLegacy decodes a value from the historical string encoding. The encoding is lossy (a string "0" and the number 0 look alike), so it must only be used where no typed value is available, e.g. values produced by external string APIs. Keywords and numeric text decode to their JS types; "[...]"/"{...}" sources decode as literals; anything else is a string.

func FromLiteralAST

func FromLiteralAST(expr ast.Expr) (Value, bool)

FromLiteralAST converts a pure literal AST (literals, arrays, objects, unary minus, template literals without substitutions) to a Value. ok=false for anything that needs evaluation context.

func Func

func Func(name string, call func(args []Value) Value) Value

Func returns a function value.

func GetProperty

func GetProperty(v Value, key string) Value

GetProperty reads a property of a non-nullish value (built-in methods are returned as bound functions).

func JSX

func JSX(html string) Value

JSX returns a rendered JSX value wrapping safe HTML.

func NewArray

func NewArray(elems ...Value) Value

NewArray returns an array value holding elems (not copied).

func NewDate

func NewDate(ms float64) Value

NewDate returns a Date for the time value ms (clipped like TimeClip).

func NewIterator

func NewIterator(tag string, next func() (Value, bool)) Value

NewIterator returns an iterator value that calls next until it reports false.

func NewMap

func NewMap() Value

NewMap returns an empty Map.

func NewObject

func NewObject() Value

NewObject returns an empty object value.

func NewSet

func NewSet() Value

NewSet returns an empty Set.

func Null

func Null() Value

Null returns the null value.

func Number

func Number(f float64) Value

Number returns a number value.

func ObjectFrom

func ObjectFrom(keys []string, vals map[string]Value) Value

ObjectFrom builds an object from ordered key/value pairs.

func ParseLiteralSource

func ParseLiteralSource(src string) (Value, bool)

ParseLiteralSource parses JS literal source (as produced by JSSource or the legacy const folder) into a Value.

func String

func String(s string) Value

String returns a string value.

func Throw

func Throw(t *ThrownError) Value

Throw returns the Unknown that carries a thrown error out of evaluation. It is unsupported, so callers without error-boundary handling report it.

func UnaryOp

func UnaryOp(op string, a Value) Value

UnaryOp applies a unary operator (excluding ++/--/delete).

func Undefined

func Undefined() Value

Undefined returns the undefined value.

func Unsupported

func Unsupported(reason string) Value

Unsupported returns an Unknown value for a construct the evaluator does not implement. Callers without a runtime fallback must report it as a diagnostic.

func (Value) BoolValue

func (v Value) BoolValue() bool

BoolValue returns the payload of a boolean value.

func (Value) Call

func (v Value) Call(args ...Value) Value

Call invokes a function value. Calling a non-function yields Unsupported.

func (Value) ContainsRuntimeObject

func (v Value) ContainsRuntimeObject() bool

ContainsRuntimeObject reports whether v holds a Map, Set, Date or iterator at any depth. The build can evaluate those, but they have no literal form, so code that reaches the client must keep the original expression.

func (Value) ContainsUnknown

func (v Value) ContainsUnknown() bool

ContainsUnknown reports whether v is Unknown or (for arrays/objects) holds an Unknown anywhere inside.

func (Value) DateMS

func (v Value) DateMS() (float64, bool)

DateMS returns the time value of a Date value.

func (Value) Elems

func (v Value) Elems() []Value

Elems returns the elements of an array value (nil otherwise). The slice is shared; callers must not mutate it.

func (Value) Get

func (v Value) Get(key string) (Value, bool)

Get returns an object's own property (ok=false when absent).

func (Value) GoString

func (v Value) GoString() string

GoString aids debugging and test failure messages.

func (Value) HTML

func (v Value) HTML() string

HTML returns the markup of a JSX value ("" otherwise).

func (Value) IsArray

func (v Value) IsArray() bool

IsArray reports whether the value is an array.

func (Value) IsFunction

func (v Value) IsFunction() bool

IsFunction reports whether the value is callable.

func (Value) IsJSX

func (v Value) IsJSX() bool

IsJSX reports whether the value is rendered markup.

func (Value) IsNullish

func (v Value) IsNullish() bool

IsNullish reports whether the value is null or undefined.

func (Value) IsObject

func (v Value) IsObject() bool

IsObject reports whether the value is a plain object.

func (Value) IsUnknown

func (v Value) IsUnknown() bool

IsUnknown reports whether the value is not statically known.

func (Value) IsUnsupported

func (v Value) IsUnsupported() bool

IsUnsupported reports whether the value is Unknown because of an unsupported construct.

func (Value) Keys

func (v Value) Keys() []string

Keys returns an object's own keys in JS order: integer-like keys ascending, then string keys in insertion order.

func (Value) Kind

func (v Value) Kind() Kind

Kind returns the value's kind.

func (Value) NumberValue

func (v Value) NumberValue() float64

NumberValue returns the payload of a number value.

func (Value) Push

func (v Value) Push(elems ...Value)

Push appends to an array value in place (no-op for non-arrays).

func (Value) Reason

func (v Value) Reason() string

Reason returns why an Unknown value is unknown ("" otherwise).

func (Value) Set

func (v Value) Set(key string, val Value)

Set assigns an object property in place.

func (Value) SetGetter

func (v Value) SetGetter(key string, fn Value)

SetGetter defines an accessor property: Get calls fn with no arguments.

func (Value) Size

func (v Value) Size() int

Size returns the number of entries of a Map or Set (0 for other values).

func (Value) StringValue

func (v Value) StringValue() string

StringValue returns the payload of a string value.

func (Value) Thrown

func (v Value) Thrown() *ThrownError

Thrown returns the error when v is the result of a throw statement.

func (Value) ToBoolean

func (v Value) ToBoolean() bool

ToBoolean returns the JS truthiness (Unknown counts as false; check IsUnknown first when that matters).

func (Value) ToNumber

func (v Value) ToNumber() float64

ToNumber implements the abstract ToNumber operation.

func (Value) ToPrimitive

func (v Value) ToPrimitive() Value

ToPrimitive converts objects to primitives (hint "default"/"number" behave alike for plain arrays and objects: valueOf returns the object itself, so toString is used).

func (Value) ToString

func (v Value) ToString() string

ToString implements the abstract ToString operation.

func (Value) Truthy

func (v Value) Truthy() (truthy, known bool)

Truthy implements ToBoolean. known=false for Unknown values.

func (Value) TypeOf

func (v Value) TypeOf() string

TypeOf implements the typeof operator.

Jump to

Keyboard shortcuts

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