|
| 1 | +import http from 'http' |
| 2 | +import fs from 'fs' |
| 3 | +import path from 'path' |
| 4 | +import { URL } from 'url' |
| 5 | +import { colorconsole } from '@hap-toolkit/shared-utils' |
| 6 | + |
| 7 | +function SignOnlinePlugin(options) { |
| 8 | + this.options = options |
| 9 | +} |
| 10 | + |
| 11 | +SignOnlinePlugin.prototype.apply = function (compiler) { |
| 12 | + const options = this.options |
| 13 | + |
| 14 | + compiler.hooks.done.tapAsync('SignOnlinePlugin', function (stats, cb) { |
| 15 | + const requestPath = options.request |
| 16 | + if (!requestPath || typeof requestPath !== 'string') { |
| 17 | + colorconsole.error(`### App Server ### 请求线上接口无效,请检查`) |
| 18 | + cb() |
| 19 | + return |
| 20 | + } |
| 21 | + const ext = options.signOnlineRpks ? 'rpks' : 'rpk' |
| 22 | + const pkgName = options.name |
| 23 | + const versionName = options.versionName |
| 24 | + const noSignFile = `${pkgName}.nosign.${versionName}.${ext}` |
| 25 | + |
| 26 | + const noSignFilePath = path.join(options.output, noSignFile) |
| 27 | + |
| 28 | + const distFileName = `${pkgName}.${options.sign}.${versionName}.${ext}` |
| 29 | + const distFilePath = path.join(options.output, distFileName) |
| 30 | + const distFileStream = fs.createWriteStream(distFilePath) |
| 31 | + |
| 32 | + let form = null |
| 33 | + |
| 34 | + const file = fs.createReadStream(noSignFilePath) |
| 35 | + |
| 36 | + if (options.formData && options.formData(file)) { |
| 37 | + form = options.formData(file) |
| 38 | + } |
| 39 | + |
| 40 | + form && Object.assign(options.headers(), form.getHeaders()) |
| 41 | + |
| 42 | + const url = new URL(requestPath) |
| 43 | + const param = { |
| 44 | + host: url.hostname, |
| 45 | + port: url.port, |
| 46 | + path: url.pathname, |
| 47 | + method: 'POST', |
| 48 | + timeout: 10000, |
| 49 | + headers: options.headers |
| 50 | + } |
| 51 | + const req = http |
| 52 | + .request(param, (res) => { |
| 53 | + colorconsole.log(`### App Loader ### 请求接口的状态码:${res.statusCode}`) |
| 54 | + res.pipe(distFileStream, { end: false }) |
| 55 | + res.on('end', (data) => { |
| 56 | + if (res.statusCode === 200) { |
| 57 | + distFileStream.end() |
| 58 | + colorconsole.log( |
| 59 | + `### App Loader ### 请求线上签名成功,dist目录生成文件:${distFileName}` |
| 60 | + ) |
| 61 | + cb() |
| 62 | + } |
| 63 | + }) |
| 64 | + }) |
| 65 | + .on('error', (err) => { |
| 66 | + colorconsole.error(`### App Server ### 请求线上签名错误,错误信息: ${err.message} $`) |
| 67 | + cb(err) |
| 68 | + }) |
| 69 | + .on('timeout', function () { |
| 70 | + colorconsole.warn( |
| 71 | + `### App Server ### 请求线上签名网络超时,请检查网络与接口地址 ${ |
| 72 | + form |
| 73 | + ? '' |
| 74 | + : '缺少FormData对象,请在配置文件quickapp.config.js里面定义的params函数返回FormData对象' |
| 75 | + }` |
| 76 | + ) |
| 77 | + req.abort() |
| 78 | + }) |
| 79 | + form && form.pipe(req) |
| 80 | + }) |
| 81 | +} |
| 82 | + |
| 83 | +export default SignOnlinePlugin |
0 commit comments