kotlin.ts 7.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import path from 'path'
import fs from 'fs-extra'
import { relative } from '../utils'
import { originalPositionFor } from '../sourceMap'
fxy060608's avatar
fxy060608 已提交
5
import { generateCodeFrame, lineColumnToStartEnd, splitRE } from './utils'
fxy060608's avatar
fxy060608 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

export interface MessageSourceLocation {
  type: 'exception' | 'error' | 'warning' | 'info' | 'logging' | 'output'
  message: string
  file?: string
  line?: number
  column?: number
  code?: string
}

interface GenerateCodeFrameOptions {
  inputDir: string
  sourceMapDir: string
  replaceTabsWithSpace?: boolean
  format: (msg: MessageSourceLocation) => string
}

export function hbuilderFormatter(m: MessageSourceLocation) {
  const msgs: string[] = []
  let msg = m.type + ': ' + m.message
  if (m.type === 'warning') {
    // 忽略部分警告
    if (msg.includes(`Classpath entry points to a non-existent location:`)) {
      return ''
    }
    msg
      .replace(/\r\n/g, '\n')
      .split('\n')
      .forEach((m) => {
        msgs.push('\u200B' + m + '\u200B')
      })
  } else if (m.type === 'error' || m.type === 'exception') {
    msg
      .replace(/\r\n/g, '\n')
      .split('\n')
      .forEach((m) => {
        msgs.push('\u200C' + m + '\u200C')
      })
  } else {
    msgs.push(msg)
  }
fxy060608's avatar
fxy060608 已提交
47 48 49
  if (m.code) {
    msgs.push(m.code)
  }
fxy060608's avatar
fxy060608 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  if (m.file) {
    if (m.file.includes('?')) {
      ;[m.file] = m.file.split('?')
    }
    msgs.push(`at ${m.file}:${m.line}:${m.column}`)
  }
  return msgs.join('\n')
}

export async function parseUTSKotlinStacktrace(
  messages: MessageSourceLocation[],
  options: GenerateCodeFrameOptions
) {
  if (typeof messages === 'string') {
    try {
      messages = JSON.parse(messages)
    } catch (e) {}
  }
  const msgs: string[] = []
  if (Array.isArray(messages) && messages.length) {
    for (const m of messages) {
      if (m.file) {
fxy060608's avatar
fxy060608 已提交
72 73 74 75 76
        const sourceMapFile = resolveSourceMapFile(
          m.file,
          options.sourceMapDir,
          options.inputDir
        )
fxy060608's avatar
fxy060608 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        if (sourceMapFile) {
          const originalPosition = await originalPositionFor({
            sourceMapFile,
            line: m.line!,
            column: m.column!,
            withSourceContent: true,
          })

          if (originalPosition.source && originalPosition.sourceContent) {
            m.file = originalPosition.source.split('?')[0]
            if (originalPosition.line !== null) {
              m.line = originalPosition.line
            }
            if (originalPosition.column !== null) {
              m.column = originalPosition.column
            }
            if (
              originalPosition.line !== null &&
              originalPosition.column !== null
            ) {
              m.code = generateCodeFrame(originalPosition.sourceContent, {
                line: originalPosition.line,
                column: originalPosition.column,
              }).replace(/\t/g, ' ')
            }
          }
        }
      }
      const msg = options.format(m)
      if (msg) {
        msgs.push(msg)
      }
    }
  }
  return msgs.join('\n')
}
fxy060608's avatar
fxy060608 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

function resolveSourceMapFile(
  file: string,
  sourceMapDir: string,
  inputDir: string
) {
  const sourceMapFile = path.resolve(
    sourceMapDir,
    relative(file, inputDir) + '.map'
  )
  if (fs.existsSync(sourceMapFile)) {
    return sourceMapFile
  }
}

const DEFAULT_APPID = 'HBuilder'

function normalizeAppid(appid: string) {
  return appid.replace(/_/g, '')
}
function createRegExp(appid: string) {
  return new RegExp('uni\\.' + appid + '\\.(.*)\\..*\\(*\\.kt:([0-9]+)\\)')
}

let kotlinManifest = {
  mtimeMs: 0,
  manifest: {} as Record<string, string>,
}

