Documentation
¶
Overview ¶
Package build drives a full `puzzle build` (constellation/doc/DOC-COMPILER-DESIGN.md §b): one esbuild api.Build pass over app/app.js with the .pzl plugin registered, then the collected global CSS and the static public/ assets are written next to the bundle. It replaces the Phase 1 prototype orchestrator (internal/compiler, deleted): no intermediate files, no runtime concatenation — the runtime is a package esbuild resolves and bundles.
Hybrid (SSG) output for `puzzle build --hybrid` (or `output: 'hybrid'` in puzzle.config.js) — the prerender + SPA-takeover mode formerly spelled 'static'. The Go compiler needs no new parser/codegen work — compiled .pzl output is already pure ViewNode-tree data — so this is entirely a downstream step: bundle a SECOND, node-platform esbuild pass whose entry imports the app's default export plus the SSG runtime, run it under node to emit one index.html per static route into the staging dir, then hand back a summary. It slots into Build() after copyPublic and before the staging→dist swap, so a prerender failure discards staging and leaves the last good dist/ exactly as it was (the same atomic-swap guarantee compile failures already get).
The true static-pages mode (`--static` / `output: 'static'`, D81) lives in prerender_pages.go and reuses the shared bundle/exec helpers here.
True static-pages output for `puzzle build --static` (or `output: 'static'` in puzzle.config.js), decision D81. Unlike the hybrid mode (prerender.go), which prerenders per-route HTML that the full SPA runtime takes over, the static mode ships content-complete HTML pages plus a SMALL per-page ES-module bundle: no router, no SPA takeover, no history API. Navigation is plain <a> page loads; the per-page script upgrades each page to an interactive document.
The Go pipeline runs the shared node prerender pass in mode 'static' (the JS side captures each page's store payload and returns an extended summary), then generates one `mountStatic` entry file per written page and runs a SECOND, browser-platform esbuild pass with Splitting over those entries into staging/_puzzle. staging/app.js is deleted (nothing references it in static mode). Like hybrid, it slots in before the staging→dist swap, so any failure discards staging and leaves the last good dist/ untouched.
Index ¶
- Constants
- func Build(root string, opts Options) error
- func FileExists(path string) bool
- func FindInstalledRuntime(start string) string
- func FindRuntime(start string) string
- func PkgIsPuzzle(pkgPath string) bool
- func ProfileEnabled(opt bool) bool
- func PublicDir(root string) string
- func SweepWorkDirs(root string)
- func ValidatePublic(root string, splitting bool) error
- type Options
- type PhaseProfile
- type RebuildResult
- type StaticWatchBuilder
- func (b *StaticWatchBuilder) Dispose()
- func (b *StaticWatchBuilder) Rebuild(changed []string) error
- func (b *StaticWatchBuilder) RebuildProfile(changed []string, prof *PhaseProfile) error
- func (b *StaticWatchBuilder) RecomposeStyles() (bool, error)
- func (b *StaticWatchBuilder) SetTailwind(fn func() (string, error))
- type StaticWatchOptions
- type WatchBuilder
- type WatchOptions
Constants ¶
const ProfileEnvVar = "PUZZLE_PROFILE_BUILD"
ProfileEnvVar turns the build profiler on for any process that runs a build, including `puzzle dev`'s static rebuild path — which calls build.Build directly and therefore has no CLI flag of its own to carry the request.
const RuntimeEnvVar = "PUZZLE_RUNTIME"
RuntimeEnvVar names a Puzzle checkout to resolve '@magic-spells/puzzle' against, overriding both the in-repo walk and node_modules.
It exists for the `puzzle-dev`-style workflow: building a working-tree COMPILER against a working-tree RUNTIME in some other project. Without it the compiler can only ever swap itself — the runtime is whatever that project's node_modules holds — so a dev CLI silently pairs new compiler with published runtime, and nothing says so.
The value is the package ROOT (the directory holding client-runtime/), not the index.js inside it, so it reads the same as a repo path:
PUZZLE_RUNTIME=~/Code/@magic-spells/puzzle puzzle dev
Variables ¶
This section is empty.
Functions ¶
func Build ¶
Build compiles the app rooted at root (the directory containing app/app.js) into root/dist. It returns a formatted error if esbuild reports any errors.
func FileExists ¶ added in v0.3.0
FileExists exposes the build package's historical file probe while sharing its implementation with the rest of the compiler.
func FindInstalledRuntime ¶ added in v0.3.0
FindInstalledRuntime walks up from start for an installed Puzzle runtime and returns the absolute path to its client-runtime/index.js, or "" if absent.
func FindRuntime ¶ added in v0.3.0
FindRuntime walks up from start looking for the in-repo runtime: a directory holding client-runtime/index.js whose package.json is named "@magic-spells/puzzle". Returns the absolute path to index.js, or "" if none.
func PkgIsPuzzle ¶ added in v0.3.0
PkgIsPuzzle reports whether pkgPath is a package.json for "@magic-spells/puzzle".
func ProfileEnabled ¶ added in v0.6.0
ProfileEnabled reports whether profiling was explicitly requested or enabled through PUZZLE_PROFILE_BUILD. Obvious false spellings keep it disabled.
func PublicDir ¶
PublicDir returns the resolved static-assets source directory (app/public, else a root-level public/), or "" if neither exists. Exported so `puzzle dev` can watch a root-level public/ tree that lies OUTSIDE the watched app/ dir (app/public is already inside it). It delegates to the same resolver the copier uses, so the watched dir and the copied dir never diverge.
func SweepWorkDirs ¶ added in v0.6.0
func SweepWorkDirs(root string)
SweepWorkDirs removes the transient directories a previous, interrupted build left behind. It is exported so `puzzle dev` can run it at startup on the SPA path, which never calls Build.
Everything about it is deliberately conservative, because it deletes trees:
- only two locations are considered, <root>/.puzzle/tmp and the app root;
- only exact known name prefixes are matched, never a general pattern;
- only real directories are removed — a symlink is skipped outright, so the sweep can never follow a link out of the app root;
- only entries untouched for staleWorkAge are removed, so a concurrently running build's staging tree survives.
Failures are ignored throughout: a leftover directory is a performance problem, and refusing to build because one could not be deleted would turn it into a correctness one.
func ValidatePublic ¶
ValidatePublic reports an error if the app's public/ tree contains a ROOT-LEVEL file whose name collides with a reserved compiler output (app.js, app.js.map, styles.css). Such a file would be copied over the bundle/stylesheet the build just produced. Nested occurrences are allowed. It is exported so `puzzle dev` (a separate package) can revalidate on every incremental rebuild. No public/ dir is not an error.
splitting extends the check to the root-level chunks/ ENTRY (file or directory), which the SPA pass owns only while build.splitting is on — the same class of collision the static pass rejects for _puzzle (prerender_pages.go). Off, that name belongs to the app again.
Types ¶
type Options ¶
type Options struct {
// Development disables minification (readable output for debugging and the
// compiled-fixture test). Production (the default, Development=false) minifies.
Development bool
// Runner runs the Tailwind pipeline when puzzle.config.js declares it. Left
// nil, the real npx-backed runner is used; tests inject a fake. It is only
// consulted when a config actually enables Tailwind.
Runner styles.Runner
// Output is the prerender mode requested on the CLI: "" (no flag), "static"
// (the true static-pages mode, `--static`), or "hybrid" (prerender + SPA
// takeover, `--hybrid`). It is reconciled with puzzle.config.js `output` in
// Build: a flag and a *different* config value is an error; either one alone
// (or agreeing) selects the mode. Empty on both sides is the default SPA build.
Output string
// Fixtures wires the app's app/fixtures.js (or .ts) through the detachable
// fixtures/mock runtime module (`--fixtures`, D98): the build bundles a
// generated wrapper entry that installs the module before the app boots,
// instead of bundling app/app.js directly. Off, nothing about the output
// changes — the module is simply never imported, which is the whole
// tree-shake. Unsupported alongside either prerender output mode.
Fixtures bool
// Metafile receives esbuild's JSON metafile when non-nil. It is primarily a
// build-test seam for proving an input contributes zero production bytes;
// normal CLI builds leave it nil and pay nothing.
Metafile *string
// Config is an ALREADY-LOADED puzzle.config.js. Non-nil, Build uses it as-is
// and never shells out to node; nil, Build loads it itself.
//
// This exists for `puzzle dev`, which loads the config once at startup and
// deliberately refuses to reload it mid-session (a config edit only prints a
// "restart to apply" advisory). Its static rebuild path calls Build on every
// save, so without this the dev loop spawned a `node -e` subprocess per
// keystroke-burst to re-read a file it had already decided to ignore. A
// standalone `puzzle build` leaves this nil and is unaffected.
Config *config.Config
// Profile prints a per-phase timing table to stderr after the build
// (`puzzle build --profile-build`). The PUZZLE_PROFILE_BUILD environment
// variable turns it on too. Off, the profiler is a nil pointer and every
// phase call is a nil check.
Profile bool
// Profiler folds phases into a caller-owned table instead of printing a
// separate `puzzle build` report. The dev server uses this only for its
// non-incremental fallback so startup/rebuild still emits exactly one table.
Profiler *PhaseProfile
}
Options configure a build.
type PhaseProfile ¶ added in v0.6.0
type PhaseProfile struct {
// contains filtered or unexported fields
}
PhaseProfile accumulates wall-clock timings for one build or rebuild.
A nil *PhaseProfile is the disabled state, and every method is nil-safe, so an unprofiled build pays a single nil comparison per phase and allocates nothing: Phase returns the shared no-op closure rather than a fresh one. The mutex and start-order ordinal let independent build phases finish concurrently without racing or making the report order depend on scheduler timing.
func NewPhaseProfile ¶ added in v0.6.0
func NewPhaseProfile(enabled bool, label string) *PhaseProfile
NewPhaseProfile returns a labeled live profiler when enabled, nil otherwise. Callers that accept both a flag and ProfileEnvVar should pass ProfileEnabled(flag) as enabled.
func (*PhaseProfile) Phase ¶ added in v0.6.0
func (p *PhaseProfile) Phase(name string) func()
Phase starts timing a named phase and returns the function that ends it. The phase's report position is fixed here, before concurrent work starts; completion order therefore cannot reorder the table.
func (*PhaseProfile) Report ¶ added in v0.6.0
func (p *PhaseProfile) Report(w io.Writer)
Report prints the phase table. It goes to stderr, never stdout: stdout carries the build summary that scripts and the skipped-route gate parse, and profiling must not change it.
type RebuildResult ¶ added in v0.6.0
RebuildResult describes the expensive work an incremental pass actually performed. Besides driving stylesheet composition, the metadata gives tests and opt-in profiling deterministic evidence that unrelated walks were skipped without relying on wall-clock thresholds.
type StaticWatchBuilder ¶ added in v0.6.0
type StaticWatchBuilder struct {
// contains filtered or unexported fields
}
StaticWatchBuilder is the persistent static-output builder for one dev session. Not safe for concurrent Rebuilds; the dev loop calls it serially.
func NewStaticWatchBuilder ¶ added in v0.6.0
func NewStaticWatchBuilder(root string, opts StaticWatchOptions) (*StaticWatchBuilder, error)
NewStaticWatchBuilder prepares the warm output tree and the two esbuild contexts whose inputs are known up front (the browser app pass and the node prerender pass). The per-page context cannot exist yet: its entry set comes from the first prerender run.
func (*StaticWatchBuilder) Dispose ¶ added in v0.6.0
func (b *StaticWatchBuilder) Dispose()
Dispose releases every esbuild context. After Dispose the builder must not be used. The warm tree is left in place: it lives under the self-ignoring .puzzle/ scratch root, and the next session clears it at construction.
func (*StaticWatchBuilder) Rebuild ¶ added in v0.6.0
func (b *StaticWatchBuilder) Rebuild(changed []string) error
Rebuild runs one incremental static build over the current sources and, on success, atomically swaps the result in for dist/. changed is the debounced watcher burst; it drives cache eviction only, never what gets rebuilt (esbuild owns that question).
Every failure path leaves dist/ exactly as it was: staging is discarded and the error is returned for the caller to print and push down the D92 channel.
func (*StaticWatchBuilder) RebuildProfile ¶ added in v0.6.0
func (b *StaticWatchBuilder) RebuildProfile(changed []string, prof *PhaseProfile) error
RebuildProfile folds this rebuild into a caller-owned profile, used for the initial dev startup table.
func (*StaticWatchBuilder) RecomposeStyles ¶ added in v0.6.0
func (b *StaticWatchBuilder) RecomposeStyles() (bool, error)
RecomposeStyles rewrites the served dist/styles.css from the current Tailwind layer and the collected <style>, rendering nothing. It is what the dev loop calls when the warm `tailwindcss --watch` child rewrites its output: a utility class appearing or disappearing changes the stylesheet and nothing else, and styles.css is the one output no page's HTML embeds, so it can be swapped in on its own. Asking for a Rebuild instead re-renders the WHOLE site on every save, because a styles-only change carries no paths for the classifier to attribute.
It reports whether the bytes on disk actually changed, so the caller can skip a reload that would hand the browser what it already has. Until the first rebuild has produced a dist/ there is nothing to update and this is a no-op.
func (*StaticWatchBuilder) SetTailwind ¶ added in v0.6.0
func (b *StaticWatchBuilder) SetTailwind(fn func() (string, error))
SetTailwind installs the accessor for the Tailwind layer of the composed stylesheet. It exists as a setter rather than a constructor field because the dev loop only knows where that layer comes from — the warm `tailwindcss --watch` child's private output file, or the one-shot fallback if that child never started or has died — after it has decided whether to start a builder at all. nil (the default) means the project declares no Tailwind pipeline.
type StaticWatchOptions ¶ added in v0.6.0
type StaticWatchOptions struct {
// Config is the already-loaded puzzle.config.js. `puzzle dev` loads it once
// at startup and refuses to reload it mid-session, so the builder holds it
// for its lifetime — same contract as build.Options.Config.
Config config.Config
// Tailwind returns the current Tailwind CSS layer. nil means no pipeline.
Tailwind func() (string, error)
// Profile enables per-phase rebuild tables. PUZZLE_PROFILE_BUILD is also
// honored; the explicit option carries `puzzle dev --profile-build`.
Profile bool
}
StaticWatchOptions configure the static dev builder.
type WatchBuilder ¶
type WatchBuilder struct {
// contains filtered or unexported fields
}
WatchBuilder is the incremental esbuild driver for `puzzle dev` (D27). It holds a persistent api.Context so each Rebuild reuses esbuild's parse/resolve caches — only changed inputs are re-read — instead of the cold full pass that build.Build does for production. It owns ONLY the JS bundle and the static public/ copy; the dev loop composes dist/styles.css itself (Tailwind comes from the warm --watch child, not a one-shot per rebuild).
The single Plugin instance lives for the context's lifetime, so its <style> collector is shared across rebuilds. That live collector is candidate state; CSS() exposes only the snapshot promoted after a complete successful rebuild, with set-or-delete and graph pruning keeping each candidate honest.
func NewWatchBuilder ¶
func NewWatchBuilder(root string, opts WatchOptions) (*WatchBuilder, error)
NewWatchBuilder creates the incremental builder for the app rooted at root (the directory containing app/app.js). It validates the entry point and constructs (but does not yet run) the esbuild context. Always development mode: readable, unminified output.
func (*WatchBuilder) CSS ¶
func (b *WatchBuilder) CSS() string
CSS returns the collected <style> blocks from the most recent fully successful rebuild. It is safe to call concurrently with Rebuild from the Tailwind output poll; candidate CSS from a failed pass is never observable.
func (*WatchBuilder) Dispose ¶
func (b *WatchBuilder) Dispose()
Dispose releases the esbuild context. After Dispose the builder must not be used.
func (*WatchBuilder) Rebuild ¶
func (b *WatchBuilder) Rebuild(changed []string) (RebuildResult, error)
Rebuild runs one incremental esbuild pass (reusing caches). changed is the debounced watcher batch: it decides whether project usage and public assets can have changed, while esbuild remains responsible for graph invalidation.
The JS bundle is written directly by esbuild (Write: true). Component CSS is promoted to the snapshot returned by CSS only after every required step succeeds; a failed pass can mutate the plugin's candidate collector, but can never expose those bytes to the Tailwind composition path.
func (*WatchBuilder) RebuildProfile ¶ added in v0.6.0
func (b *WatchBuilder) RebuildProfile(changed []string, prof *PhaseProfile) (RebuildResult, error)
RebuildProfile is Rebuild with timings folded into the caller's profile. The dev server uses it so startup has one table and each later save has one.
type WatchOptions ¶ added in v0.3.0
type WatchOptions struct {
// Splitting mirrors build.splitting (puzzle.config.js) into the dev loop, so
// a developer sees the same lazy chunks the production build will emit. It
// also switches this builder off esbuild's own writer — see the prevOutputs
// field for why.
Splitting bool
// Fixtures bundles the generated `--fixtures` wrapper entry instead of
// app/app.js (D98), installing the fixtures/mock module before the app boots.
// The wrapper is generated ONCE here, at construction, and left in place for
// the process lifetime — it lives under <root>/.puzzle/, which is outside every
// watched directory and pruned from the usage scan, so writing it can never
// trigger a rebuild.
Fixtures bool
}
WatchOptions configure the incremental dev builder.