static

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 45 Imported by: ? 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.

README

Fletch Static

Static site export, hybrid prerendering, Markdown collections, feeds, search, OG images, and direct host deployment for Fletch apps. Pure Go (CGO_ENABLED=0), zero Node.

Install

go get github.com/fletchhq/static

Adding github.com/fletchhq/static to a Fletch app's go.mod lets fletch ax sync and fletch docs discover docs/static.md and skills/static/SKILL.md automatically.

Quick start

Scaffold a static marketing or documentation site with the Fletch CLI:

fletch new mysite --site
cd mysite
fletch dev

fletch new --site sets up a Crest layout, a content/ directory, bootstrap/static.go, and built-in export and preview commands without database or Nock boilerplate. During development, fletch dev watches content/** and triggers a browser reload event without recompiling Go. The Dev Dashboard Static panel reads .fletch/static/last-export.json to display your latest export summary alongside S001–S016 and SEO diagnostics.

When you are ready to build or inspect the static output:

# Run code generation, build assets, compile, and export
fletch export

# Export and start the pure-Go target-emulating preview server
fletch export --serve

Host targets

static ships five output targets and a pure-Go preview server that emulates all five locally:

  • cloudflare (default)
  • vercel (Build Output API v3 by default; pass --vercel-json for vercel.json output)
  • netlify
  • github-pages (alias gh-pages; supports --base, --cname, and --write-workflow, with HTML redirect stubs and meta CSP)
  • plain (static files plus static-manifest.json)

Hybrid prerendering and embedded exports

You do not have to export an entire application to get static speed on hot routes. static.Prerender caches rendered snapshots inside a live Fletch app with strong ETag/304, precomputed br/gzip, hashed CSP replacement, single-flight stale-while-revalidate, and on-demand invalidation (Invalidate, Refresh, and multi-node fan-out via static.InvalidateOn).

If you prefer a single self-contained binary, embed a plain export with //go:embed all:dist and serve it with static.FromFS. It reads static-manifest.json for clean URLs, redirects, custom headers, 404.html, strong ETag/304, and br/gzip.

Packages

Package Purpose
github.com/fletchhq/static Static exporter, all 5 host targets, pure-Go preview server, split deploy with a Fletch backend (Backend, Live shells, verify-backend), hybrid Prerender, FromFS, and InvalidateOn
github.com/fletchhq/static/content Typed Markdown content collections with validated frontmatter, GFM, callouts, code tabs, components, and hot reload (separate module)
github.com/fletchhq/static/content/highlight Opt-in Chroma syntax highlighting with a Crest lexer and Fletch light/dark CSS (+3.75 MiB / +3.32 MiB stripped; median 118–127 µs per block; separate module)
github.com/fletchhq/static/og Pure-Go 1200×630 Open Graph card renderer and cached http.Handler (separate module)
github.com/fletchhq/static/feed Deterministic RSS, Atom, and JSON Feed HTTP handlers and pure renderers
github.com/fletchhq/static/search Pure-Go static search index and CSP-safe browser client reading data-pagefind-* attributes
github.com/fletchhq/static/seo Static SEO checks (SEO001–SEO007) for static.Checks
github.com/fletchhq/static/deploy/cloudflare Pure-Go, stdlib-only direct uploader for Cloudflare Workers Static Assets
github.com/fletchhq/static/deploy/netlify Pure-Go, stdlib-only direct uploader for Netlify's SHA-1 file-digest Deploy API
github.com/fletchhq/static/statictest Test helpers for static exports and handlers

examples/brochure is a five-page site with a Formspree form, the Alpine CSP build, and secure.New, exported with no Node.

examples/split is a static brochure whose Live counter, contact form and /app/* run on a Fletch backend: go run . preview --backend auto runs both on one machine.

Documentation

See docs/static.md for the full guide, target details, hybrid prerendering options, direct deployers, split deploy, and S001–S036 / SEO001–SEO007 diagnostic reference.

License

MIT or Apache-2.0, at your option. See LICENSE-MIT and LICENSE-APACHE.

Documentation

Overview

Package static exports a Fletch (or plain router) app as a static site.

Every page of a Fletch app is an http.Handler, so the exporter renders the app in process, captures the responses, and writes them out with the host files a static host needs: redirects, headers, and a 404 page. Per-request CSP nonces become SHA-256 hashes, and static-safety checks (S001 to S016) catch pages that cannot work without a server.

The package does not import the root fletch module; it takes any App, which *fletch.App satisfies.

Index

Constants

View Source
const (
	CodeLive             = "S001" // a Live route or data-f-live markup
	CodeCSRF             = "S002" // a same-origin POST form with a CSRF field
	CodeSetCookie        = "S003" // Set-Cookie on a response
	CodeStatus           = "S004" // an unexpected status or a bad 404 probe
	CodeBrokenLink       = "S005" // a broken link or a missing #fragment
	CodeNondeterministic = "S006" // two renders differ (--verify)
	CodeInlineHandler    = "S007" // on*= or style= under a hash CSP
	CodeScriptOrigin     = "S008" // a cross-origin script origin was allowlisted
	CodePrivateCache     = "S009" // private/no-store or Vary: Cookie
	CodeBaseLiteral      = "S010" // a root-relative URL in inline JS with Base set
	CodePathCollision    = "S011" // two URLs on one output file
	CodeHostLimit        = "S012" // a host limit or a host-file merge conflict
	CodeNonceReuse       = "S013" // the nonce appears outside nonce attributes
	CodeHeaderLost       = "S014" // the target cannot express a header
	CodeContentType      = "S015" // Content-Type and file extension disagree
	CodeNotPublic        = "S016" // an exported or linked page needs auth or is excluded

	// Split deploy (static.Backend): export-time proofs.
	CodeSplitConfig   = "S017" // a split-deploy option names nothing or is malformed
	CodeLiveEndpoint  = "S018" // the backend does not serve a shell's Live endpoint or contract for the site
	CodeCORS          = "S019" // the Live endpoint's CORS preflight does not allow the site
	CodeRewritten     = "S020" // links and forms were rewritten to the backend (info)
	CodeCrossSite     = "S021" // Credentials with a backend on another site
	CodeTargetSplit   = "S022" // the target cannot proxy or rewrite as asked
	CodeShellAuth     = "S023" // a Live shell's Mount needs a user or redirects
	CodeSplitCSP      = "S024" // CSP sources the backend needs (added, or missing under CSPStrict)
	CodeBackendURL    = "S025" // the backend URL is unusable
	CodeSplitConflict = "S026" // a path is both Dynamic and exported or rewritten
	CodeShellLeak     = "S027" // a shell carries a session id or CSRF token

	// Split deploy: network verification (verify-backend).
	CodeProtocol    = "S031" // the backend speaks another Live protocol
	CodeBuildSkew   = "S032" // the backend runs another build (warning; error with --require-build-match)
	CodeTemplate    = "S033" // the backend serves another template than the shell was built from
	CodeLiveProbe   = "S034" // the Live probe failed over WebSocket (and SSE)
	CodeProxyRules  = "S035" // the site does not proxy to the backend
	CodeUnreachable = "S036" // the backend is down or not ready
)

Diagnostic codes. Each is documented in docs/static.md.

View Source
const (
	CSPNone    = "none"
	CSPGlobal  = "global"
	CSPPerPath = "per-path"
	CSPMeta    = "meta"
)

CSP emission strategies, recorded in the Report.

View Source
const (
	LivePrefix   = "/_fletch/live"
	ContractPath = "/_fletch/contract"
	// ManifestFile is where a split export describes itself, relative to
	// the site root. verify-backend and the preview read it.
	ManifestFile = "_fletch/static.json"
)

Paths a Fletch backend owns in every split topology.

View Source
const (
	// TopologySeparate serves the site and the backend from two origins;
	// shells join the backend's absolute Live endpoint.
	TopologySeparate = "separate"
	// TopologyProxy has the static host proxy Dynamic paths, Live
	// endpoints and the contract to the backend, so everything is
	// same-origin.
	TopologyProxy = "proxy"
	// TopologyMixed proxies HTTP paths but joins Live on the backend
	// origin (LiveDirect).
	TopologyMixed = "mixed"
)

Topologies of a split deploy, as recorded in the Manifest.

View Source
const LastExportFile = ".fletch/static/last-export.json"

LastExportFile is where the export command keeps a copy of its Report, outside the output directory, for the dev dashboard and agents.

View Source
const WorkerFile = "fletch-proxy.js"

WorkerFile is the Cloudflare Worker a proxied split export writes next to its assets. .assetsignore keeps it from being uploaded as an asset.

Variables

View Source
var ErrExport = errors.New("static: export has errors")

ErrExport is wrapped by the error Export returns when an error diagnostic not named in ExportOptions.Allow was found. The Report lists them.

View Source
var ErrVerify = errors.New("static: backend verification failed")

ErrVerify is wrapped by the error VerifyBackend returns when an error diagnostic was found.

View Source
var TargetNames = []string{"cloudflare", "vercel", "netlify", "github-pages", "plain"}

TargetNames lists the built-in targets in the order commands show them.

Functions

func BasePath

func BasePath(ctx context.Context) string

BasePath returns the export's base path, such as "/repo", or "" outside an export. Code that builds URLs inside inline scripts uses it, because the base rewrite only reaches HTML attributes and CSS.

func Describe

func Describe(ctx context.Context, opts ...PageOpt)

Describe records facts about the page being rendered for the sitemap and diagnostics. Outside an export it does nothing.

func Drafts

func Drafts(ctx context.Context) bool

Drafts reports whether the export was asked to include drafts (--drafts).

func Exporting

func Exporting(ctx context.Context) bool

Exporting reports whether ctx belongs to a request made by an export, so a handler can skip side effects such as analytics counters.

func FromFS

func FromFS(fsys fs.FS) http.Handler

FromFS serves an export written by the plain target (fletch export --target plain), usually embedded in the binary:

//go:embed all:dist
var dist embed.FS
site, _ := fs.Sub(dist, "dist")
mux.Handle("/", static.FromFS(site))

It reads static-manifest.json for clean URLs, redirects and header rules, answers 404 with 404.html, sends a strong ETag with 304 on a match, and serves Brotli or gzip from a .br/.gz sibling or compressed once in memory. Without a manifest it maps /x to x, x.html or x/index.html. FromFS panics if the manifest is not valid JSON, as the embedded export is fixed at build time.

func InvalidateOn

func InvalidateOn(ctx context.Context, sub Subscriber, pre *Prerenderer) (cancel func(), err error)

InvalidateOn calls pre.Invalidate for every message sub delivers, so a publish on one node drops the snapshots on all of them. It runs until cancel is called or ctx is done.

func NetlifyConfig

func NetlifyConfig(dir string) string

NetlifyConfig is the netlify.toml snippet for an export into dir.

func PagesWorkflow

func PagesWorkflow(outDir string) string

PagesWorkflow is the GitHub Actions workflow that exports the site with Go alone and deploys it to GitHub Pages.

func Preview

func Preview(fsys fs.FS, o PreviewOptions) (http.Handler, error)

Preview returns a handler that serves an export the way its host would: Cloudflare and Netlify run _redirects, _headers and their URL handling; Vercel runs .vercel/output/config.json (or vercel.json); GitHub Pages serves files, clean .html URLs and the redirect stubs; plain serves files. All answer misses with 404.html. It is the production behavior, not a plain file server.

func WranglerAssets

func WranglerAssets(dir string, slash SlashPolicy) string

WranglerAssets is the wrangler.jsonc assets block for an export into dir.

func WranglerProxy added in v0.2.0

func WranglerProxy(dir string, slash SlashPolicy, proxy []string) string

WranglerProxy is the wrangler.jsonc block for a proxied split export into dir: the generated Worker as main, the assets binding it falls back to, and run_worker_first for the proxied globs.

func WriteNetlifyConfig

func WriteNetlifyConfig(projectDir, outDir string) (file string, created bool, err error)

WriteNetlifyConfig creates projectDir/netlify.toml with the publish directory. It never overwrites a file: created is false when one exists.

func WritePagesWorkflow

func WritePagesWorkflow(projectDir, outDir string) (file string, created bool, err error)

WritePagesWorkflow creates projectDir/.github/workflows/pages.yml. It never overwrites a file: created is false when one exists.

func WriteWranglerConfig

func WriteWranglerConfig(projectDir, name, compatDate, outDir string, slash SlashPolicy, proxy ...string) (file string, created bool, err error)

WriteWranglerConfig creates projectDir/wrangler.jsonc with the assets block, or with WranglerProxy when proxy lists the globs of a proxied split export. It never overwrites a file: created is false when one exists.

Types

type App

type App interface {
	Handler() http.Handler
	Router() *router.Router
}

App is what the exporter renders. *fletch.App satisfies it, and so does any type that wraps a *router.Router.

type BackendOption added in v0.2.0

type BackendOption func(*backendConfig)

BackendOption configures Backend.

func Credentials added in v0.2.0

func Credentials() BackendOption

Credentials makes Live and backend requests carry the user's cookies. Lax cookies reach only a same-site backend, so a backend on another site is S021 unless Proxy is set.

func Dynamic added in v0.2.0

func Dynamic(globs ...string) BackendOption

Dynamic declares backend-owned paths: they are not exported, links to them are legal (and point at the backend unless proxied), and each must match a backend route (S016). A glob ending in /* matches everything below it.

func LiveDirect added in v0.2.0

func LiveDirect() BackendOption

LiveDirect keeps Live on the backend origin under Proxy, for hosts that proxy HTTP but not WebSockets.

func LiveShell added in v0.2.0

func LiveShell(route string, mode ShellMode) BackendOption

LiveShell sets the shell mode of one Live route, by name or path. Default Render.

func Proxy added in v0.2.0

func Proxy(prefixes ...string) BackendOption

Proxy has the static host proxy backend paths, so the browser sees one origin. With no prefixes it proxies the Dynamic globs; Live endpoints and the contract are always added (Live unless LiveDirect).

type Built

type Built struct {
	URL       string         `json:"url"`
	Base      string         `json:"base,omitempty"`
	Slash     SlashPolicy    `json:"-"`
	Files     []File         `json:"files"`
	Redirects []RedirectRule `json:"redirects"`
	Headers   []HeaderRule   `json:"headers"`
	// CNAME is the custom domain a GitHub Pages export writes to CNAME.
	CNAME string `json:"cname,omitempty"`
	// Rewrites are static.Rewrite rules: status-200 host rewrites.
	Rewrites []RedirectRule `json:"rewrites,omitempty"`
	// Split describes the backend of a split deploy, and the proxy rules
	// a target writes for it. It is nil without static.Backend.
	Split *Manifest `json:"split,omitempty"`
	// HostFiles holds public/_redirects and public/_headers, which a target
	// merges with its generated rules or copies verbatim.
	HostFiles map[string][]byte `json:"-"`
}

Built is a finished export, ready for a Target.

func (*Built) File

func (b *Built) File(p string) (*File, bool)

File returns the file with the given output path.

type Check

type Check func(ctx context.Context, s *Built) []Diagnostic

Check is an extra check run over the finished export, such as an SEO preset. Its diagnostics are reported like the built-in ones.

type Diagnostic

type Diagnostic struct {
	ax.Diagnostic
	// Route is the route name and pattern, such as "docs.show /docs/{slug...}".
	Route string `json:"route,omitempty"`
	// Path is the URL path the problem was found on.
	Path string `json:"path,omitempty"`
	// Allowed marks an error that --allow turned into a non-failing one.
	Allowed bool `json:"allowed,omitempty"`
}

Diagnostic is an ax.Diagnostic with the route and URL path it is about.

func (Diagnostic) Failing

func (d Diagnostic) Failing() bool

Failing reports whether d fails an export.

type ExportOptions

type ExportOptions struct {
	// Out is the output directory. Default "dist".
	Out string
	// Target writes the host files. Default Cloudflare().
	Target Target
	// URL overrides the URL option and APP_URL.
	URL string
	// Base overrides the Base option.
	Base string
	// Host exports the routes of this Host group too, and sends it as the
	// request Host.
	Host string
	// Drafts makes Drafts(ctx) true in handlers.
	Drafts bool
	// NoIndex writes a Disallow robots.txt and an X-Robots-Tag header, for
	// preview deploys.
	NoIndex bool
	// Verify renders everything twice and reports differences (S006).
	Verify bool
	// Allow lists codes whose errors do not fail the export.
	Allow []string
	// DryRun builds and checks but writes nothing.
	DryRun bool
	// PageTimeout bounds one render. Default 30s.
	PageTimeout time.Duration
	// Workers is the number of concurrent renders. Default GOMAXPROCS.
	Workers int
	// VercelJSON makes the vercel target write plain files and a
	// vercel.json, for projects that Vercel builds from Git, instead of the
	// Build Output API layout.
	VercelJSON bool
	// CNAME is the custom domain the github-pages target writes to CNAME.
	// Default: the host of the site URL, unless it is a github.io, localhost
	// or loopback address.
	CNAME string
	// Backend overrides the static.Backend URL and turns split mode on
	// when the Site declares no Backend.
	Backend string
	// VerifyBackend checks the deployed backend over the network, as
	// VerifyBackend does, before anything is written; its diagnostics join
	// the Report.
	VerifyBackend bool
	// RequireBuildMatch makes a backend on another build an error (S032)
	// under VerifyBackend.
	RequireBuildMatch bool
	// Pagefind runs the pagefind binary, which must be on PATH, over the
	// written site before it replaces the previous export. It writes its own
	// index to /pagefind/, next to any static.Search index.
	Pagefind bool
}

ExportOptions are the per-run settings, usually from the export command's flags. Zero values take the Site's options or the defaults.

type File

type File struct {
	// Path is slash-separated and relative to the output root, such as
	// "docs/intro.html".
	Path string `json:"path"`
	// URL is the URL path the file answers, such as "/docs/intro".
	URL         string `json:"url"`
	ContentType string `json:"content_type,omitempty"`
	// Kind is "page", "file", "asset", "public", "generated" or "404".
	Kind  string `json:"kind"`
	Route string `json:"route,omitempty"`
	Data  []byte `json:"-"`
}

File is one exported file.

type FileReport

type FileReport struct {
	Path   string `json:"path"`
	Kind   string `json:"kind"`
	Bytes  int    `json:"bytes"`
	SHA256 string `json:"sha256"`
}

FileReport is one written file.

type Header struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

Header is one response header line.

type HeaderRule

type HeaderRule struct {
	Path    string   `json:"path"`
	Headers []Header `json:"headers"`
}

HeaderRule sets headers on every URL that matches Path; a * matches the rest of the path.

type Invalidation

type Invalidation struct {
	Paths []string `json:"paths"`
}

Invalidation is the message InvalidateOn acts on.

type Limits

type Limits struct {
	// Headers reports whether the host sets response headers from a file.
	Headers bool `json:"headers"`
	// Redirects reports whether the host runs redirect rules from a file.
	Redirects           bool `json:"redirects"`
	MaxStaticRedirects  int  `json:"max_static_redirects,omitempty"`
	MaxDynamicRedirects int  `json:"max_dynamic_redirects,omitempty"`
	MaxRedirectLine     int  `json:"max_redirect_line,omitempty"`
	MaxHeaderRules      int  `json:"max_header_rules,omitempty"`
	MaxHeaderLine       int  `json:"max_header_line,omitempty"`
	// RedirectPages reports whether the host gets redirects as HTML stub
	// pages instead of rules.
	RedirectPages bool `json:"redirect_pages,omitempty"`
	// MaxTotalRules is a budget shared by every redirect and header rule.
	MaxTotalRules int `json:"max_total_rules,omitempty"`
}

Limits describe what a host can express. A zero count means no limit.

type Manifest added in v0.2.0

type Manifest struct {
	Version     int            `json:"version"`
	Site        string         `json:"site"`
	Backend     string         `json:"backend"`
	Topology    string         `json:"topology"`
	Credentials bool           `json:"credentials"`
	Proto       int            `json:"proto,omitempty"`
	Build       string         `json:"build,omitempty"`
	Live        []ManifestLive `json:"live"`
	Dynamic     []string       `json:"dynamic"`
	Proxy       []string       `json:"proxy"`
	Rewrites    []RedirectRule `json:"rewrites,omitempty"`
}

Manifest is /_fletch/static.json: what a split export expects of its backend. verify-backend compares a deployed backend's contract to it.

func LoadManifest added in v0.2.0

func LoadManifest(dir string) (*Manifest, error)

LoadManifest reads _fletch/static.json from an export directory, for any target layout.

func ReadManifest added in v0.2.0

func ReadManifest(fsys fs.FS) (*Manifest, error)

ReadManifest reads /_fletch/static.json from an export's site root.

type ManifestLive added in v0.2.0

type ManifestLive struct {
	Name string `json:"name,omitempty"`
	// Path is the Live page's route path, the key of the backend contract.
	Path string `json:"path"`
	// Page is the URL path of the exported shell.
	Page string `json:"page"`
	// Endpoint is what the shell joins: absolute, or relative to the site
	// under Proxy.
	Endpoint string `json:"endpoint"`
	FP       string `json:"fp"`
	Mode     string `json:"mode"`
}

ManifestLive is one exported Live shell.

type Option

type Option func(*config)

Option configures a Site.

func Assets

func Assets(dir string) Option

Assets sets the asset build directory holding manifest.json. Default "public/dist".

func Backend added in v0.2.0

func Backend(url string, opts ...BackendOption) Option

Backend declares the Fletch backend that serves what a static site cannot: Live pages (exported as shells that join it at run time), Dynamic paths, and forms. url is its origin, such as "https://app.example.com"; --backend overrides it and $FLETCH_BACKEND_URL is the fallback. The export proves in process that the backend accepts the site, and fails with S017 to S027 when it would not.

func Base

func Base(path string) Option

Base serves the site under a path prefix, such as "/repo" for a GitHub project page. Root-relative URLs in HTML and CSS are prefixed.

func CSPStrict

func CSPStrict() Option

CSPStrict makes a cross-origin script that the nonce allowed an error (S008) instead of adding its origin to script-src.

func Checks

func Checks(checks ...Check) Option

Checks adds checks run over every export.

func Exclude

func Exclude(globs ...string) Option

Exclude leaves out every path that matches one of globs. A glob ending in /* matches everything below it; otherwise * stays inside one segment.

func NotFound

func NotFound(path string) Option

NotFound names the path whose response becomes 404.html. By default the exporter requests a path no app serves and keeps the app's own 404 page.

func Page

func Page(path string) Option

Page exports a URL that no route of its own serves, such as one answered by a mount.

func Paths

func Paths(route string, fn PathsFunc) Option

Paths lists the parameter sets of a route with path parameters. route is a route name, or a pattern such as "/blog/{slug}".

func Public

func Public(dir string) Option

Public sets the directory copied verbatim into the export. Default "public".

func Redirect

func Redirect(from, to string, status int) Option

Redirect adds a redirect rule. status is 301, 302, 303, 307 or 308.

func Rewrite added in v0.2.0

func Rewrite(from, to string) Option

Rewrite serves the exported file to at every path matching from, with status 200, as a host rule: an SPA fallback such as Rewrite("/docs-app/*", "/docs-app/index.html"). It needs no Backend.

func Search(opts ...search.Option) Option

Search builds a full-text search index of the exported pages: the index in /_search/index.json (sharded above 1 MiB) and the browser client in /_search/client.js. Pages marked noindex are left out; opts narrow it further, such as search.Include("/docs/*"). See package search.

func TrailingSlash

func TrailingSlash(p SlashPolicy) Option

TrailingSlash sets the canonical URL form and file layout. Default Never.

func URL

func URL(u string) Option

URL sets the site's public URL, such as "https://fletch.page". It sets the Host and scheme of every rendered request, so absolute URLs, canonical tags and the sitemap come out right. --url and ExportOptions.URL override it; APP_URL is the fallback.

type PageOpt

type PageOpt func(*pageMeta)

PageOpt describes the page being rendered; see Describe.

func LastMod

func LastMod(t time.Time) PageOpt

LastMod sets the page's sitemap lastmod.

func NoIndex

func NoIndex() PageOpt

NoIndex leaves the page out of the sitemap.

func Priority

func Priority(p float64) PageOpt

Priority sets the page's sitemap priority, from 0 to 1.

func Source

func Source(file string) PageOpt

Source names the file the page was rendered from, as "path" or "path:line", so diagnostics point at it.

type PageReport

type PageReport struct {
	URL    string `json:"url"`
	File   string `json:"file"`
	Route  string `json:"route,omitempty"`
	Source string `json:"source"`
}

PageReport is one exported HTML page.

type Params

type Params = map[string]string

Params is one set of path parameters for a route, keyed by parameter name. It is an alias so a plain map[string]string, such as the one a content collection builds, needs no conversion.

type PathsFunc

type PathsFunc func(ctx context.Context) ([]Params, error)

PathsFunc lists the parameter sets of a route with path parameters. A plain func(context.Context) ([]map[string]string, error) is assignable to it.

type PrerenderError

type PrerenderError struct {
	Diagnostics []Diagnostic
}

PrerenderError lists the safety checks a prerender failed.

func (*PrerenderError) Error

func (e *PrerenderError) Error() string

func (*PrerenderError) Unwrap

func (e *PrerenderError) Unwrap() error

Unwrap makes errors.Is(err, ErrExport) true, as for a failed export.

type PrerenderOption

type PrerenderOption interface {
	// contains filtered or unexported methods
}

PrerenderOption configures a Prerenderer. Every Option is one too, so Paths, Page, Exclude, URL and CSPStrict work the same as for New.

func Revalidate

func Revalidate(d time.Duration) PrerenderOption

Revalidate re-renders a snapshot older than d in the background while the old one is still served. Zero, the default, keeps snapshots until Invalidate or Refresh.

func Routes

func Routes(globs ...string) PrerenderOption

Routes limits prerendering to the planned paths that match one of globs, such as "/pricing" or "/blog/*". Without it the whole plan is served from memory.

func SkipCookies

func SkipCookies(names ...string) PrerenderOption

SkipCookies names the session cookies whose presence sends a request to the live handler, replacing the default "fletch_session" and "session".

func SkipRequest

func SkipRequest(fn func(*http.Request) bool) PrerenderOption

SkipRequest sends every request for which fn returns true to the live handler.

func Warm

func Warm(m WarmMode) PrerenderOption

Warm picks when the plan is rendered. Default AtBoot.

func WithErrorReporter

func WithErrorReporter(fn func(path string, err error)) PrerenderOption

WithErrorReporter receives the renders that failed or could not be cached after Warm: a failed re-render (the stale snapshot is kept), or a page that looks per-user and is served live.

type Prerenderer

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

Prerenderer serves pages of a dynamic app from in-memory snapshots made by the export engine: the same plan, render, CSP hash pass and safety checks.

func Prerender

func Prerender(app App, opts ...PrerenderOption) *Prerenderer

Prerender returns a Prerenderer for app. Install its Middleware inside secure.New and call Warm at startup:

pre := static.Prerender(app, static.Routes("/", "/pricing", "/blog/*"))
app.Use(pre.Middleware())
app.OnStart(pre.Warm)

func (*Prerenderer) Invalidate

func (p *Prerenderer) Invalidate(paths ...string)

Invalidate drops the snapshots of paths; each renders again on its next cacheable request. A path not yet planned that matches Routes, such as a new blog post, joins the plan.

func (*Prerenderer) Middleware

func (p *Prerenderer) Middleware() func(http.Handler) http.Handler

Middleware serves planned paths from their snapshots. Requests that are not GET or HEAD, carry a query string, Authorization or a session cookie, and the engine's own renders go to next.

func (*Prerenderer) Refresh

func (p *Prerenderer) Refresh(ctx context.Context) error

Refresh re-plans and re-renders every path, then swaps in the new snapshots at once. On error the current snapshots stay.

func (*Prerenderer) Warm

func (p *Prerenderer) Warm(ctx context.Context) error

Warm plans the paths and, under AtBoot, renders them all. A failing safety check is returned as a *PrerenderError, which should stop startup.

type PreviewOptions

type PreviewOptions struct {
	// Target is the host to emulate: "cloudflare" (default), "vercel",
	// "netlify", "github-pages" or "plain".
	Target string
	// Base is the path prefix the site is served under.
	Base string
	// Slash is the export's policy; it picks Cloudflare's html_handling.
	Slash SlashPolicy
	// Backend overrides the backend of a split export's _fletch/static.json
	// for the paths the host proxies.
	Backend string
}

PreviewOptions configure Preview.

type RedirectRule

type RedirectRule struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Status int    `json:"status"`
}

RedirectRule is one redirect rule. From may end in /* to match everything below it; a * at the end of To is replaced by the matched rest.

type Report

type Report struct {
	Target      string         `json:"target"`
	URL         string         `json:"url"`
	Base        string         `json:"base,omitempty"`
	Out         string         `json:"out"`
	DryRun      bool           `json:"dry_run,omitempty"`
	Pages       []PageReport   `json:"pages"`
	Files       []FileReport   `json:"files"`
	Redirects   []RedirectRule `json:"redirects"`
	Headers     []HeaderRule   `json:"headers"`
	CSP         string         `json:"csp"`
	Rewrites    []RedirectRule `json:"rewrites,omitempty"`
	Split       *Manifest      `json:"split,omitempty"`
	Diagnostics []Diagnostic   `json:"diagnostics"`
	Notes       []string       `json:"notes,omitempty"`
	Timings     Timings        `json:"timings"`
}

Report describes one export: what was written, the rules, the CSP strategy, every diagnostic, and timings. --json prints it.

func (*Report) Failed

func (r *Report) Failed() bool

Failed reports whether an error diagnostic fails the export.

type ShellMode added in v0.2.0

type ShellMode int

ShellMode picks how a Live page is exported under a Backend.

const (
	// Render runs the view's Mount at export and ships its output, which the
	// first frame after join replaces.
	Render ShellMode = iota
	// Empty exports an empty Live root: no Mount runs at export.
	Empty
)

func (ShellMode) String added in v0.2.0

func (m ShellMode) String() string

String returns "render" or "empty".

type Site

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

Site is a configured exporter for one app.

func New

func New(app App, opts ...Option) *Site

New returns a Site that exports app.

func (*Site) Commands

func (s *Site) Commands() []cli.Command

Commands returns the export, preview, verify-backend and topology commands, for app.Command.

func (*Site) Export

func (s *Site) Export(ctx context.Context, o ExportOptions) (*Report, error)

Export renders the site, checks it, and writes it into o.Out through the target, replacing the previous export only when everything succeeded. The Report is returned even when the export fails; an error diagnostic makes the error wrap ErrExport.

func (*Site) Topology added in v0.2.0

func (s *Site) Topology(o ExportOptions) (*Topology, error)

Topology resolves the split-deploy setup for o: the mode ("static" with no backend, else separate, proxy or mixed), the backend, and the Live shells. Configuration problems are in Diagnostics.

type SlashPolicy

type SlashPolicy int

SlashPolicy picks the canonical form of page URLs and the file layout.

const (
	// Never serves /pricing from pricing.html. It is the default and serves
	// the same URL with no redirect on every supported host.
	Never SlashPolicy = iota
	// Always serves /pricing/ from pricing/index.html.
	Always
)

func (SlashPolicy) String

func (p SlashPolicy) String() string

String returns "never" or "always".

type Subscriber

type Subscriber interface {
	Subscribe(ctx context.Context, fn func(Invalidation)) (cancel func(), err error)
}

Subscriber delivers Invalidation messages. A pubsub.TypedTopic of Invalidation satisfies it, so this package needs no pubsub import:

topic := pubsub.Bind(bus, pubsub.NewTopic[static.Invalidation]("static.invalidate"))
cancel, err := static.InvalidateOn(ctx, topic, pre)
// on publish, from any node:
topic.Publish(ctx, static.Invalidation{Paths: []string{"/blog", "/blog/new-post"}})

type Target

type Target interface {
	Name() string
	// Limits are the host's rule budgets and capabilities.
	Limits() Limits
	// Write writes s into out.
	Write(ctx context.Context, s *Built, out *os.Root) error
}

Target writes an export for one kind of host.

func Cloudflare

func Cloudflare() Target

Cloudflare returns the target for Cloudflare Workers Static Assets and Pages: _redirects, _headers and 404.html.

func GitHubPages

func GitHubPages() Target

GitHubPages returns the target for GitHub Pages: .nojekyll, 404.html, a CNAME file for a custom domain, and HTML stub pages for redirects, because the host has no redirect or header rules. Page policies go into <meta>.

func Netlify

func Netlify() Target

Netlify returns the target for Netlify: _redirects, _headers and 404.html. Netlify documents no rule-count limit, so S012 covers only conflicts with public/_redirects and public/_headers.

func Plain

func Plain() Target

Plain returns the target for hosts with no rule files (S3, nginx, Caddy): the files, 404.html, and static-manifest.json listing redirects and headers for a custom pipeline.

func TargetByName

func TargetByName(name string) (Target, error)

TargetByName returns a built-in target: "cloudflare", "vercel", "netlify", "github-pages" (or "gh-pages") or "plain".

func Vercel

func Vercel() Target

Vercel returns the target for Vercel. It writes the Build Output API v3 layout, .vercel/output/static and .vercel/output/config.json, which `vercel deploy --prebuilt` uploads without framework detection. Set ExportOptions.VercelJSON to write plain files and a vercel.json instead, for projects that Vercel builds from Git.

type Timings

type Timings struct {
	PlanMS   float64 `json:"plan_ms"`
	RenderMS float64 `json:"render_ms"`
	WriteMS  float64 `json:"write_ms"`
	TotalMS  float64 `json:"total_ms"`
}

Timings are in milliseconds.

type Topology added in v0.2.0

type Topology struct {
	Target   string `json:"target"`
	Site     string `json:"site"`
	Backend  string `json:"backend,omitempty"`
	Mode     string `json:"mode"`
	LiveBase string `json:"live_base,omitempty"`
	// Origins are what the backend's fletch.StaticFrontend.Origins must
	// allow.
	Origins     []string        `json:"origins"`
	Credentials bool            `json:"credentials"`
	Dynamic     []string        `json:"dynamic"`
	Proxy       []string        `json:"proxy"`
	Rewrites    []RedirectRule  `json:"rewrites"`
	LiveShells  []TopologyShell `json:"live_shells"`
	Diagnostics []Diagnostic    `json:"diagnostics"`
}

Topology is a Site's split-deploy setup as an export with the given options would resolve it, for `topology` and agents. It renders nothing.

type TopologyShell added in v0.2.0

type TopologyShell struct {
	Route    string `json:"route,omitempty"`
	Path     string `json:"path"`
	Endpoint string `json:"endpoint"`
	Mode     string `json:"mode"`
}

TopologyShell is one Live route and how it is exported.

type VerifyOptions added in v0.2.0

type VerifyOptions struct {
	// Manifest is the export's _fletch/static.json. Required.
	Manifest *Manifest
	// Site and Backend override the manifest's origins.
	Site, Backend string
	// RequireBuildMatch makes a backend on another build an error (S032).
	RequireBuildMatch bool
	// SiteCheck also checks the deployed site: that it proxies to the
	// backend (S035, proxy topologies) and serves this export's manifest
	// (S033). Run it after the static deploy.
	SiteCheck bool
	// Timeout bounds each request and the Live probe. Default 10s.
	Timeout time.Duration
	// Client sends the HTTP requests. Default: a client with Timeout that
	// does not follow redirects.
	Client *http.Client
}

VerifyOptions configure VerifyBackend.

type VerifyReport added in v0.2.0

type VerifyReport struct {
	Site        string       `json:"site"`
	Backend     string       `json:"backend"`
	Topology    string       `json:"topology"`
	Build       string       `json:"build,omitempty"`
	Diagnostics []Diagnostic `json:"diagnostics"`
}

VerifyReport is the outcome of VerifyBackend.

func VerifyBackend added in v0.2.0

func VerifyBackend(ctx context.Context, o VerifyOptions) (*VerifyReport, error)

VerifyBackend checks over the network that a deployed backend serves what the export expects: it is ready (S036), its contract allows the site with the same protocol (S018, S031), build (S032) and templates (S033), CORS preflights pass (S019), and a Live probe joins over WebSocket or SSE (S034). The error wraps ErrVerify when it failed.

func (*VerifyReport) Failed added in v0.2.0

func (r *VerifyReport) Failed() bool

Failed reports whether an error diagnostic was found.

type WarmMode

type WarmMode int

WarmMode picks when a Prerenderer renders its plan.

const (
	// AtBoot renders the whole plan in Warm, so a failing safety check stops
	// startup and the first request is already a hit. It is the default.
	AtBoot WarmMode = iota
	// Lazy renders a planned path on its first cacheable request.
	Lazy
)

Directories

Path Synopsis
content module
highlight module
deploy
cloudflare
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library.
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library.
netlify
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library.
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library.
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers.
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers.
og module
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser.
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser.
Package seo checks the search-engine and social metadata of an export.
Package seo checks the search-engine and social metadata of an export.
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics.
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics.

Jump to

Keyboard shortcuts

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