Debian Codegraph @

internal/js/esbuild/sourcemap.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
15
16 import (
17 "encoding/json"
18 "strings"
19
20 "github.com/evanw/esbuild/pkg/api"
21 "github.com/gohugoio/hugo/common/paths"
22 )
23
24 type sourceMap struct {
25 Version int `json:"version"`
26 Sources []string `json:"sources"`
27 SourcesContent []string `json:"sourcesContent"`
28 Mappings string `json:"mappings"`
29 Names []string `json:"names"`
30 }
31
32 func fixOutputFile(o *api.OutputFile, resolve func(string) string) error {
33 if strings.HasSuffix(o.Path, ".map") {
34 b, err := fixSourceMap(o.Contents, resolve)
35 if err != nil {
36 return err
37 }
38 o.Contents = b
39 }
40 return nil
41 }
42
43 func fixSourceMap(s []byte, resolve func(string) string) ([]byte, error) {
44 var sm sourceMap
45 if err := json.Unmarshal([]byte(s), &sm); err != nil {
46 return nil, err
47 }
48
49 hasSourcesContent := len(sm.SourcesContent) == len(sm.Sources)
50
51 var sources []string
52 var sourcesContent []string
53 for i, src := range sm.Sources {
54 if resolved := resolve(src); resolved != "" {
55 // Absolute filenames works fine on U*ix (tested in Chrome on MacOs), but works very poorly on Windows (again Chrome).
56 // So, convert it to a URL.
57 if u, err := paths.UrlFromFilename(resolved); err == nil {
58 sources = append(sources, u.String())
59 if hasSourcesContent {
60 sourcesContent = append(sourcesContent, sm.SourcesContent[i])
61 }
62 }
63 }
64 }
65
66 sm.Sources = sources
67 if hasSourcesContent {
68 sm.SourcesContent = sourcesContent
69 }
70
71 b, err := json.Marshal(sm)
72 if err != nil {
73 return nil, err
74 }
75
76 return b, nil
77 }
78
79 // Used in tests.
80 func SourcesFromSourceMap(s string) []string {
81 var sm sourceMap
82 if err := json.Unmarshal([]byte(s), &sm); err != nil {
83 return nil
84 }
85 return sm.Sources
86 }