webbundle

package module
v1.0.0-dev.7 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README

webbundle

Go Reference Go version

webbundle builds your single-page app's web bundle with esbuild at build time. It writes content-hashed scripts and stylesheets, the shells that name them, icons, licence notices and the manifest this repository's httpserver.SPA serves.

It replaces the bundle program each app writes around esbuild's Go API. It runs from your Dockerfile's builder stage and from go generate, never in your app binary, and needs no Node process once your npm packages are installed. It depends on esbuild, go/httpserver, golang.org/x/net (its HTML parser reads the shells) and the oksvg and rasterx SVG renderers, and is licensed under Apache-2.0.

Why use it

webbundle is built for a Go server that serves a TypeScript front end through httpserver.SPA.

  • Every built file has a content-hashed name, except a classic entry you give a URL of its own, such as a service worker at /sw.js. Two builds of the same inputs write the same bytes.
  • Syntax newer than the pinned browser versions is lowered, or the build fails naming the feature.
  • A shell with an inline script, an inline style or an event handler fails the build, so the strict Content-Security-Policy of SPA never blocks your page.
  • An import of a package you did not allow fails the build with the chain of imports that reached it.
  • Each bundled package's licence files, and those beside your own vendored files, ship in the tree; a package or a vendored font with none fails the build.
  • One SVG gives the favicon, touch icon and manifest icons.
  • A failed build leaves the last good tree in place.

Consider Vite if you want a dev server with hot module replacement, which webbundle does not have.

Install

go get github.com/cplieger/go/webbundle@latest

Usage

Your bundle program fills one Config and calls Build. The shells name each entry by its logical path, such as <script type="module" src="/app.js">, and Build writes the hashed path in its place.

// cmd/bundle/main.go
package main

import (
	"flag"
	"log"
	"os"
	"path/filepath"

	"github.com/cplieger/go/webbundle"

	"example.com/app/internal/webui"
)

func main() {
	pages := flag.Bool("pages", false, "write the page table and corpus, then stop")
	flag.Parse()
	if *pages {
		writePages()
		return
	}
	_, err := webbundle.Build(webbundle.Config{
		Src:       "web",
		Out:       "internal/webui/dist",
		Pages:     webui.Pages,
		APIPrefix: "/api",
		Entries: []webbundle.Entry{
			{Name: "prepaint", Path: "src/prepaint.ts", Kind: webbundle.Classic, Allow: []string{"@cplieger/ui/theme"}},
			{Name: "app", Path: "src/main.ts", Kind: webbundle.Module},
			{Name: "app", Path: "src/app.css", Kind: webbundle.Style},
		},
		Icon:     "icon.svg",
		Manifest: "manifest.json",
	})
	if err != nil {
		log.Fatal(err)
	}
}

func writePages() {
	table, err := webbundle.RenderPages(webui.Pages, "/api")
	if err != nil {
		log.Fatal(err)
	}
	corpus, err := webbundle.RenderPageCorpus(webui.Pages, "/api")
	if err != nil {
		log.Fatal(err)
	}
	for name, body := range map[string][]byte{"pages.gen.ts": table, "pages.corpus.gen.json": corpus} {
		if err := os.WriteFile(filepath.Join("web", name), body, 0o644); err != nil {
			log.Fatal(err)
		}
	}
}

Run both steps from go generate and commit the two page files. Build refuses a page file that no longer matches Pages, so the browser router and the server always agree on the pages:

//go:generate go run ./cmd/bundle -pages
//go:generate go run ./cmd/bundle

Commit an Out/.gitignore that ignores everything else in the folder, so //go:embed compiles in a clean clone. Build keeps that file byte for byte.

API

  • Building: Build with Config, Entry, EntryKind (Module, Classic, Style), IconPNG (IconPurpose: PurposeAny, PurposeMaskable) and Result (with Output, what each built script holds), and Engines (Engine) for the pinned browser versions.
  • Page files: RenderPages and RenderPageCorpus.
  • One stylesheet: BuildStyle (Stylesheet) and the cmd/style command.

The full reference is on pkg.go.dev.

Licence notices

