Help us shape the future of Go! Take the 2026 Go Developer Survey

sitec

package module
v0.2.79 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 45 Imported by: 2

README

sitec

Compilador de sitio: toma un árbol de fuentes Go y produce la superficie estática desplegable del sitio — hoja de estilos, bundle de scripts, sprite SVG (dentro del HTML, nunca como archivo aparte), declaración de fuentes y shell HTML.

Corre hasta terminar y sale. Es un compilador, no un servidor ni un renderizador — pensado para CI/CD tanto como para el arnés de desarrollo.

sitec              # ayuda, exit 0
sitec build -o dir # compila y escribe la salida
sitec check        # valida sin escribir nada (puerta de CI)

stdout entrega datos (manifiesto JSON); stderr entrega logs.

Uso programático (Build de producción)

Para compilar y emitir la superficie estática desplegable en un pipeline de producción sin depender del demonio de desarrollo:

package main

import "webtyp.com/sitec"

func main() {
	if err := sitec.Build(".", "web/public"); err != nil {
		panic(err)
	}
}

sitec.Build ejecuta el pipeline completo en una sola pasada, borra el contenido previo de la salida y escribe el árbol servible a disco con minificación activada por defecto.

Nota: La compilación del binario Go WASM (.wasm) es responsabilidad del llamador (ej. invocando go build o tinygo para GOOS=js GOARCH=wasm). Build emite el runtime JS y enlaza el binario.

Icono del sitio

Un proyecto declara su icono con Favicon() en su paquete de configuración (!wasm):

//go:embed logo.png
var logo []byte

func (b *Brand) Favicon() favicon.Source {
    return favicon.Source{Raster: logo}
}

sitec deriva el juego completo vía webtyp.com/image/favicon (icon-32.png, icon-192.png, apple-touch-icon.png, favicon.ico y favicon.svg si se provee SVG) y emite un <link> por cada archivo con Rel.

sitec no sanea el SVG que reciba: un SVG de un tercero se limpia antes con webtyp.com/svg/sanitize. El de un proyecto es suyo y es de confianza.

Aplicación Web Progresiva (PWA)

Un proyecto se convierte en PWA declarando Favicon() (con un logo de al menos 512 px) y PWA() en su paquete raíz (!wasm):

func (a *App) Favicon() favicon.Source {
    return favicon.Source{Raster: logo} // logo >= 512x512
}

func (a *App) PWA() pwa.Config {
    return pwa.Config{
        Name:            "Mi Aplicación",
        ShortName:       "App",
        ThemeColor:      "#0080ff",
        BackgroundColor: "#ffffff",
    }
}

En builds de producción (ModeRelease), sitec emite automáticamente manifest.webmanifest, inyecta los tags <head> y el script de registro del service worker, renombra los activos con su hash de contenido (style.3f9a1c2b.css) y genera sw.js con el manifiesto de precaché completo. En desarrollo (ModeDev), mantiene nombres fijos sin service worker.

Artefactos pesados

Los archivos grandes que descarga el código del navegador (pesos de modelos, cachés) se declaran con ArtifactSources() en el paquete raíz (!wasm), junto a Favicon() y PWA():

//go:build !wasm

func ArtifactSources() []artifacts.Source {
	return []artifacts.Source{{ID: "decider-0.8b", Version: "q4-2026-09",
		File: "models/decider.wtypw", Needs: device.Requirement{MinTier: device.TierSIMD}}}
}

sitec mide cada archivo (tamaño y SHA-256, sin cargarlo en memoria), escribe /artifacts.json y, en Build, coloca cada archivo bajo /artifacts/ con un enlace duro (o una copia por streaming). Nunca se empaquetan ni se precachean; server/httpd los sirve con Cache-Control: no-store (vía pwa.CacheControl). En desarrollo (webtyp dev) el Compiler escribe el mismo /artifacts.json y sitec/serve entrega cada archivo desde donde está, con Range, sin copiarlo.

Web Workers

El código pesado (modelos, inferencia) se extrae del hilo principal. Una convención de directorios registra los workers: cualquier subdirectorio bajo web/workers/ que contenga un main.go se compila. El nombre del subdirectorio es el nombre del worker (ej. web/workers/echo/main.go → worker echo).

