@hadss/hmrouter-plugin
Version:
HMRouter Compiler Plugin
223 lines (222 loc) • 12 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HMRouterPluginHandle = void 0;
const hvigor_ohos_plugin_1 = require("@ohos/hvigor-ohos-plugin");
const HMRouterPluginConfig_1 = require("./HMRouterPluginConfig");
const HMRouterHvigorPlugin_1 = require("./HMRouterHvigorPlugin");
const Logger_1 = require("./common/Logger");
const CommonConstants_1 = __importDefault(require("./constants/CommonConstants"));
const TaskConstants_1 = __importDefault(require("./constants/TaskConstants"));
const FileUtil_1 = __importDefault(require("./utils/FileUtil"));
const ObfuscationUtil_1 = __importDefault(require("./utils/ObfuscationUtil"));
const PluginStore_1 = __importDefault(require("./store/PluginStore"));
class HMRouterPluginHandle {
constructor(node, moduleContext) {
this.node = node;
this.moduleContext = moduleContext;
this.config = this.readConfig();
this.appContext = this.node.getParentNode()?.getContext(hvigor_ohos_plugin_1.OhosPluginId.OHOS_APP_PLUGIN);
PluginStore_1.default.getInstance().projectFilePath = this.appContext.getProjectPath();
this.plugin = new HMRouterHvigorPlugin_1.HMRouterHvigorPlugin(this.config);
}
start() {
Logger_1.Logger.info(`Exec ${this.moduleContext.getModuleType()}Plugin..., node:${this.node.getNodeName()}, nodePath:${this.node.getNodePath()}`);
this.moduleContext.targets((target) => {
const targetName = target.getTargetName();
this.node.registerTask({
name: targetName + TaskConstants_1.default.PLUGIN_TASK,
run: () => {
this.taskExec();
this.plugin.scanFiles = [];
this.plugin.routerMap = [];
},
dependencies: [targetName + TaskConstants_1.default.PRE_BUILD],
postDependencies: [targetName + TaskConstants_1.default.MERGE_PROFILE]
});
this.node.registerTask({
name: targetName + TaskConstants_1.default.COPY_ROUTER_MAP_TASK,
run: () => {
this.copyRouterMapToRawFileTask(target.getBuildTargetOutputPath(), targetName);
this.writeHspModuleName();
},
dependencies: [targetName + TaskConstants_1.default.PROCESS_ROUTER_MAP],
postDependencies: [targetName + TaskConstants_1.default.PROCESS_RESOURCE]
});
this.node.registerTask({
name: targetName + TaskConstants_1.default.GENERATE_OBFUSCATION_TASK,
run: () => {
this.generateObfuscationFileTask(this.moduleContext.getBuildProfileOpt());
},
dependencies: [targetName + TaskConstants_1.default.PLUGIN_TASK],
postDependencies: [targetName + TaskConstants_1.default.MERGE_PROFILE]
});
});
}
generateObfuscationFileTask(buildProfileOpt) {
if (!this.isEnableObfuscation(buildProfileOpt)) {
Logger_1.Logger.info('This compilation does not turn on code obfuscation, skip hmrouter_obfuscation_rules.txt file generation');
return;
}
let obfuscationFilePath = FileUtil_1.default.pathResolve(this.config.modulePath, CommonConstants_1.default.OBFUSCATION_FILE_NAME);
let routerMap = JSON.parse(FileUtil_1.default.readFileSync(this.config.getRouterMapDir()).toString()).routerMap;
let obfuscationString = ObfuscationUtil_1.default.buildObfuscatedStrings(routerMap);
FileUtil_1.default.ensureFileSync(obfuscationFilePath);
FileUtil_1.default.writeFileSync(obfuscationFilePath, obfuscationString);
if (this.moduleContext.getModuleType() === CommonConstants_1.default.HAR_MODULE_NAME) {
let consumerRulesPath = FileUtil_1.default.pathResolve(this.config.modulePath, CommonConstants_1.default.CONSUMER_FILE_NAME);
FileUtil_1.default.ensureFileSync(consumerRulesPath);
FileUtil_1.default.writeFileSync(consumerRulesPath, obfuscationString);
}
Logger_1.Logger.info('Generate obfuscation rule file successfully, filePath:', obfuscationFilePath);
}
isEnableObfuscation(buildProfileOpt) {
let currentBuildMode = this.appContext.getBuildMode();
let buildOption = buildProfileOpt.buildOptionSet?.find((item) => {
return item.name == currentBuildMode;
});
if (!buildOption)
return false;
let ruleOptions = this.ensureNestedObject(buildOption, ['arkOptions', 'obfuscation', 'ruleOptions']);
if (this.config.autoObfuscation && ruleOptions.enable) {
let files = this.ensureNestedObject(buildOption, ['arkOptions', 'obfuscation', 'ruleOptions', 'files']);
let obfuscationFilePath = CommonConstants_1.default.CURRENT_DELIMITER +
CommonConstants_1.default.OBFUSCATION_FILE_NAME;
if (typeof files === 'string') {
ruleOptions.files = [files, obfuscationFilePath];
}
else if (Array.isArray(files)) {
files.push(obfuscationFilePath);
}
else {
ruleOptions.files = obfuscationFilePath;
}
if (this.moduleContext.getModuleType() === CommonConstants_1.default.HAR_MODULE_NAME) {
let consumerFiles = this.ensureNestedObject(buildOption, ['arkOptions', 'obfuscation', 'consumerFiles']);
let consumerRulesPath = CommonConstants_1.default.CURRENT_DELIMITER +
CommonConstants_1.default.CONSUMER_FILE_NAME;
if (typeof consumerFiles === 'string') {
this.ensureNestedObject(buildOption, ['arkOptions', 'obfuscation']).consumerFiles =
[consumerFiles, consumerRulesPath];
}
else if (Array.isArray(consumerFiles)) {
consumerFiles.push(consumerRulesPath);
}
else {
this.ensureNestedObject(buildOption, ['arkOptions', 'obfuscation']).consumerFiles = consumerRulesPath;
}
}
this.moduleContext.setBuildProfileOpt(buildProfileOpt);
}
return ruleOptions.enable;
}
copyRouterMapToRawFileTask(buildOutputPath, targetName) {
let routerMapFilePath = FileUtil_1.default.pathResolve(buildOutputPath, CommonConstants_1.default.TEMP_ROUTER_MAP_PATH, targetName, CommonConstants_1.default.ROUTER_MAP_NAME);
let rawFilePath = this.config.getRawFilePath();
FileUtil_1.default.ensureFileSync(rawFilePath);
FileUtil_1.default.copyFileSync(routerMapFilePath, rawFilePath);
}
writeHspModuleName() {
if (!this.node.getAllPluginIds().includes(hvigor_ohos_plugin_1.OhosPluginId.OHOS_HAP_PLUGIN))
return;
let rawFilePath = this.config.getRawFilePath();
let rawFileRouterMap = JSON.parse(FileUtil_1.default.readFileSync(rawFilePath).toString());
rawFileRouterMap.hspModuleNames = [...new Set(PluginStore_1.default.getInstance().hspModuleNames)];
rawFileRouterMap.hspModuleNames.push(...this.getRemoteHspModuleNames(this.node, this.node.getAllPluginIds()));
FileUtil_1.default.writeFileSync(rawFilePath, JSON.stringify(rawFileRouterMap));
}
getRemoteHspModuleNames(node, pluginIds) {
let remoteHspModuleNames = [];
try {
pluginIds.forEach((id) => {
let context = node.getContext(id);
let signedHspObj = context.getOhpmRemoteHspDependencyInfo(true);
let remoteHspObj = context.getOhpmRemoteHspDependencyInfo(false);
for (const key in signedHspObj) {
remoteHspModuleNames.push(signedHspObj[key].name);
}
for (const key in remoteHspObj) {
remoteHspModuleNames.push(remoteHspObj[key].name);
}
});
}
catch (error) {
Logger_1.Logger.warn('Your DevEco Studio version less than 5.0.3.800, may cause remote hsp dependencies get failed');
}
return remoteHspModuleNames;
}
taskExec() {
let startTime = Date.now();
Logger_1.Logger.info(this.node.getNodeName() + ': HMRouterPluginTask start');
this.plugin.analyzeAnnotation();
this.updateModuleJsonOpt();
this.updateBuildProfileOpt();
let endTime = Date.now();
Logger_1.Logger.info(this.config.moduleName + ': HMRouterPluginTask end');
Logger_1.Logger.info(this.config.moduleName + ': HMRouterPluginTask cost: ' + (endTime - startTime) + ' ms');
}
updateModuleJsonOpt() {
const moduleJsonOpt = this.moduleContext.getModuleJsonOpt();
if (moduleJsonOpt.module.routerMap) {
let routerMapFileName = moduleJsonOpt.module.routerMap.split(':')[1];
let routerMapFilePath = this.config.getModuleRouterMapFilePath(routerMapFileName);
let routerMapObj = FileUtil_1.default.readJson5(routerMapFilePath);
if (routerMapFileName !== 'hm_router_map') {
this.plugin.routerMap.unshift(...routerMapObj[CommonConstants_1.default.ROUTER_MAP_KEY]);
}
}
this.plugin.generateRouterMap();
moduleJsonOpt.module.routerMap = CommonConstants_1.default.MODULE_ROUTER_MAP_NAME;
this.moduleContext.setModuleJsonOpt(moduleJsonOpt);
}
updateBuildProfileOpt() {
const buildProfileOpt = this.moduleContext.getBuildProfileOpt();
let sources = this.ensureNestedObject(buildProfileOpt, ['buildOption', 'arkOptions', 'runtimeOnly', 'sources']);
if (!Array.isArray(sources)) {
buildProfileOpt.buildOption.arkOptions.runtimeOnly.sources = [];
}
this.pushRouterInfo(buildProfileOpt, this.plugin.routerMap);
this.moduleContext.setBuildProfileOpt(buildProfileOpt);
}
pushRouterInfo(buildProfileOpt, routerMap) {
const sources = buildProfileOpt.buildOption.arkOptions.runtimeOnly.sources;
routerMap.forEach((item) => {
const name = item.name;
if (name.includes(CommonConstants_1.default.LIFECYCLE_PREFIX) ||
name.includes(CommonConstants_1.default.INTERCEPTOR_PREFIX) ||
name.includes(CommonConstants_1.default.ANIMATOR_PREFIX) ||
name.includes(CommonConstants_1.default.SERVICE_PREFIX)) {
sources.push(CommonConstants_1.default.CURRENT_DELIMITER + item.pageSourceFile);
}
});
}
readConfig() {
let configParam;
let configFilePath;
let configDir;
configFilePath = FileUtil_1.default.pathResolve(this.node.getNodePath(), CommonConstants_1.default.CONFIG_FILE_NAME);
if (!FileUtil_1.default.exist(configFilePath)) {
configFilePath =
FileUtil_1.default.pathResolve(PluginStore_1.default.getInstance().projectFilePath, CommonConstants_1.default.CONFIG_FILE_NAME);
}
if (FileUtil_1.default.exist(configFilePath)) {
configParam = FileUtil_1.default.readJson5(configFilePath);
}
else {
configParam = {};
}
configDir = FileUtil_1.default.pathResolve(configFilePath, CommonConstants_1.default.PARENT_DELIMITER);
return new HMRouterPluginConfig_1.HMRouterPluginConfig(this.node.getNodeName(), this.node.getNodePath(), configDir, configParam);
}
ensureNestedObject(obj, path) {
return path.reduce((acc, key) => {
if (!acc[key]) {
acc[key] = {};
}
return acc[key];
}, obj);
}
}
exports.HMRouterPluginHandle = HMRouterPluginHandle;