Build copies the licence and notice files of each bundled npm package version to licenses/<package>@<version>/, and those beside your own bundled files under Src (a vendored font's fonts/LICENSE-monaspace) to licenses/<path under Src>, and lists them in licenses/index.txt. A package or file an entry imports but whose code esbuild drops as unused ships nothing and gets no notice. Ship them with one line in your Dockerfile's runtime stage:

COPY --from=build /src/internal/webui/dist/licenses/ /usr/share/licenses/example-web/

A bundled package whose root folder holds no LICENSE, LICENCE, COPYING, NOTICE or THIRD_PARTY_NOTICES file fails the build, because shipping its code without its licence would breach it. So does a font under Src with no such file in its folder or a folder above it. The output tree lists which files count.

What a build refuses

Build checks the whole configuration before it writes anything, and each error names the entry, file or package at fault. It refuses a shell SPA would refuse, an import outside the allowed packages, a file type SPA does not serve, a stale page file and an icon the renderer cannot draw faithfully. What a build refuses lists every case.

Documentation

  • Configuration lists every field with its default.
  • The output tree covers file names, bundle.json, the notices and how a build replaces the tree.
  • Pages covers the page table and the page corpus.
  • Icons covers the icon files and the web app manifest.
  • Stylesheets covers style entries, their fonts and images, and cmd/style.
  • What a build refuses lists every refusal.

Contributing

Issues and pull requests are welcome. The shared contributing rules apply.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI assistance. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package webbundle builds a single-page app's web bundle with esbuild, at build time: the tree httpserver.SPA serves.

An app's bundle command fills one Config and calls Build. It runs from the Dockerfile's builder stage and from go generate, never in the app binary. Build writes every built file as assets/<name>-<hash>.<ext> (a Classic entry with a URL at that root path instead), each shell at the tree's root with its logical script and stylesheet paths replaced by the built ones, the licence notices of every bundled npm package and own file under licenses/, and bundle.json, the manifest listing every written file with its SHA-256 and every entry with its logical name, kind and path. The tree is built beside Out and swapped in whole, so a failed build leaves the last good one, and two builds of the same inputs write the same bytes.

RenderPages and RenderPageCorpus give the bytes of the TypeScript page table and the page corpus go generate commits; Build refuses either file when it is stale. BuildStyle returns one stylesheet built exactly as a Style entry is, for a test that compares CSS with the built bundle.

Index

Examples

Constants

View Source
const (
	Module  = EntryKind(httpserver.BundleModule)  // ESM, with shared chunks under assets/chunks/
	Classic = EntryKind(httpserver.BundleClassic) // an IIFE with its own closure: the prepaint, a worker host
	Style   = EntryKind(httpserver.BundleStyle)   // CSS, its url() files written as hashed assets
)

The entry kinds, as bundle.json records them.

Variables

This section is empty.

Functions

func BuildStyle

func BuildStyle(s Stylesheet) ([]byte, error)

BuildStyle returns s.Path bundled exactly as a Style entry is (the pinned engines, the file loaders, the assets/<name>-<hash> names, minified), and writes nothing. A test passes it where it needs one stylesheet's built text without a whole Build.

Example
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/cplieger/go/webbundle"
)

func main() {
	src, err := os.MkdirTemp("", "webbundle-example-")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(src)
	files := map[string]string{
		"base.css": ".page { margin: 0 auto; }\n",
		"app.css":  "@import \"./base.css\";\n.title { font-weight: 700; }\n",
	}
	for name, body := range files {
		if err := os.WriteFile(filepath.Join(src, name), []byte(body), 0o644); err != nil {
			log.Fatal(err)
		}
	}
	css, err := webbundle.BuildStyle(webbundle.Stylesheet{Src: src, Path: "app.css"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(css))
}
Output:
.page{margin:0 auto}.title{font-weight:700}

func RenderPageCorpus

func RenderPageCorpus(pages []httpserver.Page, apiPrefix string) ([]byte, error)

RenderPageCorpus returns the page corpus for pages and apiPrefix: a JSON array of httpserver.PageMatcher's answers for each pattern's sample path and its edge cases, then "/", an unknown path, apiPrefix and a path under it. A case whose path holds a dot segment, which a browser's URL parser removes before the router reads it, carries serverOnly. It refuses what RenderPages refuses.

func RenderPages

func RenderPages(pages []httpserver.Page, apiPrefix string) ([]byte, error)

RenderPages returns the TypeScript page table for pages and apiPrefix: PAGES, each page's name to its pattern in pages' order, and API_PREFIX. It refuses what httpserver.NewPageMatcher refuses.

Example
package main

import (
	"fmt"
	"log"

	"github.com/cplieger/go/httpserver/v2"
	"github.com/cplieger/go/webbundle"
)

func main() {
	pages := []httpserver.Page{
		{Name: "library", Pattern: "/library"},
		{Name: "entry", Pattern: "/library/{id}"},
	}
	table, err := webbundle.RenderPages(pages, "/api")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(table))
}
Output:
// Code generated by webbundle. DO NOT EDIT.

export const PAGES = {
  library: "/library",
  entry: "/library/{id}",
} as const;
export const API_PREFIX = "/api";

Types

type Config

