Browse Source

Detect source map URL when the source is wrapped in "(function() { ... })". See #235.

Dmitry Panov 4 năm trước cách đây
mục cha
commit
4ac8fd9669
2 tập tin đã thay đổi với 39 bổ sung4 xóa
  1. 17 0
      parser/parser_test.go
  2. 22 4
      parser/statement.go

+ 17 - 0
parser/parser_test.go

@@ -1014,3 +1014,20 @@ func TestPosition(t *testing.T) {
 		is(node.(*ast.FunctionLiteral).Source, "function(){ return abc; }")
 	})
 }
+
+func TestExtractSourceMapLine(t *testing.T) {
+	tt(t, func() {
+		is(extractSourceMapLine(""), "")
+		is(extractSourceMapLine("\n"), "")
+		is(extractSourceMapLine(" "), "")
+		is(extractSourceMapLine("1\n2\n3\n4\n"), "")
+
+		src := `"use strict";
+var x = {};
+//# sourceMappingURL=delme.js.map`
+		modSrc := `(function(exports, require, module) {` + src + `
+})`
+		is(extractSourceMapLine(modSrc), "//# sourceMappingURL=delme.js.map")
+		is(extractSourceMapLine(modSrc+"\n\n\n\n"), "//# sourceMappingURL=delme.js.map")
+	})
+}

+ 22 - 4
parser/statement.go

@@ -586,11 +586,29 @@ func (self *_parser) parseProgram() *ast.Program {
 	}
 }
 
+func extractSourceMapLine(str string) string {
+	for {
+		p := strings.LastIndexByte(str, '\n')
+		line := str[p+1:]
+		if line != "" && line != "})" {
+			if strings.HasPrefix(line, "//# sourceMappingURL=") {
+				return line
+			}
+			break
+		}
+		if p >= 0 {
+			str = str[:p]
+		} else {
+			break
+		}
+	}
+	return ""
+}
+
 func (self *_parser) parseSourceMap() *sourcemap.Consumer {
-	lastLine := self.str[strings.LastIndexByte(self.str, '\n')+1:]
-	if strings.HasPrefix(lastLine, "//# sourceMappingURL") {
-		urlIndex := strings.Index(lastLine, "=")
-		urlStr := lastLine[urlIndex+1:]
+	if smLine := extractSourceMapLine(self.str); smLine != "" {
+		urlIndex := strings.Index(smLine, "=")
+		urlStr := smLine[urlIndex+1:]
 
 		var data []byte
 		if strings.HasPrefix(urlStr, "data:application/json") {