Repository navigation
Expand file tree
/
Copy pathwasm_builder_exec.go
More file actions
319 lines (289 loc) · 11.5 KB
/
Copy pathwasm_builder_exec.go
File metadata and controls
319 lines (289 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package sitec
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strings"
"webtyp.com/fmt"
"webtyp.com/goesm"
"webtyp.com/js"
"webtyp.com/minify/v2"
jsmin "webtyp.com/minify/v2/js"
"webtyp.com/pwa"
"webtyp.com/tinygo"
)
// defaultBrowserEntry is the browser main, relative to the project root: one
// main per folder, the folder is the binary. It always compiles to an ES Module
// with goesm (BuildESModule); WebAssembly is only for Web Workers and the edge.
const defaultBrowserEntry = "web/browser/main.go"
// browserBuildTag is the destination tag of the browser binary (reach.go probes it).
const browserBuildTag = "browser"
// localPackagePrefix marks a WasmBuildOptions.Package inside the project
// ("./web/edge"); anything else is an import path ("webtyp.com/pdf/webworker").
const localPackagePrefix = "./"
// WasmBuildOptions selects what to compile, with which compiler, and what to call the result.
// Only Web Workers are WebAssembly: the page and the edge compile to ES Modules with goesm.
type WasmBuildOptions struct {
// Package is the Go package to compile, resolved against the project's go.mod:
// "./web/edge" or "./web/webworkers/<name>" for the project's own mains, an import
// path such as "webtyp.com/pdf/webworker" for a library's Web Worker.
Package string
// OutputName is the artifact name without the .wasm extension.
OutputName string
// Runtime is the compiler: js.RuntimeTinyGo or js.RuntimeGo, as the package's main.go
// declares it (WorkerRuntime).
Runtime js.Runtime
// SIMD builds with TinyGo +simd128 and -opt=2 (Web Workers that run models); TinyGo only:
// Go has no WebAssembly SIMD (GOWASM accepts satconv, signext). SIMD implies Speed.
SIMD bool
// Speed builds TinyGo with -opt=2 (Web Workers are compiled for speed).
Speed bool
// HashName hashes the content and uses it in the output name.
HashName bool
}
type defaultWasmBuilder struct {
opts WasmBuildOptions
}
// NewWasmBuilder compiles opts.Package with opts.Runtime to <OutputName>.wasm (content-hashed
// when opts.HashName). Package, OutputName and Runtime are required.
//
// Example: sitec.NewWasmBuilder(sitec.WasmBuildOptions{Package: "webtyp.com/pdf/webworker", OutputName: "pdf", Runtime: js.RuntimeTinyGo})
func NewWasmBuilder(opts WasmBuildOptions) WasmBuilder {
return &defaultWasmBuilder{opts: opts}
}
const simdTargetJSON = `{"inherits":["wasm"],"features":"+bulk-memory,+bulk-memory-opt,+call-indirect-overlong,+mutable-globals,+nontrapping-fptoint,+sign-ext,-multivalue,-reference-types,+simd128","cflags":["-msimd128"]}`
var execCommand = exec.Command
func (w *defaultWasmBuilder) Build(dir string) (WasmOutput, error) {
if w.opts.Package == "" || w.opts.OutputName == "" {
return WasmOutput{}, fmt.Err(msgWasmOptionsRequired)
}
if w.opts.Runtime != js.RuntimeTinyGo && w.opts.Runtime != js.RuntimeGo {
return WasmOutput{}, fmt.Err(msgWasmRuntimeRequired)
}
if w.opts.Runtime == js.RuntimeGo && w.opts.SIMD {
return WasmOutput{}, fmt.Err(msgGoHasNoWasmSIMD)
}
if strings.HasPrefix(w.opts.Package, localPackagePrefix) {
mainPath := filepath.Join(dir, filepath.FromSlash(w.opts.Package), mainFile)
if _, err := os.Stat(mainPath); err != nil {
return WasmOutput{}, fmt.Err("input file not found: ", filepath.Join(w.opts.Package, mainFile), " must exist")
}
}
wasmFilename := w.opts.OutputName + wasmExt
tmpOutDir, err := os.MkdirTemp("", "sitec_wasm_*")
if err != nil {
return WasmOutput{}, err
}
defer os.RemoveAll(tmpOutDir)
tmpOutPath := filepath.Join(tmpOutDir, wasmFilename)
var cmd *exec.Cmd
if w.opts.Runtime == js.RuntimeGo {
cmd = execCommand("go", "build", "-o", tmpOutPath, w.opts.Package)
cmd.Env = append(os.Environ(), "GOOS=js", "GOARCH=wasm")
} else {
if _, err := tinygo.EnsureInstalled(); err != nil {
return WasmOutput{}, fmt.Err("cannot install TinyGo: ", err)
}
args, err := w.tinyGoArgs(tmpOutDir, tmpOutPath)
if err != nil {
return WasmOutput{}, err
}
cmd = execCommand("tinygo", args...)
cmd.Env = append(tinygo.GetEnv(), "GOOS=js", "GOARCH=wasm")
}
// Run from the project root so the package resolves against the project's
// go.mod: a library's Web Worker is built with the versions the app uses.
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
return WasmOutput{}, fmt.Err("compilation failed: ", string(out), err)
}
binary, err := os.ReadFile(tmpOutPath)
if err != nil {
return WasmOutput{}, err
}
if w.opts.HashName {
wasmFilename = pwa.HashedName(wasmFilename, binary)
}
return WasmOutput{Binary: binary, Filename: wasmFilename}, nil
}
// tinyGoArgs are the TinyGo build arguments: the SIMD target or plain wasm, -opt=2 for speed.
func (w *defaultWasmBuilder) tinyGoArgs(tmpOutDir, tmpOutPath string) ([]string, error) {
args := []string{"build"}
if w.opts.SIMD {
targetPath := filepath.Join(tmpOutDir, "wasm-simd.json")
if err := os.WriteFile(targetPath, []byte(simdTargetJSON), 0644); err != nil {
return nil, err
}
args = append(args, "-target", targetPath, "-opt=2")
} else {
args = append(args, "-target", "wasm")
if w.opts.Speed {
args = append(args, "-opt=2")
}
}
// -no-debug: a shipped web binary is never a source-level debug target —
// DWARF info alone is the difference between ~99 KiB and ~456 KiB for a
// minimal binary.
return append(args, "-no-debug", "-o", tmpOutPath, w.opts.Package), nil
}
const (
mainFile = "main.go"
wasmExt = ".wasm"
msgWasmOptionsRequired = "sitec: WasmBuildOptions needs Package and OutputName"
msgWasmRuntimeRequired = "sitec: WasmBuildOptions needs Runtime: js.RuntimeTinyGo or js.RuntimeGo"
msgGoHasNoWasmSIMD = "sitec: SIMD needs TinyGo: Go has no WebAssembly SIMD"
msgBrowserEncodingJSON = "sitec: the browser code imports encoding/json (use webtyp.com/json); imported by:"
msgBrowserServerOnly = "sitec: the browser code imports a server-only package"
msgImportedBy = "imported by:"
msgBackendInBrowser = "sitec: backend code reached the browser:"
msgBuildAssetsShipped = "sitec: build-time code reached a shipped module:"
)
// The elements of an import path that mark a side (BUILD_DESTINATIONS D25, D34): a package under backend/ is server and
// edge code and never enters the page; a package under buildassets/ runs only while sitec builds (asset producers, the
// geometry of icons) and enters no shipped module. A whole build-time library (webtyp.com/css, webtyp.com/widgetstyle)
// imports the marker webtyp.com/buildassets, whose path carries the same element, so one check covers both.
const (
backendFolder = "backend"
buildAssetsFolder = "buildassets"
)
// serverOnly are the standard library packages every server library reaches
// (sockets, SQL drivers, processes) and no browser code needs: a browser
// graph that holds one of them is pulling a server library into the page.
var serverOnly = []string{"net", "net/http", "database/sql", "os/exec"}
// langPreload loads the webtyp-lang dictionary the page's meta names before
// the module runs.
const langPreload = "const __wtLangMeta=document.querySelector('meta[name=\"webtyp-lang\"]');if(__wtLangMeta&&__wtLangMeta.content){try{const __r=await fetch(__wtLangMeta.content);if(__r.ok)self.__webtypLang=await __r.json();}catch{}}\n"
// BrowserScript is the one <script type="module"> the page ships: the
// license notice the module opens with (/*! */, see BuildESModule), the
// webtyp-lang dictionary preload, then the rest of the module, so everything
// is one SRI-verified script under a strict CSP and the notice stays its
// first line.
func BrowserScript(module []byte) *js.Script {
code := string(module)
notice := ""
if strings.HasPrefix(code, "/*!") {
if end := strings.Index(code, "*/"); end >= 0 {
notice, code = code[:end+2]+"\n", strings.TrimPrefix(code[end+2:], "\n")
}
}
return &js.Script{Content: notice + langPreload + code, Module: true}
}
// BuildESModule compiles the Go main package in pkgDir into one minified ES
// Module with goesm. The edge (web/edge) ships it; the page uses
// BuildBrowserModule. The module starts with the license notice of goesm and
// Go (/*! */), which the minifier keeps.
func BuildESModule(pkgDir string) ([]byte, error) {
res, err := buildModule(pkgDir)
if err != nil {
return nil, err
}
return minifyModule(res.JS)
}
// BuildBrowserModule is BuildESModule for the page (web/browser): it also
// fails when the browser graph reaches a server-only package (net, net/http,
// database/sql, os/exec), naming the library that brings it, so no server
// library needs a build tag to stay out of the page.
func BuildBrowserModule(pkgDir string) ([]byte, error) {
res, err := buildModule(pkgDir)
if err != nil {
return nil, err
}
for _, pkg := range serverOnly {
if by := importers(res.ImportedBy, pkg); len(by) > 0 {
return nil, fmt.Err(msgBrowserServerOnly, pkg, msgImportedBy, strings.Join(by, ", "))
}
}
if chain := folderChain(res.ImportedBy, backendFolder); chain != "" {
return nil, fmt.Err(msgBackendInBrowser, chain)
}
return minifyModule(res.JS)
}
func buildModule(pkgDir string) (*goesm.Result, error) {
res, err := goesm.Build(goesm.Options{Dir: pkgDir, ShortNames: true})
if err != nil {
return nil, fmt.Err("goesm: ", err)
}
// The browser and the edge decode with webtyp.com/json: encoding/json
// brings reflect and the standard library's decoder into the module.
if by := importers(res.ImportedBy, "encoding/json"); len(by) > 0 {
return nil, fmt.Err(msgBrowserEncodingJSON, strings.Join(by, ", "))
}
if chain := folderChain(res.ImportedBy, buildAssetsFolder); chain != "" {
return nil, fmt.Err(msgBuildAssetsShipped, chain)
}
return res, nil
}
func minifyModule(code []byte) ([]byte, error) {
var b bytes.Buffer
if err := jsmin.Minify(minify.New(), &b, bytes.NewReader(code), nil); err != nil {
return nil, fmt.Err("minify goesm module: ", err)
}
return b.Bytes(), nil
}
// importers walks up from pkg through the standard library and returns the
// first packages outside it that import it (net is imported by net/http, the
// error names the library that imports net/http).
func importers(importedBy map[string][]string, pkg string) []string {
var out []string
seen := []string{pkg}
queue := []string{pkg}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
for _, by := range importedBy[cur] {
if slices.Contains(seen, by) {
continue
}
seen = append(seen, by)
if isStdlib(by) {
queue = append(queue, by)
continue
}
out = append(out, by)
}
}
sort.Strings(out)
return out
}
// isStdlib: standard library import paths have no dot in their first element.
func isStdlib(path string) bool {
first, _, _ := strings.Cut(path, "/")
return !strings.Contains(first, ".")
}
// folderChain returns "<package> ← <importer> ← … ← <main>" for the first package of the graph (sorted) with element
// in its path, or "" when the graph has none. It follows the first importer of each package, enough to show the
// developer where that code comes in.
func folderChain(importedBy map[string][]string, element string) string {
var pkgs []string
for pkg := range importedBy {
if hasElement(pkg, element) {
pkgs = append(pkgs, pkg)
}
}
if len(pkgs) == 0 {
return ""
}
sort.Strings(pkgs)
chain := []string{pkgs[0]}
cur := pkgs[0]
for {
by := importedBy[cur]
if len(by) == 0 || slices.Contains(chain, by[0]) {
break
}
cur = by[0]
chain = append(chain, cur)
}
return strings.Join(chain, " ← ")
}
func hasElement(path, element string) bool {
for _, el := range strings.Split(path, "/") {
if el == element {
return true
}
}
return false
}