extractSourceMap finds and parses the source map referenced by a transformed source file. fileURL is the URL the text was fetched from (used to resolve a relative external map). fetch retrieves an external .map when needed.
(text, fileURL string, fetch sourceFetcher)
| 67 | // source file. fileURL is the URL the text was fetched from (used to resolve a |
| 68 | // relative external map). fetch retrieves an external .map when needed. |
| 69 | func extractSourceMap(text, fileURL string, fetch sourceFetcher) (*sourceMap, bool) { |
| 70 | marker := "sourceMappingURL=" |
| 71 | idx := strings.LastIndex(text, marker) |
| 72 | if idx < 0 { |
| 73 | return nil, false |
| 74 | } |
| 75 | ref := text[idx+len(marker):] |
| 76 | if nl := strings.IndexAny(ref, "\r\n"); nl >= 0 { |
| 77 | ref = ref[:nl] |
| 78 | } |
| 79 | ref = strings.TrimSpace(ref) |
| 80 | if ref == "" { |
| 81 | return nil, false |
| 82 | } |
| 83 | |
| 84 | var raw []byte |
| 85 | if strings.HasPrefix(ref, "data:") { |
| 86 | comma := strings.IndexByte(ref, ',') |
| 87 | if comma < 0 { |
| 88 | return nil, false |
| 89 | } |
| 90 | meta, payload := ref[len("data:"):comma], ref[comma+1:] |
| 91 | if strings.Contains(meta, "base64") { |
| 92 | dec, err := base64.StdEncoding.DecodeString(payload) |
| 93 | if err != nil { |
| 94 | return nil, false |
| 95 | } |
| 96 | raw = dec |
| 97 | } else { |
| 98 | dec, err := url.QueryUnescape(payload) |
| 99 | if err != nil { |
| 100 | return nil, false |
| 101 | } |
| 102 | raw = []byte(dec) |
| 103 | } |
| 104 | } else { |
| 105 | mapURL := resolveURL(fileURL, ref) |
| 106 | body, ok := fetch(mapURL) |
| 107 | if !ok { |
| 108 | return nil, false |
| 109 | } |
| 110 | raw = []byte(body) |
| 111 | } |
| 112 | |
| 113 | var sm sourceMap |
| 114 | if err := json.Unmarshal(raw, &sm); err != nil { |
| 115 | return nil, false |
| 116 | } |
| 117 | if sm.Mappings == "" || len(sm.SourcesContent) == 0 { |
| 118 | return nil, false |
| 119 | } |
| 120 | return &sm, true |
| 121 | } |
| 122 | |
| 123 | func resolveURL(base, ref string) string { |
| 124 | b, err := url.Parse(base) |
no test coverage detected