Documentation
¶
Overview ¶
Package devtools is the inspector a build from source carries: the bundle named brand.DevName, from magex app:build or app:run, and magex app:dev. A release, or a rehearsal of one, never does: only files built with the devtools tag import it, and only a build from source passes that tag (internal/repoguard and the magefiles' tests keep both so).
While the app runs, the inspector listens on a Unix socket in its data directory, readable by the user alone, and answers one request per connection, one JSON line in and JSON lines out (Request, Line). It keeps what the app has been doing in feeds that a client reads back or follows live: the log, every record from Debug up whatever the log file keeps (LogHandler); the events the services emit (Tee); and, from an agent it runs in the window's page on every load (Page), the page's console, the trail of what the user did there, clicks and keys, so a bug can be followed without the steps being told, and the notes the user leaves on elements they point at (⌥⌘P), each with what the element is and a picture of the window (Note), which it keeps in its folder in the data directory (InspectorDir), with whether the user lets pointing start, a choice the window's Settings show in a build from source alone. It also reads the database (read-only, through internal/store), runs JavaScript in the page and returns what it gives back, describes the page's elements and the inbox's cards as the web view lays them out, takes a picture of the window as the web view draws it, and dumps the goroutines.
The magex inspect:* targets are its client (Ask and Render), so the user, or an agent helping them, can look inside a running build from the terminal.
Index ¶
- Constants
- Variables
- func Ask(ctx context.Context, socket string, req Request, each func(Line) error) error
- func InspectorDir(dataDir string) string
- func Listen(ctx context.Context, path string) (net.Listener, error)
- func Outline(picture []byte, rect Rect, viewportWidth int) ([]byte, error)
- func Render(w io.Writer, line Line) error
- func SocketPath(dataDir string) string
- func Tee(next event.Sink, feed *Feed[EventEntry], now func() time.Time) event.Sink
- type About
- type Attr
- type CommandInfo
- type Config
- type ConsoleEntry
- type Database
- type Element
- type EventEntry
- type Feed
- type InspectorState
- type Line
- type LogEntry
- type LogHandler
- type Note
- type Notes
- func (s *Notes) Add(note Note) error
- func (s *Notes) Clear() (int, error)
- func (s *Notes) Counts() (open, kept int)
- func (s *Notes) Done(ns []int, all bool) (int, error)
- func (s *Notes) Follow() (<-chan Note, func())
- func (s *Notes) Len() int
- func (s *Notes) List(all bool) []Note
- func (s *Notes) Open(dir string) error
- func (s *Notes) Reserve() int
- type Page
- func (p *Page) Agent() string
- func (p *Page) Attach(exec func(js string))
- func (p *Page) AttachShot(shot func(ctx context.Context) ([]byte, error))
- func (p *Page) ClearNotes() (int, error)
- func (p *Page) Console() *Feed[ConsoleEntry]
- func (p *Page) Eval(ctx context.Context, code string) (json.RawMessage, error)
- func (p *Page) Info() PageInfo
- func (p *Page) MarkDone(ns []int, all bool) (int, error)
- func (p *Page) Notes() *Notes
- func (p *Page) OnChange(fn func(InspectorState))
- func (p *Page) Open(dir string, logger *slog.Logger) error
- func (p *Page) Receive(message string) bool
- func (p *Page) Run(js string) error
- func (p *Page) SetPointing(on bool) error
- func (p *Page) StartPointing() error
- func (p *Page) State() InspectorState
- func (p *Page) Trail() *Feed[TrailEntry]
- type PageInfo
- type Rect
- type Request
- type Server
- type Shot
- type Status
- type TrailEntry
- type WindowInfo
Constants ¶
const ( // LineLog holds a LogEntry, LineEvent an EventEntry, LineConsole a ConsoleEntry, // LineTrail a TrailEntry, and LineNote a Note. LineLog = "log" LineEvent = "event" LineConsole = "console" LineTrail = "trail" LineNote = "note" // LineResult holds any JSON value: what a script gave back, or what a command found. LineResult = "result" // LineTable holds a query's store.QueryResult, LineText a string to print as it is, // and LineShot a Shot. LineTable = "table" LineText = "text" LineShot = "shot" // LineError ends an answer that failed, holding why as a string; LineEnd ends one // that did not. LineError = "error" LineEnd = "end" )
The types of the lines of an answer.
const Prefix = "devtools:"
Prefix starts every message the agent posts to the app, so the app tells them from any other message the page sends it. The agent's script spells it too (agentScript).
const SocketName = "devtools.sock"
SocketName is the inspector's socket's name in the app's data directory.
Variables ¶
var ErrBadNoteList = errors.New("done= takes note numbers, as 2,3, or all")
ErrBadNoteList is returned for done= that names no notes: it takes note numbers, as 2,3, or all.
var ErrCutShort = errors.New("the app stopped answering")
ErrCutShort is returned when an answer stops before its end.
var ErrInUse = errors.New("another running copy of the app is inspected there")
ErrInUse is returned for a socket another running copy of the app answers on.
var ErrInspector = errors.New("the inspector refused")
ErrInspector is returned, with the inspector's words, for an answer that ended in an error.
var ErrMissingArg = errors.New("missing argument")
ErrMissingArg is returned for a command asked without an argument it needs.
var ErrNoAnswer = errors.New("the page did not answer in time")
ErrNoAnswer is returned when the page did not answer before the request's deadline, as when it was reloading.
var ErrNoWindow = errors.New("the window has not opened yet")
ErrNoWindow is returned for a request that needs the window's page before the window has opened.
var ErrNotRunning = errors.New("no build from source is running with the inspector on these data (start " + brand.DevName + " with magex app:run or magex app:dev, or pass data= for a sandbox)")
ErrNotRunning is returned when nothing answers on the inspector's socket.
var ErrPointingOff = errors.New("pointing is turned off in the window's Settings, under About → Inspector")
ErrPointingOff is returned for pointing asked for while the user has it turned off.
var ErrScript = errors.New("the script failed in the page")
ErrScript is returned, wrapped with what the page said, for JavaScript that threw.
var ErrUnknownCommand = errors.New("no such command; ask for help")
ErrUnknownCommand is returned for a command the inspector doesn't have.
Functions ¶
func Ask ¶
Ask sends req to the inspector listening at socket and hands each line of its answer to each, until the answer ends, ctx ends (which ends a follow without an error), or each fails.
func InspectorDir ¶
InspectorDir returns the inspector's folder in the data directory dataDir, where it keeps the notes the user leaves and its own settings, so they outlive the app. Only a build from source writes it.
func Listen ¶
Listen listens on the Unix socket at path for the inspector's clients, readable and writable by the user alone. A socket a run that ended left behind is removed first; one that another running copy of the app answers on is left alone, ErrInUse.
func Outline ¶
Outline returns the PNG picture with a box drawn just outside rect, where a note's element is in a viewport viewportWidth CSS pixels wide. The picture is in the web view's own pixels, two to a CSS pixel on a Retina screen, so rect is scaled by the picture's width over viewportWidth (1 when that is not known). The box is the blue the agent outlines the element with in the window: a strong one, unlike the app's accent and its muted Info blue in either theme. An empty rect leaves the picture as it was.
func Render ¶
Render writes line to w as a terminal shows it: a feed's entry on one line, stamped with its local time; a query's rows as a table; text as it is; any other value as indented JSON. A picture is the client's to save; Render only says its size.
func SocketPath ¶
SocketPath returns where the inspector of the app whose data directory is dataDir listens.
Types ¶
type About ¶
type About struct {
Version string `json:"version"`
Commit string `json:"commit"`
Flavor string `json:"flavor"`
PID int `json:"pid"`
Started time.Time `json:"started"`
Data string `json:"data"`
Database string `json:"database"`
Logs string `json:"logs"`
Socket string `json:"socket"`
Window WindowInfo `json:"window"`
}
About describes the running app: its build, the process, where its data is, and its window.
type CommandInfo ¶
type CommandInfo struct {
Command string `json:"cmd"`
Args string `json:"args,omitempty"`
About string `json:"about"`
}
CommandInfo describes one command, as help lists it.
type Config ¶
type Config struct {
Logs *Feed[LogEntry]
Events *Feed[EventEntry]
Page *Page
Database Database
// Shot takes a PNG of the window as its web view draws it.
Shot func(ctx context.Context) ([]byte, error)
// About describes the running app.
About func() About
// Now is the time: time.Now unless a test sets it.
Now func() time.Time
}
Config is what the inspector reads and runs.
type ConsoleEntry ¶
type ConsoleEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Text string `json:"text"`
}
ConsoleEntry is one line the page wrote to its console, or an error nothing caught.
type Database ¶
type Database interface {
// Query runs one statement that reads and returns at most maxRows of its rows.
Query(ctx context.Context, query string, maxRows int) (store.QueryResult, error)
// Tables lists the database's tables, with their row counts.
Tables(ctx context.Context) ([]store.TableInfo, error)
}
Database is the app's database as the inspector reads it: read-only.
type Element ¶
type Element struct {
Tag string `json:"tag"`
ID string `json:"id,omitempty"`
Classes string `json:"classes,omitempty"`
Role string `json:"role,omitempty"`
Name string `json:"name,omitempty"`
Rect Rect `json:"rect"`
Marks map[string]string `json:"marks,omitempty"`
}
Element is an element of the page as the agent describes it: its tag, id, classes, role, and name (its label, title, or text), where it is, and its data-* and aria-* attributes.
type EventEntry ¶
type EventEntry struct {
Time time.Time `json:"time"`
Name string `json:"name"`
Data json.RawMessage `json:"data,omitempty"`
}
EventEntry is one event a service emitted: its name, and what it carried as JSON.
type Feed ¶
type Feed[T any] struct { // contains filtered or unexported fields }
Feed keeps the last entries of one kind, oldest first, and hands each new one to every follower as it is added. It is safe for concurrent use.
func (*Feed[T]) Add ¶
func (f *Feed[T]) Add(entry T)
Add keeps entry, dropping the oldest once the feed is full, and hands it to every follower that has room for it.
func (*Feed[T]) Clear ¶
Clear drops every entry the feed keeps and returns how many it kept; its followers go on following.
func (*Feed[T]) Follow ¶
func (f *Feed[T]) Follow() (<-chan T, func())
Follow returns a channel that receives every entry added from now on, and the function that stops it and closes the channel. A follower that falls followerBuffer entries behind misses the entries added while it is full.
type InspectorState ¶
type InspectorState struct {
Enabled bool `json:"enabled"`
Open int `json:"open"`
Kept int `json:"kept"`
}
InspectorState is the inspector as the window's Settings and the menu bar show it: whether the user lets pointing start (Enabled), and how many notes are open, and kept in all, done or not.
type Line ¶
type Line struct {
Type string `json:"t"`
Value json.RawMessage `json:"v,omitempty"`
}
Line is one line of the inspector's answer: Type says what Value holds.
type LogEntry ¶
type LogEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"msg"`
Attrs []Attr `json:"attrs,omitempty"`
}
LogEntry is one record of the app's log.
type LogHandler ¶
type LogHandler struct {
// contains filtered or unexported fields
}
LogHandler is a slog.Handler that keeps every record from Debug up in a feed, whatever level the app's other handlers log at, so the inspector shows the debug records a run without --debug never writes to its log file.
func NewLogHandler ¶
func NewLogHandler(feed *Feed[LogEntry]) *LogHandler
NewLogHandler returns a handler that keeps records in feed.
func (*LogHandler) Handle ¶
Handle keeps r in the feed, with the attributes the handler was given before its own.
type Note ¶
type Note struct {
N int `json:"n"`
Time time.Time `json:"time"`
Text string `json:"text"`
Target string `json:"target"`
Where string `json:"where,omitempty"`
View string `json:"view,omitempty"`
Components string `json:"components,omitempty"`
Source string `json:"source,omitempty"`
Nearby string `json:"nearby,omitempty"`
Element Element `json:"element"`
Styles [][2]string `json:"styles,omitempty"`
ViewportWidth int `json:"viewportWidth"`
ViewportHeight int `json:"viewportHeight"`
Done bool `json:"done,omitempty"`
Shot []byte `json:"shot,omitempty"`
ShotError string `json:"shotError,omitempty"`
}
A Note is what the user said about an element they pointed at in the window (⌥⌘P, or inspect:point): their words; the control it is in as the trail names it (Target), and where (Where); the view the window showed; the element as the agent describes it, its computed styles that are set, as name and value, and its text around it; under React's development build (app:dev), the components that render it, outermost first, and the file whose JSX made it, its line approximate; the viewport's size; and a picture of the window, taken as the note came, the element boxed (Outline), or why there is none. N numbers the notes from 1, after the last one kept; Done is set once the note is dealt with (inspect:notes done=).
type Notes ¶
type Notes struct {
// contains filtered or unexported fields
}
Notes keeps the notes the user leaves, the last limit of them, oldest first: in a folder once it has one (Open), each as <n>.json with its picture as <n>.png, so they outlive the app, and in memory alone until then. It hands each new note to its followers. It is safe for concurrent use.
func (*Notes) Add ¶
Add keeps note, with its picture in note.Shot, dropping the oldest beyond the limit, and hands it to the followers. A note it can't write to the folder is still kept in memory, and the error says why.
func (*Notes) Clear ¶
Clear drops every note kept, from the folder too, and returns how many there were.
func (*Notes) Done ¶
Done marks done the open notes numbered ns, or every open note when all, and returns how many it marked.
func (*Notes) Follow ¶
Follow returns a channel that receives each note added from now on, with its picture, and the function that stops it, as Feed.Follow.
func (*Notes) List ¶
List returns the notes kept, oldest first, each with its picture: the open ones, or all of them with all.
type Page ¶
type Page struct {
// contains filtered or unexported fields
}
Page is the inspector's way into the window's page, through the agent the page runs: the app runs JavaScript there (Eval) through the window's ExecJS, which Attach hands it, and hands back each message the page posts (Receive), which carries an evaluation's result, a console line, an entry of the user's trail, a note the user left on an element, the user's choices in the inspector's part of Settings, or the page describing itself. It also keeps those notes and choices (inspector.go). It is safe for concurrent use.
func NewPage ¶
NewPage returns a page with no window yet, keeping the console's last consoleSize lines, the trail's last trailSize entries, and the last noteSize notes, stamped with now. Pointing may start until the user turns it off.
func (*Page) Agent ¶
Agent returns the script that installs the agent in the page, for the window to run on every page load.
func (*Page) AttachShot ¶
AttachShot gives the page the window's way to take a picture of itself, for each note the user leaves to keep one.
func (*Page) ClearNotes ¶
ClearNotes drops every note kept, and returns how many there were.
func (*Page) Console ¶
func (p *Page) Console() *Feed[ConsoleEntry]
Console returns the feed of the page's console.
func (*Page) Eval ¶
Eval runs code in the page, with the agent's helpers as nb, and returns what it gave back as JSON, once a promise it returns settles. code is an expression, or statements that return a value; it fails with ErrScript when it throws, ErrNoWindow before the window opens, and ErrNoAnswer when ctx ends first.
func (*Page) MarkDone ¶
MarkDone marks done the open notes numbered ns, or every open note with all, and returns how many it marked.
func (*Page) OnChange ¶
func (p *Page) OnChange(fn func(InspectorState))
OnChange has fn hear the inspector's state each time the page is told it: as the page loads, and after each change.
func (*Page) Open ¶
Open keeps the inspector's notes and settings in dir (InspectorDir) from now on, reading back what is kept there, and logs through logger what it can't keep there later. A settings file it can't read leaves pointing on, and the error says why.
func (*Page) Receive ¶
Receive handles message, which the page posted to the app: it reports false, doing nothing, for a message that is not the agent's.
func (*Page) Run ¶
Run runs js in the page without waiting for anything back, or returns ErrNoWindow.
func (*Page) SetPointing ¶
SetPointing lets pointing start, or stops it from starting and ends it, and keeps the choice.
func (*Page) StartPointing ¶
StartPointing turns pointing on in the window, as ⌥⌘P does there, or returns ErrPointingOff while the user has it turned off.
func (*Page) Trail ¶
func (p *Page) Trail() *Feed[TrailEntry]
Trail returns the feed of what the user did in the page.
type PageInfo ¶
type PageInfo struct {
Loaded time.Time `json:"loaded"`
URL string `json:"url"`
Title string `json:"title"`
Width int `json:"width"`
Height int `json:"height"`
Scale float64 `json:"scale"`
UserAgent string `json:"userAgent"`
}
PageInfo is the page as the agent last described it: when it loaded, its address and title, and its viewport.
type Rect ¶
type Rect struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
Rect is where the web view lays an element out: in CSS pixels, from the viewport's top left.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server answers the inspector's clients, one request per connection.
type Shot ¶
type Shot struct {
PNG []byte `json:"png"`
}
Shot is a picture of the window as the web view draws it.
type Status ¶
type Status struct {
About
Uptime string `json:"uptime"`
Go string `json:"go"`
Goroutines int `json:"goroutines"`
HeapMB float64 `json:"heapMB"`
SysMB float64 `json:"sysMB"`
GCs uint32 `json:"gcs"`
Page PageInfo `json:"page"`
Kept map[string]int `json:"kept"`
}
Status is what the status command answers: the app as About describes it, how long it has run, its Go runtime's numbers, the page, and how many entries each feed keeps.
type TrailEntry ¶
type TrailEntry struct {
Time time.Time `json:"time"`
Kind string `json:"kind"`
Target string `json:"target"`
Where string `json:"where,omitempty"`
}
TrailEntry is one thing the user did in the page: a click, a key, typing in a field, or a choice changed, with what it was done to, and where.
type WindowInfo ¶
type WindowInfo struct {
Open bool `json:"open"`
Visible bool `json:"visible"`
Focused bool `json:"focused"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
WindowInfo is the app's window as the inspector describes it: whether it has opened, whether it shows and has focus, and where it is on the screen, in points.