Documentation
¶
Index ¶
- Constants
- func Build(rootDir, outDir string, opts ...Option) error
- func Check(rootDir string, log func(...any)) ([]string, error)
- func Dictionary() []byte
- func FileWrite(pathFile string, data bytes.Buffer) error
- func GenerateExtractorMain(outputFile string, modules []module, scanner *scanner, assetLibraries []string, ...) error
- func NewFaviconSvgHandler(ac *Config, filename string) *asset
- func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL, faviconURL string) *asset
- func ParseExistingHtmlContent(content string) (openContent, closeContent string)
- func RewriteAssetUrls(htmlStr string, newRoot string) string
- func StripLeadingUseStrict(b []byte) []byte
- func ValidateProject(dir string) error
- func VerifyTinyGoCompatible(dir string) error
- func WorkerNames(root string) ([]string, error)
- type Artifact
- type Assets
- type BuildConfig
- type CollectorOutput
- type Compiler
- func (c *Compiler) BuildWorkers() error
- func (c *Compiler) ContainsCSS(substr string) bool
- func (c *Compiler) ContainsHTML(substr string) bool
- func (c *Compiler) ContainsJS(substr string) bool
- func (c *Compiler) ContainsSVG(substr string) bool
- func (c *Compiler) DiskMirrored() bool
- func (c *Compiler) EnableSSRMode()
- func (c *Compiler) EnsureOutputDirectoryExists()
- func (c *Compiler) FlushToDisk() error
- func (c *Compiler) GetCSSURLPath() string
- func (c *Compiler) GetCachedHTML() []byte
- func (c *Compiler) GetFaviconURLPath() string
- func (c *Compiler) GetInitCodeJS() (string, error)
- func (c *Compiler) GetJSURLPath() string
- func (c *Compiler) GetMainCssPath() string
- func (c *Compiler) GetMainHtmlPath() string
- func (c *Compiler) GetMainJsPath() string
- func (c *Compiler) GetMinifiedCSS() ([]byte, error)
- func (c *Compiler) GetMinifiedJS() ([]byte, error)
- func (c *Compiler) HasIcon(id string) bool
- func (c *Compiler) InjectCSS(name string, content string)
- func (c *Compiler) InjectHTML(html string)
- func (c *Compiler) InjectJS(name string, content string)
- func (c *Compiler) InjectSpriteIcon(id, svg, viewBox string) error
- func (c *Compiler) IsSSRMode() bool
- func (c *Compiler) LargeFile(url string) (path string, ok bool)
- func (c *Compiler) LargeFiles() []artifacts.LocalFile
- func (c *Compiler) List() []Artifact
- func (c *Compiler) LoadSSRModules()
- func (c *Compiler) LoadStaticAssets() error
- func (c *Compiler) Logger(messages ...any)
- func (c *Compiler) MinifyEnabled() bool
- func (c *Compiler) Name() string
- func (c *Compiler) NewFileEvent(fileName, extension, filePath, event string) error
- func (c *Compiler) PublishImages() error
- func (c *Compiler) Read(p string) ([]byte, string, bool)
- func (c *Compiler) RefreshJSAssets()
- func (c *Compiler) RegenerateHTMLCache() error
- func (c *Compiler) RegisterComponents(providers ...any) error
- func (c *Compiler) ReloadSSRModule(moduleDir string) error
- func (c *Compiler) RouteExtractedAssets(all []*Assets) error
- func (c *Compiler) SetFS(fs FS)
- func (c *Compiler) SetImageProcessor(ip ImageProcessor)
- func (c *Compiler) SetLog(f func(message ...any))
- func (c *Compiler) SetMinifyEnabled(enabled bool)
- func (c *Compiler) SetSSRCompiler(fn func() error)
- func (c *Compiler) SetSSRExtractor(e SSRExtractor)
- func (c *Compiler) SetTranslations(t Translations)
- func (c *Compiler) SetWasm(filename string, runtime string)
- func (c *Compiler) SupportedExtensions() []string
- func (c *Compiler) UnobservedFiles() []string
- func (c *Compiler) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)
- func (c *Compiler) UpdateSSRModule(name string, css string, scripts []*js.Script, html string, ...) error
- func (c *Compiler) UpdateSSRModuleInSlot(name string, css string, scripts []*js.Script, html string, ...) error
- func (c *Compiler) WaitForSSRLoad(timeout time.Duration)
- func (c *Compiler) Write(outPath string, content []byte, mediatype string) error
- type Config
- type ContentFile
- type Extractor
- func (e *Extractor) ExtractAll() ([]*Assets, error)
- func (e *Extractor) ExtractModule(moduleDir string) (*Assets, error)
- func (e *Extractor) SetAssetLibraries(libs []string)
- func (e *Extractor) SetFinder(f modfind.Discoverer)
- func (e *Extractor) SetGraphLister(l GraphLister)
- func (e *Extractor) SetLog(fn func(...any))
- func (e *Extractor) SetToolchain(t Toolchain)
- func (e *Extractor) SetVerbose(v bool)
- func (e *Extractor) SetWasmBuilder(wb WasmBuilder)
- func (e *Extractor) WasmBuilder() WasmBuilder
- type FS
- type FaviconWire
- type GraphLister
- type ImageProcessor
- type Mode
- type Option
- type Output
- type SSRExtractor
- type ScriptOutput
- type Site
- type Toolchain
- type Translations
- type WasmBuildOptions
- type WasmBuilder
- type WasmOutput
Constants ¶
const ( DefaultOutputDir = "web/public" DefaultImageQuality = 82 )
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.
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.
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 ¶
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 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 ¶
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 NewHtmlHandler ¶
NewHtmlHandler creates an HTML asset handler using the provided output filename
func ParseExistingHtmlContent ¶
ParseExistingHtmlContent is a public wrapper for tests.
func RewriteAssetUrls ¶
RewriteAssetUrls is a public wrapper for tests.
func StripLeadingUseStrict ¶
StripLeadingUseStrict is a public wrapper for tests.
func ValidateProject ¶
ValidateProject checks if the given directory contains a valid sitec project.
func VerifyTinyGoCompatible ¶
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
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 ¶
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 (*Compiler) BuildWorkers ¶ added in v0.2.44
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
ContainsCSS checks if the CSS bundle contains the given substring.
func (*Compiler) ContainsHTML ¶ added in v0.2.9
ContainsHTML checks if the HTML bundle contains the given substring.
func (*Compiler) ContainsJS ¶ added in v0.2.9
ContainsJS checks if the JS bundle contains the given substring.
func (*Compiler) ContainsSVG ¶ added in v0.2.9
ContainsSVG checks if the SVG sprite contains the given substring.
func (*Compiler) DiskMirrored ¶ added in v0.2.9
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
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
GetCSSURLPath returns the URL path for the main CSS file.
func (*Compiler) GetCachedHTML ¶ added in v0.2.9
GetCachedHTML returns the cached minified HTML content.
func (*Compiler) GetFaviconURLPath ¶ added in v0.2.9
GetFaviconURLPath returns the URL path for the favicon file.
func (*Compiler) GetInitCodeJS ¶ added in v0.2.9
GetInitCodeJS returns the init code for the JS bundle.
func (*Compiler) GetJSURLPath ¶ added in v0.2.9
GetJSURLPath returns the URL path for the main JS file.
func (*Compiler) GetMainCssPath ¶ added in v0.2.9
GetMainCssPath returns the output path of the main CSS file.
func (*Compiler) GetMainHtmlPath ¶ added in v0.2.9
GetMainHtmlPath returns the output path of the main HTML file.
func (*Compiler) GetMainJsPath ¶ added in v0.2.9
GetMainJsPath returns the output path of the main JS file.
func (*Compiler) GetMinifiedCSS ¶ added in v0.2.9
GetMinifiedCSS returns the minified content of the CSS bundle.
func (*Compiler) GetMinifiedJS ¶ added in v0.2.9
GetMinifiedJS returns the minified content of the JS bundle.
func (*Compiler) HasIcon ¶ added in v0.2.9
HasIcon checks if an icon with the given ID is registered.
func (*Compiler) InjectCSS ¶ added in v0.2.9
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
InjectHTML appends HTML to the body
func (*Compiler) InjectJS ¶ added in v0.2.9
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
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
IsSSRMode returns true if the package is being used as a dependency (SSR mode).
func (*Compiler) LargeFile ¶ added in v0.2.44
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
LargeFiles returns the declared artifacts with their path on disk.
func (*Compiler) LoadSSRModules ¶ added in v0.2.9
func (c *Compiler) LoadSSRModules()
func (*Compiler) LoadStaticAssets ¶ added in v0.2.9
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) MinifyEnabled ¶ added in v0.2.9
MinifyEnabled reports whether minification is currently on.
func (*Compiler) NewFileEvent ¶ added in v0.2.9
func (*Compiler) PublishImages ¶ added in v0.2.9
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) 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
RegenerateHTMLCache forces regeneration of the HTML cache.
func (*Compiler) RegisterComponents ¶ added in v0.2.9
RegisterComponents registra structs que implementan las interfaces SSR.
func (*Compiler) ReloadSSRModule ¶ added in v0.2.9
func (*Compiler) RouteExtractedAssets ¶ added in v0.2.9
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) SetImageProcessor ¶ added in v0.2.9
func (c *Compiler) SetImageProcessor(ip ImageProcessor)
func (*Compiler) SetMinifyEnabled ¶ added in v0.2.9
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
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) SupportedExtensions ¶ added in v0.2.9
func (*Compiler) UnobservedFiles ¶ added in v0.2.9
func (*Compiler) UpdateFileContentInMemory ¶ added in v0.2.9
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 (*Compiler) Write ¶ added in v0.2.9
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 (*Extractor) ExtractAll ¶
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 (*Extractor) SetAssetLibraries ¶
func (*Extractor) SetFinder ¶
func (e *Extractor) SetFinder(f modfind.Discoverer)
func (*Extractor) SetGraphLister ¶
func (e *Extractor) SetGraphLister(l GraphLister)
func (*Extractor) SetToolchain ¶
func (*Extractor) SetVerbose ¶
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.
type FaviconWire ¶
type GraphLister ¶
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 Option ¶ added in v0.2.27
type Option func(*buildOptions)
Option configures the Build behavior.
func WithMinify ¶ added in v0.2.27
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) LargeFiles ¶ added in v0.2.41
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.
type SSRExtractor ¶
type ScriptOutput ¶
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.
Source Files
¶
- assets.go
- build.go
- cache.go
- dictionary.go
- emit_asset.go
- emit_core.go
- emit_events.go
- emit_favicon.go
- emit_filewrite.go
- emit_flush.go
- emit_fonts.go
- emit_html.go
- emit_images.go
- emit_injection.go
- emit_inspect.go
- emit_route.go
- emit_ssr_register.go
- emit_svg.go
- extract.go
- fs.go
- large.go
- merge.go
- pipeline.go
- reach.go
- release.go
- scanner.go
- select.go
- select_tinygo_verify.go
- toolchain.go
- toolchain_exec.go
- wasm_builder_exec.go
- workers.go