sitec

package module
v0.1.5 Latest Latest
Warning

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

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

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, 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.

Estado

En construcción. Plan: docs/PLAN.md.

Documentation

Index

Constants

View Source
const (
	DefaultOutputDir    = "web/public"
	DefaultDevOutputDir = ".tinywasm/public"
	DefaultImageQuality = 82
)

Variables

This section is empty.

Functions

func Check added in v0.1.0

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

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

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)) 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 NewSvgHandler

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

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.

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 AssetMin

type AssetMin 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 NewAssetMin

func NewAssetMin(ac *Config) *AssetMin

func (*AssetMin) ContainsCSS

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

ContainsCSS checks if the CSS bundle contains the given substring.

func (*AssetMin) ContainsHTML

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

ContainsHTML checks if the HTML bundle contains the given substring.

func (*AssetMin) ContainsJS

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

ContainsJS checks if the JS bundle contains the given substring.

func (*AssetMin) ContainsSVG

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

ContainsSVG checks if the SVG sprite contains the given substring.

func (*AssetMin) EnableSSRMode

func (c *AssetMin) EnableSSRMode()

EnableSSRMode activates the SSR event branch unconditionally. Pure setter.

func (*AssetMin) EnsureOutputDirectoryExists

func (c *AssetMin) EnsureOutputDirectoryExists()

func (*AssetMin) FlushToDisk

func (c *AssetMin) FlushToDisk() error

FlushToDisk snapshots all registered assets, writes them to disk (overwrite), and sets diskMirrored = true only on full success. Returns the first write error.

func (*AssetMin) GetCSSURLPath

func (c *AssetMin) GetCSSURLPath() string

GetCSSURLPath returns the URL path for the main CSS file.

func (*AssetMin) GetCachedHTML

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

GetCachedHTML returns the cached minified HTML content.

func (*AssetMin) GetFaviconURLPath

func (c *AssetMin) GetFaviconURLPath() string

GetFaviconURLPath returns the URL path for the favicon file.

func (*AssetMin) GetInitCodeJS

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

GetInitCodeJS returns the init code for the JS bundle.

func (*AssetMin) GetJSURLPath

func (c *AssetMin) GetJSURLPath() string

GetJSURLPath returns the URL path for the main JS file.

func (*AssetMin) GetMainCssPath

func (c *AssetMin) GetMainCssPath() string

GetMainCssPath returns the output path of the main CSS file.

func (*AssetMin) GetMainHtmlPath

func (c *AssetMin) GetMainHtmlPath() string

GetMainHtmlPath returns the output path of the main HTML file.

func (*AssetMin) GetMainJsPath

func (c *AssetMin) GetMainJsPath() string

GetMainJsPath returns the output path of the main JS file.

func (*AssetMin) GetMainSvgPath

func (c *AssetMin) GetMainSvgPath() string

GetMainSvgPath returns the output path of the main SVG file.

func (*AssetMin) GetMinifiedCSS

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

GetMinifiedCSS returns the minified content of the CSS bundle.

func (*AssetMin) GetMinifiedJS

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

GetMinifiedJS returns the minified content of the JS bundle.

func (*AssetMin) GetSVGURLPath

func (c *AssetMin) GetSVGURLPath() string

GetSVGURLPath returns the URL path for the SVG sprite file.

func (*AssetMin) HasIcon

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

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

func (*AssetMin) InjectCSS

func (c *AssetMin) 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 (*AssetMin) InjectHTML

func (c *AssetMin) InjectHTML(html string)

InjectHTML appends HTML to the body

func (*AssetMin) InjectJS

func (c *AssetMin) 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 (*AssetMin) InjectSpriteIcon

func (c *AssetMin) 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 (*AssetMin) IsSSRMode

func (c *AssetMin) IsSSRMode() bool

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

func (*AssetMin) List

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

func (*AssetMin) LoadSSRModules

func (c *AssetMin) LoadSSRModules()

func (*AssetMin) LoadStaticAssets added in v0.1.5