En release, sitec compila cada worker dos veces:

  1. Una versión SIMD (TinyGo +simd128, -opt=2) para navegadores modernos, que duplica el rendimiento de los modelos (D16).
  2. Una versión plana (-opt=2) como fallback.

En desarrollo (webtyp dev, vía Compiler.BuildWorkers) cada worker se compila una sola vez con TinyGo, SIMD y -opt=2 como <name>.wasm, y los dos scripts lo cargan.

Produce cuatro archivos por worker:

  • El script arrancador: <name>.worker.js (apunta a la versión plana).
  • El script arrancador SIMD: <name>.simd.worker.js (apunta a la versión SIMD).
  • Los binarios WASM hasheados: <name>.<hash>.wasm y <name>.simd.<hash>.wasm.

La aplicación lo arranca así en su código de página:

agentworker.Start(Scripts{
    Plain: "/echo.worker.js",
    SIMD:  "/echo.simd.worker.js",
}, ...)

Estado

En construcción.

Documentation

Index

Constants

View Source
const (
	DefaultOutputDir    = "web/public"
	DefaultImageQuality = 82
)
View Source
const ErrRouteCollides = "route %s %s (%s:%d) collides with the static asset %s — the asset is served first and the route would never run"

ErrRouteCollides is returned when a declared route has the same path as a produced static artifact. The artifact is served first, so the route would be unreachable with no error anywhere.

View Source
const ShellPath = "/app/"

ShellPath is where the WASM application shell is mounted when a project ALSO declares static pages: the pages own "/", the shell lives here.

It is a constant, not an option, and must stay that way. A framework exists to remove decisions, not to offer them (see the api-design skill): every webtyp app puts its shell at the same place, so the size and the behaviour of any of them can be reasoned about the same way. Making this configurable would hand the decision back to each app and buy nothing.

A project with no pages is unaffected: its shell stays at "/" with relative asset paths, exactly as before — that is the case every existing app is in.

View Source
const WorkersDir = "web/workers"

WorkersDir holds the project's Web Workers: every web/workers/<name>/main.go is one.

Variables

This section is empty.

Functions

func Build

func Build(rootDir, outDir string, opts ...Option) error

Build compiles every asset of the project rooted at rootDir and writes the servable tree to outDir. One pass, no watching, no server: this is the entry point a release pipeline calls.

Note: compiling the Go WASM binary (e.g. via go build or tinygo) is the caller's responsibility.

func Check

func Check(rootDir string, log func(...any)) ([]string, error)

Check validates the project extraction and returns the list of extracted module names.

func Dictionary added in v0.2.50

func Dictionary() []byte

Dictionary returns this tool's translations (its lang.json, embedded), for lang.Load at the tool's startup.

func FileWrite

func FileWrite(pathFile string, data bytes.Buffer) error

pathFile e.g., "theme/htmlMainFileName" data e.g., *bytes.Buffer NOTE: The buffer data will be cleared after writing the file

func GenerateExtractorMain

func GenerateExtractorMain(outputFile string, modules []module, scanner *scanner, assetLibraries []string, startDir string, lister GraphLister, log func(...any), verbose bool) error

GenerateExtractorMain writes a main.go file that imports all modules and collects their assets.

func NewFaviconSvgHandler

func NewFaviconSvgHandler(ac *Config, filename string) *asset

func NewHtmlHandler

func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL, faviconURL string) *asset

NewHtmlHandler creates an HTML asset handler using the provided output filename

func ParseExistingHtmlContent

func ParseExistingHtmlContent(content string) (openContent, closeContent string)

ParseExistingHtmlContent is a public wrapper for tests.

func RewriteAssetUrls

func RewriteAssetUrls(htmlStr string, newRoot string) string

RewriteAssetUrls is a public wrapper for tests.

func StripLeadingUseStrict

func StripLeadingUseStrict(b []byte) []byte

StripLeadingUseStrict is a public wrapper for tests.

func ValidateProject

func ValidateProject(dir string) error

ValidateProject checks if the given directory contains a valid sitec project.

func VerifyTinyGoCompatible

func VerifyTinyGoCompatible(dir string) error

VerifyTinyGoCompatible checks if the source tree is compatible with TinyGo compilation. It reports why the source tree would not compile with TinyGo, or nil if compatible.

