render

package
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 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 render implements the chromedp-backed SVG resize, the pure-Go svg.Hash, the SVG decoration pipeline (octicon / CSS purge / XML format), and the small Renderer interface that engine.Compute consumes. Chromedp imports live behind a build tag so the default `go test ./...` run stays usable without a chromium binary.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply(stages []PipelineStage, in string) (string, []error)

Apply runs the stages in order. The returned string is the final SVG after all (successful) stages. Errors are returned alongside in registration order, each wrapped with the offending stage's name. Apply never panics on stage errors and never short-circuits on a failure: the caller decides whether to treat collected errors as fatal.

func FormatXML

func FormatXML(in string) (string, error)

FormatXML returns a re-indented copy of the input XML/SVG payload. The output uses two-space indentation, a single `\n` line separator, and emits empty elements as self-closing `<foo/>` tokens (matching the upstream xml-formatter `collapseContent=true` knob) — EXCEPT for non-void HTML elements inside <foreignObject>, which keep an explicit `</foo>` close tag because the render-measurement step re-parses the SVG as HTML (where `<div/>` would be an unclosed element). See the EndElement handling for details.

Whitespace-only text nodes are discarded; non-empty text content inside an element ends up on its own line. CDATA, processing instructions, comments, and numeric character references survive the round trip via encoding/xml's standard tokenizer.

The function is intentionally permissive: malformed input bubbles up as an error so the engine dispatch can append it to res.Errors (FR-018) and fall back to the prior pipeline stage's output.

func Hash

func Hash(rendered string) (string, error)

Hash returns the MD5 hex digest (32 lowercase chars) of the SVG's outer HTML after the first <footer> element is removed. The hash is the comparison key that backs `output_condition=data-changed` (M6 T-114): two SVGs whose DOM differs only in the footer (timezone / version / generated time) MUST hash identically.

Edge cases:

  • Whitespace-only or empty input → ("", nil)
  • Document without an <svg> root → ("", *xerrors.InputError)
  • Multiple <footer> nodes → only the first one is removed

The implementation is pure Go (goquery / crypto/md5); no chromedp dependency lands on the hash path.

func OptimizeCSS

func OptimizeCSS(in string) (string, error)

OptimizeCSS walks the embedded `<style data-optimizable="true">` nodes, drops selectors that no element in the document matches, and minifies the result. Selectors that contain an ID component (`#metrics-end`, `#header`, etc.) are kept unconditionally so the svg.Resize anchor / template scaffold stays addressable even if no CSS targets it in the body (FR-015 + SC-006).

CSS embedded in `<style>` tags without the `data-optimizable="true"` attribute is left as-is — that's the upstream contract for opting out per template.

func ReplaceOcticons

func ReplaceOcticons(in string) (string, error)

ReplaceOcticons swaps every `:octicon-<name>(-<size>)?:` placeholder in `in` for the matching SVG fragment from assets/octicons/data.json, injecting `class="octicon"` so downstream CSS targets it. Unknown (name, size) combinations pass through verbatim.

The function is idempotent: ReplaceOcticons(ReplaceOcticons(in)) equals ReplaceOcticons(in) because the rendered `<svg class="octicon">` fragments no longer contain the source placeholder pattern.

Types

type Browser

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

Browser owns a single chromedp ExecAllocator plus the parent context it spawns tabs from. A Browser is safe for concurrent use; NewTab serializes against the internal recycle mutex.

Upstream-compatible defaults:

  • --no-sandbox, --disable-extensions, --disable-dev-shm-usage, --disable-gpu, --single-process.
  • METRICS_CHROME_PATH env var resolves the chromium executable when BrowserOpts.ExecPath is empty.
  • Recycle counter trips at BrowserOpts.RecycleEvery (defaults to 200, upstream `svg.resize.browser` parity).

func New

func New(opts BrowserOpts) (*Browser, error)

New constructs a Browser. The returned instance owns chromedp resources; callers MUST call Close when done.

When BrowserOpts.ExecPath is non-empty, the file is stat-checked up front so a missing chromium binary fails fast instead of producing a confusing chromedp.WaitProcess error several seconds later.

func (*Browser) Close

func (b *Browser) Close() error

Close cancels the allocator and waits for cleanup. Idempotent. Subsequent NewTab calls return an *InputError.

func (*Browser) NewTab

NewTab returns a child context bound to a fresh chromedp tab. Callers MUST call the returned cancel func (typically via defer) when finished with the tab. The supplied parent ctx provides the cancellation / deadline plumbing for the caller; chromedp tabs are spawned from b.parentCtx so they survive the parent ctx going out of scope until cancel runs.

NewTab transparently recycles the underlying allocator after every `RecycleEvery` invocations to avoid long-lived chromium memory growth. Concurrent NewTab calls block during a recycle.

func (*Browser) RecycledCount

func (b *Browser) RecycledCount() int

RecycledCount returns how many allocator re-inits have occurred since construction. Exposed for tests so we can assert that the recycle-every-N counter trips at the expected moment without reaching into private fields.

func (*Browser) Resize

func (b *Browser) Resize(ctx context.Context, in string, opts ResizeOpts) (ResizeResult, error)

Resize implements Renderer. It opens a fresh chromedp tab, injects the rendered SVG into about:blank, runs the upstream-derived measurement JS, optionally rasterizes to PNG/JPEG, and returns the final bytes plus the post-padding dimensions.

Chromedp errors (start failure, evaluate failure, tab teardown) are wrapped as *xerrors.RetryableError so the engine dispatch can surface them via Result.Errors while preserving the typed shape callers match on with errors.As.

