compiler.ts 6.0 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
import AdmZip from 'adm-zip'
import { sync } from 'fast-glob'
fxy060608's avatar
fxy060608 已提交
6
import type { parse, bundle, UtsTarget } from '@dcloudio/uts'
fxy060608's avatar
fxy060608 已提交
7
import { installHBuilderXPlugin, normalizePath } from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
8
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 38 39 40 41 42 43
      imports: [
        'kotlinx.coroutines.async',
        'kotlinx.coroutines.CoroutineScope',
        'kotlinx.coroutines.Deferred',
        'kotlinx.coroutines.Dispatchers',
        'io.dcloud.uts.*',
      ],
fxy060608's avatar
fxy060608 已提交
44
      logFilename: true,
fxy060608's avatar
fxy060608 已提交
45 46
    },
  })
fxy060608's avatar
fxy060608 已提交
47 48
  console.log('uts compile time: ' + (Date.now() - time) + 'ms')
  const kotlinFile = resolveKotlinFile(filename, inputDir, outputDir)
fxy060608's avatar
fxy060608 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  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 已提交
77 78 79 80
      const compilerServer = getCompilerServer()
      if (!compilerServer) {
        return
      }
fxy060608's avatar
fxy060608 已提交
81
      const { getDefaultJar, getKotlincHome, compile } = compilerServer
fxy060608's avatar
fxy060608 已提交
82
      time = Date.now()
fxy060608's avatar
fxy060608 已提交
83
      const jarFile = resolveJarPath(kotlinFile)
fxy060608's avatar
fxy060608 已提交
84 85 86
      const options = {
        kotlinc: resolveKotlincArgs(
          kotlinFile,
fxy060608's avatar
fxy060608 已提交
87
          getKotlincHome(),
fxy060608's avatar
fxy060608 已提交
88 89 90 91 92 93 94 95
          getDefaultJar().concat(resolveLibs(filename))
        ),
        d8: resolveD8Args(jarFile),
      }
      const res = await compile(options, process.env.UNI_INPUT_DIR)
      console.log('dex compile time: ' + (Date.now() - time) + 'ms')
      time = Date.now()
      if (res) {
fxy060608's avatar
fxy060608 已提交
96 97 98 99 100
        try {
          fs.unlinkSync(jarFile)
          // 短期内先不删除,方便排查问题
          // fs.unlinkSync(kotlinFile)
        } catch (e) {}
fxy060608's avatar
fxy060608 已提交
101 102 103 104
        const dexFile = resolveDexFile(jarFile)
        if (fs.existsSync(dexFile)) {
          return normalizePath(path.relative(outputDir, dexFile))
        }
fxy060608's avatar
fxy060608 已提交
105
      }
fxy060608's avatar
fxy060608 已提交
106 107
    }
  }
fxy060608's avatar
fxy060608 已提交
108
}
fxy060608's avatar
fxy060608 已提交
109

fxy060608's avatar
fxy060608 已提交
110
function resolveKotlincArgs(filename: string, kotlinc: string, jars: string[]) {
fxy060608's avatar
fxy060608 已提交
111 112 113 114 115 116 117
  return [
    filename,
    '-cp',
    resolveClassPath(jars),
    '-d',
    resolveJarPath(filename),
    '-kotlin-home',
fxy060608's avatar
fxy060608 已提交
118
    kotlinc,
fxy060608's avatar
fxy060608 已提交
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
  ]
}

function resolveD8Args(filename: string) {
  return [
    filename,
    '--no-desugaring',
    '--min-api',
    '19',
    '--output',
    resolveDexPath(filename),
  ]
}

function resolveLibs(filename: string) {
  const libsPath = path.resolve(path.dirname(filename), 'libs')
  const libs: string[] = []
  if (fs.existsSync(libsPath)) {
    libs.push(...sync('*.jar', { cwd: libsPath, absolute: true }))
    const zips = sync('*.aar', { cwd: libsPath })
    zips.forEach((name) => {
      const outputPath = resolveAndroidArchiveOutputPath(name)
      if (!fs.existsSync(outputPath)) {
        // 解压
        const zip = new AdmZip(path.resolve(libsPath, name))
        zip.extractAllTo(outputPath, true)
      }
    })
    if (zips.length) {
      libs.push(
        ...sync('*/*.jar', {
          cwd: resolveAndroidArchiveOutputPath(),
          absolute: true,
        })
      )
    }
  }
  return libs
}

function resolveAndroidArchiveOutputPath(aar?: string) {
  return path.resolve(
    process.env.UNI_OUTPUT_DIR,
    '../.uts/aar',
    aar ? aar.replace('.aar', '') : ''
  )
}
fxy060608's avatar
fxy060608 已提交
166 167 168 169
function resolveDexFile(jarFile: string) {
  return normalizePath(path.resolve(path.dirname(jarFile), 'classes.dex'))
}

fxy060608's avatar
fxy060608 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
function resolveKotlinFile(
  filename: string,
  inputDir: string,
  outputDir: string
) {
  return path
    .resolve(outputDir, path.relative(inputDir, filename))
    .replace(path.extname(filename), '.kt')
}

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

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

fxy060608's avatar
fxy060608 已提交
188 189
function resolveClassPath(jars: string[]) {
  return jars.join(os.platform() === 'win32' ? ';' : ':')
fxy060608's avatar
fxy060608 已提交
190 191
}

fxy060608's avatar
fxy060608 已提交
192 193
const getCompilerServer = ():
  | {
fxy060608's avatar
fxy060608 已提交
194
      getKotlincHome(): string
fxy060608's avatar
fxy060608 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
      getDefaultJar(): string[]
      compile(
        options: { kotlinc: string[]; d8: string[] },
        projectPath: string
      ): Promise<boolean>
    }
  | false => {
  try {
    const compilerServerPath = path.resolve(
      process.env.UNI_HBUILDERX_PLUGINS,
      'uniapp-runextension/out/main.js'
    )
    // eslint-disable-next-line no-restricted-globals
    return require(compilerServerPath)
  } catch (e) {
    installHBuilderXPlugin('uniapp-runextension')
fxy060608's avatar
fxy060608 已提交
211
  }
fxy060608's avatar
fxy060608 已提交
212 213
  return false
}
fxy060608's avatar
fxy060608 已提交
214 215 216 217 218 219 220 221 222

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 ''
}