func WorkerNames added in v0.2.44

func WorkerNames(root string) ([]string, error)

WorkerNames returns the names of the project's Workers (directories under WorkersDir with a main.go), or an error naming a directory that is not a valid name.

Types

type Artifact

type Artifact struct {
	Path      string
	Mediatype string
	Content   []byte
}

Artifact se autodescribe: la ruta ES la URL. No hay una segunda tabla de rutas que mantener en sincronía.

type Assets

type Assets struct {
	ModuleName      string
	RootCSS         string
	CSS             string
	JS              []*js.Script
	HTML            string
	Icons           *sprite.Sprite
	Fonts           font.Declaration // family declared by the module; zero value = none
	Pages           []html.Page
	Site            *Site              // declarado por RenderSite(); solo el raíz puede; nil = no declarado
	Favicon         *FaviconWire       // declarado por Favicon(); solo el raíz puede; nil = no declarado
	PWA             *pwa.Config        // declared by PWA(); root only; nil = not declared
	ArtifactSources []artifacts.Source // declared by ArtifactSources(); root only; placed under pwa.ArtifactsDir, never in memory
	IsRoot          bool
	IsFramework     bool
}

Assets is what compiling one module yields: the raw output its producers emitted, before minification and before anything is written to disk.

This type is the contract between the compiler and whoever consumes its output. It lives here, with the producer. It used to live in webtyp.com/assetmin — the consumer — which forced the producer to import the minifier, and with it an HTTP router and a terminal UI, just to name its own result.

type BuildConfig

type BuildConfig struct {
	RootDir        string // Root directory of the module (where go.mod lives). Required.
	Mode           Mode
	OutputDir      string // Relative to RootDir. Empty => DefaultOutputDir.
	SiteURL        string // Enables sitemap.xml and absolute canonical URLs.
	AppName        string
	StaticAssets   []string // Declared static assets relative to RootDir copied verbatim.
	ImageQuality   int      // 0 => DefaultImageQuality
	AssetLibraries []string // Style libraries whose importers must declare a producer.
	Log            func(...any)
}

BuildConfig contains the site build settings.

type CollectorOutput

type CollectorOutput struct {
	Root    string           `json:"root"`
	Render  string           `json:"render"`
	HTML    string           `json:"html"`
	Scripts []ScriptOutput   `json:"scripts"`
	Icons   *sprite.Sprite   `json:"icons"`
	Fonts   font.Declaration `json:"fonts"`
	Pages   []html.Page      `json:"pages"`
	Site    *Site            `json:"site"`
	Favicon *FaviconWire     `json:"favicon"`
	PWA     *pwa.Config      `json:"pwa"`
	// ArtifactSources are the large files declared by ArtifactSources(); root only.
	ArtifactSources []artifacts.Source `json:"artifacts"`
}

CollectorOutput is the structure produced by the generated main.go

func MergeResultsFor

func MergeResultsFor(modulePath string, results map[string]CollectorOutput) (CollectorOutput, bool, error)

MergeResultsFor gathers the module's own assets plus those of every package under it, in a stable order so the emitted CSS does not shuffle between runs.

type Compiler added in v0.2.9

type Compiler struct {
	*Config

	InitialLoadFailed bool // true tras agotar los reintentos de ExtractAll; el próximo evento SSR debe reintentar el escaneo completo
	// contains filtered or unexported fields
}

func NewCompiler added in v0.2.9

func NewCompiler(ac *Config) *Compiler

func (*Compiler) BuildWorkers added in v0.2.44

func (c *Compiler) BuildWorkers() error

BuildWorkers builds every Worker of the project into the Compiler's FS: in release twice, plain and SIMD, with content-hashed names; in development once, with TinyGo, the SIMD target and -opt=2, as <name>.wasm, both scripts pointing to it (a Worker runs heavy code such as a model, which Go's WebAssembly runs several times slower; development machines have SIMD).

func (*Compiler) ContainsCSS added in v0.2.9

func (c *Compiler) ContainsCSS(substr string) bool

ContainsCSS checks if the CSS bundle contains the given substring.

func (*Compiler) ContainsHTML added in v0.2.9

func (c *Compiler) ContainsHTML(substr string) bool

