Debian Codegraph @

internal/js/esbuild/batch.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package esbuild provides functions for building JavaScript resources.
15 package esbuild
16
17 import (
18 "bytes"
19 "context"
20 _ "embed"
21 "encoding/json"
22 "fmt"
23 "io"
24 "path"
25 "path/filepath"
26 "reflect"
27 "sort"
28 "strings"
29 "sync"
30 "sync/atomic"
31
32 "github.com/evanw/esbuild/pkg/api"
33 "github.com/gohugoio/hugo/cache/dynacache"
34 "github.com/gohugoio/hugo/common/hmaps"
35 "github.com/gohugoio/hugo/common/hsync"
36 "github.com/gohugoio/hugo/common/hugio"
37 "github.com/gohugoio/hugo/common/paths"
38 "github.com/gohugoio/hugo/deps"
39 "github.com/gohugoio/hugo/helpers"
40 "github.com/gohugoio/hugo/identity"
41 "github.com/gohugoio/hugo/internal/js"
42 "github.com/gohugoio/hugo/media"
43 "github.com/gohugoio/hugo/resources"
44 "github.com/gohugoio/hugo/resources/resource"
45 "github.com/gohugoio/hugo/resources/resource_factories/create"
46 "github.com/gohugoio/hugo/tpl/tplimpl"
47 "github.com/mitchellh/mapstructure"
48 )
49
50 var _ js.Batcher = (*batcher)(nil)
51
52 const (
53 NsBatch = "_hugo-js-batch"
54
55 propsKeyImportContext = "importContext"
56 )
57
58 //go:embed batch-esm-runner.gotmpl
59 var runnerTemplateStr string
60
61 var _ js.BatchPackage = (*Package)(nil)
62
63 var _ buildToucher = (*optsHolder[scriptOptions])(nil)
64
65 var (
66 _ buildToucher = (*scriptGroup)(nil)
67 _ isBuiltOrTouchedProvider = (*scriptGroup)(nil)
68 )
69
70 func NewBatcherClient(deps *deps.Deps) (js.BatcherClient, error) {
71 c := &BatcherClient{
72 d: deps,
73 buildClient: NewBuildClient(deps.BaseFs.Assets, deps.ResourceSpec, false),
74 createClient: create.New(deps.ResourceSpec),
75 batcherStore: hmaps.NewCache[string, js.Batcher](),
76 bundlesStore: hmaps.NewCache[string, js.BatchPackage](),
77 }
78
79 deps.BuildEndListeners.Add(func(...any) bool {
80 c.bundlesStore.Reset()
81 return false
82 })
83
84 return c, nil
85 }
86
87 func (o optionsMap[K, C]) ByKey() optionsGetSetters[K, C] {
88 var values []optionsGetSetter[K, C]
89 for _, v := range o {
90 values = append(values, v)
91 }
92
93 sort.Slice(values, func(i, j int) bool {
94 return values[i].Key().String() < values[j].Key().String()
95 })
96
97 return values
98 }
99
100 func (o *opts[K, C]) Compiled() C {
101 o.h.checkCompileErr()
102 return o.h.compiled
103 }
104
105 func (os optionsGetSetters[K, C]) Filter(predicate func(K) bool) optionsGetSetters[K, C] {
106 var a optionsGetSetters[K, C]
107 for _, v := range os {
108 if predicate(v.Key()) {
109 a = append(a, v)
110 }
111 }
112 return a
113 }
114
115 func (o *optsHolder[C]) IdentifierBase() string {
116 return o.optionsID
117 }
118
119 func (o *opts[K, C]) Key() K {
120 return o.key
121 }
122
123 func (o *opts[K, C]) Reset() {
124 o.once.Reset()
125 o.h.resetCounter++
126 }
127
128 func (o *opts[K, C]) Get(id uint32) js.OptionsSetter {
129 var b *optsHolder[C]
130 o.once.Do(func() {
131 b = o.h
132 b.setBuilt(id)
133 })
134 return b
135 }
136
137 func (o *opts[K, C]) GetIdentity() identity.Identity {
138 return o.h
139 }
140
141 func (o *optsHolder[C]) SetOptions(m map[string]any) string {
142 o.optsSetCounter++
143 o.optsPrev = o.optsCurr
144 o.optsCurr = m
145 o.compiledPrev = o.compiled
146 o.compiled, o.compileErr = o.compiled.compileOptions(m, o.defaults)
147 o.checkCompileErr()
148 return ""
149 }
150
151 // ValidateBatchID validates the given ID according to some very
152 func ValidateBatchID(id string, isTopLevel bool) error {
153 if id == "" {
154 return fmt.Errorf("id must be set")
155 }
156 // No Windows slashes.
157 if strings.Contains(id, "\\") {
158 return fmt.Errorf("id must not contain backslashes")
159 }
160
161 // Allow forward slashes in top level IDs only.
162 if !isTopLevel && strings.Contains(id, "/") {
163 return fmt.Errorf("id must not contain forward slashes")
164 }
165
166 return nil
167 }
168
169 func newIsBuiltOrTouched() isBuiltOrTouched {
170 return isBuiltOrTouched{
171 built: make(buildIDs),
172 touched: make(buildIDs),
173 }
174 }
175
176 func newOpts[K any, C optionsCompiler[C]](key K, optionsID string, defaults defaultOptionValues) *opts[K, C] {
177 return &opts[K, C]{
178 key: key,
179 h: &optsHolder[C]{
180 optionsID: optionsID,
181 defaults: defaults,
182 isBuiltOrTouched: newIsBuiltOrTouched(),
183 },
184 }
185 }
186
187 // BatcherClient is a client for building JavaScript packages.
188 type BatcherClient struct {
189 d *deps.Deps
190
191 once sync.Once
192 runnerTemplate *tplimpl.TemplInfo
193
194 createClient *create.Client
195 buildClient *BuildClient
196
197 batcherStore *hmaps.Cache[string, js.Batcher]
198 bundlesStore *hmaps.Cache[string, js.BatchPackage]
199 }
200
201 // New creates a new Batcher with the given ID.
202 // This will be typically created once and reused across rebuilds.
203 func (c *BatcherClient) New(id string) (js.Batcher, error) {
204 var initErr error
205 c.once.Do(func() {
206 // We should fix the initialization order here (or use the Go template package directly), but we need to wait
207 // for the Hugo templates to be ready.
208 tmpl, err := c.d.TemplateStore.TextParse("batch-esm-runner", runnerTemplateStr)
209 if err != nil {
210 initErr = err
211 return
212 }
213 c.runnerTemplate = tmpl
214 })
215
216 if initErr != nil {
217 return nil, initErr
218 }
219
220 dependencyManager := c.d.Conf.NewIdentityManager()
221 configID := "config_" + id
222
223 b := &batcher{
224 id: id,
225 scriptGroups: make(map[string]*scriptGroup),
226 dependencyManager: dependencyManager,
227 client: c,
228 configOptions: newOpts[scriptID, configOptions](
229 scriptID(configID),
230 configID,
231 defaultOptionValues{},
232 ),
233 }
234
235 c.d.BuildEndListeners.Add(func(...any) bool {
236 b.reset()
237 return false
238 })
239
240 idFinder := identity.NewFinder(identity.FinderConfig{})
241
242 c.d.OnChangeListeners.Add(func(ids ...identity.Identity) bool {
243 for _, id := range ids {
244 if r := idFinder.Contains(id, b.dependencyManager, 50); r > 0 {
245 b.staleVersion.Add(1)
246 return false
247 }
248
249 sp, ok := id.(identity.DependencyManagerScopedProvider)
250 if !ok {
251 continue
252 }
253 idms := sp.GetDependencyManagerForScopesAll()
254
255 for _, g := range b.scriptGroups {
256 g.forEachIdentity(func(id2 identity.Identity) bool {
257 bt, ok := id2.(buildToucher)
258 if !ok {
259 return false
260 }
261 for _, id3 := range idms {
262 // This handles the removal of the only source for a script group (e.g. all shortcodes in a contnt page).
263 // Note the very shallow search.
264 if r := idFinder.Contains(id2, id3, 0); r > 0 {
265 bt.setTouched(b.buildCount)
266 return false
267 }
268 }
269 return false
270 })
271 }
272 }
273
274 return false
275 })
276
277 return b, nil
278 }
279
280 func (c *BatcherClient) Store() *hmaps.Cache[string, js.Batcher] {
281 return c.batcherStore
282 }
283
284 func (c *BatcherClient) buildBatchGroup(ctx context.Context, t *batchGroupTemplateContext) (resource.Resource, string, error) {
285 var buf bytes.Buffer
286
287 if err := c.d.GetTemplateStore().ExecuteWithContext(ctx, c.runnerTemplate, &buf, t); err != nil {
288 return nil, "", err
289 }
290
291 s := paths.AddLeadingSlash(t.keyPath + ".js")
292 r, err := c.createClient.FromString(s, buf.String())
293 if err != nil {
294 return nil, "", err
295 }
296
297 return r, s, nil
298 }
299
300 // Package holds a group of JavaScript resources.
301 type Package struct {
302 id string
303 b *batcher
304
305 groups map[string]resource.Resources
306 }
307
308 func (p *Package) Groups() map[string]resource.Resources {
309 return p.groups
310 }
311
312 type batchGroupTemplateContext struct {
313 keyPath string
314 ID string
315 Runners []scriptRunnerTemplateContext
316 Scripts []scriptBatchTemplateContext
317 }
318
319 type batcher struct {
320 mu sync.Mutex
321 id string
322 buildCount uint32
323 staleVersion atomic.Uint32
324 scriptGroups scriptGroups
325
326 client *BatcherClient
327 dependencyManager identity.Manager
328
329 configOptions optionsGetSetter[scriptID, configOptions]
330
331 // The last successfully built package.
332 // If this is non-nil and not stale, we can reuse it (e.g. on server rebuilds)
333 prevBuild *Package
334 }
335
336 // Build builds the batch if not already built or if it's stale.
337 func (b *batcher) Build(ctx context.Context) (js.BatchPackage, error) {
338 key := dynacache.CleanKey(b.id + ".js")
339 p, err := b.client.bundlesStore.GetOrCreate(key, func() (js.BatchPackage, error) {
340 return b.build(ctx)
341 })
342 if err != nil {
343 return nil, fmt.Errorf("failed to build JS batch %q: %w", b.id, err)
344 }
345 return p, nil
346 }
347
348 func (b *batcher) Config(ctx context.Context) js.OptionsSetter {
349 return b.configOptions.Get(b.buildCount)
350 }
351
352 func (b *batcher) Group(ctx context.Context, id string) js.BatcherGroup {
353 if err := ValidateBatchID(id, false); err != nil {
354 panic(err)
355 }
356
357 b.mu.Lock()
358 defer b.mu.Unlock()
359
360 group, found := b.scriptGroups[id]
361 if !found {
362 idm := b.client.d.Conf.NewIdentityManager()
363 b.dependencyManager.AddIdentity(idm)
364
365 group = &scriptGroup{
366 id: id, b: b,
367 isBuiltOrTouched: newIsBuiltOrTouched(),
368 dependencyManager: idm,
369 scriptsOptions: make(optionsMap[scriptID, scriptOptions]),
370 instancesOptions: make(optionsMap[instanceID, paramsOptions]),
371 runnersOptions: make(optionsMap[scriptID, scriptOptions]),
372 }
373 b.scriptGroups[id] = group
374 }
375
376 group.setBuilt(b.buildCount)
377
378 return group
379 }
380
381 func (b *batcher) isStale() bool {
382 if b.staleVersion.Load() > 0 {
383 return true
384 }
385
386 if b.removeNotSet() {
387 return true
388 }
389
390 if b.configOptions.isStale() {
391 return true
392 }
393
394 for _, v := range b.scriptGroups {
395 if v.isStale() {
396 return true
397 }
398 }
399
400 return false
401 }
402
403 func (b *batcher) build(ctx context.Context) (js.BatchPackage, error) {
404 b.mu.Lock()
405 defer b.mu.Unlock()
406 defer func() {
407 b.staleVersion.Store(0)
408 b.buildCount++
409 }()
410
411 if b.prevBuild != nil {
412 if !b.isStale() {
413 return b.prevBuild, nil
414 }
415 }
416
417 p, err := b.doBuild(ctx)
418 if err != nil {
419 return nil, err
420 }
421
422 b.prevBuild = p
423
424 return p, nil
425 }
426
427 func (b *batcher) doBuild(ctx context.Context) (*Package, error) {
428 type importContext struct {
429 name string
430 resourceGetter resource.ResourceGetter
431 scriptOptions scriptOptions
432 dm identity.Manager
433 }
434
435 state := struct {
436 importResource *hmaps.Cache[string, resource.Resource]
437 resultResource *hmaps.Cache[string, resource.Resource]
438 importerImportContext *hmaps.Cache[string, importContext]
439 pathGroup *hmaps.Cache[string, string]
440 }{
441 importResource: hmaps.NewCache[string, resource.Resource](),
442 resultResource: hmaps.NewCache[string, resource.Resource](),
443 importerImportContext: hmaps.NewCache[string, importContext](),
444 pathGroup: hmaps.NewCache[string, string](),
445 }
446
447 multihostBasePaths := b.client.d.ResourceSpec.MultihostTargetBasePaths
448
449 // Entry points passed to ESBuid.
450 var entryPoints []string
451 addResource := func(group, pth string, r resource.Resource, isResult bool) {
452 state.pathGroup.Set(paths.TrimExt(pth), group)
453 state.importResource.Set(pth, r)
454 if isResult {
455 state.resultResource.Set(pth, r)
456 }
457 entryPoints = append(entryPoints, pth)
458 }
459
460 for _, g := range b.scriptGroups.Sorted() {
461 keyPath := g.id
462
463 t := &batchGroupTemplateContext{
464 keyPath: keyPath,
465 ID: g.id,
466 }
467
468 instances := g.instancesOptions.ByKey()
469
470 for _, vv := range g.scriptsOptions.ByKey() {
471 keyPath := keyPath + "_" + vv.Key().String()
472 opts := vv.Compiled()
473 impPath := path.Join(PrefixHugoVirtual, opts.Dir(), keyPath+opts.Resource.MediaType().FirstSuffix.FullSuffix)
474 impCtx := opts.ImportContext
475
476 state.importerImportContext.Set(impPath, importContext{
477 name: keyPath,
478 resourceGetter: impCtx,
479 scriptOptions: opts,
480 dm: g.dependencyManager,
481 })
482
483 bt := scriptBatchTemplateContext{
484 opts: vv,
485 Import: impPath,
486 Instances: []scriptInstanceBatchTemplateContext{},
487 }
488 state.importResource.Set(bt.Import, vv.Compiled().Resource)
489 predicate := func(k instanceID) bool {
490 return k.scriptID == vv.Key()
491 }
492 for _, vvv := range instances.Filter(predicate) {
493 bt.Instances = append(bt.Instances, scriptInstanceBatchTemplateContext{opts: vvv})
494 }
495
496 t.Scripts = append(t.Scripts, bt)
497 }
498
499 for _, vv := range g.runnersOptions.ByKey() {
500 runnerKeyPath := keyPath + "_" + vv.Key().String()
501 runnerImpPath := paths.AddLeadingSlash(runnerKeyPath + "_runner" + vv.Compiled().Resource.MediaType().FirstSuffix.FullSuffix)
502 t.Runners = append(t.Runners, scriptRunnerTemplateContext{opts: vv, Import: runnerImpPath})
503 addResource(g.id, runnerImpPath, vv.Compiled().Resource, false)
504 }
505
506 r, s, err := b.client.buildBatchGroup(ctx, t)
507 if err != nil {
508 return nil, fmt.Errorf("failed to build JS batch: %w", err)
509 }
510
511 state.importerImportContext.Set(s, importContext{
512 name: s,
513 resourceGetter: nil,
514 dm: g.dependencyManager,
515 })
516
517 addResource(g.id, s, r, true)
518 }
519
520 mediaTypes := b.client.d.ResourceSpec.MediaTypes()
521
522 externalOptions := b.configOptions.Compiled().Options
523 if externalOptions.Format == "" {
524 externalOptions.Format = "esm"
525 }
526 if externalOptions.Format != "esm" {
527 return nil, fmt.Errorf("only esm format is currently supported")
528 }
529
530 jsOpts := Options{
531 ExternalOptions: externalOptions,
532 InternalOptions: InternalOptions{
533 DependencyManager: b.dependencyManager,
534 Splitting: true,
535 ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string {
536 var importContextPath string
537 if args.Kind == api.ResolveEntryPoint {
538 importContextPath = args.Path
539 } else {
540 importContextPath = args.Importer
541 }
542 importContext, importContextFound := state.importerImportContext.Get(importContextPath)
543
544 // We want to track the dependencies closest to where they're used.
545 dm := b.dependencyManager
546 if importContextFound {
547 dm = importContext.dm
548 }
549
550 if r, found := state.importResource.Get(imp); found {
551 dm.AddIdentity(identity.FirstIdentity(r))
552 return imp
553 }
554
555 if importContext.resourceGetter != nil {
556 resolved := ResolveResource(imp, importContext.resourceGetter)
557 if resolved != nil {
558 resolvePath := resources.InternalResourceTargetPath(resolved)
559 dm.AddIdentity(identity.FirstIdentity(resolved))
560 imp := PrefixHugoVirtual + resolvePath
561 state.importResource.Set(imp, resolved)
562 state.importerImportContext.Set(imp, importContext)
563 return imp
564
565 }
566 }
567 return ""
568 },
569 ImportOnLoadFunc: func(args api.OnLoadArgs) (string, error) {
570 imp := args.Path
571
572 if r, found := state.importResource.Get(imp); found {
573 content, err := resources.InternalResourceSourceContent(ctx, r)
574 if err != nil {
575 return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)
576 }
577 return content, nil
578 }
579 return "", nil
580 },
581 ImportParamsOnLoadFunc: func(args api.OnLoadArgs) json.RawMessage {
582 if importContext, found := state.importerImportContext.Get(args.Path); found {
583 if !importContext.scriptOptions.IsZero() {
584 return importContext.scriptOptions.Params
585 }
586 }
587 return nil
588 },
589 ErrorMessageResolveFunc: func(args api.Message) *ErrorMessageResolved {
590 if loc := args.Location; loc != nil {
591 path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":")
592 if r, found := state.importResource.Get(path); found {
593 sourcePath := resources.InternalResourceSourcePathBestEffort(r)
594
595 var contentr hugio.ReadSeekCloser
596 if cp, ok := r.(hugio.ReadSeekCloserProvider); ok {
597 contentr, _ = cp.ReadSeekCloser()
598 }
599 return &ErrorMessageResolved{
600 Content: contentr,
601 Path: sourcePath,
602 Message: args.Text,
603 }
604
605 }
606
607 }
608 return nil
609 },
610 ResolveSourceMapSource: func(s string) string {
611 if r, found := state.importResource.Get(s); found {
612 if ss := resources.InternalResourceSourcePath(r); ss != "" {
613 return ss
614 }
615 return PrefixHugoMemory + s
616 }
617 return ""
618 },
619 EntryPoints: entryPoints,
620 },
621 }
622
623 result, err := b.client.buildClient.Build(jsOpts)
624 if err != nil {
625 return nil, fmt.Errorf("failed to build JS bundle: %w", err)
626 }
627
628 groups := make(map[string]resource.Resources)
629
630 createAndAddResource := func(targetPath, group string, o api.OutputFile, mt media.Type) error {
631 var sourceFilename string
632 if r, found := state.importResource.Get(targetPath); found {
633 sourceFilename = resources.InternalResourceSourcePathBestEffort(r)
634 }
635 targetPath = path.Join(b.id, targetPath)
636
637 rd := resources.ResourceSourceDescriptor{
638 LazyPublish: true,
639 OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
640 return hugio.NewReadSeekerNoOpCloserFromBytes(o.Contents), nil
641 },
642 MediaType: mt,
643 TargetPath: targetPath,
644 SourceFilenameOrPath: sourceFilename,
645 }
646 r, err := b.client.d.ResourceSpec.NewResource(rd)
647 if err != nil {
648 return err
649 }
650
651 groups[group] = append(groups[group], r)
652
653 return nil
654 }
655
656 outDir := b.client.d.AbsPublishDir
657
658 createAndAddResources := func(o api.OutputFile) (bool, error) {
659 p := paths.ToSlashPreserveLeading(strings.TrimPrefix(o.Path, outDir))
660 ext := path.Ext(p)
661 mt, _, found := mediaTypes.GetBySuffix(ext)
662 if !found {
663 return false, nil
664 }
665
666 group, found := state.pathGroup.Get(paths.TrimExt(p))
667
668 if !found {
669 return false, nil
670 }
671
672 if err := createAndAddResource(p, group, o, mt); err != nil {
673 return false, err
674 }
675
676 return true, nil
677 }
678
679 for _, o := range result.OutputFiles {
680 handled, err := createAndAddResources(o)
681 if err != nil {
682 return nil, err
683 }
684
685 if !handled {
686 // Copy to destination.
687 // In a multihost setup, we will have multiple targets.
688 var targetFilenames []string
689 if len(multihostBasePaths) > 0 {
690 for _, base := range multihostBasePaths {
691 p := strings.TrimPrefix(o.Path, outDir)
692 targetFilename := filepath.Join(base, b.id, p)
693 targetFilenames = append(targetFilenames, targetFilename)
694 }
695 } else {
696 p := strings.TrimPrefix(o.Path, outDir)
697 targetFilename := filepath.Join(b.id, p)
698 targetFilenames = append(targetFilenames, targetFilename)
699 }
700
701 fs := b.client.d.BaseFs.PublishFs
702
703 if err := func() error {
704 fw, err := helpers.OpenFilesForWriting(fs, targetFilenames...)
705 if err != nil {
706 return err
707 }
708 defer fw.Close()
709
710 fr := bytes.NewReader(o.Contents)
711
712 _, err = io.Copy(fw, fr)
713
714 return err
715 }(); err != nil {
716 return nil, fmt.Errorf("failed to copy to %q: %w", targetFilenames, err)
717 }
718 }
719 }
720
721 p := &Package{
722 id: path.Join(NsBatch, b.id),
723 b: b,
724 groups: groups,
725 }
726
727 return p, nil
728 }
729
730 func (b *batcher) removeNotSet() bool {
731 // We already have the lock.
732 var removed bool
733 currentBuildID := b.buildCount
734 for k, v := range b.scriptGroups {
735 if !v.isBuilt(currentBuildID) && v.isTouched(currentBuildID) {
736 // Remove entire group.
737 removed = true
738 delete(b.scriptGroups, k)
739 continue
740 }
741 if v.removeTouchedButNotSet() {
742 removed = true
743 }
744 if v.removeNotSet() {
745 removed = true
746 }
747 }
748
749 return removed
750 }
751
752 func (b *batcher) reset() {
753 b.mu.Lock()
754 defer b.mu.Unlock()
755 b.configOptions.Reset()
756 for _, v := range b.scriptGroups {
757 v.Reset()
758 }
759 }
760
761 type buildIDs map[uint32]bool
762
763 func (b buildIDs) Has(buildID uint32) bool {
764 return b[buildID]
765 }
766
767 func (b buildIDs) Set(buildID uint32) {
768 b[buildID] = true
769 }
770
771 type buildToucher interface {
772 setTouched(buildID uint32)
773 }
774
775 type configOptions struct {
776 Options ExternalOptions
777 }
778
779 func (s configOptions) isStaleCompiled(prev configOptions) bool {
780 return false
781 }
782
783 func (s configOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (configOptions, error) {
784 config, err := DecodeExternalOptions(m)
785 if err != nil {
786 return configOptions{}, err
787 }
788
789 return configOptions{
790 Options: config,
791 }, nil
792 }
793
794 type defaultOptionValues struct {
795 defaultExport string
796 }
797
798 type instanceID struct {
799 scriptID scriptID
800 instanceID string
801 }
802
803 func (i instanceID) String() string {
804 return i.scriptID.String() + "_" + i.instanceID
805 }
806
807 type isBuiltOrTouched struct {
808 built buildIDs
809 touched buildIDs
810 }
811
812 func (i isBuiltOrTouched) setBuilt(id uint32) {
813 i.built.Set(id)
814 }
815
816 func (i isBuiltOrTouched) isBuilt(id uint32) bool {
817 return i.built.Has(id)
818 }
819
820 func (i isBuiltOrTouched) setTouched(id uint32) {
821 i.touched.Set(id)
822 }
823
824 func (i isBuiltOrTouched) isTouched(id uint32) bool {
825 return i.touched.Has(id)
826 }
827
828 type isBuiltOrTouchedProvider interface {
829 isBuilt(uint32) bool
830 isTouched(uint32) bool
831 }
832
833 type key interface {
834 comparable
835 fmt.Stringer
836 }
837
838 type optionsCompiler[C any] interface {
839 isStaleCompiled(C) bool
840 compileOptions(map[string]any, defaultOptionValues) (C, error)
841 }
842
843 type optionsGetSetter[K, C any] interface {
844 isBuiltOrTouchedProvider
845 identity.IdentityProvider
846 // resource.StaleInfo
847
848 Compiled() C
849 Key() K
850 Reset()
851
852 Get(uint32) js.OptionsSetter
853 isStale() bool
854 currPrev() (map[string]any, map[string]any)
855 }
856
857 type optionsGetSetters[K key, C any] []optionsGetSetter[K, C]
858
859 type optionsMap[K key, C any] map[K]optionsGetSetter[K, C]
860
861 type opts[K any, C optionsCompiler[C]] struct {
862 key K
863 h *optsHolder[C]
864 once hsync.OnceMore
865 }
866
867 type optsHolder[C optionsCompiler[C]] struct {
868 optionsID string
869
870 defaults defaultOptionValues
871
872 // Keep track of one generation so we can detect changes.
873 // Note that most of this tracking is performed on the options/map level.
874 compiled C
875 compiledPrev C
876 compileErr error
877
878 resetCounter uint32
879 optsSetCounter uint32
880 optsCurr map[string]any
881 optsPrev map[string]any
882
883 isBuiltOrTouched
884 }
885
886 type paramsOptions struct {
887 Params json.RawMessage
888 }
889
890 func (s paramsOptions) isStaleCompiled(prev paramsOptions) bool {
891 return false
892 }
893
894 func (s paramsOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (paramsOptions, error) {
895 v := struct {
896 Params map[string]any
897 }{}
898
899 if err := mapstructure.WeakDecode(m, &v); err != nil {
900 return paramsOptions{}, err
901 }
902
903 paramsJSON, err := json.Marshal(v.Params)
904 if err != nil {
905 return paramsOptions{}, err
906 }
907
908 return paramsOptions{
909 Params: paramsJSON,
910 }, nil
911 }
912
913 type scriptBatchTemplateContext struct {
914 opts optionsGetSetter[scriptID, scriptOptions]
915 Import string
916 Instances []scriptInstanceBatchTemplateContext
917 }
918
919 func (s *scriptBatchTemplateContext) Export() string {
920 return s.opts.Compiled().Export
921 }
922
923 func (c scriptBatchTemplateContext) MarshalJSON() (b []byte, err error) {
924 return json.Marshal(&struct {
925 ID string `json:"id"`
926 Instances []scriptInstanceBatchTemplateContext `json:"instances"`
927 }{
928 ID: c.opts.Key().String(),
929 Instances: c.Instances,
930 })
931 }
932
933 func (b scriptBatchTemplateContext) RunnerJSON(i int) string {
934 script := fmt.Sprintf("Script%d", i)
935
936 v := struct {
937 ID string `json:"id"`
938
939 // Read-only live JavaScript binding.
940 Binding string `json:"binding"`
941 Instances []scriptInstanceBatchTemplateContext `json:"instances"`
942 }{
943 b.opts.Key().String(),
944 script,
945 b.Instances,
946 }
947
948 bb, err := json.Marshal(v)
949 if err != nil {
950 panic(err)
951 }
952 s := string(bb)
953
954 // Remove the quotes to make it a valid JS object.
955 s = strings.ReplaceAll(s, fmt.Sprintf("%q", script), script)
956
957 return s
958 }
959
960 type scriptGroup struct {
961 mu sync.Mutex
962 id string
963 b *batcher
964 isBuiltOrTouched
965 dependencyManager identity.Manager
966
967 scriptsOptions optionsMap[scriptID, scriptOptions]
968 instancesOptions optionsMap[instanceID, paramsOptions]
969 runnersOptions optionsMap[scriptID, scriptOptions]
970 }
971
972 // For internal use only.
973 func (b *scriptGroup) GetDependencyManager() identity.Manager {
974 return b.dependencyManager
975 }
976
977 // For internal use only.
978 func (b *scriptGroup) IdentifierBase() string {
979 return b.id
980 }
981
982 func (s *scriptGroup) Instance(sid, id string) js.OptionsSetter {
983 if err := ValidateBatchID(sid, false); err != nil {
984 panic(err)
985 }
986 if err := ValidateBatchID(id, false); err != nil {
987 panic(err)
988 }
989
990 s.mu.Lock()
991 defer s.mu.Unlock()
992
993 iid := instanceID{scriptID: scriptID(sid), instanceID: id}
994 if v, found := s.instancesOptions[iid]; found {
995 return v.Get(s.b.buildCount)
996 }
997
998 fullID := "instance_" + s.key() + "_" + iid.String()
999
1000 s.instancesOptions[iid] = newOpts[instanceID, paramsOptions](
1001 iid,
1002 fullID,
1003 defaultOptionValues{},
1004 )
1005
1006 return s.instancesOptions[iid].Get(s.b.buildCount)
1007 }
1008
1009 func (g *scriptGroup) Reset() {
1010 for _, v := range g.scriptsOptions {
1011 v.Reset()
1012 }
1013 for _, v := range g.instancesOptions {
1014 v.Reset()
1015 }
1016 for _, v := range g.runnersOptions {
1017 v.Reset()
1018 }
1019 }
1020
1021 func (s *scriptGroup) Runner(id string) js.OptionsSetter {
1022 if err := ValidateBatchID(id, false); err != nil {
1023 panic(err)
1024 }
1025
1026 s.mu.Lock()
1027 defer s.mu.Unlock()
1028 sid := scriptID(id)
1029 if v, found := s.runnersOptions[sid]; found {
1030 return v.Get(s.b.buildCount)
1031 }
1032
1033 runnerIdentity := "runner_" + s.key() + "_" + id
1034
1035 // A typical signature for a runner would be:
1036 // export default function Run(scripts) {}
1037 // The user can override the default export in the templates.
1038
1039 s.runnersOptions[sid] = newOpts[scriptID, scriptOptions](
1040 sid,
1041 runnerIdentity,
1042 defaultOptionValues{
1043 defaultExport: "default",
1044 },
1045 )
1046
1047 return s.runnersOptions[sid].Get(s.b.buildCount)
1048 }
1049
1050 func (s *scriptGroup) Script(id string) js.OptionsSetter {
1051 if err := ValidateBatchID(id, false); err != nil {
1052 panic(err)
1053 }
1054
1055 s.mu.Lock()
1056 defer s.mu.Unlock()
1057 sid := scriptID(id)
1058 if v, found := s.scriptsOptions[sid]; found {
1059 return v.Get(s.b.buildCount)
1060 }
1061
1062 scriptIdentity := "script_" + s.key() + "_" + id
1063
1064 s.scriptsOptions[sid] = newOpts[scriptID, scriptOptions](
1065 sid,
1066 scriptIdentity,
1067 defaultOptionValues{
1068 defaultExport: "*",
1069 },
1070 )
1071
1072 return s.scriptsOptions[sid].Get(s.b.buildCount)
1073 }
1074
1075 func (s *scriptGroup) isStale() bool {
1076 for _, v := range s.scriptsOptions {
1077 if v.isStale() {
1078 return true
1079 }
1080 }
1081
1082 for _, v := range s.instancesOptions {
1083 if v.isStale() {
1084 return true
1085 }
1086 }
1087
1088 for _, v := range s.runnersOptions {
1089 if v.isStale() {
1090 return true
1091 }
1092 }
1093
1094 return false
1095 }
1096
1097 func (v *scriptGroup) forEachIdentity(
1098 f func(id identity.Identity) bool,
1099 ) bool {
1100 if f(v) {
1101 return true
1102 }
1103 for _, vv := range v.instancesOptions {
1104 if f(vv.GetIdentity()) {
1105 return true
1106 }
1107 }
1108
1109 for _, vv := range v.scriptsOptions {
1110 if f(vv.GetIdentity()) {
1111 return true
1112 }
1113 }
1114
1115 for _, vv := range v.runnersOptions {
1116 if f(vv.GetIdentity()) {
1117 return true
1118 }
1119 }
1120
1121 return false
1122 }
1123
1124 func (s *scriptGroup) key() string {
1125 return s.b.id + "_" + s.id
1126 }
1127
1128 func (g *scriptGroup) removeNotSet() bool {
1129 currentBuildID := g.b.buildCount
1130 if !g.isBuilt(currentBuildID) {
1131 // This group was never accessed in this build.
1132 return false
1133 }
1134 var removed bool
1135
1136 if g.instancesOptions.isBuilt(currentBuildID) {
1137 // A new instance has been set in this group for this build.
1138 // Remove any instance that has not been set in this build.
1139 for k, v := range g.instancesOptions {
1140 if v.isBuilt(currentBuildID) {
1141 continue
1142 }
1143 delete(g.instancesOptions, k)
1144 removed = true
1145 }
1146 }
1147
1148 if g.runnersOptions.isBuilt(currentBuildID) {
1149 // A new runner has been set in this group for this build.
1150 // Remove any runner that has not been set in this build.
1151 for k, v := range g.runnersOptions {
1152 if v.isBuilt(currentBuildID) {
1153 continue
1154 }
1155 delete(g.runnersOptions, k)
1156 removed = true
1157 }
1158 }
1159
1160 if g.scriptsOptions.isBuilt(currentBuildID) {
1161 // A new script has been set in this group for this build.
1162 // Remove any script that has not been set in this build.
1163 for k, v := range g.scriptsOptions {
1164 if v.isBuilt(currentBuildID) {
1165 continue
1166 }
1167 delete(g.scriptsOptions, k)
1168
1169 // Also remove any instance with this ID.
1170 for kk := range g.instancesOptions {
1171 if kk.scriptID == k {
1172 delete(g.instancesOptions, kk)
1173 }
1174 }
1175 removed = true
1176 }
1177 }
1178
1179 return removed
1180 }
1181
1182 func (g *scriptGroup) removeTouchedButNotSet() bool {
1183 currentBuildID := g.b.buildCount
1184 var removed bool
1185 for k, v := range g.instancesOptions {
1186 if v.isBuilt(currentBuildID) {
1187 continue
1188 }
1189 if v.isTouched(currentBuildID) {
1190 delete(g.instancesOptions, k)
1191 removed = true
1192 }
1193 }
1194 for k, v := range g.runnersOptions {
1195 if v.isBuilt(currentBuildID) {
1196 continue
1197 }
1198 if v.isTouched(currentBuildID) {
1199 delete(g.runnersOptions, k)
1200 removed = true
1201 }
1202 }
1203 for k, v := range g.scriptsOptions {
1204 if v.isBuilt(currentBuildID) {
1205 continue
1206 }
1207 if v.isTouched(currentBuildID) {
1208 delete(g.scriptsOptions, k)
1209 removed = true
1210
1211 // Also remove any instance with this ID.
1212 for kk := range g.instancesOptions {
1213 if kk.scriptID == k {
1214 delete(g.instancesOptions, kk)
1215 }
1216 }
1217 }
1218
1219 }
1220 return removed
1221 }
1222
1223 type scriptGroups map[string]*scriptGroup
1224
1225 func (s scriptGroups) Sorted() []*scriptGroup {
1226 var a []*scriptGroup
1227 for _, v := range s {
1228 a = append(a, v)
1229 }
1230 sort.Slice(a, func(i, j int) bool {
1231 return a[i].id < a[j].id
1232 })
1233 return a
1234 }
1235
1236 type scriptID string
1237
1238 func (s scriptID) String() string {
1239 return string(s)
1240 }
1241
1242 type scriptInstanceBatchTemplateContext struct {
1243 opts optionsGetSetter[instanceID, paramsOptions]
1244 }
1245
1246 func (c scriptInstanceBatchTemplateContext) ID() string {
1247 return c.opts.Key().instanceID
1248 }
1249
1250 func (c scriptInstanceBatchTemplateContext) MarshalJSON() (b []byte, err error) {
1251 return json.Marshal(&struct {
1252 ID string `json:"id"`
1253 Params json.RawMessage `json:"params"`
1254 }{
1255 ID: c.opts.Key().instanceID,
1256 Params: c.opts.Compiled().Params,
1257 })
1258 }
1259
1260 type scriptOptions struct {
1261 // The script to build.
1262 Resource resource.Resource
1263
1264 // The import context to use.
1265 // Note that we will always fall back to the resource's own import context.
1266 ImportContext resource.ResourceGetter
1267
1268 // The export name to use for this script's group's runners (if any).
1269 // If not set, the default export will be used.
1270 Export string
1271
1272 // Params marshaled to JSON.
1273 Params json.RawMessage
1274 }
1275
1276 func (o *scriptOptions) Dir() string {
1277 return path.Dir(resources.InternalResourceTargetPath(o.Resource))
1278 }
1279
1280 func (s scriptOptions) IsZero() bool {
1281 return s.Resource == nil
1282 }
1283
1284 func (s scriptOptions) isStaleCompiled(prev scriptOptions) bool {
1285 if prev.IsZero() {
1286 return false
1287 }
1288
1289 // All but the ImportContext are checked at the options/map level.
1290 i1nil, i2nil := prev.ImportContext == nil, s.ImportContext == nil
1291 if i1nil && i2nil {
1292 return false
1293 }
1294 if i1nil || i2nil {
1295 return true
1296 }
1297 // On its own this check would have too many false positives, but combined with the other checks it should be fine.
1298 // We cannot do equality checking here.
1299 if !prev.ImportContext.(resource.IsProbablySameResourceGetter).IsProbablySameResourceGetter(s.ImportContext) {
1300 return true
1301 }
1302
1303 return false
1304 }
1305
1306 func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (scriptOptions, error) {
1307 v := struct {
1308 Resource resource.Resource
1309 ImportContext any
1310 Export string
1311 Params map[string]any
1312 }{}
1313
1314 if err := mapstructure.WeakDecode(m, &v); err != nil {
1315 panic(err)
1316 }
1317
1318 var paramsJSON []byte
1319 if v.Params != nil {
1320 var err error
1321 paramsJSON, err = json.Marshal(v.Params)
1322 if err != nil {
1323 panic(err)
1324 }
1325 }
1326
1327 if v.Export == "" {
1328 v.Export = defaults.defaultExport
1329 }
1330
1331 compiled := scriptOptions{
1332 Resource: v.Resource,
1333 Export: v.Export,
1334 ImportContext: resource.NewCachedResourceGetter(v.ImportContext),
1335 Params: paramsJSON,
1336 }
1337
1338 if compiled.Resource == nil {
1339 return scriptOptions{}, fmt.Errorf("resource not set")
1340 }
1341
1342 return compiled, nil
1343 }
1344
1345 type scriptRunnerTemplateContext struct {
1346 opts optionsGetSetter[scriptID, scriptOptions]
1347 Import string
1348 }
1349
1350 func (s *scriptRunnerTemplateContext) Export() string {
1351 return s.opts.Compiled().Export
1352 }
1353
1354 func (c scriptRunnerTemplateContext) MarshalJSON() (b []byte, err error) {
1355 return json.Marshal(&struct {
1356 ID string `json:"id"`
1357 }{
1358 ID: c.opts.Key().String(),
1359 })
1360 }
1361
1362 func (o optionsMap[K, C]) isBuilt(id uint32) bool {
1363 for _, v := range o {
1364 if v.isBuilt(id) {
1365 return true
1366 }
1367 }
1368
1369 return false
1370 }
1371
1372 func (o *opts[K, C]) isBuilt(id uint32) bool {
1373 return o.h.isBuilt(id)
1374 }
1375
1376 func (o *opts[K, C]) isStale() bool {
1377 if o.h.isStaleOpts() {
1378 return true
1379 }
1380 if o.h.compiled.isStaleCompiled(o.h.compiledPrev) {
1381 return true
1382 }
1383 return false
1384 }
1385
1386 func (o *optsHolder[C]) isStaleOpts() bool {
1387 if o.optsSetCounter == 1 && o.resetCounter > 0 {
1388 return false
1389 }
1390 isStale := func() bool {
1391 if len(o.optsCurr) != len(o.optsPrev) {
1392 return true
1393 }
1394 for k, v := range o.optsPrev {
1395 vv, found := o.optsCurr[k]
1396 if !found {
1397 return true
1398 }
1399 if strings.EqualFold(k, propsKeyImportContext) {
1400 // This is checked later.
1401 } else if si, ok := vv.(resource.StaleInfo); ok {
1402 if si.StaleVersion() > 0 {
1403 return true
1404 }
1405 } else {
1406 if !reflect.DeepEqual(v, vv) {
1407 return true
1408 }
1409 }
1410 }
1411 return false
1412 }()
1413
1414 return isStale
1415 }
1416
1417 func (o *opts[K, C]) isTouched(id uint32) bool {
1418 return o.h.isTouched(id)
1419 }
1420
1421 func (o *optsHolder[C]) checkCompileErr() {
1422 if o.compileErr != nil {
1423 panic(o.compileErr)
1424 }
1425 }
1426
1427 func (o *opts[K, C]) currPrev() (map[string]any, map[string]any) {
1428 return o.h.optsCurr, o.h.optsPrev
1429 }
1430
1431 func init() {
1432 // We don't want any dependencies/change tracking on the top level Package,
1433 // we want finer grained control via Package.Group.
1434 var p any = &Package{}
1435 if _, ok := p.(identity.Identity); ok {
1436 panic("esbuid.Package should not implement identity.Identity")
1437 }
1438 if _, ok := p.(identity.DependencyManagerProvider); ok {
1439 panic("esbuid.Package should not implement identity.DependencyManagerProvider")
1440 }
1441 }