plugin

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package plugin implements the esbuild onLoad plugin for *.pzl files (constellation/doc/DOC-COMPILER-DESIGN.md §b). Everything happens in memory, per file: read → SplitSections → codegen.Compile → return JS. Parse/codegen errors become esbuild api.Message values with file/line/col (§e) so the build fails with normal esbuild formatting; a file that fails to compile emits no output.

<style> blocks are collected into a per-plugin, mutex-guarded map (esbuild runs onLoad concurrently across files) and joined deterministically — sorted by file path — into a single global CSS string via CSS().

Index

Constants

View Source
const ManifestSpecifier = "@magic-spells/puzzle/formatters/manifest"

Variables

This section is empty.

Functions

func ScanFormatters

func ScanFormatters(scanRoot string) (map[string]bool, error)

ScanFormatters preserves the original formatter-only API for focused callers and tests. Build orchestration uses ScanUsage so every tree-shaking input is refreshed together.

Types

type CompileCache added in v0.6.0

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

CompileCache memoizes .pzl transforms for the lifetime of one build.

esbuild runs onLoad concurrently, and the three passes overlap only in time, not in goroutines — but the same file can still be requested concurrently within one pass. Each key gets its own sync.Once so a file is transformed exactly once no matter how many callers race for it, and the loser waits for the winner rather than duplicating the work.

func NewCompileCache added in v0.6.0

func NewCompileCache() *CompileCache

NewCompileCache returns an empty cache. A nil *CompileCache is a valid "no caching" value — every method is nil-safe — which is what the watch/dev path passes.

func (*CompileCache) AssetConsumers added in v0.6.0

func (c *CompileCache) AssetConsumers(paths []string) []string