ContainsHTML checks if the HTML bundle contains the given substring.

func (*Compiler) ContainsJS added in v0.2.9

func (c *Compiler) ContainsJS(substr string) bool

ContainsJS checks if the JS bundle contains the given substring.

func (*Compiler) ContainsSVG added in v0.2.9

func (c *Compiler) ContainsSVG(substr string) bool

ContainsSVG checks if the SVG sprite contains the given substring.

func (*Compiler) DiskMirrored added in v0.2.9

func (c *Compiler) DiskMirrored() bool

DiskMirrored reports whether FlushToDisk has already succeeded, and therefore every subsequent asset regeneration is being mirrored to disk.

func (*Compiler) EnableSSRMode added in v0.2.9

func (c *Compiler) EnableSSRMode()

EnableSSRMode activates the SSR event branch unconditionally. Pure setter.

func (*Compiler) EnsureOutputDirectoryExists added in v0.2.9

func (c *Compiler) EnsureOutputDirectoryExists()

func (*Compiler) FlushToDisk added in v0.2.9

func (c *Compiler) FlushToDisk() error

FlushToDisk snapshots all registered assets AND direct artifacts (images, the WASM binary — anything registered via Write instead of the minifier pipeline), writes them to disk (overwrite), and sets diskMirrored = true only if every write across both batches succeeds. Returns the first error.

func (*Compiler) GetCSSURLPath added in v0.2.9

func (c *Compiler) GetCSSURLPath() string

GetCSSURLPath returns the URL path for the main CSS file.

func (*Compiler) GetCachedHTML added in v0.2.9

func (c *Compiler) GetCachedHTML() []byte

GetCachedHTML returns the cached minified HTML content.

func (*Compiler) GetFaviconURLPath added in v0.2.9

func (c *Compiler) GetFaviconURLPath() string

GetFaviconURLPath returns the URL path for the favicon file.

func (*Compiler) GetInitCodeJS added in v0.2.9

func (c *Compiler) GetInitCodeJS() (string, error)

GetInitCodeJS returns the init code for the JS bundle.

func (*Compiler) GetJSURLPath added in v0.2.9

func (c *Compiler) GetJSURLPath() string

GetJSURLPath returns the URL path for the main JS file.

func (*Compiler) GetMainCssPath added in v0.2.9

func (c *Compiler) GetMainCssPath() string

GetMainCssPath returns the output path of the main CSS file.

func (*Compiler) GetMainHtmlPath added in v0.2.9

func (c *Compiler) GetMainHtmlPath() string

GetMainHtmlPath returns the output path of the main HTML file.

func (*Compiler) GetMainJsPath added in v0.2.9

func (c *Compiler) GetMainJsPath() string

GetMainJsPath returns the output path of the main JS file.

func (*Compiler) GetMinifiedCSS added in v0.2.9

func (c *Compiler) GetMinifiedCSS() ([]byte, error)

GetMinifiedCSS returns the minified content of the CSS bundle.

func (*Compiler) GetMinifiedJS added in v0.2.9

func (c *Compiler) GetMinifiedJS() ([]byte, error)

GetMinifiedJS returns the minified content of the JS bundle.

func (*Compiler) HasIcon added in v0.2.9

func (c *Compiler) HasIcon(id string) bool

HasIcon checks if an icon with the given ID is registered.

func (*Compiler) InjectCSS added in v0.2.9

func (c *Compiler) InjectCSS(name string, content string)

AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css"). AddCSS appends CSS content from providers to the bundle InjectCSS appends CSS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.css").

func (*Compiler) InjectHTML added in v0.2.9

func (c *Compiler) InjectHTML(html string)

InjectHTML appends HTML to the body

func (*Compiler) InjectJS added in v0.2.9

func (c *Compiler) InjectJS(name string, content string)

AddJS appends JS content from providers to the bundle InjectJS appends JS content to the bundle. name is used for the virtual filename (e.g., "mycomponent.js").

func (*Compiler) InjectSpriteIcon added in v0.2.9

func (c *Compiler) InjectSpriteIcon(id, svg, viewBox string) error

AddIcon adds icons from providers to the bundle InjectSpriteIcon adds an icon to the sprite bundle. id: unique icon ID. svg: raw SVG content (the symbol body, e.g. `<path d="..."/>`). viewBox: the coordinate system the content was drawn in, e.g. "0 0 24 24".

