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
- Variables
- func AttrString(v Value) (string, bool)
- func BuildNowMS() float64
- func JSONGap(space Value) string
- func JSONStringify(v Value) (string, bool)
- func JSONStringifyGap(v Value, gap string) (string, bool)
- func JSSource(v Value) (string, bool)
- func LegacyString(v Value) string
- func LooseEquals(a, b Value) bool
- func NumberToString(f float64) string
- func ObjectKeySource(k string) string
- func ParseExprSource(src string) ast.Expr
- func ParseNumberLiteral(src string) (float64, bool)
- func Pow(x, y float64) float64
- func RenderChild(v Value) (string, error)
- func RenderRawChild(v Value) string
- func ResetBuildClock()
- func SameValueZero(a, b Value) bool
- func SetBuildClock(t time.Time)
- func SourceDateEpoch() (time.Time, bool)
- func StartBuildClock() time.Time
- func StrictEquals(a, b Value) bool
- func StringToNumber(s string) float64
- func ToAST(v Value) ast.Expr
- func ToInt32(f float64) int32
- func ToIntegerOrInfinity(f float64) float64
- func ToUint32(f float64) uint32
- type Array
- type Collection
- type DateValue
- type Function
- type Hooks
- type Interp
- func (in *Interp) Args(exprs []ast.Expr) ([]Value, Value)
- func (in *Interp) BindPattern(scope *Scope, name, pattern string, v Value) Value
- func (in *Interp) Closure(name string, params []*ast.Param, body []ast.Stmt) Value
- func (in *Interp) Declare(d *ast.VarDecl) Value
- func (in *Interp) Eval(expr ast.Expr) Value
- func (in *Interp) EvalIn(scope *Scope, expr ast.Expr) Value
- func (in *Interp) ExecBlock(stmts []ast.Stmt) (Value, bool)
- func (in *Interp) ExecStmt(stmt ast.Stmt) (v Value, failed bool)
- type Iterator
- type Kind
- type Object
- type Scope
- type ThrownError
- type UnknownChildError
- type Value
- func Add(a, b Value) Value
- func ArrayOf(elems []Value) Value
- func BigInt(decimal string) Value
- func BinaryOp(op string, a, b Value) Value
- func Bool(b bool) Value
- func Dynamic(reason string) Value
- func FromJSON(text string) (Value, bool)
- func FromLegacy(s string) Value
- func FromLiteralAST(expr ast.Expr) (Value, bool)
- func Func(name string, call func(args []Value) Value) Value
- func GetProperty(v Value, key string) Value
- func JSX(html string) Value
- func NewArray(elems ...Value) Value
- func NewDate(ms float64) Value
- func NewIterator(tag string, next func() (Value, bool)) Value
- func NewMap() Value
- func NewObject() Value
- func NewSet() Value
- func Null() Value
- func Number(f float64) Value
- func ObjectFrom(keys []string, vals map[string]Value) Value
- func ParseLiteralSource(src string) (Value, bool)
- func String(s string) Value
- func Throw(t *ThrownError) Value
- func UnaryOp(op string, a Value) Value
- func Undefined() Value
- func Unsupported(reason string) Value
- func (v Value) BoolValue() bool
- func (v Value) Call(args ...Value) Value
- func (v Value) ContainsRuntimeObject() bool
- func (v Value) ContainsUnknown() bool
- func (v Value) DateMS() (float64, bool)
- func (v Value) Elems() []Value
- func (v Value) Get(key string) (Value, bool)
- func (v Value) GoString() string
- func (v Value) HTML() string
- func (v Value) IsArray() bool
- func (v Value) IsFunction() bool
- func (v Value) IsJSX() bool
- func (v Value) IsNullish() bool
- func (v Value) IsObject() bool
- func (v Value) IsUnknown() bool
- func (v Value) IsUnsupported() bool
- func (v Value) Keys() []string
- func (v Value) Kind() Kind
- func (v Value) NumberValue() float64
- func (v Value) Push(elems ...Value)
- func (v Value) Reason() string
- func (v Value) Set(key string, val Value)
- func (v Value) SetGetter(key string, fn Value)
- func (v Value) Size() int
- func (v Value) StringValue() string
- func (v Value) Thrown() *ThrownError
- func (v Value) ToBoolean() bool
- func (v Value) ToNumber() float64
- func (v Value) ToPrimitive() Value
- func (v Value) ToString() string
- func (v Value) Truthy() (truthy, known bool)
- func (v Value) TypeOf() string
Constants ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
JSONStringifyGap is JSON.stringify(v, null, gap) for a gap string already reduced to at most ten characters (see JSONGap).
func JSSource ¶
JSSource renders a statically-known value as JavaScript source (strings single-quoted). ok=false for JSX, functions and Unknown values.
func LegacyString ¶
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 NumberToString ¶
NumberToString formats a float64 exactly like JS Number.prototype.toString() (ECMA-262 Number::toString with radix 10).
func ObjectKeySource ¶
ObjectKeySource renders an object key, quoting it unless it is a valid identifier or array index.
func ParseExprSource ¶
ParseExprSource parses a single JS expression from source text (nil on failure). Object literals are accepted without wrapping parentheses.
func ParseNumberLiteral ¶
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 RenderChild ¶
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 ¶
RenderRawChild is RenderChild without HTML escaping of text, used for content captured into raw contexts (inline <script>/<style> bodies).
func SameValueZero ¶
SameValueZero is the comparison used by Array.prototype.includes.
func SetBuildClock ¶
SetBuildClock fixes the build instant to t (tests).
func SourceDateEpoch ¶
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 ¶
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 StringToNumber ¶
StringToNumber implements ToNumber applied to a string (StringNumericLiteral).
func ToAST ¶
ToAST converts a statically-known value back to a literal AST expression (nil for JSX, functions and Unknown values).
func ToIntegerOrInfinity ¶
ToIntegerOrInfinity implements the abstract operation of the same name.
Types ¶
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 (*Interp) Args ¶
Args evaluates call arguments, expanding spreads. A non-iterable spread returns the offending value as the second result.
func (*Interp) BindPattern ¶
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 ¶
Closure builds a function value from params/body capturing the current scope. Bodies may be expression bodies (a single return) or blocks.
func (*Interp) ExecBlock ¶
ExecBlock runs statements, returning the value of the first executed return (undefined when none). returned=false when the block completed without a return statement.
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 )
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.
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 BinaryOp ¶
BinaryOp applies a non-short-circuit binary operator. Unknown operands yield Unknown; unsupported operators yield Unsupported.
func FromLegacy ¶
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 ¶
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 GetProperty ¶
GetProperty reads a property of a non-nullish value (built-in methods are returned as bound functions).
func NewIterator ¶
NewIterator returns an iterator value that calls next until it reports false.
func ObjectFrom ¶
ObjectFrom builds an object from ordered key/value pairs.
func ParseLiteralSource ¶
ParseLiteralSource parses JS literal source (as produced by JSSource or the legacy const folder) into a 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 Unsupported ¶
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) ContainsRuntimeObject ¶
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 ¶
ContainsUnknown reports whether v is Unknown or (for arrays/objects) holds an Unknown anywhere inside.
func (Value) Elems ¶
Elems returns the elements of an array value (nil otherwise). The slice is shared; callers must not mutate it.
func (Value) IsFunction ¶
IsFunction reports whether the value is callable.
func (Value) IsUnsupported ¶
IsUnsupported reports whether the value is Unknown because of an unsupported construct.
func (Value) Keys ¶
Keys returns an object's own keys in JS order: integer-like keys ascending, then string keys in insertion order.
func (Value) NumberValue ¶
NumberValue returns the payload of a number value.
func (Value) StringValue ¶
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 ¶
ToBoolean returns the JS truthiness (Unknown counts as false; check IsUnknown first when that matters).
func (Value) ToPrimitive ¶
ToPrimitive converts objects to primitives (hint "default"/"number" behave alike for plain arrays and objects: valueOf returns the object itself, so toString is used).