Documentation
¶
Overview ¶
Package net is Sweef's document + network layer: HTML5 parsing into a stable node tree, CSS selector matching, form modelling, HAR records and route interception. No cgo, no deps beyond golang.org/x/net/html.
Index ¶
- func MatchRoute(r *Route, req *http.Request) (int, string, bool)
- func MediaMatches(query string, viewportWidth int, colorScheme string) bool
- type BoxRow
- type Doc
- func (d *Doc) AppendChild(parentID, childID int64) error
- func (d *Doc) AppendHTML(sel, frag string) error
- func (d *Doc) AriaSnapshot() ([]*Info, error)
- func (d *Doc) AriaSnapshotV2(o SnapshotOptions) (string, error)
- func (d *Doc) AriaSnapshotYAML() (string, error)
- func (d *Doc) Attached(n *html.Node) bool
- func (d *Doc) AttrNames(id int64) []string
- func (d *Doc) BackendByEngine(sel string) (int64, string, error)
- func (d *Doc) BackendForSelector(sel string) (int64, error)
- func (d *Doc) BaseURL() string
- func (d *Doc) BoundingBox(backendID int64) ([4]int, error)
- func (d *Doc) ByAlt(a string) []*Info
- func (d *Doc) ByLabel(label string) []*Info
- func (d *Doc) ByPlaceholder(p string) []*Info
- func (d *Doc) ByRole(role, name string) []*Info
- func (d *Doc) ByTestId(id string) []*Info
- func (d *Doc) ByText(s string, exact bool) []*Info
- func (d *Doc) ChildIDs(id int64) []int64
- func (d *Doc) CloneNode(id int64, deep bool) int64
- func (d *Doc) ComputedDisplay(n *html.Node) string
- func (d *Doc) ComputedVisibility(n *html.Node) string
- func (d *Doc) Count(sel string) int
- func (d *Doc) CreateComment(data string) int64
- func (d *Doc) CreateElement(tag, ns string) int64
- func (d *Doc) CreateFragment() int64
- func (d *Doc) CreateText(data string) int64
- func (d *Doc) DispatchEvent(backendID int64, typ string, detail string) error
- func (d *Doc) DocID() int64
- func (d *Doc) ElementBoxes(width int) []BoxRow
- func (d *Doc) ElementByID(id string) int64
- func (d *Doc) ElementFromPoint(x, y int) int64
- func (d *Doc) ElementsBy(rootID int64, kind, want string) []int64
- func (d *Doc) FirstChildID(id int64) int64
- func (d *Doc) FormFor(sel string) (method, action string, values map[string]string, err error)
- func (d *Doc) FormForBackend(id int64) (method, action string, values map[string]string, err error)
- func (d *Doc) FormOf(id int64) int64
- func (d *Doc) GeometryOf(backendID int64) (Geometry, bool)
- func (d *Doc) GetAttr(id int64, name string) (string, bool)
- func (d *Doc) GetAttribute(backendID int64, k string) (string, bool, error)
- func (d *Doc) GetChecked(id int64) bool
- func (d *Doc) GetValue(id int64) string
- func (d *Doc) IDOf(n *html.Node) int64
- func (d *Doc) InfoByBackend(backendID int64) *Info
- func (d *Doc) InlineStyleSheets() []string
- func (d *Doc) InnerHTML(backendID int64) (string, error)
- func (d *Doc) InputTarget(backendID int64) (tag, typ string, isSelect bool, err error)
- func (d *Doc) InsertAdjacentHTML(id int64, position, frag string) error
- func (d *Doc) InsertBefore(parentID, childID, refID int64) error
- func (d *Doc) IsConnected(id int64) bool
- func (d *Doc) IsScreenReaderOnly(n *html.Node) bool
- func (d *Doc) IsVisible(backendID int64) (bool, error)
- func (d *Doc) LastChildID(id int64) int64
- func (d *Doc) Layout(width int) *Layout
- func (d *Doc) LayoutWidth() int
- func (d *Doc) Matches(id int64, sel string) (bool, error)
- func (d *Doc) MutationGen() uint64
- func (d *Doc) Namespace(id int64) string
- func (d *Doc) NeedsScript() bool
- func (d *Doc) NextSiblingID(id int64) int64
- func (d *Doc) NodeByID(id int64) *html.Node
- func (d *Doc) NodeType(id int64) int
- func (d *Doc) NodeValue(id int64) string
- func (d *Doc) NthForSelector(sel string, nth int) (int64, error)
- func (d *Doc) OuterHTML(backendID int64) (string, error)
- func (d *Doc) PDFLines() []pdf.Line
- func (d *Doc) PaintGen() uint64
- func (d *Doc) ParentID(id int64) int64
- func (d *Doc) Predicate(kind, sel string, backendID int64) (bool, error)
- func (d *Doc) PrevSiblingID(id int64) int64
- func (d *Doc) QueryAllFrom(rootID int64, sel string) ([]int64, error)
- func (d *Doc) QueryFrom(rootID int64, sel string) (int64, error)
- func (d *Doc) QuerySelector(sel string) (*Info, error)
- func (d *Doc) QuerySelectorAll(sel string) ([]*Info, error)
- func (d *Doc) RefForBackend(id int64) int64
- func (d *Doc) RefState(ref int64) string
- func (d *Doc) RemoveAttr(id int64, name string)
- func (d *Doc) RemoveAttrQuiet(n *html.Node, name string)
- func (d *Doc) RemoveAttribute(backendID int64, k string) error
- func (d *Doc) RemoveChild(parentID, childID int64) error
- func (d *Doc) RemoveNode(sel string) error
- func (d *Doc) RenderText(width int) string
- func (d *Doc) ResolveEngine(sel string) ([]*Info, error)
- func (d *Doc) ScriptElement(id int64) *ScriptEl
- func (d *Doc) ScriptElements() []ScriptEl
- func (d *Doc) Scripts() []Script
- func (d *Doc) SelectOption(backendID int64, want string) error
- func (d *Doc) SelectOptions(backendID int64) ([]string, error)
- func (d *Doc) SelectedIndex(id int64) int
- func (d *Doc) Serialize(w io.Writer) error
- func (d *Doc) SerializeNode(id int64) string
- func (d *Doc) SetAttr(id int64, name, val string)
- func (d *Doc) SetAttrQuiet(n *html.Node, name, val string)
- func (d *Doc) SetAttribute(backendID int64, k, v string) error
- func (d *Doc) SetChecked(backendID int64, checked bool) error
- func (d *Doc) SetCheckedRaw(id int64, v bool)
- func (d *Doc) SetInnerHTML(backendID int64, frag string) error
- func (d *Doc) SetInnerHTMLCtx(id int64, frag string) error
- func (d *Doc) SetLayoutProvider(fn func(width int) *Layout)
- func (d *Doc) SetLayoutWidth(w int)
- func (d *Doc) SetMutationListener(fn func(Mutation))
- func (d *Doc) SetNodeValue(id int64, s string)
- func (d *Doc) SetSelectedIndex(id int64, i int)
- func (d *Doc) SetStylesheets(sheets []string, viewportWidth int, colorScheme string)
- func (d *Doc) SetTextContent(id int64, s string)
- func (d *Doc) SetValue(backendID int64, value string) error
- func (d *Doc) SnapshotInfos() []*Info
- func (d *Doc) StylesheetLinks() []string
- func (d *Doc) TagName(id int64) string
- func (d *Doc) Text(sel string) (string, error)
- func (d *Doc) TextByBackend(backendID int64) (string, error)
- func (d *Doc) TextContent(id int64) string
- func (d *Doc) Title() string
- func (d *Doc) Touch()
- func (d *Doc) TouchPaint()
- type Geometry
- type Info
- type Layout
- type Mutation
- type RequestRecord
- type Route
- type Script
- type ScriptEl
- type SelFeatures
- type Selector
- type SelectorEntry
- type SnapshotOptions
- type WireItem
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MatchRoute ¶
MatchRoute runs a route's handler against a request if the URL matches.
Types ¶
type BoxRow ¶
BoxRow is one element's box in document order, for fidelity scoring and diagnostics (every element appears; Has is false when it has no box).
type Doc ¶
Doc owns one parsed HTML tree. Node identity is a small integer issued by a per-document id table (see ids.go) that survives mutation; see idOf/find.
func ParseDocument ¶
func (*Doc) AppendChild ¶
func (*Doc) AppendHTML ¶
AppendHTML parses frag and appends it as children of the element matching sel (Playwright locator.evaluateHandle insertAdjacentHTML('beforeend')).
func (*Doc) AriaSnapshot ¶
AriaSnapshot returns the flattened accessibility tree (roles/names/refs) used by Page.snapshot. It never errors on an empty page.
func (*Doc) AriaSnapshotV2 ¶
func (d *Doc) AriaSnapshotV2(o SnapshotOptions) (string, error)
AriaSnapshotV2 renders the page as a Playwright-style accessibility tree in YAML. Every actionable node carries [ref=eN]; pass "eN" back to any action as its selector.
func (*Doc) AriaSnapshotYAML ¶
AriaSnapshotYAML renders the whole document with default options.
func (*Doc) BackendByEngine ¶
BackendByEngine resolves a Playwright-style selector to the first backend id.
func (*Doc) BackendForSelector ¶
BackendForSelector resolves a selector to its stable backend node id.
func (*Doc) BoundingBox ¶
BoundingBox returns the element's box from the flow layout (see layout.go).
func (*Doc) ByLabel ¶
ByLabel matches form controls by their associated <label for=>, aria-label, placeholder or title.
func (*Doc) ByPlaceholder ¶
ByPlaceholder matches controls by placeholder text.
func (*Doc) ByRole ¶
ByRole returns nodes whose computed ARIA role matches role, optionally filtered by accessible name (text/aria-label).
func (*Doc) ComputedDisplay ¶
ComputedDisplay returns the element's display value after the cascade: the winning declaration if any, else "none" for UA-hidden elements (head, script, style, template, …, and the hidden attribute), else "block" or "inline" from a tag table. Non-elements return "".
func (*Doc) ComputedVisibility ¶
ComputedVisibility returns "visible", "hidden" or "collapse". visibility inherits from the parent when the element does not set it.
func (*Doc) CreateComment ¶
func (*Doc) CreateElement ¶
func (*Doc) CreateFragment ¶
CreateFragment makes a detached container used for DocumentFragment.
func (*Doc) CreateText ¶
func (*Doc) DispatchEvent ¶
DispatchEvent is a semantic stand-in for page.dispatchEvent: Sweef's engine has no JS event listeners in pure-Go builds, so we translate the events agents actually rely on into tree mutations that keep state coherent.
func (*Doc) ElementBoxes ¶
ElementBoxes lists every element in document order with its layout box.
func (*Doc) ElementByID ¶
func (*Doc) ElementFromPoint ¶
ElementFromPoint returns the innermost element whose layout box contains (x, y), or 0. Smaller boxes win, then later document order (paint order).
func (*Doc) FirstChildID ¶
func (*Doc) FormForBackend ¶
FormForBackend is FormFor addressed by node id.
func (*Doc) FormOf ¶
FormOf returns the id of the enclosing <form> (or the form= target), 0 if none.
func (*Doc) GeometryOf ¶
GeometryOf returns precise element geometry when a layout provider is set.
func (*Doc) GetAttribute ¶
GetAttribute returns the value of attr k on the first node matching sel. For input/textarea controls, "value" falls back to the live current value.
func (*Doc) GetChecked ¶
func (*Doc) InfoByBackend ¶
InfoByBackend returns the serialisable node info for a backend id, or nil.
func (*Doc) InlineStyleSheets ¶
InlineStyleSheets returns the text of every <style> element in document order, skipping media="print". A <style> with another non-trivial media attribute is wrapped in an equivalent @media block so SetStylesheets can evaluate it.
func (*Doc) InputTarget ¶
InputTarget reports whether a backend node is a fillable form control and what kind (input/textarea/select).
func (*Doc) InsertAdjacentHTML ¶
func (*Doc) InsertBefore ¶
func (*Doc) IsConnected ¶
IsConnected reports whether the node is attached to the document root.
func (*Doc) IsScreenReaderOnly ¶
IsScreenReaderOnly reports whether n carries one of the common visually-hidden-but-accessible patterns (.sr-only / .visually-hidden): position:absolute with clip:rect(0 0 0 0) / clip-path:inset(50%), or a 1px×1px box with overflow:hidden. Such nodes stay in snapshots, as in Playwright; this is an informational helper only.
func (*Doc) IsVisible ¶
IsVisible approximates CSS visibility without layout: hidden attribute, aria-hidden, computed display:none/visibility:hidden (inline style and stylesheet rules) anywhere up the chain, and input[type=hidden] are invisible.
func (*Doc) LastChildID ¶
func (*Doc) LayoutWidth ¶
LayoutWidth is the viewport width used for boxes and hit-testing.
func (*Doc) MutationGen ¶
MutationGen returns a counter that increases on every tree or style mutation. The GUI compositor compares it between frames to decide whether a tab needs repainting (damage tracking) without polling the DOM.
func (*Doc) NeedsScript ¶
NeedsScript reports whether the document has anything for a JavaScript engine to do: a <script> element of a JavaScript type, or an inline event handler attribute (onclick=, onload=, ...). Pages without either can be served without creating a VM.
func (*Doc) NextSiblingID ¶
func (*Doc) NodeType ¶
NodeType returns the DOM nodeType constant (1 element, 3 text, 8 comment, 9 document, 10 doctype) or 0 for an unknown id.
func (*Doc) NthForSelector ¶
NthForSelector resolves the nth (0-based) match of a selector.
func (*Doc) PDFLines ¶
PDFLines flattens the visible document into the structured lines the PDF renderer lays out: headings, paragraphs, list items, links (with absolute hrefs for clickable annotations), form controls and preformatted blocks.
func (*Doc) PrevSiblingID ¶
func (*Doc) RefForBackend ¶
RefForBackend returns the snapshot ref for an internal id, assigning one when the node has not been listed yet (so nodes found through evaluate can be acted on). 0 for unknown ids and non-elements.
func (*Doc) RefState ¶
RefState classifies a snapshot ref for error messages: "attached", "detached" or "unknown".
func (*Doc) RemoveAttr ¶
func (*Doc) RemoveAttrQuiet ¶
RemoveAttrQuiet is the removal counterpart of SetAttrQuiet.
func (*Doc) RemoveChild ¶
func (*Doc) RemoveNode ¶
RemoveNode detaches the element matching sel from its parent.
func (*Doc) RenderText ¶
RenderText draws a crude but useful text-mode page render.
func (*Doc) ResolveEngine ¶
ResolveEngine parses Playwright selector syntax: css default, plus text=..., text="exact", role=button[name="Ok"], label=..., placeholder=..., alt=..., testid=..., and engine prefixes css=/xpath-less variants.
func (*Doc) ScriptElement ¶
ScriptElement describes one script by id, or nil.
func (*Doc) ScriptElements ¶
ScriptElements lists every <script> in document order.
func (*Doc) SelectOption ¶
SetValueByLabel matches <option> by visible text if no exact value match.
func (*Doc) SelectOptions ¶
SelectOptions lists option values under a <select>.
func (*Doc) SelectedIndex ¶
func (*Doc) SerializeNode ¶
SerializeNode renders one node (outerHTML) or "" when unknown.
func (*Doc) SetAttrQuiet ¶
SetAttrQuiet sets an attribute on n without notifying mutation listeners and without counting as a mutation for layout caching: it is for the engine's own markers (data-sweef-lite) written while the layout provider is running, which lays the document out again before returning. Callers outside the layout provider use SetAttrQuiet followed by Touch.
func (*Doc) SetChecked ¶
CheckState toggles checkbox/radio state in the tree.
func (*Doc) SetCheckedRaw ¶
func (*Doc) SetInnerHTMLCtx ¶
SetInnerHTMLCtx parses frag in the context of the element itself (so <tr> inside <table> parses correctly) and replaces its children.
func (*Doc) SetLayoutProvider ¶
SetLayoutProvider replaces the built-in flow layout with fn (the render engine). fn must not call Layout on the same Doc. Clears the cache.
func (*Doc) SetLayoutWidth ¶
SetLayoutWidth sets the viewport width (from emulation) for layout.
func (*Doc) SetMutationListener ¶
SetMutationListener installs (or clears, with nil) a callback fired on every tree mutation performed through this layer.
func (*Doc) SetNodeValue ¶
func (*Doc) SetSelectedIndex ¶
func (*Doc) SetStylesheets ¶
SetStylesheets parses sheets (in cascade order: inline <style> contents and fetched <link rel=stylesheet> bodies, document order) and installs the resulting rules. @media is evaluated against viewportWidth (px; 0 means 1280) and colorScheme ("light"/"dark"; "" means light). Calling it again replaces the previous rules and clears the cache.
func (*Doc) SetTextContent ¶
func (*Doc) SnapshotInfos ¶
SnapshotInfos flattens the v2 tree into Info records (Page.snapshot JSON).
func (*Doc) StylesheetLinks ¶
StylesheetLinks returns the href of every <link rel=stylesheet> in document order, skipping media="print", alternate and disabled sheets. rel="preload" as="style" is not a stylesheet and is not listed.
func (*Doc) TextContent ¶
TextContent is the raw concatenation of descendant text (no whitespace normalisation; scripts/styles included, per spec).
func (*Doc) Touch ¶
func (d *Doc) Touch()
Touch counts as a tree mutation for layout caching and repaint detection (MutationGen) without changing the tree. The engine uses it when resources that were deferred become available (lazy images).
func (*Doc) TouchPaint ¶
func (d *Doc) TouchPaint()
TouchPaint marks that pixels drawn into the document from outside the tree changed (a new video frame) without touching layout: the cached layout stays valid, only PaintGen moves, and a repaint is needed.
type Geometry ¶
type Geometry struct {
Client [4]float64 // getBoundingClientRect: x, y, w, h (transforms applied)
Border [4]float64 // untransformed border box (offsetLeft/Top/Width/Height basis)
ClientW, ClientH float64
ScrollW, ScrollH float64
Frags [][4]float64 // getClientRects
}
Geometry is the CSSOM View geometry of one element, in CSS px.
type Info ¶
type Info struct {
NodeID int64 `json:"nodeId"`
BackendID int64 `json:"backendNodeId"`
Ref int64 `json:"ref,omitempty"` // snapshot ref (eN), 0 if never listed
Name string `json:"name"`
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Role string `json:"role,omitempty"`
Text string `json:"text,omitempty"`
Href string `json:"href,omitempty"`
Visible bool `json:"visible"`
Disabled bool `json:"disabled"`
Checked bool `json:"checked,omitempty"`
Focusable bool `json:"focusable"`
}
Info mirrors engine.NodeInfo without import cycle (engine converts).
type Layout ¶
type Layout struct {
Width, Height int
Boxes map[*html.Node][4]int
Items []WireItem
// Set by a layout provider (the render engine): precise geometry and
// hit-testing. Nil for the built-in flow layout.
Hit func(x, y float64) *html.Node
Geo func(n *html.Node) (Geometry, bool)
Ext any // provider-private result (the engine keeps *render.Result here)
}
Layout is the result of one layout pass.
type Mutation ¶
type Mutation struct {
Op string `json:"op"` // set-attr | remove-attr | set-value | inner-html | check | select
BackendID int64 `json:"backendNodeId"`
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
}
Mutation describes a DOM change in Playwright-mutation-like terms. The engine subscribes so it can re-run init hooks / notify agents without reparsing.
type RequestRecord ¶
type RequestRecord struct {
Method string `json:"request.method"`
URL string `json:"request.url"`
FinalURL string `json:"response.url,omitempty"`
Status int `json:"response.status"`
Headers map[string]string `json:"request.headers,omitempty"`
ResponseHeaders map[string]string `json:"response.headers,omitempty"`
DurationMs int64 `json:"time"`
}
type Route ¶
Route implements Playwright-style interception: glob patterns matched on URL path; handler returns (status, body, handled).
type ScriptEl ¶
type ScriptEl struct {
ID int64
Src string
Type string
Async bool
Defer bool
Module bool
NoModule bool
Source string
}
ScriptEl describes one <script> element for the loader.
type SelFeatures ¶
type SelFeatures struct {
// Attrs are the attribute names the selector (or the pseudo-classes it
// uses) reads, lower case. "class" and "id" are included when used.
Attrs []string
// Sib: the element the selector is matched against depends on its
// siblings (+ ~ :nth-child :first-child :last-child :only-child
// :*-of-type, or the same inside :not()/:is() arguments).
Sib bool
// AncSib: an ancestor-side compound depends on its siblings, so the
// match can change when an ancestor's siblings change.
AncSib bool
// Empty: :empty is used (depends on the element's children).
Empty bool
// Complex: :has() or :scope; callers should not cache across mutations.
Complex bool
}
SelFeatures describes the inputs of a selector alternative.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector is a compiled selector list ("a, b > c").
func CompileSelector ¶
CompileSelector parses a selector list; a SyntaxError is returned when invalid.
func CompileSelectorQ ¶
CompileSelectorQ is CompileSelector with quirks-mode matching: class and id selectors compare ASCII case-insensitively.
func (*Selector) Entries ¶
func (s *Selector) Entries() []SelectorEntry
Entries returns the alternatives of the list, each matchable on its own.
type SelectorEntry ¶
type SelectorEntry struct {
Spec uint32 // ids<<20 | classes+attrs+pseudos<<10 | tags
// contains filtered or unexported fields
}
SelectorEntry is one comma-separated alternative with its specificity.
func (SelectorEntry) Features ¶
func (e SelectorEntry) Features() SelFeatures
Features reports what the alternative reads.
type SnapshotOptions ¶
type SnapshotOptions struct {
MaxChars int // hard cap on output bytes (0 = 60000)
Selector string // CSS selector or ref scoping the walk (default body)
InteractiveOnly bool // keep only ref-bearing nodes + their heading context
MaxTextLen int // characters kept per text/paragraph node (0 = 200)
MaxDepth int // 0 = unlimited
// Frame, when set, supplies the snapshot lines of the document inside an <iframe>
// element (already indented relative to the iframe line, refs qualified with the
// frame prefix it returns), so one snapshot covers the page and its frames.
Frame func(n *html.Node) (ref string, lines []string)
}
SnapshotOptions tune the size and scope of one snapshot.
type WireItem ¶
type WireItem struct {
Kind string // text | link | heading | button | input | checkbox | radio | select | img | hr | marker | box
X, Y int
W, H int
Text string
Scale int // glyph scale for text
Bold bool
Filled bool // checkbox/radio state
}
WireItem is one paintable thing in document order.