func (*Compiler) IsSSRMode added in v0.2.9

func (c *Compiler) IsSSRMode() bool

IsSSRMode returns true if the package is being used as a dependency (SSR mode).

func (*Compiler) LargeFile added in v0.2.44

func (c *Compiler) LargeFile(url string) (path string, ok bool)

LargeFile returns where on disk the declared artifact served at url is (sitec/serve streams it in development; Build places it in release).

func (*Compiler) LargeFiles added in v0.2.44

func (c *Compiler) LargeFiles() []artifacts.LocalFile

LargeFiles returns the declared artifacts with their path on disk.

func (*Compiler) List added in v0.2.9

func (c *Compiler) List() []Artifact

func (*Compiler) LoadSSRModules added in v0.2.9

func (c *Compiler) LoadSSRModules()

func (*Compiler) LoadStaticAssets added in v0.2.9

func (c *Compiler) LoadStaticAssets() error

LoadStaticAssets copia a la salida los activos declarados por RenderSite(). Separado de RouteExtractedAssets porque un activo estático no participa en la cascada de CSS ni en el sprite: solo se copia.

Es el camino que usa el demonio de desarrollo: Compiler conoce el sitio del raíz y puede copiar lo que declara sin pasar por Build(). Build() la usa igualmente, unida a BuildConfig.StaticAssets y sin duplicados.

func (*Compiler) Logger added in v0.2.9

func (c *Compiler) Logger(messages ...any)

func (*Compiler) MinifyEnabled added in v0.2.9

func (c *Compiler) MinifyEnabled() bool

MinifyEnabled reports whether minification is currently on.

func (*Compiler) Name added in v0.2.9

func (c *Compiler) Name() string

func (*Compiler) NewFileEvent added in v0.2.9

func (c *Compiler) NewFileEvent(fileName, extension, filePath, event string) error

func (*Compiler) PublishImages added in v0.2.9

func (c *Compiler) PublishImages() error

PublishImages mete las imágenes ya procesadas en el conjunto de artefactos en memoria (Artifacts()), que es lo único que el servidor de desarrollo consulta y lo que el release vuelca con WriteTo.

Sin esto una imagen solo existía como archivo en el caché de conversión, así que la única manera de servirla era que el demonio creara un directorio de salida dentro del proyecto del usuario —una segunda salida del sitio, con bytes distintos a los del entregable de release.

NO escribe en disco: escribir es responsabilidad de quien decide volcar (Site/Output.WriteTo, FlushToDisk), no un efecto secundario de publicar. El contenido sale idéntico porque el pipeline es determinista.

Es idempotente: reescribe cada ruta con el contenido actual.

func (*Compiler) Read added in v0.2.9

func (c *Compiler) Read(p string) ([]byte, string, bool)

FS implementation for Compiler:

func (*Compiler) RefreshJSAssets added in v0.2.9

func (c *Compiler) RefreshJSAssets()

RefreshJSAssets triggers a refresh of JS assets. Call this when the WASM binary changes to ensure they are up to date.

func (*Compiler) RegenerateHTMLCache added in v0.2.9

func (c *Compiler) RegenerateHTMLCache() error

RegenerateHTMLCache forces regeneration of the HTML cache.

func (*Compiler) RegisterComponents added in v0.2.9

func (c *Compiler) RegisterComponents(providers ...any) error

RegisterComponents registra structs que implementan las interfaces SSR.

func (*Compiler) ReloadSSRModule added in v0.2.9

func (c *Compiler) ReloadSSRModule(moduleDir string) error

func (*Compiler) RouteExtractedAssets added in v0.2.9

func (c *Compiler) RouteExtractedAssets(all []*Assets) error