func (c *AssetMin) 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: AssetMin 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 (*AssetMin) Logger

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

func (*AssetMin) MinifyEnabled added in v0.0.54

func (c *AssetMin) MinifyEnabled() bool

MinifyEnabled reports whether minification is currently on.

func (*AssetMin) Name

func (c *AssetMin) Name() string

func (*AssetMin) NewFileEvent

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

func (*AssetMin) PublishImages added in v0.1.3

func (c *AssetMin) 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 (*AssetMin) Read

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

FS implementation for AssetMin:

func (*AssetMin) RefreshJSAssets

func (c *AssetMin) RefreshJSAssets()

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

func (*AssetMin) RegenerateHTMLCache

func (c *AssetMin) RegenerateHTMLCache() error

RegenerateHTMLCache forces regeneration of the HTML cache.

func (*AssetMin) RegisterComponents

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

RegisterComponents registra structs que implementan las interfaces SSR.

func (*AssetMin) ReloadSSRModule

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

func (*AssetMin) RouteExtractedAssets added in v0.0.55

func (c *AssetMin) 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 (*AssetMin) SetFS

func (c *AssetMin) SetFS(fs FS)

func (*AssetMin) SetImageProcessor

func (c *AssetMin) SetImageProcessor(ip ImageProcessor)

func (*AssetMin) SetLog

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

func (*AssetMin) SetMinifyEnabled added in v0.0.54

func (c *AssetMin) 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 (*AssetMin) SetSSRCompiler

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

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

func (*AssetMin) SetSSRExtractor

func (c *AssetMin) SetSSRExtractor(e SSRExtractor)

func (*AssetMin) SetWasm

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

func (*AssetMin) SupportedExtensions

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

func (*AssetMin) UnobservedFiles

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

func (*AssetMin) UpdateFileContentInMemory

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

func (*AssetMin) UpdateSSRModule

func (c *AssetMin) 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 (*AssetMin) UpdateSSRModuleInSlot

func (c *AssetMin) 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 (*AssetMin) WaitForSSRLoad

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

func (*AssetMin) Write

func (c *AssetMin) 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 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
	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 github.com/tinywasm/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 added in v0.1.0

type BuildConfig struct {
	RootDir        string // Root directory of the module (where go.mod lives). Required.
	Mode           Mode
	OutputDir      string // Relative to RootDir. Empty => DefaultOutputDir (Release) or DefaultDevOutputDir (Dev).
	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"`
}

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 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)

func (*Extractor) ExtractModule

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

func (*Extractor) Finder added in v0.0.57

func (e *Extractor) Finder() *modfind.Finder

func (*Extractor) SetAssetLibraries

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

func (*Extractor) SetFinder

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

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) 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 GraphLister

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

GraphLister devuelve las rutas de importación transitivas de pattern para el GOOS/GOARCH dado. Se inyecta para que los tests no necesiten toolchain.

type ImageProcessor

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

type Mode added in v0.1.0

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 Output added in v0.1.5

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 Build added in v0.1.0

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

Build executes the entire build pipeline in memory. It does not write to the output disk.

func (*Output) Artifacts added in v0.1.5

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

Artifacts returns all produced artifacts.

func (*Output) WriteTo added in v0.1.5

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 added in v0.1.0

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 WasmBuildOptions added in v0.0.58

type WasmBuildOptions struct {
	// Entry is the input file, relative to the directory passed to Build.
	// Empty means "web/client.go".
	Entry string
	// OutputName is the artifact name without the .wasm extension.
	// Empty means "client".
	OutputName string
}

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

The zero value builds a site frontend: web/client.go → client.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(stdlib bool) WasmBuilder

NewDefaultWasmBuilder builds a site frontend from web/client.go.

func NewWasmBuilder added in v0.0.58

func NewWasmBuilder(stdlib bool, opts WasmBuildOptions) WasmBuilder

NewWasmBuilder builds an arbitrary entry point, for callers that are not compiling a site frontend.

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