gov8

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 16 Imported by: 0

README

gov8 — Go bindings for V8

Go Reference windows-amd64

Embed Google's V8 JavaScript engine in Go with a typed API and a packaged Windows runtime. Applications install with go get and run without requiring Rust, Visual Studio, a C/C++ compiler, or a separate V8 download.

Highlights

  • Real V8 — execute JavaScript and WebAssembly using the engine from Chrome.
  • Go and JavaScript interop — expose Go callbacks to JavaScript and call JavaScript functions from Go.
  • Zero-build application setup — the verified Windows amd64 runtime is included in the Go module and extracted automatically.
  • Audited behavior — a pinned rusty_v8 oracle runs matching fixtures and benchmarks against the Go implementation.
  • Broad safe API coverage — isolates, contexts, handle scopes, scripts, callbacks, promises, modules, WebAssembly, snapshots, and Inspector.

The public API follows the safe executable surface of the pinned Rust v8 crate while preserving V8's explicit ownership, lifetime, and thread-affinity rules.

Requirements

gov8 currently supports Windows amd64 only. It uses the same pinned MSVC V8 artifact as the Rust reference; Windows arm64, MinGW, macOS, and Linux are not supported.

Applications using gov8 need only:

  • Go 1.24 or newer

The current engine is V8 15.2.124.1-rusty, from Rust v8 = 152.2.0.

Install

Add the module, then run your program normally:

go get github.com/maclof/gov8@latest
go run .

No Rust, Visual Studio, C compiler, PowerShell setup script, or runtime download is needed by applications. The module contains a gzip-compressed, pinned Windows amd64 shim. On first use it verifies and extracts that DLL to a content-addressed directory below the user's OS cache; later runs verify and reuse the same file. The module adds about 18 MB to a program binary and uses about 46 MB in the per-user cache.

GOV8_SHIM_DLL remains available as a trusted developer override. The file must be a matching Windows amd64 shim with the module's exact ABI:

$env:GOV8_SHIM_DLL = 'C:\path\to\gov8\build\shim\gov8_shim.dll'
go run .

Maintainers who need to rebuild the native shim or run the Rust oracle also need Rust 1.98, Visual Studio with the MSVC C++ x64 build tools, and PowerShell:

git clone https://github.com/maclof/gov8.git
Set-Location gov8
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\setup_windows.ps1
$env:GOV8_SHIM_DLL = (Resolve-Path build\shim\gov8_shim.dll)
go test ./...

The setup script downloads or reuses the pinned inputs, verifies their SHA-256 digests, and atomically writes build\shim\gov8_shim.dll.

When intentionally updating the packaged shim after a source change, rebuild it and regenerate the deterministic gzip asset:

powershell -NoProfile -ExecutionPolicy Bypass -File scripts\setup_windows.ps1
go run ./internal/cmd/package-shim

Run JavaScript

An isolate is the closest V8 equivalent to a standalone VM. A context supplies its global environment, and a scope owns temporary V8 values:

package main

import (
	"fmt"
	"log"

	gov8 "github.com/maclof/gov8"
)

func run() error {
	if err := gov8.Initialize(); err != nil {
		return err
	}
	defer gov8.Shutdown()

	iso, err := gov8.NewIsolate()
	if err != nil {
		return err
	}
	defer iso.Close()
	defer gov8.ReleaseIsolateHostState(iso)

	ctx, err := iso.NewContext()
	if err != nil {
		return err
	}
	defer ctx.Close()

	scope, err := iso.NewScope()
	if err != nil {
		return err
	}
	defer scope.Close()

	script, err := ctx.Compile(scope, `21 * 2`, nil)
	if err != nil {
		return err
	}
	defer script.Close()

	result, err := script.Run(scope, nil)
	if err != nil {
		return err
	}
	n, ok, err := result.IntegerValue(ctx)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("JavaScript result is not an integer")
	}
	fmt.Println(n) // 42
	return nil
}

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

The same program lives in examples/basic/main.go.

Call Go from JavaScript

Create a V8 function backed by a Go callback, then put it on the context's global object. This snippet assumes the iso, ctx, and scope from the previous example:

add, err := iso.NewFunction(scope, ctx,
	func(cs *gov8.CallbackScope, args gov8.FunctionCallbackArguments, rv gov8.ReturnValue) {
		if args.Length() < 2 {
			return // an unset return slot becomes JavaScript undefined
		}
		a, err := args.Get(0)
		if err != nil {
			return
		}
		b, err := args.Get(1)
		if err != nil {
			return
		}
		av, aok, err := cs.IntegerValue(a)
		if err != nil || !aok {
			return
		}
		bv, bok, err := cs.IntegerValue(b)
		if err != nil || !bok {
			return
		}
		_ = rv.SetInt32(int32(av + bv))
	}, nil)
if err != nil {
	return err
}

global, err := ctx.GlobalObject(scope)
if err != nil {
	return err
}
set, err := global.SetByName(scope, ctx, "add", add.Value)
if err != nil {
	return err
}
if !set {
	return fmt.Errorf("could not define global add")
}

script, err := ctx.Compile(scope, `add(20, 22)`, nil)
if err != nil {
	return err
}
defer script.Close()
sum, err := script.Run(scope, nil)
if err != nil {
	return err
}
sumText, err := sum.ToString(ctx)
if err != nil {
	return err
}
fmt.Println(sumText) // 42

Callback arguments, return values, and values created through CallbackScope are borrowed views valid only during that callback. Do not retain them. To turn a callback failure into a JavaScript exception, create an error with cs.NewError and pass it to cs.ThrowException.

Call JavaScript from Go

Evaluate a function, check its type, and call it with a receiver and arguments:

script, err := ctx.Compile(scope,
	`(function (name) { return "Hello, " + name + "!" })`, nil)
if err != nil {
	return err
}
defer script.Close()

value, err := script.Run(scope, nil)
if err != nil {
	return err
}
fn, ok, err := gov8.AsFunction(value, ctx)
if err != nil {
	return err
}
if !ok {
	return fmt.Errorf("script did not return a function")
}

receiver, err := scope.Undefined()
if err != nil {
	return err
}
name, err := scope.NewString("Go")
if err != nil {
	return err
}
greeting, called, err := fn.Call(scope, receiver, name)
if err != nil {
	return err
}
if !called {
	return fmt.Errorf("JavaScript function threw")
}
text, err := greeting.ToString(ctx) // "Hello, Go!"
if err != nil {
	return err
}
fmt.Println(text)

Exceptions and errors

Ordinary misuse, lifecycle failures, and uncaught JavaScript exceptions are returned as Go errors. APIs such as Compile and Run take an optional *gov8.TryCatch: pass nil when the error is enough, or pass a catcher when you need the JavaScript exception or message.

tc, err := iso.NewTryCatch()
if err != nil {
	return err
}
defer tc.Close()

script, err := ctx.Compile(scope, `throw new Error("boom")`, tc)
if err != nil {
	return err
}
defer script.Close()

if _, err := script.Run(scope, tc); err != nil {
	caught, catchErr := tc.HasCaught()
	if catchErr != nil {
		return catchErr
	}
	if caught {
		message, catchErr := tc.ExceptionText(scope, ctx)
		if catchErr != nil {
			return catchErr
		}
		fmt.Println(message) // Error: boom
	}
}

Lifetimes and threads

V8's ownership rules are visible in the API:

  • Call Initialize once before creating isolates, then call Shutdown only after every isolate is closed.
  • NewIsolate locks the creating goroutine to its OS thread. Use the isolate and close it from that same goroutine; a different isolate can run on its own goroutine.
  • Close resources in dependency order: scripts and scopes, contexts, ReleaseIsolateHostState, isolate, then the global platform.
  • Scopes must nest. Closing a scope invalidates every local Value created in it. Use persistent handles such as Global when a value must survive a scope.
  • Never retain callback-borrowed arguments, return slots, or callback-scope values after the callback returns.
  • Check every error, and check accompanying ok booleans where an operation can fail without a Go error or JavaScript can throw.

Verify and benchmark

From the repository root:

go test ./... -count=1
go test -race ./... -count=1
go vet ./...

# One quick Go benchmark smoke run.
go test . -run '^$' -bench '^BenchmarkScriptRunPrecompiledWorkload$' -benchtime=1x

# Rust oracle and benchmark smoke run.
Push-Location rust-oracle
cargo test --locked
cargo bench --locked --bench script -- --test
Pop-Location

Matched benchmark reports and their environment metadata are kept in rust-oracle/bench-results.

Project status

The current suite contains 526 normalized cross-language fixture checks: 525 are exact and 1 uses a documented safety normalization. The declaration ledger records 1,698 direct matches, 10 intentional Go-shape differences, no safe executable gaps, and 149 intentionally unexposed raw/borrowed/generic Rust shapes.

This does not mean every Rust ownership or generic type has a literal Go spelling, and it is not a performance-parity claim. The audited safe executable surface has feature and behavioral parity; intentional Go safety shapes and measured performance gaps are tracked openly. The raw CreateParams stack-limit pointer is omitted, and the oracle confirms pinned V8 overwrites it before JavaScript execution.

Contributions should include tests for success, failure, exception, lifetime, and concurrency behavior where applicable, plus matched benchmarks for hot paths.

License

gov8 is available under the MIT License. The packaged native shim also contains third-party software covered by the notices in THIRD_PARTY_NOTICES.md.

Documentation

Rendered for windows/amd64

Overview

Package gov8 provides Go bindings for Google's V8 JavaScript and WebAssembly engine.

Applications can embed JavaScript in Go using typed APIs for isolates, contexts, handle scopes, scripts, callbacks, promises, modules, WebAssembly, snapshots, and the V8 Inspector. The packaged Windows amd64 runtime works without requiring application developers to install Rust, Visual Studio, or a C/C++ compiler.

The binding uses the pinned rusty_v8 release static library for x86_64-pc-windows-msvc (v8 crate =152.2.0, engine 15.2.124.1-rusty), wrapped by a C ABI shim DLL shipped in gzip-compressed form with the module.

Supported platform

Windows amd64 only. Every file in this module carries a `//go:build windows && amd64` constraint, so building for any other target fails with "build constraints exclude all Go files" — the same deliberate single-platform stance as the Rust oracle. Applications need only Go: on first use the packaged DLL is verified and extracted to a content-addressed per-user cache. GOV8_SHIM_DLL can select a trusted ABI-compatible developer build.

Ownership and lifetime rules

  • Process: Initialize/Dispose/DisposePlatform follow the pinned crate's strict one-shot state machine; violations return errors (the crate panics — see the parity notes on gov8.Initialize). Dispose is additionally refused while any isolate is still live, and isolate creation is synchronized against teardown, so an isolate can never be created across or after Dispose.
  • Isolate: V8 isolates are thread-affine. Creating an Isolate locks the creating goroutine to its OS thread for the isolate's lifetime; every operation validates the owning thread ID and every Close must happen on that thread. There is no hidden cross-thread marshaling. The thread-id check is a misuse guard, not a capability: only the goroutine that created the isolate may call its APIs, even when another goroutine happens to be scheduled on the same OS thread.
  • Ownership: every wrapper validates that the resources it passes to the engine (scopes, contexts, TryCatches, queues, values) belong to the same isolate before crossing the ABI; cross-isolate misuse returns an error instead of reaching V8.
  • Scope: v8 local handles live in a HandleScope owned by gov8.Scope. All Values are valid only while their Scope is open; using one after Scope.Close returns an error instead of touching the engine.
  • Context/Script/MicrotaskQueue/TryCatch are engine-persistent objects with explicit Close; no finalizers are used anywhere — Close is the only correctness mechanism and leaks are visible in tests.
  • No Go pointers cross the C boundary; string/byte traffic uses pinned buffers copied during the call, and no C++ exception is ever allowed to unwind across the ABI (the shim converts them to status codes).
Example (CallJavaScriptFromGo)
package main

import (
	"fmt"

	gov8 "github.com/maclof/gov8"
)

func main() {
	ownedPlatform := false
	if !gov8.PlatformPresent() {
		if err := gov8.Initialize(); err != nil {
			panic(err)
		}
		ownedPlatform = true
	}
	if ownedPlatform {
		defer func() {
			if err := gov8.Shutdown(); err != nil {
				panic(err)
			}
		}()
	}

	iso, err := gov8.NewIsolate()
	if err != nil {
		panic(err)
	}
	defer iso.Close()
	defer gov8.ReleaseIsolateHostState(iso)

	ctx, err := iso.NewContext()
	if err != nil {
		panic(err)
	}
	defer ctx.Close()

	scope, err := iso.NewScope()
	if err != nil {
		panic(err)
	}
	defer scope.Close()

	script, err := ctx.Compile(scope,
		`(function (name) { return "Hello, " + name + "!" })`, nil)
	if err != nil {
		panic(err)
	}
	defer script.Close()
	value, err := script.Run(scope, nil)
	if err != nil {
		panic(err)
	}
	fn, ok, err := gov8.AsFunction(value, ctx)
	if err != nil || !ok {
		panic("script did not return a function")
	}
	receiver, err := scope.Undefined()
	if err != nil {
		panic(err)
	}
	name, err := scope.NewString("Go")
	if err != nil {
		panic(err)
	}
	greeting, called, err := fn.Call(scope, receiver, name)
	if err != nil || !called {
		panic("JavaScript function call failed")
	}
	text, err := greeting.ToString(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Println(text)
}
Output:
Hello, Go!
Example (ExecuteJavaScript)
package main

import (
	"fmt"

	gov8 "github.com/maclof/gov8"
)

func main() {
	ownedPlatform := false
	if !gov8.PlatformPresent() {
		if err := gov8.Initialize(); err != nil {
			panic(err)
		}
		ownedPlatform = true
	}
	if ownedPlatform {
		defer func() {
			if err := gov8.Shutdown(); err != nil {
				panic(err)
			}
		}()
	}

	iso, err := gov8.NewIsolate()
	if err != nil {
		panic(err)
	}
	defer iso.Close()
	defer gov8.ReleaseIsolateHostState(iso)

	ctx, err := iso.NewContext()
	if err != nil {
		panic(err)
	}
	defer ctx.Close()

	scope, err := iso.NewScope()
	if err != nil {
		panic(err)
	}
	defer scope.Close()

	script, err := ctx.Compile(scope, `21 * 2`, nil)
	if err != nil {
		panic(err)
	}
	defer script.Close()

	result, err := script.Run(scope, nil)
	if err != nil {
		panic(err)
	}
	n, ok, err := result.IntegerValue(ctx)
	if err != nil || !ok {
		panic("JavaScript result is not an integer")
	}
	fmt.Println(n)
}
Output:
42
Example (GoCallback)
package main

import (
	"fmt"

	gov8 "github.com/maclof/gov8"
)

func main() {
	ownedPlatform := false
	if !gov8.PlatformPresent() {
		if err := gov8.Initialize(); err != nil {
			panic(err)
		}
		ownedPlatform = true
	}
	if ownedPlatform {
		defer func() {
			if err := gov8.Shutdown(); err != nil {
				panic(err)
			}
		}()
	}

	iso, err := gov8.NewIsolate()
	if err != nil {
		panic(err)
	}
	defer iso.Close()
	defer gov8.ReleaseIsolateHostState(iso)

	ctx, err := iso.NewContext()
	if err != nil {
		panic(err)
	}
	defer ctx.Close()

	scope, err := iso.NewScope()
	if err != nil {
		panic(err)
	}
	defer scope.Close()

	add, err := iso.NewFunction(scope, ctx,
		func(cs *gov8.CallbackScope, args gov8.FunctionCallbackArguments, rv gov8.ReturnValue) {
			a, err := args.Get(0)
			if err != nil {
				return
			}
			b, err := args.Get(1)
			if err != nil {
				return
			}
			av, aok, err := cs.IntegerValue(a)
			if err != nil || !aok {
				return
			}
			bv, bok, err := cs.IntegerValue(b)
			if err != nil || !bok {
				return
			}
			_ = rv.SetInt32(int32(av + bv))
		}, nil)
	if err != nil {
		panic(err)
	}

	global, err := ctx.GlobalObject(scope)
	if err != nil {
		panic(err)
	}
	set, err := global.SetByName(scope, ctx, "add", add.Value)
	if err != nil || !set {
		panic("could not define global add")
	}

	script, err := ctx.Compile(scope, `add(20, 22)`, nil)
	if err != nil {
		panic(err)
	}
	defer script.Close()
	result, err := script.Run(scope, nil)
	if err != nil {
		panic(err)
	}
	text, err := result.ToString(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Println(text)
}
Output:
42

Index

Examples

Constants

View Source
const (
	MsgLog     uint32 = 1 << 0
	MsgDebug   uint32 = 1 << 1
	MsgInfo    uint32 = 1 << 2
	MsgError   uint32 = 1 << 3
	MsgWarning uint32 = 1 << 4
	MsgAll     uint32 = MsgLog | MsgDebug | MsgInfo | MsgError | MsgWarning
)

MessageErrorLevel bits mirror v8::Isolate::MessageErrorLevel.

View Source
const (
	// KindSnapshotCreator rejects creator-backed isolates. Unreachable
	// through this wrapper: creator isolates never present as a plain
	// *Isolate with an annex (the snapshot slice owns them); kept for
	// exhaustive matching.
	KindSnapshotCreator IntoSharedErrorKind = "snapshot_creator"
	// KindLiveWeakHandlesOrPendingFinalizers rejects isolates with live
	// weak handles or pending finalizers.
	KindLiveWeakHandlesOrPendingFinalizers = "live_weak_handles_or_pending_finalizers"
	// KindEmbedderCppHeap rejects isolates with an attached cppgc heap;
	// this module never attaches one.
	KindEmbedderCppHeap = "embedder_cpp_heap"
	// KindAnotherIsolateEntered rejects conversion while this or another
	// isolate is the thread's current one above the target.
	KindAnotherIsolateEntered = "another_isolate_entered"
)
View Source
const NoContextSnapshotIndex = ^uint64(0)

NoContextSnapshotIndex is the size_t sentinel accepted by Context::FromSnapshot. On an isolate without snapshot data it creates a fresh context, while ordinary absent indices return ok=false.

Variables

View Source
var ErrFunctionNotCacheable = errors.New("gov8: function is not a cacheable CompileFunction result")

ErrFunctionNotCacheable is returned before V8 is called when a Function did not originate from CompileFunctionAdvanced. Upstream would fatal-abort for ordinary native/script functions and access-violate for bound functions.

View Source
var ErrModuleNotCacheable = errors.New("gov8: module script is not cacheable")

ErrModuleNotCacheable is returned before reaching V8 when a caller-created zero value or a module without SourceTextModule provenance is used for cache production. Upstream CreateCodeCache requires genuine compiled provenance.

View Source
var ErrNotInitialized = errors.New("gov8: v8 platform is not initialized")

ErrNotInitialized is returned when engine work is attempted before Initialize.

View Source
var ErrSingleThreadedPlatformFlagRequired = errors.New("gov8: single-threaded platform requires the --single-threaded V8 flag")

ErrSingleThreadedPlatformFlagRequired is returned instead of admitting the pinned engine's fatal single-threaded-platform-without-flag configuration.

TypedArrayKinds lists all 12 kinds in the fixed oracle order (part of the observable contract of the typed-arrays fixture).

Functions

func ArrayLength

func ArrayLength(s *Scope, v Value) (int, error)

ArrayLength returns the length of a callback-delivered array value (e.g. the CallSite array of a PrepareStackTraceCallback).

func CRDTPCBORToJSON

func CRDTPCBORToJSON(input []byte) (result []byte, ok bool, err error)

CRDTPCBORToJSON converts CRDTP CBOR to UTF-8 JSON. ok is false for malformed input. The result never aliases native memory or input.

func CRDTPJSONToCBOR

func CRDTPJSONToCBOR(input []byte) (result []byte, ok bool, err error)

CRDTPJSONToCBOR converts UTF-8 JSON to the canonical CBOR representation used by the Chrome DevTools protocol. ok is false for malformed input. The result never aliases native memory or input.

func CachedDataVersionTag

func CachedDataVersionTag() (uint32, error)

CachedDataVersionTag returns the engine's code-cache version tag (pinned value 3252425384 for this build).

func CaptureStackTrace

func CaptureStackTrace(c *Context, s *Scope, obj Value) (bool, error)

CaptureStackTrace attaches a ".stack" property to a plain object (Exception::CaptureStackTrace). ok mirrors the engine's MaybeBool.

func ConfigureCustomPlatform

func ConfigureCustomPlatform(options CustomPlatformOptions, impl PlatformImpl) error

ConfigureCustomPlatform selects a custom task dispatcher for the next Initialize. The implementation is retained until DisposePlatform.

func ConfigurePlatform

func ConfigurePlatform(options PlatformOptions) error

ConfigurePlatform selects the platform that the next Initialize call will install. It is process-global, may be called exactly once, and must run before Initialize. If it is never called, Initialize retains its historical behavior: default platform, automatic worker count, idle tasks disabled.

func Dispose

func Dispose() (bool, error)

Dispose calls V8::Dispose. Valid only in the Initialized state and only when no isolates are live (V8 requires all isolates to be destroyed before V8::Dispose, matching the oracle's dispose semantics); otherwise it returns an error without touching the engine. After a successful Dispose no isolates may be used (the Go wrapper enforces this) and DisposePlatform must follow.

Dispose is synchronized against NewIsolate: a concurrent NewIsolate either registers its isolate first (Dispose then fails with a live-isolate error) or observes the state transition and fails — an isolate can never be created across teardown.

func DisposePlatform

func DisposePlatform() error

DisposePlatform calls V8::DisposePlatform and releases the platform created by Initialize. Valid only after Dispose.

func DrainGuaranteedWeakFinalizers

func DrainGuaranteedWeakFinalizers(i *Isolate) error

DrainGuaranteedWeakFinalizers runs every guaranteed finalizer registered on the isolate that has not run yet (its object was never collected, or collection was never forced). The pinned crate guarantees these callbacks "run before the isolate is destroyed" by draining its finalizer map inside OwnedIsolate::Drop; Go has no destructor hook for Isolate.Close, so the drain is this explicit, deterministic call: invoke it on the owning thread after the last engine work and before Isolate.Close. The documented guarantee — the callback runs before the isolate is destroyed — is preserved. Drained weaks are consumed (further use reports the usual closed errors). It is safe to call when nothing is pending.

func EnableWebAssemblyTrapHandler

func EnableWebAssemblyTrapHandler(useV8SignalHandler bool) (bool, error)

EnableWebAssemblyTrapHandler activates V8's trap-based WebAssembly bounds checks. Call it before Initialize. If useV8SignalHandler is true, V8 installs its own signal handler; otherwise the embedder is responsible for routing faults to V8. The result reports whether trap handling is available in the pinned engine build.

func ExceptionMessageText

func ExceptionMessageText(s *Scope, errValue Value) (string, error)

ExceptionMessageText formats err through Exception::CreateMessage and Message::Get — the "Uncaught Error: ..." text the engine would produce. Useful inside a PrepareStackTraceCallback for the formatted message.

func ICUGetDefaultTimeZone

func ICUGetDefaultTimeZone() (string, error)

ICUGetDefaultTimeZone returns ICU's process-wide default time-zone ID.

func ICUGetLanguageTag

func ICUGetLanguageTag() (string, error)

ICUGetLanguageTag returns ICU's process-wide default locale as a BCP 47 language tag.

func ICUSetCommonData78

func ICUSetCommonData78(data []byte) error

ICUSetCommonData78 installs an ICU 78 common-data package. ICU retains successful packages for process lifetime. gov8 therefore makes a 16-byte aligned native copy; the caller may immediately reuse or release data.

As with rusty_v8, data must contain a complete ICU common-data package.

func ICUSetDefaultLocale

func ICUSetDefaultLocale(locale string) error

ICUSetDefaultLocale sets ICU's process-wide default locale. Unlike rusty_v8, which panics while constructing a CString, Go reports interior NUL and invalid UTF-8 inputs as errors.

func ICUSetDefaultTimeZone

func ICUSetDefaultTimeZone(timeZoneID string) (accepted bool, err error)

ICUSetDefaultTimeZone installs a process-wide ICU time-zone ID. accepted is false, with the prior default unchanged, for unknown IDs and interior NULs. Invalid UTF-8 is reported as a Go error because Rust strings cannot contain it. Isolates which have observed dates must separately receive a date/time configuration change notification, matching rusty_v8's contract.

func Initialize

func Initialize() error

Initialize installs the platform selected by ConfigurePlatform, calls V8::Initialize, and prepares the default ArrayBuffer allocator. With no explicit selection it preserves the original default configuration (worker count 0, idle tasks disabled). It must be called exactly once per process; invalid lifecycle transitions are returned as errors.

func InitializeCppGCProcess

func InitializeCppGCProcess() error

InitializeCppGCProcess initializes cppgc independently of V8 for detached heap use. Go rejects duplicate initialization before rusty_v8's fatal CHECK.

func InspectorCanDispatchMethod

func InspectorCanDispatchMethod(method InspectorStringView) (bool, error)

InspectorCanDispatchMethod reports whether Inspector can dispatch the CDP method. It preserves the view's 8-bit/16-bit encoding and embedded NULs.

func IsException

func IsException(err error) bool

IsException reports whether err is a JS-observable failure (a compile or run failure recorded by a TryCatch) as opposed to a wrapper misuse error.

func IsLocked

func IsLocked(i *Isolate) bool

IsLocked reports whether the thread currently holds the engine lock for the isolate (v8::Locker::IsLocked, the pinned thread_holds_lock probe).

func Latin1ToUTF8

func Latin1ToUTF8(input, output []byte) (int, error)

Latin1ToUTF8 converts Latin-1 bytes to UTF-8 in output and returns the number of bytes written. The pinned Rust helper requires output to provide the worst-case capacity of two bytes per input byte; this safe Go shape validates that precondition and leaves output untouched on failure.

func PlatformPresent

func PlatformPresent() bool

PlatformPresent reports whether a platform has been installed by this process (same observable behavior as the oracle's get_current_platform presence check).

func ReleaseIsolateHostState

func ReleaseIsolateHostState(i *Isolate) error

ReleaseIsolateHostState releases host state attached to the isolate by host features: native-callback registrations (Go registry and the shim's per-isolate callback contexts, including their Global embedder-data handles), Wasm streaming bindings, and isolate slot values.

This is the explicit Go equivalent of the Rust destructors that run when the isolate is dropped: Go has no destructors, and a finalizer would run after engine teardown where calling it would be unsafe. Call it on the owning thread after all engine work is done and before Isolate.Close. It is safe to call twice.

func RuntimeVersionString

func RuntimeVersionString() (string, error)

RuntimeVersionString returns V8::GetVersion() from the loaded engine.

func SIMDUTFBase64LengthFromBinary

func SIMDUTFBase64LengthFromBinary(length uint64, options SIMDUTFBase64Options) (uint64, error)

SIMDUTFBase64LengthFromBinary accepts uint64 so Windows amd64 callers can observe the full size_t boundary behavior characterized by the Rust oracle.

func SIMDUTFBinaryToBase64

func SIMDUTFBinaryToBase64(input, output []byte, options SIMDUTFBase64Options) (int, error)

func SIMDUTFConvertLatin1ToUTF8

func SIMDUTFConvertLatin1ToUTF8(input, output []byte) (int, error)

func SIMDUTFConvertLatin1ToUTF16LE

func SIMDUTFConvertLatin1ToUTF16LE(input []byte, output []uint16) (int, error)

func SIMDUTFConvertUTF8ToLatin1

func SIMDUTFConvertUTF8ToLatin1(input, output []byte) (int, error)

func SIMDUTFConvertUTF8ToUTF16BE

func SIMDUTFConvertUTF8ToUTF16BE(input []byte, output []uint16) (int, error)

func SIMDUTFConvertUTF8ToUTF16LE

func SIMDUTFConvertUTF8ToUTF16LE(input []byte, output []uint16) (int, error)

func SIMDUTFConvertUTF8ToUTF32

func SIMDUTFConvertUTF8ToUTF32(input []byte, output []uint32) (int, error)

func SIMDUTFConvertUTF16BEToUTF8

func SIMDUTFConvertUTF16BEToUTF8(input []uint16, output []byte) (int, error)

func SIMDUTFConvertUTF16LEToLatin1

func SIMDUTFConvertUTF16LEToLatin1(input []uint16, output []byte) (int, error)

func SIMDUTFConvertUTF16LEToUTF8

func SIMDUTFConvertUTF16LEToUTF8(input []uint16, output []byte) (int, error)

func SIMDUTFConvertUTF32ToUTF8

func SIMDUTFConvertUTF32ToUTF8(input []uint32, output []byte) (int, error)

func SIMDUTFConvertValidUTF8ToLatin1

func SIMDUTFConvertValidUTF8ToLatin1(input, output []byte) (int, error)

func SIMDUTFConvertValidUTF8ToUTF16LE

func SIMDUTFConvertValidUTF8ToUTF16LE(input []byte, output []uint16) (int, error)

func SIMDUTFConvertValidUTF16LEToUTF8

func SIMDUTFConvertValidUTF16LEToUTF8(input []uint16, output []byte) (int, error)

func SIMDUTFCountUTF8

func SIMDUTFCountUTF8(v []byte) (int, error)

func SIMDUTFCountUTF16BE

func SIMDUTFCountUTF16BE(v []uint16) (int, error)

func SIMDUTFCountUTF16LE

func SIMDUTFCountUTF16LE(v []uint16) (int, error)

func SIMDUTFLatin1LengthFromUTF8

func SIMDUTFLatin1LengthFromUTF8(v []byte) (int, error)

func SIMDUTFMaximalBinaryLengthFromBase64

func SIMDUTFMaximalBinaryLengthFromBase64(input []byte) (int, error)

func SIMDUTFUTF8LengthFromLatin1

func SIMDUTFUTF8LengthFromLatin1(v []byte) (int, error)

func SIMDUTFUTF8LengthFromUTF16BE

func SIMDUTFUTF8LengthFromUTF16BE(v []uint16) (int, error)

func SIMDUTFUTF8LengthFromUTF16LE

func SIMDUTFUTF8LengthFromUTF16LE(v []uint16) (int, error)

func SIMDUTFUTF8LengthFromUTF32

func SIMDUTFUTF8LengthFromUTF32(v []uint32) (int, error)

func SIMDUTFUTF16LengthFromUTF8

func SIMDUTFUTF16LengthFromUTF8(v []byte) (int, error)

func SIMDUTFUTF16LengthFromUTF32

func SIMDUTFUTF16LengthFromUTF32(v []uint32) (int, error)

func SIMDUTFUTF32LengthFromUTF8

func SIMDUTFUTF32LengthFromUTF8(v []byte) (int, error)

func SIMDUTFUTF32LengthFromUTF16LE

func SIMDUTFUTF32LengthFromUTF16LE(v []uint16) (int, error)

func SIMDUTFValidateASCII

func SIMDUTFValidateASCII(input []byte) (bool, error)

func SIMDUTFValidateUTF8

func SIMDUTFValidateUTF8(input []byte) (bool, error)

func SIMDUTFValidateUTF16BE

func SIMDUTFValidateUTF16BE(input []uint16) (bool, error)

func SIMDUTFValidateUTF16LE

func SIMDUTFValidateUTF16LE(input []uint16) (bool, error)

func SIMDUTFValidateUTF32

func SIMDUTFValidateUTF32(input []uint32) (bool, error)

func Same

func Same(a, b Value) (bool, error)

Same reports whether two values are the same object (v8::Local operator==, object identity rather than handle-slot identity).

func SetEntropySource

func SetEntropySource(src EntropySource) error

SetEntropySource installs src as the process entropy source. Installed before Initialize it pins every fresh isolate's PRNG identically; called again (before or after Initialize) it replaces the previous source and still affects isolates created afterwards. A nil source is rejected.

func SetFatalErrorHandler

func SetFatalErrorHandler(h FatalErrorHandler) error

SetFatalErrorHandler installs h as the process fatal-error handler. The handler is site-specific in the pinned build: it fires for the flags-freeze CHECK and the post-OOM abort, not for every fatal site (e.g. the "Must use --expose-gc" CHECK does not call it).

func SetFlagsFromCommandLine

func SetFlagsFromCommandLine(args []string) ([]string, error)

SetFlagsFromCommandLine passes args to the engine BEFORE Initialize. Recognized flags are consumed; the args the engine did not understand are returned in order (including the program name at args[0]). The engine exits the process on --help; do not pass it.

func SetFlagsFromCommandLineWithUsage

func SetFlagsFromCommandLineWithUsage(args []string, usage string) ([]string, error)

SetFlagsFromCommandLineWithUsage is the usage-bearing form of SetFlagsFromCommandLine. V8 prints usage followed by its flag catalogue when args requests help. As in rusty_v8, usage must not contain an embedded NUL.

func SetFlagsFromString

func SetFlagsFromString(flags string) error

SetFlagsFromString sets V8 flags from a whitespace-separated string. Must run before Initialize for deterministic behavior: after initialization the flag set is frozen and a value-changing write is engine-fatal (documented above, characterized out-of-process). Unknown flags are reported to stderr by the engine and otherwise ignored; recognized flags in the same string still take effect.

func Shutdown

func Shutdown() error

Shutdown runs the full teardown in the pinned order: Dispose followed by DisposePlatform. All isolates must be closed beforehand.

func ShutdownCppGCProcess

func ShutdownCppGCProcess() error

ShutdownCppGCProcess pairs an explicit initialization. It rejects live heaps, duplicate shutdown, and V8-managed cppgc state rather than forwarding rusty_v8's unguarded unsafe shutdown.

func StringMaxLength

func StringMaxLength() (int, error)

StringMaxLength returns v8::String::kMaxLength (536870888 on 64-bit targets): the maximum string length the engine accepts, and the bound every creation entry point validates.

func VersionString

func VersionString() (string, error)

VersionString returns the compile-time version string of the pinned engine, "15.2.124.1-rusty" (the -rusty suffix is the crate's embedder marker).

Types

type AccessorConfiguration

type AccessorConfiguration struct {
	Getter    AccessorGetterCallback
	Setter    AccessorSetterCallback
	Data      Value
	Attribute PropertyAttribute
}

AccessorConfiguration is the Go counterpart of v8::AccessorConfiguration. Getter is required. Data is retained by the isolate and is returned verbatim by PropertyCallbackArguments.Data even when its creation scope has closed. A zero Data value means no associated data (callbacks observe undefined).

type AccessorGetterCallback

type AccessorGetterCallback func(cs *CallbackScope, args PropertyCallbackArguments, rv ReturnValue)

AccessorGetterCallback mirrors v8::AccessorNameGetterCallback: every read of the intercepted property invokes it; the read result goes into rv.

type AccessorSetterCallback

type AccessorSetterCallback func(cs *CallbackScope, args PropertyCallbackArguments, value Value)

AccessorSetterCallback mirrors v8::AccessorNameSetterCallback: every write to the intercepted property invokes it with the assigned value.

type AllowJavascriptExecutionScope

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

AllowJavascriptExecutionScope is a nested lexical exception to a disallow guard. It must close before its parent guard.

func (*AllowJavascriptExecutionScope) Close

Close restores the enclosing disallow state.

type AllowWasmCodeGenerationCallback

type AllowWasmCodeGenerationCallback func(*CallbackScope, Value) bool

AllowWasmCodeGenerationCallback decides whether synchronous WebAssembly compilation may proceed in the originating context. source is V8's source string (empty for the WebAssembly.Module constructor in the pinned engine). The callback may schedule a JavaScript exception with CallbackScope.

type Array

type Array struct{ Value }

Array is a JS Array object.

func AsArray

func AsArray(v Value) (*Array, error)

AsArray casts a value to an Array after prevalidating the engine kind.

func (*Array) GetIndex

func (a *Array) GetIndex(s *Scope, c *Context, index uint32) (Value, error)

GetIndex reads an index property. A missing index reads as the undefined value; only a thrown exception returns an error.

func (*Array) HasIndex

func (a *Array) HasIndex(s *Scope, c *Context, index uint32) (bool, error)

HasIndex reports whether the index property exists. An error means the operation threw (the Maybe is Nothing); otherwise ok is Just(b).

func (*Array) Length

func (a *Array) Length() (int64, error)

Length returns the array length (the full uint32 range is preserved).

func (*Array) SetIndex

func (a *Array) SetIndex(s *Scope, c *Context, index uint32, v Value) (bool, error)

SetIndex writes an index property (growing length as the JS semantics require). ok is Just(false) when the write was ignored; an error means the operation threw.

type ArrayBuffer

type ArrayBuffer struct {
	Value
}

ArrayBuffer is a scope-local v8::ArrayBuffer.

func AsArrayBuffer

func AsArrayBuffer(v Value) (*ArrayBuffer, error)

AsArrayBuffer converts a generic value into an ArrayBuffer view of it.

func NewArrayBuffer

func NewArrayBuffer(s *Scope, c *Context, byteLength int) (*ArrayBuffer, error)

NewArrayBuffer allocates a new zero-initialized ArrayBuffer of byteLength bytes (v8::ArrayBuffer::new). The context supplies the instance map the engine allocates against (its native context must be the caller's). Absurd sizes fail inside the engine exactly as in the pinned oracle: as a process-fatal OOM, not a Go error.

func NewArrayBufferWithBackingStore

func NewArrayBufferWithBackingStore(s *Scope, c *Context, bs *BackingStore) (*ArrayBuffer, error)

NewArrayBufferWithBackingStore creates an ArrayBuffer aliasing the store (v8::ArrayBuffer::with_backing_store). The store gains one reference while the engine object lives; the Go BackingStore wrapper is unaffected.

func (*ArrayBuffer) ByteLength

func (ab *ArrayBuffer) ByteLength() (int, error)

ByteLength returns the buffer's length in bytes (0 after detach).

func (*ArrayBuffer) Data

func (ab *ArrayBuffer) Data() (uintptr, bool, error)

Data returns the buffer's raw data pointer (0 when there is none: a zero-length or detached buffer). The pointer is engine-owned, valid only while the buffer is alive, and must never be dereferenced or retained by Go; use a BackingStore (ReadAt/WriteAt) or views to touch the bytes.

func (*ArrayBuffer) Detach

func (ab *ArrayBuffer) Detach(c *Context, key Value) (bool, error)

Detach detaches the buffer and all its views. c is the context used for engine-internal bookkeeping (a key mismatch allocates a TypeError from it); key is the detach key to present (an empty Value{} means "no key", Rust's detach(None)). The bool result is false only when the stored [[ArrayBufferDetachKey]] rejected the request (Rust's None, with the engine's TypeError captured by a shim-internal TryCatch); non-detachable buffers report true without touching the engine, mirroring the crate's wrapper.

func (*ArrayBuffer) GetBackingStore

func (ab *ArrayBuffer) GetBackingStore() (*BackingStore, error)

GetBackingStore returns a NEW counted reference to the buffer's backing store. The caller must Close it; while it is open the store outlives the buffer, exactly like holding a SharedRef in the pinned crate.

func (*ArrayBuffer) IsDetachable

func (ab *ArrayBuffer) IsDetachable() (bool, error)

IsDetachable reports whether the buffer may be detached.

func (*ArrayBuffer) SetDetachKey

func (ab *ArrayBuffer) SetDetachKey(key Value) error

SetDetachKey stores the [[ArrayBufferDetachKey]]: after this, only a Detach presenting an equal key succeeds.

func (*ArrayBuffer) WasDetached

func (ab *ArrayBuffer) WasDetached() (bool, error)

WasDetached reports whether the buffer has been detached. It reproduces the pinned crate's wrapper exactly: a non-zero-length buffer reports false without consulting the engine (only zero-length buffers read the real WasDetached bit).

type ArrayBufferAllocator

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

ArrayBufferAllocator is one owned shared reference to a V8 ArrayBuffer allocator. Close releases this reference; isolates and backing stores retain independent native shared references as required by V8.

func NewArrayBufferAllocator

func NewArrayBufferAllocator(callbacks ArrayBufferAllocatorCallbacks) (*ArrayBufferAllocator, error)

NewArrayBufferAllocator creates a native-memory allocator observed and controlled by safe Go callbacks. In contrast to rusty_v8's unsafe new_rust_allocator, callbacks never return or retain raw memory pointers. This standalone factory may be called before Initialize.

func NewDefaultArrayBufferAllocator

func NewDefaultArrayBufferAllocator() (*ArrayBufferAllocator, error)

NewDefaultArrayBufferAllocator creates V8's malloc/free based convenience allocator. Like rusty_v8's standalone factory, it may be called before Initialize so the result can be installed in CreateParams. The caller owns the returned reference and must Close it.

func (*ArrayBufferAllocator) Close

func (a *ArrayBufferAllocator) Close() error

Close releases this owned reference. It does not invalidate isolates or backing stores that already retained the allocator. Close is concurrency-safe.

func (*ArrayBufferAllocator) UseCount

func (a *ArrayBufferAllocator) UseCount() (int, error)

UseCount returns the number of native shared references currently retaining the allocator. It is primarily useful for ownership diagnostics.

type ArrayBufferAllocatorCallbacks

type ArrayBufferAllocatorCallbacks struct {
	Allocate              func(byteLength int) bool
	AllocateUninitialized func(byteLength int) bool
	Free                  func(byteLength int, firstByte byte)
	Drop                  func()
}

ArrayBufferAllocatorCallbacks implements the observable part of V8's ArrayBuffer allocator contract without allowing Go pointers to escape into native memory. Allocate and AllocateUninitialized decide whether an allocation is accepted. Native code owns the returned storage. Free observes the allocation length and its first byte immediately before native release. Drop runs once when the last native shared reference to the allocator dies.

V8 may invoke these callbacks on multiple isolate threads concurrently. They must be concurrency-safe and must not call into V8. A callback panic cannot unwind through V8 and therefore terminates the process through the standard gov8 fail-fast callback boundary.

type BackingStore

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

func (*BackingStore) ByteLength

func (bs *BackingStore) ByteLength() (int, error)

ByteLength returns the length in bytes of the store's memory.

func (*BackingStore) Close

func (bs *BackingStore) Close() error

Close drops this reference to the store. When it is the last one, the store's memory is freed (and an external deleter runs) synchronously on the calling thread. Close is idempotent-guarded: a second call is an error.

func (*BackingStore) IsResizableByUserJavaScript

func (bs *BackingStore) IsResizableByUserJavaScript() (bool, error)

IsResizableByUserJavaScript reports whether the store belongs to a resizable ArrayBuffer (or growable SharedArrayBuffer).

func (*BackingStore) IsShared

func (bs *BackingStore) IsShared() (bool, error)

IsShared reports whether the store was created for a SharedArrayBuffer.

func (*BackingStore) ReadAt

func (bs *BackingStore) ReadAt(buf []byte, off int) (int, error)

ReadAt copies up to len(buf) bytes from the store at byte offset off into buf and returns the number of bytes copied. Out-of-range reads are errors (Rust would panic on the slice bound).

func (*BackingStore) UseCount

func (bs *BackingStore) UseCount() (int, error)

UseCount returns the store's live reference count: 1 while standalone, +1 for every engine object (ArrayBuffer/SharedArrayBuffer) currently aliasing it. This is the readable form of the crate's assert_use_count_eq polling assertion.

func (*BackingStore) WriteAt

func (bs *BackingStore) WriteAt(data []byte, off int) (int, error)

WriteAt writes data into the store at byte offset off and returns the number of bytes written. The store is interior-mutable, so writes are visible through every ArrayBuffer and view aliasing it. Out-of-range writes are errors.

type BackingStoreDeleter

type BackingStoreDeleter func(data unsafe.Pointer, byteLength int, deleterData uintptr)

BackingStoreDeleter is invoked exactly once when the last reference to a FromPtr backing store dies: (data, byteLength, deleterData) -- the same triple v8's BackingStoreDeleterCallback observes.

type BackingStoreDeleterEntry

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

type BoundScript

type BoundScript struct {
	Value
}

BoundScript is a script bound into the currently entered context (UnboundScript::bind_to_current_context). It is a scope-local handle.

func (BoundScript) Run

func (b BoundScript) Run(c *Context, s *Scope, tc *TryCatch) (Value, error)

Run executes the bound script in c. TryCatch routing matches Script.Run.

type CFunction

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

CFunction describes one caller-owned native fast-call address. The address must name process-lifetime executable native code whose ABI exactly matches TypeInfo. Go callbacks and Go pointers are intentionally unsupported: V8 may invoke this address without entering the Go callback ABI.

func NewCFunction

func NewCFunction(address uintptr, typeInfo *CFunctionInfo) (CFunction, error)

NewCFunction binds a nonzero native address to immutable type metadata.

func (CFunction) Address

func (f CFunction) Address() uintptr

Address reports the native entry address.

func (CFunction) TypeInfo

func (f CFunction) TypeInfo() *CFunctionInfo

TypeInfo reports immutable signature metadata.

type CFunctionInfo

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

CFunctionInfo is immutable CFunction signature metadata. Its private argument slice is copied at construction and copied again into native-owned storage when a fast FunctionTemplate is built.

func NewCFunctionInfo

func NewCFunctionInfo(returnInfo FastTypeInfo, arguments []FastTypeInfo, repr FastInt64Representation) (*CFunctionInfo, error)

NewCFunctionInfo constructs a validated fast-call signature. CallbackOptions is allowed only as the final argument and is excluded from ArgumentCount, matching v8::CFunctionInfo.

func (*CFunctionInfo) ArgumentCount

func (i *CFunctionInfo) ArgumentCount() int

ArgumentCount excludes a final CallbackOptions argument, as V8 does.

func (*CFunctionInfo) ArgumentInfo

func (i *CFunctionInfo) ArgumentInfo(index int) (FastTypeInfo, bool)

ArgumentInfo returns ordinary argument metadata. CallbackOptions is not addressable through this method because it is excluded from ArgumentCount.

func (*CFunctionInfo) HasOptions

func (i *CFunctionInfo) HasOptions() bool

HasOptions reports whether the final native parameter is FastApiCallbackOptions.

func (*CFunctionInfo) Int64Representation

func (i *CFunctionInfo) Int64Representation() FastInt64Representation

Int64Representation reports the signature's 64-bit integer policy.

func (*CFunctionInfo) ReturnInfo

func (i *CFunctionInfo) ReturnInfo() FastTypeInfo

ReturnInfo reports the signature return metadata.

type CRDTPCallbackDropper

type CRDTPCallbackDropper interface{ CRDTPCallbackDropped() }

CRDTPCallbackDropper optionally observes when native ownership releases a channel, domain handler, or fallthrough callback. It executes across the native callback boundary, so a panic is fail-fast like a Rust Drop panic.

type CRDTPDispatchRequest

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

func (*CRDTPDispatchRequest) AssociatedData

func (r *CRDTPDispatchRequest) AssociatedData() ([]byte, error)

func (*CRDTPDispatchRequest) CallID

func (r *CRDTPDispatchRequest) CallID() (int32, bool, error)

func (*CRDTPDispatchRequest) Method

func (r *CRDTPDispatchRequest) Method() ([]byte, error)

func (*CRDTPDispatchRequest) Params

func (r *CRDTPDispatchRequest) Params() ([]byte, error)

func (*CRDTPDispatchRequest) SessionID

func (r *CRDTPDispatchRequest) SessionID() ([]byte, error)

type CRDTPDispatchResponse

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

CRDTPDispatchResponse is an owned protocol dispatch result. Error-response and error-notification artifacts consume it exactly once.

func NewCRDTPFallThroughResponse

func NewCRDTPFallThroughResponse() (*CRDTPDispatchResponse, error)

func NewCRDTPInvalidParams

func NewCRDTPInvalidParams(message string) (*CRDTPDispatchResponse, error)

func NewCRDTPInvalidRequest

func NewCRDTPInvalidRequest(message string) (*CRDTPDispatchResponse, error)

func NewCRDTPMethodNotFound

func NewCRDTPMethodNotFound(message string) (*CRDTPDispatchResponse, error)

func NewCRDTPParseError

func NewCRDTPParseError(message string) (*CRDTPDispatchResponse, error)

func NewCRDTPServerError

func NewCRDTPServerError(message string) (*CRDTPDispatchResponse, error)

func NewCRDTPSuccessResponse

func NewCRDTPSuccessResponse() (*CRDTPDispatchResponse, error)

func (*CRDTPDispatchResponse) Close

func (r *CRDTPDispatchResponse) Close() error

func (*CRDTPDispatchResponse) Code

func (r *CRDTPDispatchResponse) Code() (int32, error)

func (*CRDTPDispatchResponse) IsError

func (r *CRDTPDispatchResponse) IsError() (bool, error)

func (*CRDTPDispatchResponse) IsFallThrough

func (r *CRDTPDispatchResponse) IsFallThrough() (bool, error)

func (*CRDTPDispatchResponse) IsSuccess

func (r *CRDTPDispatchResponse) IsSuccess() (bool, error)

func (*CRDTPDispatchResponse) Message

func (r *CRDTPDispatchResponse) Message() (string, error)

type CRDTPDispatchable

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

CRDTPDispatchable is an owned parsed protocol message. Construction copies both inputs, so they may be modified or released immediately afterward. A malformed message still produces a value whose OK method reports false; accessors reject such a value instead of invoking upstream preconditioned accessors.

func NewCRDTPDispatchable

func NewCRDTPDispatchable(cbor, associatedData []byte) (*CRDTPDispatchable, error)

func NewCRDTPDispatchableWithFallthrough

func NewCRDTPDispatchableWithFallthrough(cbor, associatedData []byte, callback CRDTPFallthroughCallback) (*CRDTPDispatchable, error)

func (*CRDTPDispatchable) AssociatedData

func (d *CRDTPDispatchable) AssociatedData() ([]byte, error)

func (*CRDTPDispatchable) CallID

func (d *CRDTPDispatchable) CallID() (id int32, has bool, err error)

func (*CRDTPDispatchable) Close

func (d *CRDTPDispatchable) Close() error

func (*CRDTPDispatchable) Method

func (d *CRDTPDispatchable) Method() ([]byte, error)

func (*CRDTPDispatchable) MethodString

func (d *CRDTPDispatchable) MethodString() (string, error)

func (*CRDTPDispatchable) OK

func (d *CRDTPDispatchable) OK() (bool, error)

func (*CRDTPDispatchable) Params

func (d *CRDTPDispatchable) Params() ([]byte, error)

func (*CRDTPDispatchable) SessionID

func (d *CRDTPDispatchable) SessionID() ([]byte, error)

type CRDTPDomainDispatcher

type CRDTPDomainDispatcher interface {
	Dispatch(command []byte, request *CRDTPDispatchRequest, responder *CRDTPDomainResponder) bool
}

CRDTPDomainDispatcher handles a command synchronously. request and responder are callback-borrowed and reject use after this method returns. Returning false asks UberDispatcher to synthesize the pinned method-not-found response.

type CRDTPDomainResponder

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

func (*CRDTPDomainResponder) SendResponse

func (r *CRDTPDomainResponder) SendResponse(callID int32, response *CRDTPDispatchResponse, result *CRDTPSerializable) error

SendResponse synchronously sends and consumes response and optional result. Both handles are detached before native entry because channel delivery may reenter Go before this call returns.

type CRDTPFallthroughCallback

type CRDTPFallthroughCallback interface {
	FallThrough(callID int32, method, message, associatedData []byte)
}

CRDTPFallthroughCallback receives an unhandled message synchronously.

type CRDTPFallthroughFunc

type CRDTPFallthroughFunc func(callID int32, method, message, associatedData []byte)

func (CRDTPFallthroughFunc) FallThrough

func (f CRDTPFallthroughFunc) FallThrough(callID int32, method, message, associatedData []byte)

type CRDTPFrontendChannel

type CRDTPFrontendChannel interface {
	SendProtocolResponse(callID int32, message *CRDTPSerializable)
	SendProtocolNotification(message *CRDTPSerializable)
	FlushProtocolNotifications()
}

CRDTPFrontendChannel receives owned protocol messages. The receiver owns each non-nil CRDTPSerializable and may retain it after the callback; it must eventually call Close. Notification and flush callbacks are implemented for completeness of the pinned interface, although the public dispatcher send path exercised here emits responses only.

type CRDTPFrontendChannelHandle

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

CRDTPFrontendChannelHandle owns the native FrontendChannel bridge.

func NewCRDTPFrontendChannel

func NewCRDTPFrontendChannel(handler CRDTPFrontendChannel) (*CRDTPFrontendChannelHandle, error)

func (*CRDTPFrontendChannelHandle) Close

func (c *CRDTPFrontendChannelHandle) Close() error

type CRDTPSerializable

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

CRDTPSerializable is an owned lazily serialized protocol artifact. Bytes returns a fresh copy on every call. Passing it as params consumes it once.

func CreateCRDTPErrorNotification

func CreateCRDTPErrorNotification(response *CRDTPDispatchResponse) (*CRDTPSerializable, error)

func CreateCRDTPErrorResponse

func CreateCRDTPErrorResponse(callID int32, response *CRDTPDispatchResponse) (*CRDTPSerializable, error)

func CreateCRDTPNotification

func CreateCRDTPNotification(method string, params *CRDTPSerializable) (*CRDTPSerializable, error)

CreateCRDTPNotification creates a notification and consumes params. Unlike rusty_v8's CString-shaped API, Go rejects an interior NUL with an error before native entry and leaves params usable.

func CreateCRDTPResponse

func CreateCRDTPResponse(callID int32, params *CRDTPSerializable) (*CRDTPSerializable, error)

func (*CRDTPSerializable) Bytes

func (s *CRDTPSerializable) Bytes() ([]byte, error)

func (*CRDTPSerializable) Close

func (s *CRDTPSerializable) Close() error

type CRDTPUberDispatcher

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

CRDTPUberDispatcher synchronously routes protocol messages to wired domains. It must be closed before its channel.

func NewCRDTPUberDispatcher

func NewCRDTPUberDispatcher(channel *CRDTPFrontendChannelHandle) (*CRDTPUberDispatcher, error)

func (*CRDTPUberDispatcher) Close

func (d *CRDTPUberDispatcher) Close() error

func (*CRDTPUberDispatcher) Dispatch

func (d *CRDTPUberDispatcher) Dispatch(message *CRDTPDispatchable) error

func (*CRDTPUberDispatcher) WireDomain

func (d *CRDTPUberDispatcher) WireDomain(domain string, handler CRDTPDomainDispatcher) error

type CallbackMessage

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

CallbackMessage is a message delivered to a MessageListenerCallback. It is bound to the dispatch scope and the engine's entered-or-microtask context captured at dispatch time.

func (*CallbackMessage) AsMessage

func (m *CallbackMessage) AsMessage() (*Message, error)

AsMessage exposes the complete safe Message getter surface for a listener callback. The returned handle remains valid only for the callback scope.

func (*CallbackMessage) CreateMessage

func (m *CallbackMessage) CreateMessage(c *Context, exception Value) (*Message, error)

CreateMessage reconstructs a Message for exception in the callback's local scope, allowing listener code to compare it with the delivered Message.

func (*CallbackMessage) EndPosition

func (m *CallbackMessage) EndPosition() (int64, error)

EndPosition returns the exclusive end offset of the error region.

func (*CallbackMessage) ErrorLevel

func (m *CallbackMessage) ErrorLevel() (int64, error)

ErrorLevel returns the MessageErrorLevel bits of the message.

func (*CallbackMessage) LineNumber

func (m *CallbackMessage) LineNumber() (line int32, ok bool, err error)

LineNumber returns the 1-based line of the error; ok=false when absent.

func (*CallbackMessage) StartPosition

func (m *CallbackMessage) StartPosition() (int64, error)

StartPosition returns the 0-based character offset where the error region starts.

func (*CallbackMessage) Text

func (m *CallbackMessage) Text() (string, error)

Text returns the Message::Get text (carries the "Uncaught " prefix).

func (*CallbackMessage) ValueText

func (m *CallbackMessage) ValueText(exception Value) (string, error)

ValueText converts the exception delivered alongside this message to its ECMAScript ToString text, using the engine context captured by the dispatch (the entered-or-microtask context the engine had when the listener fired).

type CallbackPropertyDescriptor

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

CallbackPropertyDescriptor is the Go view of the v8::PropertyDescriptor snapshot a definer callback receives. (runtime_values.go already owns the name PropertyDescriptor for the engine-handle wrapper used by Object.defineProperty; this read-only view is the callback-side shape.) Presence flags mirror the C++ has_* accessors; the value fields are only meaningful when the corresponding has bit is set. It is bound to the running callback and must not outlive it.

func (CallbackPropertyDescriptor) Configurable

func (d CallbackPropertyDescriptor) Configurable() bool

Configurable returns the descriptor's configurable flag.

func (CallbackPropertyDescriptor) Enumerable

func (d CallbackPropertyDescriptor) Enumerable() bool

Enumerable returns the descriptor's enumerable flag.

func (CallbackPropertyDescriptor) HasConfigurable

func (d CallbackPropertyDescriptor) HasConfigurable() bool

HasConfigurable reports whether the descriptor carries a configurable flag.

func (CallbackPropertyDescriptor) HasEnumerable

func (d CallbackPropertyDescriptor) HasEnumerable() bool

HasEnumerable reports whether the descriptor carries an enumerable flag.

func (CallbackPropertyDescriptor) HasValue

func (d CallbackPropertyDescriptor) HasValue() bool

HasValue reports whether the descriptor carries a value.

func (CallbackPropertyDescriptor) HasWritable

func (d CallbackPropertyDescriptor) HasWritable() bool

HasWritable reports whether the descriptor carries a writable flag.

func (CallbackPropertyDescriptor) Value

Value returns the descriptor's value; ok is false when absent.

func (CallbackPropertyDescriptor) Writable

func (d CallbackPropertyDescriptor) Writable() bool

Writable returns the descriptor's writable flag.

type CallbackScope

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

CallbackScope is the execution scope handed to native callbacks. It pairs the callback's own Scope (value construction) with the engine's current context, captured by the trampoline as a scope-local wire: context-bound conversions inside callbacks run through that wire instead of a persistent context wrapper (the engine materializes no extra Global per invocation).

func (*CallbackScope) CallFunction

func (cs *CallbackScope) CallFunction(fn Value, recv Value, args []Value) (Value, bool, error)

CallFunction re-enters JavaScript from inside the callback: it invokes fn (a function value) with recv and args. ok is false when the call threw.

func (*CallbackScope) CurrentContextGlobal

func (cs *CallbackScope) CurrentContextGlobal() (Value, error)

CurrentContextGlobal returns the originating context's global object as a callback-local value.

func (*CallbackScope) IntegerValue

func (cs *CallbackScope) IntegerValue(v Value) (int64, bool, error)

IntegerValue is Value::IntegerValue in the callback's current context; ok is false when the conversion failed.

func (*CallbackScope) Isolate

func (cs *CallbackScope) Isolate() *Isolate

Isolate returns the isolate the callback runs on.

func (*CallbackScope) NewArrayWithElements

func (cs *CallbackScope) NewArrayWithElements(elements []Value) (Value, error)

NewArrayWithElements creates a JS array from the given elements in the callback's current context (v8::Array::NewWithElements). Elements must belong to the callback's isolate.

func (*CallbackScope) NewCallbackPromiseResolver

func (cs *CallbackScope) NewCallbackPromiseResolver() (PromiseResolver, Promise, error)

NewCallbackPromiseResolver creates a resolver in the callback's current context.

func (*CallbackScope) NewError

func (cs *CallbackScope) NewError(message string) (Value, error)

NewError builds a JS Error object with the given message in the callback scope (v8::Exception::Error).

func (*CallbackScope) NewObject

func (cs *CallbackScope) NewObject() (Value, error)

NewObject creates a plain JS object in the callback's current context (v8::Object::New). Used by descriptor handlers and enumerator writers.

func (*CallbackScope) NewString

func (cs *CallbackScope) NewString(str string) (Value, error)

NewString creates a JS string in the callback scope.

func (*CallbackScope) NewTypeError

func (cs *CallbackScope) NewTypeError(message string) (Value, error)

NewTypeError creates a callback-local TypeError in the callback's current context.

func (*CallbackScope) NumberValue

func (cs *CallbackScope) NumberValue(v Value) (float64, bool, error)

NumberValue is Value::NumberValue in the callback's current context.

func (*CallbackScope) ObjectGet

func (cs *CallbackScope) ObjectGet(obj Value, key string) (Value, bool, error)

ObjectGet reads a named property in the callback's current context; ok is false when the read threw.

func (*CallbackScope) ObjectSet

func (cs *CallbackScope) ObjectSet(obj Value, key string, v Value) (bool, error)

ObjectSet writes a named property in the callback's current context; ok is false when the write threw or was rejected.

func (*CallbackScope) Scope

func (cs *CallbackScope) Scope() *Scope

Scope returns the callback's value-construction scope. Values created through it are only valid inside the callback.

func (*CallbackScope) SettleCallbackPromise

func (cs *CallbackScope) SettleCallbackPromise(resolver PromiseResolver, value Value, reject bool) (bool, error)

SettleCallbackPromise resolves or rejects a callback-local resolver.

func (*CallbackScope) ThrowException

func (cs *CallbackScope) ThrowException(v Value) error

ThrowException schedules v to propagate to the JS caller once the native callback returns (Scope::throw_exception in the oracle). The callback's return value is ignored by the engine when an exception is scheduled.

func (*CallbackScope) ToString

func (cs *CallbackScope) ToString(v Value) (string, error)

ToString returns the ECMAScript ToString of the value (lossy UTF-8), evaluated in the callback's current context.

type CompileOptions

type CompileOptions uint32

CompileOptions mirror the pinned crate's script_compiler::CompileOptions subset this slice exercises.

const (
	// OptNoCompileOptions is the default compile.
	OptNoCompileOptions CompileOptions = 0
	// OptConsumeCodeCache consumes pre-produced cache bytes.
	OptConsumeCodeCache CompileOptions = 1
	// OptEagerCompile eagerly compiles (no lazy inner functions).
	OptEagerCompile CompileOptions = 2
)
const (
	OptProduceCompileHints                       CompileOptions = 1 << 2
	OptConsumeCompileHints                       CompileOptions = 1 << 3
	OptFollowCompileHintsMagicComment            CompileOptions = 1 << 4
	OptFollowCompileHintsPerFunctionMagicComment CompileOptions = 1 << 5
)

Additional CompileOptions exposed by rusty_v8 152.2.0. CompileOptions is a bit set: unknown bits are deliberately preserved and forwarded because the pinned engine ignores them for classic compilation.

type CompiledWasmModule

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

CompiledWasmModule owns V8's shareable compiled representation. It is safe to inspect or use from another thread or isolate until Close.

func (*CompiledWasmModule) Close

func (m *CompiledWasmModule) Close() error

Close releases the compiled representation. It does not invalidate local WasmModuleObjects previously created from it.

func (*CompiledWasmModule) Serialize

Serialize creates deterministic compiled-module cache bytes and binds them to a private copy of this module's source wire bytes. Serialization requires optimized Wasm code; V8 can report the module as not serializable when only Liftoff code exists.

func (*CompiledWasmModule) SourceURL

func (m *CompiledWasmModule) SourceURL() (string, error)

SourceURL returns the source URL attached during compilation, if any.

func (*CompiledWasmModule) WireBytes

func (m *CompiledWasmModule) WireBytes() ([]byte, error)

WireBytes returns a copy of the original wasm wire bytes.

type ConstructorBehavior

type ConstructorBehavior uint8

ConstructorBehavior mirrors v8::ConstructorBehavior. The zero value selects the engine default (kAllow), matching the crate's builder default.

const (
	// ConstructorBehaviorDefault uses the engine default (kAllow).
	ConstructorBehaviorDefault ConstructorBehavior = iota
	// ConstructorBehaviorThrow maps to kThrow: `new F()` rejects with a
	// TypeError and the function has no .prototype.
	ConstructorBehaviorThrow
	// ConstructorBehaviorAllow maps to kAllow.
	ConstructorBehaviorAllow
)

type Context

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

Context is a persistent execution context (a rooted v8::Global<Context>). It is valid until Close and, like everything else, only usable on the isolate's owning thread.

func (*Context) AllowCodeGenerationFromStrings

func (c *Context) AllowCodeGenerationFromStrings(allow bool) error

AllowCodeGenerationFromStrings toggles codegen-from-strings for the context (Context::AllowCodeGenerationFromStrings).

func (*Context) ClearAllSlots

func (c *Context) ClearAllSlots()

ClearAllSlots removes every host-side slot of the context. Embedder data is engine state and survives, exactly like the pinned clear_all_slots.

func (*Context) Close

func (c *Context) Close() error

Close releases the context. It must not be used afterwards.

func (*Context) Compile

func (c *Context) Compile(s *Scope, source string, tc *TryCatch) (*Script, error)

Compile compiles source in the context. If tc is non-nil, compile failures leave the exception details in it (HasCaught etc.); if tc is nil, a shim-internal TryCatch observes the failure and only the error result is returned. The scope (and TryCatch, when given) must belong to the same isolate as the context.

func (*Context) CompileCached

func (c *Context) CompileCached(s *Scope, source string, origin *Origin, cache []byte, tc *TryCatch) (script *Script, rejected bool, err error)

CompileCached compiles source consuming pre-produced code-cache bytes (ScriptCompiler::compile with ConsumeCodeCache). The cache is prevalidated with CheckCodeCache first: an incompatible cache is rejected with an error instead of reaching the deserializer. rejected reports the engine's own post-compile rejected flag (false for a healthy cache). Value-valued resource names are rejected before FFI; only the direct CompileWithOrigin path is characterized as safe for arbitrary Values.

func (*Context) CompileFunction

func (c *Context) CompileFunction(s *Scope, source string, params []string, tc *TryCatch) (Value, error)

CompileFunction compiles source as a function body with declared parameter names (ScriptCompiler::compile_function). The result is a scope-local function value.

func (*Context) CompileFunctionAdvanced

func (c *Context) CompileFunctionAdvanced(s *Scope, source string, params []string, cache *FunctionCodeCache, tc *TryCatch) (function *Function, rejected bool, err error)

CompileFunctionAdvanced compiles source as a function body with declared parameters. Passing nil cache performs a normal compile. A non-nil cache is consumed directly. V8 may reject changed source or truncated engine-produced data and cleanly recompile; changed parameter names/count may accept the cache and retain the cached function's original parameter metadata. rejected reports V8's cached-data rejected bit. Arbitrary external bytes cannot be constructed as FunctionCodeCache, preserving the safe deserializer boundary.

func (*Context) CompileModule

func (c *Context) CompileModule(s *Scope, source, resourceName string, tc *TryCatch) (*Module, error)

CompileModule parses source as an ECMAScript SourceTextModule. ResourceName is exposed to V8 diagnostics and import-meta host hooks. Syntax failures are reported as exception errors and, when supplied, recorded in tc.

func (*Context) CompileModuleCached

func (c *Context) CompileModuleCached(s *Scope, source string,
	options ModuleCompileOptions, cache *ModuleCodeCache,
	tc *TryCatch) (module *Module, rejected bool, err error)

CompileModuleCached compiles source with an optional opaque cache. rejected is V8's CachedData rejected bit. Rejection is non-fatal: V8 recompiles the supplied source and returns a usable module.

func (*Context) CompileModuleWithOptions

func (c *Context) CompileModuleWithOptions(s *Scope, source string, options ModuleCompileOptions, tc *TryCatch) (*Module, error)

CompileModuleWithOptions is CompileModule with explicit ScriptOrigin line and column offsets.

func (*Context) CompileScriptCompilerSource

func (c *Context) CompileScriptCompilerSource(scope *Scope, source *ScriptCompilerSource, options CompileOptions, reason NoCacheReason, tc *TryCatch) (*Script, error)

CompileScriptCompilerSource compiles a classic ScriptCompilerSource in the context. ConsumeCodeCache without present cached data is rejected before FFI because the pinned native call access-violates. Syntax failures are routed through tc exactly like Context.Compile.

func (*Context) CompileSourceTextModule

func (c *Context) CompileSourceTextModule(s *Scope, source, resourceName string, tc *TryCatch) (*Module, error)

CompileSourceTextModule is an explicit alias for CompileModule.

func (*Context) CompileUnbound

func (c *Context) CompileUnbound(s *Scope, source string, origin *Origin, opts CompileOptions, tc *TryCatch) (*UnboundScript, error)

CompileUnbound compiles an unbound script with a string-valued origin and options (ScriptCompiler::compile_unbound_script). TryCatch routing matches Context.Compile.

func (*Context) CompileUncaughtWithOrigin

func (c *Context) CompileUncaughtWithOrigin(s *Scope, source string, origin *Origin) (*Script, error)

CompileUncaughtWithOrigin compiles without an internal fallback TryCatch, allowing syntax errors to reach message listeners. ResourceNameValue is rejected because this first residual listener slice only exposes the safe string-origin bridge used by the pinned oracle.

func (*Context) CompileWasmModule

func (c *Context) CompileWasmModule(s *Scope, wireBytes []byte, tc *TryCatch) (*WasmModuleObject, error)

CompileWasmModule synchronously compiles WebAssembly wire bytes. Malformed bytes return an exception error and are captured by tc when supplied.

func (*Context) CompileWithOrigin

func (c *Context) CompileWithOrigin(s *Scope, source string, origin *Origin, tc *TryCatch) (*Script, error)

CompileWithOrigin compiles source with a script origin. TryCatch routing matches Context.Compile.

func (*Context) CreateMessage

func (c *Context) CreateMessage(s *Scope, exception Value) (*Message, error)

CreateMessage reconstructs V8's Message for exception. It accepts native errors, primitives, and arbitrary JavaScript values. The result is local to s and can recover the current JS source location when called in a callback.

func (*Context) Data

func (c *Context) Data(s *Scope) (Data, error)

Data materializes c as a Data local owned by s.

func (*Context) Enter

func (c *Context) Enter() (*ContextScope, error)

Enter enters the context (v8 Context::Enter). Exit with Close, obeying reverse-enter order across all contexts of the isolate.

func (*Context) GetAlignedPointerFromEmbedderData

func (c *Context) GetAlignedPointerFromEmbedderData(slot int) (uintptr, error)

GetAlignedPointerFromEmbedderData reads the aligned pointer from embedder slot slot.

func (*Context) GetEmbedderData

func (c *Context) GetEmbedderData(s *Scope, slot int) (Value, bool, error)

GetEmbedderData reads the value in embedder slot slot (0-based). ok=false when the engine reports the slot absent. NOTE: the engine's default slot content is an internal oddball, not a JS value — only predicates are meaningful on it (the pinned oracle records exactly those).

func (*Context) GetExceptionStackTrace

func (c *Context) GetExceptionStackTrace(s *Scope, exception Value) (*StackTrace, bool, error)

GetExceptionStackTrace returns the structured stack trace attached to exception. ok is false when the value carries none.

func (*Context) GetExtrasBindingObject

func (c *Context) GetExtrasBindingObject(s *Scope) (*Object, error)

GetExtrasBindingObject returns V8's stable extras binding object as a local Object owned by s.

func (*Context) GetMicrotaskQueue

func (c *Context) GetMicrotaskQueue() (uintptr, error)

GetMicrotaskQueue returns the raw pointer of the context's attached queue (0 when none is attached).

func (*Context) GetSecurityToken

func (c *Context) GetSecurityToken(s *Scope) (Value, error)

GetSecurityToken returns the context's current security token (v8 Context::GetSecurityToken).

func (*Context) GetSlot

func (c *Context) GetSlot(key any) (any, bool)

GetSlot returns the value stored under key.

func (*Context) GlobalObject

func (c *Context) GlobalObject(s *Scope) (*Object, error)

GlobalObject returns the context's global object as a scope-local value. The scope must belong to the same isolate as the context.

func (*Context) IsCodeGenerationFromStringsAllowed

func (c *Context) IsCodeGenerationFromStringsAllowed() (bool, error)

IsCodeGenerationFromStringsAllowed reports the context's current codegen-from-strings setting (allowed by default).

func (*Context) NewError

func (c *Context) NewError(s *Scope, message string) (Value, error)

NewError constructs an Error in c. The returned value is local to s.

func (*Context) NewErrorFromStringValue

func (c *Context) NewErrorFromStringValue(s *Scope, message Value) (Value, error)

NewErrorFromStringValue passes an existing scope-local V8 String directly to the Error constructor without a Go UTF-8 round-trip or coercion. This preserves exact UTF-16 contents and representation, including lone surrogates and external backing resources.

func (*Context) NewRangeError

func (c *Context) NewRangeError(s *Scope, message string) (Value, error)

NewRangeError constructs a RangeError in c. The returned value is local to s.

func (*Context) NewRangeErrorFromStringValue

func (c *Context) NewRangeErrorFromStringValue(s *Scope, message Value) (Value, error)

NewRangeErrorFromStringValue passes an existing scope-local V8 String to the RangeError constructor without a Go UTF-8 round-trip or coercion.

func (*Context) NewReferenceError

func (c *Context) NewReferenceError(s *Scope, message string) (Value, error)

NewReferenceError constructs a ReferenceError in c. The returned value is local to s.

func (*Context) NewReferenceErrorFromStringValue

func (c *Context) NewReferenceErrorFromStringValue(s *Scope, message Value) (Value, error)

NewReferenceErrorFromStringValue passes an existing scope-local V8 String to the ReferenceError constructor without a Go UTF-8 round-trip or coercion.

func (*Context) NewSyntaxError

func (c *Context) NewSyntaxError(s *Scope, message string) (Value, error)

NewSyntaxError constructs a SyntaxError in c. The returned value is local to s.

func (*Context) NewSyntaxErrorFromStringValue

func (c *Context) NewSyntaxErrorFromStringValue(s *Scope, message Value) (Value, error)

NewSyntaxErrorFromStringValue passes an existing scope-local V8 String to the SyntaxError constructor without a Go UTF-8 round-trip or coercion.

func (*Context) NewSyntheticModule

func (c *Context) NewSyntheticModule(s *Scope, moduleName string,
	exportNames []string, callback SyntheticModuleEvaluationCallback) (*Module, error)

NewSyntheticModule creates a module with fixed export names. Duplicate names are rejected in Go because V8's later instantiation path CHECK-fails on duplicates. The callback is retained until Module.Close.

func (*Context) NewTypeError

func (c *Context) NewTypeError(s *Scope, message string) (Value, error)

NewTypeError constructs a TypeError in c. The returned value is local to s.

func (*Context) NewTypeErrorFromStringValue

func (c *Context) NewTypeErrorFromStringValue(s *Scope, message Value) (Value, error)

NewTypeErrorFromStringValue passes an existing scope-local V8 String to the TypeError constructor without a Go UTF-8 round-trip or coercion.

func (*Context) RemoveSlot

func (c *Context) RemoveSlot(key any) (any, bool)

RemoveSlot removes and returns the value stored under key.

func (*Context) SetAlignedPointerInEmbedderData

func (c *Context) SetAlignedPointerInEmbedderData(slot int, p uintptr) error

SetAlignedPointerInEmbedderData stores an aligned raw pointer in embedder slot slot. The pointer crosses as a raw word; it must not be a Go pointer (the engine never dereferences it). Alignment is validated Go-side: the upstream ApiCheck-fatals ("Pointer is not aligned") on unaligned values.

func (*Context) SetEmbedderData

func (c *Context) SetEmbedderData(s *Scope, slot int, v Value) error

SetEmbedderData writes a JS value into embedder slot slot.

func (*Context) SetMicrotaskQueue

func (c *Context) SetMicrotaskQueue(m *MicrotaskQueue) error

SetMicrotaskQueue attaches a native queue to the context (replacing the isolate default). The queue must belong to the same isolate as the context.

func (*Context) SetPromiseHooks

func (c *Context) SetPromiseHooks(hooks ContextPromiseHooks) error

SetPromiseHooks installs hooks on this context. The Go API names the target Context explicitly; the Rust API infers it from its entered ContextScope.

func (*Context) SetSecurityToken

func (c *Context) SetSecurityToken(s *Scope, token Value) error

SetSecurityToken shares another context's token with this context (v8 Context::SetSecurityToken), re-enabling cross-context global access.

func (*Context) SetSlot

func (c *Context) SetSlot(key, value any) (previous any, wasEmpty bool)

SetSlot stores value under key and returns the previous value, if any (the crate's set_slot hands back the replaced Rc).

func (*Context) UseDefaultSecurityToken

func (c *Context) UseDefaultSecurityToken() error

UseDefaultSecurityToken restores the context's own global object as its security token (v8 Context::UseDefaultSecurityToken).

func (*Context) WasmModuleFromCompiled

func (c *Context) WasmModuleFromCompiled(s *Scope, compiled *CompiledWasmModule) (result *WasmModuleObject, err error)

WasmModuleFromCompiled creates a local module object from a shareable compiled module. The compiled handle remains owned by the caller.

type ContextOptions

type ContextOptions struct {
	GlobalTemplate *ObjectTemplate
	GlobalObject   *Object
	MicrotaskQueue *MicrotaskQueue
}

ContextOptions are the construction-time options exercised by the pinned v8 crate. The local template/global handles and queue must all belong to the isolate passed to NewContextWithOptions.

type ContextPromiseHooks

type ContextPromiseHooks struct {
	Init    *Function
	Before  *Function
	After   *Function
	Resolve *Function
}

ContextPromiseHooks are context-local Promise lifecycle callbacks. Nil fields disable the corresponding hook; an all-nil value disables all hooks.

type ContextRef

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

ContextRef is an engine-observed scope-local Context. It preserves the Local<Context> lifetime of the pinned Rust API: the reference and values materialized from it are invalid once its Scope closes.

func (*ContextRef) Enter

func (r *ContextRef) Enter() (*ContextScope, error)

Enter enters this scope-local Context. The source Scope need not be the current innermost HandleScope, but it must remain live until the returned ContextScope closes; Scope.Close enforces that borrowed lifetime.

func (*ContextRef) GlobalObject

func (r *ContextRef) GlobalObject(s *Scope) (*Object, error)

GlobalObject returns this Context's global object in s. The reference's source Scope and the result Scope must both still be live and belong to the same isolate.

func (*ContextRef) IsEmpty

func (r *ContextRef) IsEmpty() (bool, error)

IsEmpty reports whether V8 returned no current/entered Context. The pinned Rust getters cannot safely represent this native state, while Go keeps it as an explicit, non-dereferenceable result.

func (*ContextRef) SameAs

func (r *ContextRef) SameAs(c *Context) (bool, error)

SameAs reports whether the observed context is c (engine identity).

func (*ContextRef) SameAsRef

func (r *ContextRef) SameAsRef(other *ContextRef) (bool, error)

SameAsRef reports engine identity equality with another scope-local Context. Empty references compare equal only to another empty reference.

type ContextScope

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

ContextScope is an entered-context guard (the engine half of the crate's ContextScope). Contexts must be exited in reverse enter order; the Go stack below enforces that where the crate's type system does.

func (*ContextScope) Close

func (cs *ContextScope) Close() error

Close exits the context. The innermost entered context must be exited first (the engine's Enter/Exit pair is LIFO).

type CounterLookupCallback

type CounterLookupCallback func(name string)

CounterLookupCallback observes a V8 statistics-counter name. The callback runs synchronously on an engine thread and must not retain engine pointers or re-enter the isolate. Counter storage itself is owned by the shim and remains stable for the isolate lifetime.

type CppGCEmbedderStackState

type CppGCEmbedderStackState uint8
const (
	CppGCStackMayContainHeapPointers CppGCEmbedderStackState = iota
	CppGCStackNoHeapPointers
)

type CppGCGenericCallbacks

type CppGCGenericCallbacks struct {
	CellDropped  func(int32)
	NameObserved func()
	Destroy      func()
}

CppGCGenericCallbacks observes copied generic-payload events. CellDropped is called synchronously when SetCell replaces a value and once more when the managed owner is destroyed. NameObserved may run while a heap snapshot is visiting the object. Destroy runs once after the allocation's native state has been destroyed. Callbacks may run on a GC worker, must be concurrency safe, and must not call into V8. Panics fail fast at the native callback boundary.

type CppGCGenericGraph

type CppGCGenericGraph[T any] struct {
	// contains filtered or unexported fields
}

CppGCGenericGraph is a strong root for one typed-state cppgc graph object. The native object stores only numeric state/graph IDs and native tracing fields. All operations are isolate-owner-thread-only.

func NewCppGCGenericGraph

func NewCppGCGenericGraph[T any](iso *Isolate, scope *Scope, options CppGCGenericGraphOptions[T]) (*CppGCGenericGraph[T], error)

NewCppGCGenericGraph creates a managed typed-state graph object.

func (*CppGCGenericGraph[T]) ClearStrong

func (graph *CppGCGenericGraph[T]) ClearStrong(index uint32) error

func (*CppGCGenericGraph[T]) ClearWeak

func (graph *CppGCGenericGraph[T]) ClearWeak(index uint32) error

func (*CppGCGenericGraph[T]) Close

func (graph *CppGCGenericGraph[T]) Close() error

Close releases this graph's strong off-heap root. The managed object remains alive while reached by another graph edge; final state Drop and Destroy run only when cppgc later determines it is unreachable.

func (*CppGCGenericGraph[T]) ReplaceState

func (graph *CppGCGenericGraph[T]) ReplaceState(value T) error

ReplaceState deep-clones value, atomically installs the managed copy, and synchronously drops the old managed state before returning.

func (*CppGCGenericGraph[T]) SetStrong

func (graph *CppGCGenericGraph[T]) SetStrong(index uint32, child *CppGCGenericGraph[T]) error

SetStrong assigns one indexed strong edge using cppgc's write barrier.

func (*CppGCGenericGraph[T]) SetTraced

func (graph *CppGCGenericGraph[T]) SetTraced(scope *Scope, value Value) error

SetTraced replaces the embedded V8 traced reference. A zero Value clears it.

func (*CppGCGenericGraph[T]) SetWeak

func (graph *CppGCGenericGraph[T]) SetWeak(index uint32, child *CppGCGenericGraph[T]) error

SetWeak assigns one indexed weak edge using cppgc's write barrier.

func (*CppGCGenericGraph[T]) State

func (graph *CppGCGenericGraph[T]) State() (T, error)

State returns a deep clone of the currently managed typed state.

func (*CppGCGenericGraph[T]) Strong

func (graph *CppGCGenericGraph[T]) Strong(index uint32) (CppGCGenericGraphObservation[T], bool, error)

func (*CppGCGenericGraph[T]) Traced

func (graph *CppGCGenericGraph[T]) Traced(scope *Scope) (Value, bool, error)

Traced copies the embedded traced reference into scope, or returns ok=false when it is empty.

func (*CppGCGenericGraph[T]) UpdateState

func (graph *CppGCGenericGraph[T]) UpdateState(update func(*T) error) error

UpdateState clones the current value, lets update modify only that detached copy, then writes a managed clone back into the same stable state entry. It models an in-place GcCell mutation: Drop is not called for the prior value. A returned error leaves managed state unchanged.

func (*CppGCGenericGraph[T]) Weak

func (graph *CppGCGenericGraph[T]) Weak(index uint32) (CppGCGenericGraphObservation[T], bool, error)

type CppGCGenericGraphCallbacks

type CppGCGenericGraphCallbacks[T any] struct {
	Clone         func(T) (T, error)
	Drop          func(T)
	NameObserved  func()
	TraceObserved func()
	Destroy       func()
}

CppGCGenericGraphCallbacks controls copied typed-state ownership. Clone is required and must return a deep copy: it prevents callers from retaining a mutable alias to state owned by the managed object. Drop receives each logical state installed by construction or ReplaceState exactly once, synchronously on replacement and during final cppgc destruction. UpdateState mutates the same logical state and therefore does not end its lifetime. NameObserved and final Drop/Destroy may run on a GC worker; callbacks must be concurrency-safe and must not call V8. TraceObserved is invoked whenever cppgc traces the graph object. Callback panics fail fast because they cannot unwind through cppgc.

type CppGCGenericGraphObservation

type CppGCGenericGraphObservation[T any] struct {
	State T
}

CppGCGenericGraphObservation is a copied edge observation. State is cloned through the target's codec and contains no borrowed managed pointer.

type CppGCGenericGraphOptions

type CppGCGenericGraphOptions[T any] struct {
	State       T
	Name        string
	StrongSlots uint32
	WeakSlots   uint32
	Traced      Value
	Callbacks   CppGCGenericGraphCallbacks[T]
}

CppGCGenericGraphOptions configures copied typed state and declarative traced slots. Slot counts are fixed for the object's lifetime; any number fitting uint32 is supported. Name is copied and must not contain NUL. Traced may be zero for an initially empty V8 traced reference.

type CppGCGenericLayout

type CppGCGenericLayout struct {
	Size              uint32
	Alignment         uint32
	AddressAligned    bool
	CellStorageStable bool
}

CppGCGenericLayout is a copied layout/storage observation. AddressAligned and CellStorageStable are computed natively without exposing either address.

type CppGCGenericObject

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

CppGCGenericObject is a strong native root for a copied-state cppgc object. Close releases the root; final destruction occurs at a later cppgc collection. Operations are isolate-owner-thread-only and never expose the managed address, GcCell reference, or Visitor.

func (*CppGCGenericObject) Cell

func (object *CppGCGenericObject) Cell() (int32, error)

Cell returns a copy of the object's scalar cell value.

func (*CppGCGenericObject) ClearOptionalMember

func (object *CppGCGenericObject) ClearOptionalMember() error

ClearOptionalMember assigns None. Collection of the former target remains asynchronous until a later cppgc collection.

func (*CppGCGenericObject) Close

func (object *CppGCGenericObject) Close() error

Close releases the strong root. It is idempotent; callbacks run only when a later collection destroys the now-unreachable allocation.

func (*CppGCGenericObject) Layout

func (object *CppGCGenericObject) Layout() (CppGCGenericLayout, error)

Layout returns copied logical-layout and native invariant observations.

func (*CppGCGenericObject) NewWeakPersistent

func (object *CppGCGenericObject) NewWeakPersistent() (*CppGCWeakPersistent, error)

NewWeakPersistent creates a weak observer initialized from this object.

func (*CppGCGenericObject) OptionalMember

func (object *CppGCGenericObject) OptionalMember() (CppGCObjectSnapshot, bool, error)

OptionalMember returns copied metadata for the traced member.

func (*CppGCGenericObject) SetCell

func (object *CppGCGenericObject) SetCell(value int32) error

SetCell replaces the copied scalar. CellDropped observes the replaced value synchronously, matching GcCell::set destruction timing.

func (*CppGCGenericObject) SetOptionalMember

func (object *CppGCGenericObject) SetOptionalMember(child *CppGCGenericObject) error

SetOptionalMember sets the object's traced Option<Member<T>> equivalent. Both objects remain independently rooted until their Close calls.

func (*CppGCGenericObject) UpdateCell

func (object *CppGCGenericObject) UpdateCell(delta int32) (int32, error)

UpdateCell adds delta in native storage and returns a copied result. Overflow is rejected without changing the cell.

type CppGCGenericOptions

type CppGCGenericOptions struct {
	ObjectID  int32
	Cell      int32
	Name      string
	Size      uint32
	Alignment uint32
	Callbacks CppGCGenericCallbacks
}

CppGCGenericOptions describes copied state stored in a native cppgc allocation. Size and Alignment describe the logical payload layout being adapted; the native managed envelope remains private. Alignment must be a power of two no greater than cppgc's public limit of 16. Name is copied and must not contain NUL.

type CppGCHeap

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

func NewCppGCHeap

func NewCppGCHeap(params CppGCHeapCreateParams) (*CppGCHeap, error)

func (*CppGCHeap) AllocateLeaf

func (h *CppGCHeap) AllocateLeaf(objectID int32, callbacks CppGCObjectCallbacks) (*CppGCHeapAllocation, error)

func (*CppGCHeap) AttachedTo

func (h *CppGCHeap) AttachedTo(i *Isolate) (bool, error)

func (*CppGCHeap) Close

func (h *CppGCHeap) Close() error

func (*CppGCHeap) CollectGarbageForTesting

func (h *CppGCHeap) CollectGarbageForTesting(state CppGCEmbedderStackState) error

func (*CppGCHeap) EnableDetachedGarbageCollectionsForTesting

func (h *CppGCHeap) EnableDetachedGarbageCollectionsForTesting() error

func (*CppGCHeap) Terminate

func (h *CppGCHeap) Terminate() error

type CppGCHeapAllocation

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

CppGCHeapAllocation observes an unrooted managed leaf without retaining or exposing its native address.

func (*CppGCHeapAllocation) Alive

func (a *CppGCHeapAllocation) Alive() bool

func (*CppGCHeapAllocation) ID

func (a *CppGCHeapAllocation) ID() int32

type CppGCHeapCreateParams

type CppGCHeapCreateParams struct {
	MarkingSupport  CppGCMarkingType
	SweepingSupport CppGCSweepingType
}

func DefaultCppGCHeapCreateParams

func DefaultCppGCHeapCreateParams() CppGCHeapCreateParams

type CppGCMarkingType

type CppGCMarkingType uint8
const (
	CppGCMarkingAtomic CppGCMarkingType = iota
	CppGCMarkingIncremental
	CppGCMarkingIncrementalAndConcurrent
)

func (CppGCMarkingType) String

func (v CppGCMarkingType) String() string

type CppGCMemberEdges

type CppGCMemberEdges struct {
	Strong        CppGCObjectSnapshot
	StrongPresent bool
	Weak          CppGCObjectSnapshot
	WeakPresent   bool
	SameTarget    bool
}

CppGCMemberEdges is a copied observation of the two graph edges embedded in a gov8 cppgc object. No native pointer escapes: absent or GC-cleared edges are represented by the corresponding Present field being false.

type CppGCObject

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

CppGCObject is a non-owning view of a cppgc allocation attached to a local API-wrapper object. V8 owns the allocation. The view is valid only while its wrapper's Scope is live; it never contains or exposes the native pointer.

func (*CppGCObject) ID

func (object *CppGCObject) ID() (int32, error)

ID returns the embedder scalar stored in the cppgc allocation.

func (*CppGCObject) Same

func (object *CppGCObject) Same(other *CppGCObject) (bool, error)

Same reports whether two views identify the same cppgc allocation. It does not compare native addresses.

func (*CppGCObject) Tag

func (object *CppGCObject) Tag() (CppGCTag, error)

Tag returns the exact tag used to wrap this allocation.

type CppGCObjectCallbacks

type CppGCObjectCallbacks struct {
	Trace   func()
	Destroy func()
}

CppGCObjectCallbacks observes cppgc tracing and final destruction. Either callback may be nil. V8 may trace on a GC worker, so callbacks must be concurrency-safe and must not call thread-affine V8 APIs. Destroy runs synchronously during sweeping or isolate teardown and must not re-enter its isolate (Isolate.Close holds the lifecycle lock during native teardown). A panic is a fail-fast host error because it cannot unwind through cppgc.

type CppGCObjectSnapshot

type CppGCObjectSnapshot struct {
	ObjectID int32
	Tag      CppGCTag
}

CppGCObjectSnapshot is copied metadata for an object reached through a cppgc persistent handle. It contains no native pointer and remains safe to inspect after the managed object is collected.

type CppGCPersistent

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

CppGCPersistent is a strong, native-owned cppgc root. It keeps its managed object alive independently of the JavaScript API wrapper. Operations are owner-thread-only. Isolate teardown releases an outstanding native handle; later Close remains idempotent, while Get and Set report the closed isolate.

func NewCppGCPersistent

func NewCppGCPersistent(object *CppGCObject) (*CppGCPersistent, error)

NewCppGCPersistent creates a strong cppgc root initialized from object.

func NewEmptyCppGCPersistent

func NewEmptyCppGCPersistent(iso *Isolate) (*CppGCPersistent, error)

NewEmptyCppGCPersistent creates an empty strong cppgc root.

func (*CppGCPersistent) ClearStrongMember

func (owner *CppGCPersistent) ClearStrongMember() error

ClearStrongMember makes the owner's strong edge empty. Collection remains asynchronous and occurs only at a later cppgc collection.

func (*CppGCPersistent) ClearWeakMember

func (owner *CppGCPersistent) ClearWeakMember() error

ClearWeakMember makes the owner's weak edge empty.

func (*CppGCPersistent) Close

func (persistent *CppGCPersistent) Close() error

Close releases the strong root. Close is idempotent.

func (*CppGCPersistent) Get

func (persistent *CppGCPersistent) Get() (CppGCObjectSnapshot, bool, error)

Get returns copied managed-object metadata, or ok=false when empty.

func (*CppGCPersistent) Matches

func (persistent *CppGCPersistent) Matches(object *CppGCObject) (bool, error)

Matches reports whether persistent currently points to object.

func (*CppGCPersistent) MemberEdges

func (owner *CppGCPersistent) MemberEdges() (CppGCMemberEdges, error)

MemberEdges returns both copied edge observations and whether they identify the same live allocation.

func (*CppGCPersistent) Set

func (persistent *CppGCPersistent) Set(object *CppGCObject) error

Set changes the managed object rooted by persistent.

func (*CppGCPersistent) SetFromPersistent

func (persistent *CppGCPersistent) SetFromPersistent(source *CppGCPersistent) error

SetFromPersistent changes the rooted object to the object currently held by source. An empty source clears persistent.

func (*CppGCPersistent) SetFromWeakPersistent

func (persistent *CppGCPersistent) SetFromWeakPersistent(source *CppGCWeakPersistent) error

SetFromWeakPersistent changes the rooted object to the object currently held by source. An empty source clears persistent.

func (*CppGCPersistent) SetStrongMember

func (owner *CppGCPersistent) SetStrongMember(child *CppGCObject) error

SetStrongMember assigns the owner's traced strong edge. child must be a live gov8 managed object from the same isolate and current Scope.

func (*CppGCPersistent) SetWeakMember

func (owner *CppGCPersistent) SetWeakMember(child *CppGCObject) error

SetWeakMember assigns the owner's traced weak edge. It never keeps child alive and is automatically cleared when child is collected.

func (*CppGCPersistent) StrongMember

func (owner *CppGCPersistent) StrongMember() (CppGCObjectSnapshot, bool, error)

StrongMember returns copied metadata for the strong target, if present.

func (*CppGCPersistent) WeakMember

func (owner *CppGCPersistent) WeakMember() (CppGCObjectSnapshot, bool, error)

WeakMember returns copied metadata for the weak target, if it has not been collected.

type CppGCSweepingType

type CppGCSweepingType uint8
const (
	CppGCSweepingAtomic CppGCSweepingType = iota
	CppGCSweepingIncremental
	CppGCSweepingIncrementalAndConcurrent
)

func (CppGCSweepingType) String

func (v CppGCSweepingType) String() string

type CppGCTag

type CppGCTag uint16

CppGCTag is the sandbox tag associated with a wrapped cppgc object. Tags are embedder-wide type identifiers; callers must use a stable tag for each native object family.

const MaxCppGCTag CppGCTag = 0x7ffe

MaxCppGCTag is the largest tag accepted by pinned V8 152.2.0. 0 is also a valid tag.

type CppGCWeakPersistent

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

CppGCWeakPersistent is a weak, native-owned cppgc handle. It does not keep its managed object alive and becomes empty when that object is collected. Operations are owner-thread-only. Isolate teardown releases an outstanding native handle; later Close remains idempotent.

func NewCppGCWeakPersistent

func NewCppGCWeakPersistent(object *CppGCObject) (*CppGCWeakPersistent, error)

NewCppGCWeakPersistent creates a weak cppgc handle initialized from object.

func NewEmptyCppGCWeakPersistent

func NewEmptyCppGCWeakPersistent(iso *Isolate) (*CppGCWeakPersistent, error)

NewEmptyCppGCWeakPersistent creates an empty weak cppgc handle.

func (*CppGCWeakPersistent) Close

func (persistent *CppGCWeakPersistent) Close() error

Close releases the weak handle. Close is idempotent.

func (*CppGCWeakPersistent) Get

func (persistent *CppGCWeakPersistent) Get() (CppGCObjectSnapshot, bool, error)

Get returns copied managed-object metadata, or ok=false when empty or after the weakly referenced object has been collected.

func (*CppGCWeakPersistent) Matches

func (persistent *CppGCWeakPersistent) Matches(object *CppGCObject) (bool, error)

Matches reports whether persistent currently points to object.

func (*CppGCWeakPersistent) Set

func (persistent *CppGCWeakPersistent) Set(object *CppGCObject) error

Set changes the managed object observed by persistent.

func (*CppGCWeakPersistent) SetFromPersistent

func (persistent *CppGCWeakPersistent) SetFromPersistent(source *CppGCPersistent) error

SetFromPersistent changes the observed object to the object currently held by source. An empty source clears persistent.

func (*CppGCWeakPersistent) SetFromWeakPersistent

func (persistent *CppGCWeakPersistent) SetFromWeakPersistent(source *CppGCWeakPersistent) error

SetFromWeakPersistent changes the observed object to the object currently held by source. An empty source clears persistent.

type CreateParams

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

CreateParams is the safe Go counterpart of v8::CreateParams for the options characterized by the pinned oracle. Custom allocators, raw stack limits at isolate construction and snapshots are composed by dedicated APIs. A custom cppgc heap may be transferred exactly once with SetCppGCHeap.

func NewCreateParams

func NewCreateParams() *CreateParams

NewCreateParams returns the Rust builder's defaults. The allocator flag is false before finalization and Atomics.wait is allowed.

func (*CreateParams) AllowAtomicsWait

func (p *CreateParams) AllowAtomicsWait() bool

func (*CreateParams) CodeRangeSizeInBytes

func (p *CreateParams) CodeRangeSizeInBytes() uint64

func (*CreateParams) ConfigureHeapLimits

func (p *CreateParams) ConfigureHeapLimits(initial, maximum uint64) error

ConfigureHeapLimits derives constraints from initial and maximum heap size.

func (*CreateParams) ConfigureHeapLimitsFromSystemMemory

func (p *CreateParams) ConfigureHeapLimitsFromSystemMemory(physical, virtual uint64) error

ConfigureHeapLimitsFromSystemMemory derives constraints from physical and virtual memory limits using V8's platform-exact formula.

func (*CreateParams) HasEmptyExternalReferences

func (p *CreateParams) HasEmptyExternalReferences() bool

func (*CreateParams) HasExternalReferences

func (p *CreateParams) HasExternalReferences() bool

HasExternalReferences reports whether SetExternalReferences or UseEmptyExternalReferences was called. It distinguishes an explicitly empty table from the CreateParams default, which leaves the V8 pointer null.

func (*CreateParams) HasSetArrayBufferAllocator

func (p *CreateParams) HasSetArrayBufferAllocator() bool

func (*CreateParams) InitialOldGenerationSizeInBytes

func (p *CreateParams) InitialOldGenerationSizeInBytes() uint64

func (*CreateParams) InitialYoungGenerationSizeInBytes

func (p *CreateParams) InitialYoungGenerationSizeInBytes() uint64

func (*CreateParams) MaxOldGenerationSizeInBytes

func (p *CreateParams) MaxOldGenerationSizeInBytes() uint64

func (*CreateParams) MaxYoungGenerationSizeInBytes

func (p *CreateParams) MaxYoungGenerationSizeInBytes() uint64

func (*CreateParams) SetAllowAtomicsWait

func (p *CreateParams) SetAllowAtomicsWait(value bool) *CreateParams

func (*CreateParams) SetArrayBufferAllocator

func (p *CreateParams) SetArrayBufferAllocator(allocator *ArrayBufferAllocator) error

SetArrayBufferAllocator configures a shared default or callback-backed allocator. The allocator must remain open until NewIsolateWithParams has copied its native shared reference; it may be closed immediately afterward.

func (*CreateParams) SetCodeRangeSizeInBytes

func (p *CreateParams) SetCodeRangeSizeInBytes(value uint64) *CreateParams

func (*CreateParams) SetCounterLookupCallback

func (p *CreateParams) SetCounterLookupCallback(callback CounterLookupCallback) *CreateParams

func (*CreateParams) SetCppGCHeap

func (p *CreateParams) SetCppGCHeap(heap *CppGCHeap) error

SetCppGCHeap selects a custom cppgc heap for one future isolate. The heap is claimed immediately and ownership transfers when native construction accepts it; it cannot be reused by another CreateParams or as detached.

func (*CreateParams) SetExternalReferences

func (p *CreateParams) SetExternalReferences(references []ExternalReference) *CreateParams

SetExternalReferences configures an optional external-reference table. The slice is copied immediately. The shim makes a second native copy, appends a null terminator when absent, and retains that table through isolate disposal. Calling this with an empty slice is equivalent to rusty_v8's empty Cow: an explicit one-element native table containing only the null terminator.

func (*CreateParams) SetInitialOldGenerationSizeInBytes

func (p *CreateParams) SetInitialOldGenerationSizeInBytes(value uint64) *CreateParams

func (*CreateParams) SetInitialYoungGenerationSizeInBytes

func (p *CreateParams) SetInitialYoungGenerationSizeInBytes(value uint64) *CreateParams

func (*CreateParams) SetMaxOldGenerationSizeInBytes

func (p *CreateParams) SetMaxOldGenerationSizeInBytes(value uint64) *CreateParams

func (*CreateParams) SetMaxYoungGenerationSizeInBytes

func (p *CreateParams) SetMaxYoungGenerationSizeInBytes(value uint64) *CreateParams

func (*CreateParams) SetStackLimit

func (p *CreateParams) SetStackLimit(value uintptr) *CreateParams

SetStackLimit records a pointer for getter parity only. NewIsolateWithParams rejects a non-zero value because a Go-stack address is not a stable native stack boundary for an isolate lifetime.

func (*CreateParams) StackLimit

func (p *CreateParams) StackLimit() uintptr

func (*CreateParams) UseDefaultArrayBufferAllocator

func (p *CreateParams) UseDefaultArrayBufferAllocator() *CreateParams

UseDefaultArrayBufferAllocator configures the engine's default allocator. Arbitrary allocator callbacks are excluded because Go function/data pointers cannot safely implement V8's allocator lifetime contract.

func (*CreateParams) UseEmptyExternalReferences

func (p *CreateParams) UseEmptyExternalReferences() *CreateParams

UseEmptyExternalReferences installs a process-lifetime, null-terminated empty external-reference table. Non-empty raw address tables are excluded.

type CustomPlatformOptions

type CustomPlatformOptions struct {
	ThreadPoolSize  uint32
	IdleTaskSupport bool
	Unprotected     bool
}

CustomPlatformOptions configures the DefaultPlatform-backed custom task dispatcher installed by ConfigureCustomPlatform. ThreadPoolSize follows rusty_v8: zero selects the hardware default and values above 16 are clamped.

type Data

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

Data is a scope-local handle to any V8 heap data. Unlike Value, Data can also represent metadata-only engine objects such as FixedArray and ModuleRequest. It follows the same scope, isolate, and thread-affinity rules as Value.

func (Data) Equal

func (d Data) Equal(other Data) (bool, error)

Equal reports V8 Data identity. Both locals must be live and belong to the same isolate; unlike Value.StrictEquals this does not perform JS equality.

func (Data) IsBigInt

func (d Data) IsBigInt() (bool, error)

The Data predicate family mirrors every public Data::is_* method in the pinned crate. They are valid for both JavaScript Values and metadata locals.

func (Data) IsBoolean

func (d Data) IsBoolean() (bool, error)

func (Data) IsContext

func (d Data) IsContext() (bool, error)

func (Data) IsFixedArray

func (d Data) IsFixedArray() (bool, error)

IsFixedArray reports whether the data is a FixedArray.

func (Data) IsFunctionTemplate

func (d Data) IsFunctionTemplate() (bool, error)

func (Data) IsModule

func (d Data) IsModule() (bool, error)

func (Data) IsModuleRequest

func (d Data) IsModuleRequest() (bool, error)

IsModuleRequest reports whether the data is a ModuleRequest.

func (Data) IsName

func (d Data) IsName() (bool, error)

func (Data) IsNumber

func (d Data) IsNumber() (bool, error)

func (Data) IsObjectTemplate

func (d Data) IsObjectTemplate() (bool, error)

func (Data) IsPrimitive

func (d Data) IsPrimitive() (bool, error)

IsPrimitive reports whether the data is a JavaScript primitive Value.

func (Data) IsPrivate

func (d Data) IsPrivate() (bool, error)

func (Data) IsString

func (d Data) IsString() (bool, error)

func (Data) IsSymbol

func (d Data) IsSymbol() (bool, error)

func (Data) IsValue

func (d Data) IsValue() (bool, error)

IsValue reports whether the data can be viewed as a JavaScript Value.

func (Data) ModuleRequest

func (d Data) ModuleRequest() (*ModuleRequestData, bool, error)

ModuleRequest converts data known to hold module request metadata.

func (Data) Value

func (d Data) Value() (Value, bool, error)

Value converts data known to be a JavaScript Value. ok is false for metadata-only Data.

type DataErrorKind

type DataErrorKind uint8

DataErrorKind mirrors v8::DataError: NoData for consumed or out-of-range indices, BadType for a wrongly typed request.

const (
	DataErrorNoData DataErrorKind = iota + 1
	DataErrorBadType
)

type DataView

type DataView struct {
	Value
}

DataView is a scope-local DataView.

func AsDataView

func AsDataView(v Value) (*DataView, error)

AsDataView converts a generic value into a DataView view of it.

func NewDataView

func NewDataView(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*DataView, error)

NewDataView creates a DataView over ab's bytes [byteOffset, byteOffset+length). Out-of-bounds geometry is an error (the engine would CHECK-abort; the shim prevalidates).

func (*DataView) Buffer

func (dv *DataView) Buffer() (*ArrayBuffer, error)

Buffer returns the DataView's underlying ArrayBuffer.

func (*DataView) ByteLength

func (dv *DataView) ByteLength() (int, error)

ByteLength returns the view's size in bytes.

func (*DataView) ByteOffset

func (dv *DataView) ByteOffset() (int, error)

ByteOffset returns the view's offset into its buffer.

func (*DataView) CopyContents

func (dv *DataView) CopyContents(dst []byte) (int, error)

CopyContents copies at most len(dst) bytes of the DataView's contents into dst (ArrayBufferView::CopyContents) and returns the number of bytes written. The copy includes the byte offset: a DataView at offset 3 copies buffer bytes 3..3+min(len(dst), byteLength).

func (*DataView) Data

func (dv *DataView) Data() (uintptr, bool, error)

Data returns the view's engine-side data pointer; see TypedArray.Data.

func (*DataView) GetBackingStore

func (dv *DataView) GetBackingStore() (*BackingStore, error)

GetBackingStore returns a NEW counted reference to the DataView buffer's backing store; see TypedArray.GetBackingStore.

func (*DataView) GetContents

func (dv *DataView) GetContents(storage []byte) (ViewContents, error)

GetContents copies up to len(storage) bytes of the DataView's live contents into storage and describes the full span; see TypedArray.GetContents.

type Date

type Date struct{ Value }

Date is a JS Date object.

func AsDate

func AsDate(v Value) (*Date, error)

AsDate casts a value to a Date after prevalidating the engine kind.

func (*Date) ValueOf

func (d *Date) ValueOf() (float64, error)

ValueOf returns the stored time value (NaN for an invalid date).

type DelegateValueDeserializer

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

DelegateValueDeserializer is a ValueDeserializer whose delegate can implement the pinned crate's deserializer hook surface. Created by NewDelegateValueDeserializer; a nil delegate reproduces the trait defaults (every read path throws the deterministic "not implemented" error).

func NewDelegateValueDeserializer

func NewDelegateValueDeserializer(s *Scope, c *Context, data []byte, d ValueDeserializerDelegate) (*DelegateValueDeserializer, error)

NewDelegateValueDeserializer creates a delegate-completed deserializer over data (no copy) bound to the context's isolate. d may be nil (trait defaults). data must not be mutated while the deserializer is open.

func (*DelegateValueDeserializer) Close

func (vd *DelegateValueDeserializer) Close() error

Close destroys the engine deserializer (which releases its reference to the input bytes), then the shim delegate, then unregisters the Go delegate. Only after this call may the caller reuse or free the input slice.

func (*DelegateValueDeserializer) Context

func (vd *DelegateValueDeserializer) Context() *Context

Context returns the context the deserializer reads against.

func (*DelegateValueDeserializer) GetWireFormatVersion

func (vd *DelegateValueDeserializer) GetWireFormatVersion() (uint32, error)

GetWireFormatVersion reports the wire format version of the data (0 for header-less/legacy data; must be called after ReadHeader for versioned data to be meaningful).

func (*DelegateValueDeserializer) NewError

func (vd *DelegateValueDeserializer) NewError(message string) (Value, error)

NewError builds a JS Error object in the hook's scope (for hooks that throw their own failure instead of answering None).

func (*DelegateValueDeserializer) ReadDouble

func (vd *DelegateValueDeserializer) ReadDouble() (val float64, ok bool, err error)

ReadDouble reads one little-endian f64 (for use inside ReadHostObject).

func (*DelegateValueDeserializer) ReadHeader

func (vd *DelegateValueDeserializer) ReadHeader(c *Context, tc *TryCatch) (ok bool, err error)

ReadHeader reads and validates the wire-format header. ok is false when the header was absent (not an error); an invalid header throws (IsException, details in tc — nil uses a shim-internal fallback). Reads after ReadHeader report the header's wire format version through GetWireFormatVersion.

func (*DelegateValueDeserializer) ReadRawBytes

func (vd *DelegateValueDeserializer) ReadRawBytes(length int) (data []byte, ok bool, err error)

ReadRawBytes copies the next length bytes out of the wire (for use inside ReadHostObject). The bytes are copied at the boundary: Go owns the returned slice. ok is false when the wire is exhausted (V8 only advances its position on success).

func (*DelegateValueDeserializer) ReadUint32

func (vd *DelegateValueDeserializer) ReadUint32() (val uint32, ok bool, err error)

ReadUint32 reads one varint u32 (for use inside ReadHostObject). ok is false when the wire is exhausted.

func (*DelegateValueDeserializer) ReadUint64

func (vd *DelegateValueDeserializer) ReadUint64() (val uint64, ok bool, err error)

ReadUint64 reads one varint u64 (for use inside ReadHostObject).

func (*DelegateValueDeserializer) ReadValue

func (vd *DelegateValueDeserializer) ReadValue(c *Context, tc *TryCatch) (Value, error)

ReadValue deserializes the next value. A returned error satisfying IsException means the engine threw (invalid wire data, an unregistered or unanswered transfer id, a rejected host object, ...); the details are in tc (nil uses a shim-internal fallback), exactly like the crate's read_value returning None.

func (*DelegateValueDeserializer) Scope

func (vd *DelegateValueDeserializer) Scope() *Scope

Scope returns the scope the deserializer was created with; hooks build returned values through it.

func (*DelegateValueDeserializer) SetSupportsLegacyWireFormat

func (vd *DelegateValueDeserializer) SetSupportsLegacyWireFormat(enabled bool) error

SetSupportsLegacyWireFormat is the delegate-backed counterpart of ValueDeserializer.SetSupportsLegacyWireFormat.

func (*DelegateValueDeserializer) ThrowException

func (vd *DelegateValueDeserializer) ThrowException(v Value) error

ThrowException schedules v to propagate out of the failing read.

func (*DelegateValueDeserializer) TransferArrayBuffer

func (vd *DelegateValueDeserializer) TransferArrayBuffer(id uint32, ab *ArrayBuffer) error

TransferArrayBuffer registers the receiving buffer for transfer id (reader-side maps are keyed by id: re-registering an id replaces its target, last registration wins).

func (*DelegateValueDeserializer) TransferSharedArrayBuffer

func (vd *DelegateValueDeserializer) TransferSharedArrayBuffer(id uint32, sab *SharedArrayBuffer) error

TransferSharedArrayBuffer registers the receiving SAB for id (v8::ValueDeserializer::TransferSharedArrayBuffer). Pinned semantics note: SAB reads on this build never consult these registrations — the GetSharedArrayBufferFromID hook is always the source.

type DelegateValueSerializer

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

DelegateValueSerializer is a ValueSerializer whose delegate can implement the full pinned crate hook surface (see the hook interfaces above). It is created by NewDelegateValueSerializer; plain wire production (WriteHeader, WriteValue, TransferArrayBuffer, Release) and direct helper writes (WriteUint32 / ...) mirror the crate's ValueSerializer and its helper trait. Close is explicit and required; there are no finalizers.

func NewDelegateValueSerializer

func NewDelegateValueSerializer(s *Scope, c *Context, d ValueSerializerDelegate) (*DelegateValueSerializer, error)

NewDelegateValueSerializer creates a delegate-completed serializer bound to the scope's isolate and the given context. d must implement ValueSerializerDelegate (throw_data_clone_error is the one required hook, as in the crate); the optional hook interfaces above are detected from d.

func (*DelegateValueSerializer) Close

func (vs *DelegateValueSerializer) Close() error

Close destroys the engine serializer and unregisters the Go delegate. The delegate can no longer be invoked afterwards. Close must be called on the owning thread before the scope closes. An un-released wire buffer is freed by the engine destructor through the shim delegate (the crate's drop path).

func (*DelegateValueSerializer) Context

func (vs *DelegateValueSerializer) Context() *Context

Context returns the context the serializer writes against.

func (*DelegateValueSerializer) NewError

func (vs *DelegateValueSerializer) NewError(message string) (Value, error)

NewError builds a JS Error object in the hook's scope (for hooks that throw their own failure).

func (*DelegateValueSerializer) NewRangeError

func (vs *DelegateValueSerializer) NewRangeError(message string) (Value, error)

NewRangeError builds a JS RangeError object in the hook's scope (v8::Exception::RangeError).

func (*DelegateValueSerializer) Release

func (vs *DelegateValueSerializer) Release() ([]byte, error)

Release returns the accumulated wire bytes and makes the serializer unusable. A second Release returns empty bytes and no error, exactly like the crate's release() (fixture-pinned). Close after Release is still required and still valid (the destructor path frees nothing then).

func (*DelegateValueSerializer) Scope

func (vs *DelegateValueSerializer) Scope() *Scope

Scope returns the scope the serializer was created with; hooks build returned values through it (the engine scope is open during the hook).

func (*DelegateValueSerializer) SetTreatArrayBufferViewsAsHostObjects

func (vs *DelegateValueSerializer) SetTreatArrayBufferViewsAsHostObjects(mode bool) error

SetTreatArrayBufferViewsAsHostObjects routes ArrayBufferViews (typed arrays, DataViews) to WriteHostObject instead of the native view codec (v8::ValueSerializer::SetTreatArrayBufferViewsAsHostObjects).

func (*DelegateValueSerializer) ThrowException

func (vs *DelegateValueSerializer) ThrowException(v Value) error

ThrowException schedules v to propagate out of the failing write (the delegate-drives-the-exception completion path). The write then fails with the exception pending; an enclosing TryCatch observes it verbatim.

func (*DelegateValueSerializer) TransferArrayBuffer

func (vs *DelegateValueSerializer) TransferArrayBuffer(id uint32, ab *ArrayBuffer) error

TransferArrayBuffer marks ab as transferred out of band under the given id (writer-side maps are keyed by buffer: re-registering the same buffer replaces its id, last registration wins).

func (*DelegateValueSerializer) WriteDouble

func (vs *DelegateValueSerializer) WriteDouble(value float64) error

WriteDouble appends value as a little-endian 64-bit double.

func (*DelegateValueSerializer) WriteHeader

func (vs *DelegateValueSerializer) WriteHeader() error

WriteHeader writes the wire-format version header (version 16 bytes "ff 10" on this build).

func (*DelegateValueSerializer) WriteRawBytes

func (vs *DelegateValueSerializer) WriteRawBytes(data []byte) error

WriteRawBytes appends the raw bytes with NO length prefix: framing is entirely the writer's job (v8::ValueSerializer::WriteRawBytes).

func (*DelegateValueSerializer) WriteUint32

func (vs *DelegateValueSerializer) WriteUint32(value uint32) error

WriteUint32 appends value in base-128 varint form (the helper write used inside WriteHostObject; usable outside hooks too).

func (*DelegateValueSerializer) WriteUint64

func (vs *DelegateValueSerializer) WriteUint64(value uint64) error

WriteUint64 appends value in base-128 varint form.

func (*DelegateValueSerializer) WriteValue

func (vs *DelegateValueSerializer) WriteValue(c *Context, v Value, tc *TryCatch) (ok bool, err error)

WriteValue serializes value into the wire buffer. ok is false when the value could not be serialized; when the write threw (delegated hook failure, the default host-object error, the engine's SAB rejection, ...) the returned error satisfies IsException and the details are in tc (nil uses a shim-internal fallback, in which case the exception is not observable).

type DisallowJavascriptExecutionScope

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

DisallowJavascriptExecutionScope is a lexical engine guard. It must Close in strict LIFO order on the isolate's owner thread.

func (*DisallowJavascriptExecutionScope) Close

Close restores the execution state that preceded the disallow guard.

func (*DisallowJavascriptExecutionScope) NewAllowJavascriptExecutionScope

func (d *DisallowJavascriptExecutionScope) NewAllowJavascriptExecutionScope() (*AllowJavascriptExecutionScope, error)

NewAllowJavascriptExecutionScope temporarily permits JavaScript inside this currently active disallow guard.

type DynamicImportCallback

type DynamicImportCallback func(DynamicImportRequest) (Promise, error)

DynamicImportCallback returns the promise forwarded to JavaScript.

type DynamicImportRequest

type DynamicImportRequest struct {
	Scope              *CallbackScope
	HostDefinedOptions Data
	ResourceName       Value
	Specifier          Value
	Phase              ModuleImportPhase
	Attributes         *FixedArray
}

DynamicImportRequest contains callback-local host import arguments.

type EntropySource

type EntropySource func(buf []byte) bool

EntropySource fills buf with entropy bytes and reports whether it did. Returning false declines; the engine then uses its default randomness source. It runs on engine threads (any thread, including background compilation workers) and must not re-enter the engine or retain buf.

type EscapableScope

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

EscapableScope is a v8 EscapableHandleScope: one value can be "escaped" out of it into the scope it was created under, surviving this scope's closure. Escape may be called exactly once (the pinned crate's guard).

func (*EscapableScope) Close

func (e *EscapableScope) Close() error

Close closes the escapable scope. Values created inside it (other than the escaped one) become invalid.

func (*EscapableScope) Escape

func (e *EscapableScope) Escape(v Value) (Value, error)

Escape pushes v into the outer scope and returns the escaped handle bound to the outer scope (valid after this escapable scope closes). A second escape on the same scope returns the pinned crate's error verbatim; the engine is not touched (its release-mode Escape would silently corrupt the first escaped value by overwriting the escape slot).

type Eternal

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

Eternal is V8's set-once-style persistent handle. The pinned engine also accepts another Set while non-empty and makes the new value observable; this wrapper deliberately preserves that characterized overwrite behavior.

Eternal differs from Global: clearing only empties the Eternal wrapper. V8 owns the eternal-table entry for the isolate lifetime. Close destroys the small host wrapper and must be called deterministically.

func EmptyEternal

func EmptyEternal() (*Eternal, error)

EmptyEternal constructs an empty Eternal, corresponding to v8::Eternal::empty. The pinned API has no constructor that takes a Local; initialize (and later overwrite or reuse) it with Set.

func (*Eternal) Clear

func (e *Eternal) Clear() error

Clear empties the Eternal. While its isolate is live, Clear is thread-affine. The pinned subprocess oracle also proves Clear safe after the isolate is closed, including when the Eternal was still non-empty.

func (*Eternal) Close

func (e *Eternal) Close() error

Close destroys the host-side Eternal wrapper. It does not need a live isolate; the pinned destructor is safe after isolate disposal.

func (*Eternal) Get

func (e *Eternal) Get(s *Scope) (value Value, ok bool, err error)

Get reopens the Eternal as a local in s. ok is false while it is empty. The scope must belong to the isolate on which the Eternal was first set.

func (*Eternal) IsEmpty

func (e *Eternal) IsEmpty() (bool, error)

IsEmpty reports whether the Eternal currently contains a value. A handle bound to a live isolate remains thread-affine. Once that isolate is closed, this pure opaque-slot query remains safe, as established by the oracle.

func (*Eternal) Set

func (e *Eternal) Set(s *Scope, v Value) error

Set stores v in the Eternal. Repeated Set calls on the same isolate are allowed and overwrite the value on the pinned V8 build.

type ExternalOneByteConst

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

ExternalOneByteConst is a build-time-style external one-byte resource (the Go analog of the crate's OneByteConst): created once from ASCII data, shareable across isolates, never disposed, process-lifetime. There is deliberately no Close: matching the Rust &'static, the resource must outlive every external string created from it in any isolate, and V8 may finalize those long after the embedding code's references are gone.

func CreateExternalOneByteConst

func CreateExternalOneByteConst(data string) (*ExternalOneByteConst, error)

CreateExternalOneByteConst creates a shared const resource from ASCII data. The data is copied; the Go string is not retained by the engine.

func (*ExternalOneByteConst) Data

func (r *ExternalOneByteConst) Data() string

Data returns the resource's ASCII contents (the as_str analog).

type ExternalReference

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

ExternalReference is one raw address in V8's external-reference table. It is comparable, like rusty_v8's Copy union, but opaque so a Go pointer cannot be confused with an ordinary Go object reference.

Non-zero raw addresses must identify native code or native data which stays valid for every isolate using the reference. A Go heap or stack address does not satisfy that contract. NewCallbackExternalReference is the safe way to obtain addresses for callbacks implemented by gov8.

func NewCallbackExternalReference

func NewCallbackExternalReference(kind ExternalReferenceCallbackKind) (ExternalReference, error)

NewCallbackExternalReference returns the native shared trampoline address for a gov8 callback kind. The result is process-lifetime and may be reused by any CreateParams external-reference table.

func NewExternalReference

func NewExternalReference(address uintptr) ExternalReference

NewExternalReference constructs a reference from a native address. Zero is the table terminator. The caller owns the pointed-to native allocation and must keep it alive for the isolate lifetime.

func (ExternalReference) Address

func (r ExternalReference) Address() uintptr

Address returns the represented native address.

func (ExternalReference) IsNull

func (r ExternalReference) IsNull() bool

IsNull reports whether the reference is V8's table terminator.

func (ExternalReference) String

func (r ExternalReference) String() string

type ExternalReferenceCallbackKind

type ExternalReferenceCallbackKind int32

ExternalReferenceCallbackKind selects one process-lifetime native trampoline used by gov8's callback implementation. Named and indexed enumerators need distinct constants in Go even though rusty_v8 exposes both through the same union field type.

const (
	ExternalReferenceFunction ExternalReferenceCallbackKind = iota
	ExternalReferenceNamedGetter
	ExternalReferenceNamedSetter
	ExternalReferenceNamedDefiner
	ExternalReferenceNamedDeleter
	ExternalReferenceNamedQuery
	ExternalReferenceIndexedGetter
	ExternalReferenceIndexedSetter
	ExternalReferenceIndexedDefiner
	ExternalReferenceIndexedDeleter
	ExternalReferenceIndexedQuery
	ExternalReferenceNamedEnumerator
	ExternalReferenceIndexedEnumerator
	ExternalReferenceMessage
)

type ExternalStringDeleter

type ExternalStringDeleter func(data uintptr, length int)

ExternalStringDeleter observes the release of a raw external string's buffer: exactly one call with the payload address and its length, at the first forced major GC after the last strong reference drops (or during isolate disposal while the string is alive). It must be pure Go: it runs inside engine GC / teardown, where re-entering the engine is not permitted. The shim frees the buffer after the callback returns; the callback must not retain the address.

type FastInt64Representation

type FastInt64Representation uint8

FastInt64Representation selects the JavaScript representation of 64-bit integer arguments and results.

const (
	FastInt64AsNumber FastInt64Representation = iota
	FastInt64AsBigInt
)

type FastType

type FastType uint8

FastType mirrors v8::CTypeInfo::Type in pinned V8 15.2. The callback options marker is the upstream out-of-enum sentinel 255.

const (
	FastTypeVoid FastType = iota
	FastTypeBool
	FastTypeUint8
	FastTypeInt32
	FastTypeUint32
	FastTypeInt64
	FastTypeUint64
	FastTypeFloat32
	FastTypeFloat64
	FastTypePointer
	FastTypeV8Value
	FastTypeSeqOneByteString
	FastTypeAPIObject
	FastTypeAny

	FastTypeCallbackOptions FastType = 255
)

func (FastType) Info

func (t FastType) Info() (FastTypeInfo, error)

Info returns flag-free metadata for the type.

type FastTypeFlags

type FastTypeFlags uint8

FastTypeFlags mirrors v8::CTypeInfo::Flags.

const (
	FastTypeAllowShared FastTypeFlags = 1 << iota
	FastTypeEnforceRange
	FastTypeClamp
	FastTypeIsRestricted
)

func FastTypeFlagsFromBits

func FastTypeFlagsFromBits(bits uint8) (FastTypeFlags, bool)

FastTypeFlagsFromBits returns flags only when every bit is known.

func FastTypeFlagsFromBitsTruncated

func FastTypeFlagsFromBitsTruncated(bits uint8) FastTypeFlags

FastTypeFlagsFromBitsTruncated drops unknown bits.

type FastTypeInfo

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

FastTypeInfo is immutable metadata corresponding to v8::CTypeInfo. Use NewFastTypeInfo so invalid enum and flag combinations are rejected before the engine's CHECK boundaries.

func NewFastTypeInfo

func NewFastTypeInfo(fastType FastType, flags FastTypeFlags) (FastTypeInfo, error)

NewFastTypeInfo constructs validated fast-call type metadata.

func (FastTypeInfo) Flags

func (i FastTypeInfo) Flags() FastTypeFlags

Flags reports the type flags.

func (FastTypeInfo) Identifier

func (i FastTypeInfo) Identifier() uint32

Identifier reports CTypeInfo::GetId (type in the high byte, flags in the low byte).

func (FastTypeInfo) Type

func (i FastTypeInfo) Type() FastType

Type reports the V8 fast-call type.

type FatalErrorHandler

type FatalErrorHandler func(file string, line int32, message string)

FatalErrorHandler observes engine fatal CHECK failures (file is "" and line 0 in official builds). It may run on any engine thread in a broken process state: it must not re-enter the engine. When it returns, the engine aborts the process — this handler only observes.

type FixedArray

type FixedArray struct{ Data }

FixedArray is V8's fixed-sized, read-only array of Data values.

func (*FixedArray) Get

func (a *FixedArray) Get(s *Scope, index int) (Data, bool, error)

Get returns the element at index. Out-of-range indices return ok=false and never enter V8's unchecked FixedArray::Get path.

func (*FixedArray) Length

func (a *FixedArray) Length() (int, error)

Length returns the number of elements.

type Function

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

Function is a JS function object created natively (from a template via GetFunction, or directly via Isolate.NewFunction). It is a scope-local value bound to the context it was created for.

func AsFunction

func AsFunction(v Value, c *Context) (*Function, bool, error)

AsFunction converts a function-valued scope-local value into a *Function bound to the given context (the Go analog of the crate's Local<Function>::try_from). The value and context must belong to the same isolate; ok is false when the value is not a function.

func (*Function) BoundTarget

func (f *Function) BoundTarget() (Value, error)

BoundTarget returns the original target for a bound function. For an unbound function it returns JavaScript undefined, matching GetBoundFunction.

func (*Function) Call

func (f *Function) Call(s *Scope, recv Value, args ...Value) (Value, bool, error)

Call invokes the function (v8 Function::Call). The receiver and arguments must belong to the same isolate; the result wire lives in the given scope. ok is false when the call threw (the exception is recorded by the active TryCatch).

func (*Function) CreateCodeCache

func (f *Function) CreateCodeCache() (*FunctionCodeCache, error)

CreateCodeCache creates cache data for a function compiled by CompileFunctionAdvanced. Provenance is checked in Go before the fatal V8 API is entered.

func (*Function) Name

func (f *Function) Name() (string, error)

Name returns the function's `name` property text.

func (*Function) NewInstance

func (f *Function) NewInstance(s *Scope, args ...Value) (*Object, bool, error)

NewInstance performs a host-side construct call (v8 Function::new_instance): the construct callback receives the freshly created instance as its receiver. ok is false when the call threw.

func (*Function) ScriptColumnNumber

func (f *Function) ScriptColumnNumber() (column int32, ok bool, err error)

ScriptColumnNumber returns the zero-based function definition column. ok is false for native functions and other functions without source metadata.

func (*Function) ScriptID

func (f *Function) ScriptID() (int32, error)

ScriptID returns Function::ScriptId (zero for a native function).

func (*Function) ScriptLineNumber

func (f *Function) ScriptLineNumber() (line int32, ok bool, err error)

ScriptLineNumber returns the zero-based function definition line. ok is false for native functions and other functions without source metadata.

func (*Function) ScriptOrigin

func (f *Function) ScriptOrigin() (FunctionScriptOrigin, error)

ScriptOrigin returns Function::GetScriptOrigin.

func (*Function) SetName

func (f *Function) SetName(name string) error

SetName sets Function::SetName. V8 intentionally ignores this operation on bound functions; no special case is applied by Go.

type FunctionBuilder

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

FunctionBuilder is the Go counterpart of v8::FunctionBuilder. Builder methods mutate and return the builder so calls can be chained.

func (*FunctionBuilder) Build

func (b *FunctionBuilder) Build(s *Scope, c *Context) (*Function, error)

Build creates the function in c and binds its local handle to s.

func (*FunctionBuilder) BuildFast

func (b *FunctionBuilder) BuildFast(s *Scope, overloads []CFunction) (*FunctionTemplate, error)

BuildFast creates a FunctionTemplate with native fast-call overloads and this builder's ordinary Go callback as its slow fallback. Like rusty_v8's FunctionBuilder::build_fast, construction is always forbidden even if the builder's ConstructorBehavior option was set to Allow.

func (*FunctionBuilder) ConstructorBehavior

func (b *FunctionBuilder) ConstructorBehavior(behavior ConstructorBehavior) *FunctionBuilder

ConstructorBehavior selects regular (allow) or concise (throw) behavior.

func (*FunctionBuilder) Data

func (b *FunctionBuilder) Data(data Value) *FunctionBuilder

Data sets the callback data value.

func (*FunctionBuilder) Length

func (b *FunctionBuilder) Length(length int) *FunctionBuilder

Length sets the function's length property.

func (*FunctionBuilder) SideEffectType

func (b *FunctionBuilder) SideEffectType(sideEffectType SideEffectType) *FunctionBuilder

SideEffectType sets debugger side-effect metadata for the callback.

type FunctionCallback

type FunctionCallback func(cs *CallbackScope, args FunctionCallbackArguments, rv ReturnValue)

FunctionCallback mirrors v8::FunctionCallback. cs carries the callback's scope, the engine's current context and native re-entry helpers; args are the JS call arguments; rv receives the return value (undefined when the callback sets nothing).

type FunctionCallbackArguments

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

FunctionCallbackArguments mirrors v8::FunctionCallbackArguments. Length and IsConstructCall are immutable Go-owned snapshots and remain safe to inspect on a copied wrapper. Get, This, NewTarget and Data expose engine locals and are valid only while the callback is running; they validate the callback's borrowed Scope before reading the trampoline-owned native frame. Get returns undefined for out-of-bounds indices (matching the crate's bounds handling), This is the receiver, NewTarget is the constructor function for construct calls and undefined otherwise, and Data is the callback data attached at creation time.

func (FunctionCallbackArguments) Data

Data returns the callback data attached when the function (template) was created; undefined when none was attached.

func (FunctionCallbackArguments) Get

Get returns the argument at index i, or undefined when out of bounds.

func (FunctionCallbackArguments) IsConstructCall

func (a FunctionCallbackArguments) IsConstructCall() bool

IsConstructCall reports whether this is a `new F(..)` construct call.

func (FunctionCallbackArguments) Length

func (a FunctionCallbackArguments) Length() int

Length returns the number of actually passed arguments.

func (FunctionCallbackArguments) NewTarget

func (a FunctionCallbackArguments) NewTarget() (Value, error)

NewTarget returns new.target: the constructor function for construct calls, undefined for plain calls.

func (FunctionCallbackArguments) This

func (a FunctionCallbackArguments) This() (*Object, error)

This returns the call receiver (the created instance for construct calls).

type FunctionCodeCache

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

FunctionCodeCache is engine-produced cache data for a CompileFunction result. Its payload is intentionally opaque: accepting arbitrary bytes would expose V8 152's process-fatal deserializer boundary. A cache remains usable after its producer isolate closes and can therefore be consumed in another isolate.

func (*FunctionCodeCache) Len

func (c *FunctionCodeCache) Len() int

Len returns the cache payload size.

type FunctionCodeHandling

type FunctionCodeHandling int32

FunctionCodeHandling mirrors v8::SnapshotCreator::FunctionCodeHandling.

const (
	// FunctionCodeClear drops compiled function code from the snapshot.
	FunctionCodeClear FunctionCodeHandling = 0
	// FunctionCodeKeep keeps compiled function code in the snapshot.
	FunctionCodeKeep FunctionCodeHandling = 1
)

type FunctionOptions

type FunctionOptions struct {
	// Length is the value of the JS function's `length` property. Every int32
	// value is accepted; V8 stores the observable API-function length in its
	// uint16 representation. Values outside int32 are rejected before V8.
	Length int
	// Data is the callback data observed via args.Data(); zero Value means
	// none. It must belong to the same isolate as the template/function.
	Data Value
	// Signature restricts the valid receivers to instances of the
	// signature's function template (or of templates inheriting from it);
	// nil means unrestricted. Template creation only.
	Signature *Signature
	// ConstructorBehavior controls whether the template's function can be
	// constructed (`new`). Zero value = engine default (allow).
	ConstructorBehavior ConstructorBehavior
	// SideEffectType is debugger metadata for throwOnSideEffect evaluation.
	// The zero value is the engine default (HasSideEffect).
	SideEffectType SideEffectType
}

FunctionOptions mirrors the FunctionTemplate/Function builder knobs the pinned oracle exercises. Zero-value (or nil) selects the engine defaults (length 0, no data, no signature, kAllow).

type FunctionScriptOrigin

type FunctionScriptOrigin struct {
	ScriptID        int32
	ResourceName    Value
	SourceMapURL    Value
	HasResourceName bool
	HasSourceMapURL bool
}

FunctionScriptOrigin is the scope-local portion of Function::GetScriptOrigin. The presence bits distinguish V8's empty Local values for native functions from ordinary JavaScript values.

type FunctionTemplate

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

FunctionTemplate is a scope-local template for creating JS functions (and, through new, constructor-backed objects).

func (*FunctionTemplate) Data

func (t *FunctionTemplate) Data() (Data, error)

Data returns t as its Data supertype without changing its local lifetime.

func (*FunctionTemplate) GetFunction

func (t *FunctionTemplate) GetFunction(s *Scope, c *Context) (*Function, error)

GetFunction instantiates the template's function object in the context (the unique function per context, exactly as in the oracle). The returned Function is bound to the given scope for its wire.

func (*FunctionTemplate) Inherit

func (t *FunctionTemplate) Inherit(parent *FunctionTemplate) error

Inherit makes t inherit from parent (v8 FunctionTemplate::Inherit): the derived template's prototype's [[Prototype]] becomes the parent's prototype, so `instanceof` works for both constructors and prototype properties chain. Template-level statics do NOT inherit.

func (*FunctionTemplate) InstanceTemplate

func (t *FunctionTemplate) InstanceTemplate() (*ObjectTemplate, error)

InstanceTemplate returns the object template used for instances created when the function is called as a constructor.

func (*FunctionTemplate) PrototypeTemplate

func (t *FunctionTemplate) PrototypeTemplate() (*ObjectTemplate, error)

PrototypeTemplate returns the object template used as the prototype of instances created by this template's constructor.

func (*FunctionTemplate) ReadOnlyPrototype

func (t *FunctionTemplate) ReadOnlyPrototype() error

ReadOnlyPrototype sets the ReadOnly attribute on the `prototype` property of functions created from this template: sloppy-mode assignment silently fails (v8 FunctionTemplate::ReadOnlyPrototype).

func (*FunctionTemplate) RemovePrototype

func (t *FunctionTemplate) RemovePrototype() error

RemovePrototype removes the `prototype` property from functions created from this template; `new` rejects with "not a constructor" (v8 FunctionTemplate::RemovePrototype).

func (*FunctionTemplate) Set

func (t *FunctionTemplate) Set(key string, value Value) error

Set adds a property to the function itself (a template-level "static"): every function instantiated from this template in any context carries it (v8 Template::Set). Values must belong to the template's isolate.

func (*FunctionTemplate) SetAccessorProperty

func (t *FunctionTemplate) SetAccessorProperty(key string, getter, setter *FunctionTemplate, attr PropertyAttribute) error

SetAccessorProperty installs getter (and optionally setter) function templates as an accessor property on the template itself — for a function template this is a *static* accessor on the constructor function (v8 FunctionTemplate::SetAccessorProperty). Exactly one of getter/setter must be non-nil.

func (*FunctionTemplate) SetAccessorPropertyName

func (t *FunctionTemplate) SetAccessorPropertyName(key Value, getter, setter *FunctionTemplate, attr PropertyAttribute) error

SetAccessorPropertyName installs a static function-template accessor under a String or Symbol key on the constructor function produced by t.

func (*FunctionTemplate) SetClassName

func (t *FunctionTemplate) SetClassName(name string) error

SetClassName sets the constructor function's `name` (v8 FunctionTemplate::SetClassName).

func (*FunctionTemplate) SetDataNameWithAttr

func (t *FunctionTemplate) SetDataNameWithAttr(key Value, data Data, attr PropertyAttribute) error

SetDataNameWithAttr installs supported V8 Data on the function object under a String or Symbol key.

func (*FunctionTemplate) SetDataWithAttr

func (t *FunctionTemplate) SetDataWithAttr(key string, data Data, attr PropertyAttribute) error

SetDataWithAttr adds supported V8 Data to the function object instantiated from this template. It has the same safety boundary as ObjectTemplate's method.

func (*FunctionTemplate) SetIntrinsicDataProperty

func (t *FunctionTemplate) SetIntrinsicDataProperty(key string, intrinsic Intrinsic, attr PropertyAttribute) error

SetIntrinsicDataProperty is the FunctionTemplate flavor of the Template base method: instances created from the template's constructor receive the property.

func (*FunctionTemplate) SetIntrinsicDataPropertyName

func (t *FunctionTemplate) SetIntrinsicDataPropertyName(key Value, intrinsic Intrinsic, attr PropertyAttribute) error

SetIntrinsicDataPropertyName is the FunctionTemplate flavor of the shared Template base operation.

func (*FunctionTemplate) SetName

func (t *FunctionTemplate) SetName(key Value, value Value) error

SetName is the Name-keyed counterpart of Set for properties installed on the function object produced by this template.

func (*FunctionTemplate) SetNameWithAttr

func (t *FunctionTemplate) SetNameWithAttr(key Value, value Value, attr PropertyAttribute) error

SetNameWithAttr is the FunctionTemplate flavor of Name-keyed Template::Set.

func (*FunctionTemplate) SetWithAttr

func (t *FunctionTemplate) SetWithAttr(key string, value Value, attr PropertyAttribute) error

SetWithAttr adds a primitive property with explicit attributes to the function object instantiated from this template. Use SetDataWithAttr for nested templates and other non-Value Data.

type GCCallback

type GCCallback func(gcType GCType, flags GCCallbackFlags)

GCCallback is the prologue/epilogue callback. It runs on the isolate's thread inside engine GC and must not re-enter the engine.

type GCCallbackFlags

type GCCallbackFlags uint32

GCCallbackFlags mirrors v8::GCCallbackFlags.

type GCCallbackToken

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

GCCallbackToken identifies a registered GC callback for removal.

type GCType

type GCType uint32

GCType mirrors v8::GCType.

const (
	GCTypeScavenge             GCType = 1 << 0
	GCTypeMinorMarkSweep       GCType = 1 << 1
	GCTypeMarkSweepCompact     GCType = 1 << 2
	GCTypeIncrementalMarking   GCType = 1 << 3
	GCTypeProcessWeakCallbacks GCType = 1 << 4
	GCTypeAll                  GCType = 0x1F
)

type GarbageCollectionType

type GarbageCollectionType uint32

GarbageCollectionType mirrors v8::Isolate::GarbageCollectionType.

const (
	// GcFull is a full garbage collection.
	GcFull GarbageCollectionType = 0
	// GcMinor is a minor (young-generation) collection.
	GcMinor GarbageCollectionType = 1
)

type GetSharedArrayBufferFromIDHook

type GetSharedArrayBufferFromIDHook interface {
	GetSharedArrayBufferFromID(id uint32) (*SharedArrayBuffer, bool)
}

GetSharedArrayBufferFromIDHook mirrors v8::ValueDeserializerImpl:: get_shared_array_buffer_from_id. found=false maps to None and the same engine error. Note the pinned semantics: transfer_shared_array_buffer registrations are NEVER consulted for the SAB tag — this hook is always the only source.

type GetSharedArrayBufferIDHook

type GetSharedArrayBufferIDHook interface {
	GetSharedArrayBufferID(sab *SharedArrayBuffer) (id uint32, answered bool)
}

GetSharedArrayBufferIDHook mirrors v8::ValueSerializerImpl:: get_shared_array_buffer_id. answered=false maps to None, which the pinned build rejects with V8's own data-clone error.

type GetWasmModuleFromIDHook

type GetWasmModuleFromIDHook interface {
	GetWasmModuleFromID(id uint32)
}

GetWasmModuleFromIDHook is the original observation-only shape for v8::ValueDeserializerImpl::get_wasm_module_from_id. Implementing it switches the read from the trait-default "not implemented" throw to the None-completion path. Use ResolveWasmModuleFromIDHook to return a module.

type GetWasmModuleTransferIDHook

type GetWasmModuleTransferIDHook interface {
	GetWasmModuleTransferID(module Value) (id uint32, answered bool)
}

GetWasmModuleTransferIDHook mirrors v8::ValueSerializerImpl:: get_wasm_module_transfer_id. module is the generic value view of the WasmModuleObject. answered=false maps to None: the module silently disappears from the wire and the enclosing write succeeds.

type Global

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

Global is a strong persistent handle to a JS value.

func GlobalFromRaw

func GlobalFromRaw(i *Isolate, raw uintptr) (*Global, error)

GlobalFromRaw adopts a raw cell produced by (*Global).IntoRaw. The raw pointer must originate from the same isolate and must not be adopted twice.

func NewGlobal

func NewGlobal(s *Scope, v Value) (*Global, error)

NewGlobal roots v in a new strong persistent cell. The value (and the scope it was created in) must belong to the same isolate as the scope.

func (*Global) Clone

func (g *Global) Clone() (*Global, error)

Clone creates a new strong cell holding the same object (Global::clone).

func (*Global) Close

func (g *Global) Close() error

Close releases the strong cell. After the host isolate was closed this is a silent no-op (the engine handles died with the isolate), matching the pinned Drop behavior for disposed isolates.

func (*Global) Equal

func (g *Global) Equal(other *Global) (bool, error)

Equal reports whether both globals hold the same object (object identity, not cell identity). Globals hosted by different live isolates compare unequal without touching either isolate, exactly like the pinned crate.

func (*Global) IntoRaw

func (g *Global) IntoRaw() (uintptr, error)

IntoRaw consumes the global and returns the raw cell pointer. The caller MUST eventually pass it to GlobalFromRaw (on the same isolate), otherwise the referenced object stays pinned until the isolate dies. The global wrapper is consumed and must not be used afterwards.

func (*Global) NewWeak

func (g *Global) NewWeak() (*Weak, error)

NewWeak creates a weak handle over the global's object without a finalizer (Weak::new).

func (*Global) NewWeakWithFinalizer

func (g *Global) NewWeakWithFinalizer(cb WeakFinalizer) (*Weak, error)

NewWeakWithFinalizer creates a weak handle that invokes cb after the object is collected. There is no guarantee the callback runs at all (GC-based finalization is best effort, matching the pinned crate); use NewWeakWithGuaranteedFinalizer for resource management.

func (*Global) NewWeakWithGuaranteedFinalizer

func (g *Global) NewWeakWithGuaranteedFinalizer(cb func()) (*Weak, error)

NewWeakWithGuaranteedFinalizer creates a weak handle whose callback is guaranteed to run before the isolate is disposed (it may run earlier, upon collection). The callback receives no isolate: it may run during isolate teardown.

func (*Global) ToLocal

func (g *Global) ToLocal(s *Scope) (Value, error)

ToLocal reopens the global as a scope-local value. The value is valid while the scope is open.

type HasCustomHostObjectHook

type HasCustomHostObjectHook interface {
	HasCustomHostObject() bool
}

HasCustomHostObjectHook mirrors v8::ValueSerializerImpl:: has_custom_host_object. Return true to have the engine consult IsHostObject for every new plain object; false keeps the embedder-field fallback (objects with internal fields are host objects). The engine consults it once per serializer, at construction.

type HeapCodeStatistics

type HeapCodeStatistics struct {
	CodeAndMetadataSize      uint64
	BytecodeAndMetadataSize  uint64
	ExternalScriptSourceSize uint64
	CPUProfilerMetadataSize  uint64
}

HeapCodeStatistics is V8's code/bytecode metadata snapshot.

type HeapSpaceStatistics

type HeapSpaceStatistics struct {
	Name          string
	Size          uint64
	UsedSize      uint64
	AvailableSize uint64
	PhysicalSize  uint64
}

HeapSpaceStatistics is one V8 heap-space snapshot.

type HeapStatistics

type HeapStatistics struct {
	TotalHeapSize            uint64
	TotalHeapSizeExecutable  uint64
	TotalPhysicalSize        uint64
	TotalAvailableSize       uint64
	UsedHeapSize             uint64
	HeapSizeLimit            uint64
	MallocedMemory           uint64
	ExternalMemory           uint64
	PeakMallocedMemory       uint64
	DoesZapGarbage           bool
	NumberOfNativeContexts   uint64
	NumberOfDetachedContexts uint64
	TotalGlobalHandlesSize   uint64
	UsedGlobalHandlesSize    uint64
	TotalAllocatedBytes      uint64
}

HeapStatistics is a snapshot of the isolate's heap counters. Sizes are machine-dependent; the deterministic invariants are the comparisons the oracle pins.

type ICUCommonDataError

type ICUCommonDataError struct {
	Code int32
}

ICUCommonDataError reports the UErrorCode returned by ICU while installing a common-data package. The numeric code intentionally matches rusty_v8's Result<(), i32> error value.

func (*ICUCommonDataError) Error

func (e *ICUCommonDataError) Error() string

type IdleTask

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

IdleTask is a transferred V8 idle task with the same one-shot ownership and affinity contract as Task.

func (*IdleTask) Close

func (task *IdleTask) Close() error

Close destroys an idle task without running it and may run on any thread.

func (*IdleTask) Run

func (task *IdleTask) Run(isolate *Isolate, deadlineInSeconds float64) error

Run executes the idle task with an absolute deadline and destroys it.

type ImportMetaCallback

type ImportMetaCallback func(scope *CallbackScope, module *Module, meta *Object) error

ImportMetaCallback initializes the stable import.meta object for a module.

type IndexFilter

type IndexFilter uint8

IndexFilter mirrors v8::IndexFilter.

const (
	IndexFilterIncludeIndices IndexFilter = 0
	IndexFilterSkipIndices    IndexFilter = 1
)

type IndexedPropertyDefinerCallback

type IndexedPropertyDefinerCallback func(cs *CallbackScope, index uint32, desc CallbackPropertyDescriptor, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertyDeleterCallback

type IndexedPropertyDeleterCallback func(cs *CallbackScope, index uint32, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertyDescriptorCallback

type IndexedPropertyDescriptorCallback func(cs *CallbackScope, index uint32, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertyEnumeratorCallback

type IndexedPropertyEnumeratorCallback func(cs *CallbackScope, args PropertyCallbackArguments, rv ReturnValue)

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertyGetterCallback

type IndexedPropertyGetterCallback func(cs *CallbackScope, index uint32, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertyHandlerConfig

IndexedPropertyHandlerConfig mirrors the crate's IndexedPropertyHandlerConfiguration builder.

type IndexedPropertyQueryCallback

type IndexedPropertyQueryCallback func(cs *CallbackScope, index uint32, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type IndexedPropertySetterCallback

type IndexedPropertySetterCallback func(cs *CallbackScope, index uint32, value Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type Inspector

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

func NewInspector

func NewInspector(i *Isolate) (*Inspector, error)

func NewInspectorWithClient

func NewInspectorWithClient(i *Isolate, client InspectorClient) (*Inspector, error)

NewInspectorWithClient creates an Inspector whose synchronous pause-loop callbacks are delivered to client. NewInspector continues to use V8's default no-op client behavior.

func (*Inspector) AllAsyncTasksCanceled

func (i *Inspector) AllAsyncTasksCanceled() error

func (*Inspector) AsyncTaskCanceled

func (i *Inspector) AsyncTaskCanceled(task InspectorAsyncTaskID) error

func (*Inspector) AsyncTaskFinished

func (i *Inspector) AsyncTaskFinished(task InspectorAsyncTaskID) error

func (*Inspector) AsyncTaskScheduled

func (i *Inspector) AsyncTaskScheduled(name InspectorStringView, task InspectorAsyncTaskID, recurring bool) error

AsyncTaskScheduled records the scheduling stack for task. A non-recurring task loses it after its first finish; a recurring task keeps it until cancel.

func (*Inspector) AsyncTaskStarted

func (i *Inspector) AsyncTaskStarted(task InspectorAsyncTaskID) error

func (*Inspector) Close

func (i *Inspector) Close() error

func (*Inspector) Connect

func (*Inspector) ContextCreated

func (i *Inspector) ContextCreated(c *Context, group int32, name, aux InspectorStringView) error

func (*Inspector) ContextDestroyed

func (i *Inspector) ContextDestroyed(c *Context) error

func (*Inspector) CreateInspectorStackTrace

func (i *Inspector) CreateInspectorStackTrace(trace *StackTrace) (*InspectorStackTrace, bool, error)

CreateInspectorStackTrace converts a scope-local V8 StackTrace to an owned Inspector snapshot. ok is false when trace is nil or Inspector produces no snapshot. The pinned build returns no snapshot for a nil input.

func (*Inspector) ExceptionThrown

func (i *Inspector) ExceptionThrown(scope *Scope, context *Context,
	message InspectorStringView, exception Value, detailedMessage, url InspectorStringView,
	lineNumber, columnNumber uint32, stackTrace *InspectorStackTrace, scriptID int32) (uint32, error)

ExceptionThrown reports an exception and returns its Inspector exception id. stackTrace may be nil and is consumed when non-nil, including when Inspector has no registered context and returns id zero. scope must be current, context must be the current entered context, and exception must be a live local from the same isolate.

func (*Inspector) IdleFinished

func (i *Inspector) IdleFinished() error

func (*Inspector) IdleStarted

func (i *Inspector) IdleStarted() error

type InspectorAsyncTaskID

type InspectorAsyncTaskID uintptr

InspectorAsyncTaskID is an opaque identity token used to correlate an embedder task's schedule, start, finish, and cancellation events. V8 only compares this token; it never dereferences it. Zero is a valid token.

type InspectorBorrowedStackTrace

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

InspectorBorrowedStackTrace is an opaque marker valid only during a console callback. The underlying trace remains owned by V8.

func (InspectorBorrowedStackTrace) Present

func (s InspectorBorrowedStackTrace) Present() bool

Present reports whether V8 supplied a borrowed stack trace marker.

type InspectorChannel

type InspectorChannel interface {
	SendResponse(callID int32, message *InspectorStringBuffer)
	SendNotification(message *InspectorStringBuffer)
	FlushProtocolNotifications()
}

InspectorChannel receives Chrome DevTools Protocol traffic synchronously.

type InspectorClient

type InspectorClient interface{}

InspectorClient is the optional-capability base for Inspector callbacks. Implement the focused capability interfaces for callbacks of interest. Callback methods must not panic; a panic terminates the process.

type InspectorClientTrustLevel

type InspectorClientTrustLevel int32
const (
	InspectorUntrusted InspectorClientTrustLevel = iota
	InspectorFullyTrusted
)

type InspectorConsoleMessageClient

type InspectorConsoleMessageClient interface {
	ConsoleAPIMessage(contextGroupID int32, level int32, message, url InspectorStringView,
		lineNumber, columnNumber uint32, stackTrace InspectorBorrowedStackTrace)
}

InspectorConsoleMessageClient receives console API messages synchronously.

type InspectorDefaultContextClient

type InspectorDefaultContextClient interface {
	EnsureDefaultContextInGroup(contextGroupID int32) *Context
}

InspectorDefaultContextClient supplies the default registered context for a context group. Nil means that no default context exists.

type InspectorInspectable

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

InspectorInspectable is an owned pending Inspector inspectable. Close drops an unadded value. AddInspectedObject transfers ownership to the session and consumes this wrapper; V8 then drops it on eviction or session destruction.

func (*InspectorInspectable) Close

func (i *InspectorInspectable) Close() error

Close releases an inspectable that has not been transferred to a session.

type InspectorInspectableGetter

type InspectorInspectableGetter func(callbackScope *CallbackScope, context *Context) (Value, error)

InspectorInspectableGetter is evaluated on every command-line API dereference of $0 through $4. The Context is the existing registered Go wrapper matching V8's callback context. The returned value must be created or reopened in callbackScope.Scope(); returning an error is unrecoverable at this native callback boundary and terminates the process.

type InspectorObjectIDError

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

InspectorObjectIDError owns the UTF-16 Inspector diagnostic associated with an invalid or released/missing remote object ID.

func (*InspectorObjectIDError) Error

func (e *InspectorObjectIDError) Error() string

func (*InspectorObjectIDError) Kind

Kind reports whether the ID was malformed or referred to an object that is no longer present. Unknown preserves future Inspector diagnostics safely.

func (*InspectorObjectIDError) Message

Message returns an owned copy of the Inspector diagnostic string.

type InspectorObjectIDErrorKind

type InspectorObjectIDErrorKind uint8

InspectorObjectIDErrorKind classifies failures returned by UnwrapObject.

const (
	InspectorObjectIDErrorUnknown InspectorObjectIDErrorKind = iota
	InspectorObjectIDInvalid
	InspectorObjectIDNotFound
)

type InspectorPauseLoopClient

InspectorPauseLoopClient is the convenience combination of both optional pause-loop capabilities.

type InspectorQuitMessageLoopOnPauseClient

type InspectorQuitMessageLoopOnPauseClient interface {
	QuitMessageLoopOnPause()
}

InspectorQuitMessageLoopOnPauseClient receives debugger pause-loop exit.

type InspectorRemoteObject

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

InspectorRemoteObject is an owned Inspector Runtime.RemoteObject. Its protocol representation is independent of the session, Inspector, context, and isolate that produced it. ToBytes and Close therefore remain usable after those resources have been closed and have no isolate-thread affinity.

func (*InspectorRemoteObject) Close

func (r *InspectorRemoteObject) Close() error

Close releases the owned protocol object. It is valid after isolate disposal and is synchronized with ToBytes.

func (*InspectorRemoteObject) ToBytes

func (r *InspectorRemoteObject) ToBytes() ([]byte, error)

ToBytes returns a fresh copy of the RemoteObject's CRDTP/CBOR encoding.

type InspectorResourceNameClient

type InspectorResourceNameClient interface {
	ResourceNameToURL(resourceName InspectorStringView) *InspectorStringBuffer
}

InspectorResourceNameClient optionally maps script resource names to URLs.

type InspectorRunMessageLoopOnPauseClient

type InspectorRunMessageLoopOnPauseClient interface {
	RunMessageLoopOnPause(contextGroupID int32)
}

InspectorRunMessageLoopOnPauseClient receives debugger pause-loop entry.

type InspectorSession

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

func (*InspectorSession) AddInspectedObject

func (s *InspectorSession) AddInspectedObject(inspectable *InspectorInspectable) error

AddInspectedObject transfers inspectable to the session. V8 retains only the five newest values and destroys evicted entries synchronously.

func (*InspectorSession) CancelPauseOnNextStatement

func (s *InspectorSession) CancelPauseOnNextStatement() error

CancelPauseOnNextStatement cancels a pending scheduled pause.

func (*InspectorSession) Close

func (s *InspectorSession) Close() error

func (*InspectorSession) DispatchProtocolMessage

func (s *InspectorSession) DispatchProtocolMessage(message InspectorStringView) error

func (*InspectorSession) ReleaseObjectGroup

func (s *InspectorSession) ReleaseObjectGroup(group InspectorStringView) error

ReleaseObjectGroup releases remote objects associated with group.

func (*InspectorSession) SchedulePauseOnNextStatement

func (s *InspectorSession) SchedulePauseOnNextStatement(reason, detail InspectorStringView) error

SchedulePauseOnNextStatement asks V8 to pause at the next statement.

func (*InspectorSession) UnwrapObject

func (s *InspectorSession) UnwrapObject(scope *Scope, objectID InspectorStringView) (
	Value, *Context, *InspectorStringBuffer, error)

UnwrapObject resolves an Inspector-generated ID. The returned Value is copied into scope immediately. Context is the already-registered Go Context whose persistent native context matches the Inspector result; this method never fabricates a second owning wrapper. ObjectGroup is always non-nil on success, including for Some("").

func (*InspectorSession) WrapObject

func (s *InspectorSession) WrapObject(scope *Scope, context *Context, value Value,
	objectGroup InspectorStringView, generatePreview bool) (*InspectorRemoteObject, bool, error)

WrapObject wraps value using the inspected context selected by context and this session's context group. present is false when no matching inspected context has been registered. The object group preserves 8-bit, UTF-16, and embedded-NUL input exactly at the native boundary.

type InspectorStackTrace

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

InspectorStackTrace owns a V8 Inspector stack-trace snapshot. Close releases an unconsumed snapshot. ExceptionThrown consumes it exactly once.

func (*InspectorStackTrace) Close

func (st *InspectorStackTrace) Close() error

Close releases an Inspector stack trace that has not been consumed. The pinned V8StackTraceImpl destructor is isolate-independent (it is defaulted and owns only copied frame/protocol state), so Close remains safe after the originating Inspector or isolate is closed and from another thread.

type InspectorStringBuffer

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

InspectorStringBuffer owns a copied inspector string.

func NewInspectorStringBuffer

func NewInspectorStringBuffer(source InspectorStringView) *InspectorStringBuffer

func (*InspectorStringBuffer) StringView

type InspectorStringView

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

InspectorStringView is an owned 8-bit or UTF-16 inspector string view. The prefix distinguishes it from this package's existing V8 StringView. Ownership is the Go safety difference from rusty_v8's borrowed view.

func EmptyInspectorStringView

func EmptyInspectorStringView() InspectorStringView

func NewInspectorStringView8

func NewInspectorStringView8(value []byte) InspectorStringView

func NewInspectorStringView16

func NewInspectorStringView16(value []uint16) InspectorStringView

func (InspectorStringView) Characters8

func (v InspectorStringView) Characters8() ([]byte, bool)

func (InspectorStringView) Characters16

func (v InspectorStringView) Characters16() ([]uint16, bool)

func (InspectorStringView) Is8Bit

func (v InspectorStringView) Is8Bit() bool

func (InspectorStringView) IsEmpty

func (v InspectorStringView) IsEmpty() bool

func (InspectorStringView) Len

func (v InspectorStringView) Len() int

func (InspectorStringView) String

func (v InspectorStringView) String() string

type InspectorUniqueIDClient

type InspectorUniqueIDClient interface{ GenerateUniqueID() int64 }

InspectorUniqueIDClient supplies Inspector-generated identifiers.

type InspectorValueDescriptionClient

type InspectorValueDescriptionClient interface {
	DescriptionForValueSubtype(scope *CallbackScope, value Value) *InspectorStringBuffer
}

InspectorValueDescriptionClient supplies an optional description after a non-nil subtype result. The CallbackScope and Value are borrowed.

type InspectorValueSubtypeClient

type InspectorValueSubtypeClient interface {
	ValueSubtype(scope *CallbackScope, value Value) *InspectorStringBuffer
}

InspectorValueSubtypeClient supplies an optional protocol subtype for an object. The CallbackScope and Value are borrowed for this callback only.

type InspectorWaitingForDebuggerClient

type InspectorWaitingForDebuggerClient interface{ RunIfWaitingForDebugger(contextGroupID int32) }

InspectorWaitingForDebuggerClient receives Runtime.runIfWaitingForDebugger.

type IntegrityLevel

type IntegrityLevel uint8

IntegrityLevel mirrors v8::IntegrityLevel (kFrozen = 0, kSealed = 1 in the engine's encoding).

const (
	IntegrityFrozen IntegrityLevel = 0
	IntegritySealed IntegrityLevel = 1
)

type Intercepted

type Intercepted uint32

Intercepted mirrors v8::Intercepted. The callback returns InterceptedYes when it handled the request (the engine stops the lookup) and InterceptedNo to fall through to normal property resolution. The numeric values are the engine's own (kYes = 0, kNo = 1).

const (
	InterceptedYes Intercepted = 0
	InterceptedNo  Intercepted = 1
)

type InterruptCallback

type InterruptCallback func(i *Isolate, data uintptr)

InterruptCallback is the callback for RequestInterrupt. It runs on the isolate's thread, inside engine execution, at the engine's next interrupt check. The data uintptr is passed through verbatim; like every value crossing the engine boundary it must not be a Go pointer.

type IntoSharedError

type IntoSharedError struct {
	Kind IntoSharedErrorKind
	// contains filtered or unexported fields
}

IntoSharedError reports why TryIntoShared refused an isolate. IntoIsolate hands the isolate back unchanged (the pinned IntoSharedError::into_isolate recovery): the conversion attempt had no engine-side effect.

func (*IntoSharedError) Error

func (e *IntoSharedError) Error() string

func (*IntoSharedError) IntoIsolate

func (e *IntoSharedError) IntoIsolate() *Isolate

IntoIsolate returns the rejected isolate back to the caller. It is still fully usable (entered mode, owning thread).

type IntoSharedErrorKind

type IntoSharedErrorKind string

IntoSharedErrorKind is the stable string form of the pinned IntoSharedErrorKind.

type Intrinsic

type Intrinsic uint8

Intrinsic mirrors v8::Intrinsic: context-owned intrinsic objects that can be bound as data properties at template instantiation. Values match the pinned header's enum order.

const (
	IntrinsicArrayProtoEntries      Intrinsic = 0
	IntrinsicArrayProtoForEach      Intrinsic = 1
	IntrinsicArrayProtoKeys         Intrinsic = 2
	IntrinsicArrayProtoValues       Intrinsic = 3
	IntrinsicArrayPrototype         Intrinsic = 4
	IntrinsicAsyncIteratorPrototype Intrinsic = 5
	IntrinsicErrorPrototype         Intrinsic = 6
	IntrinsicIteratorPrototype      Intrinsic = 7
	IntrinsicMapIteratorPrototype   Intrinsic = 8
	IntrinsicObjProtoValueOf        Intrinsic = 9
	IntrinsicSetIteratorPrototype   Intrinsic = 10
)

type IsHostObjectHook

type IsHostObjectHook interface {
	IsHostObject(obj *Object) (isHost, answered bool)
}

IsHostObjectHook mirrors v8::ValueSerializerImpl::is_host_object. It fires for each new plain object when HasCustomHostObject returned true. answered=false maps to None: the write fails without an exception.

type Isolate

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

Isolate is a V8 isolate. V8 isolates are strictly thread-affine: creating an Isolate locks the calling goroutine to its OS thread (runtime. LockOSThread) for the lifetime of the isolate, and every operation validates that it runs on that thread. This surfaces the engine's real threading contract instead of hiding it: to use several isolates concurrently, run each one's operations on its own goroutine (see the concurrency tests).

Resources derived from an isolate (scopes, contexts, values, scripts, try-catches, microtask queues) must normally be closed before Isolate.Close. Outstanding cppgc persistent handles are drained during native teardown and their later Close is a no-op. Isolate.Close must run on the owning thread.

func NewIsolate

func NewIsolate() (*Isolate, error)

NewIsolate creates a fresh isolate with a default ArrayBuffer allocator. Creation is serialized against Dispose/DisposePlatform: the engine allocation happens while the process teardown lock is held and the new isolate is registered as live before the lock is released, so an isolate can never come into existence across (or after) process teardown.

func NewIsolateFromSnapshot

func NewIsolateFromSnapshot(blob *StartupData) (*Isolate, error)

NewIsolateFromSnapshot creates an isolate that instantiates its default context from the startup blob (CreateParams::snapshot_blob via Isolate::new). The blob is guarded before any engine call: empty blobs and blobs shorter than the snapshot version header would trip fatal V8 CHECKs in the pinned engine, so they are rejected as errors here. The engine keeps reading the blob bytes for context creation until the isolate is closed; the wrapper tracks this and StartupData.Release frees the engine copy once every isolate created from the blob is closed.

func NewIsolateFromSnapshotWithParams

func NewIsolateFromSnapshotWithParams(blob *StartupData, params *CreateParams) (*Isolate, error)

NewIsolateFromSnapshotWithParams consumes a snapshot with the external references configured in params. Other non-default CreateParams options are rejected explicitly by this additive constructor rather than ignored.

A blob produced with a non-empty reference table is rejected before V8 when params has no table; rusty_v8 reaches a fatal "No external references" boundary in that case.

func NewIsolateWithLimits

func NewIsolateWithLimits(initialHeapBytes, maxHeapBytes uint64) (*Isolate, error)

NewIsolateWithLimits creates a fresh isolate with explicit heap limits (CreateParams::heap_limits): ConfigureDefaultsFromHeapSize(initial, max). The ceiling makes heap-pressure workloads end in the intended, bounded fatal OOM instead of uncontrolled process growth. Creation follows the same lifecycle rules as NewIsolate (serialized against Dispose, OS-thread pinned, registered as live).

func NewIsolateWithParams

func NewIsolateWithParams(params *CreateParams) (*Isolate, error)

NewIsolateWithParams creates an entered, thread-affine isolate with the selected safe CreateParams surface.

func NewIsolateWithSnapshotParams

func NewIsolateWithSnapshotParams(params *SnapshotCreateParams) (*Isolate, error)

NewIsolateWithSnapshotParams creates an entered, thread-affine isolate from the snapshot while applying every safe CreateParams field supported by NewIsolateWithParams: resource constraints, Atomics.wait, shared ArrayBuffer allocators, custom cppgc heaps, external references, and counter lookup.

func (*Isolate) AddGCEpilogueCallback

func (i *Isolate) AddGCEpilogueCallback(cb GCCallback, filter GCType) (*GCCallbackToken, error)

AddGCEpilogueCallback registers cb to run after each GC matching filter.

func (*Isolate) AddGCPrologueCallback

func (i *Isolate) AddGCPrologueCallback(cb GCCallback, filter GCType) (*GCCallbackToken, error)

AddGCPrologueCallback registers cb to run before each GC matching filter.

func (*Isolate) AddMessageListener

func (i *Isolate) AddMessageListener(cb MessageListenerCallback) (bool, error)

AddMessageListener registers cb for ERROR-level messages. Listeners are append-only (no removal API in the pinned surface); the same listener registered twice is delivered twice.

func (*Isolate) AddMessageListenerWithErrorLevel

func (i *Isolate) AddMessageListenerWithErrorLevel(cb MessageListenerCallback, errorLevel uint32) (bool, error)

AddMessageListenerWithErrorLevel registers cb filtered to the given MessageErrorLevel bits; it only observes messages whose level matches (e.g. a WARNING-filtered listener never sees ERROR-level throws).

func (*Isolate) AddNearHeapLimitCallback

func (i *Isolate) AddNearHeapLimitCallback(cb NearHeapLimitCallback) error

AddNearHeapLimitCallback installs cb (replacing any previous callback — the engine invokes only the most recently added callback; the replaced registration never fires again).

func (*Isolate) AdjustAmountOfExternalAllocatedMemory

func (i *Isolate) AdjustAmountOfExternalAllocatedMemory(delta int64) (int64, error)

AdjustAmountOfExternalAllocatedMemory changes the external-memory accounting by delta and returns the new total (the engine's return, not the previous total).

func (*Isolate) CancelTerminateExecution

func (i *Isolate) CancelTerminateExecution() error

CancelTerminateExecution clears the termination state and restores the isolate to a fully usable state.

func (*Isolate) CheckCodeCache

func (i *Isolate) CheckCodeCache(cache []byte) (int, error)

CheckCodeCache prevalidates consumer cache bytes with the engine's graceful header sanity check (CachedData::CompatibilityCheck) WITHOUT entering the code-cache deserializer. It returns the raw sanity-check result (0 = compatible) so callers can distinguish rejection reasons, and an error for wrapper-level misuse. Bytes below the minimum serialized-code header size are rejected without touching the engine. This prevents the upstream deserializer fatal for header-level corruption; mid-payload corruption that passes the header checks is not detectable without running the (fatal-prone) deserializer in this build and is characterized in the subprocess tests instead.

func (*Isolate) ClearKeptObjects

func (i *Isolate) ClearKeptObjects() error

ClearKeptObjects drops the engine's kept-object set: WeakRef targets kept alive only by that set become collectible at the next full collection.

func (*Isolate) ClearPromiseRejectCallback

func (i *Isolate) ClearPromiseRejectCallback() error

ClearPromiseRejectCallback removes the isolate's promise-reject callback and its Go registration. Clearing without a prior registration is a no-op on the engine side and returns nil.

func (*Isolate) ClearWasmStreamingCallback

func (i *Isolate) ClearWasmStreamingCallback() error

ClearWasmStreamingCallback removes the installed streaming callback. It is safe when no callback is installed.

func (*Isolate) Close

func (i *Isolate) Close() error

Close disposes the isolate and releases the owning goroutine's OS-thread lock. It must be called from the goroutine that created the isolate.

func (*Isolate) CollectCPUProfilerSample

func (i *Isolate) CollectCPUProfilerSample(traceID *uint64) error

CollectCPUProfilerSample collects a sample; nil omits the trace identifier.

func (*Isolate) CollectCppGCGarbageForTesting

func (i *Isolate) CollectCppGCGarbageForTesting(state CppGCEmbedderStackState) error

CollectCppGCGarbageForTesting synchronously collects the isolate's default cppgc heap with the explicit embedder-stack state. It is the checked Go form of PinScope::get_cpp_heap followed by Heap::collect_garbage_for_testing.

func (*Isolate) CounterValue

func (i *Isolate) CounterValue(name string) (value int32, found bool, err error)

CounterValue returns the current engine-owned value for a named counter.

func (*Isolate) CurrentContext

func (i *Isolate) CurrentContext(s *Scope) (*ContextRef, error)

CurrentContext observes the isolate's current context (the innermost entered one) as a scope-local reference.

func (*Isolate) CurrentHostDefinedOptions

func (i *Isolate) CurrentHostDefinedOptions(scope *Scope) (*PrimitiveArray, bool, error)

CurrentHostDefinedOptions returns the PrimitiveArray attached to the currently executing script origin. Outside script execution it reports present=false.

func (*Isolate) DataSlotCount

func (i *Isolate) DataSlotCount() (int, error)

DataSlotCount reports the isolate's raw data-slot count (3 for a plain isolate in this build — the pinned oracle's value).

func (*Isolate) DateTimeConfigurationChangeNotification

func (i *Isolate) DateTimeConfigurationChangeNotification(d TimeZoneDetection) error

DateTimeConfigurationChangeNotification tells the engine that date/time configuration changed, resetting cached values. Neither mode changes UTC date math.

func (*Isolate) EmptyWeak

func (i *Isolate) EmptyWeak() (*Weak, error)

EmptyWeak creates a new empty weak handle, identical to one whose object was already collected (Weak::empty).

func (*Isolate) EnteredOrMicrotaskContext

func (i *Isolate) EnteredOrMicrotaskContext(s *Scope) (*ContextRef, error)

EnteredOrMicrotaskContext observes the entered or microtask context.

func (*Isolate) FunctionBuilder

func (i *Isolate) FunctionBuilder(callback FunctionCallback) *FunctionBuilder

FunctionBuilder starts a direct native Function builder.

func (*Isolate) GetData

func (i *Isolate) GetData(slot int) (uintptr, error)

GetData reads the raw pointer stored in slot. Indices are validated against the slot count: the upstream GetData performs no bounds check in release builds.

func (*Isolate) GetHeapCodeAndMetadataStatistics

func (i *Isolate) GetHeapCodeAndMetadataStatistics() (*HeapCodeStatistics, bool, error)

func (*Isolate) GetHeapSpaceStatistics

func (i *Isolate) GetHeapSpaceStatistics(index uint64) (*HeapSpaceStatistics, bool, error)

GetHeapSpaceStatistics returns ok=false for every out-of-range index without forwarding it to V8's size_t API.

func (*Isolate) GetHeapStatistics

func (i *Isolate) GetHeapStatistics() (*HeapStatistics, error)

GetHeapStatistics snapshots the isolate's heap statistics.

func (*Isolate) GetMicrotasksPolicy

func (i *Isolate) GetMicrotasksPolicy() (MicrotasksPolicy, error)

GetMicrotasksPolicy reports the isolate-level microtasks policy.

func (*Isolate) GetSlot

func (i *Isolate) GetSlot(key any) (any, bool)

GetSlot returns the value stored under key.

func (*Isolate) HasCppHeap

func (i *Isolate) HasCppHeap() (bool, error)

HasCppHeap reports whether V8 attached its default cppgc heap.

func (*Isolate) HasPendingBackgroundTasks

func (i *Isolate) HasPendingBackgroundTasks() (bool, error)

HasPendingBackgroundTasks reports whether the isolate still has background work (in this build true is reachable only via background Wasm compilation, which is out of scope).

func (*Isolate) HostRefAdd

func (i *Isolate) HostRefAdd(v any) (uintptr, error)

HostRefAdd stores v on the isolate and returns an 8-aligned integer token suitable as an External payload or aligned internal-field pointer. The token stays valid until HostRefRemove.

func (*Isolate) HostRefGet

func (i *Isolate) HostRefGet(token uintptr) (any, bool)

HostRefGet resolves a token previously returned by HostRefAdd.

func (*Isolate) HostRefRemove

func (i *Isolate) HostRefRemove(token uintptr) (any, bool)

HostRefRemove resolves a token and hands ownership back to the caller: the token stops resolving and the Go value becomes the caller's again.

func (*Isolate) IsExecutionTerminating

func (i *Isolate) IsExecutionTerminating() (bool, error)

IsExecutionTerminating reports whether execution is currently terminating because of a TerminateExecution request.

func (*Isolate) LowMemoryNotification

func (i *Isolate) LowMemoryNotification() error

Isolate.LowMemoryNotification requests a full garbage collection (the crate's isolate.low_memory_notification). Used to make engine-side drops of ArrayBuffer/backing-store references observable deterministically.

func (*Isolate) MemoryPressureNotification

func (i *Isolate) MemoryPressureNotification(l MemoryPressureLevel) error

MemoryPressureNotification signals the given pressure level to the isolate. All three levels are accepted back-to-back; the isolate stays fully usable.

func (*Isolate) NewBackingStore

func (i *Isolate) NewBackingStore(byteLength int) (*BackingStore, error)

NewBackingStore allocates a zero-initialized, isolate-owned backing store (the crate's ArrayBuffer::new_backing_store).

func (*Isolate) NewBackingStoreFromPtr

func (i *Isolate) NewBackingStoreFromPtr(data unsafe.Pointer, byteLength int, fn BackingStoreDeleter, deleterData uintptr) (*BackingStore, error)

NewBackingStoreFromPtr creates a backing store over CALLER-owned memory (the crate's new_backing_store_from_ptr). The engine reads through data until the deleter runs; the caller must keep the memory valid until then and must not free it beforehand. The deleter fires exactly once, after the last reference dies, with the registered triple.

func (*Isolate) NewBackingStoreFromSlice

func (i *Isolate) NewBackingStoreFromSlice(data []byte) (*BackingStore, error)

NewBackingStoreFromSlice creates a backing store that owns a copy of data (the crate's new_backing_store_from_vec / from_boxed_slice). The Go slice is copied at construction and never retained; the copy is freed by the store's deleter when the last reference dies.

func (*Isolate) NewContext

func (i *Isolate) NewContext() (*Context, error)

NewContext creates a default context on the isolate. A context is engine-persistent; it does not require a Scope to create or keep alive.

func (*Isolate) NewContextWithOptions

func (i *Isolate) NewContextWithOptions(s *Scope, options *ContextOptions) (*Context, error)

NewContextWithOptions constructs a persistent context from scope-local options. Unlike NewContext, it needs an explicit Scope because V8 consumes Local<ObjectTemplate> and Local<Value> arguments during construction.

func (*Isolate) NewCppGCGenericObject

func (i *Isolate) NewCppGCGenericObject(options CppGCGenericOptions) (*CppGCGenericObject, error)

NewCppGCGenericObject performs allocation, copied-state construction, and strong rooting in one native call on the isolate's default cppgc heap.

func (*Isolate) NewFastFunctionTemplate

func (i *Isolate) NewFastFunctionTemplate(s *Scope, callback FunctionCallback, opts *FunctionOptions, overloads []CFunction) (*FunctionTemplate, error)

NewFastFunctionTemplate is FunctionBuilder::build_fast for Go. V8 retains the CFunction array and all nested type metadata until isolate disposal, so the shim copies every descriptor into native-owned per-isolate storage. overloads may be reused or mutated by the caller after this method returns.

The ordinary Go callback is the slow path used whenever V8 cannot take a fast overload. As in pinned rusty_v8, fast templates always use ConstructorBehavior::Throw; opts.ConstructorBehavior is validated but does not alter that build_fast rule.

func (*Isolate) NewFunction

func (i *Isolate) NewFunction(s *Scope, c *Context, cb FunctionCallback, opts *FunctionOptions) (*Function, error)

NewFunction creates a native function object directly in the context (v8 Function::builder(cb)[.length(n)][.data(v)].build / Function::new). opts may be nil.

func (*Isolate) NewFunctionTemplate

func (i *Isolate) NewFunctionTemplate(s *Scope, cb FunctionCallback, opts *FunctionOptions) (*FunctionTemplate, error)

NewFunctionTemplate creates a function template whose native callback is cb. opts may be nil. The template lives in the given scope.

func (*Isolate) NewFunctionTemplateFromExternalReference

func (i *Isolate) NewFunctionTemplateFromExternalReference(scope *Scope, callback ExternalReference, data Value) (*FunctionTemplate, error)

NewFunctionTemplateFromExternalReference creates the snapshot-portable stateless function represented by ExternalReferenceFunction. data must be a V8 External; when invoked, the function returns that external pointer as a BigInt. V8 remaps both the callback and pointer through the table when the function is serialized and loaded in another isolate.

Arbitrary Go FunctionCallback closures are intentionally excluded: their Go registry state cannot be serialized into a V8 snapshot.

func (*Isolate) NewInspectorInspectable

func (i *Isolate) NewInspectorInspectable(getter InspectorInspectableGetter,
	onDrop func()) (*InspectorInspectable, error)

NewInspectorInspectable creates an inspectable callback owned by isolate. onDrop, when non-nil, is called exactly once when an unadded inspectable is closed, V8 evicts a transferred inspectable, or its session is destroyed. onDrop must be pure Go and must not panic or re-enter V8.

func (*Isolate) NewMicrotaskQueue

func (i *Isolate) NewMicrotaskQueue(policy MicrotasksPolicy) (*MicrotaskQueue, error)

NewMicrotaskQueue creates a native queue with the given policy.

func (*Isolate) NewObjectTemplate

func (i *Isolate) NewObjectTemplate(s *Scope) (*ObjectTemplate, error)

NewObjectTemplate creates an empty object template.

func (*Isolate) NewObjectTemplateFromFunction

func (i *Isolate) NewObjectTemplateFromFunction(s *Scope, ft *FunctionTemplate) (*ObjectTemplate, error)

NewObjectTemplateFromFunction creates an object template derived from a function template (v8 ObjectTemplate::new_from_template): instances inherit the function template's prototype object.

func (*Isolate) NewScope

func (i *Isolate) NewScope() (*Scope, error)

NewScope opens a new HandleScope on the isolate.

func (*Isolate) NewSharedArrayBufferBackingStore

func (i *Isolate) NewSharedArrayBufferBackingStore(byteLength int) (*BackingStore, error)

NewSharedArrayBufferBackingStore allocates a standalone shared backing store (the crate's SharedArrayBuffer::new_backing_store); IsShared reports true for it and it can back SharedArrayBuffers.

func (*Isolate) NewSharedArrayBufferBackingStoreFromPtr

func (i *Isolate) NewSharedArrayBufferBackingStoreFromPtr(data unsafe.Pointer, byteLength int, fn BackingStoreDeleter, deleterData uintptr) (*BackingStore, error)

NewSharedArrayBufferBackingStoreFromPtr creates a shared backing store over caller-owned memory. The memory and deleter have the same lifetime contract as NewBackingStoreFromPtr.

func (*Isolate) NewSharedArrayBufferBackingStoreFromSlice

func (i *Isolate) NewSharedArrayBufferBackingStoreFromSlice(data []byte) (*BackingStore, error)

NewSharedArrayBufferBackingStoreFromSlice creates a shared backing store that owns a copy of data (the crate's new_backing_store_from_vec / new_backing_store_from_boxed_slice). The Go slice is never retained.

func (*Isolate) NewSignature

func (i *Isolate) NewSignature(s *Scope, ft *FunctionTemplate) (*Signature, error)

NewSignature builds a Signature over ft (v8::Signature::New): receivers created from ft — or from templates inheriting from it — pass the check.

func (*Isolate) NewTryCatch

func (i *Isolate) NewTryCatch() (*TryCatch, error)

NewTryCatch creates and registers a TryCatch on the isolate.

func (*Isolate) NumberOfHeapSpaces

func (i *Isolate) NumberOfHeapSpaces() (int64, error)

NumberOfHeapSpaces reports the isolate's heap space count (13 in this build — the pinned oracle's value).

func (*Isolate) PerformMicrotaskCheckpoint

func (i *Isolate) PerformMicrotaskCheckpoint() error

PerformMicrotaskCheckpoint drains the isolate's default microtask queue.

func (*Isolate) PumpMessageLoop

func (i *Isolate) PumpMessageLoop(waitForWork bool) (bool, error)

PumpMessageLoop executes at most one platform task for the isolate. It is required to deliver asynchronous WasmModuleCompilation resolutions.

func (*Isolate) RemoveGCEpilogueCallback

func (i *Isolate) RemoveGCEpilogueCallback(t *GCCallbackToken) error

RemoveGCEpilogueCallback removes an epilogue registration.

func (*Isolate) RemoveGCPrologueCallback

func (i *Isolate) RemoveGCPrologueCallback(t *GCCallbackToken) error

RemoveGCPrologueCallback removes a prologue registration.

func (*Isolate) RemoveNearHeapLimitCallback

func (i *Isolate) RemoveNearHeapLimitCallback(heapLimit uint64) error

RemoveNearHeapLimitCallback removes the active callback and restores the given heap limit (RemoveNearHeapLimitCallback's heap_limit). A stale registration left over from a closed isolate at the same engine address is treated as absent (calling the engine's remove in that case would hit its UNREACHABLE guard).

func (*Isolate) RemoveSlot

func (i *Isolate) RemoveSlot(key any) (any, bool)

RemoveSlot removes and returns the value stored under key, handing ownership back to the caller (no release hook runs).

func (*Isolate) RequestGarbageCollectionForTesting

func (i *Isolate) RequestGarbageCollectionForTesting(t GarbageCollectionType) error

RequestGarbageCollectionForTesting requests a collection of the given type. Requires --expose-gc set before Initialize: without it the engine fails a fatal CHECK and aborts the process (pinned, engine-fatal; not guarded away).

func (*Isolate) RunIdleTasks

func (i *Isolate) RunIdleTasks(idleTimeInSeconds float64) error

RunIdleTasks runs pending idle tasks for at most idleTimeInSeconds. As in rusty_v8, all finite and non-finite float64 values are forwarded unchanged; the default platform treats negative/NaN/infinite boundaries safely.

func (*Isolate) SetAllowAtomicsWait

func (i *Isolate) SetAllowAtomicsWait(allow bool) error

SetAllowAtomicsWait toggles whether Atomics.wait may block on this isolate. When disallowed, Atomics.wait throws a TypeError before any blocking. The toggle can be flipped repeatedly on a live isolate.

func (*Isolate) SetAllowWasmCodeGenerationCallback

func (i *Isolate) SetAllowWasmCodeGenerationCallback(callback AllowWasmCodeGenerationCallback) error

SetAllowWasmCodeGenerationCallback replaces the isolate's policy callback. The pinned API has no clear operation; install another callback to replace it. ReleaseIsolateHostState drains the Go registration before isolate close.

func (*Isolate) SetCaptureStackTraceForUncaughtExceptions

func (i *Isolate) SetCaptureStackTraceForUncaughtExceptions(enable bool, frameLimit int) error

SetCaptureStackTraceForUncaughtExceptions toggles the isolate-wide capture of stack traces for uncaught exceptions with the given frame limit (Isolate::SetCaptureStackTraceForUncaughtExceptions).

func (*Isolate) SetData

func (i *Isolate) SetData(slot int, data uintptr) error

SetData stores a raw pointer in slot (data is passed through verbatim; it must not be a Go pointer). Indices are validated against the slot count: the upstream SetData performs no bounds check in release builds and an out-of-range slot is an unchecked OOB write.

func (*Isolate) SetHostCreateShadowRealmContextCallback

func (i *Isolate) SetHostCreateShadowRealmContextCallback(cb ShadowRealmContextCallback) error

SetHostCreateShadowRealmContextCallback replaces or clears the isolate's ShadowRealm context factory.

func (*Isolate) SetHostImportModuleDynamicallyCallback

func (i *Isolate) SetHostImportModuleDynamicallyCallback(cb DynamicImportCallback) error

SetHostImportModuleDynamicallyCallback replaces or clears the legacy evaluation-phase dynamic import callback.

func (*Isolate) SetHostImportModuleWithPhaseDynamicallyCallback

func (i *Isolate) SetHostImportModuleWithPhaseDynamicallyCallback(cb DynamicImportCallback) error

SetHostImportModuleWithPhaseDynamicallyCallback replaces or clears the experimental phase-aware dynamic import callback.

func (*Isolate) SetHostInitializeImportMetaObjectCallback

func (i *Isolate) SetHostInitializeImportMetaObjectCallback(cb ImportMetaCallback) error

SetHostInitializeImportMetaObjectCallback replaces or clears the isolate's import-meta initializer. A nil callback clears the Go registration.

func (*Isolate) SetIdle

func (i *Isolate) SetIdle(idle bool) error

SetIdle marks the isolate as idle (or not). It must be called on the isolate's thread while no JS is executing; the flag has no synchronous observable effect.

func (*Isolate) SetMicrotasksPolicy

func (i *Isolate) SetMicrotasksPolicy(p MicrotasksPolicy) error

SetMicrotasksPolicy sets the isolate-level microtasks policy.

func (*Isolate) SetModifyCodeGenerationFromStringsCallback

func (i *Isolate) SetModifyCodeGenerationFromStringsCallback(cb ModifyCodeGenerationFromStringsCallback) error

SetModifyCodeGenerationFromStringsCallback installs cb on the isolate (one slot). The engine consults it ONLY when the context disallows code generation from strings or the eval source is not a string; plain evals in an allowed context skip it entirely.

func (*Isolate) SetOOMErrorHandler

func (i *Isolate) SetOOMErrorHandler(cb OOMErrorCallback) error

SetOOMErrorHandler installs cb on the isolate (one slot). Pair it with a heap-limited isolate (NewIsolateWithLimits) so OOM paths stay bounded.

func (*Isolate) SetPrepareStackTraceCallback

func (i *Isolate) SetPrepareStackTraceCallback(cb PrepareStackTraceCallback) error

SetPrepareStackTraceCallback installs cb on the isolate (one slot).

func (*Isolate) SetPromiseHook

func (i *Isolate) SetPromiseHook(h PromiseHook) error

SetPromiseHook installs h on the isolate (replacing any previous hook — the engine keeps one slot). A nil hook is rejected; there is no unset in the pinned surface.

func (*Isolate) SetPromiseRejectCallback

func (i *Isolate) SetPromiseRejectCallback(s *Scope, cb PromiseRejectCallback) error

SetPromiseRejectCallback installs cb as the isolate's promise-reject callback. Installing again replaces the previous callback (V8 keeps one per isolate); the superseded Go registration is dropped.

The scope anchors the handles delivered to the callback: it must belong to the isolate and stay open while the callback is installed (any Go scope used to drive the engine during a rejection satisfies this in practice). This parameter is a Go-side safety binding with no Rust counterpart — the Rust API takes only the callback.

func (*Isolate) SetSlot

func (i *Isolate) SetSlot(key, value any) (wasEmpty bool)

SetSlot stores value under key. It reports whether the slot was previously empty; when it was not, the replaced value is released immediately if it implements slotReleaser (matching the oracle's replace-drops-old semantics) and otherwise simply becomes unreachable.

func (*Isolate) SetUseCounterCallback

func (i *Isolate) SetUseCounterCallback(cb UseCounterCallback) error

SetUseCounterCallback installs cb on the isolate (one slot).

func (*Isolate) SetWasmAsyncResolvePromiseCallback

func (i *Isolate) SetWasmAsyncResolvePromiseCallback(callback WasmAsyncResolvePromiseCallback) error

SetWasmAsyncResolvePromiseCallback replaces the callback V8 invokes for WebAssembly.compile/instantiate promise completion. There is no clear API.

func (*Isolate) SetWasmStreamingCallback

func (i *Isolate) SetWasmStreamingCallback(callback WasmStreamingCallback) error

SetWasmStreamingCallback installs the isolate's compileStreaming callback. Call ClearWasmStreamingCallback, or ReleaseIsolateHostState, before closing the isolate.

func (*Isolate) TakeHeapSnapshot

func (i *Isolate) TakeHeapSnapshot(callback func([]byte) bool) error

TakeHeapSnapshot serializes a V8 heap snapshot as JSON chunks. callback is called one or more times and receives a final empty chunk after successful serialization. Returning false aborts serialization without making the isolate unusable. Each chunk is copied into Go-owned memory and may be retained after callback returns.

Snapshotting is synchronous and thread-affine. Starting another snapshot or closing the isolate from callback is rejected. A callback panic is a fatal host error because it cannot unwind through V8.

func (*Isolate) TerminateExecution

func (i *Isolate) TerminateExecution() error

TerminateExecution requests termination from the isolate's own thread (the isolate-level form of the pinned Isolate::terminate_execution, which always accepts the request). The request is delivered at the next interrupt check, not synchronously.

func (*Isolate) ThreadSafeHandle

func (i *Isolate) ThreadSafeHandle() *ThreadSafeHandle

ThreadSafeHandle returns a handle that may terminate this isolate's execution from any goroutine.

func (*Isolate) TryIntoShared

func (i *Isolate) TryIntoShared() (*SharedIsolate, error)

TryIntoShared converts an owned isolate into a shared one. On rejection the returned error's IntoIsolate recovers the isolate unchanged; on success the isolate accepts engine work only under Lock (the thread-safe handle keeps working, exactly like the pinned IsolateHandle).

func (*Isolate) UseDetailedSourcePositionsForProfiling

func (i *Isolate) UseDetailedSourcePositionsForProfiling() error

type JavascriptExecutionFailure

type JavascriptExecutionFailure uint8

JavascriptExecutionFailure controls a DisallowJavascriptExecutionScope.

const (
	// CrashOnFailure terminates the process when JavaScript execution is
	// attempted. Exercise it only in a subprocess.
	CrashOnFailure JavascriptExecutionFailure = iota
	// ThrowOnFailure throws the string "illegal access" into the active V8
	// TryCatch when execution is attempted.
	ThrowOnFailure
	// DumpOnFailure permits execution (the pinned build emits no diagnostic).
	DumpOnFailure
)

type KeyCollectionMode

type KeyCollectionMode uint8

KeyCollectionMode mirrors v8::KeyCollectionMode.

const (
	KeyCollectionOwnOnly           KeyCollectionMode = 0
	KeyCollectionIncludePrototypes KeyCollectionMode = 1
)

type KeyConversionMode

type KeyConversionMode uint8

KeyConversionMode mirrors v8::KeyConversionMode.

const (
	KeyConversionConvertToString KeyConversionMode = 0
	KeyConversionKeepNumbers     KeyConversionMode = 1
	KeyConversionNoNumbers       KeyConversionMode = 2
)

type LazyDataPropertyConfiguration

type LazyDataPropertyConfiguration struct {
	Getter               AccessorGetterCallback
	Data                 Value
	Attribute            PropertyAttribute
	GetterSideEffectType SideEffectType
	SetterSideEffectType SideEffectType
}

LazyDataPropertyConfiguration controls Object::SetLazyDataProperty. The getter is called until it completes successfully, after which V8 replaces the lazy property with the returned value (undefined when the callback did not set ReturnValue). Data has the same isolate-owned retention semantics as AccessorConfiguration.Data.

type Locker

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

Locker holds the isolate locked and entered on the locking thread. Regular engine operations on the isolate (scopes, contexts, values, scripts, try-catches) run unchanged while a Locker is alive.

func (*Locker) Close

func (l *Locker) Close() error

Close releases the lock: the isolate is exited on this thread and the engine lock is released. It must be called from the locking thread and exactly once.

func (*Locker) Isolate

func (l *Locker) Isolate() *Isolate

Isolate returns the locked isolate.

func (*Locker) UnlockWindow

func (l *Locker) UnlockWindow(fn func() error) error

UnlockWindow releases the lock for the duration of fn so other threads can lock and use the isolate, then reacquires it before returning (Locker::unlock). The isolate must not be touched from fn's goroutine while suspended: the window clears the thread binding, so any accidental engine access from this goroutine fails the affinity check instead of racing the other thread.

Errors mirror the pinned guards: calling unlock while another isolate was entered on top ("entered on top of this one") and a closure that returned with an isolate still entered (the pinned crate asserts; this port refuses to touch the engine and leaves the window open, which keeps the isolate unusable but sound). When another thread still holds the lock at window end, the reacquisition blocks until it is released — the pinned RelockGuard behavior.

type Map

type Map struct{ Value }

Map is a JS Map object (engine SameValueZero keys: NaN keys work and +0/-0 are the same key).

func AsMap

func AsMap(v Value) (*Map, error)

AsMap casts a value to a Map after prevalidating the engine kind.

func (*Map) AsArray

func (m *Map) AsArray(s *Scope, c *Context) (*Array, error)

AsArray renders the map as [[k0, v0], [k1, v1], ...] in insertion order.

func (*Map) Clear

func (m *Map) Clear() error

Clear removes every entry.

func (*Map) Delete

func (m *Map) Delete(s *Scope, c *Context, key Value) (bool, error)

Delete removes key; ok reports whether it was present.

func (*Map) Get

func (m *Map) Get(s *Scope, c *Context, key Value) (Value, error)

Get returns the value stored for key (the undefined value when absent).

func (*Map) Has

func (m *Map) Has(s *Scope, c *Context, key Value) (bool, error)

Has reports key membership.

func (*Map) Set

func (m *Map) Set(s *Scope, c *Context, key, value Value) (*Map, error)

Set inserts or overwrites the mapping and returns the collection itself (a fresh wrapper over the engine-returned handle; compare with Same to observe identity, matching the pinned returned-handle check).

func (*Map) Size

func (m *Map) Size() (int64, error)

Size returns the number of entries.

type MemoryPressureLevel

type MemoryPressureLevel uint32

MemoryPressureLevel mirrors v8::MemoryPressureLevel.

const (
	MemoryPressureNone     MemoryPressureLevel = 0
	MemoryPressureModerate MemoryPressureLevel = 1
	MemoryPressureCritical MemoryPressureLevel = 2
)

type Message

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

Message is the engine's error message for a caught exception.

func (*Message) EndColumn

func (m *Message) EndColumn() (int64, error)

EndColumn returns the exclusive end column of the error region.

func (*Message) EndPosition

func (m *Message) EndPosition() (int64, error)

EndPosition returns the exclusive end offset of the error region.

func (*Message) ErrorLevel

func (m *Message) ErrorLevel() (int64, error)

ErrorLevel returns the MessageErrorLevel of the message.

func (*Message) IsOpaque

func (m *Message) IsOpaque() (bool, error)

IsOpaque reports the origin's is_opaque flag.

func (*Message) IsSharedCrossOrigin

func (m *Message) IsSharedCrossOrigin() (bool, error)

IsSharedCrossOrigin reports the origin's is_shared_cross_origin flag.

func (*Message) LineNumber

func (m *Message) LineNumber(c *Context) (line int32, ok bool, err error)

LineNumber returns the 1-based line of the error; ok=false when absent.

func (*Message) ResourceName

func (m *Message) ResourceName(c *Context) (string, error)

ResourceName returns the script resource name ("" when absent).

func (*Message) ResourceNameValue

func (m *Message) ResourceNameValue() (Value, bool, error)

ResourceNameValue returns the script resource name as V8's original scope-local Value. No string coercion is performed; ok=false represents an absent handle, while an explicit undefined resource returns ok=true.

func (*Message) SameIdentity

func (m *Message) SameIdentity(other *Message) (bool, error)

SameIdentity reports V8 Local<Message> identity, not merely equal text.

func (*Message) SourceLine

func (m *Message) SourceLine(c *Context) (string, bool, error)

SourceLine returns the source line the error points at; ok=false when absent.

func (*Message) SourceLineValue

func (m *Message) SourceLineValue(c *Context) (Value, bool, error)

SourceLineValue returns the source line as its scope-local JavaScript String. ok=false represents Option::None; an empty String returns ok=true.

func (*Message) StackTrace

func (m *Message) StackTrace() (*StackTrace, bool, error)

StackTrace returns the trace attached to the message; ok=false when the engine produced none (the default for uncaught exceptions unless SetCaptureStackTraceForUncaughtExceptions enabled capture).

func (*Message) StartColumn

func (m *Message) StartColumn() (int64, error)

StartColumn returns the 0-based column where the error region starts.

func (*Message) StartPosition

func (m *Message) StartPosition() (int64, error)

StartPosition returns the 0-based character offset where the error region starts.

func (*Message) Text

func (m *Message) Text(c *Context) (string, error)

Text returns Message::Get text (carries the "Uncaught " prefix for TryCatch-caught exceptions in this build).

func (*Message) TextValue

func (m *Message) TextValue() (Value, error)

TextValue returns Message::Get as its scope-local JavaScript String. Unlike Text it performs no UTF-8 conversion. The returned Value is local to the Message's Scope and remains usable after the originating TryCatch closes.

func (*Message) WasmFunctionIndex

func (m *Message) WasmFunctionIndex() (int64, error)

WasmFunctionIndex returns the Wasm function index for a Wasm-originated message, or -1 for a non-Wasm message.

type MessageListenerCallback

type MessageListenerCallback func(msg *CallbackMessage, exception Value)

MessageListenerCallback observes a message produced by an exception that escaped every TryCatch (uncaught only — TryCatch-caused exceptions are never reported). msg is valid only during the callback; exception is the thrown value (scope-local, same lifetime). The same listener registered twice is called twice per message.

type MicrotaskQueue

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

MicrotaskQueue is a native microtask queue (v8::MicrotaskQueue). The engine object is owned by the pinned artifact's MicrotaskQueueHandle binding; the Go wrapper holds the wrapper pointer and the raw queue pointer (used for identity comparisons after attaching to a context).

func (*MicrotaskQueue) Close

func (m *MicrotaskQueue) Close() error

Close releases the queue. A queue still attached to a context must be detached (or the context closed) first by the caller; V8 keeps the context's pointer valid until the context dies.

func (*MicrotaskQueue) Enqueue

func (m *MicrotaskQueue) Enqueue(c *Context, fn Value) error

Enqueue adds a JS function to the queue through the native API. The context may be supplied and is entered for the duration (mirroring the oracle); pass nil for none. The function value and the context must belong to the same isolate as the queue.

func (*MicrotaskQueue) GetMicrotasksScopeDepth

func (m *MicrotaskQueue) GetMicrotasksScopeDepth() (int32, error)

GetMicrotasksScopeDepth returns the number of nested run-microtasks scopes. A direct PerformCheckpoint has depth zero, including from inside a callback.

func (*MicrotaskQueue) IsRunningMicrotasks

func (m *MicrotaskQueue) IsRunningMicrotasks() (bool, error)

IsRunningMicrotasks reports whether this queue is currently draining.

func (*MicrotaskQueue) PerformCheckpoint

func (m *MicrotaskQueue) PerformCheckpoint(c *Context) error

PerformCheckpoint runs all queued microtasks (draining nested jobs). The context in which the checkpoint was logically taken may be supplied and is entered for the duration, mirroring the oracle's long-lived ContextScope around checkpoints; pass nil for none. The context must belong to the same isolate as the queue.

func (*MicrotaskQueue) Raw

func (m *MicrotaskQueue) Raw() (uintptr, error)

Raw returns the underlying v8::MicrotaskQueue pointer for identity comparison against Context.GetMicrotaskQueue.

type MicrotasksPolicy

type MicrotasksPolicy uint8

MicrotasksPolicy mirrors v8::MicrotasksPolicy. Auto drains microtasks when the engine considers the call stack empty; Explicit drains only on an explicit PerformMicrotaskCheckpoint.

const (
	PolicyAuto MicrotasksPolicy = iota
	PolicyExplicit
)

type ModifyCodeGenerationFromStringsCallback

type ModifyCodeGenerationFromStringsCallback func(source Value, isCodeLike bool) (allowed bool, modified *string)

ModifyCodeGenerationFromStringsCallback decides whether code generation from the given source value is allowed in a context that disallows it (or for a non-string eval source). Return allowed=false to block (the engine throws EvalError); allowed=true with modified=nil passes the source through unchanged; allowed=true with a non-nil rewritten source compiles the replacement string instead. The callback runs on the isolate's thread during eval/Function/new Function.

type Module

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

Module is a persistent source-text or synthetic module rooted in its isolate. It remains usable across handle scopes, but is bound to its creation context. Close must be called before closing that context or isolate.

func (*Module) Close

func (m *Module) Close() error

Close releases the persistent module handle.

func (*Module) Data

func (m *Module) Data(s *Scope) (Data, error)

Data materializes m as a Data local owned by s.

func (*Module) Evaluate

func (m *Module) Evaluate(s *Scope, tc *TryCatch) (Promise, error)

Evaluate evaluates a linked SourceTextModule graph and returns its promise. SyntheticModule has a general Value completion and uses EvaluateValue.

func (*Module) EvaluateForImportDefer

func (m *Module) EvaluateForImportDefer(s *Scope) (Value, bool, error)

EvaluateForImportDefer gathers asynchronous dependencies without evaluating the module itself. ok is false when V8 returned an empty MaybeLocal.

func (*Module) EvaluateValue

func (m *Module) EvaluateValue(s *Scope, tc *TryCatch) (Value, error)

EvaluateValue evaluates either module kind and returns V8's raw completion value. SourceTextModule callers normally use Evaluate. SyntheticModule callbacks may return any Value; after the first evaluation, repeated evaluation returns V8's fulfilled top-level Promise without invoking the callback again.

func (*Module) Exception

func (m *Module) Exception(s *Scope) (Value, error)

Exception returns the exception stored by an errored module.

func (*Module) GetUnboundModuleScript

func (m *Module) GetUnboundModuleScript() (*UnboundModuleScript, error)

GetUnboundModuleScript returns the persistent context-independent script underlying m. The returned wrapper has independent lifetime and must close.

func (*Module) HasTopLevelAwait

func (m *Module) HasTopLevelAwait() (bool, error)

HasTopLevelAwait reports whether this module itself contains top-level await.

func (*Module) IdentityHash

func (m *Module) IdentityHash() (int32, error)

IdentityHash returns V8's non-zero identity hash. It is stable but not guaranteed unique.

func (*Module) Instantiate

func (m *Module) Instantiate(s *Scope, resolver ModuleResolver, tc *TryCatch) (bool, error)

Instantiate links the module graph through resolver.

func (*Module) Instantiate2

func (m *Module) Instantiate2(s *Scope, resolver ModuleResolver, source ModuleSourceResolver, tc *TryCatch) (bool, error)

Instantiate2 links evaluation-phase and source-phase requests with separate resolvers.

func (*Module) IsGraphAsync

func (m *Module) IsGraphAsync() (bool, error)

IsGraphAsync reports whether the instantiated graph contains top-level await.

func (*Module) IsSourceTextModule

func (m *Module) IsSourceTextModule() (bool, error)

IsSourceTextModule reports whether this is a source-text module.

func (*Module) IsSyntheticModule

func (m *Module) IsSyntheticModule() (bool, error)

IsSyntheticModule reports whether this is a synthetic module.

func (*Module) ModuleRequests

func (m *Module) ModuleRequests(s *Scope) (*FixedArray, error)

ModuleRequests returns a module's direct requests as their native FixedArray metadata container. The returned local belongs to s.

func (*Module) Namespace

func (m *Module) Namespace(s *Scope) (Value, error)

Namespace returns the module namespace once the graph has been instantiated.

func (*Module) NamespaceWithPhase

func (m *Module) NamespaceWithPhase(s *Scope, phase ModuleImportPhase) (Value, error)

NamespaceWithPhase returns the namespace representation for phase.

func (*Module) Requests

func (m *Module) Requests() ([]ModuleRequest, error)

Requests returns all direct dependencies in source order, including import phase, source offsets, and import attributes.

func (*Module) ScriptID

func (m *Module) ScriptID() (int32, error)

ScriptID returns the underlying script id. It is unavailable after the module enters the errored state.

func (*Module) SetSyntheticModuleExport

func (m *Module) SetSyntheticModuleExport(s *Scope, name string, value Value,
	tc *TryCatch) (bool, error)

SetSyntheticModuleExport updates one declared export. An undeclared name throws ReferenceError and returns an exception error, recorded in tc when supplied.

func (*Module) SourceOffsetToLocation

func (m *Module) SourceOffsetToLocation(offset int32) (ModuleLocation, error)

SourceOffsetToLocation converts a module source offset to a zero-based line and column.

func (*Module) StalledTopLevelAwaitMessages

func (m *Module) StalledTopLevelAwaitMessages(s *Scope) ([]StalledTopLevelAwait, error)

StalledTopLevelAwaitMessages returns the pinned crate's diagnostic tuples. Like rusty_v8 152.2.0, the underlying query is capped at 16 entries.

func (*Module) Status

func (m *Module) Status() (ModuleStatus, error)

Status returns the current module state.

type ModuleCachingCallback

type ModuleCachingCallback func(*ModuleCachingInterface)

ModuleCachingCallback runs synchronously during Finish when cached compiled bytes were announced. The interface is valid only during the callback.

type ModuleCachingInterface

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

ModuleCachingInterface exposes the completed wire bytes and accepts a candidate serialized module during a caching callback. Go restricts the setter to one call because repeated-set behavior is not characterized by the pinned API.

func (*ModuleCachingInterface) SetCachedCompiledModule

func (m *ModuleCachingInterface) SetCachedCompiledModule(cache *SerializedWasmModuleCache) (bool, error)

SetCachedCompiledModule offers a provenance-checked serialized module to V8. A mismatched source is rejected before the native fatal boundary. Like the raw setter, this operation is one-shot once native consumption begins.

func (*ModuleCachingInterface) SetCachedCompiledModuleBytes

func (m *ModuleCachingInterface) SetCachedCompiledModuleBytes(bytes []byte) (bool, error)

SetCachedCompiledModuleBytes offers one raw serialized candidate to V8 and mirrors rusty_v8's byte-slice API. V8 152 CHECK-fails rather than returning false for mismatched wire bytes or a truncated cache; callers with cache provenance should use SetCachedCompiledModule, which validates those fatal preconditions in Go. Repeated calls are rejected safely before FFI.

func (*ModuleCachingInterface) WireBytes

func (m *ModuleCachingInterface) WireBytes() ([]byte, error)

WireBytes returns a copy of the complete wasm wire bytes. It is callback-only.

type ModuleCodeCache

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

ModuleCodeCache is an engine-produced SourceTextModule cache. Its bytes are intentionally opaque and unconstructible outside this package. A cache owns a Go copy, so it remains usable after its producer isolate closes.

func (*ModuleCodeCache) Equal

func (c *ModuleCodeCache) Equal(other *ModuleCodeCache) bool

Equal reports whether two opaque cache payloads are byte-identical without exposing either payload.

func (*ModuleCodeCache) Len

func (c *ModuleCodeCache) Len() int

Len returns the opaque cache payload size.

type ModuleCompileOptions

type ModuleCompileOptions struct {
	ResourceName string
	LineOffset   int32
	ColumnOffset int32
}

ModuleCompileOptions controls the ScriptOrigin attached to a module.

type ModuleImportAttribute

type ModuleImportAttribute struct {
	Key          string
	Value        string
	SourceOffset int32
}

ModuleImportAttribute is one import attribute. SourceOffset points to the attribute in the module source.

type ModuleImportPhase

type ModuleImportPhase int32

ModuleImportPhase mirrors v8::ModuleImportPhase.

const (
	ModuleImportSource ModuleImportPhase = iota
	ModuleImportDefer
	ModuleImportEvaluation
)

type ModuleLocation

type ModuleLocation struct {
	Line   int32
	Column int32
}

ModuleLocation is a zero-based source line and column.

type ModuleRequest

type ModuleRequest struct {
	Specifier    string
	Phase        ModuleImportPhase
	SourceOffset int32
	Attributes   []ModuleImportAttribute
}

ModuleRequest describes one direct module dependency.

type ModuleRequestData

type ModuleRequestData struct{ Data }

ModuleRequestData is a local module-request metadata handle.

func (*ModuleRequestData) ImportAttributes

func (r *ModuleRequestData) ImportAttributes(s *Scope) (*FixedArray, error)

ImportAttributes returns the raw [key, value, source-offset, ...] metadata array for the request. The returned local is owned by the supplied scope.

type ModuleResolveRequest

type ModuleResolveRequest struct {
	Specifier  string
	Referrer   *Module
	Attributes []ModuleImportAttribute
}

ModuleResolveRequest is delivered synchronously while Instantiate is linking. Its referrer and specifier are valid for the callback duration.

type ModuleResolver

type ModuleResolver func(ModuleResolveRequest) (*Module, error)

ModuleResolver resolves a direct import to a compiled module. Returning nil or an error fails linking. The returned module must share isolate and context.

type ModuleSourceResolveRequest

type ModuleSourceResolveRequest struct {
	Scope        *CallbackScope
	Specifier    string
	Referrer     *Module
	Phase        ModuleImportPhase
	SourceOffset int32
	Location     ModuleLocation
	Attributes   []ModuleImportAttribute
}

ModuleSourceResolveRequest is active only while Instantiate2 is linking. ReturnValue must be an Object in the callback scope's isolate.

type ModuleSourceResolver

type ModuleSourceResolver func(ModuleSourceResolveRequest) (ReturnValue Value, Err error)

ModuleSourceResolver resolves an import-source request to V8's source representation object. It runs synchronously during Instantiate2.

type ModuleStatus

type ModuleStatus int32

ModuleStatus is the ECMAScript module state, with evaluated failures split into ModuleErrored as in V8 and rusty_v8 152.2.0.

const (
	ModuleUninstantiated ModuleStatus = iota
	ModuleInstantiating
	ModuleInstantiated
	ModuleEvaluating
	ModuleEvaluated
	ModuleErrored
)

func (ModuleStatus) String

func (s ModuleStatus) String() string

type NamedPropertyDefinerCallback

type NamedPropertyDefinerCallback func(cs *CallbackScope, key Value, desc CallbackPropertyDescriptor, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertyDeleterCallback

type NamedPropertyDeleterCallback func(cs *CallbackScope, key Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertyDescriptorCallback

type NamedPropertyDescriptorCallback func(cs *CallbackScope, key Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertyEnumeratorCallback

type NamedPropertyEnumeratorCallback func(cs *CallbackScope, args PropertyCallbackArguments, rv ReturnValue)

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertyGetterCallback

type NamedPropertyGetterCallback func(cs *CallbackScope, key Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertyHandlerConfig

NamedPropertyHandlerConfig mirrors the crate's NamedPropertyHandlerConfiguration builder. Data is the handler's callback data observed via args.Data(); zero Value means none.

type NamedPropertyQueryCallback

type NamedPropertyQueryCallback func(cs *CallbackScope, key Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NamedPropertySetterCallback

type NamedPropertySetterCallback func(cs *CallbackScope, key, value Value, args PropertyCallbackArguments, rv ReturnValue) Intercepted

Named property handler callbacks. key is the property Name; args carries holder/this/data/should-throw; rv receives the handler's result where the engine expects one (getter value, query attributes, deleter/definer boolean, descriptor object).

type NativeFunction

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

NativeFunction is a scope-local JS function backed by a Go callback through the integer registry. The V8 function object lives (and dies) with the creating Scope; Close unregisters the Go side explicitly.

func (*NativeFunction) Close

func (f *NativeFunction) Close() error

Close unregisters the Go callback entry. It does not touch the engine: the function object is scope-owned. Close is safe from any thread.

func (*NativeFunction) Value

func (f *NativeFunction) Value() Value

Value returns the scope-local function value for use with promise APIs (and anything else that takes a function). It remains a valid V8 function until the creating scope closes, even after Close — but after Close its Go callback is unregistered and invoking it simply returns undefined.

type NativePromiseHandler

type NativePromiseHandler func(args []Value) (result Value, ok bool)

NativePromiseHandler is the Go implementation behind a native function used as a promise reaction handler (or any other caller of that function). It runs on the isolate's owning thread during engine execution: inside reaction jobs on PerformMicrotaskCheckpoint, or synchronously during Resolve/Reject when handlers are attached to an already-settled promise.

args are scope-local values valid ONLY for the duration of the call (the engine-owned handle scope around the callback closes when it returns); they must not be retained. Returning (Value{}, _) — or ok=false — leaves the JS return value undefined, which makes the derived promise fulfill with undefined. A returned Value must belong to an open scope of the same isolate. A panic prints a diagnostic and fail-fast aborts rather than unwinding into V8.

type NearHeapLimitCallback

type NearHeapLimitCallback func(currentHeapLimit, initialHeapLimit uint64) uint64

NearHeapLimitCallback is consulted when the heap approaches its limit. It receives the current and initial heap limits (bytes) and returns the new limit to install — raising it grants more budget (return current*2 to double), shrinking it forces the intended, controlled fatal OOM. The engine keeps ONE slot: only the most recently added callback is invoked. The callback runs on the isolate's thread inside GC and must not re-enter the engine.

type NewStringType

type NewStringType uint8

NewStringType mirrors v8::NewStringType.

const (
	// StringNormal creates a new string with fresh storage.
	StringNormal NewStringType = iota
	// StringInternalized hints old-generation allocation and deduplication
	// of identical strings ("Aside from performance implications there are
	// no differences between the two creation modes" - v8-primitive.h).
	StringInternalized
)

type NoCacheReason

type NoCacheReason int32

NoCacheReason reports why an embedder is not requesting or supplying a code cache. It is metadata for V8's compilation accounting and does not alter the result of a classic compile.

const (
	NoCacheNoReason NoCacheReason = iota
	NoCacheBecauseCachingDisabled
	NoCacheBecauseNoResource
	NoCacheBecauseInlineScript
	NoCacheBecauseModule
	NoCacheBecauseStreamingSource
	NoCacheBecauseInspector
	NoCacheBecauseScriptTooSmall
	NoCacheBecauseCacheTooCold
	NoCacheBecauseV8Extension
	NoCacheBecauseExtensionModule
	NoCacheBecausePacScript
	NoCacheBecauseInDocumentWrite
	NoCacheBecauseResourceWithNoCacheHandler
	NoCacheBecauseDeferredProduceCodeCache
)

type OOMErrorCallback

type OOMErrorCallback func(location, detail string, isHeapOOM bool)

OOMErrorCallback observes a fatal out-of-memory event: location names the site ("Reached heap limit" for heap OOM), detail is the engine's detail string (empty on the heap-OOM path in this build), isHeapOOM distinguishes heap OOM from other OOMs. When the handler returns, the engine aborts the process; the handler only observes.

type Object

type Object struct {
	Value
}

Object is a value known to be a JS object (used for the global object).

func AsObject

func AsObject(v Value) (*Object, error)

AsObject converts a generic value into an object view of it. Deserialized plain objects are inspected through it (property access), mirroring the oracle's try_cast::<v8::Object>.

func (*Object) CallAsConstructor

func (o *Object) CallAsConstructor(s *Scope, c *Context, args []Value, tc *TryCatch) (Value, error)

CallAsConstructor invokes the object as a constructor (`new`): the returned value is the constructed `this` unless the constructor returns an object, which replaces it. A non-constructor raises the pinned "object is not a constructor" TypeError, delivered to tc when given and reported as an error.

func (*Object) CallAsFunction

func (o *Object) CallAsFunction(s *Scope, c *Context, recv Value, args []Value, tc *TryCatch) (Value, error)

CallAsFunction invokes the object as a function with recv as the receiver (the undefined receiver is normalized to the global object by the engine, exactly like a sloppy-mode JS call). A non-callable object raises the pinned "object is not a function" TypeError, delivered to tc when given and reported as an error.

func (*Object) CreateDataProperty

func (o *Object) CreateDataProperty(s *Scope, c *Context, key, value Value) (bool, error)

CreateDataProperty creates (or redefines) key as a plain enumerable, writable, configurable data property. key must be a Name (string or symbol).

func (*Object) CreationContext

func (o *Object) CreationContext(s *Scope) (context *ContextRef, present bool, err error)

CreationContext returns the scope-local Context in which o was created. present is false when V8 returns an empty MaybeLocal; that is not an error. The returned reference becomes invalid when s closes.

func (*Object) CreationContextIs

func (o *Object) CreationContextIs(s *Scope, c *Context) (bool, error)

CreationContextIs reports whether the object was created in c. An object with no creation context at all (the engine's empty maybe) is an error, not a mismatch — the pinned crate maps that case to None.

func (*Object) DefineOwnProperty

func (o *Object) DefineOwnProperty(s *Scope, c *Context, key, value Value, attr PropertyAttribute) (bool, error)

DefineOwnProperty defines key with value and the given attribute bits (like Object.defineProperty with a partial data descriptor).

func (*Object) DefineProperty

func (o *Object) DefineProperty(s *Scope, c *Context, key Value, desc *PropertyDescriptor) (bool, error)

DefineProperty defines key according to the descriptor (the general Object.defineProperty mechanism). key must be a Name.

func (*Object) Delete

func (o *Object) Delete(s *Scope, c *Context, key Value, tc *TryCatch) (bool, error)

Delete removes the property under an arbitrary key value. A missing key deletes "successfully" (true); a non-configurable or frozen property refuses the delete (false) without throwing in sloppy mode.

func (*Object) DeleteIndex

func (o *Object) DeleteIndex(s *Scope, c *Context, index uint32, tc *TryCatch) (bool, error)

DeleteIndex removes the index property (creating a hole in arrays).

func (*Object) DeletePrivate

func (o *Object) DeletePrivate(s *Scope, c *Context, key *Private) (bool, error)

DeletePrivate removes the private key; ok reports whether it was present.

func (*Object) GetByKey

func (o *Object) GetByKey(s *Scope, c *Context, key Value) (Value, error)

GetByKey reads the property held under an arbitrary key value (string or symbol). A missing key reads as the undefined value; an error means the getter threw.

func (*Object) GetByName

func (o *Object) GetByName(s *Scope, c *Context, name string) (val Value, ok bool, err error)

GetByName reads a named property from the object. ok is false when the getter threw. The scope and context must belong to the same isolate as the object.

func (*Object) GetConstructorName

func (o *Object) GetConstructorName(s *Scope) (Value, error)

GetConstructorName returns the name of the function invoked as the object's constructor (a scope-local string value): the literal constructor for instances, "Object" for plain API objects and literals, "Function" for function and class objects themselves, and the new.target name for Reflect.construct results. Read it with StringValue.

func (*Object) GetIdentityHash

func (o *Object) GetIdentityHash() (int32, error)

GetIdentityHash returns the object's identity hash: never zero, stable for the object's lifetime, seeded per isolate (never compare hashes across isolates or processes). Identical to Value.GetHash of the same object interpreted as int32.

func (*Object) GetOwnPropertyDescriptor

func (o *Object) GetOwnPropertyDescriptor(s *Scope, c *Context, key Value) (Value, error)

GetOwnPropertyDescriptor returns the property's descriptor object (JSON/stringify-able, mirroring Object.getOwnPropertyDescriptor). A missing key reads as the undefined VALUE (the pinned nuance); an error means the call threw.

func (*Object) GetOwnPropertyNames

func (o *Object) GetOwnPropertyNames(s *Scope, c *Context, propertyFilter PropertyFilter, conversion KeyConversionMode) (*Array, error)

GetOwnPropertyNames returns only own property names, applying the pinned Object::get_own_property_names filter and numeric-key conversion. Unlike GetPropertyNames, this upstream API has no prototype or index-filter knobs.

func (*Object) GetPrivate

func (o *Object) GetPrivate(s *Scope, c *Context, key *Private) (Value, error)

GetPrivate reads the value stored under the private key (the undefined value when absent).

func (*Object) GetPropertyAttributes

func (o *Object) GetPropertyAttributes(s *Scope, c *Context, key Value) (attr PropertyAttribute, present bool, err error)

GetPropertyAttributes returns the PropertyAttribute bits of key. The second result mirrors the engine's Maybe: a MISSING property is Just(NONE) (present=true, attr=PropertyAttributeNone) — the pinned nuance; present is only false when the call threw (err is non-nil in that case).

func (*Object) GetPropertyNames

func (o *Object) GetPropertyNames(s *Scope, c *Context, mode KeyCollectionMode, propertyFilter PropertyFilter, indexFilter IndexFilter, conversion KeyConversionMode) (*Array, error)

GetPropertyNames collects the object's property names according to the four-way filter (collection mode, property filter, index filter and key conversion), mirroring the crate's GetPropertyNamesArgs.

func (*Object) GetPrototype

func (o *Object) GetPrototype(s *Scope) (Value, error)

GetPrototype returns the object's prototype. The engine always produces a value here: Object.prototype for fresh plain objects, and the null value for objects whose prototype is null (including Object.prototype itself). The scope must belong to the object's isolate.

func (*Object) GetRealNamedProperty

func (o *Object) GetRealNamedProperty(s *Scope, c *Context, key Value, tc *TryCatch) (val Value, found bool, err error)

GetRealNamedProperty reads the property under a Name key while bypassing named interceptors (walking the real prototype chain instead). found is false on a plain miss — which is NOT an error; err is non-nil only when the lookup threw. key must be a Name (string or symbol).

func (*Object) GetRealNamedPropertyAttributes

func (o *Object) GetRealNamedPropertyAttributes(s *Scope, c *Context, key Value) (attr PropertyAttribute, present bool, err error)

GetRealNamedPropertyAttributes returns the PropertyAttribute bits of the real (interceptor-bypassing) property under the Name key. A missing property is (AttrNone, false, nil) — the engine's Nothing; err is non-nil only when the lookup threw.

func (*Object) GetWithReceiver

func (o *Object) GetWithReceiver(s *Scope, c *Context, key Value, receiver *Object) (Value, error)

GetWithReceiver reads key with receiver as the lookup start and `this` for accessors (even when unrelated to the holder). A missing property reads as the undefined value; an error means the getter threw.

func (*Object) Has

func (o *Object) Has(s *Scope, c *Context, key Value, tc *TryCatch) (bool, error)

Has reports whether the object has the property (own or on the prototype chain) under an arbitrary key value: strings and symbols work directly, other values are converted by the engine (a plain object converts to "[object Object]"; an object that cannot convert throws a TypeError which is delivered to tc when given). A thrown conversion is reported as an error; tc follows the Compile/Run convention.

func (*Object) HasIndex

func (o *Object) HasIndex(s *Scope, c *Context, index uint32, tc *TryCatch) (bool, error)

HasIndex reports whether the index property exists.

func (*Object) HasOwnProperty

func (o *Object) HasOwnProperty(s *Scope, c *Context, key Value, tc *TryCatch) (bool, error)

HasOwnProperty reports whether key is an OWN property (the prototype chain is not consulted). key must be a Name (string or symbol).

func (*Object) HasPrivate

func (o *Object) HasPrivate(s *Scope, c *Context, key *Private) (bool, error)

HasPrivate reports whether the private key is present.

func (*Object) HasRealNamedProperty

func (o *Object) HasRealNamedProperty(s *Scope, c *Context, key Value) (bool, error)

HasRealNamedProperty reports whether a real (interceptor-bypassing) property exists under the Name key. Note the pinned engine's own-only observation for this query is pinned by the conformance slice: inherited real properties are found by GetRealNamedProperty but report false here.

func (*Object) IsAPIWrapper

func (o *Object) IsAPIWrapper() (bool, error)

IsAPIWrapper reports V8's embedder-wrapper classification. Objects merely having internal fields need not be API wrappers; V8 decides the category.

func (*Object) IsCallable

func (o *Object) IsCallable() (bool, error)

IsCallable reports whether the object can be called as a function (functions, arrows, methods, bound functions, class constructors, callable proxies, builtins — but not plain objects).

func (*Object) IsConstructor

func (o *Object) IsConstructor() (bool, error)

IsConstructor reports whether the object can be invoked by `new`. It follows bound targets and proxies of constructors; arrows, methods, generators, async functions and non-constructable builtins are false.

func (*Object) PreviewEntries

func (o *Object) PreviewEntries(s *Scope, c *Context) (entries *Array, keyValue, present bool, err error)

PreviewEntries returns V8's debugger-style entry snapshot for Map, Set, WeakMap, WeakSet, and their iterators. present=false is the upstream empty Option for unsupported receivers. keyValue reports whether adjacent array elements form key/value pairs. Go takes c explicitly because Scope does not itself carry the current Context; Rust's PinScope supplies that implicitly.

func (*Object) SetAccessor

func (o *Object) SetAccessor(s *Scope, c *Context, key Value, getter AccessorGetterCallback, setter AccessorSetterCallback) (bool, error)

SetAccessor installs a native accessor pair on the OBJECT itself (not a template): every read invokes getter and every write invokes setter (either may be nil). The write routes through Object::Set, so JS writes reach the setter too. To JS property descriptors the property appears as a data property carrying its current value (the pinned AccessorInfo observation). key must be a Name.

func (*Object) SetAccessorWithConfiguration

func (o *Object) SetAccessorWithConfiguration(s *Scope, c *Context, key Value, configuration AccessorConfiguration) (bool, error)

SetAccessorWithConfiguration installs an instance-level accessor. Unlike the lower-level V8 signature, the pinned rusty_v8 configuration always has a getter; Go rejects a missing getter before crossing the callback ABI.

func (*Object) SetByKey

func (o *Object) SetByKey(s *Scope, c *Context, key, value Value) (bool, error)

SetByKey writes the property held under an arbitrary key value. ok is Just(false) when the write was ignored (e.g. a non-writable inherited property in non-strict mode); an error means the setter threw.

func (*Object) SetByName

func (o *Object) SetByName(s *Scope, c *Context, name string, v Value) (ok bool, err error)

SetByName writes a named property. ok is false when the setter threw; the bool return of v8 Object::Set is folded into ok as well (the oracle treats both empty Maybe and false identically for this check). The scope, context, and value must all belong to the same isolate as the object.

func (*Object) SetIntegrityLevel

func (o *Object) SetIntegrityLevel(s *Scope, c *Context, level IntegrityLevel) (bool, error)

SetIntegrityLevel seals (no deletions, no additions) or freezes (additionally read-only existing data properties) the object.

func (*Object) SetLazyDataProperty

func (o *Object) SetLazyDataProperty(s *Scope, c *Context, key Value, getter AccessorGetterCallback) (bool, error)

SetLazyDataProperty installs a lazy data property: getter runs on the first read of key, and the property is then an ordinary data property — later reads (native or JS) never re-invoke the getter. key must be a Name; the install uses no attributes and side-effect-ful callbacks, the pinned crate's defaults.

func (*Object) SetLazyDataPropertyWithConfiguration

func (o *Object) SetLazyDataPropertyWithConfiguration(s *Scope, c *Context, key Value, configuration LazyDataPropertyConfiguration) (bool, error)

SetLazyDataPropertyWithConfiguration installs a lazy data property with explicit callback data, attributes, and debugger side-effect metadata. V8 152 CHECK-fails for a setter side-effect type of HasNoSideEffect; the Go API turns that fatal-only precondition into a deterministic error.

func (*Object) SetLazyDataPropertyWithData

func (o *Object) SetLazyDataPropertyWithData(s *Scope, c *Context, key Value, getter AccessorGetterCallback, data Value, attr PropertyAttribute, getterSideEffectType, setterSideEffectType SideEffectType) (bool, error)

SetLazyDataPropertyWithData is the positional counterpart of rusty_v8's set_lazy_data_property_with_data.

func (*Object) SetPrivate

func (o *Object) SetPrivate(s *Scope, c *Context, key *Private, value Value) (bool, error)

SetPrivate stores value under the private key (invisible to JS).

func (*Object) SetPrototype

func (o *Object) SetPrototype(s *Scope, c *Context, proto Value) (bool, error)

SetPrototype re-points the object's prototype (v8 Object::SetPrototypeV2). Setting null is legal. The engine's cyclic __proto__ rejection surfaces as (false, err) WITHOUT a pending exception — HasCaught stays false — so callers must not treat the error alone as "an exception was thrown".

func (*Object) SetWithReceiver

func (o *Object) SetWithReceiver(s *Scope, c *Context, key, value Value, receiver *Object) (bool, error)

SetWithReceiver writes key with receiver as `this` for accessors and as the redirect target for data properties (writing through an unrelated receiver creates the property on the receiver). ok is Just(false) when the write was ignored; an error means the setter threw.

type ObjectTemplate

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

ObjectTemplate is a scope-local template for creating objects.

func (*ObjectTemplate) Data

func (t *ObjectTemplate) Data() (Data, error)

Data returns t as its Data supertype without changing its local lifetime.

func (*ObjectTemplate) InternalFieldCount

func (t *ObjectTemplate) InternalFieldCount() (int, error)

InternalFieldCount returns the number of internal fields configured on this template.

func (*ObjectTemplate) NewInstance

func (t *ObjectTemplate) NewInstance(s *Scope, c *Context) (*Object, bool, error)

NewInstance creates a new object from the template in the context; ok is false when creation threw.

func (*ObjectTemplate) Set

func (t *ObjectTemplate) Set(key string, value Value) error

Set adds a property to every object created from this template (v8 Template::Set with PropertyAttribute::None).

func (*ObjectTemplate) SetAccessorProperty

func (t *ObjectTemplate) SetAccessorProperty(key string, getter, setter *FunctionTemplate, attr PropertyAttribute) error

SetAccessorProperty installs an accessor-SHAPED property on the template (v8 ObjectTemplate::SetAccessorProperty): instances expose function-valued get/set in their property descriptor, unlike the native data property of SetAccessorWithSetter. Exactly one of getter/setter must be non-nil.

func (*ObjectTemplate) SetAccessorPropertyName

func (t *ObjectTemplate) SetAccessorPropertyName(key Value, getter, setter *FunctionTemplate, attr PropertyAttribute) error

SetAccessorPropertyName installs function-template getter/setter accessors under a String or Symbol key on every object produced by this template.

func (*ObjectTemplate) SetAccessorWithConfiguration

func (t *ObjectTemplate) SetAccessorWithConfiguration(key string, configuration AccessorConfiguration) error

SetAccessorWithConfiguration installs a native accessor on every instance produced by this ObjectTemplate. The callback data is isolate-retained and Attribute is applied to the instantiated property. Keys are strings in the current Go template surface; the pinned crate additionally accepts Symbols.

func (*ObjectTemplate) SetAccessorWithConfigurationName

func (t *ObjectTemplate) SetAccessorWithConfigurationName(key Value, configuration AccessorConfiguration) error

SetAccessorWithConfigurationName installs a native accessor under a String or Symbol key on every instance. Callback data and attributes are retained by V8 with the template. Getter is required by AccessorConfiguration.

func (*ObjectTemplate) SetAccessorWithSetter

func (t *ObjectTemplate) SetAccessorWithSetter(key string, getter AccessorGetterCallback, setter AccessorSetterCallback) error

SetAccessorWithSetter installs a native data property: every read invokes the getter, every write the setter, and no backing storage exists (v8 ObjectTemplate::SetNativeDataProperty). Exactly one callback may be nil to install a setter-less or getter-less accessor.

func (*ObjectTemplate) SetAccessorWithSetterName

func (t *ObjectTemplate) SetAccessorWithSetterName(key Value, getter AccessorGetterCallback, setter AccessorSetterCallback) error

SetAccessorWithSetterName is the String-or-Symbol-keyed counterpart of SetAccessorWithSetter. Exactly one callback may be nil. A setter-only accessor uses the same safe no-op getter as the string-key convenience.

func (*ObjectTemplate) SetCallAsFunctionHandler

func (t *ObjectTemplate) SetCallAsFunctionHandler(cb FunctionCallback, data Value) error

SetCallAsFunctionHandler makes every instance created from this template callable (v8 ObjectTemplate::SetCallAsFunctionHandler): plain calls and construct calls both dispatch to cb (IsConstructCall distinguishes them) and even primitive return values are delivered as construct results. data is observed via args.Data(); zero Value means none.

func (*ObjectTemplate) SetData

func (t *ObjectTemplate) SetData(key string, ft *FunctionTemplate) error

SetData installs a template-derived value (a FunctionTemplate) as a plain property on this object template -- Template::Set where the Data value is another template (e.g. putting a method template on a prototype template).

func (*ObjectTemplate) SetDataNameWithAttr

func (t *ObjectTemplate) SetDataNameWithAttr(key Value, data Data, attr PropertyAttribute) error

SetDataNameWithAttr installs supported V8 Data under a String or Symbol key. Safe data is limited to primitives and nested Function/ObjectTemplate values, matching SetDataWithAttr's fatal-boundary protection.

func (*ObjectTemplate) SetDataWithAttr

func (t *ObjectTemplate) SetDataWithAttr(key string, data Data, attr PropertyAttribute) error

SetDataWithAttr adds supported V8 Data to every object created from this template. JavaScript primitives and nested FunctionTemplate or ObjectTemplate values are accepted. JSReceiver values and internal metadata are rejected before V8's fatal Template::Set boundary.

func (*ObjectTemplate) SetImmutableProto

func (t *ObjectTemplate) SetImmutableProto() error

SetImmutableProto makes every instance created from this template an immutable-prototype exotic object: setPrototypeOf (and __proto__ assignment) THROWS instead of silently failing (v8 ObjectTemplate::SetImmutableProto).

func (*ObjectTemplate) SetIndexedPropertyHandler

func (t *ObjectTemplate) SetIndexedPropertyHandler(cfg IndexedPropertyHandlerConfig) error

SetIndexedPropertyHandler installs the indexed property interceptor family on the template.

func (*ObjectTemplate) SetInternalFieldCount

func (t *ObjectTemplate) SetInternalFieldCount(n int) (bool, error)

SetInternalFieldCount configures every instance created from this template to have n internal fields. The bool return mirrors the crate: false only when n is out of range.

func (*ObjectTemplate) SetIntrinsicDataProperty

func (t *ObjectTemplate) SetIntrinsicDataProperty(key string, intrinsic Intrinsic, attr PropertyAttribute) error

SetIntrinsicDataProperty binds one of the context's real intrinsic objects (e.g. Array.prototype) as a data property on every instance created from this template (v8 Template::SetIntrinsicDataProperty), with attr applied.

func (*ObjectTemplate) SetIntrinsicDataPropertyName

func (t *ObjectTemplate) SetIntrinsicDataPropertyName(key Value, intrinsic Intrinsic, attr PropertyAttribute) error

SetIntrinsicDataPropertyName binds a context intrinsic under a String or Symbol key on every object produced from the template.

func (*ObjectTemplate) SetName

func (t *ObjectTemplate) SetName(key Value, value Value) error

SetName is the Name-keyed counterpart of Set. key may be a String or a Symbol and is retained by V8 with the template.

func (*ObjectTemplate) SetNameWithAttr

func (t *ObjectTemplate) SetNameWithAttr(key Value, value Value, attr PropertyAttribute) error

SetNameWithAttr is Template::Set with a String or Symbol key and explicit property attributes.

func (*ObjectTemplate) SetNamedPropertyHandler

func (t *ObjectTemplate) SetNamedPropertyHandler(cfg NamedPropertyHandlerConfig) error

SetNamedPropertyHandler installs the named property interceptor family on the template (v8 ObjectTemplate::SetHandler with a NamedPropertyHandlerConfiguration).

func (*ObjectTemplate) SetWithAttr

func (t *ObjectTemplate) SetWithAttr(key string, value Value, attr PropertyAttribute) error

SetWithAttr is Template::Set with explicit property attributes.

type Origin

type Origin struct {
	// ResourceName is the script's file name. Required (the engine keys
	// exception positions and stack frames off it). It is retained as the
	// convenient string form used by existing callers.
	ResourceName string
	// ResourceNameValue supplies the resource name as an existing scope-local
	// JavaScript Value, matching ScriptOrigin's arbitrary Local<Value> input.
	// A non-zero Value takes precedence over ResourceName and preserves its
	// exact type and identity. It must be live and belong to this Context's
	// isolate when CompileWithOrigin is called. CompileUnbound and
	// CompileCached reject this form before FFI because the pinned code-cache
	// path fatals for object-valued resource names.
	ResourceNameValue Value
	// LineOffset/ColumnOffset shift reported line/column numbers.
	LineOffset   int32
	ColumnOffset int32
	// ScriptID is the origin-declared id. Fresh compiles get their own
	// engine-assigned id (the oracle pins that the declared id is ignored).
	ScriptID int32
	// SourceMapURL, or "" for none.
	SourceMapURL        string
	IsOpaque            bool
	IsSharedCrossOrigin bool
	// IsWasm and IsModule exist for completeness. IsModule with a classic
	// compile is an upstream engine FATAL in this build (ApiCheck:
	// "CompileModule must be used to compile modules"); modules are out of
	// milestone scope, and the boundary is characterized by the Go
	// subprocess tests rather than reachable productively.
	IsWasm   bool
	IsModule bool
}

Origin mirrors the ScriptOrigin knobs of the pinned crate. The zero value is the neutral origin (line/column 0, script id 0, no source map, plain classic script).

type PlatformImpl

type PlatformImpl interface {
	PostTask(PlatformIsolate, *Task)
	PostNonNestableTask(PlatformIsolate, *Task)
	PostDelayedTask(PlatformIsolate, *Task, float64)
	PostNonNestableDelayedTask(PlatformIsolate, *Task, float64)
	PostIdleTask(PlatformIsolate, *IdleTask)
}

PlatformImpl receives ownership of foreground tasks posted by V8. Calls may arrive concurrently from arbitrary native threads; implementations must be concurrency-safe. Retain the task, then run it later on the isolate's owning thread, or Close it without running.

type PlatformImplCloser

type PlatformImplCloser interface{ Close() }

PlatformImplCloser is optionally implemented by PlatformImpl. Close is invoked exactly once when DisposePlatform destroys the native platform, after outstanding task wrappers have been closed.

type PlatformImplDefaults

type PlatformImplDefaults struct{}

PlatformImplDefaults supplies rusty_v8 152.2.0's default PlatformImpl methods for embedding in a custom implementation. Every method runs and destroys the transferred task synchronously on the thread that invoked the callback. The delayed methods intentionally ignore their delay, and the idle method uses an absolute deadline of +0.0.

This behavior is opt-in because synchronous execution is reentrant and may deadlock inside V8. In particular, PostNonNestableTask can be called by Atomics.notify while V8 holds its waiter lock; immediately running that task attempts to acquire the same lock. Synchronous execution also means a task posted from a background thread runs on that background thread. Embed this type only when exact rusty_v8 default behavior is required and those hazards are acceptable. PlatformImplFuncs remains the nil-safe adapter: an unset callback drops its task without running it.

func (PlatformImplDefaults) PostDelayedTask

func (PlatformImplDefaults) PostDelayedTask(_ PlatformIsolate, task *Task, _ float64)

func (PlatformImplDefaults) PostIdleTask

func (PlatformImplDefaults) PostIdleTask(_ PlatformIsolate, task *IdleTask)

func (PlatformImplDefaults) PostNonNestableDelayedTask

func (PlatformImplDefaults) PostNonNestableDelayedTask(_ PlatformIsolate, task *Task, _ float64)

func (PlatformImplDefaults) PostNonNestableTask

func (PlatformImplDefaults) PostNonNestableTask(_ PlatformIsolate, task *Task)

func (PlatformImplDefaults) PostTask

func (PlatformImplDefaults) PostTask(_ PlatformIsolate, task *Task)

type PlatformImplFuncs

type PlatformImplFuncs struct {
	Task                   func(PlatformIsolate, *Task)
	NonNestableTask        func(PlatformIsolate, *Task)
	DelayedTask            func(PlatformIsolate, *Task, float64)
	NonNestableDelayedTask func(PlatformIsolate, *Task, float64)
	IdleTask               func(PlatformIsolate, *IdleTask)
}

PlatformImplFuncs adapts function fields into PlatformImpl. A nil callback closes (drops) its task. In particular, it never runs non-nestable work synchronously: rusty_v8's immediate default deadlocks when Atomics.notify posts such work while holding V8's waiter lock, so Go chooses safe dropping as the explicit normalization.

func (PlatformImplFuncs) PostDelayedTask

func (f PlatformImplFuncs) PostDelayedTask(isolate PlatformIsolate, task *Task, delay float64)

func (PlatformImplFuncs) PostIdleTask

func (f PlatformImplFuncs) PostIdleTask(isolate PlatformIsolate, task *IdleTask)

func (PlatformImplFuncs) PostNonNestableDelayedTask

func (f PlatformImplFuncs) PostNonNestableDelayedTask(isolate PlatformIsolate, task *Task, delay float64)

func (PlatformImplFuncs) PostNonNestableTask

func (f PlatformImplFuncs) PostNonNestableTask(isolate PlatformIsolate, task *Task)

func (PlatformImplFuncs) PostTask

func (f PlatformImplFuncs) PostTask(isolate PlatformIsolate, task *Task)

type PlatformIsolate

type PlatformIsolate uintptr

PlatformIsolate is the stable, opaque identity supplied with a foreground task. It is comparable and suitable as a queue key, but cannot be converted into an Isolate. Task.Run verifies it against the caller-supplied Isolate.

type PlatformKind

type PlatformKind uint8

PlatformKind selects one of the default platform implementations exposed by the pinned rusty_v8 release. Custom PlatformImpl implementations are a separate API family and are not represented here.

const (
	PlatformDefault PlatformKind = iota
	PlatformUnprotected
	PlatformSingleThreaded
)

type PlatformOptions

type PlatformOptions struct {
	Kind               PlatformKind
	ThreadPoolSize     uint32
	IdleTaskSupport    bool
	SingleThreadedFlag bool
}

PlatformOptions configures the process-global platform installed by Initialize. ThreadPoolSize is clamped to 16, exactly like rusty_v8; zero asks V8 to choose a worker count. It is ignored for PlatformSingleThreaded and must be zero there.

SingleThreadedFlag is an explicit safety acknowledgement required for PlatformSingleThreaded. ConfigurePlatform applies V8's --single-threaded flag when it is true. The pinned native API accepts a single-threaded platform without that flag, but later asynchronous Wasm compilation access violates; Go rejects that configuration before engine entry instead.

type PrepareStackTraceCallback

type PrepareStackTraceCallback func(s *Scope, errorValue, sites Value) (result Value, ok bool)

PrepareStackTraceCallback replaces the `stack` VALUE for every error whose stack is first accessed. It receives the error and the CallSite array; the returned Value becomes the stack value. The ok result remains for API compatibility, but false is invalid and fails fast: pinned V8 asserts on an empty MaybeLocal, and rusty_v8 therefore requires a Local. Installing the hook disables the JS Error.prepareStackTrace hook entirely. The callback runs once per distinct error; the scope handed to it is owned by the engine trampoline and values created through it remain valid until the callback returns to the engine.

type PrimitiveArray

type PrimitiveArray struct{ Data }

PrimitiveArray is V8's fixed-sized mutable array of primitive Values.

func NewPrimitiveArray

func NewPrimitiveArray(s *Scope, length int) (*PrimitiveArray, error)

NewPrimitiveArray creates a primitive array initialized with undefined. rusty_v8 accepts usize and truncates it to C int. gov8 preserves every safe non-negative result of that conversion (for example 2^32 becomes zero), but rejects Go-negative inputs and conversions whose int32 result is negative, which are process-fatal in V8.

func (*PrimitiveArray) Get

func (a *PrimitiveArray) Get(s *Scope, index int) (Value, bool, error)

Get returns the primitive at index. Out-of-range indices return ok=false instead of reaching V8's process-fatal API check.

func (*PrimitiveArray) Length

func (a *PrimitiveArray) Length() (int, error)

Length returns the number of slots.

func (*PrimitiveArray) Set

func (a *PrimitiveArray) Set(s *Scope, index int, item Value) (bool, error)

Set replaces the primitive at index. ok=false reports an out-of-range index; non-primitive and cross-isolate values return an error.

type PrimitiveArrayGlobal

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

PrimitiveArrayGlobal is a strong persistent handle to a PrimitiveArray. It permits reopening the array in a later scope or context of the same isolate, matching Global<PrimitiveArray> in rusty_v8.

func NewPrimitiveArrayGlobal

func NewPrimitiveArrayGlobal(s *Scope, array *PrimitiveArray) (*PrimitiveArrayGlobal, error)

NewPrimitiveArrayGlobal roots array in a persistent cell.

func (*PrimitiveArrayGlobal) Close

func (g *PrimitiveArrayGlobal) Close() error

Close releases the persistent cell. Closing after the isolate is a safe no-op, consistent with the module's generic Global handle.

func (*PrimitiveArrayGlobal) ToLocal

func (g *PrimitiveArrayGlobal) ToLocal(s *Scope) (*PrimitiveArray, error)

ToLocal reopens the persistent array in s.

type Private

type Private struct{ Value }

Private is a private symbol (v8::Private). It is a Data, not a Value: the embedded Value exists only for handle plumbing and must not be used with value predicates. Private properties are completely invisible to JS property machinery.

func (*Private) Data

func (p *Private) Data() (Data, error)

Data returns p as its Data supertype without changing its local lifetime.

func (*Private) Name

func (p *Private) Name(s *Scope) (Value, error)

Name returns the private's name value (the undefined value for an anonymous private).

type Promise

type Promise struct {
	Value
}

Promise is a scope-local JS promise (v8::Promise).

func AsPromise

func AsPromise(v Value) (*Promise, error)

AsPromise casts a live scope-local value to a Promise after checking its engine kind. The returned Promise retains the value's original Scope and therefore becomes invalid with that Scope, matching Local::try_cast in the pinned Rust crate.

func (Promise) Catch

func (p Promise) Catch(c *Context, handler Value) (Promise, bool, error)

Catch registers handler as the rejection reaction. ok is false when the engine returned no derived promise (the oracle's Option mapping).

func (Promise) HasHandler

func (p Promise) HasHandler() (bool, error)

HasHandler reports whether the promise has at least one derived promise (resolve/reject handlers, including default handlers).

func (Promise) MarkAsHandled

func (p Promise) MarkAsHandled() error

MarkAsHandled marks the promise as handled so an unhandled-rejection notification is suppressed.

func (Promise) Result

func (p Promise) Result(s *Scope) (Value, error)

Result returns the [[PromiseResult]] value. The promise must not be pending (the engine contract; the check mirrors the Rust API).

func (Promise) State

func (p Promise) State() (PromiseState, error)

State reports the promise state.

func (Promise) StrictEquals

func (p Promise) StrictEquals(other Value) (bool, error)

StrictEquals reports v8 Value::StrictEquals for two values of the same isolate (used to prove derived promises are distinct objects).

func (Promise) Then

func (p Promise) Then(c *Context, handler Value) (Promise, error)

Then registers handler as the fulfillment AND rejection reaction (PerformPromiseThen with a fresh native promise as result) and returns the derived promise, which is always a distinct object. Under the Explicit microtasks policy the reaction job runs only on a microtask checkpoint. handler must be a function value of the same isolate — either a native function from NewNativeFunction or a JS function.

func (Promise) Then2

func (p Promise) Then2(c *Context, onFulfilled, onRejected Value) (Promise, error)

Then2 is Then with separate fulfillment and rejection reactions.

type PromiseHook

type PromiseHook func(t PromiseHookType, promise, parent Value)

PromiseHook observes promise lifecycle events. Init/Resolve fire synchronously at creation/resolution; Before/After bracket the reaction job at the microtask checkpoint. promise and parent are scope-local values valid only during the callback (parent is undefined for non-derived promises).

type PromiseHookType

type PromiseHookType uint32

PromiseHookType mirrors v8::PromiseHookType.

const (
	PromiseHookInit    PromiseHookType = 0
	PromiseHookResolve PromiseHookType = 1
	PromiseHookBefore  PromiseHookType = 2
	PromiseHookAfter   PromiseHookType = 3
)

type PromiseRejectCallback

type PromiseRejectCallback func(PromiseRejectMessage)

PromiseRejectCallback observes promise rejection events. It runs on the isolate's owning thread during engine execution. A panic prints a diagnostic and fail-fast aborts rather than unwinding into V8.

type PromiseRejectEvent

type PromiseRejectEvent int

PromiseRejectEvent mirrors v8::PromiseRejectEvent. The AfterResolved events were removed from V8 and never fire on the pinned build; they are kept for API parity.

const (
	PromiseRejectWithNoHandler     PromiseRejectEvent = 0
	PromiseHandlerAddedAfterReject PromiseRejectEvent = 1
	PromiseRejectAfterResolved     PromiseRejectEvent = 2
	PromiseResolveAfterResolved    PromiseRejectEvent = 3
)

func (PromiseRejectEvent) String

func (e PromiseRejectEvent) String() string

String returns the short oracle event names used in normalized output.

type PromiseRejectMessage

type PromiseRejectMessage struct {
	Event   PromiseRejectEvent
	Promise Promise
	// contains filtered or unexported fields
}

PromiseRejectMessage is delivered to the isolate's promise-reject callback synchronously: at reject time when no handler exists (WithNoHandler), when a handler is attached to a previously rejected promise (HandlerAddedAfterReject), or from a reaction job when a derived promise is left rejected and unhandled (WithNoHandler again).

Promise (and the value, when present) are scope-local handles valid only for the duration of the callback; they are bound to the scope the callback was registered with, which must still be open.

func (PromiseRejectMessage) Value

func (m PromiseRejectMessage) Value() (Value, bool)

Value returns the rejection value; ok is false for events that carry no value (HandlerAddedAfterReject).

type PromiseResolver

type PromiseResolver struct {
	Value
}

PromiseResolver is a scope-local promise resolver (v8::Promise::Resolver) together with the promise it settles (retrieved via GetPromise).

func (PromiseResolver) GetPromise

func (r PromiseResolver) GetPromise(s *Scope) (Promise, error)

GetPromise returns the resolver's associated promise.

func (PromiseResolver) Reject

func (r PromiseResolver) Reject(c *Context, v Value) (bool, error)

Reject settles the associated promise with value as the rejection reason, with the same call-success semantics as Resolve.

func (PromiseResolver) Resolve

func (r PromiseResolver) Resolve(c *Context, v Value) (bool, error)

Resolve settles the associated promise with value. The returned bool is the success of the CALL, not a settlement change: resolving or rejecting an already-settled promise is silently ignored by the engine and still reports true (pinned oracle contract).

type PromiseState

type PromiseState int

PromiseState mirrors v8::PromiseState.

const (
	PromisePending   PromiseState = 0
	PromiseFulfilled PromiseState = 1
	PromiseRejected  PromiseState = 2
)

func (PromiseState) String

func (s PromiseState) String() string

type PropertyAttribute

type PropertyAttribute uint8

PropertyAttribute mirrors v8::PropertyAttribute.

const (
	AttrNone       PropertyAttribute = 0
	AttrReadOnly   PropertyAttribute = 1
	AttrDontEnum   PropertyAttribute = 2
	AttrDontDelete PropertyAttribute = 4
)

type PropertyCallbackArguments

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

PropertyCallbackArguments mirrors v8::PropertyCallbackArguments for accessor callbacks and property interceptors: Holder is the object the property lives on, This is the receiver the operation was invoked on, Data is the callback data, and ShouldThrowOnError reports the strict-mode verdict (always false on kinds that do not carry it).

func (PropertyCallbackArguments) Data

Data returns the accessor's/handler's callback data; undefined when none.

func (PropertyCallbackArguments) Holder

func (a PropertyCallbackArguments) Holder() (*Object, error)

Holder returns the object holding the intercepted property.

func (PropertyCallbackArguments) Property

func (a PropertyCallbackArguments) Property() (Value, error)

Property returns the Name supplied to a named accessor callback. It is not available for indexed interceptor callbacks.

func (PropertyCallbackArguments) ShouldThrowOnError

func (a PropertyCallbackArguments) ShouldThrowOnError() bool

ShouldThrowOnError mirrors the pinned crate's PropertyCallbackArguments::should_throw_on_error. The pinned binding (src/binding.cc, v8 =152.2.0) instantiates v8::PropertyCallbackInfo<v8::Value>::ShouldThrowOnError(), whose `if constexpr (!HasShouldThrowOnError()) return false;` path makes the observation compile-time false on this build — including strict-mode stores (characterized by the tpladv fixture's "strict=false" entries). The raw engine bit is still captured in the dispatch frame; the Go surface intentionally reports the pinned crate's observable verdict.

func (PropertyCallbackArguments) This

func (a PropertyCallbackArguments) This() (*Object, error)

This returns the receiver the property operation was invoked on. v8 152's PropertyCallbackInfo exposes only Holder() (there is no separate This() accessor), so the shim captures the holder in both frame slots and this observation equals Holder() for property callbacks.

type PropertyDescriptor

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

PropertyDescriptor mirrors v8::PropertyDescriptor: a partial property description with presence flags for each field. It holds scope-local handle slots, so it is bound to the Scope it was created in: Close it before that Scope closes and do not use it afterwards (every accessor enforces both). It must only be used on the owning isolate thread.

func (*PropertyDescriptor) Close

func (pd *PropertyDescriptor) Close() error

Close releases the descriptor. It must not be used afterwards.

func (*PropertyDescriptor) Configurable

func (pd *PropertyDescriptor) Configurable() (bool, error)

Configurable returns the configurable flag (meaningful only when HasConfigurable).

func (*PropertyDescriptor) Enumerable

func (pd *PropertyDescriptor) Enumerable() (bool, error)

Enumerable returns the enumerable flag (meaningful only when HasEnumerable).

func (*PropertyDescriptor) Get

func (pd *PropertyDescriptor) Get() (Value, error)

Get returns the getter (valid only while the creating scope is open).

func (*PropertyDescriptor) HasConfigurable

func (pd *PropertyDescriptor) HasConfigurable() (bool, error)

HasConfigurable reports whether the configurable flag is specified.

func (*PropertyDescriptor) HasEnumerable

func (pd *PropertyDescriptor) HasEnumerable() (bool, error)

HasEnumerable reports whether the enumerable flag is specified.

func (*PropertyDescriptor) HasGet

func (pd *PropertyDescriptor) HasGet() (bool, error)

HasGet reports whether a getter is present.

func (*PropertyDescriptor) HasSet

func (pd *PropertyDescriptor) HasSet() (bool, error)

HasSet reports whether a setter is present.

func (*PropertyDescriptor) HasValue

func (pd *PropertyDescriptor) HasValue() (bool, error)

HasValue reports whether a data value is present.

func (*PropertyDescriptor) HasWritable

func (pd *PropertyDescriptor) HasWritable() (bool, error)

HasWritable reports whether the writable flag is specified.

func (*PropertyDescriptor) Set

func (pd *PropertyDescriptor) Set() (Value, error)

Set returns the setter (valid only while the creating scope is open).

func (*PropertyDescriptor) SetConfigurable

func (pd *PropertyDescriptor) SetConfigurable(configurable bool) error

SetConfigurable specifies the configurable flag in place.

func (*PropertyDescriptor) SetEnumerable

func (pd *PropertyDescriptor) SetEnumerable(enumerable bool) error

SetEnumerable specifies the enumerable flag in place.

func (*PropertyDescriptor) Value

func (pd *PropertyDescriptor) Value() (Value, error)

Value returns the data value (valid only while the creating scope is open; call HasValue first).

func (*PropertyDescriptor) Writable

func (pd *PropertyDescriptor) Writable() (bool, error)

Writable returns the writable flag (meaningful only when HasWritable).

type PropertyFilter

type PropertyFilter uint8

PropertyFilter mirrors v8::PropertyFilter (a bitmask).

const (
	PropertyFilterAllProperties    PropertyFilter = 0
	PropertyFilterOnlyWritable     PropertyFilter = 1 << 0
	PropertyFilterOnlyEnumerable   PropertyFilter = 1 << 1
	PropertyFilterOnlyConfigurable PropertyFilter = 1 << 2
	PropertyFilterSkipStrings      PropertyFilter = 1 << 3
	PropertyFilterSkipSymbols      PropertyFilter = 1 << 4
)

type PropertyHandlerFlags

type PropertyHandlerFlags uint8

PropertyHandlerFlags mirrors v8::PropertyHandlerFlags (the public bits; the engine's internal new-signature bit is managed by the engine bindings and never crosses this API).

const (
	// HandlerFlagNone is the default: every key reaches the handler.
	HandlerFlagNone PropertyHandlerFlags = 0
	// HandlerFlagNonMasking lets an existing own data property win over the
	// getter; absent properties are still intercepted.
	HandlerFlagNonMasking PropertyHandlerFlags = 1
	// HandlerFlagOnlyInterceptStrings bypasses the handler for symbol keys.
	HandlerFlagOnlyInterceptStrings PropertyHandlerFlags = 1 << 1
	// HandlerFlagHasNoSideEffect marks getter/query/enumerator as
	// side-effect-free (only observable under debug-evaluate).
	HandlerFlagHasNoSideEffect PropertyHandlerFlags = 1 << 2
)

type Proxy

type Proxy struct{ Value }

Proxy is a JS Proxy exotic object.

func AsProxy

func AsProxy(v Value) (*Proxy, error)

AsProxy casts a value to a Proxy after prevalidating the engine kind.

func (*Proxy) GetHandler

func (p *Proxy) GetHandler(s *Scope) (Value, error)

GetHandler returns the proxy handler object.

func (*Proxy) GetTarget

func (p *Proxy) GetTarget(s *Scope) (Value, error)

GetTarget returns the proxy target. After Revoke the engine clears the internal target, so this resolves to the JavaScript null value.

func (*Proxy) IsRevoked

func (p *Proxy) IsRevoked() (bool, error)

IsRevoked reports whether the proxy has been revoked.

func (*Proxy) Revoke

func (p *Proxy) Revoke() error

Revoke revokes the proxy. Property operations on it throw afterwards (observable natively through failed property calls and any active TryCatch).

type ReadHostObjectHook

type ReadHostObjectHook interface {
	ReadHostObject(r *DelegateValueDeserializer) (*Object, bool)
}

ReadHostObjectHook mirrors v8::ValueDeserializerImpl::read_host_object. Build the object with r.Scope()/r.Context() and the usual constructors; consume the wire with r.ReadUint32 / r.ReadRawBytes / .... found=false maps to None: the engine throws "Unable to deserialize cloned data." (a silent None is never a clean read on this build).

type RegExp

type RegExp struct{ Value }

RegExp is a JS RegExp object.

func AsRegExp

func AsRegExp(v Value) (*RegExp, error)

AsRegExp casts a value to a RegExp after prevalidating the engine kind.

func (*RegExp) Exec

func (re *RegExp) Exec(s *Scope, c *Context, subject Value) (*Object, error)

Exec runs the regexp against subject, honoring and updating lastIndex for global/sticky patterns. A miss is a non-nil result whose Value is the null value (the pinned Some(null) shape); a thrown exception returns a nil result and an error (the exception stays observable through any active TryCatch). subject must be a JS string.

func (*RegExp) GetSource

func (re *RegExp) GetSource(s *Scope) (Value, error)

GetSource returns the pattern source verbatim (a scope-local string).

type RegExpFlags

type RegExpFlags uint32

RegExpFlags mirrors v8::RegExp::Flags / the crate's RegExpCreationFlags.

const (
	RegExpGlobal      RegExpFlags = 1 << iota // g
	RegExpIgnoreCase                          // i
	RegExpMultiline                           // m
	RegExpSticky                              // y
	RegExpUnicode                             // u
	RegExpDotAll                              // s
	RegExpLinear                              // l (experimental engine)
	RegExpHasIndices                          // d
	RegExpUnicodeSets                         // v
)

type ResolveWasmModuleFromIDHook

type ResolveWasmModuleFromIDHook interface {
	ResolveWasmModuleFromID(r *DelegateValueDeserializer, id uint32) (module *WasmModuleObject, found bool)
}

ResolveWasmModuleFromIDHook is the typed completion of ValueDeserializerImpl::get_wasm_module_from_id. The returned module must be a live WasmModuleObject created in r.Scope() for the target isolate. found=false maps to None and V8's generic cloned-data error. The older GetWasmModuleFromIDHook remains supported as an observation-only hook.

type ReturnValue

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

ReturnValue receives the callback's JS return value. It is bound to the running callback; the engine pre-seeds it with undefined, so a callback that sets nothing returns undefined.

func (ReturnValue) Get

func (rv ReturnValue) Get() (Value, error)

Get reads back the value currently held by the return value: undefined when nothing was set, otherwise the last value stored by a setter (v8 ReturnValue::Get). The result is bound to the running callback's scope and must not outlive it.

func (ReturnValue) Set

func (rv ReturnValue) Set(v Value) error

Set stores an arbitrary value as the callback result.

func (ReturnValue) SetBool

func (rv ReturnValue) SetBool(v bool) error

SetBool stores a boolean.

func (ReturnValue) SetEmptyString

func (rv ReturnValue) SetEmptyString() error

SetEmptyString stores the empty string.

func (ReturnValue) SetFloat64

func (rv ReturnValue) SetFloat64(v float64) error

SetFloat64 stores a float64 (surfacing as a JS number).

func (ReturnValue) SetInt32

func (rv ReturnValue) SetInt32(v int32) error

SetInt32 stores an int32 (surfacing as a JS number).

func (ReturnValue) SetNull

func (rv ReturnValue) SetNull() error

SetNull stores null.

func (ReturnValue) SetUint32

func (rv ReturnValue) SetUint32(v uint32) error

SetUint32 stores a uint32 (surfacing as a JS number).

func (ReturnValue) SetUndefined

func (rv ReturnValue) SetUndefined() error

SetUndefined stores undefined.

type SIMDUTFBase64Options

type SIMDUTFBase64Options uint64

SIMDUTFBase64Options selects alphabet and padding behavior.

const (
	SIMDUTFBase64Default SIMDUTFBase64Options = iota
	SIMDUTFBase64URL
	SIMDUTFBase64DefaultNoPadding
	SIMDUTFBase64URLWithPadding
)

type SIMDUTFEncoding

type SIMDUTFEncoding int32

SIMDUTFEncoding is a bitmask returned by SIMDUTFDetectEncodings.

const (
	SIMDUTFEncodingUTF8    SIMDUTFEncoding = 1
	SIMDUTFEncodingUTF16LE SIMDUTFEncoding = 2
	SIMDUTFEncodingUTF16BE SIMDUTFEncoding = 4
	SIMDUTFEncodingUTF32LE SIMDUTFEncoding = 8
	SIMDUTFEncodingUTF32BE SIMDUTFEncoding = 16
	SIMDUTFEncodingLatin1  SIMDUTFEncoding = 32
)

func SIMDUTFDetectEncodings

func SIMDUTFDetectEncodings(v []byte) (SIMDUTFEncoding, error)

type SIMDUTFErrorCode

type SIMDUTFErrorCode int32

SIMDUTFErrorCode is a pinned simdutf error category.

const (
	SIMDUTFSuccess                SIMDUTFErrorCode = 0
	SIMDUTFHeaderBits             SIMDUTFErrorCode = 1
	SIMDUTFTooShort               SIMDUTFErrorCode = 2
	SIMDUTFTooLong                SIMDUTFErrorCode = 3
	SIMDUTFOverlong               SIMDUTFErrorCode = 4
	SIMDUTFTooLarge               SIMDUTFErrorCode = 5
	SIMDUTFSurrogate              SIMDUTFErrorCode = 6
	SIMDUTFInvalidBase64Character SIMDUTFErrorCode = 7
	SIMDUTFBase64InputRemainder   SIMDUTFErrorCode = 8
	SIMDUTFBase64ExtraBits        SIMDUTFErrorCode = 9
	SIMDUTFOutputBufferTooSmall   SIMDUTFErrorCode = 10
	SIMDUTFOther                  SIMDUTFErrorCode = 11
)

func (SIMDUTFErrorCode) String

func (c SIMDUTFErrorCode) String() string

type SIMDUTFLastChunkHandling

type SIMDUTFLastChunkHandling uint64

SIMDUTFLastChunkHandling controls incomplete final base64 groups.

const (
	SIMDUTFLastChunkLoose SIMDUTFLastChunkHandling = iota
	SIMDUTFLastChunkStrict
	SIMDUTFLastChunkStopBeforePartial
	SIMDUTFLastChunkOnlyFullChunks
)

type SIMDUTFResult

type SIMDUTFResult struct {
	Error SIMDUTFErrorCode
	Count int
}

SIMDUTFResult reports either the number of units processed/written or the input position at which conversion failed.

func SIMDUTFBase64ToBinary

func SIMDUTFBase64ToBinary(input, output []byte, options SIMDUTFBase64Options, last SIMDUTFLastChunkHandling) (SIMDUTFResult, error)

func SIMDUTFConvertUTF8ToLatin1WithErrors

func SIMDUTFConvertUTF8ToLatin1WithErrors(input, output []byte) (SIMDUTFResult, error)

func SIMDUTFConvertUTF8ToUTF16LEWithErrors

func SIMDUTFConvertUTF8ToUTF16LEWithErrors(input []byte, output []uint16) (SIMDUTFResult, error)

func SIMDUTFConvertUTF16LEToUTF8WithErrors

func SIMDUTFConvertUTF16LEToUTF8WithErrors(input []uint16, output []byte) (SIMDUTFResult, error)

func SIMDUTFValidateASCIIWithErrors

func SIMDUTFValidateASCIIWithErrors(input []byte) (SIMDUTFResult, error)

func SIMDUTFValidateUTF8WithErrors

func SIMDUTFValidateUTF8WithErrors(input []byte) (SIMDUTFResult, error)

func SIMDUTFValidateUTF16BEWithErrors

func SIMDUTFValidateUTF16BEWithErrors(input []uint16) (SIMDUTFResult, error)

func SIMDUTFValidateUTF16LEWithErrors

func SIMDUTFValidateUTF16LEWithErrors(input []uint16) (SIMDUTFResult, error)

func SIMDUTFValidateUTF32WithErrors

func SIMDUTFValidateUTF32WithErrors(input []uint32) (SIMDUTFResult, error)

func (SIMDUTFResult) OK

func (r SIMDUTFResult) OK() bool

type Scope

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

Scope owns a v8 HandleScope. Every local handle (Value) created through a Scope lives in that scope's slot storage and becomes invalid once the scope is closed; the Go wrapper enforces this by refusing to operate on values whose scope is closed. Open scopes per isolate must strictly nest (that is a V8 rule) and must be closed on the isolate's owning thread.

func (*Scope) BigIntFromInt64

func (s *Scope) BigIntFromInt64(v int64) (Value, error)

BigIntFromInt64 returns a BigInt constructed from an int64.

func (*Scope) BigIntFromUint64

func (s *Scope) BigIntFromUint64(v uint64) (Value, error)

BigIntFromUint64 returns a BigInt constructed from a uint64.

func (*Scope) BigIntFromWords

func (s *Scope) BigIntFromWords(c *Context, sign bool, words []uint64, tc *TryCatch) (Value, error)

BigIntFromWords builds (-1)^sign * sum(words[i] * 2^(64*i)). The context is required (the engine API resolves the current context for allocation and the over-limit throw). A word count beyond the engine's BigInt maximum fails with a pending JS RangeError: with tc non-nil the exception is observable there and the error is returned; with tc nil a shim-internal TryCatch observes it.

func (*Scope) Boolean

func (s *Scope) Boolean(b bool) (Value, error)

Boolean returns a JS boolean in the scope.

func (*Scope) Close

func (s *Scope) Close() error

Close closes the HandleScope. All Values created through this scope must no longer be used afterwards.

func (*Scope) ConcatString

func (s *Scope) ConcatString(left, right Value) (Value, error)

ConcatString concatenates two strings (String::concat). Both operands must be strings of the receiver's isolate. A result beyond StringMaxLength fails with a recoverable error.

func (*Scope) ContextFromSnapshot

func (s *Scope) ContextFromSnapshot(index int) (*Context, bool, error)

ContextFromSnapshot recovers an added context (global proxy included) from the snapshot backing the isolate. ok is false for out-of-range or absent indices, matching the pinned Context::from_snapshot returning None.

func (*Scope) ContextFromSnapshotWithOptions

func (s *Scope) ContextFromSnapshotWithOptions(index uint64, options *ContextOptions) (*Context, bool, error)

ContextFromSnapshotWithOptions recovers an added context using the exact size_t snapshot index and the options supported by rusty_v8. GlobalTemplate is intentionally ignored: Context::from_snapshot reuses serialized global state and forwards only GlobalObject and MicrotaskQueue to V8.

NoContextSnapshotIndex mirrors usize::MAX. It creates a fresh context even when the isolate has no startup blob. Other absent indices return ok=false.

func (*Scope) CurrentScriptNameOrSourceURL

func (s *Scope) CurrentScriptNameOrSourceURL() (string, bool, error)

CurrentScriptNameOrSourceURL returns the script name (or source URL) of the topmost JS frame; ok=false when there is none.

func (*Scope) CurrentScriptNameOrSourceURLValue

func (s *Scope) CurrentScriptNameOrSourceURLValue() (Value, bool, error)

CurrentScriptNameOrSourceURLValue returns the topmost script name or sourceURL as a scope-local JavaScript String without copying it to Go.

func (*Scope) CurrentStackTrace

func (s *Scope) CurrentStackTrace(frameLimit int) (*StackTrace, bool, error)

CurrentStackTrace captures up to frameLimit frames of the current JS stack; ok=false when the engine produced none.

func (*Scope) EmptyString

func (s *Scope) EmptyString() (Value, error)

EmptyString returns the canonical empty string (the engine's read-only empty-string root, not a fresh allocation).

func (*Scope) GetAsyncIteratorSymbol

func (s *Scope) GetAsyncIteratorSymbol() (*Symbol, error)

GetAsyncIteratorSymbol returns the well-known Symbol.asyncIterator.

func (*Scope) GetContextDataFromSnapshotOnce

func (s *Scope) GetContextDataFromSnapshotOnce(c *Context, index int, want SnapshotDataType) (Value, error)

GetContextDataFromSnapshotOnce is the context-snapshot counterpart of GetIsolateDataFromSnapshotOnce, with the same exactly-once and BadType semantics. The context must belong to the same isolate as the scope.

func (*Scope) GetContinuationPreservedEmbedderData

func (s *Scope) GetContinuationPreservedEmbedderData() (Value, error)

GetContinuationPreservedEmbedderData returns the isolate-wide continuation data in s. Before the first Set it is the JavaScript undefined value.

func (*Scope) GetHasInstanceSymbol

func (s *Scope) GetHasInstanceSymbol() (*Symbol, error)

GetHasInstanceSymbol returns the well-known Symbol.hasInstance.

func (*Scope) GetIsConcatSpreadableSymbol

func (s *Scope) GetIsConcatSpreadableSymbol() (*Symbol, error)

GetIsConcatSpreadableSymbol returns the well-known Symbol.isConcatSpreadable.

func (*Scope) GetIsolateDataFromSnapshotOnce

func (s *Scope) GetIsolateDataFromSnapshotOnce(index int, want SnapshotDataType) (Value, error)

GetIsolateDataFromSnapshotOnce returns data previously attached with SnapshotCreator.AddIsolateData and consumes the reference: a second request for the same index yields a *SnapshotDataError with DataErrorNoData, as does an out-of-range index. A wrongly typed request yields DataErrorBadType — and still consumes the slot (the engine fetches the raw data before the type check; upstream caveat, mirrored).

func (*Scope) GetIteratorSymbol

func (s *Scope) GetIteratorSymbol() (*Symbol, error)

GetIteratorSymbol returns the well-known Symbol.iterator.

func (*Scope) GetMatchSymbol

func (s *Scope) GetMatchSymbol() (*Symbol, error)

GetMatchSymbol returns the well-known Symbol.match.

func (*Scope) GetReplaceSymbol

func (s *Scope) GetReplaceSymbol() (*Symbol, error)

GetReplaceSymbol returns the well-known Symbol.replace.

func (*Scope) GetSearchSymbol

func (s *Scope) GetSearchSymbol() (*Symbol, error)

GetSearchSymbol returns the well-known Symbol.search.

func (*Scope) GetSplitSymbol

func (s *Scope) GetSplitSymbol() (*Symbol, error)

GetSplitSymbol returns the well-known Symbol.split.

func (*Scope) GetToPrimitiveSymbol

func (s *Scope) GetToPrimitiveSymbol() (*Symbol, error)

GetToPrimitiveSymbol returns the well-known Symbol.toPrimitive.

func (*Scope) GetToStringTagSymbol

func (s *Scope) GetToStringTagSymbol() (*Symbol, error)

GetToStringTagSymbol returns the well-known Symbol.toStringTag.

func (*Scope) GetUnscopablesSymbol

func (s *Scope) GetUnscopablesSymbol() (*Symbol, error)

GetUnscopablesSymbol returns the well-known Symbol.unscopables.

func (*Scope) Int32

func (s *Scope) Int32(v int32) (Value, error)

Int32 returns a JS integer (int32 range) in the scope.

func (*Scope) NewArray

func (s *Scope) NewArray(c *Context, length int32) (*Array, error)

NewArray creates an array of the given length. Negative lengths are forwarded verbatim and collapse to an empty array (the pinned native-API boundary; the JS constructor throws a RangeError instead). The context and scope must belong to the same isolate.

func (*Scope) NewArrayWithElements

func (s *Scope) NewArrayWithElements(c *Context, elements []Value) (*Array, error)

NewArrayWithElements creates an array holding the given elements verbatim. All elements must belong to the scope's isolate.

func (*Scope) NewDate

func (s *Scope) NewDate(c *Context, t float64) (*Date, error)

NewDate creates a Date holding the given time value (milliseconds since the epoch; any double is accepted, including NaN for an invalid date). The context and scope must belong to the same isolate.

func (*Scope) NewDisallowJavascriptExecutionScope

func (s *Scope) NewDisallowJavascriptExecutionScope(onFailure JavascriptExecutionFailure) (*DisallowJavascriptExecutionScope, error)

NewDisallowJavascriptExecutionScope starts a JavaScript execution guard.

func (*Scope) NewError

func (s *Scope) NewError(message string) (Value, error)

NewError builds a JS Error through the isolate's explicitly entered context. It is retained for compatibility with Context.Enter users; new code should prefer Context.NewError, whose context cannot be omitted. The current-context check is safety-critical: the pinned no-context constructor path access-violates rather than returning an empty handle.

func (*Scope) NewEscapableScope

func (s *Scope) NewEscapableScope() (*EscapableScope, error)

NewEscapableScope opens an escapable handle scope under s. Exactly one value can be escaped into s.

func (*Scope) NewExternal

func (s *Scope) NewExternal(payload uintptr) (Value, error)

NewExternal wraps an embedder-provided pointer in a JS External value (v8 External::New with the default pointer tag).

The payload is a plain uintptr and is never interpreted by gov8: it must NOT be a bare Go pointer unless the embedder keeps the object alive for as long as the engine can reach the value (Go's GC is currently non-moving, but this is not a guarantee — prefer HostRef tokens for Go data).

func (*Scope) NewExternalOneByteString

func (s *Scope) NewExternalOneByteString(data []byte) (Value, error)

NewExternalOneByteString creates an external one-byte string owning a copy of data; the engine frees the copy when it finalizes the string.

func (*Scope) NewExternalOneByteStringRaw

func (s *Scope) NewExternalOneByteStringRaw(data []byte, deleter ExternalStringDeleter) (Value, uintptr, error)

NewExternalOneByteStringRaw creates an external one-byte string over a copy of data whose release is observed by deleter. It returns the payload address the engine will report to the deleter (the pinned pointer-identity observation; the address identifies shim-owned memory and must not be dereferenced or freed by Go).

func (*Scope) NewExternalOneByteStringStatic

func (s *Scope) NewExternalOneByteStringStatic(data []byte) (Value, error)

NewExternalOneByteStringStatic creates an external one-byte string over a copy of data that lives for the rest of the process (static semantics). The resource object itself is engine-owned and released after finalization.

func (*Scope) NewExternalTwoByteString

func (s *Scope) NewExternalTwoByteString(units []uint16) (Value, error)

NewExternalTwoByteString is the two-byte counterpart.

func (*Scope) NewExternalTwoByteStringRaw

func (s *Scope) NewExternalTwoByteStringRaw(units []uint16, deleter ExternalStringDeleter) (Value, uintptr, error)

NewExternalTwoByteStringRaw is the two-byte counterpart (length in code units, as reported by the engine and the deleter).

func (*Scope) NewExternalTwoByteStringStatic

func (s *Scope) NewExternalTwoByteStringStatic(units []uint16) (Value, error)

NewExternalTwoByteStringStatic is the two-byte counterpart.

func (*Scope) NewMap

func (s *Scope) NewMap(c *Context) (*Map, error)

NewMap creates an empty Map. The context and scope must belong to the same isolate.

func (*Scope) NewNativeFunction

func (s *Scope) NewNativeFunction(c *Context, fn NativePromiseHandler) (*NativeFunction, error)

NewNativeFunction creates a native function in the context whose invocations dispatch to fn through the integer registry. The function is created in the scope and must be used while that scope is open.

func (*Scope) NewObject

func (s *Scope) NewObject(c *Context) (*Object, error)

NewObject creates a fresh plain JS object (v8::Object::new). The context and scope must belong to the same isolate.

func (*Scope) NewObjectWithPrototypeAndProperties

func (s *Scope) NewObjectWithPrototypeAndProperties(c *Context, prototype Value, names, values []Value) (*Object, error)

NewObjectWithPrototypeAndProperties creates an object with the supplied prototype and own data properties. Each name must be a String or Symbol; every local must be live and belong to this scope's isolate. Properties are writable, enumerable, and configurable, matching v8::Object::with_prototype_and_properties.

Unlike the Rust wrapper's assert_eq!, unequal name/value lengths are reported as an error before entering V8.

func (*Scope) NewPrivate

func (s *Scope) NewPrivate(name Value) (*Private, error)

NewPrivate creates a fresh private symbol. A zero Value name creates an anonymous private; otherwise the name must be a JS string.

func (*Scope) NewPromiseResolver

func (s *Scope) NewPromiseResolver(c *Context) (PromiseResolver, error)

NewPromiseResolver creates a resolver with a fresh pending promise in the context. The scope must belong to the same isolate as the context.

func (*Scope) NewPropertyDescriptor

func (s *Scope) NewPropertyDescriptor() (*PropertyDescriptor, error)

NewPropertyDescriptor creates the default (empty) descriptor.

func (*Scope) NewPropertyDescriptorFromGetSet

func (s *Scope) NewPropertyDescriptorFromGetSet(get, set Value) (*PropertyDescriptor, error)

NewPropertyDescriptorFromGetSet creates an accessor descriptor from the given getter and setter (both must be callable values).

func (*Scope) NewPropertyDescriptorFromValue

func (s *Scope) NewPropertyDescriptorFromValue(value Value) (*PropertyDescriptor, error)

NewPropertyDescriptorFromValue creates a data descriptor with only the value present.

func (*Scope) NewPropertyDescriptorFromValueWritable

func (s *Scope) NewPropertyDescriptorFromValueWritable(value Value, writable bool) (*PropertyDescriptor, error)

NewPropertyDescriptorFromValueWritable creates a data descriptor with the value present and the writable flag specified.

func (*Scope) NewProxy

func (s *Scope) NewProxy(c *Context, target, handler *Object) (*Proxy, error)

NewProxy creates a proxy over target with the given handler.

func (*Scope) NewRegExp

func (s *Scope) NewRegExp(c *Context, pattern Value, flags RegExpFlags, tc *TryCatch) (*RegExp, error)

NewRegExp compiles pattern with the given flags. A syntax error is reported through tc when given (the engine's SyntaxError with the exact "Uncaught " message text) and an error is returned; with tc nil a shim- internal TryCatch observes the failure and only the error is returned. pattern must be a JS string.

func (*Scope) NewSet

func (s *Scope) NewSet(c *Context) (*Set, error)

NewSet creates an empty Set. The context and scope must belong to the same isolate.

func (*Scope) NewString

func (s *Scope) NewString(str string) (Value, error)

NewString creates a JS string from a UTF-8 Go string. Invalid UTF-8 is replaced with U+FFFD by the engine (matching the oracle's lossy conversion path).

func (*Scope) NewStringFromOneByte

func (s *Scope) NewStringFromOneByte(data []byte, t NewStringType) (Value, error)

NewStringFromOneByte creates a string from one-byte (Latin-1) bytes.

func (*Scope) NewStringFromOneByteConst

func (s *Scope) NewStringFromOneByteConst(r *ExternalOneByteConst) (Value, error)

NewStringFromOneByteConst creates an external string over the shared const resource. Safe on any number of isolates (the resource's Dispose is a no-op, so one isolate's finalization cannot destroy another isolate's string data).

func (*Scope) NewStringFromTwoByte

func (s *Scope) NewStringFromTwoByte(units []uint16, t NewStringType) (Value, error)

NewStringFromTwoByte creates a string from UTF-16 code units. The engine counts units against StringMaxLength. Latin-1-representable content collapses to a one-byte representation (observable via IsOneByte).

func (*Scope) NewStringFromUTF8

func (s *Scope) NewStringFromUTF8(data []byte, t NewStringType) (Value, error)

NewStringFromUTF8 creates a string from UTF-8 bytes. Invalid sequences are replaced with U+FFFD by the engine (lossy). Inputs longer than StringMaxLength bytes are rejected by the engine with a recoverable error (no exception is pending).

func (*Scope) NewStringView

func (s *Scope) NewStringView(v Value) (*StringView, error)

NewStringView opens a view onto the string's current contents (flattening it if needed). v must be a string of the receiver's isolate.

func (*Scope) NewSymbol

func (s *Scope) NewSymbol(description Value) (*Symbol, error)

NewSymbol creates a fresh symbol. A zero Value description creates an anonymous symbol; otherwise the description must be a JS string.

func (*Scope) Null

func (s *Scope) Null() (Value, error)

Null returns the JS null value in the scope.

func (*Scope) Number

func (s *Scope) Number(f float64) (Value, error)

Number returns a JS number (float64) in the scope.

func (*Scope) PrivateForApi

func (s *Scope) PrivateForApi(name Value) (*Private, error)

PrivateForApi returns the private symbol registered per isolate for name (Private.for_api — repeated calls with the same name return the same private). name must be a JS string. Although the pinned Rust signature accepts None, that input access-violates in this build; Go rejects a zero Value before FFI.

func (*Scope) SetContinuationPreservedEmbedderData

func (s *Scope) SetContinuationPreservedEmbedderData(value Value) error

SetContinuationPreservedEmbedderData stores isolate-wide continuation data. The value is retained by V8 and remains visible from every context.

func (*Scope) SymbolForApi

func (s *Scope) SymbolForApi(description Value) (*Symbol, error)

SymbolForApi returns the symbol registered in the embedder-only registry for description (a separate registry from Symbol.for). description must be a JS string.

func (*Scope) SymbolForKey

func (s *Scope) SymbolForKey(description Value) (*Symbol, error)

SymbolForKey returns the symbol registered in the global (JS-visible) registry for description — the Symbol.for equivalent. description must be a JS string.

func (*Scope) Uint32

func (s *Scope) Uint32(v uint32) (Value, error)

Uint32 returns a JS unsigned integer (uint32 range) in the scope.

func (*Scope) Undefined

func (s *Scope) Undefined() (Value, error)

Undefined returns the JS undefined value in the scope.

func (*Scope) UnwrapCppGCObject

func (s *Scope) UnwrapCppGCObject(wrapper *Object, tag CppGCTag) (object *CppGCObject, target Value, ok bool, err error)

UnwrapCppGCObject returns the managed allocation and its traced target. ok is false for an unwrapped object, a mismatched tag, or a wrapper managed by another native object family. Go deliberately verifies exact tag and family identity even though the pinned raw unsafe Rust API does not.

func (*Scope) WrapCppGCObject

func (s *Scope) WrapCppGCObject(wrapper *Object, target Value, objectID int32, tag CppGCTag, callbacks CppGCObjectCallbacks) (*CppGCObject, error)

WrapCppGCObject atomically allocates a native cppgc object and attaches it to wrapper. wrapper must be an API wrapper (for example, an object created by invoking a FunctionTemplate-backed constructor). target is retained by a native TracedReference visited from the cppgc object's Trace method.

The allocation and Object::Wrap happen in one shim call: no raw, unrooted cppgc pointer crosses into Go.

type Script

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

Script is a compiled script, rooted as a persistent v8::Global<Script> so it can be run repeatedly (e.g. benchmark workloads) and survives handle scope lifetimes. It is bound to the isolate and context it was compiled for.

func (*Script) Close

func (sc *Script) Close() error

Close releases the persistent script handle.

func (*Script) ID

func (sc *Script) ID() (int32, error)

ID returns the engine's script id. Compiling identical source twice in one isolate resolves through V8's compilation cache to the same id; distinct source yields strictly increasing ids (pinned oracle finding).

func (*Script) Run

func (sc *Script) Run(s *Scope, tc *TryCatch) (Value, error)

Run executes the script in its context. The completion value is a scope-local Value. If tc is non-nil, runtime exceptions are recorded there; otherwise the error alone is returned. The scope (and TryCatch, when given) must belong to the same isolate as the script.

func (*Script) RunUncaught

func (sc *Script) RunUncaught(s *Scope) (Value, error)

RunUncaught runs the script with NO TryCatch active, so an exception escapes to the isolate's message listeners — the pinned oracle's `script.run` shape (the default Run installs an internal fallback TryCatch, which would swallow the message). The completion value is a scope-local Value; a runtime exception returns the error.

func (*Script) Unbound

func (sc *Script) Unbound() (*UnboundScript, error)

Unbound returns the script's context-independent form (Script::GetUnboundScript).

type ScriptCompilerCachedData

type ScriptCompilerCachedData struct {
	Present  bool
	Rejected bool
	Bytes    []byte
}

ScriptCompilerCachedData is a snapshot of the cached-data state retained by a ScriptCompilerSource. Bytes is a copy and remains unchanged when V8 marks the data rejected.

type ScriptCompilerOrigin

type ScriptCompilerOrigin struct {
	ResourceName        Value
	LineOffset          int32
	ColumnOffset        int32
	IsSharedCrossOrigin bool
	ScriptID            int32
	SourceMapURL        *Value
	IsOpaque            bool
	IsWasm              bool
	HostDefinedOptions  *PrimitiveArray
}

ScriptCompilerOrigin is the scope-local origin accepted by ScriptCompilerSource. ResourceName may be any JavaScript Value, including undefined or an object. SourceMapURL is nil for no source-map value and may otherwise point to any Value. HostDefinedOptions is restricted to the exact PrimitiveArray type used by the pinned public API.

type ScriptCompilerSource

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

ScriptCompilerSource owns source text, optional scope-local origin handles, and optional copied cache bytes. It must only be compiled while all Values in Origin are live. The source object itself owns no native allocation.

func NewScriptCompilerSource

func NewScriptCompilerSource(source string, origin *ScriptCompilerOrigin) *ScriptCompilerSource

NewScriptCompilerSource creates a source without cached data.

func NewScriptCompilerSourceWithCachedData

func NewScriptCompilerSourceWithCachedData(source string, origin *ScriptCompilerOrigin, cache []byte) (*ScriptCompilerSource, error)

NewScriptCompilerSourceWithCachedData creates a source with caller-provided cached data. An empty slice is still present cached data, matching CachedData::new(&[]) and its graceful rejection during compilation.

func (*ScriptCompilerSource) CachedData

CachedData returns a copy of the source's current cached-data state.

func (*ScriptCompilerSource) Text

func (s *ScriptCompilerSource) Text() string

Text returns the immutable source text.

type SerializedWasmModuleCache

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

SerializedWasmModuleCache is an immutable serialized CompiledWasmModule together with the exact wire bytes from which it was produced. Keeping both private lets SetCachedCompiledModule reject a wire mismatch before V8's process-fatal deserializer precondition. SerializedBytes returns a copy for persistence or diagnostics; arbitrary bytes deliberately cannot be turned back into this safe-provenance type.

This producer type is an intentional Go extension: rusty_v8 152.2.0 omits the public V8 CompiledWasmModule::Serialize method.

func (*SerializedWasmModuleCache) Len

func (c *SerializedWasmModuleCache) Len() int

Len returns the serialized cache size in bytes.

func (*SerializedWasmModuleCache) SerializedBytes

func (c *SerializedWasmModuleCache) SerializedBytes() []byte

SerializedBytes returns an independent copy suitable for persistence. Use SetCachedCompiledModule with the original typed cache when provenance is available; the raw byte setter retains rusty_v8 compatibility but inherits V8's fatal mismatch/truncation preconditions.

type Set

type Set struct{ Value }

Set is a JS Set object (SameValueZero dedup: NaN deduplicates, +0 and -0 are the same element).

func AsSet

func AsSet(v Value) (*Set, error)

AsSet casts a value to a Set after prevalidating the engine kind.

func (*Set) Add

func (st *Set) Add(s *Scope, c *Context, key Value) (*Set, error)

Add inserts key and returns the collection itself (compare with Same to observe identity).

func (*Set) AsArray

func (st *Set) AsArray(s *Scope, c *Context) (*Array, error)

AsArray renders the set's elements in insertion order.

func (*Set) Clear

func (st *Set) Clear() error

Clear removes every element.

func (*Set) Delete

func (st *Set) Delete(s *Scope, c *Context, key Value) (bool, error)

Delete removes key; ok reports whether it was present.

func (*Set) Has

func (st *Set) Has(s *Scope, c *Context, key Value) (bool, error)

Has reports membership.

func (*Set) Size

func (st *Set) Size() (int64, error)

Size returns the number of elements.

type ShadowRealmContextCallback

type ShadowRealmContextCallback func(*CallbackScope) (*Context, error)

ShadowRealmContextCallback supplies the context for a new ShadowRealm. The returned persistent Context remains owned by the caller and must be closed.

type SharedArrayBuffer

type SharedArrayBuffer struct {
	Value
}

SharedArrayBuffer is a scope-local v8::SharedArrayBuffer.

func AsSharedArrayBuffer

func AsSharedArrayBuffer(v Value) (*SharedArrayBuffer, error)

AsSharedArrayBuffer converts a generic value into a SharedArrayBuffer.

func NewSharedArrayBuffer

func NewSharedArrayBuffer(s *Scope, c *Context, byteLength int) (*SharedArrayBuffer, error)

NewSharedArrayBuffer allocates a new zero-initialized SharedArrayBuffer.

func NewSharedArrayBufferWithBackingStore

func NewSharedArrayBufferWithBackingStore(s *Scope, c *Context, bs *BackingStore) (*SharedArrayBuffer, error)

NewSharedArrayBufferWithBackingStore creates a SharedArrayBuffer aliasing the (shared) store (v8::SharedArrayBuffer::with_backing_store).

func (*SharedArrayBuffer) ByteLength

func (sab *SharedArrayBuffer) ByteLength() (int, error)

ByteLength returns the buffer's length in bytes.

func (*SharedArrayBuffer) GetBackingStore

func (sab *SharedArrayBuffer) GetBackingStore() (*BackingStore, error)

GetBackingStore returns a NEW counted reference to the buffer's backing store; the caller must Close it.

type SharedIsolate

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

SharedIsolate is an isolate usable from multiple threads, one at a time. All engine access goes through Lock; the thread-safe handle keeps working without the lock.

func (*SharedIsolate) Close

func (s *SharedIsolate) Close() error

Close disposes the shared isolate. No lock may be held and no unlock window may be open. The creating goroutine drops its OS thread pin; a Close from another goroutine leaves that pin to expire with the creating goroutine (Go pins threads per goroutine).

func (*SharedIsolate) Isolate

func (s *SharedIsolate) Isolate() *Isolate

Isolate returns the underlying isolate wrapper. Engine operations on it are only legal while a Lock is held.

func (*SharedIsolate) Lock

func (s *SharedIsolate) Lock() (*Locker, error)

Lock acquires the isolate's engine lock and enters the isolate on the calling goroutine's OS thread, blocking while any other thread holds it.

Errors mirror the pinned lock() guards verbatim: locking again from a thread that already holds this isolate's lock ("already locked by this thread") and locking while another isolate is entered on this thread ("while another isolate is entered"). Both fire before any engine state changes, so the isolate remains fully usable after the error.

func (*SharedIsolate) ThreadSafeHandle

func (s *SharedIsolate) ThreadSafeHandle() *ThreadSafeHandle

ThreadSafeHandle returns a handle usable from any thread without holding the lock (termination control and interrupt requests), matching the pinned SharedIsolate::thread_safe_handle.

type ShimError

type ShimError struct {
	Op     string
	Code   int64
	Detail string
}

ShimError is the error type for failures reported by the shim layer. Code is the negative status code from internal/shim/shim.cc.

func (*ShimError) Error

func (e *ShimError) Error() string

type SideEffectType

type SideEffectType uint8

SideEffectType mirrors v8::SideEffectType. It is debugger metadata used by inspector evaluations that request throwOnSideEffect; it does not suppress callbacks during ordinary execution.

const (
	SideEffectHasSideEffect SideEffectType = iota
	SideEffectHasNoSideEffect
	SideEffectHasSideEffectToReceiver
)

type Signature

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

Signature restricts which receivers a templated function accepts (v8 Signature::New). It is a scope-local template-side value like the templates it is built from.

func (*Signature) Data

func (sig *Signature) Data() (Data, error)

Data returns sig as its Data supertype without changing its local lifetime.

type SnapshotCreateParams

type SnapshotCreateParams struct {
	*CreateParams
	// contains filtered or unexported fields
}

SnapshotCreateParams composes the existing safe CreateParams surface with an owned reference to a StartupData blob. It is the Go counterpart of a rusty_v8 CreateParams after snapshot_blob has been selected.

The wrapper is single-use: NewIsolateWithSnapshotParams consumes it before validating and entering the native constructor, so every returned error after that call still consumes the wrapper. StartupData itself remains caller-owned and reusable; the shim copies its bytes into isolate-lifetime native storage.

The embedded CreateParams preserves its existing fluent API, but its direct setters are not synchronized and are not frozen after Consumed reports true. Configure a SnapshotCreateParams from one goroutine before handing it to the constructor; do not mutate it concurrently with construction. Post-consume getter changes do not permit a second isolate creation.

func NewSnapshotCreateParams

func NewSnapshotCreateParams(snapshot *StartupData) (*SnapshotCreateParams, error)

NewSnapshotCreateParams returns default CreateParams carrying snapshot. Empty, truncated, or version-incompatible blobs are rejected before V8's fatal snapshot-version boundary.

func (*SnapshotCreateParams) ConfigureHeapLimits

func (p *SnapshotCreateParams) ConfigureHeapLimits(initial, maximum uint64) error

ConfigureHeapLimits derives V8 constraints from initial and maximum heap sizes. Unlike the pinned builder's fatal inverted pair, Go rejects initial>maximum before entering V8. Direct individual constraint setters remain available through the embedded CreateParams and intentionally retain their permissive round-trip behavior.

func (*SnapshotCreateParams) Consumed

func (p *SnapshotCreateParams) Consumed() bool

Consumed reports whether NewIsolateWithSnapshotParams has consumed p.

func (*SnapshotCreateParams) SetSnapshotBlob

func (p *SnapshotCreateParams) SetSnapshotBlob(snapshot *StartupData) error

SetSnapshotBlob replaces the currently selected blob, matching repeated rusty_v8 snapshot_blob builder calls. The previous blob remains owned by its caller and may be reused independently.

type SnapshotCreator

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

SnapshotCreator wraps a creator isolate (v8::SnapshotCreator). The engine isolate is owned by the C++ SnapshotCreator: CreateBlob consumes it — exactly like the pinned OwnedIsolate::create_blob — and Close releases it without producing a blob (Go resolves the pinned crate's drop-without-create_blob panic into an explicit, safe operation; see Close). All methods must run on the creator's owning thread.

func NewSnapshotCreator

func NewSnapshotCreator() (*SnapshotCreator, error)

NewSnapshotCreator creates a fresh creator isolate.

func NewSnapshotCreatorFromExistingSnapshot

func NewSnapshotCreatorFromExistingSnapshot(blob *StartupData) (*SnapshotCreator, error)

NewSnapshotCreatorFromExistingSnapshot creates a creator isolate seeded from an existing startup blob (snapshot-of-snapshot chains). The blob is validated before any engine call.

func NewSnapshotCreatorFromExistingSnapshotWithExternalReferences

func NewSnapshotCreatorFromExistingSnapshotWithExternalReferences(blob *StartupData, references []ExternalReference) (*SnapshotCreator, error)

NewSnapshotCreatorFromExistingSnapshotWithExternalReferences is the existing-snapshot counterpart of NewSnapshotCreatorWithExternalReferences.

func NewSnapshotCreatorWithExternalReferences

func NewSnapshotCreatorWithExternalReferences(references []ExternalReference) (*SnapshotCreator, error)

NewSnapshotCreatorWithExternalReferences creates a snapshot creator with a copied, null-terminated external-reference table. The table stays native and live until CreateBlob or Close consumes the creator.

func (*SnapshotCreator) AddContext

func (sc *SnapshotCreator) AddContext(c *Context) (int, error)

AddContext adds an additional context (with its global proxy) to the snapshot and returns its index. Indices are assigned in insertion order starting at 0.

func (*SnapshotCreator) AddContextData

func (sc *SnapshotCreator) AddContextData(c *Context, v Value) (int, error)

AddContextData attaches a scope-local value to a context's snapshot and returns its index.

func (*SnapshotCreator) AddIsolateData

func (sc *SnapshotCreator) AddIsolateData(v Value) (int, error)

AddIsolateData attaches a scope-local value (Integer, String, ...) to the isolate snapshot and returns its index. The value's scope must be open.

func (*SnapshotCreator) Close

func (sc *SnapshotCreator) Close() error

Close releases the creator isolate without producing a blob. In the pinned crate dropping a creator without create_blob panics; Go has no destructors, so abandonment is this explicit, safe operation, and the negative tests document the deviation. After Close (or CreateBlob) the creator and its isolate are dead: further use returns errors.

func (*SnapshotCreator) CreateBlob

func (sc *SnapshotCreator) CreateBlob(policy FunctionCodeHandling) (*StartupData, error)

CreateBlob serializes the creator into a startup data blob and consumes the creator isolate (like the pinned OwnedIsolate::create_blob, which takes the isolate by value): the creator cannot be used afterwards. It must not run inside a handle scope. An engine failure still consumes the creator and is reported as an error (the pinned crate returns None here and panics only later, on drop without a blob).

func (*SnapshotCreator) Isolate

func (sc *SnapshotCreator) Isolate() *Isolate

Isolate returns the creator's isolate. It is usable like any isolate on the owning thread until CreateBlob or Close consumes it.

func (*SnapshotCreator) SetDefaultContext

func (sc *SnapshotCreator) SetDefaultContext(c *Context) error

SetDefaultContext sets the default context included in the snapshot. It must be called at most once per creator (engine CHECK).

type SnapshotDataError

type SnapshotDataError struct {
	Kind DataErrorKind
}

SnapshotDataError is the error outcome of exactly-once snapshot-data retrieval.

func (*SnapshotDataError) Error

func (e *SnapshotDataError) Error() string

type SnapshotDataType

type SnapshotDataType uint8

SnapshotDataType selects the downcast applied to data retrieved from a snapshot. It carries the same observable information as the pinned crate's type parameter: which engine predicate decides Ok versus BadType.

const (
	// SnapshotDataValue accepts any value-typed data (v8::Value).
	SnapshotDataValue SnapshotDataType = 0
	// SnapshotDataString accepts string values (v8::String).
	SnapshotDataString SnapshotDataType = 1
	// SnapshotDataPrivate accepts private symbols (v8::Private).
	SnapshotDataPrivate SnapshotDataType = 2
)

type StackFrame

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

StackFrame is one frame of a StackTrace (scope-local handle).

func (*StackFrame) Column

func (f *StackFrame) Column() (int64, error)

Column returns the frame's 1-based column.

func (*StackFrame) FunctionName

func (f *StackFrame) FunctionName() (string, bool, error)

FunctionName returns the called function's name; ok=false when anonymous.

func (*StackFrame) FunctionNameValue

func (f *StackFrame) FunctionNameValue() (Value, bool, error)

FunctionNameValue returns the function name as a scope-local JavaScript String. ok=false means the frame has no function name.

func (*StackFrame) IsConstructor

func (f *StackFrame) IsConstructor() (bool, error)

IsConstructor reports whether the frame is a construct call.

func (*StackFrame) IsEval

func (f *StackFrame) IsEval() (bool, error)

IsEval reports whether the frame came from an eval call.

func (*StackFrame) IsUserJavaScript

func (f *StackFrame) IsUserJavaScript() (bool, error)

IsUserJavaScript reports whether the frame is user JavaScript.

func (*StackFrame) IsWasm

func (f *StackFrame) IsWasm() (bool, error)

IsWasm reports whether the frame is a Wasm frame.

func (*StackFrame) LineNumber

func (f *StackFrame) LineNumber() (int64, error)

LineNumber returns the frame's 1-based line.

func (*StackFrame) ScriptID

func (f *StackFrame) ScriptID() (int64, error)

ScriptID returns the frame's script id (positive for normal scripts).

func (*StackFrame) ScriptName

func (f *StackFrame) ScriptName() (string, bool, error)

ScriptName returns the frame's script name; ok=false when absent.

func (*StackFrame) ScriptNameOrSourceURL

func (f *StackFrame) ScriptNameOrSourceURL() (string, bool, error)

ScriptNameOrSourceURL returns the frame's script resource name, or its sourceURL directive when V8 provides that fallback. ok is false when absent.

func (*StackFrame) ScriptNameOrSourceURLValue

func (f *StackFrame) ScriptNameOrSourceURLValue() (Value, bool, error)

ScriptNameOrSourceURLValue returns the script name or sourceURL fallback as a scope-local JavaScript String.

func (*StackFrame) ScriptNameValue

func (f *StackFrame) ScriptNameValue() (Value, bool, error)

ScriptNameValue returns the script name as a scope-local JavaScript String.

func (*StackFrame) ScriptSource

func (f *StackFrame) ScriptSource() (string, bool, error)

ScriptSource returns the frame's complete script source. ok is false when V8 does not expose source for the frame.

func (*StackFrame) ScriptSourceValue

func (f *StackFrame) ScriptSourceValue() (Value, bool, error)

ScriptSourceValue returns the complete script source as a scope-local JavaScript String.

func (*StackFrame) SourceMappingURL

func (f *StackFrame) SourceMappingURL() (string, bool, error)

SourceMappingURL returns the frame script's source-map URL. ok is false when no sourceMappingURL is present.

func (*StackFrame) SourceMappingURLValue

func (f *StackFrame) SourceMappingURLValue() (Value, bool, error)

SourceMappingURLValue returns the source-map URL as a scope-local JavaScript String.

type StackTrace

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

StackTrace is a captured JS stack trace (scope-local handle).

func ExceptionStackTrace

func ExceptionStackTrace(s *Scope, exc Value) (*StackTrace, bool, error)

ExceptionStackTrace returns the stack trace attached to an exception value; ok=false when it carries none (natively created errors never do in this build -- the pinned gap).

func (*StackTrace) Frame

func (st *StackTrace) Frame(i int) (*StackFrame, error)

Frame returns the frame at index i (topmost first). Both bounds are checked before the frame-getter FFI. This intentionally differs from rusty_v8 152.2.0: get_frame(FrameCount) reports Some, but dereferencing that handle reproducibly access-violates, so safe Go code must never receive it.

func (*StackTrace) FrameCount

func (st *StackTrace) FrameCount() (int, error)

FrameCount returns the number of frames in the trace.

type StalledTopLevelAwait

type StalledTopLevelAwait struct {
	Module  *Module
	Message *Message
}

StalledTopLevelAwait pairs the unresolved module with V8's diagnostic. Message is local to the Scope passed to StalledTopLevelAwaitMessages.

type StartupData

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

StartupData holds a snapshot blob. Blobs produced by CreateBlob carry a Go-owned copy of the engine bytes. Blobs used for isolate creation keep engine-owned copies alive until Release: the engine reads the original blob bytes on every Context::New of a snapshot-backed isolate, so the copies must outlive every isolate created from the blob.

func StartupDataFromBytes

func StartupDataFromBytes(b []byte) *StartupData

StartupDataFromBytes wraps raw snapshot bytes (the analog of the pinned crate's StartupData::from(Vec<u8>), e.g. a blob loaded from a file). The bytes are used as-is; validity is checked at use. Because a raw blob does not reveal whether it contains external references, consume it through NewIsolateFromSnapshotWithParams with an explicit table; the table may be empty for a blob known by the caller not to contain external references.

func (*StartupData) Bytes

func (s *StartupData) Bytes() []byte

Bytes returns the blob contents. The caller must not mutate the result.

func (*StartupData) CanBeRehashed

func (s *StartupData) CanBeRehashed() bool

CanBeRehashed reports whether V8 can rehash the startup blob when loading it. The pinned crate documents this query for blobs returned by SnapshotCreator.CreateBlob. Invalid and truncated embedder-provided data is answered locally as false because passing it to V8 can trip a fatal CHECK.

func (*StartupData) Clone

func (s *StartupData) Clone() (*StartupData, error)

Clone returns an independent Go-owned copy of the startup bytes and their known external-reference requirement. It mirrors StartupData::clone in the pinned crate: releasing the original does not affect consumers of the copy. A released StartupData cannot be cloned because Release marks the Go owner as retired even though its diagnostic Bytes view remains available.

func (*StartupData) IsEmpty

func (s *StartupData) IsEmpty() bool

IsEmpty reports whether the blob carries no bytes.

func (*StartupData) IsValid

func (s *StartupData) IsValid() bool

IsValid reports whether the blob carries a version header matching this engine. Unlike the pinned crate, data shorter than the snapshot version header is answered locally (false) instead of tripping a fatal V8 CHECK.

func (*StartupData) Release

func (s *StartupData) Release() error

Release frees the engine-owned copies of the blob. It fails while any isolate created from the blob is still open: the engine reads the blob bytes for context creation until the isolate is disposed. Releasing only after the isolates are closed makes the failure mode of forgetting this call a bounded memory leak, never a use-after-free. It is safe to call twice (and on Go-only blobs produced by CreateBlob, which hold no engine memory).

type StringEncoding

type StringEncoding int32

StringEncoding mirrors the C++ v8::String::Encoding values reported by GetExternalStringResourceBase.

const (
	StringEncodingTwoByte StringEncoding = 0x0
	StringEncodingUnknown StringEncoding = 0x1
	StringEncodingOneByte StringEncoding = 0x8
)

type StringView

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

StringView is a direct view onto a string's contents (v8::String:: ValueView). The view does not copy: it is only valid while no GC or allocation can move the viewed string, which means (a) all engine work waits until Close and (b) the view is closed before the scope that created it. Reading the contents goes through Copy, which the shim performs under the view's own no-GC scope in a single call, so no raw engine pointer ever reaches Go. Close is the only release mechanism (deterministic, like every resource in this module).

func (*StringView) Bytes

func (sv *StringView) Bytes() (data []byte, oneByte bool, err error)

Bytes returns the view's raw contents (see Copy for the encoding) and the encoding flag, allocating an exact-size buffer.

func (*StringView) Close

func (sv *StringView) Close() error

Close releases the view. It must be called before the creating scope closes and before any further engine work on the isolate.

func (*StringView) Copy

func (sv *StringView) Copy(buf []byte) (int, error)

Copy copies the view's raw contents into buf: bytes for one-byte content, little-endian UTF-16 code units for two-byte content. It returns the number of bytes copied. The copy happens inside one shim call under the view's no-GC scope.

func (*StringView) Info

func (sv *StringView) Info() (oneByte bool, length int, err error)

Info reports the view's encoding and length (in code units for two-byte content, bytes for one-byte content).

type Symbol

type Symbol struct{ Value }

Symbol is a JS symbol primitive.

func AsSymbol

func AsSymbol(v Value) (*Symbol, error)

AsSymbol casts a value to a Symbol after prevalidating the engine kind.

func (*Symbol) Description

func (sym *Symbol) Description(s *Scope) (Value, error)

Description returns the symbol description (the undefined value for an anonymous symbol).

type SyntheticModuleEvaluation

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

SyntheticModuleEvaluation is valid only for the duration of its callback. Values created through Scope are callback-local and must not escape it.

func (*SyntheticModuleEvaluation) Module

func (e *SyntheticModuleEvaluation) Module() *Module

Module returns the synthetic module being evaluated.

func (*SyntheticModuleEvaluation) NewTypeError

func (e *SyntheticModuleEvaluation) NewTypeError(message string) (Value, error)

NewTypeError constructs a callback-local TypeError.

func (*SyntheticModuleEvaluation) Scope

Scope returns the callback-local construction and conversion scope.

func (*SyntheticModuleEvaluation) SetExport

func (e *SyntheticModuleEvaluation) SetExport(name string, value Value) error

SetExport updates one of the names declared when the module was created.

func (*SyntheticModuleEvaluation) Throw

func (e *SyntheticModuleEvaluation) Throw(exception Value) error

Throw schedules exception as the evaluation failure. The callback should then return; the dispatcher converts the result to an empty MaybeLocal.

type SyntheticModuleEvaluationCallback

type SyntheticModuleEvaluationCallback func(*SyntheticModuleEvaluation) (Value, error)

SyntheticModuleEvaluationCallback runs once when a synthetic module is evaluated. Returning a Promise preserves V8's asynchronous evaluation semantics; the first EvaluateValue returns any other value directly. Later evaluation returns V8's fulfilled top-level Promise with undefined. A zero Value is normalized to undefined; unlike rusty_v8's empty MaybeLocal callback result, it cannot trigger V8's fatal missing-exception check. Returning an error throws into V8.

type Task

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

Task is a transferred V8 foreground task. Run and Close are one-shot and mutually exclusive. Close may run on any thread; Run requires the owning live Isolate and therefore cannot accidentally execute on a worker thread.

func (*Task) Close

func (task *Task) Close() error

Close destroys a task without executing it and may be called from any thread. It returns an error after Run or another Close.

func (*Task) Run

func (task *Task) Run(isolate *Isolate) error

Run executes and destroys the task. isolate must be the exact live isolate named by the posting callback and Run must occur on its owning thread.

type ThreadSafeHandle

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

ThreadSafeHandle is a thread-safe reference to an isolate. Its main use is to terminate execution of a running isolate from another thread. It is created with Isolate.ThreadSafeHandle and remains safe to call after the isolate was closed (answering false, like the pinned IsolateHandle).

func (*ThreadSafeHandle) CancelTerminateExecution

func (h *ThreadSafeHandle) CancelTerminateExecution() bool

CancelTerminateExecution resumes execution capability after a previous TerminateExecution once the termination exception has unwound to the embedder. Returns false if the isolate was already closed.

func (*ThreadSafeHandle) IsExecutionTerminating

func (h *ThreadSafeHandle) IsExecutionTerminating() bool

IsExecutionTerminating reports whether JS execution is currently terminating because of TerminateExecution (the termination exception is still unwinding). Exposed on the handle for parity with the pinned IsolateHandle; the engine state it reads belongs to the isolate thread. Returns false if the isolate was already closed.

func (*ThreadSafeHandle) RequestInterrupt

func (h *ThreadSafeHandle) RequestInterrupt(cb InterruptCallback, data uintptr) bool

RequestInterrupt schedules cb to run once on the isolate's thread during its next JS execution, with data handed back verbatim. Returns false if the isolate was already closed (the callback never runs then). Safe to call from any goroutine (the engine posts the request).

func (*ThreadSafeHandle) TerminateExecution

func (h *ThreadSafeHandle) TerminateExecution() bool

TerminateExecution forcefully terminates JS execution in the isolate. It may be called from any goroutine. The request only takes effect at the target's next interrupt check. Returns false if the isolate was already closed.

type TimeZoneDetection

type TimeZoneDetection uint32

TimeZoneDetection mirrors v8::Isolate::TimeZoneDetection.

const (
	// TZSkip does not redetect the host time zone.
	TZSkip TimeZoneDetection = 0
	// TZRedetect redetects the host time zone and uses it as the default.
	TZRedetect TimeZoneDetection = 1
)

type TracedReference

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

TracedReference is V8's embedder-traced handle. It is not a strong root. V8 expects it to be embedded in an externally traced C++/cppgc owner; gov8 does not currently expose that owner integration. Consequently Get is only safe while the caller independently knows the target is live (for example, while a Local or Eternal roots it). Never rely on a TracedReference alone to keep a JavaScript object alive across garbage collection.

func EmptyTracedReference

func EmptyTracedReference() (*TracedReference, error)

EmptyTracedReference constructs an empty TracedReference.

func NewTracedReference

func NewTracedReference(s *Scope, v Value) (*TracedReference, error)

NewTracedReference constructs a TracedReference containing v.

func (*TracedReference) Close

func (r *TracedReference) Close() error

Close destroys the host wrapper. Like the pinned TracedReference Drop, it intentionally does not Reset and remains safe after isolate disposal.

func (*TracedReference) Get

func (r *TracedReference) Get(s *Scope) (value Value, ok bool, err error)

Get reopens the reference as a local in s. ok is false while empty. This method cannot prove traced reachability; see TracedReference's type comment.

func (*TracedReference) Reset

func (r *TracedReference) Reset(s *Scope, value *Value) error

Reset always clears the old reference, then stores value when non-nil. Passing nil corresponds to rusty_v8 reset(scope, None). The reference stays bound to its first isolate even after reset-to-empty, so cross-isolate Get fails deterministically before the engine boundary.

type TryCatch

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

TryCatch observes exceptions thrown inside compile/run calls that are passed the TryCatch. It mirrors the observable surface the oracle characterizes: HasCaught, CanContinue, Reset, message text (with the engine's "Uncaught " prefix), exception ToString text, exception kind, and message position information (0-based character offset and column, 1-based line).

A TryCatch registers itself with the isolate for its whole lifetime (between NewTryCatch and Close) and must be closed on the owning thread, nested consistently with the isolate's other engine work.

func (*TryCatch) CanContinue

func (t *TryCatch) CanContinue() (bool, error)

CanContinue reports whether execution can continue after the exception.

func (*TryCatch) Close

func (t *TryCatch) Close() error

Close unregisters and releases the TryCatch.

func (*TryCatch) Exception

func (t *TryCatch) Exception(s *Scope) (Value, bool, error)

Exception returns the caught exception as a scope-local value. ok is false when the TryCatch is empty. The explicit Scope is the Go representation of rusty_v8's parent-scope lifetime: the returned value remains valid after the TryCatch closes, but not after s closes.

func (*TryCatch) ExceptionIsString

func (t *TryCatch) ExceptionIsString() (bool, error)

ExceptionIsString reports whether the caught exception is a JS string.

func (*TryCatch) ExceptionText

func (t *TryCatch) ExceptionText(s *Scope, c *Context) (string, error)

ExceptionText returns the ECMAScript ToString of the caught exception (no "Uncaught " prefix). Empty when nothing was caught.

func (*TryCatch) HasCaught

func (t *TryCatch) HasCaught() (bool, error)

HasCaught reports whether an exception was caught.

func (*TryCatch) HasTerminated

func (t *TryCatch) HasTerminated() (bool, error)

HasTerminated reports whether the TryCatch terminated because execution was forcefully terminated (the durable post-abort observable of a termination that unwound through the TryCatch).

func (*TryCatch) IsVerbose

func (t *TryCatch) IsVerbose() (bool, error)

IsVerbose reports whether caught exceptions are also reported to the isolate's message listeners.

func (*TryCatch) LineNumber

func (t *TryCatch) LineNumber(s *Scope, c *Context) (line int32, ok bool, err error)

LineNumber returns the 1-based line of the message; ok is false when absent. The scope and context must belong to the same isolate as the TryCatch.

func (*TryCatch) Message

func (t *TryCatch) Message(s *Scope) (*Message, bool, error)

Message returns the caught exception's message, ok=false when the TryCatch holds nothing. The message is a scope-local handle: it must be read while the scope is open.

func (*TryCatch) MessageText

func (t *TryCatch) MessageText(s *Scope, c *Context) (string, error)

MessageText returns v8 Message::Get() text (carries the "Uncaught " prefix for TryCatch-caught exceptions in this build). Empty when nothing was caught.

func (*TryCatch) ReThrow

func (t *TryCatch) ReThrow(s *Scope) (Value, bool, error)

ReThrow rethrows the caught exception and immediately closes the innermost TryCatch before returning. The returned local is V8's observable undefined result; the original exception has already propagated to the next outer TryCatch. This is the safe counterpart to legacy Rethrow, whose caller had to manually leave and close the catcher immediately.

func (*TryCatch) Reset

func (t *TryCatch) Reset() error

Reset clears the caught exception; subsequent HasCaught reports false and later scripts run normally.

func (*TryCatch) Rethrow

func (t *TryCatch) Rethrow(s *Scope) (Value, bool, error)

Rethrow schedules the caught exception for the next outer handler and returns V8's scope-local ReThrow result. In the pinned build that result is undefined, while the original exception propagates to the outer TryCatch. The caller must leave engine execution immediately after this call.

func (*TryCatch) SetCaptureMessage

func (t *TryCatch) SetCaptureMessage(value bool) error

SetCaptureMessage controls whether subsequently caught exceptions capture a Message. It is true by default. Disabling it does not suppress Exception.

func (*TryCatch) SetVerbose

func (t *TryCatch) SetVerbose(value bool) error

SetVerbose controls whether caught exceptions are also reported to the isolate's message listeners. It is false by default.

func (*TryCatch) StackTrace

func (t *TryCatch) StackTrace(s *Scope, c *Context) (Value, bool, error)

StackTrace returns the caught exception's .stack property as a scope-local value. ok is false when nothing was caught or no stack property is present. This is TryCatch::StackTrace, distinct from Message.StackTrace (which is a structured StackTrace captured only when isolate-level capture is enabled).

func (*TryCatch) StartColumn

func (t *TryCatch) StartColumn(s *Scope) (int64, error)

StartColumn returns the 0-based column of the message (0 when absent). The scope must belong to the same isolate as the TryCatch.

func (*TryCatch) StartPosition

func (t *TryCatch) StartPosition(s *Scope) (int64, error)

StartPosition returns the 0-based character offset of the message in the source (0 when no message is present). The scope must belong to the same isolate as the TryCatch.

type TypedArray

type TypedArray struct {
	Value
}

TypedArray is a scope-local typed array (v8::TypedArray surface).

func AsTypedArray

func AsTypedArray(v Value) (*TypedArray, error)

AsTypedArray converts a generic value into a typed-array view of it.

func NewBigInt64Array

func NewBigInt64Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewBigInt64Array creates a BigInt64Array over ab. byteOffset must be a multiple of 8 and byteOffset+8*length must not exceed the buffer.

func NewBigUint64Array

func NewBigUint64Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewBigUint64Array creates a BigUint64Array over ab. byteOffset must be a multiple of 8 (v8::BigUint64Array::new).

func NewFloat16Array

func NewFloat16Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewFloat16Array creates a Float16Array over ab (IEEE binary16 elements). byteOffset must be a multiple of 2 (v8::Float16Array::new; the pinned build ships js_float16array on).

func NewFloat32Array

func NewFloat32Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewFloat32Array creates a Float32Array over ab. byteOffset must be a multiple of 4 (v8::Float32Array::new).

func NewFloat64Array

func NewFloat64Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewFloat64Array creates a Float64Array over ab. byteOffset must be a multiple of 8 and byteOffset+8*length must not exceed the buffer.

func NewInt8Array

func NewInt8Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewInt8Array creates an Int8Array over ab (v8::Int8Array::new).

func NewInt16Array

func NewInt16Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewInt16Array creates an Int16Array over ab. byteOffset must be a multiple of 2 (v8::Int16Array::new).

func NewInt32Array

func NewInt32Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewInt32Array creates an Int32Array over ab. byteOffset must be a multiple of 4 (v8::Int32Array::new).

func NewTypedArrayOfKind

func NewTypedArrayOfKind(s *Scope, c *Context, ab *ArrayBuffer, kind TypedArrayKind, byteOffset, length int) (*TypedArray, error)

NewTypedArrayOfKind creates a typed array of the given kind over ab's bytes [byteOffset, byteOffset+length*elementSize) (X::new for every one of the 12 kinds). length counts elements. Geometry that the engine would answer with a process-fatal V8 CHECK/ApiCheck is prevalidated and returned as an error, in the engine's fatal order:

  1. length > kind max length ("...length exceeds max allowed value")
  2. byteOffset not a multiple of the element size ("...not aligned...")
  3. byteOffset/length out of the buffer ("...out of bounds")

func NewUint8Array

func NewUint8Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewUint8Array creates a Uint8Array over ab's bytes [byteOffset, byteOffset+length) (v8::Uint8Array::new). length counts elements.

func NewUint8ClampedArray

func NewUint8ClampedArray(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewUint8ClampedArray creates a Uint8ClampedArray over ab (v8::Uint8ClampedArray::new).

func NewUint16Array

func NewUint16Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewUint16Array creates a Uint16Array over ab. byteOffset must be a multiple of 2 (v8::Uint16Array::new).

func NewUint32Array

func NewUint32Array(s *Scope, c *Context, ab *ArrayBuffer, byteOffset, length int) (*TypedArray, error)

NewUint32Array creates a Uint32Array over ab. byteOffset must be a multiple of 4 (v8::Uint32Array::new).

func (*TypedArray) Buffer

func (ta *TypedArray) Buffer() (*ArrayBuffer, error)

Buffer returns the typed array's underlying ArrayBuffer.

func (*TypedArray) ByteLength

func (ta *TypedArray) ByteLength() (int, error)

ByteLength returns the view's size in bytes.

func (*TypedArray) ByteOffset

func (ta *TypedArray) ByteOffset() (int, error)

ByteOffset returns the view's offset into its buffer.

func (*TypedArray) CopyContents

func (ta *TypedArray) CopyContents(dst []byte) (int, error)

copyContents copies at most len(dst) bytes of the view's contents into dst (ArrayBufferView::CopyContents) and returns the number of bytes written.

func (*TypedArray) Data

func (ta *TypedArray) Data() (uintptr, bool, error)

Data returns the view's engine-side data pointer (crate data(): buffer data + byte offset). The second result reports whether the pointer is non-null (it is null for detached views). OBSERVATION ONLY: the pointer is valid only while the view is alive, must never be dereferenced or retained by Go, and becomes invalid when the scope closes.

func (*TypedArray) GetBackingStore

func (ta *TypedArray) GetBackingStore() (*BackingStore, error)

GetBackingStore returns a NEW counted reference to the view buffer's backing store (crate get_backing_store). The caller must Close it. Works for SharedArrayBuffer-backed views as well (IsShared reports true there).

func (*TypedArray) GetContents

func (ta *TypedArray) GetContents(storage []byte) (ViewContents, error)

GetContents copies up to len(storage) bytes of the view's live contents into storage and describes the full span (ArrayBufferView::GetContents). The reported Length is independent of len(storage): for this build the contents are always off-heap and the engine ignores the storage size. The bytes in storage reflect the live backing store at call time — re-read after JS writes to observe the writes.

func (*TypedArray) HasBuffer

func (ta *TypedArray) HasBuffer() (bool, error)

HasBuffer reports whether the typed array's backing buffer is allocated.

func (*TypedArray) Length

func (ta *TypedArray) Length() (int, error)

Length returns the element count of the typed array.

type TypedArrayKind

type TypedArrayKind = viewKind

TypedArrayKind identifies a typed-array element type at the shim boundary (the same wire values as the viewKind constants of buffer.go, which this alias keeps in lockstep with).

const (
	KindUint8        TypedArrayKind = viewUint8
	KindInt8         TypedArrayKind = viewInt8
	KindUint16       TypedArrayKind = viewUint16
	KindInt16        TypedArrayKind = viewInt16
	KindUint32       TypedArrayKind = viewUint32
	KindInt32        TypedArrayKind = viewInt32
	KindFloat16      TypedArrayKind = viewFloat16
	KindFloat32      TypedArrayKind = viewFloat32
	KindFloat64      TypedArrayKind = viewFloat64
	KindBigInt64     TypedArrayKind = viewBigInt64
	KindBigUint64    TypedArrayKind = viewBigUint64
	KindUint8Clamped TypedArrayKind = viewUint8Clamped
)

The 12 typed-array kinds (v8::Int8Array ... v8::BigUint64Array).

func (TypedArrayKind) ElementSize

func (k TypedArrayKind) ElementSize() int

ElementSize returns the kind's element size in bytes (0 for an invalid kind). These are the engine's sizeof(element) values; the shim enforces the same alignment classes before entering V8.

func (TypedArrayKind) IsTypedArrayOfKind

func (k TypedArrayKind) IsTypedArrayOfKind(v Value) (bool, error)

IsTypedArrayOfKind reports whether the value is a typed array of exactly kind k (the per-kind predicates routed through the kind table).

func (TypedArrayKind) IsValid

func (k TypedArrayKind) IsValid() bool

IsValid reports whether k is one of the 12 kinds.

func (TypedArrayKind) String

func (k TypedArrayKind) String() string

String returns the kind's JS constructor name (or "TypedArray(<n>)" for an invalid kind).

type TypedArrayKindLimits

type TypedArrayKindLimits struct {
	// MaxLengths maps each kind to its maximum element count
	// (TypedArray::kMaxByteLength / element size, truncated).
	MaxLengths map[TypedArrayKind]int64
	// MaxByteLength is the largest supported typed-array byte size
	// (2^53-1 for this build).
	MaxByteLength int64
	// MaxSizeInHeap is the pinned artifact's on-heap typed-array size
	// threshold (0: this build never stores typed arrays on the JS heap).
	MaxSizeInHeap int64
}

TypedArrayKindLimits carries the pinned build's typed-array size limits for every kind (X::MAX_LENGTH in the crate).

func TypedArrayKindLimitsQuery

func TypedArrayKindLimitsQuery() (TypedArrayKindLimits, error)

TypedArrayKindLimitsQuery reads the pinned build's limits for all 12 kinds from the engine shim (v8-typed-array.h kMaxLength constants, TypedArray::kMaxByteLength and the GN-arg-pinned heap threshold).

type TypedArrayLimits

type TypedArrayLimits struct {
	// MaxByteLength is the largest supported typed-array byte size
	// (2^53-1 for this build).
	MaxByteLength int64
	// Uint8MaxLength / Float64MaxLength / BigInt64MaxLength are the
	// per-type maximum element counts accepted by the constructors.
	Uint8MaxLength    int64
	Float64MaxLength  int64
	BigInt64MaxLength int64
	// MaxSizeInHeap is the pinned artifact's on-heap typed-array size
	// threshold (0: this build never stores typed arrays on the JS heap).
	MaxSizeInHeap int64
}

TypedArrayLimits carries the pinned build's typed-array size limits.

func TypedArrayLimitsQuery

func TypedArrayLimitsQuery() (TypedArrayLimits, error)

TypedArrayLimits reads the pinned build's limits from the engine shim (v8::TypedArray::kMaxByteLength and the per-type kMaxLength constants of the pinned headers).

type UnboundModuleScript

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

UnboundModuleScript is the context-independent compiled script underlying a SourceTextModule. It is isolate- and thread-affine, but remains valid after the producing Module and its Context are closed.

func (*UnboundModuleScript) Close

func (u *UnboundModuleScript) Close() error

Close releases the persistent unbound-script root.

func (*UnboundModuleScript) CreateCodeCache

func (u *UnboundModuleScript) CreateCodeCache() (*ModuleCodeCache, error)

CreateCodeCache serializes the compiled unbound module. The provenance guard runs before the V8 API, and the returned cache is a process-independent copy.

func (*UnboundModuleScript) ScriptID

func (u *UnboundModuleScript) ScriptID() (int32, error)

ScriptID returns V8's unique script identifier.

func (*UnboundModuleScript) SourceMappingURL

func (u *UnboundModuleScript) SourceMappingURL(s *Scope) (Value, error)

SourceMappingURL returns the value read from the sourceMappingURL comment.

func (*UnboundModuleScript) SourceURL

func (u *UnboundModuleScript) SourceURL(s *Scope) (Value, error)

SourceURL returns the value read from the sourceURL magic comment.

type UnboundScript

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

UnboundScript is the context-independent form of a compiled script (rooted in a persistent handle). It can be re-bound into any context of its isolate.

func (*UnboundScript) Bind

func (u *UnboundScript) Bind(s *Scope) (BoundScript, error)

Bind binds the unbound script into the context entered via Context.Enter (upstream the entered-context precondition is enforced by the type system; here it is a runtime requirement — binding without an entered context binds into the engine's default, which the checks never rely on).

func (*UnboundScript) Close

func (u *UnboundScript) Close() error

Close releases the unbound script's persistent handle.

func (*UnboundScript) CreateCodeCache

func (u *UnboundScript) CreateCodeCache() ([]byte, error)

CreateCodeCache produces the script's code cache bytes (UnboundScript::CreateCodeCache). The bytes are a plain Go copy; the engine allocation is released inside the call.

func (*UnboundScript) ID

func (u *UnboundScript) ID() (int32, error)

ID returns the unbound script's engine id (equal to its source script's).

type UseCounterCallback

type UseCounterCallback func(feature uint32)

UseCounterCallback receives the engine's UseCounterFeature discriminant (a stable engine-assigned number; e.g. 9 = strict mode directive in the pinned build). It runs during compilation/execution on the isolate's thread and must not re-enter the engine.

type Value

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

Value is a scope-local JS value: a raw v8 local-handle slot address bound to the Scope that created it. Methods on a Value whose Scope is closed, or that are invoked from a foreign thread, return errors without touching the engine. Values are plain structs — copying one is fine; lifetime, not identity, is what matters.

func CallFunction

func CallFunction(c *Context, s *Scope, fn, recv Value, args []Value, tc *TryCatch) (Value, error)

CallFunction invokes fn with recv and args in the context. TryCatch routing matches Script.Run: a thrown exception yields an error and is recorded in tc when supplied.

func JSONParse

func JSONParse(c *Context, s *Scope, text Value, tc *TryCatch) (Value, error)

JSONParse parses text as JSON. A malformed input throws a SyntaxError which is reported through tc when given (HasCaught and MessageText carry the pinned message) and an error is returned; with tc nil the exception is observed by a shim-internal TryCatch and only the error is returned. text must be a JS string.

func JSONStringify

func JSONStringify(c *Context, s *Scope, value Value, tc *TryCatch) (Value, error)

JSONStringify renders value as JSON text. Circular structures and toJSON failures throw a TypeError which is reported through tc when given (and an error returned); the top-level undefined/function/symbol boundaries are NOT errors — the engine renders them as the literal string "undefined" (the pinned C++ quirk). Any value kind is accepted.

func (Value) BigIntInt64

func (v Value) BigIntInt64() (val int64, lossless bool, err error)

BigIntInt64 returns (value, lossless) for a BigInt via v8 BigInt::Int64Value.

func (Value) BigIntToWords

func (v Value) BigIntToWords(buf []uint64) (sign bool, words []uint64, err error)

BigIntToWords writes the BigInt's absolute-value words into buf (little endian) and reports the sign bit. The engine truncates to the buffer capacity; the returned subslice covers exactly the words written, and buffer bytes beyond it are untouched. A zero BigInt writes nothing.

func (Value) BigIntUint64

func (v Value) BigIntUint64() (value uint64, lossless bool, err error)

BigIntUint64 returns the unsigned 64-bit view of a BigInt and whether the conversion was lossless (false when truncated or negative).

func (Value) BigIntWordCount

func (v Value) BigIntWordCount() (int, error)

BigIntWordCount returns the number of 64-bit words the BigInt occupies.

func (Value) BooleanValue

func (v Value) BooleanValue() (bool, error)

BooleanValue returns the ECMAScript ToBoolean of the value.

func (Value) ContainsOnlyOneByte

func (v Value) ContainsOnlyOneByte() (bool, error)

ContainsOnlyOneByte reports whether every code unit of the string fits one byte. It may read the entire string, so it never has false negatives.

func (Value) Data

func (v Value) Data() (Data, error)

Data returns v as its Data supertype without changing its local lifetime.

func (Value) ExternalValue

func (v Value) ExternalValue() (uintptr, error)

ExternalValue returns the External's raw payload pointer.

func (Value) GetAlignedPointerFromInternalField

func (v Value) GetAlignedPointerFromInternalField(index int, tag int) (uintptr, bool, error)

GetAlignedPointerFromInternalField reads an aligned pointer previously stored with the same tag. ok is false for out-of-bounds indices. A stored null pointer reads back as (0, true, nil): the shim encodes a null result as the zero word with no error text, which this wrapper distinguishes from real failures (those carry a shim status and detail message).

func (Value) GetExternalOneByteStringResource

func (v Value) GetExternalOneByteStringResource() (resource uintptr, data []byte, ok bool, err error)

GetExternalOneByteStringResource resolves the one-byte external resource (base getter + encoding cast). ok is false for plain strings and two-byte externals. data echoes the resource's bytes through the engine's virtual accessors; resource identifies the resource object for pointer-identity observations and must not be dereferenced.

func (Value) GetExternalStringResource

func (v Value) GetExternalStringResource() (resource uintptr, ok bool, err error)

GetExternalStringResource resolves the generic (two-byte-typed) resource; ok is false for one-byte externals and plain strings in this pinned build.

func (Value) GetExternalStringResourceBase

func (v Value) GetExternalStringResourceBase() (resource uintptr, encoding StringEncoding, ok bool, err error)

GetExternalStringResourceBase resolves the resource base and reports the engine's Encoding of the string (valid for plain strings too, where resource is 0).

func (Value) GetHash

func (v Value) GetHash() (uint32, error)

GetHash returns the value's identity hash (v8 Value::GetHash): stable per object/name within one isolate, not across isolates or processes. Hash equality is a proxy for object identity, mirroring the oracle's get_hash()-based observations.

func (Value) GetInternalField

func (v Value) GetInternalField(index int) (Value, bool, error)

GetInternalField reads internal field index. ok is false when the index is out of bounds or the field was never set.

func (Value) InstanceOf

func (v Value) InstanceOf(s *Scope, c *Context, obj *Object, tc *TryCatch) (bool, error)

InstanceOf reports the Value::InstanceOf prototype-chain membership test against obj. A non-callable right-hand side throws the pinned "Right-hand side of 'instanceof' is not callable" TypeError, delivered to tc when given and reported as an error.

func (Value) Int32Value

func (v Value) Int32Value(c *Context) (val int32, ok bool, err error)

Int32Value returns v8 Value::Int32Value (a context conversion to i32).

func (Value) IntegerValue

func (v Value) IntegerValue(c *Context) (val int64, ok bool, err error)

IntegerValue returns v8 Value::IntegerValue (a context conversion to i64).

func (Value) IntegerValueRaw

func (v Value) IntegerValueRaw() (int64, error)

IntegerValueRaw returns v8::Integer::Value (the int64 payload of an Integer-typed value) without a context conversion.

func (Value) InternalFieldCount

func (v Value) InternalFieldCount() (int, error)

InternalFieldCount returns the number of internal fields configured on the object's instance template (0 for plain objects).

func (Value) IsArgumentsObject

func (v Value) IsArgumentsObject() (bool, error)

IsArgumentsObject reports whether the value is an arguments object.

func (Value) IsArray

func (v Value) IsArray() (bool, error)

IsArray reports whether the value is an array.

func (Value) IsArrayBuffer

func (v Value) IsArrayBuffer() (bool, error)

IsArrayBuffer reports whether the value is an ArrayBuffer.

func (Value) IsArrayBufferView

func (v Value) IsArrayBufferView() (bool, error)

IsArrayBufferView reports whether the value is a view over a buffer (a typed array or a DataView).

func (Value) IsAsyncFunction

func (v Value) IsAsyncFunction() (bool, error)

IsAsyncFunction reports whether the value is an async function object.

func (Value) IsBigInt

func (v Value) IsBigInt() (bool, error)

IsBigInt reports whether the value is a BigInt primitive.

func (Value) IsBigInt64Array

func (v Value) IsBigInt64Array() (bool, error)

IsBigInt64Array reports whether the value is a BigInt64Array.

func (Value) IsBigIntObject

func (v Value) IsBigIntObject() (bool, error)

IsBigIntObject reports whether the value is a BigInt wrapper object.

func (Value) IsBigUint64Array

func (v Value) IsBigUint64Array() (bool, error)

IsBigUint64Array reports whether the value is a BigUint64Array.

func (Value) IsBoolean

func (v Value) IsBoolean() (bool, error)

IsBoolean reports whether the value is a boolean.

func (Value) IsBooleanObject

func (v Value) IsBooleanObject() (bool, error)

IsBooleanObject reports whether the value is a Boolean wrapper object.

func (Value) IsDataView

func (v Value) IsDataView() (bool, error)

IsDataView reports whether the value is a DataView.

func (Value) IsDate

func (v Value) IsDate() (bool, error)

IsDate reports whether the value is a Date object.

func (Value) IsExternal

func (v Value) IsExternal() (bool, error)

IsExternal reports whether the value is a JS External.

func (Value) IsExternalOneByte

func (v Value) IsExternalOneByte() (bool, error)

IsExternalOneByte reports whether the string is external and one-byte.

func (Value) IsExternalString

func (v Value) IsExternalString() (bool, error)

IsExternalString reports whether the string is backed by an external resource (of either encoding).

func (Value) IsExternalTwoByte

func (v Value) IsExternalTwoByte() (bool, error)

IsExternalTwoByte reports whether the string is external and two-byte.

func (Value) IsFalse

func (v Value) IsFalse() (bool, error)

IsFalse reports whether the value is exactly the primitive false.

func (Value) IsFloat16Array

func (v Value) IsFloat16Array() (bool, error)

IsFloat16Array reports whether the value is a Float16Array.

func (Value) IsFloat32Array

func (v Value) IsFloat32Array() (bool, error)

IsFloat32Array reports whether the value is a Float32Array.

func (Value) IsFloat64Array

func (v Value) IsFloat64Array() (bool, error)

IsFloat64Array reports whether the value is a Float64Array.

func (Value) IsFunction

func (v Value) IsFunction() (bool, error)

IsFunction reports whether the value is a function.

func (Value) IsGeneratorFunction

func (v Value) IsGeneratorFunction() (bool, error)

IsGeneratorFunction reports whether the value is a generator function object.

func (Value) IsGeneratorObject

func (v Value) IsGeneratorObject() (bool, error)

IsGeneratorObject reports whether the value is a generator object.

func (Value) IsInt8Array

func (v Value) IsInt8Array() (bool, error)

IsInt8Array reports whether the value is an Int8Array.

func (Value) IsInt16Array

func (v Value) IsInt16Array() (bool, error)

IsInt16Array reports whether the value is an Int16Array.

func (Value) IsInt32

func (v Value) IsInt32() (bool, error)

IsInt32 reports whether the value is a 32-bit signed integer.

func (Value) IsInt32Array

func (v Value) IsInt32Array() (bool, error)

IsInt32Array reports whether the value is an Int32Array.

func (Value) IsMap

func (v Value) IsMap() (bool, error)

IsMap reports whether the value is a Map object.

func (Value) IsMapIterator

func (v Value) IsMapIterator() (bool, error)

IsMapIterator reports whether the value is a Map iterator object.

func (Value) IsModuleNamespaceObject

func (v Value) IsModuleNamespaceObject() (bool, error)

IsModuleNamespaceObject reports whether the value is an ECMAScript module namespace exotic object.

func (Value) IsName

func (v Value) IsName() (bool, error)

IsName reports whether the value can be used as a property name (a string or a symbol primitive).

func (Value) IsNativeError

func (v Value) IsNativeError() (bool, error)

IsNativeError reports whether the value is an Error instance from the engine's native error family (TypeError, RangeError, ...).

func (Value) IsNull

func (v Value) IsNull() (bool, error)

IsNull reports whether the value is null.

func (Value) IsNullOrUndefined

func (v Value) IsNullOrUndefined() (bool, error)

IsNullOrUndefined reports whether the value is null or undefined.

func (Value) IsNumber

func (v Value) IsNumber() (bool, error)

IsNumber reports whether the value is a number.

func (Value) IsNumberObject

func (v Value) IsNumberObject() (bool, error)

IsNumberObject reports whether the value is a Number wrapper object.

func (Value) IsObject

func (v Value) IsObject() (bool, error)

IsObject reports whether the value is an object.

func (Value) IsOneByte

func (v Value) IsOneByte() (bool, error)

IsOneByte reports whether the string is known (without reading it) to be one-byte encoded. False negatives are possible.

func (Value) IsPrimitive

func (v Value) IsPrimitive() (bool, error)

IsPrimitive reports whether the value is undefined, null, a boolean, string, symbol, number, or bigint.

func (Value) IsPromise

func (v Value) IsPromise() (bool, error)

IsPromise reports whether the value is a Promise object.

func (Value) IsProxy

func (v Value) IsProxy() (bool, error)

IsProxy reports whether the value is a Proxy exotic object.

func (Value) IsRegExp

func (v Value) IsRegExp() (bool, error)

IsRegExp reports whether the value is a RegExp object.

func (Value) IsSet

func (v Value) IsSet() (bool, error)

IsSet reports whether the value is a Set object.

func (Value) IsSetIterator

func (v Value) IsSetIterator() (bool, error)

IsSetIterator reports whether the value is a Set iterator object.

func (Value) IsSharedArrayBuffer

func (v Value) IsSharedArrayBuffer() (bool, error)

IsSharedArrayBuffer reports whether the value is a SharedArrayBuffer.

func (Value) IsString

func (v Value) IsString() (bool, error)

IsString reports whether the value is a string.

func (Value) IsStringObject

func (v Value) IsStringObject() (bool, error)

IsStringObject reports whether the value is a String wrapper object.

func (Value) IsSymbol

func (v Value) IsSymbol() (bool, error)

IsSymbol reports whether the value is a symbol primitive.

func (Value) IsSymbolObject

func (v Value) IsSymbolObject() (bool, error)

IsSymbolObject reports whether the value is a Symbol wrapper object.

func (Value) IsTrue

func (v Value) IsTrue() (bool, error)

IsTrue reports whether the value is exactly the primitive true. A Boolean wrapper object is not true by this predicate even when ToBoolean of it would be (BooleanValue).

func (Value) IsTypedArray

func (v Value) IsTypedArray() (bool, error)

IsTypedArray reports whether the value is a typed array.

func (Value) IsUint8Array

func (v Value) IsUint8Array() (bool, error)

IsUint8Array reports whether the value is a Uint8Array.

func (Value) IsUint8ClampedArray

func (v Value) IsUint8ClampedArray() (bool, error)

IsUint8ClampedArray reports whether the value is a Uint8ClampedArray.

func (Value) IsUint16Array

func (v Value) IsUint16Array() (bool, error)

IsUint16Array reports whether the value is a Uint16Array.

func (Value) IsUint32

func (v Value) IsUint32() (bool, error)

IsUint32 reports whether the value is a 32-bit unsigned integer.

func (Value) IsUint32Array

func (v Value) IsUint32Array() (bool, error)

IsUint32Array reports whether the value is a Uint32Array.

func (Value) IsUndefined

func (v Value) IsUndefined() (bool, error)

IsUndefined reports whether the value is undefined.

func (Value) IsWasmMemoryObject

func (v Value) IsWasmMemoryObject() (bool, error)

IsWasmMemoryObject reports whether v is a WebAssembly.Memory.

func (Value) IsWasmModuleObject

func (v Value) IsWasmModuleObject() (bool, error)

IsWasmModuleObject reports whether v is a WebAssembly.Module.

func (Value) IsWeakMap

func (v Value) IsWeakMap() (bool, error)

IsWeakMap reports whether the value is a JSWeakMap instance.

func (Value) IsWeakSet

func (v Value) IsWeakSet() (bool, error)

IsWeakSet reports whether the value is a JSWeakSet instance.

func (Value) Length

func (v Value) Length() (int, error)

Length returns the number of UTF-16 code units in a string value.

func (Value) NumberValue

func (v Value) NumberValue(c *Context) (val float64, ok bool, err error)

NumberValue returns v8 Value::NumberValue (a context conversion). ok is false when the conversion failed without throwing.

func (Value) NumberValueRaw

func (v Value) NumberValueRaw() (float64, error)

NumberValueRaw returns v8::Number::Value (the float64 payload of a Number-typed value) without a context conversion.

func (Value) SameValue

func (v Value) SameValue(other Value) (bool, error)

SameValue reports ECMAScript SameValue equality (identity for objects; the security-token comparison of the oracle checks).

func (Value) SameValueZero

func (v Value) SameValueZero(s *Scope, other Value) (bool, error)

SameValueZero reports the ECMAScript SameValueZero relation (the Map/Set key semantics): SameValue plus +0 == -0. It is implemented exactly as the pinned crate implements it on the Rust side: SameValue, or both sides strictly equal to the zero Smi. The scope only materializes that zero.

func (Value) SetAlignedPointerInInternalField

func (v Value) SetAlignedPointerInInternalField(index int, ptr uintptr, tag int) error

SetAlignedPointerInInternalField stores an embedder pointer in internal field index under a type tag (0-15; the engine aborts on out-of-range tags). The pointer must be 8-aligned. Use HostRefAdd tokens for Go data; raw pointers must reference embedder-owned native memory that outlives the object.

func (Value) SetInternalField

func (v Value) SetInternalField(index int, data Value) (bool, error)

SetInternalField stores a Data value in internal field index. ok is false when the index is out of bounds — this wrapper is the bounds check (the engine's release build performs none, so reaching V8 with an out-of-range index would corrupt memory).

func (Value) StrictEquals

func (v Value) StrictEquals(other Value) (bool, error)

StrictEquals reports ECMAScript strict equality between two values from the same isolate (v8 Value::StrictEquals).

func (Value) StringValue

func (v Value) StringValue() (string, error)

StringValue returns the value as a Go string, assuming it is a JS string.

func (Value) ToBigInt

func (v Value) ToBigInt(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToBigInt returns the per-spec ToBigInt of the value: booleans and integral decimal strings convert; numbers and non-integral strings throw a TypeError (delivered to tc when given). Read the result with BigIntInt64.

func (Value) ToBoolean

func (v Value) ToBoolean(s *Scope) (Value, error)

ToBoolean returns the value coerced to a Boolean (never throws). Read the result with BooleanValue, or use BooleanValue directly for the same one-step observation.

func (Value) ToDetailString

func (v Value) ToDetailString(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToDetailString returns Value::ToDetailString: identical to ToString for primitives, `Symbol(desc)` for symbols, an error's ToString message without the "Uncaught" prefix, and V8's compact `#<Object>` form for plain JSReceiver objects. A failed conversion is an error (delivered to tc when given).

func (Value) ToInt32

func (v Value) ToInt32(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToInt32 returns the ECMAScript ToInt32 conversion as a scope-local value.

func (Value) ToInteger

func (v Value) ToInteger(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToInteger returns the ECMAScript ToInteger truncation of the value as an Integer (a scope-local value; read the raw int64 with IntegerValueRaw — note the raw read saturates out-of-range magnitudes exactly like the pinned C++ double→int64 cast, e.g. ±Infinity reads as math.MinInt64). A BigInt operand throws a TypeError, delivered to tc when given.

func (Value) ToNumber

func (v Value) ToNumber(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToNumber returns the ECMAScript ToNumber conversion as a scope-local Number. BigInt and Symbol operands throw and are delivered to tc when set.

func (Value) ToObject

func (v Value) ToObject(s *Scope, c *Context, tc *TryCatch) (*Object, error)

ToObject returns the ECMAScript ToObject of the value: wrapper objects for primitives, identity for objects. undefined and null throw a TypeError, delivered to tc when given and reported as an error.

func (Value) ToString

func (v Value) ToString(c *Context) (string, error)

ToString returns the ECMAScript ToString of the value as a Go string (lossy UTF-8, matching the oracle's to_rust_string_lossy).

func (Value) ToStringTC

func (v Value) ToStringTC(s *Scope, c *Context, tc *TryCatch) (string, error)

ToStringTC is the TryCatch-routed ToString: unlike Value.ToString (whose shim path installs an internal TryCatch and swallows conversion failures), a throwing conversion here is delivered to tc (HasCaught and MessageText observe it) and reported as an error. Use it when the value may not convert (symbols); tc follows the Compile/Run convention.

func (Value) ToStringValue

func (v Value) ToStringValue(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToStringValue returns the ECMAScript ToString conversion as a scope-local V8 String. It preserves exact UTF-16 contents; use Value.ToString when a lossy Go UTF-8 convenience result is sufficient.

func (Value) ToUint32

func (v Value) ToUint32(s *Scope, c *Context, tc *TryCatch) (Value, error)

ToUint32 returns the ECMAScript ToUint32 conversion as a scope-local value.

func (Value) TypeOf

func (v Value) TypeOf(s *Scope) (Value, error)

TypeOf returns the "typeof" string of the value (a scope-local string value). The scope must belong to the value's isolate.

func (Value) TypeRepr

func (v Value) TypeRepr() (string, error)

TypeRepr returns rusty_v8 Value::type_repr's human-readable classification. The ordering deliberately matches the pinned crate, including its generic "TypedArray" result for Float16Array.

func (Value) Uint32Value

func (v Value) Uint32Value(c *Context) (val uint32, ok bool, err error)

Uint32Value returns v8 Value::Uint32Value (a context conversion to u32).

func (Value) Utf8Length

func (v Value) Utf8Length() (int, error)

Utf8Length returns the number of bytes in the value's UTF-8 encoding (string values only).

func (Value) WriteOneByte

func (v Value) WriteOneByte(offset int, buf []byte, flags WriteFlags) (int, error)

WriteOneByte writes up to len(buf) one-byte (Latin-1) characters starting at code-unit offset (String::WriteOneByte). Two-byte content is truncated to its low byte per unit. Returns the number of bytes written.

func (Value) WriteTwoByte

func (v Value) WriteTwoByte(offset int, buf []uint16, flags WriteFlags) (int, error)

WriteTwoByte writes up to len(buf) UTF-16 code units of the string starting at code-unit offset into buf (String::Write). It returns the number of units written: the minimum of the remaining string length and the buffer capacity. offset must be within [0, Length]; a buffer too small for the requested range plus the NUL (when WriteNullTerminate is set) is an error before any engine call.

func (Value) WriteUTF8

func (v Value) WriteUTF8(buf []byte, flags WriteFlags) (n int, processed int, err error)

WriteUTF8 encodes the string as UTF-8 into buf (String::WriteUtf8). It never writes partial sequences: when the next character does not fit, encoding stops. n counts the bytes written (including the NUL when WriteNullTerminate is set, which requires capacity >= 1); processed counts the UTF-16 code units consumed.

type ValueDeserializer

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

ValueDeserializer reads JS values from structured-clone wire bytes. The input slice is retained (uncopied) until Close: see the lifetime notes at the top of this file.

func NewValueDeserializer

func NewValueDeserializer(s *Scope, c *Context, data []byte) (*ValueDeserializer, error)

NewValueDeserializer creates a deserializer over data (no copy) bound to the context's isolate. The delegate behavior is the pinned crate's default: reads of host objects, transferred shared array buffers and wasm modules throw the deterministic "Deno deserializer: ... not implemented" errors. data must not be mutated while the deserializer is open.

func (*ValueDeserializer) Close

func (vd *ValueDeserializer) Close() error

Close destroys the engine deserializer, which releases its reference to the input bytes; only after this call may the caller reuse or free the slice. The wrapper's own reference is dropped here too.

func (*ValueDeserializer) GetWireFormatVersion

func (vd *ValueDeserializer) GetWireFormatVersion() (uint32, error)

GetWireFormatVersion reports the detected version. Versioned data becomes meaningful after ReadHeader; accepted headerless data reports version 0.

func (*ValueDeserializer) ReadHeader

func (vd *ValueDeserializer) ReadHeader(c *Context) (ok bool, err error)

ReadHeader reads and validates the wire-format header. Call it before ReadValue. Header-less data is classified as legacy version 0 and, unless legacy support is explicitly enabled with SetSupportsLegacyWireFormat, is rejected by this pinned engine. Missing, truncated, and unsupported headers therefore return an error satisfying IsException; current versioned data returns true.

func (*ValueDeserializer) ReadValue

func (vd *ValueDeserializer) ReadValue(c *Context, tc *TryCatch) (Value, error)

ReadValue deserializes the next value. A returned error satisfying IsException means the engine threw (invalid wire data, an unregistered transfer id, or a rejected host object); the details are in tc (nil uses a shim-internal fallback), exactly like the crate's read_value returning None.

func (*ValueDeserializer) SetSupportsLegacyWireFormat

func (vd *ValueDeserializer) SetSupportsLegacyWireFormat(enabled bool) error

SetSupportsLegacyWireFormat controls acceptance of headerless and old structured-clone wire formats. It must be called before ReadHeader or ReadValue. V8 treats late mutation as an invalid state; Go rejects it before crossing the native boundary. Repeated calls before reading are allowed and the last value wins.

func (*ValueDeserializer) TransferArrayBuffer

func (vd *ValueDeserializer) TransferArrayBuffer(id uint32, ab *ArrayBuffer) error

TransferArrayBuffer registers the receiving buffer for transfer id (v8::ValueDeserializer::transfer_array_buffer). The registered buffer's own store is reused as the transferred contents.

type ValueDeserializerDelegate

type ValueDeserializerDelegate interface{}

ValueDeserializerDelegate is the (fully optional) analogue of the pinned crate's ValueDeserializerImpl: every hook below is optional, so the empty interface is a valid delegate reproducing the trait defaults. nil is accepted and means the same.

type ValueSerializer

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

ValueSerializer produces structured-clone wire bytes for JS values.

func NewValueSerializer

func NewValueSerializer(s *Scope, c *Context, d ValueSerializerDelegate) (*ValueSerializer, error)

NewValueSerializer creates a serializer bound to the scope's isolate and the given context (the crate captures the scope's current context; gov8 passes the context explicitly). d must be non-nil; a data-clone error without a delegate would otherwise leave the engine without a reporting path (the Rust API requires a boxed impl too).

func (*ValueSerializer) Close

func (vs *ValueSerializer) Close() error

Close destroys the engine serializer and unregisters the Go delegate. The delegate can no longer be invoked afterwards. Close must be called on the owning thread before the scope closes.

func (*ValueSerializer) Release

func (vs *ValueSerializer) Release() ([]byte, error)

Release returns the accumulated wire bytes and makes the serializer unusable (the engine hands buffer ownership to the shim, which copies into Go memory and frees the original). The contents are whatever was written before a failed write — the crate behaves the same way.

func (*ValueSerializer) TransferArrayBuffer

func (vs *ValueSerializer) TransferArrayBuffer(id uint32, ab *ArrayBuffer) error

TransferArrayBuffer marks ab as transferred out of band under the given id (v8::ValueSerializer::transfer_array_buffer). The receiving side must register the same id on its deserializer or deserialization fails deterministically. This build does NOT detach the source at write time.

func (*ValueSerializer) WriteHeader

func (vs *ValueSerializer) WriteHeader() error

WriteHeader writes the wire-format version header (v8's WriteHeader; this build emits version 16 bytes "ff 10"). write_value alone emits NO header bytes — an explicit WriteHeader is the canonical embedder flow and changes the bytes observable in the wire.

func (*ValueSerializer) WriteValue

func (vs *ValueSerializer) WriteValue(c *Context, v Value, tc *TryCatch) (ok bool, err error)

WriteValue serializes value into the wire buffer. ok is false when the value could not be serialized; when a delegate threw (the normal data-clone path) the returned error satisfies IsException and the details are in tc (the caller's TryCatch; nil uses a shim-internal fallback, in which case the exception is not observable).

type ValueSerializerDelegate

type ValueSerializerDelegate interface {
	// ThrowDataCloneError is invoked when the engine reports a data-clone
	// error (for example serializing a function). Return true to re-throw
	// the message as a JS Error so an enclosing TryCatch observes the
	// failure (the structured-clone behavior); false leaves the engine
	// untouched and WriteValue simply reports failure.
	ThrowDataCloneError(message string) (rethrow bool)
}

Value serialization / deserialization (structured clone wire format).

Rust surface mapped here (pinned crate v8 =152.2.0):

v8::ValueSerializer::new(scope, Box<D>)        -> NewValueSerializer(s, d)
    write_header                               -> (*ValueSerializer).WriteHeader
    write_value(context, value) -> Option<bool>-> (*ValueSerializer).WriteValue
    transfer_array_buffer(id, ab)              -> (*ValueSerializer).TransferArrayBuffer
    release() -> Vec<u8>                       -> (*ValueSerializer).Release
v8::ValueDeserializer::new(scope, D, data)     -> NewValueDeserializer(s, c, data)
    read_value(context) -> Option<Local>       -> (*ValueDeserializer).ReadValue
    read_header / transfer_array_buffer        -> the matching methods

Delegate model. Rust passes a boxed ValueSerializerImpl trait object; Go cannot expose function pointers to the engine, so delegates live in an integer registry and the engine only ever sees an int64 id (the same pattern as the native-callback registries). One process-wide trampoline per callback shape (syscall.NewCallback, pinned by the Go runtime) is registered with the shim once.

  • ValueSerializerDelegate.ThrowDataCloneError receives the engine's message TEXT (already lossy-decoded, like to_rust_string_lossy) and returns whether the shim should re-throw it as a JS Error — the behavior of the oracle's DataCloneErrorReporter, which round-trips the message through a fresh String and throws Exception::error. The hook intentionally receives no live handles: nothing crosses the boundary except bytes and an int.
  • The remaining serializer hooks and all deserializer hooks are NOT delegated to Go: the shim reproduces the pinned crate's DEFAULT behaviors verbatim (Nothing from the SAB-id / wasm-transfer-id paths; the deterministic "Deno serializer/deserializer: ... not implemented" Error throws from the host-object paths). Custom host objects need cross-boundary object marshaling and remain future scope; nothing here silently succeeds where the crate fails.

Wire-bytes ownership. Release copies the wire bytes into a Go slice and frees the engine buffer inside the shim; Go never holds a pointer into the serializer. The serializer is unusable after Release (mirroring the crate).

Deserializer input lifetime. The engine stores the caller's data pointer WITHOUT copying — the pinned fixture's behavior depends on it (see the oracle's deser_describe! lifetime note). The Go wrapper therefore keeps the input slice referenced from NewValueDeserializer until Close; Close destroys the engine object first and only then drops the reference. Do not mutate the slice while the deserializer is open, and do not rely on it after Close.

type Version

type Version struct {
	Major, Minor, Build, Patch int32
}

V8 version constants reported by the pinned engine build.

func EngineVersion

func EngineVersion() (Version, error)

EngineVersion returns the engine version constants (15.2.124.1 for the pinned build).

type ViewContents

type ViewContents struct {
	// Length is the span's full length in bytes. For this build it is always
	// the view's byte length and independent of the caller's storage size
	// (the off-heap GetContents path ignores the storage argument).
	Length int
	// Source is the span's base address. OBSERVATION ONLY (same rules as
	// TypedArray.Data): never dereference or retain it.
	Source uintptr
}

ViewContents describes the engine's live contents span of a view (ArrayBufferView::GetContents).

func (ViewContents) SourceIsData

func (vc ViewContents) SourceIsData(data uintptr) bool

SourceIsData reports whether the live span's base is the view's data pointer (the off-heap aliasing contract pinned by the oracle). A null source (detached view) never matches.

type WasmAsyncResolution

type WasmAsyncResolution struct {
	CallbackScope *CallbackScope
	Resolver      PromiseResolver
	Result        Value
	Success       WasmAsyncSuccess
}

WasmAsyncResolution is callback-local. Resolver, Result and CallbackScope become invalid as soon as the callback returns.

func (*WasmAsyncResolution) Promise

func (r *WasmAsyncResolution) Promise() (Promise, error)

Promise returns the exact promise associated with Resolver.

func (*WasmAsyncResolution) Settle

func (r *WasmAsyncResolution) Settle() (bool, error)

Settle resolves on Success and rejects on Fail using V8's supplied result.

type WasmAsyncResolvePromiseCallback

type WasmAsyncResolvePromiseCallback func(*WasmAsyncResolution)

WasmAsyncResolvePromiseCallback receives V8's resolver and result in the originating context. V8 does not settle the resolver after a custom callback is installed; the callback must call resolution.Settle (or use CallbackScope.SettleCallbackPromise explicitly).

type WasmAsyncSuccess

type WasmAsyncSuccess int32

WasmAsyncSuccess is the completion verdict passed to the asynchronous Wasm promise callback.

const (
	WasmAsyncSuccessSuccess WasmAsyncSuccess = 0
	WasmAsyncSuccessFail    WasmAsyncSuccess = 1
)

func (WasmAsyncSuccess) String

func (s WasmAsyncSuccess) String() string

type WasmMemoryObject

type WasmMemoryObject struct{ Value }

WasmMemoryObject is a scope-local WebAssembly.Memory value.

func AsWasmMemoryObject

func AsWasmMemoryObject(v Value) (*WasmMemoryObject, error)

AsWasmMemoryObject performs a checked local-value conversion.

func (*WasmMemoryObject) Buffer

func (m *WasmMemoryObject) Buffer(c *Context) (*ArrayBuffer, error)

Buffer returns the WebAssembly.Memory object's current ArrayBuffer. Context is explicit because gov8 does not keep a context pointer in local Values.

type WasmModuleCompilation

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

WasmModuleCompilation is V8's experimental, movable asynchronous compiler. Calls are serialized; OnBytesReceived, SetURL, Abort, and Close may be made from any thread. Finish must run on the target isolate's owning thread.

func NewWasmModuleCompilation

func NewWasmModuleCompilation() (*WasmModuleCompilation, error)

NewWasmModuleCompilation begins an isolate-independent asynchronous compile.

func (*WasmModuleCompilation) Abort

func (c *WasmModuleCompilation) Abort() error

Abort consumes the compilation and may run on any thread.

func (*WasmModuleCompilation) Close

func (c *WasmModuleCompilation) Close() error

Close drops an unfinished compilation and may run on any thread.

func (*WasmModuleCompilation) Finish

func (c *WasmModuleCompilation) Finish(scope *Scope, context *Context, cacheCallback ModuleCachingCallback,
	callback WasmModuleCompilationCallback) error

Finish consumes the compilation and schedules callback on the target isolate. cacheCallback is required exactly when cache mode was selected.

func (*WasmModuleCompilation) OnBytesReceived

func (c *WasmModuleCompilation) OnBytesReceived(data []byte) error

OnBytesReceived feeds one owned chunk and may run on any thread.

func (*WasmModuleCompilation) SetHasCompiledModuleBytes

func (c *WasmModuleCompilation) SetHasCompiledModuleBytes() error

SetHasCompiledModuleBytes selects cache mode. Any earlier byte notification, including an empty chunk, is rejected before V8's fatal boundary.

func (*WasmModuleCompilation) SetMoreFunctionsCanBeSerializedCallback

func (c *WasmModuleCompilation) SetMoreFunctionsCanBeSerializedCallback(callback WasmSerializationCallback) error

SetMoreFunctionsCanBeSerializedCallback installs the background-safe serialization notification callback.

func (*WasmModuleCompilation) SetURL

func (c *WasmModuleCompilation) SetURL(url string) error

SetURL sets the compiled module source URL and may run on any thread.

type WasmModuleCompilationCallback

type WasmModuleCompilationCallback func(*WasmModuleCompilationResult)

WasmModuleCompilationCallback runs once on the isolate thread after an experimental asynchronous compilation resolves. Exactly one of Module and Error is populated, and all local values are callback-local.

type WasmModuleCompilationResult

type WasmModuleCompilationResult struct {
	CallbackScope *CallbackScope
	Module        *WasmModuleObject
	Error         Value
}

WasmModuleCompilationResult is valid only while its callback is running.

type WasmModuleObject

type WasmModuleObject struct{ Value }

WasmModuleObject is a scope-local WebAssembly.Module value.

func AsWasmModuleObject

func AsWasmModuleObject(v Value) (*WasmModuleObject, error)

AsWasmModuleObject performs a checked local-value conversion.

func (*WasmModuleObject) CompiledModule

func (m *WasmModuleObject) CompiledModule() (*CompiledWasmModule, error)

CompiledModule returns a newly owned compiled representation.

type WasmSerializationCallback

type WasmSerializationCallback func(*CompiledWasmModule)

WasmSerializationCallback may run on a background thread. It receives an owned compiled module; the callback must close it or transfer its ownership.

type WasmStreaming

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

WasmStreaming is V8's streaming compilation sink. Unlike WasmModuleCompilation it is isolate/thread-affine.

func (*WasmStreaming) Abort

func (s *WasmStreaming) Abort(exception *Value) error

Abort consumes the stream. A non-nil exception must be a live local value from the same isolate.

func (*WasmStreaming) Close

func (s *WasmStreaming) Close() error

Close drops an unfinished stream without finishing or rejecting its promise.

func (*WasmStreaming) Finish

func (s *WasmStreaming) Finish(callback ModuleCachingCallback) error

Finish consumes the stream. callback is required in cache mode and must be nil otherwise.

func (*WasmStreaming) OnBytesReceived

func (s *WasmStreaming) OnBytesReceived(data []byte) error

OnBytesReceived feeds one chunk. Even an empty chunk establishes call order and prevents later SetHasCompiledModuleBytes.

func (*WasmStreaming) SetHasCompiledModuleBytes

func (s *WasmStreaming) SetHasCompiledModuleBytes() error

SetHasCompiledModuleBytes selects cache mode. Calling it after any byte notification is rejected in Go before V8's fatal CHECK boundary.

func (*WasmStreaming) SetURL

func (s *WasmStreaming) SetURL(url string) error

SetURL sets the source URL before completion.

type WasmStreamingCallback

type WasmStreamingCallback func(callbackScope *CallbackScope, source Value, stream *WasmStreaming)

WasmStreamingCallback is the embedder injection point for WebAssembly.compileStreaming. source and callbackScope are callback-local; stream is owned by the callback and must eventually be finished, aborted, or closed.

type Weak

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

Weak is a weak persistent handle to a JS value.

func (*Weak) Clone

func (w *Weak) Clone() (*Weak, error)

Clone creates a new weak handle over the same object without a finalizer (Weak::clone). A clone of an empty/collected weak is an empty weak.

func (*Weak) Close

func (w *Weak) Close() error

Close drops the weak handle. While the object is still strongly held this resets the underlying weak cell and cancels the pending finalizer (the callback never fires, even after forced GCs or isolate teardown). When collection already happened but the finalizer has not run, the callback is cancelled here too. After the host isolate was closed this is a silent no-op.

func (*Weak) EqualGlobal

func (w *Weak) EqualGlobal(g *Global) (bool, error)

EqualGlobal reports weak-to-global equality: true while the weak holds the same object as the global, false once the object was collected.

func (*Weak) EqualWeak

func (w *Weak) EqualWeak(other *Weak) (bool, error)

EqualWeak reports weak-to-weak equality with the pinned crate's semantics: same-isolate weaks compare by object identity, two collected weaks compare equal, and a collected weak equals nothing live.

func (*Weak) IsEmpty

func (w *Weak) IsEmpty() (bool, error)

IsEmpty reports whether the object was collected (or the weak is empty). After the host isolate was closed this reports true without touching the engine, matching the pinned crate.

func (*Weak) ToGlobal

func (w *Weak) ToGlobal() (*Global, bool, error)

ToGlobal creates a strong global over the weak's object; ok is false when the object was collected.

func (*Weak) ToLocal

func (w *Weak) ToLocal(s *Scope) (Value, bool, error)

ToLocal reopens the weak's object as a scope-local value; ok is false when the object was collected.

type WeakFinalizer

type WeakFinalizer func(i *Isolate)

WeakFinalizer is the regular weak-finalizer callback. It runs after the object lost its last strong reference and the engine processed the weak cell. It must be pure Go: the engine must not be re-entered from a finalizer (it runs during GC or isolate teardown).

type WriteFlags

type WriteFlags int32

WriteFlags mirror v8::String::WriteFlags.

const (
	// WriteNullTerminate appends a NUL terminator. The buffer must have
	// space for it (validated before the engine call).
	WriteNullTerminate WriteFlags = 1 << iota
	// WriteReplaceInvalidUTF8 makes WriteUTF8 emit U+FFFD for lone
	// surrogate code units instead of their raw 3-byte CESU-8 encoding.
	WriteReplaceInvalidUTF8
)

type WriteHostObjectHook

type WriteHostObjectHook interface {
	WriteHostObject(obj *Object, w *DelegateValueSerializer) (ok, answered bool)
}

WriteHostObjectHook mirrors v8::ValueSerializerImpl::write_host_object. w is the serializer itself (the crate passes the ValueSerializer as its helper trait object): the hook writes its own bytes with w.WriteUint32 / WriteRawBytes / WriteDouble / WriteValue / .... The engine ignores the returned ok once no exception is pending (pinned release-build semantics); answered=false maps to None.

Directories

Path Synopsis
Package main implements the gov8 conformance runner.
Package main implements the gov8 conformance runner.
buffers command
The 20 buffers/serialization conformance checks, in the fixed oracle order (rust-oracle/src/bin/conformance-buffers.rs CHECKS).
The 20 buffers/serialization conformance checks, in the fixed oracle order (rust-oracle/src/bin/conformance-buffers.rs CHECKS).
controls-hooks command
The controls/hooks checks, in the fixed contractual order (the order is part of the observable contract).
The controls/hooks checks, in the fixed contractual order (the order is part of the observable contract).
core-advanced command
The 25 core-advanced checks in the fixed oracle order (the order is part of the observable contract).
The 25 core-advanced checks in the fixed oracle order (the order is part of the observable contract).
host-promises command
Package main implements the promise-slice conformance runner.
Package main implements the promise-slice conformance runner.
host-templates command
object-ops command
The 25 object-ops checks in the fixed oracle order (the order is part of the observable contract).
The 25 object-ops checks in the fixed oracle order (the order is part of the observable contract).
runtime-values command
serializer-delegates command
Shared harness for the conformance-serializer-delegates checks: the runtime triple, the eval helper, the hook counters, the normalized value description, and the delegate implementations — one focused struct per hook-behavior variant, mirroring the local helpers and delegate structs of rust-oracle/src/bin/conformance-serializer-delegates.rs one for one.
Shared harness for the conformance-serializer-delegates checks: the runtime triple, the eval helper, the hook counters, the normalized value description, and the delegate implementations — one focused struct per hook-behavior variant, mirroring the local helpers and delegate structs of rust-oracle/src/bin/conformance-serializer-delegates.rs one for one.
snapshots command
strings-bigint command
The 17 advanced strings/BigInt checks in the fixed oracle order (the JSON-lines fixture follows exactly this order): all strings/ checks precede all bigint/ checks.
The 17 advanced strings/BigInt checks in the fixed oracle order (the JSON-lines fixture follows exactly this order): all strings/ checks precede all bigint/ checks.
typed-arrays command
The 14 typed-array conformance checks, in the fixed oracle order (rust-oracle/src/bin/conformance-typed-arrays.rs CHECKS).
The 14 typed-array conformance checks, in the fixed oracle order (rust-oracle/src/bin/conformance-typed-arrays.rs CHECKS).
examples
basic command
internal
cmd/package-shim command
Command package-shim deterministically compresses a source-built gov8 shim for inclusion in the Go module.
Command package-shim deterministically compresses a source-built gov8 shim for inclusion in the Go module.
prebuilt
Package prebuilt materializes gov8's pinned native shim.
Package prebuilt materializes gov8's pinned native shim.

Jump to

Keyboard shortcuts

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