type Config struct {
	Define         map[string]string  // esbuild defines, each value JSON
	IconPNGs       map[IconPNG]string // committed PNGs under Src, copied instead of rendered; nil renders
	Src            string             // the static-src root, holding package.json and node_modules
	Out            string             // the output tree the UI package embeds, replaced whole
	PagesFile      string             // the TypeScript page table under Src; "" is "pages.gen.ts"
	APIPrefix      string             // the API's path prefix ("/api"), as httpserver.SPAConfig.APIPrefix
	PageCorpusFile string             // the page corpus under Src; "" is "pages.corpus.gen.json"
	Icon           string             // the app's icon, an SVG under Src; "" is none
	MaskableIcon   string             // an SVG under Src drawn for a mask, listed only in the manifest; "" is none
	Manifest       string             // the web app manifest, a JSON file under Src; "" writes none
	Shells         []string           // the shells under Src; nil is ["index.html"]
	Entries        []Entry
	Pages          []httpserver.Page // the UI package's pages
	Packages       []string          // npm packages a bundle may include; nil is ["@cplieger/*"]
}

Config is one app's bundle: where its sources are, where the tree goes, and what it holds.

Manifest's members pass through to the built manifest, which gains "icons" from Icon and MaskableIcon; each "src" member names a file by its path from the manifest's folder, written as a hashed asset and named by its served URL. Its id, start_url, scope, shortcut urls and share_target.action are root-relative, and all but id lie inside scope.

type Engine

type Engine struct {
	Name    string // "chrome", "firefox" or "safari"
	Version string // the engine's version, as "157" or "27"
}

Engine is a browser engine and the oldest version of it a bundle runs on.

func Engines

func Engines() []Engine

Engines returns the browser engines and versions Build and BuildStyle target: syntax one of them lacks is lowered, or the build fails naming the feature and the engine. A test that needs the support floor reads it here.

type Entry

type Entry struct {
	Name string // the logical name, [a-z][a-z0-9_]*: "/<Name>.js" or "/<Name>.css" in a shell
	Path string // the source file under Src
	Kind EntryKind
	// URL is "" for a hashed path under /assets/. On a Classic entry it may
	// be "/<file>.js": the entry is written there unhashed, the same URL in
	// every build, and bundle.json lists it as stable. A service worker
	// needs one, since the browser looks for its update at the URL it
	// registered; a hashed URL changes with every build, and scope is no
	// reason, since a Service-Worker-Allowed header lets one under /assets/
	// control /.
	URL    string
	Forbid []string // items its imports may not reach
	Allow  []string // when set, the only items its imports may reach
}

Entry is one bundle entry point.

A Forbid or Allow item names an npm package ("@scope/name"), a file a package exports ("@scope/name/sub") or a path under Src ("src/wire", or "./<path>" where it is also a package name), by whole path segments. Both judge only the files whose code the entry ships; the entry file is exempt, and an item that can match no input fails the build. docs/configuration.md gives the full rules.

type EntryKind

type EntryKind string

EntryKind is how an entry is built.

type IconPNG

type IconPNG struct {
	Purpose IconPurpose
	Size    int // in px, the PNG being square
}

IconPNG names one PNG Build writes for the icons: Icon's at 32, 180, 192 and 512 px, MaskableIcon's at 192 and 512 px.

type IconPurpose

type IconPurpose string

IconPurpose is the purpose a manifest lists an icon with.

const (
	PurposeAny      IconPurpose = ""         // Icon's PNGs, listed with no purpose, which is "any"
	PurposeMaskable IconPurpose = "maskable" // MaskableIcon's PNGs, listed as "maskable"
)

The icon purposes.

type Output

type Output struct {
	Packages []string // the npm packages whose code it holds, sorted
	Own      bool     // whether it holds code of a file under Src outside node_modules
}

Output is what one script of the tree holds: an app can tell a chunk built only from npm packages from one that also holds its own code, though both list the same packages.

type Result

type Result struct {
	Outputs map[string]Output // every script in the tree (entries and chunks), by its path under Out; bundle.json does not record it
	Files   []string          // every written path under Out, sorted
	Notices []string          // every npm package whose code the bundle ships, sorted; licenses/index.txt also lists the notices under Src
}

Result is what a build wrote.

func Build

func Build(c Config) (Result, error)

Build builds c's tree into c.Out: the classic entries first, then the module entries (which read the classic entries' served URLs through the BUNDLE_URLS define), then the style entries, the shells with their logical paths replaced, and bundle.json. The tree is built beside Out and swapped in whole, so a refused or failed build leaves Out as it was; Out/.gitignore is carried through byte for byte. Two builds of the same inputs write the same bytes.

type Stylesheet

type Stylesheet struct {
	Src  string // the static-src root, as Config.Src
	Path string // the CSS file, a slash path under Src
}

Stylesheet names one CSS file for BuildStyle.

Directories

Path Synopsis
cmd
style command
Command style prints one CSS file bundled exactly as a webbundle Style entry is, with webbundle.BuildStyle, and writes nothing.
Command style prints one CSS file bundled exactly as a webbundle Style entry is, with webbundle.BuildStyle, and writes nothing.

Jump to

Keyboard shortcuts

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