type BrowserOpts

type BrowserOpts struct {
	// ExecPath, when non-empty, overrides chromedp's auto-detect path
	// for the chromium / chrome binary. Falls back to the
	// METRICS_CHROME_PATH env var when empty.
	ExecPath string
	// RecycleEvery sets how many NewTab calls trigger an allocator
	// re-init. Zero falls back to the default (200).
	RecycleEvery int
	// Headless toggles the --headless flag. Default true. Set false
	// only for local debugging via --puppeteer-disable-headless.
	Headless bool
	// ExtraFlags are appended to the chromedp ExecAllocator option
	// set after the upstream-compatible defaults are applied.
	ExtraFlags []chromedp.ExecAllocatorOption
	// Logger is used for debug / warn events. nil falls back to
	// slog.Default().
	Logger *slog.Logger
}

BrowserOpts captures the construction-time configuration. Zero values map to upstream-compatible defaults.

type FakeRenderer

type FakeRenderer struct {
	// Width / Height override the returned ResizeResult dimensions.
	// Zero falls back to 1 so image.Decode-style callers still see a
	// valid bounding box.
	Width, Height int
	// ErrOnConvert, when non-nil, maps a Convert value to the error
	// Resize should return for that branch. e.g. {"png": sentinel}.
	ErrOnConvert map[string]error
}

FakeRenderer returns deterministic, minimal bytes for tests. Use only in _test.go files or build-tagged fixtures: production code always uses *Browser. The fake never starts chromium and never touches the network.

func NewFakeRenderer

func NewFakeRenderer() *FakeRenderer

NewFakeRenderer constructs a zero-value FakeRenderer for callers that prefer a constructor over a struct literal.

func (*FakeRenderer) Resize

func (f *FakeRenderer) Resize(_ context.Context, in string, opts ResizeOpts) (ResizeResult, error)

Resize implements Renderer. SVG / "" passes the input through as bytes; PNG / JPEG returns a hard-coded minimal valid image.

type ImageFetcher added in v1.1.0

type ImageFetcher interface {
	ImgB64(ctx context.Context, target string) (string, error)
}

ImageFetcher fetches a remote image and returns a `data:<mime>;base64,<payload>` URI suitable for embedding directly in SVG/HTML. *httpx.Client satisfies this via its ImgB64 method.

type PipelineStage

type PipelineStage struct {
	// Name labels the stage in error wrapping and debug logs.
	Name string
	// Run takes the current SVG and returns the next SVG. Any error
	// is surfaced via Apply's []error return; the input string is
	// forwarded to the next stage unchanged (best-effort chain).
	Run func(in string) (string, error)
}

PipelineStage is the function signature each decoration / optimization step exposes. Stages are composed by Apply.

func InlineImagesStage added in v1.1.0

func InlineImagesStage(ctx context.Context, fetcher ImageFetcher) PipelineStage

InlineImagesStage returns a decoration stage that rewrites every remote `<img src="http(s)://...">` in the SVG into a self-contained `data:` URI by fetching the resource through fetcher.

Why this exists: GitHub renders embedded SVGs through its camo image proxy, which does not resolve external resources referenced from inside the SVG — the `<img>` tags the avatar / icon partials emit (base.header avatar, people, contributors, sponsors, sponsorships, topics). An SVG that keeps `src="https://avatars.githubusercontent.com/..."` therefore shows broken icons on GitHub and anywhere the file is opened offline. Inlining each image as base64 makes the SVG self-contained.

Best-effort (FR-018): URLs that are already inline (`data:`) or use a non-http scheme pass through untouched, and a fetch failure leaves the original URL in place while the error is aggregated into Apply's []error. Each distinct URL is fetched at most once per invocation.

type Renderer

type Renderer interface {
	Resize(ctx context.Context, in string, opts ResizeOpts) (ResizeResult, error)
}

Renderer is the abstraction engine.Compute uses to convert a rendered SVG string into final SVG/PNG/JPEG bytes. It exists so the engine package never imports chromedp directly: production code injects a *Browser via Deps.Render, tests inject a *FakeRenderer.

type ResizeOpts

type ResizeOpts struct {
	// Convert ∈ {"", "svg", "png", "jpeg"}. Empty is normalized to
	// "svg". Anything else is reported as *UnsupportedFormatError by
	// normalize.
	Convert string
	// Padding mirrors the upstream `config.padding` input format:
	// either a single string "<abs> + <rel>%" or two strings
	// [width-padding, height-padding] / one comma-separated string.
	Padding []string
	// Scripts is the list of user JS bodies to evaluate before
	// measuring. Each entry is wrapped into `(async () => { ... })()`
	// by the resize JS template.
	Scripts []string
	// ViewportWidth / ViewportHeight default to 980/980 when zero.
	ViewportWidth, ViewportHeight int
	// SettleDelay overrides the post-script sleep. Zero falls back to
	// 2.4 seconds (upstream parity).
	SettleDelay time.Duration
}

ResizeOpts captures the per-call parameters of Resize. Slices are read-only after construction.

type ResizeResult

type ResizeResult struct {
	// Body holds the serialized payload — SVG bytes for ""/"svg",
	// raw PNG bytes for "png", raw JPEG bytes for "jpeg".
	Body []byte
	// Width / Height are the post-padding integer dimensions written
	// back into the <svg> root (Height only) and recorded for
	// diagnostics.
	Width, Height int
	// MIME is the IANA type matching Body, one of
	// "image/svg+xml" | "image/png" | "image/jpeg".
	MIME string
}

ResizeResult is the value Resize returns on success.

Jump to

Keyboard shortcuts

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