[JS] Factor out source map path rewriting
This commit is contained in:
@@ -16,9 +16,7 @@
|
||||
|
||||
package org.jetbrains.kotlin.js.parser.sourcemaps
|
||||
|
||||
import java.io.File
|
||||
import java.io.PrintStream
|
||||
import java.io.Reader
|
||||
import java.io.*
|
||||
|
||||
class SourceMap(val sourceContentResolver: (String) -> Reader?) {
|
||||
val groups = mutableListOf<SourceMapGroup>()
|
||||
@@ -49,8 +47,48 @@ class SourceMap(val sourceContentResolver: (String) -> Reader?) {
|
||||
writer.println()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@Throws(IOException::class, SourceMapSourceReplacementException::class)
|
||||
fun replaceSources(sourceMapFile: File, mapping: (String) -> String): Boolean {
|
||||
val content = sourceMapFile.readText()
|
||||
return sourceMapFile.writer().buffered().use {
|
||||
mapSources(content, it, mapping)
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(IOException::class, SourceMapSourceReplacementException::class)
|
||||
fun mapSources(content: String, output: Writer, mapping: (String) -> String): Boolean {
|
||||
val json = try {
|
||||
parseJson(content)
|
||||
} catch (e: JsonSyntaxException) {
|
||||
throw SourceMapSourceReplacementException(cause = e)
|
||||
}
|
||||
val jsonObject = json as? JsonObject ?: throw SourceMapSourceReplacementException("Top-level object expected")
|
||||
val sources = jsonObject.properties["sources"]
|
||||
if (sources != null) {
|
||||
val sourcesArray =
|
||||
sources as? JsonArray ?: throw SourceMapSourceReplacementException("'sources' property is not of array type")
|
||||
var changed = false
|
||||
val fixedSources = sourcesArray.elements.mapTo(mutableListOf<JsonNode>()) {
|
||||
val sourcePath = it as? JsonString ?: throw SourceMapSourceReplacementException("'sources' array must contain strings")
|
||||
val replacedPath = mapping(sourcePath.value)
|
||||
if (!changed && replacedPath != sourcePath.value) {
|
||||
changed = true
|
||||
}
|
||||
JsonString(replacedPath)
|
||||
}
|
||||
if (!changed) return false
|
||||
jsonObject.properties["sources"] = JsonArray(fixedSources)
|
||||
}
|
||||
jsonObject.write(output)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SourceMapSourceReplacementException(message: String? = null, cause: Throwable? = null) : Exception(message, cause)
|
||||
|
||||
data class SourceMapSegment(
|
||||
val generatedColumnNumber: Int,
|
||||
val sourceFileName: String?,
|
||||
@@ -66,4 +104,4 @@ sealed class SourceMapParseResult
|
||||
|
||||
class SourceMapSuccess(val value: SourceMap) : SourceMapParseResult()
|
||||
|
||||
class SourceMapError(val message: String) : SourceMapParseResult()
|
||||
class SourceMapError(val message: String) : SourceMapParseResult()
|
||||
|
||||
Reference in New Issue
Block a user