devtools

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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).

View Source
const SocketName = "devtools.sock"

SocketName is the inspector's socket's name in the app's data directory.

Variables

View Source
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.

View Source
var ErrCutShort = errors.New("the app stopped answering")

ErrCutShort is returned when an answer stops before its end.

View Source
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.

View Source
var ErrInspector = errors.New("the inspector refused")

ErrInspector is returned, with the inspector's words, for an answer that ended in an error.

View Source
var ErrMissingArg = errors.New("missing argument")

ErrMissingArg is returned for a command asked without an argument it needs.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
var ErrScript = errors.New("the script failed in the page")

ErrScript is returned, wrapped with what the page said, for JavaScript that threw.

View Source
var ErrUnknownCommand = errors.New("no such command; ask for help")

ErrUnknownCommand is returned for a command the inspector doesn't have.

Functions

func Ask

func Ask(ctx context.Context, socket string, req Request, each func(Line) error) error

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

func InspectorDir(dataDir string) string

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

func Listen(ctx context.Context, path string) (net.Listener, error)

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

func Outline(picture []byte, rect Rect, viewportWidth int) ([]byte, error)

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

func Render(w io.Writer, line Line) error

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

func SocketPath(dataDir string) string

SocketPath returns where the inspector of the app whose data directory is dataDir listens.

func Tee

func Tee(next event.Sink, feed *Feed[EventEntry], now func() time.Time) event.Sink

Tee returns a Sink that keeps every event in feed, stamped with now, then hands it on to next.

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 Attr

type Attr struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

Attr is one attribute of a log record, its key dotted with its groups' names.

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 NewFeed

func NewFeed[T any](capacity int) *Feed[T]

NewFeed returns a feed that keeps the last capacity entries.

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

func (f *Feed[T]) Clear() int

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.

func (*Feed[T]) Last

func (f *Feed[T]) Last(n int) []T

Last returns the last n entries kept, oldest first; n of 0 or less returns them all.

func (*Feed[T]) Len

func (f *Feed[T]) Len() int

Len returns how many entries the feed keeps now.

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) Enabled

func (h *LogHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether a record at level is kept: Debug and up are.

func (*LogHandler) Handle

func (h *LogHandler) Handle(_ context.Context, r slog.Record) error

Handle keeps r in the feed, with the attributes the handler was given before its own.

func (*LogHandler) WithAttrs

func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a handler that adds attrs to every record it keeps.

func (*LogHandler) WithGroup

func (h *LogHandler) WithGroup(name string) slog.Handler

WithGroup returns a handler whose records' attributes are keyed under name.

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 NewNotes

func NewNotes(maxNotes int) *Notes

NewNotes returns notes that keep the last maxNotes notes, in memory until Open.

func (*Notes) Add

func (s *Notes) Add(note Note) error

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

func (s *Notes) Clear() (int, error)

Clear drops every note kept, from the folder too, and returns how many there were.

func (*Notes) Counts

func (s *Notes) Counts() (open, kept int)

Counts returns how many of the notes kept are open, and how many there are.

func (*Notes) Done

func (s *Notes) Done(ns []int, all bool) (int, error)

Done marks done the open notes numbered ns, or every open note when all, and returns how many it marked.

func (*Notes) Follow

func (s *Notes) Follow() (<-chan Note, func())

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) Len

func (s *Notes) Len() int

Len returns how many notes are kept.

func (*Notes) List

func (s *Notes) List(all bool) []Note

List returns the notes kept, oldest first, each with its picture: the open ones, or all of them with all.

func (*Notes) Open

func (s *Notes) Open(dir string) error

Open keeps the notes in dir from now on, making it when it is missing, and reads back the notes kept there, the last limit of them; a note it can't read is left out. Notes kept in memory before go on the disk too.

func (*Notes) Reserve

func (s *Notes) Reserve() int

Reserve returns the number the next note takes.

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

func NewPage(consoleSize, trailSize, noteSize int, now func() time.Time) *Page

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

func (p *Page) Agent() string

Agent returns the script that installs the agent in the page, for the window to run on every page load.

func (*Page) Attach

func (p *Page) Attach(exec func(js string))

Attach gives the page the window's way to run JavaScript in it.

func (*Page) AttachShot

func (p *Page) AttachShot(shot func(ctx context.Context) ([]byte, error))

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

func (p *Page) ClearNotes() (int, error)

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

func (p *Page) Eval(ctx context.Context, code string) (json.RawMessage, error)

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) Info

func (p *Page) Info() PageInfo

Info returns the page as the agent last described it.

func (*Page) MarkDone

func (p *Page) MarkDone(ns []int, all bool) (int, error)

MarkDone marks done the open notes numbered ns, or every open note with all, and returns how many it marked.

func (*Page) Notes

func (p *Page) Notes() *Notes

Notes returns the notes the user left on elements they pointed at.

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

func (p *Page) Open(dir string, logger *slog.Logger) error

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

func (p *Page) Receive(message string) bool

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

func (p *Page) Run(js string) error

Run runs js in the page without waiting for anything back, or returns ErrNoWindow.

func (*Page) SetPointing

func (p *Page) SetPointing(on bool) error

SetPointing lets pointing start, or stops it from starting and ends it, and keeps the choice.

func (*Page) StartPointing

func (p *Page) StartPointing() error

StartPointing turns pointing on in the window, as ⌥⌘P does there, or returns ErrPointingOff while the user has it turned off.

func (*Page) State

func (p *Page) State() InspectorState

State returns the inspector's state now.

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 Request

type Request struct {
	Command string            `json:"cmd"`
	Args    map[string]string `json:"args,omitempty"`
}

Request is what a client asks the inspector: the first line a connection carries.

type Server

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

Server answers the inspector's clients, one request per connection.

func NewServer

func NewServer(cfg Config) *Server

NewServer returns a server over cfg.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve answers the clients that connect to ln until ctx ends, then closes ln and returns once every answer has stopped.

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.

Jump to

Keyboard shortcuts

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