RouteExtractedAssets applies a batch of already-extracted module assets — deciding which module's RootCSS wins, appending every module's RenderCSS to its slot, and copying declared fonts — then resolves the final root stylesheet. It is the routing half of LoadSSRModules, exported so a caller that needs its own retry/backoff policy around ExtractAll (app's AssetsHandler does) can still reach routing: routeAssets and resolveAndApplyRootCSS are unexported, and Go does not promote them through embedding across package boundaries.

func (*Compiler) SetFS added in v0.2.9

func (c *Compiler) SetFS(fs FS)

func (*Compiler) SetImageProcessor added in v0.2.9

func (c *Compiler) SetImageProcessor(ip ImageProcessor)

func (*Compiler) SetLog added in v0.2.9

func (c *Compiler) SetLog(f func(message ...any))

func (*Compiler) SetMinifyEnabled added in v0.2.9

func (c *Compiler) SetMinifyEnabled(enabled bool)

SetMinifyEnabled toggles minification on or off. The consumer (app's TUI minify toggle) owns the UI; this is the only way to reach the flag, which was private before — activeMinifier() is the sole reader.

func (*Compiler) SetSSRCompiler added in v0.2.9

func (c *Compiler) SetSSRCompiler(fn func() error)

SetSSRCompiler registers a Go compiler callback. Pure setter — does NOT invoke fn. Pass nil to unregister.

func (*Compiler) SetSSRExtractor added in v0.2.9

func (c *Compiler) SetSSRExtractor(e SSRExtractor)

func (*Compiler) SetTranslations added in v0.2.45

func (c *Compiler) SetTranslations(t Translations)

SetTranslations installs the translations provider. Without it, no dictionary is inlined and the client shows English.

func (*Compiler) SetWasm added in v0.2.9

func (c *Compiler) SetWasm(filename string, runtime string)

func (*Compiler) SupportedExtensions added in v0.2.9

func (c *Compiler) SupportedExtensions() []string

func (*Compiler) UnobservedFiles added in v0.2.9

func (c *Compiler) UnobservedFiles() []string

func (*Compiler) UpdateFileContentInMemory added in v0.2.9

func (c *Compiler) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)

func (*Compiler) UpdateSSRModule added in v0.2.9

func (c *Compiler) UpdateSSRModule(name string, css string, scripts []*js.Script, html string, icons *sprite.Sprite) error

UpdateSSRModule inyecta o reemplaza los assets de un módulo por nombre en el slot por defecto (middle).

func (*Compiler) UpdateSSRModuleInSlot added in v0.2.9

func (c *Compiler) UpdateSSRModuleInSlot(name string, css string, scripts []*js.Script, html string, icons *sprite.Sprite, slot string) error

UpdateSSRModuleInSlot inyecta o reemplaza los assets de un módulo en el slot especificado.

func (*Compiler) WaitForSSRLoad added in v0.2.9

func (c *Compiler) WaitForSSRLoad(timeout time.Duration)

func (*Compiler) Write added in v0.2.9

func (c *Compiler) Write(outPath string, content []byte, mediatype string) error

Write writes a pre-built artifact (e.g. the compiled WASM binary) straight to the configured FS sink, bypassing the ContentFile-assembly and minification pipeline used for CSS/JS/HTML fragments.

A compiled binary is a finished artifact, not a text fragment to concatenate: WriteContent joins fragments with "\n" between them, which corrupts a binary. And no minifier is registered for arbitrary binary mediatypes (only text/css, javascript, image/svg+xml, text/html are), so routing it through RegenerateCache made minifier.Bytes return ErrNotExist — an error that FlushToDisk's loop silently discarded, leaving the artifact's cache empty and the file written to disk at 0 bytes.

type Config

type Config struct {
	OutputDir       string // eg: web/static, web/public, web/assets
	RootDir         string // Root directory of the project where go.mod exists
	AppName         string // Application name for templates (default: "MyApp")
	AssetsURLPrefix string // New: for HTTP routes
	DevMode         bool   // If true, disables caching (default: false)
	SiteURL         string // Optional: canonical base URL (e.g. "https://example.com"), used for sitemap.xml and canonical URL resolution
}

type ContentFile

type ContentFile struct {
	Path    string // eg: modules/module1/file.js
	Content []byte /// eg: "console.log('hello world')"
}

ContentFile represents a file with its path and content

type Extractor

type Extractor struct {
	AssetLibraries []string
	// contains filtered or unexported fields
}

func New

func New(rootDir string) *Extractor

func (*Extractor) ExtractAll

func (e *Extractor) ExtractAll() ([]*Assets, error)

ExtractAll extracts assets from all discovered modules. An empty result with a nil error means no module declares assets; the caller decides whether that is acceptable.

func (*Extractor) ExtractModule

func (e *Extractor) ExtractModule(moduleDir string) (*Assets, error)

func (*Extractor) SetAssetLibraries

func (e *Extractor) SetAssetLibraries(libs []string)

func (*Extractor) SetFinder

func (e *Extractor) SetFinder(f modfind.Discoverer)

func (*Extractor) SetGraphLister

func (e *Extractor) SetGraphLister(l GraphLister)

func (*Extractor) SetLog

func (e *Extractor) SetLog(fn func(...any))

func (*Extractor) SetToolchain

func (e *Extractor) SetToolchain(t Toolchain)

func (*Extractor) SetVerbose

func (e *Extractor) SetVerbose(v bool)

func (*Extractor) SetWasmBuilder

func (e *Extractor) SetWasmBuilder(wb WasmBuilder)

func (*Extractor) WasmBuilder

func (e *Extractor) WasmBuilder() WasmBuilder

type FS

type FS interface {
	Write(path string, content []byte, mediatype string) error
	Read(path string) ([]byte, string, bool)
	List() []Artifact
}

FS es el sumidero de la etapa emit. memFS no toca disco; osFS escribe.

func NewMemFS

func NewMemFS() FS

func NewOsFS

func NewOsFS() FS

type FaviconWire

type FaviconWire struct {
	Raster []byte `json:"raster"`
	SVG    []byte `json:"svg"`
}

type GraphLister

type GraphLister func(rootDir, pattern, goos, goarch string) ([]string, error)

GraphLister returns the transitive import paths of pattern for the given GOOS/GOARCH. Injected so tests don't need a real toolchain.

type ImageProcessor

type ImageProcessor interface {
	UnobservedFiles() []string
	Artifacts() []imgmin.Artifact
}

type Mode

type Mode uint8

Mode decides what artifact Build produces.

const (
	// ModeRelease is the deliverable: WASM via TinyGo, minified.
	ModeRelease Mode = iota
	// ModeDev is the development cache: fast compilation, unminified.
	ModeDev
)

type Option added in v0.2.27

type Option func(*buildOptions)

Option configures the Build behavior.

func WithLog added in v0.2.27

func WithLog(log func(...any)) Option

WithLog sets a custom logger for the build process.

func WithMinify added in v0.2.27

func WithMinify(enabled bool) Option

WithMinify explicitly sets whether minification is enabled.

func WithoutMinify added in v0.2.27

func WithoutMinify() Option

WithoutMinify disables minification for the build output.

type Output

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

Output es el resultado de un Build COMPLETO: los artefactos producidos, listos para volcarse a un FS (WriteTo) o servirse desde Artifacts().

func BuildWithConfig added in v0.2.27

func BuildWithConfig(cfg BuildConfig) (*Output, error)

BuildWithConfig executes the build pipeline with a custom BuildConfig and returns the Output in memory.

func (*Output) Artifacts

func (s *Output) Artifacts() []Artifact

Artifacts returns all produced artifacts.

func (*Output) LargeFiles added in v0.2.41

func (s *Output) LargeFiles() []artifacts.LocalFile

LargeFiles returns the declared artifacts this build places under pwa.ArtifactsDir, with the path of each on disk. They are never part of Artifacts(): they are too large to hold in memory.

func (*Output) Routes added in v0.2.9

func (s *Output) Routes() []routescan.Decl

Routes returns the routes the project declared in config/routes.go, in source order. Empty when the project declares none.

func (*Output) WriteTo

func (s *Output) WriteTo(fs FS) error

WriteTo writes the built site artifacts to the given FS.

type SSRExtractor

type SSRExtractor interface {
	ExtractModule(moduleDir string) (*Assets, error)
	ExtractAll() ([]*Assets, error)
}

type ScriptOutput

type ScriptOutput struct {
	Name    string `json:"name"`
	Content string `json:"content"`
}

type Site

type Site struct {
	// URL es la URL pública del sitio. Habilita sitemap.xml y las URL
	// canónicas absolutas. Vacía ⇒ no se emite sitemap.
	URL string `json:"url"`

	// StaticAssets son rutas relativas a la raíz del módulo que se copian
	// verbatim a la salida. Para lo que NO pasa por el pipeline de imágenes:
	// SVG de marca, PDF, robots.txt.
	//
	// Un archivo o directorio declarado y ausente es un ERROR de build, no un
	// aviso: un logo que falta en producción se descubre demasiado tarde.
	StaticAssets []string `json:"static_assets"`
}

Site es lo que un módulo RAÍZ declara sobre el sitio que produce.

Declararla convierte al proyecto en un sitio estático: el entregable es el directorio de salida y RenderPages() es el dueño del index.html. Un proyecto sin RenderSite() es una aplicación y su index.html es el shell de arranque del WASM.

Lo que declara RenderSite() manda sobre lo que traiga BuildConfig. El proyecto es la autoridad sobre sí mismo; BuildConfig es el afinado del llamador. Cuando ambos traen valor y difieren, se registra un aviso con los dos valores y se aplica el del proyecto.

type Toolchain

type Toolchain interface {
	List(dir string, args ...string) ([]byte, error)
	ListEnv(dir string, env []string, args ...string) ([]byte, error)
	Run(dir string, args ...string) ([]byte, error)
}

Toolchain ejecuta el toolchain de Go. Todo go list / go run / go build del compilador pasa por este puerto, para que el cacheo, el manejo de GOOS y la clasificación de errores existan en exactamente un lugar.

func NewExecToolchain

func NewExecToolchain() Toolchain

type Translations added in v0.2.45

type Translations interface {
	// SyncTranslations updates <rootDir>/config/lang.json from the code.
	SyncTranslations(rootDir string) error
	// BundleTranslations returns the complete <script type="application/json" ...>
	// element with the merged dictionary, or "" when there is nothing to ship.
	BundleTranslations(rootDir string) (string, error)
}

Translations keeps the project's translation files in step with its code and produces the element the client reads its dictionary from. webtyp.com/lang/langc implements it; the app injects it.

type WasmBuildOptions

type WasmBuildOptions struct {
	// Entry is the input file relative to the directory passed to Build, used to
	// locate the package directory to compile and verify its existence.
	// Empty means "web/browser/main.go".
	Entry string
	// OutputName is the artifact name without the .wasm extension.
	// Empty means "browser".
	OutputName string

	// SIMD builds with TinyGo +simd128 and -opt=2 (Web Workers that run models).
	SIMD bool
	// Speed builds with -opt=2 (Web Workers are compiled for speed, pages for size).
	// SIMD implies Speed.
	Speed bool
	// HashName hashes the content and uses it in the output name.
	HashName bool
}

WasmBuildOptions selects what to compile and what to call the result.

The zero value builds a site frontend: web/browser/main.go → browser.wasm. Set the fields to compile something else — an edge worker entry point, for example, which is main.go and must come out named for the platform that serves it.

type WasmBuilder

type WasmBuilder interface {
	Build(dir string) (WasmOutput, error)
}

WasmBuilder produce el binario del cliente Y el runtime JS que lo carga. sitec decide sus rutas, sus nombres y su sink; CÓMO compilarlo (TinyGo vs Go, flags) es del adaptador.

func NewDefaultWasmBuilder

func NewDefaultWasmBuilder(devMode bool) WasmBuilder

NewDefaultWasmBuilder builds a site frontend from web/browser/main.go. In release (devMode false) the binary is named by its content hash (browser.<hash>.wasm) and the page bootstrap loads that name.

func NewWasmBuilder

func NewWasmBuilder(stdlib bool, opts WasmBuildOptions) WasmBuilder

NewWasmBuilder builds an arbitrary entry point, for callers that are not compiling a site frontend. The output keeps its fixed name (e.g. an edge Worker binary that a deploy config references by name): only the page binary is content-hashed.

type WasmOutput

type WasmOutput struct {
	Binary   []byte // el .wasm
	Filename string // su nombre, que el shell HTML referencia
	Runtime  string // el glue JS correspondiente al modo usado
}

WasmOutput son los DOS artefactos de una compilación. Van juntos a propósito: TinyGo y Go estándar emiten runtimes wasm_exec distintos, así que un binario servido con el loader del otro modo no arranca. Devolverlos por separado permitiría emparejarlos mal.

Directories

Path Synopsis
cmd
sitec command

Jump to

Keyboard shortcuts

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