// @flow

import invariant from 'assert'
import { SourceMapConsumer } from 'source-map'
import { NEWLINE_REGEXP, getFileKey, type Chunk, type Job, type ImportResolved, type ImportTransformed } from 'pundle-api'

export function getLinesCount(text: string): number {
  return text.split(NEWLINE_REGEXP).length
}

export function getContentForOutput(
  chunk: Chunk,
  job: Job,
): {
  files: Array<ImportTransformed>,
} {
  const relevantFiles = new Set()

  function iterateImports(fileImport: ImportResolved, topLevelOnly: boolean) {
    const file = job.files.get(getFileKey(fileImport))
    invariant(file, `File referenced in chunk ('${fileImport.filePath}') not found in local cache!?`)

    if (relevantFiles.has(file)) return
    relevantFiles.add(file)

    if (!topLevelOnly) {
      file.imports.forEach(item => iterateImports(item, false))
    }
  }

  if (chunk.entry) {
    iterateImports(
      {
        meta: chunk.meta,
        format: chunk.format,
        filePath: chunk.entry,
      },
      !!chunk.imports.length,
    )
  }
  chunk.imports.forEach(item => iterateImports(item, true))

  return {
    files: Array.from(relevantFiles),
  }
}

export function mergeSourceMap(sourceMap: Object, targetMap: Object, offset: number, filePath: string): Promise<void> {
  return SourceMapConsumer.with(sourceMap, null, function(entryMap) {
    entryMap.eachMapping(function(mapping) {
      targetMap.addMapping({
        source: filePath,
        original: { line: mapping.originalLine, column: mapping.originalColumn },
        generated: { line: offset + mapping.generatedLine, column: mapping.generatedColumn },
      })
    })

    const sources = (sourceMap.sources || []).filter(Boolean)
    const sourcesContent = (sourceMap.sourcesContent || []).filter(Boolean)
    if (sources.length === sourcesContent.length) {
      sources.forEach((item, index) => {
        targetMap.setSourceContent(item, sourcesContent[index])
      })
    }
  })
}

@@ -1277,16 +1277,65 @@
 void%3E %7B%0A
+  const parsedSourceMap = JSON.parse(sourceMap)%0A%0A
   return
@@ -1358,17 +1358,23 @@
 er.with(
-s
+parsedS
 ourceMap
@@ -1712,25 +1712,31 @@
  sources = (
-s
+parsedS
 ourceMap.sou
@@ -1791,17 +1791,23 @@
 tent = (
-s
+parsedS
 ourceMap

Fix sourceMap for JS