function updateUTSKotlinSourceMapManifestCache(cacheDir: string) {
  const manifestFile = path.resolve(cacheDir, 'src/.manifest.json')
  const stats = fs.statSync(manifestFile)
  if (stats.isFile()) {
    if (kotlinManifest.mtimeMs !== stats.mtimeMs) {
      const manifest = fs.readJSONSync(manifestFile) as Record<
        string,
        Record<string, string>
      >
      const classManifest: Record<string, string> = {}
      Object.keys(manifest).forEach((name) => {
        const kotlinClass = manifest[name].class
        if (kotlinClass) {
          classManifest[kotlinClass] = name
        }
      })
      kotlinManifest.mtimeMs = stats.mtimeMs
      kotlinManifest.manifest = classManifest
    }
  }
}

function parseFilenameByClassName(className: string) {
  return kotlinManifest.manifest[className.split('$')[0]] || 'index.kt'
}

function resolveSourceMapFileByKtFile(file: string, sourceMapDir: string) {
  const sourceMapFile = path.resolve(sourceMapDir, file + '.map')
  if (fs.existsSync(sourceMapFile)) {
    return sourceMapFile
  }
}

fxy060608's avatar
fxy060608 已提交
175 176 177 178 179
const COLORS: Record<string, string> = {
  warn: '\u200B',
  error: '\u200C',
}

fxy060608's avatar
fxy060608 已提交
180 181 182
interface GenerateRuntimeCodeFrameOptions {
  appid: string
  cacheDir: string
fxy060608's avatar
fxy060608 已提交
183
  logType?: 'log' | 'info' | 'warn' | 'debug' | 'error'
fxy060608's avatar
fxy060608 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}

function resolveSourceMapDirByCacheDir(cacheDir: string) {
  return path.resolve(cacheDir, 'sourceMap')
}

export async function parseUTSKotlinRuntimeStacktrace(
  stacktrace: string,
  options: GenerateRuntimeCodeFrameOptions
) {
  const appid = normalizeAppid(options.appid || DEFAULT_APPID)
  if (!stacktrace.includes('uni.' + appid + '.')) {
    return stacktrace
  }
  updateUTSKotlinSourceMapManifestCache(options.cacheDir)
  const re = createRegExp(appid)
  const res: string[] = []
  const lines = stacktrace.split(splitRE)
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    const codes = await parseUTSKotlinRuntimeStacktraceLine(
      line,
      re,
      resolveSourceMapDirByCacheDir(options.cacheDir)
    )
fxy060608's avatar
fxy060608 已提交
209 210 211 212 213 214 215 216 217
    if (codes.length && res.length) {
      const color = options.logType
        ? COLORS[options.logType as string] || ''
        : ''
      let error = res[0]
      if (color) {
        error = color + error + color
      }
      return [error, ...codes].join('\n')
fxy060608's avatar
fxy060608 已提交
218 219 220 221 222 223 224 225 226 227 228 229
    } else {
      res.push(line)
    }
  }
  return res.join('\n')
}

async function parseUTSKotlinRuntimeStacktraceLine(
  lineStr: string,
  re: RegExp,
  sourceMapDir: string
) {
fxy060608's avatar
fxy060608 已提交
230
  const lines: string[] = []
fxy060608's avatar
fxy060608 已提交
231 232
  const matches = lineStr.match(re)
  if (!matches) {
fxy060608's avatar
fxy060608 已提交
233
    return lines
fxy060608's avatar
fxy060608 已提交
234
  }
fxy060608's avatar
fxy060608 已提交
235

fxy060608's avatar
fxy060608 已提交
236 237 238 239 240 241
  const [, className, line] = matches
  const sourceMapFile = resolveSourceMapFileByKtFile(
    parseFilenameByClassName(className),
    sourceMapDir
  )
  if (!sourceMapFile) {
fxy060608's avatar
fxy060608 已提交
242
    return lines
fxy060608's avatar
fxy060608 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  }
  const originalPosition = await originalPositionFor({
    sourceMapFile,
    line: parseInt(line),
    column: 0,
    withSourceContent: true,
  })
  if (originalPosition.source && originalPosition.sourceContent) {
    if (originalPosition.line !== null && originalPosition.column !== null) {
      const { start, end } = lineColumnToStartEnd(
        originalPosition.sourceContent,
        originalPosition.line,
        originalPosition.column
      )
      lines.push(
        generateCodeFrame(originalPosition.sourceContent, start, end).replace(
          /\t/g,
          ' '
        )
      )
    }
fxy060608's avatar
fxy060608 已提交
264 265 266 267 268
    lines.push(
      `at ${originalPosition.source.split('?')[0]}:${originalPosition.line}:${
        originalPosition.column
      }`
    )
fxy060608's avatar
fxy060608 已提交
269 270 271
  }
  return lines
}