// @ts-nocheck import { parse, types as t, transformFromAstSync, traverse } from '@babel/core' // ver.js 中定义模块的数组 const TARGET_IDENTIFIER_NAME = 'project_apiArr' const MODULE_IDENTIFIER_NAME = 'module' interface PackageInfo { name: string version: string grayscale?: boolean } function changeDeployVersion(code: string, pkg: PackageInfo): string { const { name, version, grayscale } = pkg let ast try { ast = parse(code, { filename: 'ver.js' }) } catch (error: any) { throw new Error(`代码解析错误: ${error.message}`, { cause: error }) } const keyName = grayscale ? 'grayscale' : 'main' function findTargetDeclarator(ast: any): any | undefined { let res: any | undefined traverse(ast, { VariableDeclarator(path) { if ( t.isIdentifier(path.node.id, { name: TARGET_IDENTIFIER_NAME }) && t.isArrayExpression(path.node.init) ) { res = path } }, }) return res } function findModuleObject(path: any): any | undefined { let res: any | undefined path.traverse({ ObjectExpression(path) { if ( path.node.properties.some( (node) => t.isObjectProperty(node) && t.isIdentifier(node.key, { name: MODULE_IDENTIFIER_NAME }) && t.isLiteral(node.value, { value: name }) ) ) { res = path } }, }) return res } function modifyModuleVersion(path: any): void { let hasModify = false path.traverse({ Property(path) { if (t.isObjectProperty(path.node) && t.isIdentifier(path.node.key, { name: keyName })) { if (t.isStringLiteral(path.node.value)) { path.node.value.value = version } hasModify = true } }, }) if (!hasModify) { path.node.properties.push(t.objectProperty(t.identifier(keyName), t.stringLiteral(version))) } } function addModuleToTarget(path: any): void { if (t.isArrayExpression(path.node.init)) { const elements = path.node.init.elements elements.splice( elements.length - 2, 0, t.objectExpression([ t.objectProperty(t.identifier(MODULE_IDENTIFIER_NAME), t.stringLiteral(name)), t.objectProperty(t.identifier(keyName), t.stringLiteral(version)), ]) ) } } const targetPath = findTargetDeclarator(ast) if (!targetPath) throw new Error(`ver.js 不合规范,未找到参数 ${TARGET_IDENTIFIER_NAME}`) const moduleObjPath = findModuleObject(targetPath) if (moduleObjPath) { modifyModuleVersion(moduleObjPath) } else { addModuleToTarget(targetPath) } const result = transformFromAstSync(ast, undefined, { filename: 'ver.js', minified: true, comments: false, }) if (!result || !result.code) { throw new Error('代码转换失败') } return result.code } export default changeDeployVersion