AssetConsumers returns the symlink-resolved .pzl paths that inline any of paths with {#svg}, as recorded by the transforms this cache has memoized. It is the dependency edge no esbuild metafile carries: an inlined asset is a watch file, not a module input, so route-level invalidation has to ask the compiler which views a changed icon reaches. Unknown paths contribute nothing; the caller decides what an empty answer means.

func (*CompileCache) Evict added in v0.6.0

func (c *CompileCache) Evict(paths []string)

Evict drops every memoized transform that names one of paths — the .pzl itself, or any file it inlined via {#svg} — and the SVG memo for those paths. A nil cache and an empty batch are no-ops.

The .pzl entries do not strictly NEED evicting (their keys carry a content hash, so a changed file misses on its own); the SVG memo does, and a .pzl whose bytes are unchanged but whose inlined icon moved must miss too, which is exactly what the {#svg} edge in byFile expresses. Dropping the .pzl entries as well keeps a long dev session's map proportional to the tree rather than to the number of saves.

type Features added in v0.3.0

type Features struct {
	Flip   bool
	Portal bool
	RawAt  bool
}

Features are the build-wide DCE bits — one boolean per gated runtime module — handed to esbuild as literal defines. Kept as a comparable struct so WatchBuilder can decide with one == whether the Define set frozen into its esbuild context went stale.

type Plugin

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

Plugin owns the cross-file state of one build: the app root (used to derive stable, app-relative filenames for error reporting and the D20 emission-mode decision) and the thread-safe <style> collector.

func New

func New(appRoot string) *Plugin

New creates a Plugin rooted at the app directory (the directory containing app/app.js). appRoot should be absolute. The root is symlink-resolved up front so relName() compares like with like: esbuild reports args.Path with symlinks resolved, and an unresolved root (macOS /var → /private/var, a symlinked project dir) would make filepath.Rel fall back to the absolute path — hashing a machine-specific string into ScopeID (D59 byte-stability).

func (*Plugin) CSS

func (p *Plugin) CSS() string

CSS returns every collected <style> block, sorted by source file path and joined with blank lines. v1 emits global CSS with no scoping.

func (*Plugin) CSSRevision added in v0.6.0

func (p *Plugin) CSSRevision() uint64

CSSRevision returns the current collector revision without joining every block. A revision moves only when the effective map changes, so incremental callers can avoid sorting and composing CSS after an unrelated rebuild.

func (*Plugin) CSSSnapshot added in v0.6.0

func (p *Plugin) CSSSnapshot() (string, uint64)

CSSSnapshot returns the current canonical stylesheet and the revision of the effective collector state that produced it. The pair is captured under one lock so a long-lived build driver can atomically promote it from candidate state to last-good state after a successful rebuild.

func (*Plugin) ESBuild

func (p *Plugin) ESBuild() api.Plugin

ESBuild returns the api.Plugin to register in BuildOptions.Plugins.

func (*Plugin) Features added in v0.3.0

func (p *Plugin) Features() Features

Features returns the DCE define bits captured by the most recent SetUsage call.

func (*Plugin) PruneCSS

func (p *Plugin) PruneCSS(keep map[string]bool)

PruneCSS drops collected <style> entries whose source .pzl is not in keep, the set of absolute source paths in the current module graph (derived from the esbuild metafile after a successful incremental rebuild). This catches the one case CSS()'s os.Stat prune cannot: a file still on disk but no longer imported, whose onLoad never re-runs so its stale block would otherwise linger.

Both sides are symlink-resolved before comparison so a keep-set path computed from a cwd-relative metafile key matches a css key set from esbuild's resolved args.Path even when a symlinked prefix (macOS /tmp → /private/tmp) differs.

func (*Plugin) SetCompileCache added in v0.6.0

func (p *Plugin) SetCompileCache(c *CompileCache)

SetCompileCache attaches a build-scoped memo shared with the other passes of the same build. Left unset (the WatchBuilder path), every onLoad transforms from source as before.

func (*Plugin) SetFormatters

func (p *Plugin) SetFormatters(used map[string]bool)

SetFormatters stores the app-wide built-in formatter union used by the virtual manifest. escape is always present as the safety default.

func (*Plugin) SetRuntimeDir

func (p *Plugin) SetRuntimeDir(dir string)

SetRuntimeDir points the virtual formatter manifest at client-runtime/.

func (*Plugin) SetUsage added in v0.3.0

func (p *Plugin) SetUsage(usage Usage)

SetUsage stores every build-wide usage bit discovered by ScanUsage. Formatter manifest behavior stays identical; the booleans feed esbuild's literal DCE defines.

type Usage added in v0.3.0

type Usage struct {
	Formatters map[string]bool
	HasFlip    bool
	HasPortal  bool
	HasRawAt   bool
}

Usage is the build-wide feature set discovered by ScanUsage.

func ScanUsage added in v0.3.0

func ScanUsage(scanRoot string) (Usage, error)

ScanUsage walks scanRoot for first-party source usage that controls runtime tree-shaking: it parses .pzl templates for formatter chains, flip attributes, Portal nodes, and raw blocks. All are template facts, so only .pzl files are read.

The scan deliberately errs toward OVER-inclusion: it walks the whole project (not just app/) so a component imported from a sibling directory still contributes its usage, and it SKIPS files it cannot read or parse rather than failing. Rationale: a false positive only leaves a small runtime module in the bundle, whereas a false negative silently removes a used feature. Since v1.12 (D43) an unseeded builtin no longer crashes the render — codegen wraps every call in the __missing typo-guard, so the value passes through with a console.error — but the scan still seeds every USED builtin so the guard stays a *typo* guard, not a bundling crutch: correctly-spelled builtins must resolve to the real formatter, not the pass-through. A genuinely broken .pzl that the app actually imports is still reported — with position info — by the esbuild .pzl OnLoad pass; the scan must not preempt that by failing the build over a file nothing imports. See DOC-COMPILER-DESIGN §b.

A long-lived dev builder calls UsageScanner.Scan (scanmemo.go) instead, which is this same walk with a per-file memo in front of the parse; both share scanFileUsage so they cannot answer differently.

func (Usage) Features added in v0.6.0

func (u Usage) Features() Features

Features projects the scan result onto the define bits. It is exported for the long-lived builders, which hold a Usage directly and have to decide whether the Defines frozen into an esbuild context went stale.

type UsageScanner added in v0.6.0

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

UsageScanner is a reusable, incremental ScanUsage. Construct one per long-lived builder; a one-shot build has nothing to reuse and calls ScanUsage instead.

func NewUsageScanner added in v0.6.0

func NewUsageScanner() *UsageScanner

NewUsageScanner returns an empty scanner. Its first Scan is a full walk.

func (*UsageScanner) Scan added in v0.6.0

func (s *UsageScanner) Scan(scanRoot string) (Usage, error)

Scan walks scanRoot and returns the project-wide Usage, parsing only the .pzl files whose mtime or size changed since the previous Scan. It follows ScanUsage's contract exactly — same walk, same pruned directories, same fail-soft handling of unreadable or unparseable files — so the two are interchangeable and a builder can be tested against either.

Jump to

Keyboard shortcuts

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