compiler.ts 5.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import os from 'os'
fxy060608's avatar
fxy060608 已提交
2
import fs from 'fs-extra'
fxy060608's avatar
fxy060608 已提交
3
import path from 'path'
fxy060608's avatar
fxy060608 已提交
4 5 6
import execa from 'execa'
import { once } from '@dcloudio/uni-shared'
import type { parse, bundle, UtsTarget } from '@dcloudio/uts'
fxy060608's avatar
fxy060608 已提交
7 8
import { normalizePath } from '@dcloudio/uni-cli-shared'
import { camelize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
9

fxy060608's avatar
fxy060608 已提交
10 11
export function getUtsCompiler(): {
  parse: typeof parse
fxy060608's avatar
fxy060608 已提交
12
  bundle: typeof bundle
fxy060608's avatar
fxy060608 已提交
13 14 15 16 17
  UtsTarget: typeof UtsTarget
} {
  // eslint-disable-next-line no-restricted-globals
  return require('@dcloudio/uts')
}
fxy060608's avatar
fxy060608 已提交
18 19 20 21 22 23 24 25 26 27
export async function compile(filename: string) {
  if (!process.env.UNI_HBUILDERX_PLUGINS) {
    return
  }
  const { bundle, UtsTarget } = getUtsCompiler()
  const inputDir = process.env.UNI_INPUT_DIR
  const outputDir = process.env.UNI_OUTPUT_DIR
  let time = Date.now()
  await bundle({
    target: UtsTarget.KOTLIN,
fxy060608's avatar
fxy060608 已提交
28
    input: {
fxy060608's avatar
fxy060608 已提交
29 30
      root: inputDir,
      filename,
fxy060608's avatar
fxy060608 已提交
31 32
    },
    output: {
fxy060608's avatar
fxy060608 已提交
33
      outDir: outputDir,
fxy060608's avatar
fxy060608 已提交
34
      package: parsePackage(filename),
fxy060608's avatar
fxy060608 已提交
35
      sourceMap: true,
fxy060608's avatar
fxy060608 已提交
36
      extname: 'kt',
fxy060608's avatar
fxy060608 已提交
37
      imports: ['kotlinx.coroutines.*', 'io.dcloud.uts.runtime.*'],
fxy060608's avatar
fxy060608 已提交
38
      logFilename: true,
fxy060608's avatar
fxy060608 已提交
39 40
    },
  })
fxy060608's avatar
fxy060608 已提交
41 42
  console.log('uts compile time: ' + (Date.now() - time) + 'ms')
  const kotlinFile = resolveKotlinFile(filename, inputDir, outputDir)
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  if (process.env.NODE_ENV === 'production') {
    // 生产模式下,需要将 kt 文件转移到 src 下
    fs.mkdirSync(path.resolve(kotlinFile, '../src'))
    if (fs.existsSync(kotlinFile)) {
      fs.moveSync(kotlinFile, path.resolve(kotlinFile, '../src/index.kt'))
    }
    const kotlinMapFile = kotlinFile + '.map'
    if (fs.existsSync(kotlinMapFile)) {
      fs.moveSync(
        kotlinMapFile,
        path.resolve(kotlinFile, '../src/index.map.kt')
      )
    }

    const copies = ['assets', 'libs', 'res']
    const moduleDir = path.dirname(filename)
    const outputModuleDir = path.dirname(kotlinFile)
    fs.readdirSync(moduleDir).forEach((file) => {
      if (copies.includes(file)) {
        fs.copySync(
          path.join(moduleDir, file),
          path.join(outputModuleDir, file)
        )
      }
    })
  } else if (process.env.NODE_ENV === 'development') {
    // 开发模式下,需要生成 dex
    if (fs.existsSync(kotlinFile)) {
fxy060608's avatar
fxy060608 已提交
71
      time = Date.now()
fxy060608's avatar
fxy060608 已提交
72 73 74 75 76 77 78 79 80 81 82 83
      await compileKotlin(kotlinFile)
      console.log('kotlin compile time: ' + (Date.now() - time) + 'ms')
      const jarFile = resolveJarPath(kotlinFile)
      if (fs.existsSync(jarFile)) {
        time = Date.now()
        await d8(jarFile)
        console.log('d8 compile time: ' + (Date.now() - time) + 'ms')
        try {
          fs.unlinkSync(jarFile)
          // 短期内先不删除,方便排查问题
          // fs.unlinkSync(kotlinFile)
        } catch (e) {}
fxy060608's avatar
fxy060608 已提交
84 85 86 87
        const dexFile = resolveDexFile(jarFile)
        if (fs.existsSync(dexFile)) {
          return normalizePath(path.relative(outputDir, dexFile))
        }
fxy060608's avatar
fxy060608 已提交
88
      }
fxy060608's avatar
fxy060608 已提交
89 90
    }
  }
fxy060608's avatar
fxy060608 已提交
91
}
fxy060608's avatar
fxy060608 已提交
92

fxy060608's avatar
fxy060608 已提交
93 94 95 96
function resolveDexFile(jarFile: string) {
  return normalizePath(path.resolve(path.dirname(jarFile), 'classes.dex'))
}

fxy060608's avatar
fxy060608 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 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
function resolveKotlinFile(
  filename: string,
  inputDir: string,
  outputDir: string
) {
  return path
    .resolve(outputDir, path.relative(inputDir, filename))
    .replace(path.extname(filename), '.kt')
}

function resolveDirs(): { kotlinc: string; d8: string; lib: string } {
  // eslint-disable-next-line no-restricted-globals
  return require(path.resolve(
    process.env.UNI_HBUILDERX_PLUGINS,
    'uts-kotlin-compiler'
  ))
}

const resolveKotlinc = once(() => {
  const { kotlinc } = resolveDirs()
  return path.resolve(
    kotlinc,
    'bin',
    'kotlinc' + (os.platform() === 'win32' ? '.bat' : '')
  )
})

async function compileKotlin(filename: string) {
  const kotlinc = resolveKotlinc()
  await execa(
    kotlinc,
    [filename, '-cp', resolveClassPath(), '-d', resolveJarPath(filename)],
    {
      stdio: 'inherit',
    }
  )
}

async function d8(filename: string) {
  const java = resolveJavaPath()
  const d8 = resolveD8Path()
  await execa(
    java,
    [
      '-cp',
      d8,
      'com.android.tools.r8.D8',
      filename,
fxy060608's avatar
fxy060608 已提交
145
      '--no-desugaring',
fxy060608's avatar
fxy060608 已提交
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 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      '--min-api',
      '19',
      '--output',
      resolveDexPath(filename),
    ],
    {
      stdio: 'inherit',
    }
  )
}

function resolveDexPath(filename: string) {
  return path.dirname(filename)
}

function resolveJarPath(filename: string) {
  return filename.replace(path.extname(filename), '.jar')
}

const resolveBuiltInClassPath = once(() => {
  const libDir = resolveDirs().lib
  return fs
    .readdirSync(libDir)
    .filter((file) => file.endsWith('.jar'))
    .map((file) => path.resolve(libDir, file))
})

function resolveClassPath() {
  return resolveBuiltInClassPath().join(os.platform() === 'win32' ? ';' : ':')
}

const resolveJavaPath = once(() => {
  return path.resolve(
    process.env.UNI_HBUILDERX_PLUGINS,
    'amazon-corretto',
    'bin/java'
  )
})

const resolveD8Path = once(() => {
  const { d8 } = resolveDirs()
  return path.resolve(d8, 'd8.jar')
})
fxy060608's avatar
fxy060608 已提交
189 190 191 192 193 194 195 196 197

export function parsePackage(filepath: string) {
  const parts = normalizePath(filepath).split('/')
  const index = parts.findIndex((part) => part === 'uni_modules')
  if (index > -1) {
    return 'uts.modules.' + camelize(parts[index + 1])
  }
  return ''
}