@hyext/builder-revues 1.0.7 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
@@ -3,922 +3,19 @@
|
|
3
3
|
* (c) 2024-2024 Alex
|
4
4
|
* Released under the MIT License.
|
5
5
|
*/
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
var axios = require('axios');
|
22
|
-
var R = require('ramda');
|
23
|
-
|
24
|
-
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
25
|
-
|
26
|
-
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
27
|
-
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
28
|
-
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
|
29
|
-
var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
|
30
|
-
var handlebars__default = /*#__PURE__*/_interopDefaultLegacy(handlebars);
|
31
|
-
var liveServer__default = /*#__PURE__*/_interopDefaultLegacy(liveServer);
|
32
|
-
var archiver__default = /*#__PURE__*/_interopDefaultLegacy(archiver);
|
33
|
-
var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
34
|
-
var R__default = /*#__PURE__*/_interopDefaultLegacy(R);
|
35
|
-
|
36
|
-
/*! *****************************************************************************
|
37
|
-
Copyright (c) Microsoft Corporation.
|
38
|
-
|
39
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
40
|
-
purpose with or without fee is hereby granted.
|
41
|
-
|
42
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
43
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
44
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
45
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
46
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
47
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
48
|
-
PERFORMANCE OF THIS SOFTWARE.
|
49
|
-
***************************************************************************** */
|
50
|
-
|
51
|
-
function __awaiter(thisArg, _arguments, P, generator) {
|
52
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
53
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
54
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
55
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
56
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
57
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
58
|
-
});
|
59
|
-
}
|
60
|
-
|
61
|
-
var EDeployMode;
|
62
|
-
(function (EDeployMode) {
|
63
|
-
EDeployMode[EDeployMode["Integration"] = 0] = "Integration";
|
64
|
-
EDeployMode[EDeployMode["Separate"] = 1] = "Separate";
|
65
|
-
})(EDeployMode || (EDeployMode = {}));
|
66
|
-
|
67
|
-
const tempDir = os__default["default"].tmpdir();
|
68
|
-
const cacheDir = path__default["default"].join(tempDir, '.revue_cache');
|
69
|
-
// 根据环境变量判断 要不要把运行框架代码留在项目内 还是 CDN
|
70
|
-
const deployMode = EDeployMode.Integration;
|
71
|
-
const buildEnv = process.env.HYEXT_BUILD_ENV || 'dev'; // 'production' | 'test' | 'dev'
|
72
|
-
const staticPath = path__default["default"].resolve(__dirname, '../static' );
|
73
|
-
const templatePath = path__default["default"].join(staticPath, 'template');
|
74
|
-
var COMPILE_TYPE;
|
75
|
-
(function (COMPILE_TYPE) {
|
76
|
-
COMPILE_TYPE["miniProgram"] = "miniProgram";
|
77
|
-
COMPILE_TYPE["miniProgramPlugin"] = "miniProgramPlugin";
|
78
|
-
COMPILE_TYPE["miniGame"] = "miniGame";
|
79
|
-
COMPILE_TYPE["miniGamePlugin"] = "miniGamePlugin";
|
80
|
-
})(COMPILE_TYPE || (COMPILE_TYPE = {}));
|
81
|
-
|
82
|
-
const sep = chalk__default["default"].gray('·');
|
83
|
-
const createLogger = (prefix) => {
|
84
|
-
prefix = ` ${prefix}`;
|
85
|
-
const logger = {
|
86
|
-
log(...args) {
|
87
|
-
const msg = util.format.apply(util.format, args);
|
88
|
-
console.log(chalk__default["default"].white(prefix), sep, msg);
|
89
|
-
},
|
90
|
-
fatal(...args) {
|
91
|
-
if (args[0] instanceof Error)
|
92
|
-
args[0] = args[0].message.trim();
|
93
|
-
const msg = util.format.apply(util.format, args);
|
94
|
-
console.error(chalk__default["default"].red(prefix), sep, msg);
|
95
|
-
process.exit(1);
|
96
|
-
},
|
97
|
-
success(...args) {
|
98
|
-
const msg = util.format.apply(util.format, args);
|
99
|
-
console.log(chalk__default["default"].green(prefix), sep, msg);
|
100
|
-
}
|
101
|
-
};
|
102
|
-
return logger;
|
103
|
-
};
|
104
|
-
var logger = createLogger('REVUE');
|
105
|
-
|
106
|
-
const filename = 'project.config.json';
|
107
|
-
function copyProjectConfigJSON(srcDir, destDir) {
|
108
|
-
fs__default["default"].copyFileSync(path__default["default"].join(srcDir, filename), path__default["default"].join(destDir, filename));
|
109
|
-
}
|
110
|
-
|
111
|
-
function initCacheDir() {
|
112
|
-
if (fs__default["default"].existsSync(cacheDir))
|
113
|
-
return;
|
114
|
-
fs__default["default"].mkdirSync(cacheDir);
|
115
|
-
}
|
116
|
-
|
117
|
-
function compile(mode, projectPath, outputPath) {
|
118
|
-
return __awaiter(this, void 0, void 0, function* () {
|
119
|
-
const isProd = mode === 'prod';
|
120
|
-
const compileSettings = isProd ? {
|
121
|
-
minify: true,
|
122
|
-
autoPrefixWXSS: true,
|
123
|
-
minifyWXSS: true,
|
124
|
-
} : {};
|
125
|
-
initCacheDir();
|
126
|
-
yield codeCompiler.compilerManager.init({
|
127
|
-
projectPath,
|
128
|
-
outputPath,
|
129
|
-
cachePath: cacheDir,
|
130
|
-
compileSettings
|
131
|
-
});
|
132
|
-
const action = isProd ? 'compile' : 'compileDev';
|
133
|
-
yield codeCompiler.compilerManager[action]();
|
134
|
-
copyProjectConfigJSON(projectPath, outputPath);
|
135
|
-
});
|
136
|
-
}
|
137
|
-
function compileGame(mode, projectPath, outputPath) {
|
138
|
-
return __awaiter(this, void 0, void 0, function* () {
|
139
|
-
initCacheDir();
|
140
|
-
yield codeCompiler.compilerManager.init({
|
141
|
-
projectPath,
|
142
|
-
outputPath,
|
143
|
-
cachePath: cacheDir,
|
144
|
-
compileSettings: {
|
145
|
-
cocos: true,
|
146
|
-
minify: mode === 'prod'
|
147
|
-
}
|
148
|
-
});
|
149
|
-
const action = mode === 'dev' ? 'compileDev' : 'compile';
|
150
|
-
yield codeCompiler.compilerManager[action]();
|
151
|
-
copyProjectConfigJSON(projectPath, outputPath);
|
152
|
-
});
|
153
|
-
}
|
154
|
-
function watchGame(projectPath, outputPath, cb) {
|
155
|
-
return __awaiter(this, void 0, void 0, function* () {
|
156
|
-
yield compileGame('dev', projectPath, outputPath);
|
157
|
-
codeCompiler.compilerManager.watch({ graphId: 'game', }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
158
|
-
// await compilerManager.compileSingleCode({
|
159
|
-
// type,
|
160
|
-
// filePath,
|
161
|
-
// graphId: 'game'
|
162
|
-
// })
|
163
|
-
logger.log('detected change:', filePath);
|
164
|
-
logger.log('recompile...');
|
165
|
-
codeCompiler.compilerManager.destroy();
|
166
|
-
yield codeCompiler.compilerManager.init({
|
167
|
-
projectPath,
|
168
|
-
outputPath,
|
169
|
-
cachePath: cacheDir,
|
170
|
-
compileSettings: {
|
171
|
-
cocos: true,
|
172
|
-
}
|
173
|
-
});
|
174
|
-
yield codeCompiler.compilerManager.compileDev(true);
|
175
|
-
cb && cb();
|
176
|
-
}));
|
177
|
-
});
|
178
|
-
}
|
179
|
-
function watch(projectPath, outputPath, cb) {
|
180
|
-
return __awaiter(this, void 0, void 0, function* () {
|
181
|
-
yield compile('dev', projectPath, outputPath);
|
182
|
-
codeCompiler.compilerManager.watch({ graphId: 'miniprogram' }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
183
|
-
yield codeCompiler.compilerManager.compileSingleCode({
|
184
|
-
type,
|
185
|
-
filePath,
|
186
|
-
graphId: 'miniprogram'
|
187
|
-
});
|
188
|
-
cb && cb();
|
189
|
-
}));
|
190
|
-
});
|
191
|
-
}
|
192
|
-
|
193
|
-
const hash = Date.now();
|
194
|
-
const sentryScriptUrlOnProd = '//a.msstatic.com/huya/hd/h5/hyext-sentry-setup-script/sentry-setup.js';
|
195
|
-
const sentryScriptUrlOnTest = '//test-hd.huya.com/h5/hyext-sentry-setup-script/test/sentry-setup.js';
|
196
|
-
const sentryScriptUrl = process.env.HYEXT_BUILD_ENV !== 'production'
|
197
|
-
? sentryScriptUrlOnTest
|
198
|
-
: sentryScriptUrlOnProd + `?hash=${hash}`;
|
199
|
-
|
200
|
-
handlebars__default["default"].registerHelper('toJSON', function (object) {
|
201
|
-
return new handlebars__default["default"].SafeString(JSON.stringify(object));
|
202
|
-
});
|
203
|
-
function render(content, data, opts) {
|
204
|
-
const temp = handlebars__default["default"].compile(content, {
|
205
|
-
noEscape: true
|
206
|
-
});
|
207
|
-
return temp(data, opts);
|
208
|
-
}
|
209
|
-
function renderTemplate(input, output, data) {
|
210
|
-
const content = fs__default["default"]
|
211
|
-
.readFileSync(input)
|
212
|
-
.toString();
|
213
|
-
fs__default["default"].outputFileSync(output, render(content, data));
|
214
|
-
}
|
215
|
-
|
216
|
-
function objectToParamsStr(obj) {
|
217
|
-
return Object.keys(obj).reduce((str, key) => {
|
218
|
-
// @ts-ignore
|
219
|
-
str += `&${key}=${encodeURIComponent(obj[key])}`;
|
220
|
-
return str;
|
221
|
-
}, '');
|
222
|
-
}
|
223
|
-
|
224
|
-
const PluginDriver = {
|
225
|
-
context: { deviceOrientation: 'portrait', },
|
226
|
-
hooks: {
|
227
|
-
onMergedMainPackge: new tapable.SyncHook(['IOnMergedMainPackge']),
|
228
|
-
onSrartBefore: new tapable.SyncHook(['IOnSrartBefore']),
|
229
|
-
}
|
230
|
-
};
|
231
|
-
|
232
|
-
class InjectWebviewUrlParamsPlugin {
|
233
|
-
apply(pluginDriver) {
|
234
|
-
pluginDriver.hooks.onMergedMainPackge.tap('InjectWebviewUrlParamsPlugin', opts => {
|
235
|
-
const { compileType, mainPath } = opts;
|
236
|
-
const isGame = compileType === COMPILE_TYPE.miniGame;
|
237
|
-
if (isGame) {
|
238
|
-
const gameJson = fs__default["default"].readJsonSync(path__default["default"].join(mainPath, 'game.json'));
|
239
|
-
if (typeof gameJson.deviceOrientation === 'string' &&
|
240
|
-
gameJson.deviceOrientation.includes('landscape')) {
|
241
|
-
pluginDriver.context.deviceOrientation = 'landscape';
|
242
|
-
}
|
243
|
-
}
|
244
|
-
pluginDriver.context.webviewUrlParams = {
|
245
|
-
isLandscape: 0,
|
246
|
-
disablePopGesture: 1,
|
247
|
-
hideStatusBar: isGame ? 1 : 0,
|
248
|
-
hideBar: 1,
|
249
|
-
bounces: 0,
|
250
|
-
hideloading: 1
|
251
|
-
};
|
252
|
-
});
|
253
|
-
}
|
254
|
-
}
|
255
|
-
function makeWebviewUrlParamsStr() {
|
256
|
-
const params = PluginDriver.context.webviewUrlParams;
|
257
|
-
return params ? objectToParamsStr(params) : '';
|
258
|
-
}
|
259
|
-
|
260
|
-
const HOST = {
|
261
|
-
test: '//test-extsdk.msstatic.com',
|
262
|
-
prod: '//extsdk-msstatic.cdn.huya.com'
|
263
|
-
};
|
264
|
-
// $1是动态的extType
|
265
|
-
function getSDKUrlTemplate(opts) {
|
266
|
-
return `${opts.isTestEnv ? HOST.test : HOST.prod}/sdk/${opts.extType}/${opts.hostId}/${opts.extUuid || 0}/sdk.js`;
|
267
|
-
}
|
268
|
-
|
269
|
-
function isMainPackage(config) {
|
270
|
-
return config.name === codeCompiler.pkgFileType.MainPkg && config.root === '.';
|
271
|
-
}
|
272
|
-
function getPackageConfig(basePath) {
|
273
|
-
const filePath = path__default["default"].join(basePath, 'packageConfig.json');
|
274
|
-
return fs__default["default"].readJSONSync(filePath);
|
275
|
-
}
|
276
|
-
function getPackageExtConfig(basePath) {
|
277
|
-
const filePath = path__default["default"].join(basePath, 'packageExtConfig.json');
|
278
|
-
return fs__default["default"].readJSONSync(filePath);
|
279
|
-
}
|
280
|
-
function mergeSubPackagesToMainPackage(packagePath, main, subList, onMoveBefore) {
|
281
|
-
const mainPath = path__default["default"].join(packagePath, main.name);
|
282
|
-
subList.forEach(conf => {
|
283
|
-
const subRoot = path__default["default"].join(packagePath, conf.name);
|
284
|
-
const subPath = path__default["default"].join(subRoot, conf.root);
|
285
|
-
const dest = path__default["default"].join(mainPath, conf.root);
|
286
|
-
onMoveBefore && onMoveBefore(subRoot, mainPath, conf);
|
287
|
-
fs__default["default"].moveSync(subPath, dest, { overwrite: true });
|
288
|
-
fs__default["default"].removeSync(path__default["default"].join(packagePath, conf.name));
|
289
|
-
});
|
290
|
-
}
|
291
|
-
|
292
|
-
function mergeMainPackage(releasePath, onMoveBefore) {
|
293
|
-
const packagePath = path__default["default"].join(releasePath, 'package');
|
294
|
-
const packageConfig = getPackageConfig(packagePath);
|
295
|
-
const targetIndex = packageConfig.findIndex(item => {
|
296
|
-
return isMainPackage(item);
|
297
|
-
});
|
298
|
-
if (targetIndex === -1) {
|
299
|
-
throw new Error('无法找到主包构建信息');
|
300
|
-
}
|
301
|
-
const mainPakConf = packageConfig[targetIndex];
|
302
|
-
packageConfig.splice(targetIndex, 1);
|
303
|
-
const subPakConfList = packageConfig;
|
304
|
-
if (subPakConfList.length > 0) {
|
305
|
-
// 合并分包资源到子包
|
306
|
-
mergeSubPackagesToMainPackage(packagePath, mainPakConf, subPakConfList, onMoveBefore);
|
307
|
-
}
|
308
|
-
return {
|
309
|
-
mainPakConf,
|
310
|
-
packagePath
|
311
|
-
};
|
312
|
-
}
|
313
|
-
function injectNpm(dest, packageName) {
|
314
|
-
const nodePath = require.resolve(packageName);
|
315
|
-
let dirPath = path__default["default"].join(nodePath, '../');
|
316
|
-
let dirname = path__default["default"].basename(dirPath);
|
317
|
-
if (dirname === 'dist') {
|
318
|
-
fs__default["default"].copySync(dirPath, dest);
|
319
|
-
}
|
320
|
-
else {
|
321
|
-
// 开发模式 可能是src/index
|
322
|
-
dirPath = path__default["default"].resolve(dirPath, '../');
|
323
|
-
dirPath = path__default["default"].join(dirPath, 'dist');
|
324
|
-
if (fs__default["default"].existsSync(dirPath)) {
|
325
|
-
fs__default["default"].copySync(dirPath, dest);
|
326
|
-
}
|
327
|
-
else {
|
328
|
-
logger.log(`Builder can't resolve ${packageName} entry from ${nodePath}`);
|
329
|
-
}
|
330
|
-
}
|
331
|
-
}
|
332
|
-
function genEntrys(props) {
|
333
|
-
const { builderConfig, mainPakConf, extUuid } = props;
|
334
|
-
return builderConfig.supportExtTypes.map(extType => {
|
335
|
-
const entryFilename = `index_${extType}.html`;
|
336
|
-
return {
|
337
|
-
extType,
|
338
|
-
entryPath: 'package/' + mainPakConf.name + '/' + entryFilename,
|
339
|
-
sdkUrl: getSDKUrlTemplate({
|
340
|
-
extType,
|
341
|
-
extUuid,
|
342
|
-
hostId: builderConfig.hostId,
|
343
|
-
isTestEnv: builderConfig.isTestEnv
|
344
|
-
}),
|
345
|
-
entryFilename
|
346
|
-
};
|
347
|
-
});
|
348
|
-
}
|
349
|
-
|
350
|
-
// TODO: 改异步
|
351
|
-
// 合并游戏分包到主包
|
352
|
-
function mergeGamePackage(releasePath, opts) {
|
353
|
-
const builderConfig = opts.builderConfig;
|
354
|
-
const { mainPakConf, packagePath } = mergeMainPackage(releasePath);
|
355
|
-
const mainPath = path__default["default"].join(packagePath, mainPakConf.name);
|
356
|
-
const entrys = genEntrys({
|
357
|
-
builderConfig,
|
358
|
-
mainPakConf,
|
359
|
-
extUuid: opts.extInfo.extUuid
|
360
|
-
});
|
361
|
-
PluginDriver.hooks.onMergedMainPackge.call({
|
362
|
-
mainConf: mainPakConf,
|
363
|
-
mainPath,
|
364
|
-
compileType: COMPILE_TYPE.miniGame
|
365
|
-
});
|
366
|
-
return {
|
367
|
-
packagePath,
|
368
|
-
mainPath,
|
369
|
-
entrys,
|
370
|
-
mainPublicPath: 'package/' + mainPakConf.name
|
371
|
-
};
|
372
|
-
}
|
373
|
-
function renderGame(opts) {
|
374
|
-
// 渲染模版
|
375
|
-
renderGameTemplate(opts);
|
376
|
-
// wasn文件 会被 cocos 同步请求,由于二进制文件同步请求失败 所以改为 base64 文本
|
377
|
-
transformWasnFileToBase64File(opts.mainPath);
|
378
|
-
}
|
379
|
-
// mark 热更新 整个函数不会重渲染。
|
380
|
-
function renderGameTemplate(opts) {
|
381
|
-
const { releasePath, mainPath, entrys, debug, dev, extInfo } = opts;
|
382
|
-
const templatePath = path__default["default"].join(staticPath, 'template');
|
383
|
-
const sourcePathPrefix = deployMode === EDeployMode.Integration
|
384
|
-
? path__default["default"].relative(mainPath, releasePath)
|
385
|
-
: '';
|
386
|
-
const renderConfigList = [
|
387
|
-
{
|
388
|
-
input: path__default["default"].join(templatePath, 'game-frame.hbs'),
|
389
|
-
output: path__default["default"].join(mainPath, 'game-frame.html'),
|
390
|
-
data: {
|
391
|
-
sourcePathPrefix
|
392
|
-
}
|
393
|
-
}
|
394
|
-
];
|
395
|
-
if (dev) {
|
396
|
-
renderConfigList.push({
|
397
|
-
input: path__default["default"].join(templatePath, 'remote-debugger.hbs'),
|
398
|
-
output: path__default["default"].join(mainPath, 'remote-debugger.html'),
|
399
|
-
data: {
|
400
|
-
extUuid: extInfo.extUuid,
|
401
|
-
paramsStr: makeWebviewUrlParamsStr()
|
402
|
-
}
|
403
|
-
});
|
404
|
-
}
|
405
|
-
const entryRenderConfList = entrys.map(info => {
|
406
|
-
return {
|
407
|
-
input: path__default["default"].join(templatePath, 'minigame-page-manager.hbs'),
|
408
|
-
output: path__default["default"].join(mainPath, info.entryFilename),
|
409
|
-
data: {
|
410
|
-
sourcePathPrefix,
|
411
|
-
hyextSDKUrl: info.sdkUrl,
|
412
|
-
debug,
|
413
|
-
sentryScript: dev ? undefined : sentryScriptUrl,
|
414
|
-
buildEnv: buildEnv,
|
415
|
-
extInfo: Object.assign(Object.assign({}, extInfo), { envVersion: dev ? 'develop' : 'release', extType: info.extType }),
|
416
|
-
deviceOrientation: PluginDriver.context.deviceOrientation
|
417
|
-
}
|
418
|
-
};
|
419
|
-
});
|
420
|
-
entryRenderConfList.concat(renderConfigList).forEach(config => {
|
421
|
-
renderTemplate(config.input, config.output, config.data);
|
422
|
-
});
|
423
|
-
}
|
424
|
-
const ignorePath = [
|
425
|
-
'node_modules/**/*',
|
426
|
-
'**/node_modules/**',
|
427
|
-
'**/.git/**',
|
428
|
-
'.git/**/*',
|
429
|
-
'**/.svn/**',
|
430
|
-
'.svn/**/*',
|
431
|
-
'.DS_Store',
|
432
|
-
'**/.DS_Store'
|
433
|
-
];
|
434
|
-
function transformWasnFileToBase64File(mainPath) {
|
435
|
-
const files = glob.sync('**/**.wasm', {
|
436
|
-
cwd: mainPath,
|
437
|
-
ignore: ignorePath,
|
438
|
-
nodir: true,
|
439
|
-
absolute: false
|
440
|
-
});
|
441
|
-
files.length && console.log('transform wasm to base64 files: \n', files);
|
442
|
-
files.forEach(file => {
|
443
|
-
const abs = path__default["default"].join(mainPath, file);
|
444
|
-
const text = fs__default["default"].readFileSync(abs).toString('base64');
|
445
|
-
fs__default["default"].outputFileSync(abs + '.txt', text);
|
446
|
-
});
|
447
|
-
}
|
448
|
-
|
449
|
-
function copyServiceBundleToDest(subRoot, mainRoot, config) {
|
450
|
-
const bundleName = config.name + '.js';
|
451
|
-
const bundleMapName = config.name + '.js.map';
|
452
|
-
const bundlePath = path__default["default"].join(subRoot, bundleName);
|
453
|
-
const bundleMapPath = path__default["default"].join(subRoot, bundleMapName);
|
454
|
-
if (fs__default["default"].existsSync(bundlePath)) {
|
455
|
-
fs__default["default"].outputFileSync(path__default["default"].join(mainRoot, bundleName), fs__default["default"].readFileSync(bundlePath));
|
456
|
-
}
|
457
|
-
if (fs__default["default"].existsSync(bundleMapPath)) {
|
458
|
-
fs__default["default"].outputFileSync(path__default["default"].join(mainRoot, bundleMapName), fs__default["default"].readFileSync(bundleMapPath));
|
459
|
-
}
|
460
|
-
}
|
461
|
-
function mergeMiniprogramPackage(releasePath, opts) {
|
462
|
-
const builderConfig = opts.builderConfig;
|
463
|
-
const { mainPakConf, packagePath } = mergeMainPackage(releasePath, copyServiceBundleToDest);
|
464
|
-
const mainPath = path__default["default"].join(packagePath, mainPakConf.name);
|
465
|
-
const entrys = genEntrys({
|
466
|
-
builderConfig,
|
467
|
-
mainPakConf,
|
468
|
-
extUuid: opts.extInfo.extUuid
|
469
|
-
});
|
470
|
-
PluginDriver.hooks.onMergedMainPackge.call({
|
471
|
-
mainConf: mainPakConf,
|
472
|
-
mainPath,
|
473
|
-
compileType: COMPILE_TYPE.miniProgram
|
474
|
-
});
|
475
|
-
return { entrys, mainPublicPath: 'package/' + mainPakConf.name, mainPath, packagePath };
|
476
|
-
}
|
477
|
-
function renderMiniProgram(opts) {
|
478
|
-
renderMiniprogramTemplate(opts);
|
479
|
-
}
|
480
|
-
function renderMiniprogramTemplate(opts) {
|
481
|
-
const { packagePath, releasePath, mainPath, entrys, debug, dev, extInfo } = opts;
|
482
|
-
const extConfig = getPackageExtConfig(packagePath);
|
483
|
-
const sourcePathPrefix = deployMode === EDeployMode.Integration
|
484
|
-
? path__default["default"].relative(mainPath, releasePath)
|
485
|
-
: '';
|
486
|
-
const packageExtConfigStr = JSON.stringify(extConfig);
|
487
|
-
const renderConfigList = [
|
488
|
-
{
|
489
|
-
input: path__default["default"].join(templatePath, 'service.hbs'),
|
490
|
-
output: path__default["default"].join(mainPath, 'service.html'),
|
491
|
-
data: {
|
492
|
-
sourcePathPrefix
|
493
|
-
}
|
494
|
-
}
|
495
|
-
];
|
496
|
-
if (dev) {
|
497
|
-
renderConfigList.push({
|
498
|
-
input: path__default["default"].join(templatePath, 'remote-debugger.hbs'),
|
499
|
-
output: path__default["default"].join(mainPath, 'remote-debugger.html'),
|
500
|
-
data: {
|
501
|
-
extUuid: extInfo.extUuid,
|
502
|
-
paramsStr: makeWebviewUrlParamsStr()
|
503
|
-
}
|
504
|
-
});
|
505
|
-
}
|
506
|
-
const entryRenderConfList = entrys.map(info => {
|
507
|
-
return {
|
508
|
-
input: path__default["default"].join(templatePath, 'miniapp-page-manager.hbs'),
|
509
|
-
output: path__default["default"].join(mainPath, info.entryFilename),
|
510
|
-
data: {
|
511
|
-
sourcePathPrefix,
|
512
|
-
packageExtConfig: packageExtConfigStr,
|
513
|
-
hyextSDKUrl: info.sdkUrl,
|
514
|
-
debug,
|
515
|
-
buildEnv: buildEnv,
|
516
|
-
// sentryScript: dev ? undefined : sentryScriptUrl,
|
517
|
-
sentryScript: sentryScriptUrl,
|
518
|
-
extInfo: Object.assign(Object.assign({}, extInfo), { envVersion: dev ? 'develop' : 'release', version: '', extType: info.extType })
|
519
|
-
}
|
520
|
-
};
|
521
|
-
});
|
522
|
-
entryRenderConfList.concat(renderConfigList).forEach(config => {
|
523
|
-
renderTemplate(config.input, config.output, config.data);
|
524
|
-
});
|
525
|
-
}
|
526
|
-
|
527
|
-
function mergePackages(projectConfig, outputPath, opts) {
|
528
|
-
const baseRenderOpts = {
|
529
|
-
packagePath: '',
|
530
|
-
mainPath: '',
|
531
|
-
releasePath: outputPath,
|
532
|
-
entrys: [],
|
533
|
-
extInfo: opts.extInfo,
|
534
|
-
debug: opts.debug,
|
535
|
-
dev: opts.dev
|
536
|
-
};
|
537
|
-
const implement = (watch) => {
|
538
|
-
logger.log('正在合并分包...');
|
539
|
-
let mergeResult;
|
540
|
-
if (!watch) {
|
541
|
-
injectRuntimeLib(outputPath);
|
542
|
-
}
|
543
|
-
if (projectConfig.compileType == 'game') {
|
544
|
-
mergeResult = mergeGamePackage(outputPath, opts);
|
545
|
-
!watch && renderGame(Object.assign(Object.assign({}, baseRenderOpts), mergeResult));
|
546
|
-
}
|
547
|
-
else {
|
548
|
-
mergeResult = mergeMiniprogramPackage(outputPath, opts);
|
549
|
-
!watch && renderMiniProgram(Object.assign(Object.assign({}, baseRenderOpts), mergeResult));
|
550
|
-
}
|
551
|
-
logger.success('合并分包完成');
|
552
|
-
return mergeResult;
|
553
|
-
};
|
554
|
-
return Object.assign(Object.assign({}, implement(false)), { retry: implement });
|
555
|
-
}
|
556
|
-
function injectRuntimeLib(releasePath) {
|
557
|
-
const frameworkPath = path__default["default"].join(staticPath, 'framework');
|
558
|
-
// 安置本地框架文件
|
559
|
-
if (deployMode === EDeployMode.Integration) {
|
560
|
-
// 迁移运行框架
|
561
|
-
fs__default["default"].copySync(frameworkPath, path__default["default"].join(releasePath, 'framework'));
|
562
|
-
// 迁移SDK
|
563
|
-
const sdkPath = path__default["default"].join(releasePath, 'sdk');
|
564
|
-
fs__default["default"].mkdirSync(sdkPath);
|
565
|
-
injectNpm(sdkPath, '@revues/web-sdk-core');
|
566
|
-
injectNpm(sdkPath, '@revues/web-frame');
|
567
|
-
injectNpm(sdkPath, '@revues/hyext-adapter');
|
568
|
-
// TODO: 这段代码是测试 @revues/js-sdk 增加构建变量去决定执行
|
569
|
-
// injectNpm(sdkPath, '@revues/js-sdk')
|
570
|
-
}
|
571
|
-
}
|
572
|
-
|
573
|
-
class RemoveUnlessDirPlugin {
|
574
|
-
apply(pluginDriver) {
|
575
|
-
pluginDriver.hooks.onSrartBefore.tap('RemoveUnlessDIrPlugin', (opts) => {
|
576
|
-
const { inputPath } = opts;
|
577
|
-
const releasePath = path__default["default"].join(inputPath, 'release');
|
578
|
-
const distPath = path__default["default"].join(inputPath, 'dist');
|
579
|
-
remove(releasePath);
|
580
|
-
remove(distPath);
|
581
|
-
});
|
582
|
-
}
|
583
|
-
}
|
584
|
-
function remove(v) {
|
585
|
-
if (fs__default["default"].existsSync(v)) {
|
586
|
-
fs__default["default"].removeSync(v);
|
587
|
-
}
|
588
|
-
}
|
589
|
-
|
590
|
-
function initPlugins(pluginDriver) {
|
591
|
-
new InjectWebviewUrlParamsPlugin().apply(pluginDriver);
|
592
|
-
new RemoveUnlessDirPlugin().apply(pluginDriver);
|
593
|
-
}
|
594
|
-
|
595
|
-
var httpsConf = {
|
596
|
-
cert: fs__default["default"].readFileSync(path__default["default"].join(staticPath, "./certs/cert.pem")),
|
597
|
-
key: fs__default["default"].readFileSync(path__default["default"].join(staticPath, "./certs/key.pem")),
|
598
|
-
passphrase: ""
|
599
|
-
};
|
600
|
-
|
601
|
-
function startLiveServer(opts) {
|
602
|
-
var params = {
|
603
|
-
port: opts.port,
|
604
|
-
host: opts.host,
|
605
|
-
root: opts.root,
|
606
|
-
open: false,
|
607
|
-
ignore: opts.ignore,
|
608
|
-
file: "index.html",
|
609
|
-
wait: 1000,
|
610
|
-
mount: opts.mount,
|
611
|
-
logLevel: 1,
|
612
|
-
https: httpsConf
|
613
|
-
};
|
614
|
-
// @ts-expect-error
|
615
|
-
liveServer__default["default"].start(params);
|
616
|
-
}
|
617
|
-
|
618
|
-
function compress(output) {
|
619
|
-
return new Promise((resolve, reject) => {
|
620
|
-
const stream = fs__default["default"].createWriteStream(`${output}.zip`), archive = archiver__default["default"]('zip', { zlib: { level: 9 } });
|
621
|
-
stream.on('close', () => {
|
622
|
-
const size = archive.pointer();
|
623
|
-
resolve({ name: `${path__default["default"].basename(output)}.zip`, size });
|
624
|
-
}),
|
625
|
-
archive.on('warning', e => {
|
626
|
-
if ('ENOENT' !== e.code)
|
627
|
-
throw e;
|
628
|
-
}),
|
629
|
-
archive.on('error', e => {
|
630
|
-
reject(e);
|
631
|
-
throw e;
|
632
|
-
}),
|
633
|
-
archive.pipe(stream),
|
634
|
-
archive.directory(`${output}`, false),
|
635
|
-
archive.finalize();
|
636
|
-
});
|
637
|
-
}
|
638
|
-
|
639
|
-
function urlToBase64(url) {
|
640
|
-
return __awaiter(this, void 0, void 0, function* () {
|
641
|
-
try {
|
642
|
-
const res = yield axios__default["default"].get(url, { responseType: 'arraybuffer' });
|
643
|
-
const buffer = Buffer.from(res.data);
|
644
|
-
const info = getFileInfoByUrl(url);
|
645
|
-
return `data:image/${info.ext};base64,` + `${buffer.toString('base64')}`;
|
646
|
-
}
|
647
|
-
catch (e) {
|
648
|
-
throw new Error(`urlToBase64 failed, url is "${url}", error msg is ${e.message}`);
|
649
|
-
}
|
650
|
-
});
|
651
|
-
}
|
652
|
-
function getFileInfoByUrl(url) {
|
653
|
-
var _a;
|
654
|
-
const main = url.split('?')[0];
|
655
|
-
const arr = main.split('/');
|
656
|
-
const [filename, ext] = (_a = arr[arr.length - 1]) === null || _a === void 0 ? void 0 : _a.split('.');
|
657
|
-
if (ext == null || ext == '') {
|
658
|
-
throw new Error(`url:${url}格式错误,无法获取文件信息`);
|
659
|
-
}
|
660
|
-
return {
|
661
|
-
filename,
|
662
|
-
ext
|
663
|
-
};
|
664
|
-
}
|
665
|
-
|
666
|
-
// 36PX
|
667
|
-
function makeBuildResults(mode, opts) {
|
668
|
-
return __awaiter(this, void 0, void 0, function* () {
|
669
|
-
const { baseURI, entrys, outputPath } = opts;
|
670
|
-
const releasePath = path__default["default"].join(outputPath, 'build-result');
|
671
|
-
const buildResultMap = {};
|
672
|
-
const paramsStr = makeWebviewUrlParamsStr();
|
673
|
-
const buildResultList = entrys.map(info => {
|
674
|
-
const result = {
|
675
|
-
type: 'HTML',
|
676
|
-
content: {
|
677
|
-
pages: [
|
678
|
-
{
|
679
|
-
path: getPagePath(info, paramsStr)
|
680
|
-
}
|
681
|
-
],
|
682
|
-
baseURI
|
683
|
-
}
|
684
|
-
};
|
685
|
-
buildResultMap[info.extType] = result;
|
686
|
-
return {
|
687
|
-
type: info.extType,
|
688
|
-
buildResult: {
|
689
|
-
[info.extType]: result
|
690
|
-
}
|
691
|
-
};
|
692
|
-
});
|
693
|
-
if (mode === 'development') {
|
694
|
-
const fsTasks = buildResultList.map((buildResultInfo) => {
|
695
|
-
return fs__default["default"].outputFile(path__default["default"].join(releasePath, buildResultInfo.type + '.json'), JSON.stringify(buildResultInfo.buildResult, null, 2));
|
696
|
-
});
|
697
|
-
yield Promise.all(fsTasks);
|
698
|
-
}
|
699
|
-
return buildResultMap;
|
700
|
-
});
|
701
|
-
}
|
702
|
-
function getPagePath(entryInfo, extraParams) {
|
703
|
-
const extType = entryInfo.extType;
|
704
|
-
let entry = entryInfo.entryPath;
|
705
|
-
// 移动端需要补 __module_busi__
|
706
|
-
if (extType.endsWith('_h5')) {
|
707
|
-
entry += '?__module_busi__=kiwi-ExtSDK' + extraParams;
|
708
|
-
}
|
709
|
-
return entry;
|
710
|
-
}
|
711
|
-
|
712
|
-
const getIPAddress = () => {
|
713
|
-
const ifaces = os__default["default"].networkInterfaces();
|
714
|
-
const addresses = R__default["default"].flatten(R__default["default"].values(ifaces));
|
715
|
-
const address = R__default["default"].filter((iface) => /(ipv)?4/ig.test(iface.family) && !/^127\./.test(iface.address), addresses);
|
716
|
-
return address;
|
717
|
-
};
|
718
|
-
const getPublicIP = (config) => {
|
719
|
-
var _a;
|
720
|
-
const address = getIPAddress();
|
721
|
-
/*
|
722
|
-
* 有多个 ip 地址又没有在 config.host 中指定的话, 直接退出
|
723
|
-
*/
|
724
|
-
if (address && address.length > 1) {
|
725
|
-
logger.log(`检测到本机有多个 ip 地址:\n- ${address
|
726
|
-
.map((x) => x.address)
|
727
|
-
.join('\n- ')}`);
|
728
|
-
logger.log('请在 project.config.json 的 host 中指定正确的 ip');
|
729
|
-
process.exit(1);
|
730
|
-
}
|
731
|
-
if (address && address.length <= 0) {
|
732
|
-
logger.log('未能找到本机 ip 地址, 本地开发 app 侧将无法加载小程序');
|
733
|
-
process.exit(1);
|
734
|
-
}
|
735
|
-
return (_a = address[0]) === null || _a === void 0 ? void 0 : _a.address;
|
736
|
-
};
|
737
|
-
|
738
|
-
const supportedExtTypeSet = new Set([
|
739
|
-
"app_inner_h5",
|
740
|
-
'web_video_com',
|
741
|
-
'app_panel_h5',
|
742
|
-
'zs_anchor_panel_h5',
|
743
|
-
'pc_anchor_panel',
|
744
|
-
'pc_panel'
|
745
|
-
]);
|
746
|
-
function checkExtTypes(extTypes) {
|
747
|
-
let unsupportList = [];
|
748
|
-
if (!extTypes || extTypes.length === 0) {
|
749
|
-
logger.fatal('请在project.config.json相应地方填写supportExtTypes.');
|
750
|
-
}
|
751
|
-
else {
|
752
|
-
extTypes.forEach((item) => {
|
753
|
-
if (!supportedExtTypeSet.has(item)) {
|
754
|
-
unsupportList.push(item);
|
755
|
-
}
|
756
|
-
});
|
757
|
-
}
|
758
|
-
if (unsupportList.length > 0) {
|
759
|
-
logger.fatal(`未支持的小程序类型:${unsupportList.join('|')}.`);
|
760
|
-
}
|
761
|
-
}
|
762
|
-
function processDevConfig(config) {
|
763
|
-
// 强制开启
|
764
|
-
config.https = true;
|
765
|
-
if (config.host == null) {
|
766
|
-
config.host = getPublicIP() || ''; // 用ip地址不用localshot
|
767
|
-
}
|
768
|
-
if (config.port == null) {
|
769
|
-
config.port = 18080;
|
770
|
-
}
|
771
|
-
}
|
772
|
-
function processGlobalConfig(config) {
|
773
|
-
if (config.hostId == null) {
|
774
|
-
config.hostId = 'huyaext';
|
775
|
-
}
|
776
|
-
}
|
777
|
-
function processBuilderConfigJSON(mode, config) {
|
778
|
-
const opts = Object.assign({}, config);
|
779
|
-
checkExtTypes(config.supportExtTypes);
|
780
|
-
processGlobalConfig(opts);
|
781
|
-
if (mode === 'development') {
|
782
|
-
processDevConfig(opts);
|
783
|
-
}
|
784
|
-
return opts;
|
785
|
-
}
|
786
|
-
function getDevBaseURI(config) {
|
787
|
-
const protocol = config.https ? 'https' : 'http';
|
788
|
-
return `${protocol}://${config.host}:${config.port}/`;
|
789
|
-
}
|
790
|
-
|
791
|
-
function checkAppId(project) {
|
792
|
-
const appId = project.appId || project.appid;
|
793
|
-
if (appId == null || appId === '') {
|
794
|
-
logger.fatal('请填写正确的appid');
|
795
|
-
}
|
796
|
-
else if (appId.length > 10) {
|
797
|
-
logger.fatal('appid错误,请登录 https://ext.huya.com/ 在您的小程序概要中查看小程序ID');
|
798
|
-
}
|
799
|
-
return appId;
|
800
|
-
}
|
801
|
-
function checkProjectName(project) {
|
802
|
-
return project.projectname || project.projectName || '小程序';
|
803
|
-
}
|
804
|
-
|
805
|
-
function getTempProjectDir(projecName) {
|
806
|
-
return path__default["default"].join(tempDir, '.revues-projects', projecName);
|
807
|
-
}
|
808
|
-
class RevueBuilder {
|
809
|
-
constructor() {
|
810
|
-
// 单例 PluginDriver 更加灵活
|
811
|
-
initPlugins(PluginDriver);
|
812
|
-
}
|
813
|
-
// 这里拿到打包好的代码 原样输出 + build result
|
814
|
-
build(opts) {
|
815
|
-
return __awaiter(this, void 0, void 0, function* () {
|
816
|
-
const { inputPath, outputPath, publicPath, projectConfig, config, extUuid, extName, extVersion, extVersionId, extLogo } = opts;
|
817
|
-
const processedConfig = processBuilderConfigJSON('production', config);
|
818
|
-
fs__default["default"].existsSync(outputPath) && fs__default["default"].removeSync(outputPath);
|
819
|
-
// 把 inputPath 的文件 迁移到 outputPath
|
820
|
-
yield fs__default["default"].copy(inputPath, outputPath, { overwrite: true });
|
821
|
-
const { entrys } = mergePackages(projectConfig, outputPath, {
|
822
|
-
builderConfig: processedConfig,
|
823
|
-
extInfo: {
|
824
|
-
extUuid,
|
825
|
-
extName,
|
826
|
-
extVersion,
|
827
|
-
extVersionId,
|
828
|
-
extLogo: yield urlToBase64(extLogo)
|
829
|
-
}
|
830
|
-
});
|
831
|
-
return yield makeBuildResults('production', {
|
832
|
-
entrys: entrys,
|
833
|
-
baseURI: publicPath,
|
834
|
-
outputPath
|
835
|
-
});
|
836
|
-
});
|
837
|
-
}
|
838
|
-
start(opts) {
|
839
|
-
var _a;
|
840
|
-
return __awaiter(this, void 0, void 0, function* () {
|
841
|
-
const { debug, inputPath, projectConfig, outputPath: outputPath$1, config } = opts;
|
842
|
-
PluginDriver.hooks.onSrartBefore.call({ inputPath });
|
843
|
-
const processedConfig = processBuilderConfigJSON('development', config);
|
844
|
-
const appId = checkAppId(projectConfig);
|
845
|
-
const projectName = checkProjectName(projectConfig);
|
846
|
-
const extInfo = {
|
847
|
-
extUuid: appId,
|
848
|
-
extName: projectName,
|
849
|
-
extVersion: undefined,
|
850
|
-
extVersionId: undefined,
|
851
|
-
extLogo: undefined
|
852
|
-
};
|
853
|
-
let retryRef = (watch) => { };
|
854
|
-
const outputPath = getTempProjectDir(`${projectName}-${appId}`)
|
855
|
-
;
|
856
|
-
if (projectConfig.compileType == 'game') {
|
857
|
-
yield watchGame(inputPath, outputPath, () => {
|
858
|
-
retryRef(true);
|
859
|
-
});
|
860
|
-
}
|
861
|
-
else {
|
862
|
-
yield watch(inputPath, outputPath, () => {
|
863
|
-
retryRef(true);
|
864
|
-
});
|
865
|
-
}
|
866
|
-
const { entrys, mainPublicPath, retry } = mergePackages(projectConfig, outputPath, {
|
867
|
-
builderConfig: processedConfig,
|
868
|
-
extInfo,
|
869
|
-
debug,
|
870
|
-
dev: true
|
871
|
-
});
|
872
|
-
retryRef = retry;
|
873
|
-
logger.log('启动 live server 服务...');
|
874
|
-
logger.success('本地访问地址:', getDevBaseURI(processedConfig) + ((_a = entrys[0]) === null || _a === void 0 ? void 0 : _a.entryPath));
|
875
|
-
logger.success('扫码预览地址:', getDevBaseURI(processedConfig) + mainPublicPath + '/remote-debugger.html');
|
876
|
-
startLiveServer(Object.assign(Object.assign({}, processedConfig), { root: outputPath, ignore: 'node_modules' }));
|
877
|
-
return yield makeBuildResults('development', {
|
878
|
-
entrys,
|
879
|
-
baseURI: getDevBaseURI(processedConfig),
|
880
|
-
outputPath: outputPath$1
|
881
|
-
});
|
882
|
-
});
|
883
|
-
}
|
884
|
-
// 这里仅仅在 client 打包 小程序/小游戏
|
885
|
-
release(opts) {
|
886
|
-
return __awaiter(this, void 0, void 0, function* () {
|
887
|
-
const { contextPath, releasePath, projectConfig } = opts;
|
888
|
-
if (fs__default["default"].existsSync(releasePath)) {
|
889
|
-
fs__default["default"].removeSync(releasePath);
|
890
|
-
}
|
891
|
-
logger.log('开始打包');
|
892
|
-
const projectName = projectConfig.projectName || projectConfig.projectname || 'project';
|
893
|
-
const outputPath = path__default["default"].join(releasePath, projectName);
|
894
|
-
if (projectConfig.compileType == 'game') {
|
895
|
-
yield compileGame('prod', contextPath, outputPath);
|
896
|
-
}
|
897
|
-
else {
|
898
|
-
yield compile('prod', contextPath, outputPath);
|
899
|
-
}
|
900
|
-
// zip
|
901
|
-
const zipPath = path__default["default"].join(releasePath, projectName);
|
902
|
-
yield compress(zipPath);
|
903
|
-
logger.success('打包成功,zip包地址:' + zipPath);
|
904
|
-
});
|
905
|
-
}
|
906
|
-
config() { }
|
907
|
-
providedProjectConfig() { }
|
908
|
-
clearCache() {
|
909
|
-
try {
|
910
|
-
if (fs__default["default"].existsSync(cacheDir)) {
|
911
|
-
fs__default["default"].removeSync(cacheDir);
|
912
|
-
}
|
913
|
-
logger.success('项目缓存清除成功~');
|
914
|
-
}
|
915
|
-
catch (error) {
|
916
|
-
logger.success('项目缓存清除失败 \n' + error.message);
|
917
|
-
}
|
918
|
-
}
|
919
|
-
}
|
920
|
-
const revueBuilder = new RevueBuilder();
|
921
|
-
|
922
|
-
module.exports = revueBuilder;
|
923
|
-
|
924
|
-
exports["default"] = revueBuilder;
|
6
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs-extra"),t=require("path"),n=require("@revues/code-compiler"),o=require("os"),a=require("chalk"),i=require("util"),r=require("glob"),s=require("handlebars"),u=require("tapable"),c=require("live-server"),l=require("archiver"),d=require("axios"),p=require("ramda");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m,g=f(e),h=f(t),y=f(o),v=f(a),j=f(s),x=f(c),P=f(l),b=f(d),S=f(p);
|
7
|
+
/*! *****************************************************************************
|
8
|
+
Copyright (c) Microsoft Corporation.
|
9
|
+
|
10
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
11
|
+
purpose with or without fee is hereby granted.
|
12
|
+
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
14
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
15
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
16
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
17
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
18
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
19
|
+
PERFORMANCE OF THIS SOFTWARE.
|
20
|
+
***************************************************************************** */
|
21
|
+
function k(e,t,n,o){return new(n||(n=Promise))((function(a,i){function r(e){try{u(o.next(e))}catch(e){i(e)}}function s(e){try{u(o.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,s)}u((o=o.apply(e,t||[])).next())}))}!function(e){e[e.Integration=0]="Integration",e[e.Separate=1]="Separate"}(m||(m={}));const I=y.default.tmpdir(),w=h.default.join(I,".revue_cache"),T=m.Integration,_=process.env.HYEXT_BUILD_ENV||"dev",O=h.default.resolve(__dirname,"../static"),E=h.default.join(O,"template");var U;!function(e){e.miniProgram="miniProgram",e.miniProgramPlugin="miniProgramPlugin",e.miniGame="miniGame",e.miniGamePlugin="miniGamePlugin"}(U||(U={}));const $=v.default.gray("·");var C=(e=>{e=` ${e}`;return{log(...t){const n=i.format.apply(i.format,t);console.log(v.default.white(e),$,n)},fatal(...t){t[0]instanceof Error&&(t[0]=t[0].message.trim());const n=i.format.apply(i.format,t);console.error(v.default.red(e),$,n),process.exit(1)},success(...t){const n=i.format.apply(i.format,t);console.log(v.default.green(e),$,n)}}})("REVUE");const M="project.config.json";function F(e,t){g.default.copyFileSync(h.default.join(e,M),h.default.join(t,M))}function N(){g.default.existsSync(w)||g.default.mkdirSync(w)}function q(e,t,o){return k(this,void 0,void 0,(function*(){const a="prod"===e,i=a?{minify:!0,autoPrefixWXSS:!0,minifyWXSS:!0}:{};N(),yield n.compilerManager.init({projectPath:t,outputPath:o,cachePath:w,compileSettings:i});const r=a?"compile":"compileDev";yield n.compilerManager[r](),F(t,o)}))}function D(e,t,o){return k(this,void 0,void 0,(function*(){N(),yield n.compilerManager.init({projectPath:t,outputPath:o,cachePath:w,compileSettings:{cocos:!0,minify:"prod"===e}});const a="dev"===e?"compileDev":"compile";yield n.compilerManager[a](),F(t,o)}))}const B=Date.now(),V="production"!==process.env.HYEXT_BUILD_ENV?"//test-hd.huya.com/h5/hyext-sentry-setup-script/test/sentry-setup.js":`//a.msstatic.com/huya/hd/h5/hyext-sentry-setup-script/sentry-setup.js?hash=${B}`;function R(e,t,n){const o=g.default.readFileSync(e).toString();g.default.outputFileSync(t,function(e,t,n){return j.default.compile(e,{noEscape:!0})(t,n)}(o,n))}j.default.registerHelper("toJSON",(function(e){return new j.default.SafeString(JSON.stringify(e))}));const z={context:{deviceOrientation:"portrait"},hooks:{onMergedMainPackge:new u.SyncHook(["IOnMergedMainPackge"]),onSrartBefore:new u.SyncHook(["IOnSrartBefore"])}};class G{apply(e){e.hooks.onMergedMainPackge.tap("InjectWebviewUrlParamsPlugin",(t=>{const{compileType:n,mainPath:o}=t,a=n===U.miniGame;if(a){const t=g.default.readJsonSync(h.default.join(o,"game.json"));"string"==typeof t.deviceOrientation&&t.deviceOrientation.includes("landscape")&&(e.context.deviceOrientation="landscape")}e.context.webviewUrlParams={isLandscape:0,disablePopGesture:1,hideStatusBar:a?1:0,hideBar:1,bounces:0,hideloading:1}}))}}function L(){const e=z.context.webviewUrlParams;return e?(t=e,Object.keys(t).reduce(((e,n)=>e+`&${n}=${encodeURIComponent(t[n])}`),"")):"";var t}const J={test:"//test-extsdk.msstatic.com",prod:"//extsdk-msstatic.cdn.huya.com"};function H(e,t){const o=h.default.join(e,"package"),a=function(e){const t=h.default.join(e,"packageConfig.json");return g.default.readJSONSync(t)}(o),i=a.findIndex((e=>{return(t=e).name===n.pkgFileType.MainPkg&&"."===t.root;var t}));if(-1===i)throw new Error("无法找到主包构建信息");const r=a[i];a.splice(i,1);const s=a;return s.length>0&&function(e,t,n,o){const a=h.default.join(e,t.name);n.forEach((t=>{const n=h.default.join(e,t.name),i=h.default.join(n,t.root),r=h.default.join(a,t.root);o&&o(n,a,t),g.default.moveSync(i,r,{overwrite:!0}),g.default.removeSync(h.default.join(e,t.name))}))}(o,r,s,t),{mainPakConf:r,packagePath:o}}function W(e,t){const n=require.resolve(t);let o=h.default.join(n,"../");"dist"===h.default.basename(o)?g.default.copySync(o,e):(o=h.default.resolve(o,"../"),o=h.default.join(o,"dist"),g.default.existsSync(o)?g.default.copySync(o,e):C.log(`Builder can't resolve ${t} entry from ${n}`))}function X(e){const{builderConfig:t,mainPakConf:n,extUuid:o}=e;return t.supportExtTypes.map((e=>{const a=`index_${e}.html`;return{extType:e,entryPath:"package/"+n.name+"/"+a,sdkUrl:(i={extType:e,extUuid:o,hostId:t.hostId,isTestEnv:t.isTestEnv},`${i.isTestEnv?J.test:J.prod}/sdk/${i.extType}/${i.hostId}/${i.extUuid||0}/sdk.js`),entryFilename:a};var i}))}function K(e){!function(e){const{releasePath:t,mainPath:n,entrys:o,debug:a,dev:i,extInfo:r}=e,s=h.default.join(O,"template"),u=T===m.Integration?h.default.relative(n,t):"",c=[{input:h.default.join(s,"game-frame.hbs"),output:h.default.join(n,"game-frame.html"),data:{sourcePathPrefix:u}}];i&&c.push({input:h.default.join(s,"remote-debugger.hbs"),output:h.default.join(n,"remote-debugger.html"),data:{extInfo:r,paramsStr:L()}});const l=o.map((e=>({input:h.default.join(s,"minigame-page-manager.hbs"),output:h.default.join(n,e.entryFilename),data:{sourcePathPrefix:u,hyextSDKUrl:e.sdkUrl,debug:a,sentryScript:i?void 0:V,buildEnv:_,extInfo:Object.assign(Object.assign({},r),{envVersion:i?"develop":"release",extType:e.extType}),deviceOrientation:z.context.deviceOrientation}})));l.concat(c).forEach((e=>{R(e.input,e.output,e.data)}))}(e),function(e){const t=r.sync("**/**.wasm",{cwd:e,ignore:Y,nodir:!0,absolute:!1});t.length&&console.log("transform wasm to base64 files: \n",t),t.forEach((t=>{const n=h.default.join(e,t),o=g.default.readFileSync(n).toString("base64");g.default.outputFileSync(n+".txt",o)}))}(e.mainPath)}const Y=["node_modules/**/*","**/node_modules/**","**/.git/**",".git/**/*","**/.svn/**",".svn/**/*",".DS_Store","**/.DS_Store"];function A(e,t,n){const o=n.name+".js",a=n.name+".js.map",i=h.default.join(e,o),r=h.default.join(e,a);g.default.existsSync(i)&&g.default.outputFileSync(h.default.join(t,o),g.default.readFileSync(i)),g.default.existsSync(r)&&g.default.outputFileSync(h.default.join(t,a),g.default.readFileSync(r))}function Q(e){!function(e){const{packagePath:t,releasePath:n,mainPath:o,entrys:a,debug:i,dev:r,extInfo:s}=e,u=function(e){const t=h.default.join(e,"packageExtConfig.json");return g.default.readJSONSync(t)}(t),c=T===m.Integration?h.default.relative(o,n):"",l=JSON.stringify(u),d=[{input:h.default.join(E,"service.hbs"),output:h.default.join(o,"service.html"),data:{sourcePathPrefix:c}}];r&&d.push({input:h.default.join(E,"remote-debugger.hbs"),output:h.default.join(o,"remote-debugger.html"),data:{extInfo:s,paramsStr:L()}});a.map((e=>({input:h.default.join(E,"miniapp-page-manager.hbs"),output:h.default.join(o,e.entryFilename),data:{sourcePathPrefix:c,packageExtConfig:l,hyextSDKUrl:e.sdkUrl,debug:i,buildEnv:_,sentryScript:V,extInfo:Object.assign(Object.assign({},s),{envVersion:r?"develop":"release",version:"",extType:e.extType})}}))).concat(d).forEach((e=>{R(e.input,e.output,e.data)}))}(e)}function Z(e,t,n){const o={packagePath:"",mainPath:"",releasePath:t,entrys:[],extInfo:n.extInfo,debug:n.debug,dev:n.dev},a=a=>{let i;return C.log("正在合并分包..."),a||function(e){const t=h.default.join(O,"framework");if(T===m.Integration){g.default.copySync(t,h.default.join(e,"framework"));const n=h.default.join(e,"sdk");g.default.mkdirSync(n),W(n,"@revues/web-sdk-core"),W(n,"@revues/web-frame"),W(n,"@revues/hyext-adapter")}}(t),"game"==e.compileType?(i=function(e,t){const n=t.builderConfig,{mainPakConf:o,packagePath:a}=H(e),i=h.default.join(a,o.name),r=X({builderConfig:n,mainPakConf:o,extUuid:t.extInfo.extUuid});return z.hooks.onMergedMainPackge.call({mainConf:o,mainPath:i,compileType:U.miniGame}),{packagePath:a,mainPath:i,entrys:r,mainPublicPath:"package/"+o.name}}(t,n),!a&&K(Object.assign(Object.assign({},o),i))):(i=function(e,t){const n=t.builderConfig,{mainPakConf:o,packagePath:a}=H(e,A),i=h.default.join(a,o.name),r=X({builderConfig:n,mainPakConf:o,extUuid:t.extInfo.extUuid});return z.hooks.onMergedMainPackge.call({mainConf:o,mainPath:i,compileType:U.miniProgram}),{entrys:r,mainPublicPath:"package/"+o.name,mainPath:i,packagePath:a}}(t,n),!a&&Q(Object.assign(Object.assign({},o),i))),C.success("合并分包完成"),i};return Object.assign(Object.assign({},a(!1)),{retry:a})}class ee{apply(e){e.hooks.onSrartBefore.tap("RemoveUnlessDIrPlugin",(e=>{const{inputPath:t}=e,n=h.default.join(t,"release"),o=h.default.join(t,"dist");te(n),te(o)}))}}function te(e){g.default.existsSync(e)&&g.default.removeSync(e)}var ne={cert:g.default.readFileSync(h.default.join(O,"./certs/cert.pem")),key:g.default.readFileSync(h.default.join(O,"./certs/key.pem")),passphrase:""};function oe(e){return k(this,void 0,void 0,(function*(){try{const t=yield b.default.get(e,{responseType:"arraybuffer"}),n=Buffer.from(t.data),o=function(e){var t;const n=e.split("?")[0],o=n.split("/"),[a,i]=null===(t=o[o.length-1])||void 0===t?void 0:t.split(".");if(null==i||""==i)throw new Error(`url:${e}格式错误,无法获取文件信息`);return{filename:a,ext:i}}(e);return`data:image/${o.ext};base64,${n.toString("base64")}`}catch(t){throw new Error(`urlToBase64 failed, url is "${e}", error msg is ${t.message}`)}}))}function ae(e,t){return k(this,void 0,void 0,(function*(){const{baseURI:n,entrys:o,outputPath:a}=t,i=h.default.join(a,"build-result"),r={},s=L(),u=o.map((e=>{const t={type:"HTML",content:{pages:[{path:ie(e,s)}],baseURI:n}};return r[e.extType]=t,{type:e.extType,buildResult:{[e.extType]:t}}}));if("development"===e){const e=u.map((e=>g.default.outputFile(h.default.join(i,e.type+".json"),JSON.stringify(e.buildResult,null,2))));yield Promise.all(e)}return r}))}function ie(e,t){const n=e.extType;let o=e.entryPath;return n.endsWith("_h5")&&(o+="?__module_busi__=kiwi-ExtSDK"+t),o}const re=e=>{var t;const n=(()=>{const e=y.default.networkInterfaces(),t=S.default.flatten(S.default.values(e));return S.default.filter((e=>/(ipv)?4/gi.test(e.family)&&!/^127\./.test(e.address)),t)})();return n&&n.length>1&&(C.log(`检测到本机有多个 ip 地址:\n- ${n.map((e=>e.address)).join("\n- ")}`),C.log("请在 project.config.json 的 host 中指定正确的 ip"),process.exit(1)),n&&n.length<=0&&(C.log("未能找到本机 ip 地址, 本地开发 app 侧将无法加载小程序"),process.exit(1)),null===(t=n[0])||void 0===t?void 0:t.address},se=new Set(["app_inner_h5","web_video_com","app_panel_h5","zs_anchor_panel_h5","pc_anchor_panel","pc_panel"]);function ue(e,t){const n=Object.assign({},t);return function(e){let t=[];e&&0!==e.length?e.forEach((e=>{se.has(e)||t.push(e)})):C.fatal("请在project.config.json相应地方填写supportExtTypes."),t.length>0&&C.fatal(`未支持的小程序类型:${t.join("|")}.`)}(t.supportExtTypes),function(e){null==e.hostId&&(e.hostId="huyaext")}(n),"development"===e&&function(e){e.https=!0,null==e.host&&(e.host=re()||""),null==e.port&&(e.port=18080)}(n),n}function ce(e){return`${e.https?"https":"http"}://${e.host}:${e.port}/`}function le(e){return"game"===e.compileType?"miniGame":"miniProgram"}const de=new class{constructor(){var e;e=z,(new G).apply(e),(new ee).apply(e)}build(e){return k(this,void 0,void 0,(function*(){const{inputPath:t,outputPath:n,publicPath:o,projectConfig:a,config:i,extUuid:r,extName:s,extVersion:u,extVersionId:c,extLogo:l}=e,d=ue("production",i);g.default.existsSync(n)&&g.default.removeSync(n),yield g.default.copy(t,n,{overwrite:!0});const{entrys:p}=Z(a,n,{builderConfig:d,extInfo:{projectType:le(a),extUuid:r,extName:s,extVersion:u,extVersionId:c,extLogo:yield oe(l)}});return yield ae("production",{entrys:p,baseURI:o,outputPath:n})}))}start(e){var t;return k(this,void 0,void 0,(function*(){const{debug:o,inputPath:a,projectConfig:i,outputPath:r,config:s}=e;z.hooks.onSrartBefore.call({inputPath:a});const u=ue("development",s),c=function(e){const t=e.appId||e.appid;return null==t||""===t?C.fatal("请填写正确的appid"):t.length>10&&C.fatal("appid错误,请登录 https://ext.huya.com/ 在您的小程序概要中查看小程序ID"),t}(i),l=(d=i).projectname||d.projectName||"小程序";var d;const p={extUuid:c,extName:l,projectType:le(i),extVersion:void 0,extVersionId:void 0,extLogo:void 0};let f=e=>{};const m=(g=`${l}-${c}`,h.default.join(I,".revues-projects",g));var g;"game"==i.compileType?yield function(e,t,o){return k(this,void 0,void 0,(function*(){yield D("dev",e,t),n.compilerManager.watch({graphId:"game"},((a,i)=>k(this,void 0,void 0,(function*(){C.log("detected change:",i),C.log("recompile..."),n.compilerManager.destroy(),yield n.compilerManager.init({projectPath:e,outputPath:t,cachePath:w,compileSettings:{cocos:!0}}),yield n.compilerManager.compileDev(!0),o&&o()}))))}))}(a,m,(()=>{f(!0)})):yield function(e,t,o){return k(this,void 0,void 0,(function*(){yield q("dev",e,t),n.compilerManager.watch({graphId:"miniprogram"},((e,t)=>k(this,void 0,void 0,(function*(){yield n.compilerManager.compileSingleCode({type:e,filePath:t,graphId:"miniprogram"}),o&&o()}))))}))}(a,m,(()=>{f(!0)}));const{entrys:y,mainPublicPath:v,retry:j}=Z(i,m,{builderConfig:u,extInfo:p,debug:o,dev:!0});return f=j,C.log("启动 live server 服务..."),C.success("本地访问地址:",ce(u)+(null===(t=y[0])||void 0===t?void 0:t.entryPath)),C.success("扫码预览地址:",ce(u)+v+"/remote-debugger.html"),function(e){var t={port:e.port,host:e.host,root:e.root,open:!1,ignore:e.ignore,file:"index.html",wait:1e3,mount:e.mount,logLevel:1,https:ne};x.default.start(t)}(Object.assign(Object.assign({},u),{root:m,ignore:"node_modules"})),yield ae("development",{entrys:y,baseURI:ce(u),outputPath:r})}))}release(e){return k(this,void 0,void 0,(function*(){const{contextPath:t,releasePath:n,projectConfig:o}=e;g.default.existsSync(n)&&g.default.removeSync(n),C.log("开始打包");const a=o.projectName||o.projectname||"project",i=h.default.join(n,a);"game"==o.compileType?yield D("prod",t,i):yield q("prod",t,i);const r=h.default.join(n,a);var s;yield(s=r,new Promise(((e,t)=>{const n=g.default.createWriteStream(`${s}.zip`),o=P.default("zip",{zlib:{level:9}});n.on("close",(()=>{const t=o.pointer();e({name:`${h.default.basename(s)}.zip`,size:t})})),o.on("warning",(e=>{if("ENOENT"!==e.code)throw e})),o.on("error",(e=>{throw t(e),e})),o.pipe(n),o.directory(`${s}`,!1),o.finalize()}))),C.success("打包成功,zip包地址:"+r)}))}config(){}providedProjectConfig(){}clearCache(){try{g.default.existsSync(w)&&g.default.removeSync(w),C.success("项目缓存清除成功~")}catch(e){C.success("项目缓存清除失败 \n"+e.message)}}};module.exports=de,exports.default=de;
|