Repository navigation
Expand file tree
/
Copy pathbuild.go
More file actions
641 lines (566 loc) · 16.1 KB
/
Copy pathbuild.go
File metadata and controls
641 lines (566 loc) · 16.1 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
package sitec
import (
"io"
"os"
"path/filepath"
"strings"
"webtyp.com/artifacts"
"webtyp.com/fmt"
"webtyp.com/image/min"
"webtyp.com/js"
"webtyp.com/router/routescan"
)
const (
DefaultOutputDir = "web/public"
DefaultImageQuality = 82
mediaTypeJSON = "application/json"
)
// Mode decides what artifact Build produces.
type Mode uint8
const (
// ModeRelease is the deliverable: WASM via TinyGo, minified.
ModeRelease Mode = iota
// ModeDev is the development cache: fast compilation, unminified.
ModeDev
)
// 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 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"`
}
// BuildConfig contains the site build settings.
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)
}
// 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 ErrRouteCollides = "route %s %s (%s:%d) collides with the static asset %s — the asset is served first and the route would never run"
const symbolParamStart = "{"
func normalizePath(p string) string {
if p == "" {
return "/"
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
if len(p) > 1 && strings.HasSuffix(p, "/") {
p = strings.TrimSuffix(p, "/")
}
return p
}
func splitPath(p string) []string {
norm := normalizePath(p)
if norm == "/" {
return []string{}
}
return strings.Split(norm[1:], "/")
}
func routeMatchesArtifact(routeSegs, artSegs []string) bool {
if len(routeSegs) != len(artSegs) {
return false
}
for i := 0; i < len(routeSegs); i++ {
r := routeSegs[i]
a := artSegs[i]
if strings.HasPrefix(r, symbolParamStart) {
continue
}
if r != a {
return false
}
}
return true
}
func checkRouteCollisions(routes []routescan.Decl, artifacts []Artifact) error {
if len(routes) == 0 || len(artifacts) == 0 {
return nil
}
type parsedArtifact struct {
origPath string
segments []string
}
parsedArts := make([]parsedArtifact, 0, len(artifacts))
for _, art := range artifacts {
parsedArts = append(parsedArts, parsedArtifact{
origPath: art.Path,
segments: splitPath(art.Path),
})
}
for _, decl := range routes {
routeSegs := splitPath(decl.Path)
for _, art := range parsedArts {
if routeMatchesArtifact(routeSegs, art.segments) {
return fmt.Err(fmt.Sprintf(ErrRouteCollides, decl.Method, decl.Path, routescan.DefaultFile, decl.Line, art.origPath))
}
}
}
return nil
}
// Output es el resultado de un Build COMPLETO: los artefactos producidos,
// listos para volcarse a un FS (WriteTo) o servirse desde Artifacts().
type Output struct {
c *Compiler
routes []routescan.Decl
arts []Artifact
large []artifacts.LocalFile
}
// Routes returns the routes the project declared in config/routes.go, in
// source order. Empty when the project declares none.
func (s *Output) Routes() []routescan.Decl {
if s == nil {
return nil
}
return s.routes
}
// Artifacts returns all produced artifacts.
func (s *Output) Artifacts() []Artifact {
if s == nil {
return nil
}
if s.arts != nil {
return s.arts
}
if s.c == nil {
return nil
}
return s.c.List()
}
// 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 (s *Output) LargeFiles() []artifacts.LocalFile {
if s == nil {
return nil
}
return s.large
}
// An artifact's Path is a URL ("/style.css", "/", "/acerca/") — the URL is
// the identity. diskPath resolves it to a real file under OutputDir
// ("web/public/especialidades/oftalmologia/index.html"). Formula shared with
// Compiler.artifactDiskPath (emit_flush.go).
func (s *Output) diskPath(art Artifact) string {
return s.c.artifactDiskPath(art.Path)
}
// WriteTo writes the built site artifacts to the given FS.
func (s *Output) WriteTo(fs FS) error {
if s == nil || s.c == nil {
return fmt.Err("sitec: WriteTo called on nil Output")
}
for _, art := range s.Artifacts() {
if err := fs.Write(s.diskPath(art), art.Content, art.Mediatype); err != nil {
return err
}
}
return nil
}
// Option configures the Build behavior.
type Option func(*buildOptions)
type buildOptions struct {
minify bool
log func(...any)
}
// WithoutMinify disables minification for the build output.
func WithoutMinify() Option {
return func(o *buildOptions) {
o.minify = false
}
}
// WithMinify explicitly sets whether minification is enabled.
func WithMinify(enabled bool) Option {
return func(o *buildOptions) {
o.minify = enabled
}
}
// WithLog sets a custom logger for the build process.
func WithLog(log func(...any)) Option {
return func(o *buildOptions) {
o.log = log
}
}
// 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 Build(rootDir, outDir string, opts ...Option) error {
if rootDir == "" {
return fmt.Err("sitec: RootDir is required")
}
if outDir == "" {
outDir = DefaultOutputDir
}
root, err := filepath.Abs(rootDir)
if err != nil {
return fmt.Err("sitec: error resolving RootDir:", err)
}
options := buildOptions{
minify: true,
}
for _, opt := range opts {
if opt != nil {
opt(&options)
}
}
outPath := outDir
if !filepath.IsAbs(outPath) {
outPath = filepath.Join(root, outDir)
}
if err := os.RemoveAll(outPath); err != nil {
return fmt.Err("sitec: error cleaning output directory:", err)
}
if err := os.MkdirAll(outPath, 0755); err != nil {
return fmt.Err("sitec: error creating output directory:", err)
}
// OutputDir carries outPath (already absolute), never the raw outDir:
// artifactDiskPath (emit_flush.go) resolves every artifact as
// filepath.Join(c.OutputDir, rel) — it never joins RootDir in. That is
// harmless for the daemon, which always runs with the CWD already at the
// project root, but Build is a one-shot entry point meant to be called
// from anywhere (a CI job, a release script) — a relative OutputDir here
// silently writes under the CALLER's CWD instead of under rootDir. Caught
// by TestOneShotBuild_ConsumerFixture asserting on the real path, not by
// inspecting Content in memory.
cfg := BuildConfig{
RootDir: root,
OutputDir: outPath,
Mode: ModeRelease,
Log: options.log,
}
out, err := buildPipeline(cfg, options.minify)
if err != nil {
return err
}
if err := out.WriteTo(NewOsFS()); err != nil {
return err
}
return placeLargeFiles(outPath, out.LargeFiles())
}
// linkFile is os.Link; a variable so a test can make linking fail.
var linkFile = os.Link
// placeLargeFiles puts each declared artifact at its URL under outPath: a hard link, or a streamed
// copy when linking fails (another filesystem, Windows without the permission). Never read whole.
func placeLargeFiles(outPath string, files []artifacts.LocalFile) error {
for _, f := range files {
dest := filepath.Join(outPath, filepath.FromSlash(strings.TrimPrefix(f.URL, "/")))
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return fmt.Errf("sitec: placing %s: %v", f.URL, err)
}
if linkFile(f.Path, dest) == nil {
continue
}
if err := copyFile(f.Path, dest); err != nil {
return fmt.Errf("sitec: placing %s: %v", f.URL, err)
}
}
return nil
}
func copyFile(src, dest string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dest)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}
// BuildWithConfig executes the build pipeline with a custom BuildConfig and returns the Output in memory.
func BuildWithConfig(cfg BuildConfig) (*Output, error) {
return buildPipeline(cfg, cfg.Mode != ModeDev)
}
func buildPipeline(cfg BuildConfig, minify bool) (*Output, error) {
if cfg.RootDir == "" {
return nil, fmt.Err("sitec: RootDir is required")
}
root, err := filepath.Abs(cfg.RootDir)
if err != nil {
return nil, fmt.Err("sitec: error resolving RootDir:", err)
}
if err := ValidateProject(root); err != nil {
return nil, err
}
e := New(root)
if cfg.Log != nil {
e.SetLog(cfg.Log)
}
// Solo se sobrescribe si el llamador declaró su propia lista: pasar nil no
// debe apagar la comprobación que New() deja encendida.
if len(cfg.AssetLibraries) > 0 {
e.SetAssetLibraries(cfg.AssetLibraries)
}
all, err := e.ExtractAll()
if err != nil {
return nil, err
}
if len(all) == 0 {
return nil, fmt.Err(msgEmptyExtraction())
}
outDir := cfg.OutputDir
if outDir == "" {
outDir = DefaultOutputDir
}
imgQuality := cfg.ImageQuality
if imgQuality == 0 {
imgQuality = DefaultImageQuality
}
c := NewCompiler(&Config{
OutputDir: outDir,
RootDir: root,
AppName: cfg.AppName,
SiteURL: cfg.SiteURL,
DevMode: cfg.Mode == ModeDev,
})
c.SetMinifyEnabled(minify)
if cfg.Log != nil {
c.SetLog(cfg.Log)
}
c.SetFS(NewMemFS())
imgHandler := min.New(&min.Config{
RootDir: root,
OutputDir: filepath.Join(outDir, "img"),
Quality: imgQuality,
})
if cfg.Log != nil {
imgHandler.SetLog(cfg.Log)
}
imgHandler.SetFinder(e.discoverer())
c.SetImageProcessor(imgHandler)
browserDir := filepath.Join(root, filepath.Dir(filepath.FromSlash(defaultBrowserEntry)))
if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(defaultBrowserEntry))); err == nil {
module, err := BuildBrowserModule(browserDir)
if err != nil {
return nil, err
}
if err := c.UpdateSSRModule("bootstrap", "", []*js.Script{BrowserScript(module)}, "", nil); err != nil {
return nil, err
}
}
if err := c.BuildWorkers(); err != nil {
return nil, err
}
if err := c.RouteExtractedAssets(all); err != nil {
return nil, err
}
if err := imgHandler.LoadImages(); err != nil {
return nil, err
}
if err := c.PublishImages(); err != nil {
return nil, err
}
// Activos estáticos: los de RenderSite() (el proyecto manda) más los de
// BuildConfig, unidos sin duplicados en un solo recorrido.
var staticAssets []string
if c.site != nil {
staticAssets = append(staticAssets, c.site.StaticAssets...)
}
staticAssets = append(staticAssets, cfg.StaticAssets...)
staticAssets = dedupeStrings(staticAssets)
if err := copyStaticAssets(c, root, staticAssets); err != nil {
return nil, err
}
// ArtifactSources(): RouteExtractedAssets already wrote /artifacts.json; the files are placed
// by Build, never held in memory (D-PWA-15).
large := c.LargeFiles()
routes, err := routescan.Scan(root)
if err != nil {
return nil, err
}
out := &Output{c: c, routes: routes, large: large}
if cfg.Mode == ModeRelease {
arts, err := finalizeRelease(c.List(), releaseInput{
CSSURL: c.mainStyleCssHandler.GetURLPath(),
JSURL: c.mainJsHandler.GetURLPath(),
PWA: c.pwa,
Favicons: c.getFaviconFiles(),
Log: c.log,
})
if err != nil {
return nil, err
}
if err := checkSecretsInScripts(root, arts, c.Logger); err != nil {
return nil, err
}
out.arts = arts
}
served := out.Artifacts()
for _, f := range large {
served = append(served, Artifact{Path: f.URL})
}
if err := checkRouteCollisions(routes, served); err != nil {
return nil, err
}
return out, nil
}
// 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 (c *Compiler) LoadStaticAssets() error {
c.mu.Lock()
site := c.site
rootDir := ""
if c.Config != nil {
rootDir = c.RootDir
}
c.mu.Unlock()
if site == nil {
return nil
}
return copyStaticAssets(c, rootDir, site.StaticAssets)
}
func dedupeStrings(in []string) []string {
seen := make(map[string]bool, len(in))
out := make([]string, 0, len(in))
for _, s := range in {
if s == "" || seen[s] {
continue
}
seen[s] = true
out = append(out, s)
}
return out
}
// Check validates the project extraction and returns the list of extracted module names.
func Check(rootDir string, log func(...any)) ([]string, error) {
root, err := filepath.Abs(rootDir)
if err != nil {
return nil, fmt.Err("sitec: error resolving RootDir:", err)
}
if err := ValidateProject(root); err != nil {
return nil, err
}
e := New(root)
if log != nil {
e.SetLog(log)
}
all, err := e.ExtractAll()
if err != nil {
return nil, err
}
var modules []string
for _, a := range all {
if a != nil {
modules = append(modules, a.ModuleName)
}
}
routes, err := routescan.Scan(root)
if err != nil {
return nil, err
}
if len(routes) > 0 {
// Build an ephemeral Compiler output to obtain produced static artifacts
outDir := DefaultOutputDir
c := NewCompiler(&Config{
OutputDir: outDir,
RootDir: root,
})
c.SetFS(NewMemFS())
if err := c.RouteExtractedAssets(all); err == nil {
if err := checkRouteCollisions(routes, c.List()); err != nil {
return nil, err
}
}
}
return modules, nil
}
func copyStaticAssets(c *Compiler, rootDir string, staticAssets []string) error {
for _, entry := range staticAssets {
srcPath := filepath.Join(rootDir, entry)
info, err := os.Stat(srcPath)
if err != nil {
return fmt.Err(msgStaticAbsent(entry))
}
if info.IsDir() {
err = filepath.Walk(srcPath, func(p string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if fi.IsDir() {
return nil
}
rel, err := filepath.Rel(rootDir, p)
if err != nil {
return err
}
content, err := os.ReadFile(p)
if err != nil {
return err
}
mt := detectMediaType(p)
return c.Write(rel, content, mt)
})
if err != nil {
return err
}
} else {
content, err := os.ReadFile(srcPath)
if err != nil {
return err
}
mt := detectMediaType(srcPath)
if err := c.Write(entry, content, mt); err != nil {
return err
}
}
}
return nil
}
func detectMediaType(p string) string {
switch filepath.Ext(p) {
case ".css":
return "text/css"
case ".js":
return "text/javascript"
case ".svg":
return "image/svg+xml"
case ".html":
return "text/html"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".webp":
return "image/webp"
case ".json":
return "application/json"
case ".wasm":
return "application/wasm"
default:
return "text/plain"
}
}