diff --git a/compiler/main.js b/compiler/main.js index 22ad1ae7daf847b2ba6ff39a11044cfd117b2dea..c0d7eafb355f953cb17e43c053cbfb729b70614b 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -31,9 +31,7 @@ const { FAIL, TEST_RUNNER_DIR_SET, TS2ABC, - WORKERS_DIR, - ARKTS_1_2, - EXTNAME_TS + WORKERS_DIR } = require('./lib/pre_define'); const { @@ -41,18 +39,20 @@ const { } = require('./lib/gen_aot'); const { - LogDataFactory -} = require('./lib/fast_build/ark_compiler/logger'); + configure, + getLogger +} = require('log4js'); const { - ErrorCode, - ArkTSInternalErrorDescription -} = require('./lib/fast_build/ark_compiler/error_code'); + entryFileLanguageInfo, + isMixCompile, + processAbilityPagesFullPath, + transformAbilityPages +} = require('./lib/fast_build/ark_compiler/interop/interop_manager'); const { - configure, - getLogger -} = require('log4js'); + ARKTS_1_2 +} = require('./lib/fast_build/ark_compiler/interop/pre_define'); configure({ appenders: { 'ETS': {type: 'stderr', layout: {type: 'messagePassThrough'}}}, @@ -83,7 +83,6 @@ let sdkConfigPrefix = 'ohos|system|kit|arkts'; let ohosSystemModulePaths = []; let ohosSystemModuleSubDirPaths = []; let allModulesPaths = []; -let entryFileLanguageInfo = new Map(); function initProjectConfig(projectConfig) { initProjectPathConfig(projectConfig); @@ -144,8 +143,6 @@ function initProjectPathConfig(projectConfig) { projectConfig.aceSoPath = projectConfig.aceSoPath || process.env.aceSoPath; projectConfig.localPropertiesPath = projectConfig.localPropertiesPath || process.env.localPropertiesPath; projectConfig.projectProfilePath = projectConfig.projectProfilePath || process.env.projectProfilePath; - // In hybrid compilation, if the entry file is a static file, the path should be convert into under bridgeCodepath one - projectConfig.entryBridgeCodePath = projectConfig.entryBridgeCodePath || process.env.entryBridgeCodePath; } function loadMemoryTrackingConfig(projectConfig) { @@ -163,7 +160,6 @@ function loadEntryObj(projectConfig) { initProjectConfig(projectConfig); loadMemoryTrackingConfig(projectConfig); loadBuildJson(); - initMixCompileHar(projectConfig); if (process.env.aceManifestPath && aceCompileMode === 'page') { setEntryFile(projectConfig); setFaTestRunnerFile(projectConfig); @@ -174,9 +170,6 @@ function loadEntryObj(projectConfig) { setStageTestRunnerFile(projectConfig); loadNavigationConfig(aceBuildJson); } - if (projectConfig.mixCompile && projectConfig.isRemoteModule) { - return; - } if (staticPreviewPage) { projectConfig.entryObj['./' + staticPreviewPage] = projectConfig.projectPath + path.sep + staticPreviewPage + '.ets?entry'; @@ -219,6 +212,9 @@ function loadEntryObj(projectConfig) { } } } + if (isMixCompile()) { + processAbilityPagesFullPath(abilityPagesFullPath); + } } function loadNavigationConfig(aceBuildJson) { @@ -281,23 +277,7 @@ function buildManifest(manifest, aceConfigPath) { } function getPackageJsonEntryPath() { - /** - * adapt to oh_modules compile - * origin local module => project/library/src/main/ets - * oh_module => project/library/src/main - * bcs some oh_module don't contain ets dir - */ - - const candidatePaths = [ - path.resolve(projectConfig.projectPath, '../../../', projectConfig.packageJson), - path.resolve(projectConfig.projectPath, '../../', projectConfig.packageJson), - ]; - - const rootPackageJsonPath = - candidatePaths.find(fs.existsSync) ?? - (() => { - throw new Error('package.json not found in ../../../ or ../../'); - })(); + const rootPackageJsonPath = path.resolve(projectConfig.projectPath, '../../../' + projectConfig.packageJson); if (fs.existsSync(rootPackageJsonPath)) { let rootPackageJsonContent; try { @@ -426,9 +406,6 @@ function setIntentEntryPages(projectConfig) { } function setAbilityPages(projectConfig) { - if (projectConfig.isRemoteModule) { - return; - } let abilityPages = []; if (projectConfig.aceModuleJsonPath && fs.existsSync(projectConfig.aceModuleJsonPath)) { const moduleJson = JSON.parse(fs.readFileSync(projectConfig.aceModuleJsonPath).toString()); @@ -500,35 +477,21 @@ function setBundleModuleInfo(projectConfig, moduleJson) { } } -/** - * This file collects root files [entry, ability] for Rollup to bundle. - * - * The ability paths are configured in `aceModuleJson`. - * - In version 1.1, the value is a relative path. - * - In version 1.2, the value is an OHM URL (specific to 1.2). - * - * We need to read these values and populate them into `entryObj`. - * - `entryObj` is an object where: - * - The key should be converted to the relative path format used in version 1.1. - * - The value should be the corresponding absolute file path. - * - For version 1.2 entries, the value should be converted to the corresponding glue code path. - */ - function setAbilityFile(projectConfig, abilityPages) { abilityPages.forEach(abilityPath => { - const isStatic = entryFileLanguageInfo.get(abilityPath) ?? false; - const projectAbilityPath = isStatic ? path.join(projectConfig.entryBridgeCodePath, abilityPath + EXTNAME_TS) : - path.resolve(projectConfig.projectPath, '../', abilityPath); - if (path.isAbsolute(abilityPath) && !isStatic) { + const projectAbilityPath = path.resolve(projectConfig.projectPath, '../', abilityPath); + if (path.isAbsolute(abilityPath)) { abilityPath = '.' + abilityPath.slice(projectConfig.projectPath.length); } - const entryPageKey = isStatic ? transformModuleNameToRelativePath(abilityPath) : - abilityPath.replace(/^\.\/ets\//, './').replace(/\.ts$/, '').replace(/\.ets$/, ''); + const entryPageKey = abilityPath.replace(/^\.\/ets\//, './').replace(/\.ts$/, '').replace(/\.ets$/, ''); if (fs.existsSync(projectAbilityPath)) { abilityConfig.projectAbilityPath.push(projectAbilityPath); projectConfig.entryObj[entryPageKey] = projectAbilityPath + '?entry'; setEntryArrayForObf(entryPageKey); } else { + if (isMixCompile() && transformAbilityPages(abilityPath)) { + return; + } throw Error( `\u001b[31m ERROR: srcEntry file '${projectAbilityPath.replace(/\\/g, '/')}' does not exist. \u001b[39m` ).message; @@ -545,13 +508,11 @@ function readAbilityEntrance(moduleJson) { if (moduleSrcEntry) { abilityPages.push(moduleSrcEntry); - // abilityPagesFullPath is only for v1.1 - v1.2 files won't be included here - !isStatic && abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntry)); + abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntry)); entryFileLanguageInfo.set(moduleSrcEntry, isStatic); } else if (moduleSrcEntrance) { abilityPages.push(moduleSrcEntrance); - // abilityPagesFullPath is only for v1.1 - v1.2 files won't be included here - !isStatic && abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntrance)); + abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntrance)); entryFileLanguageInfo.set(moduleSrcEntrance, isStatic); } if (moduleJson.module.abilities && moduleJson.module.abilities.length > 0) { @@ -570,15 +531,13 @@ function setEntrance(abilityConfig, abilityPages) { abilityConfig.forEach(ability => { const isStatic = ability.codeLanguage === ARKTS_1_2; if (ability.srcEntry) { - ability.srcEntry = ability.srcEntry.replace(/:[^/]+$/, ''); abilityPages.push(ability.srcEntry); entryFileLanguageInfo.set(ability.srcEntry, isStatic); - !isStatic && abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, ability.srcEntry)); + abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, ability.srcEntry)); } else if (ability.srcEntrance) { - ability.srcEntrance = ability.srcEntrance.replace(/:[^/]+$/, ''); abilityPages.push(ability.srcEntrance); entryFileLanguageInfo.set(ability.srcEntrance, isStatic); - !isStatic && abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, ability.srcEntrance)); + abilityPagesFullPath.add(getAbilityFullPath(projectConfig.projectPath, ability.srcEntrance)); } }); } @@ -1209,47 +1168,6 @@ function initMain() { abilityConfig.abilityType = process.env.abilityType || 'page'; } -/** - * due to some oh_modules is different with the original arkTs module. - * Some branches were not reached, causing some information to be uninitialized. - */ -function initMixCompileHar(projectConfig) { - projectConfig.isRemoteModule = process.env.isRemoteModule === 'true'; - projectConfig.mixCompile = process.env.mixCompile === 'true'; - if (projectConfig.isRemoteModule && projectConfig.mixCompile) { - projectConfig.compileHar = true; - process.env.compileMode = 'moduleJson'; - getPackageJsonEntryPath(); - /** - * ets-loader will generate decl file from projectConfig.intentEntry which init in setIntentEntryPages. - * aceModuleJsonPath->ark_modules.json - * when compile oh_module with ets-loader, aceModuleJsonPath will be undefined. - * so projectConfig.intentEntry is empty. - */ - setIntentEntryPages(projectConfig); - } -} - -function transformModuleNameToRelativePath(moduleName) { - let defaultSourceRoot = 'src/main'; - const normalizedModuleName = moduleName.replace(/\\/g, '/'); - const normalizedRoot = defaultSourceRoot.replace(/\\/g, '/'); - - const rootIndex = normalizedModuleName.indexOf(`/${normalizedRoot}/`); - if (rootIndex === -1) { - const errInfo = LogDataFactory.newInstance( - ErrorCode.ETS2BUNDLE_INTERNAL_WRONG_MODULE_NAME_FROM_ACEMODULEJSON, - ArkTSInternalErrorDescription, - `defaultSourceRoot '${defaultSourceRoot}' not found ` + - `when process moduleName '${moduleName}'` - ); - throw Error(errInfo.toString()); - } - - const relativePath = normalizedModuleName.slice(rootIndex + normalizedRoot.length + 1); - return './' + relativePath; -} - exports.globalProgram = globalProgram; exports.projectConfig = projectConfig; exports.loadEntryObj = loadEntryObj; @@ -1278,4 +1196,4 @@ exports.ohosSystemModuleSubDirPaths = ohosSystemModuleSubDirPaths; exports.allModulesPaths = allModulesPaths; exports.resetProjectConfig = resetProjectConfig; exports.resetGlobalProgram = resetGlobalProgram; -exports.setEntryArrayForObf = setEntryArrayForObf; +exports.setEntryArrayForObf = setEntryArrayForObf; \ No newline at end of file diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index cb870e2dadea966cf01826f0f3dfd45d675dc938..749392765ada568b7183c0f9a6524bcfb69da559 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -34,7 +34,6 @@ import { preprocessNewExtend } from './validate_ui_syntax'; import { - ARKTS_1_1, INNER_COMPONENT_MEMBER_DECORATORS, COMPONENT_DECORATORS_PARAMS, COMPONENT_BUILD_FUNCTION, @@ -106,17 +105,18 @@ import { import { ErrorCodeModule } from './hvigor_error_code/const/error_code_module'; import { buildErrorInfoFromDiagnostic } from './hvigor_error_code/utils'; import { - RunnerParms, - generateInteropDecls -} from '../node_modules/declgen/build/src/generateInteropDecls'; + getArkTSEvoDeclFilePath, + redirectToDeclFileForInterop +} from './fast_build/ark_compiler/interop/process_arkts_evolution'; +import { + FileManager, + getApiPathForInterop, + isMixCompile +} from './fast_build/ark_compiler/interop/interop_manager'; import { - arkTSEvolutionModuleMap, - arkTSHybridModuleMap, - getArkTSEvoDeclFilePath -} from './process_arkts_evolution'; -import { processInteropUI } from './process_interop_ui'; -import { FileManager } from './fast_build/ark_compiler/interop/interop_manager'; -import { ARKTS_1_2 } from './pre_define'; + ARKTS_1_1, + ARKTS_1_2 +} from './fast_build/ark_compiler/interop/pre_define'; export interface LanguageServiceCache { service?: ts.LanguageService; @@ -569,7 +569,7 @@ export function serviceChecker(rootFileNames: string[], newLogger: Object = null MemoryMonitor.stopRecordStage(runArkTSLinterRecordInfo); stopTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); - if (process.env.watchMode !== 'true' && !projectConfig.isRemoteModule) { + if (process.env.watchMode !== 'true') { const processBuildHaprrecordInfo = MemoryMonitor.recordStage(MemoryDefine.PROCESS_BUILD_HAP); processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); MemoryMonitor.stopRecordStage(processBuildHaprrecordInfo); @@ -1092,28 +1092,23 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string } else { resolvedModules.push(result.resolvedModule); } - } else if (result.resolvedModule.resolvedFileName && /\.ets$/.test(result.resolvedModule.resolvedFileName) && - !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName) && (arkTSEvolutionModuleMap.size !== 0 || arkTSHybridModuleMap.size !== 0)) { + } else if (isMixCompile() && result.resolvedModule.resolvedFileName && /\.ets$/.test(result.resolvedModule.resolvedFileName) && + !/\.d\.ets$/.test(result.resolvedModule.resolvedFileName)) { // When result has a value and the path parsed is the source code file path of module 1.2, // the parsing result needs to be modified to the glue code path of module 1.2 - let arktsEvoDeclFilePathExist: boolean = false; - const resolvedFileName: string = toUnixPath(result.resolvedModule.resolvedFileName); - const resultDETSPath: string = getArkTSEvoDeclFilePath({ moduleRequest: '', resolvedFileName }); - if (ts.sys.fileExists(resultDETSPath)) { - resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); - arktsEvoDeclFilePathExist = true; - } - if (!arktsEvoDeclFilePathExist) { + const queryResult = redirectToDeclFileForInterop(result.resolvedModule.resolvedFileName); + if (queryResult) { + resolvedModules.push(queryResult); + } else { resolvedModules.push(result.resolvedModule); } } else { resolvedModules.push(result.resolvedModule); } } else if (new RegExp(`^@(${sdkConfigPrefix})\\.`, 'i').test(moduleName.trim())) { - const searchPaths = languageVersion && languageVersion === ARKTS_1_2 - ? Array.from(FileManager.staticSDKDeclPath) - : [...new Set(sdkConfigs.flatMap(config => config.apiPath))]; - const resolveModuleInfo = getRealModulePath(searchPaths, moduleName, ['.d.ts', '.d.ets']); + const apiPaths = sdkConfigs.flatMap(config => config.apiPath); + isMixCompile() && getApiPathForInterop(apiPaths, languageVersion); + const resolveModuleInfo: ResolveModuleInfo = getRealModulePath(apiPaths, moduleName, ['.d.ts', '.d.ets']); const modulePath = resolveModuleInfo.modulePath; const extension = resolveModuleInfo.isEts ? '.d.ets' : '.d.ts'; const fullModuleName = moduleName + extension; @@ -1160,7 +1155,8 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); const DETSModulePath: string = path.resolve(path.dirname(containingFile), /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); - const arktsEvoDeclFilePath: string = getArkTSEvoDeclFilePath({ moduleRequest: moduleName, resolvedFileName: '' }); + const arktsEvoDeclFilePath: string = isMixCompile() ? + getArkTSEvoDeclFilePath({ moduleRequest: moduleName, resolvedFileName: '' }) : ''; if (ts.sys.fileExists(modulePath)) { resolvedModules.push(getResolveModule(modulePath, '.d.ts')); } else if (ts.sys.fileExists(systemDETSModulePath)) { @@ -1175,7 +1171,7 @@ export function resolveModuleNames(moduleNames: string[], containingFile: string resolvedModules.push(getResolveModule(fileModulePath, '.js')); } else if (ts.sys.fileExists(DETSModulePath)) { resolvedModules.push(getResolveModule(DETSModulePath, '.d.ets')); - } else if (ts.sys.fileExists(arktsEvoDeclFilePath)) { + } else if (isMixCompile() && ts.sys.fileExists(arktsEvoDeclFilePath)) { resolvedModules.push(getResolveModule(arktsEvoDeclFilePath, '.d.ets')); } else { const srcIndex: number = projectConfig.projectPath.indexOf('src' + path.sep + 'main'); @@ -1859,38 +1855,3 @@ export function resetEtsCheck(): void { targetESVersionChanged = false; fileToIgnoreDiagnostics = undefined; } - -export function generateDeclarationFileForSTS(rootFileNames: string[]) { - if (!(projectConfig.compileHar || projectConfig.compileShared)) { - return; - } - const unixRootFileNames = rootFileNames.map(path => { - return toUnixPath(path); - }); - - const uniqueFiles = Array.from(new Set([ - ...unixRootFileNames, - /** - * arkui lacks explicit import statements and needs to be manually added to the global rootfile, - * otherwise an error will be reported during the tsc compilation of declgen - */ - ...readDeaclareFiles() - ])); - - const config: RunnerParms = { - inputDirs: [], - inputFiles: uniqueFiles, - outDir: projectConfig.dependentModuleMap.get(projectConfig.entryPackageName).declgenV2OutPath, - // use package name as folder name - rootDir: projectConfig.modulePath, - customResolveModuleNames: resolveModuleNames, - customCompilerOptions: compilerOptions, - includePaths: [projectConfig.modulePath] - }; - if (fs.existsSync(config.outDir)) { - fs.rmSync(config.outDir, { recursive: true, force: true }); - } - fs.mkdirSync(config.outDir, { recursive: true }); - generateInteropDecls(config); - processInteropUI(projectConfig.dependentModuleMap?.get(projectConfig.entryPackageName)?.declgenV2OutPath); -} \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/common/ark_define.ts b/compiler/src/fast_build/ark_compiler/common/ark_define.ts index 8f995e3753dd2fa4a66297e45556a03129c89064..78f167b62de4b6b7724f8f598ff4ee2472fba794 100644 --- a/compiler/src/fast_build/ark_compiler/common/ark_define.ts +++ b/compiler/src/fast_build/ark_compiler/common/ark_define.ts @@ -121,5 +121,3 @@ export const SEPARATOR_BITWISE_AND: string = '&'; export const SEPARATOR_AT: string = '@'; export const SEPARATOR_SLASH: string = '/'; -export const GEN_ABC_CMD: string = "genAbcCmd"; -export const GEN_ABC_CMD_FILE_PATH: string = "genAbcCmd.json"; diff --git a/compiler/src/fast_build/ark_compiler/error_code.ts b/compiler/src/fast_build/ark_compiler/error_code.ts index 6447221fbaefc3924436a2391b0d268c77a364c5..08cc8ebe8ae25528ac4758eb439ec5077173603f 100644 --- a/compiler/src/fast_build/ark_compiler/error_code.ts +++ b/compiler/src/fast_build/ark_compiler/error_code.ts @@ -47,6 +47,7 @@ export enum ErrorCode { ETS2BUNDLE_INTERNAL_EXECUTE_ES2ABC_WITH_ASYNC_HANDLER_FAILED = '10310022', ETS2BUNDLE_INTERNAL_FAILED_TO_FIND_GLUD_CODE = '10310023', ETS2BUNDLE_INTERNAL_WRONG_MODULE_NAME_FROM_ACEMODULEJSON = '10310024', + ETS2BUNDLE_INTERNAL_MISSING_BRIDGECODE_PATH_INFO = '10310025', // EXTERNAL ERRORS ETS2BUNDLE_EXTERNAL_FORBIDDEN_IMPORT_ARKTS_FILE = '10311001', @@ -65,6 +66,8 @@ export enum ErrorCode { ETS2BUNDLE_EXTERNAL_UNION_TYPE_AMBIGUITY = '10311013', ETS2BUNDLE_EXTERNAL_ALIAS_CONFIG_FORMAT_INVALID = '10311014', ETS2BUNDLE_EXTERNAL_GET_LANGUAGE_VERSION_FAILED = '10311015', + ETS2BUNDLE_EXTERNAL_COLLECT_INTEROP_INFO_FAILED = '10311015', + // CONSTANTS FOR ES2ABC ERROR CODE ES2ABC_SYNTAX_ERROR_ERROR_CODE = '10705000', ES2ABC_PATCH_FIX_ERROR_ERROR_CODE = '10706001' diff --git a/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts b/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts index 691ec3101626c954d20159ab20d2e490a1ced065..02817e68e8fa1ad492279107254818332141750b 100644 --- a/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts +++ b/compiler/src/fast_build/ark_compiler/interop/interop_manager.ts @@ -16,13 +16,13 @@ import fs from 'fs'; import path from 'path'; -import { sdkConfigs } from '../../../../main'; +import { + projectConfig, + sdkConfigs +} from '../../../../main'; import { toUnixPath } from '../../../utils'; import { - ARKTS_1_1, ArkTSEvolutionModule, - ARKTS_1_2, - HYBRID, FileInfo, AliasConfig } from './type'; @@ -37,8 +37,17 @@ import { } from '../logger'; import { ArkTSErrorDescription, + ArkTSInternalErrorDescription, ErrorCode } from '../error_code'; +import { EXTNAME_TS } from '../common/ark_define'; +import { + ARKTS_1_1, + ARKTS_1_2, + ARKTS_HYBRID +} from './pre_define'; + +export let entryFileLanguageInfo = new Map(); export class FileManager { private static instance: FileManager | undefined = undefined; @@ -208,6 +217,7 @@ export class FileManager { FileManager.glueCodeFileInfos?.clear(); FileManager.aliasConfig?.clear(); FileManager.mixCompile = false; + entryFileLanguageInfo.clear(); } getLanguageVersionByFilePath(filePath: string): { @@ -255,7 +265,7 @@ export class FileManager { return undefined; } - const isHybrid = matchedModuleInfo.language === HYBRID; + const isHybrid = matchedModuleInfo.language === ARKTS_HYBRID; const pkgName = matchedModuleInfo.packageName; if (!isHybrid) { @@ -442,4 +452,96 @@ export function isBridgeCode(filePath: string, projectConfig: Object): boolean { } } return false; -} \ No newline at end of file +} + +export function isMixCompile(): boolean { + return process.env.mixCompile === 'true'; +} + +/** + * Delete the 1.2 part in abilityPagesFullPath. This array will be used in transform. + * The 1.2 source files will not participate in the 1.1 compilation process. + */ +export function processAbilityPagesFullPath(abilityPagesFullPath: Set): void { + if (!isMixCompile()) { + return; + } + + const extensions = ['.ts', '.ets']; + + for (const filePath of Array.from(abilityPagesFullPath)) { + let realPath: string | null = null; + + for (const ext of extensions) { + const candidate = filePath.endsWith(ext) ? filePath : filePath + ext; + if (fs.existsSync(candidate)) { + realPath = candidate; + break; + } + } + + if (!realPath) { + continue; + } + + const firstLine = readFirstLineSync(realPath); + if (firstLine.includes('use static')) { + abilityPagesFullPath.delete(filePath); + } + } +} + + +export function transformAbilityPages(abilityPath: string): boolean { + const entryBridgeCodePath = process.env.entryBridgeCodePath; + if (!entryBridgeCodePath) { + const errInfo = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_INTERNAL_MISSING_BRIDGECODE_PATH_INFO, + ArkTSInternalErrorDescription, + `Missing entryBridgeCodePath` + ); + throw Error(errInfo.toString()); + } + if (!entryFileLanguageInfo?.get(abilityPath)) { + return false; + } + if (abilityPath.includes(':')) { + abilityPath = abilityPath.substring(0, abilityPath.lastIndexOf(':')); + } + const bridgeCodePath = path.join(entryBridgeCodePath, abilityPath + EXTNAME_TS); + if (fs.existsSync(bridgeCodePath)) { + projectConfig.entryObj[transformModuleNameToRelativePath(abilityPath)] = bridgeCodePath; + return true; + } + return false; +} + +function transformModuleNameToRelativePath(moduleName): string { + let defaultSourceRoot = 'src/main'; + const normalizedModuleName = moduleName.replace(/\\/g, '/'); + const normalizedRoot = defaultSourceRoot.replace(/\\/g, '/'); + + const rootIndex = normalizedModuleName.indexOf(`/${normalizedRoot}/`); + if (rootIndex === -1) { + const errInfo = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_INTERNAL_WRONG_MODULE_NAME_FROM_ACEMODULEJSON, + ArkTSInternalErrorDescription, + `defaultSourceRoot '${defaultSourceRoot}' not found ` + + `when process moduleName '${moduleName}'` + ); + throw Error(errInfo.toString()); + } + + const relativePath = normalizedModuleName.slice(rootIndex + normalizedRoot.length + 1); + return './' + relativePath; +} + +export function getApiPathForInterop(apiDirs: string[], languageVersion: string): void { + if (languageVersion !== ARKTS_1_2) { + return; + } + + const staticPaths = [...FileManager.staticSDKDeclPath]; + apiDirs.unshift(...staticPaths); +} + diff --git a/compiler/src/fast_build/ark_compiler/interop/pre_define.ts b/compiler/src/fast_build/ark_compiler/interop/pre_define.ts new file mode 100644 index 0000000000000000000000000000000000000000..eaa908d4149f56a25a56bee5b66a7200743d75d5 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/interop/pre_define.ts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const ARKTS_1_2: string = '1.2'; +export const ARKTS_1_1: string = '1.1'; +export const ARKTS_1_0: string = '1.0'; +export const ARKTS_HYBRID: string = 'hybrid'; \ No newline at end of file diff --git a/compiler/src/process_arkts_evolution.ts b/compiler/src/fast_build/ark_compiler/interop/process_arkts_evolution.ts similarity index 95% rename from compiler/src/process_arkts_evolution.ts rename to compiler/src/fast_build/ark_compiler/interop/process_arkts_evolution.ts index 6c6cdc8dae4b8403ba6a8f0d157f70c0d17c6a8d..7cf11fe98c789047b8d91337b4267025298e4a26 100644 --- a/compiler/src/process_arkts_evolution.ts +++ b/compiler/src/fast_build/ark_compiler/interop/process_arkts_evolution.ts @@ -17,36 +17,40 @@ import fs from 'fs'; import path from 'path'; import ts from 'typescript'; +import { getResolveModule } from '../../../ets_checker'; import { - EXTNAME_TS, - EXTNAME_ETS, - EXTNAME_D_ETS, ARKTS_1_0, ARKTS_1_1, ARKTS_1_2, - ARKTS_HYBRID, - SUPER_ARGS + ARKTS_HYBRID } from './pre_define'; import { - toUnixPath, - mkdirsSync, IFileLog, - LogType -} from './utils'; + LogType, + mkdirsSync, + toUnixPath +} from '../../../utils'; +import { getPkgInfo } from '../../../ark_utils'; import { - red, - reset -} from './fast_build/ark_compiler/common/ark_define'; -import { getPkgInfo } from './ark_utils'; -import createAstNodeUtils from './create_ast_node_utils'; + EXTNAME_D_ETS, + EXTNAME_ETS, + EXTNAME_TS, + SUPER_ARGS +} from '../../../pre_define'; import { + CommonLogger, LogData, LogDataFactory -} from './fast_build/ark_compiler/logger'; +} from '../logger'; import { ArkTSErrorDescription, ErrorCode -} from './fast_build/ark_compiler/error_code'; +} from '../error_code'; +import createAstNodeUtils from '../../../create_ast_node_utils'; +import { + red, + reset +} from '../common/ark_define'; interface DeclFileConfig { declPath: string; @@ -157,10 +161,19 @@ export function getArkTSEvoDeclFilePath(resolvedFileInfo: ResolvedFileInfo): str } export function collectArkTSEvolutionModuleInfo(share: Object): void { + if (!share.projectConfig.dependentModuleMap) { + return; + } if (!share.projectConfig.useNormalizedOHMUrl) { - share.throwArkTsCompilerError(red, 'ArkTS:ERROR: Failed to compile mixed project.\n' + - 'Error Message: Failed to compile mixed project because useNormalizedOHMUrl is false.\n' + - 'Solutions: > Check whether useNormalizedOHMUrl is true.', reset); + const errInfo: LogData = LogDataFactory.newInstance( + ErrorCode.ETS2BUNDLE_EXTERNAL_COLLECT_INTEROP_INFO_FAILED, + ArkTSErrorDescription, + 'Failed to compile mixed project.', + `Failed to compile mixed project because useNormalizedOHMUrl is false.`, + ['Please check whether useNormalizedOHMUrl is true.'] + ); + CommonLogger.getInstance(share).printErrorAndExit(errInfo); + } // dependentModuleMap Contents eg. // 1.2 hap -> 1.1 har: It contains the information of 1.1 har @@ -671,3 +684,12 @@ function addSuper(needSuper: boolean, injectStatement: ts.ExpressionStatement[], ); } } + +export function redirectToDeclFileForInterop(resolvedFileName: string): ts.ResolvedModuleFull { + const filePath: string = toUnixPath(resolvedFileName); + const resultDETSPath: string = getArkTSEvoDeclFilePath({ moduleRequest: '', resolvedFileName: filePath }); + if (ts.sys.fileExists(resultDETSPath)) { + return getResolveModule(resultDETSPath, EXTNAME_D_ETS); + } + return undefined; +} \ No newline at end of file diff --git a/compiler/src/fast_build/ark_compiler/interop/type.ts b/compiler/src/fast_build/ark_compiler/interop/type.ts index 17d7165f9b535e0713fc455f1f4c548592efef81..47387278d24297945efcdcf12a481da0d262b949 100644 --- a/compiler/src/fast_build/ark_compiler/interop/type.ts +++ b/compiler/src/fast_build/ark_compiler/interop/type.ts @@ -90,11 +90,6 @@ interface DeclFileConfig { ohmUrl: string; } -export const ARKTS_1_2: string = '1.2'; -export const ARKTS_1_1: string = '1.1'; -export const ARKTS_1_0: string = '1.0'; -export const HYBRID: string = 'hybrid'; - export interface Params { dependentModuleMap: Map; projectConfig: ProjectConfig; diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts index 8b37d97b0dc9edcf9cc51f0b5d2486eb4d6d59f1..b159966457bd6c060037737fa99f3bf1eb7d9653 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_mode.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -53,8 +53,7 @@ import { ES2ABC, ETS, TS, - JS, - GEN_ABC_CMD + JS } from '../common/ark_define'; import { needAotCompiler, @@ -99,8 +98,6 @@ import { FaultHandler } from '../../../gen_aot'; import { - ARKTS_1_2, - ARKTS_HYBRID, NATIVE_MODULE } from '../../../pre_define'; import { @@ -119,15 +116,17 @@ import { LogDataFactory } from '../logger'; import { - addDeclFilesConfig, - arkTSModuleMap, ArkTSEvolutionModule, - getDeclgenBridgeCodePath, + arkTSModuleMap, genCachePathForBridgeCode, + getDeclgenBridgeCodePath, isArkTSEvolutionFile, pkgDeclFilesConfig -} from '../../../process_arkts_evolution'; -import { FileManager } from '../interop/interop_manager'; +} from '../interop/process_arkts_evolution'; +import { + FileManager, + isMixCompile +} from '../interop/interop_manager'; export class ModuleInfo { filePath: string; @@ -179,7 +178,6 @@ export class ModuleMode extends CommonMode { compileContextInfoPath: string; abcPaths: string[] = []; byteCodeHar: boolean; - rollupCache: Object; constructor(rollupObject: Object) { super(rollupObject); @@ -212,7 +210,6 @@ export class ModuleMode extends CommonMode { if (this.useNormalizedOHMUrl) { this.compileContextInfoPath = this.generateCompileContextInfo(rollupObject); } - this.rollupCache = rollupObject.cache; } private generateCompileContextInfo(rollupObject: Object): string { @@ -254,9 +251,10 @@ export class ModuleMode extends CommonMode { ); this.logger.printErrorAndExit(errInfo); } - const isArkTSEvolution: boolean = isArkTSEvolutionFile(moduleId, metaInfo); - const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.pkgName) : metaInfo.pkgPath; + let pkgPath: string = metaInfo.pkgPath; + if (isMixCompile() && isArkTSEvolutionFile(moduleId, metaInfo)) { + pkgPath = path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.pkgName); + } const pkgParams = { pkgName: metaInfo.pkgName, pkgPath, @@ -527,18 +525,16 @@ export class ModuleMode extends CommonMode { if (this.useNormalizedOHMUrl) { packageName = metaInfo.pkgName; - const isArkTSEvolution: boolean = isArkTSEvolutionFile(filePath, metaInfo); - const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(packageName), metaInfo.pkgName) : metaInfo.pkgPath; + let pkgPath: string = metaInfo.pkgPath; + if (isMixCompile() && isArkTSEvolutionFile(filePath, metaInfo)) { + pkgPath = path.join(getDeclgenBridgeCodePath(metaInfo.pkgName), metaInfo.pkgName); + } const pkgParams = { pkgName: packageName, pkgPath, isRecordName: true, }; recordName = getNormalizedOhmUrlByFilepath(filePath, this.projectConfig, this.logger, pkgParams, undefined); - if (!isArkTSEvolution) { - addDeclFilesConfig(originalFilePath, this.projectConfig, this.logger, pkgPath, packageName); - } } else { recordName = getOhmUrlByFilepath(filePath, this.projectConfig, this.logger, moduleName); if (isPackageModules) { @@ -702,13 +698,6 @@ export class ModuleMode extends CommonMode { // collect data error from subprocess let logDataList: Object[] = []; let errMsg: string = ''; - const eventGenDescriptionsForMergedEs2abc = createAndStartEvent(parentEvent, 'generate descriptions for merged es2abc'); - stopEvent(eventGenDescriptionsForMergedEs2abc); - - if (this.projectConfig.invokeEs2abcByHvigor) { - this.rollupCache.set(GEN_ABC_CMD, this.cmdArgs); - return; - } const genAbcCmd: string = this.cmdArgs.join(' '); try { diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts index c1410d9ac515ea663266473358240f0f4171ba94..dd14f7b65b5a56104650477a1955f24be6b2f546 100644 --- a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -52,9 +52,6 @@ import { } from '../common/ob_config_resolver'; import { ORIGIN_EXTENTION } from '../process_mock'; import { - ARKTS_1_2, - ARKTS_HYBRID, - ESMODULE, TRANSFORMED_MOCK_CONFIG, USER_DEFINE_MOCK_CONFIG } from '../../../pre_define'; @@ -82,11 +79,15 @@ import { import { checkIfJsImportingArkts } from '../check_import_module'; import { getDeclgenBridgeCodePath, - writeBridgeCodeFileSyncByNode, - isArkTSEvolutionFile -} from '../../../process_arkts_evolution'; -import { FileManager } from '../interop/interop_manager'; + isArkTSEvolutionFile, + writeBridgeCodeFileSyncByNode +} from '../interop/process_arkts_evolution'; +import { + FileManager, + isMixCompile +} from '../interop/interop_manager'; import { FileInfo } from '../interop/type'; +import { ARKTS_1_2 } from '../interop/pre_define'; const ROLLUP_IMPORT_NODE: string = 'ImportDeclaration'; const ROLLUP_EXPORTNAME_NODE: string = 'ExportNamedDeclaration'; @@ -425,16 +426,16 @@ export class ModuleSourceFile { } private async writeSourceFile(parentEvent: Object): Promise { - if (!this.isArkTSEvolution) { - if (this.isSourceNode && !isJsSourceFile(this.moduleId)) { - await writeFileSyncByNode( this.source, ModuleSourceFile.projectConfig, this.metaInfo, - this.moduleId, parentEvent, ModuleSourceFile.logger); - } else { - await writeFileContentToTempDir(this.moduleId, this.source, ModuleSourceFile.projectConfig, - ModuleSourceFile.logger, parentEvent, this.metaInfo); - } - } else { + if (isMixCompile() && this.isArkTSEvolution) { await writeBridgeCodeFileSyncByNode( this.source, this.moduleId, this.metaInfo); + return; + } + if (this.isSourceNode && !isJsSourceFile(this.moduleId)) { + await writeFileSyncByNode( this.source, ModuleSourceFile.projectConfig, this.metaInfo, + this.moduleId, parentEvent, ModuleSourceFile.logger); + } else { + await writeFileContentToTempDir(this.moduleId, this.source, ModuleSourceFile.projectConfig, + ModuleSourceFile.logger, parentEvent, this.metaInfo); } } @@ -530,9 +531,10 @@ export class ModuleSourceFile { } private static spliceNormalizedOhmurl(moduleInfo: Object, filePath: string, importerFile?: string): string { - const isArkTSEvolution: boolean = isArkTSEvolutionFile(filePath, moduleInfo.meta); - const pkgPath: string = isArkTSEvolution ? - path.join(getDeclgenBridgeCodePath(moduleInfo.meta.pkgName), moduleInfo.meta.pkgName) : moduleInfo.meta.pkgPath; + let pkgPath: string = moduleInfo.meta.pkgPath; + if (isMixCompile() && isArkTSEvolutionFile(filePath, moduleInfo.meta)) { + pkgPath = path.join(getDeclgenBridgeCodePath(moduleInfo.meta.pkgName), moduleInfo.meta.pkgName); + } const pkgParams = { pkgName: moduleInfo.meta.pkgName, pkgPath, diff --git a/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts index 9d21a248547745477be96ff9242ba133a8b9a133..d7b3b7f9108ba4f9b7c13f9d4e7da77113eee75b 100644 --- a/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts +++ b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts @@ -27,8 +27,8 @@ import { cleanUpUtilsObjects, writeDeclarationFiles } from '../../ark_utils'; import { cleanUpKitImportObjects } from '../../process_kit_import'; import { cleanUpFilesList } from './utils'; import { CommonLogger } from './logger'; -import { cleanUpProcessArkTSEvolutionObj } from '../../process_arkts_evolution'; -import { FileManager } from './interop/interop_manager'; +import { FileManager, isMixCompile } from './interop/interop_manager'; +import { cleanUpProcessArkTSEvolutionObj } from './interop/process_arkts_evolution'; export function genAbc() { return { @@ -75,7 +75,7 @@ export function genAbc() { ModuleSourceFile.cleanUpObjects(); cleanSharedModuleSet(); CommonLogger.destroyInstance(); - cleanUpProcessArkTSEvolutionObj(); + isMixCompile() && cleanUpProcessArkTSEvolutionObj(); FileManager.cleanFileManagerObject(); } }; diff --git a/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts b/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts deleted file mode 100644 index 8ec011349789024eebe3cf7c8fe472149a2af769..0000000000000000000000000000000000000000 --- a/compiler/src/fast_build/ark_compiler/run_es2abc_standalone.ts +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import fs from 'fs'; -import path from 'path'; -import childProcess from 'child_process'; -import { - COMPILE_CONTEXT_INFO_JSON, - FILESINFO_TXT, - GEN_ABC_CMD_FILE_PATH, - MODULES_ABC, - MODULES_CACHE, - NPMENTRIES_TXT, - SOURCEMAPS, - SOURCEMAPS_JSON -} from './common/ark_define'; - -/** - * A script is called by hvigor in a mixed compilation scenario which 1.0 module is not main module,np - * such as module1.2-> module1.0-> module1.2 -> module1.0, compile all 1.0 modules - * and has nothing to do with the ace_ets2bundle process. - */ - -/** - * - * @param cachePathList projectConfig.cachePath of the modules to be merged - * @param targetCachePath The merged target cache directory - * @param aceModuleBuild The aceModuleBuild path of the target module is used to write the abc file to the disk - * @returns erro.toString() - */ -export function run(cachePathList: string[], targetCachePath: string, aceModuleBuild: string): void { - if (!cachePathList || cachePathList.length == 0) { - return - } - mergeCacheData(cachePathList, targetCachePath, FILESINFO_TXT); - mergeCacheData(cachePathList, targetCachePath, MODULES_CACHE); - mergeCacheData(cachePathList, targetCachePath, NPMENTRIES_TXT); - mergeCompileContextInfo(cachePathList, targetCachePath); - mergeSourceMap(cachePathList, targetCachePath); - const cmd: string[] = JSON.parse(fs.readFileSync(path.join(cachePathList[0], GEN_ABC_CMD_FILE_PATH), 'utf-8')); - updateCmd(cmd, targetCachePath, aceModuleBuild); - execCmd(cmd); -} - -export function mergeCacheData(cachePathList: string[], targetCachePath: string, fileName: string): void { - const dataSet: Set = new Set(); - cachePathList.forEach(cachePath => { - const inputFilePath: string = path.join(cachePath, fileName); - if (fs.existsSync(inputFilePath)) { - const fileData: string = fs.readFileSync(inputFilePath).toString(); - fileData.split('\n').forEach(data => { - //eat blank line - if (data) { - dataSet.add(data); - } - }); - } - }); - - const outputFilePath: string = path.join(targetCachePath, fileName); - fs.writeFileSync(outputFilePath, Array.from(dataSet).join('\n')); -} - -function execCmd(cmd: string[]): string { - try { - const result = childProcess.execSync(cmd.join(' '), { - windowsHide: true, - encoding: 'utf-8' - }); - return result; - } catch (error) { - return error.toString(); - } -} - -export function updateCmd(cmd: string[], targetCachePath: string, aceModuleBuild: string) { - for (let i = 0; i < cmd.length; i++) { - if (cmd[i].indexOf("filesInfo.txt") != -1) { - const filesInfoPath: string = path.join(targetCachePath, FILESINFO_TXT); - cmd[i] = `"@${filesInfoPath}"`; - continue; - } - if (cmd[i] === ('--output')) { - const moduleAbcPath = path.join(aceModuleBuild, MODULES_ABC); - cmd[++i] = `"${moduleAbcPath}"`; - continue; - } - if (cmd[i] === ('--cache-file')) { - const cacheFilePath = path.join(targetCachePath, MODULES_CACHE); - cmd[++i] = `"@${cacheFilePath}"`; - continue; - } - if (cmd[i] === ('--npm-module-entry-list')) { - const npmEntriesInfoPath = path.join(targetCachePath, NPMENTRIES_TXT); - cmd[++i] = `"@${npmEntriesInfoPath}"`; - continue; - } - if (cmd[i] === (`--compile-context-info`)) { - const compileContextInfoPath = path.join(targetCachePath, COMPILE_CONTEXT_INFO_JSON); - cmd[++i] = `"${compileContextInfoPath}"`; - continue; - } - } -} - -function deepMerge(target: Object, source: Object): Object { - for (const key of Object.keys(source)) { - if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) { - target[key] = deepMerge(target[key] || {}, source[key]); - } else { - target[key] = source[key]; - } - } - return target; -} - -export function mergeCompileContextInfo(cachePathList: string[], targetCachePath: string) { - const mergedData = { - hspPkgNames: [], - compileEntries: [], - updateVersionInfo: {} - }; - - cachePathList.forEach(cachePath => { - const compileContextPath = path.join(cachePath, COMPILE_CONTEXT_INFO_JSON); - - if (fs.existsSync(compileContextPath)) { - const data = JSON.parse(fs.readFileSync(compileContextPath, 'utf-8')); - - mergedData.hspPkgNames = [...mergedData.hspPkgNames, ...data.hspPkgNames]; - mergedData.compileEntries = [...mergedData.compileEntries, ...data.compileEntries]; - - mergedData.updateVersionInfo = deepMerge(mergedData.updateVersionInfo, data.updateVersionInfo); - } - }); - - const targetPath = path.join(targetCachePath, COMPILE_CONTEXT_INFO_JSON); - fs.writeFileSync(targetPath, JSON.stringify(mergedData, null, 2)); -} - -export function mergeSourceMap(cachePathList: string[], targetCachePath: string) { - const mergedMap: Record = {}; - cachePathList.forEach((item) => { - /** - * Prevent sourcemap.json file from not being generated. - * Some bug scenarios only have one file written to disk. - */ - const possiblePaths = [ - path.join(item, SOURCEMAPS), - path.join(item, SOURCEMAPS_JSON), - ]; - - const sourceMapPath = possiblePaths.find(fs.existsSync); - if (!sourceMapPath) { - return; - } - const sourceMap = JSON.parse(fs.readFileSync(sourceMapPath, 'utf-8')); - Object.assign(mergedMap, sourceMap); - }); - - const outputPath = path.join(targetCachePath, SOURCEMAPS); - fs.writeFileSync(outputPath, JSON.stringify(mergedMap, null, 2), 'utf-8'); -} diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts index bd886b3fdfa0c719a7b876c87e8af748cafe176e..f5f6eafe136b4fdb78c59821ddfb6863c7c6195e 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -47,10 +47,11 @@ import { MemoryMonitor } from '../meomry_monitor/rollup-plugin-memory-monitor'; import { MemoryDefine } from '../meomry_monitor/memory_define'; import { LINTER_SUBSYSTEM_CODE } from '../../hvigor_error_code/hvigor_error_info'; import { ErrorCodeModule } from '../../hvigor_error_code/const/error_code_module'; -import { collectArkTSEvolutionModuleInfo } from '../../process_arkts_evolution'; +import { collectArkTSEvolutionModuleInfo } from '../ark_compiler/interop/process_arkts_evolution'; import { initFileManagerInRollup, - isBridgeCode + isBridgeCode, + isMixCompile } from '../ark_compiler/interop/interop_manager'; export let tsWatchEmitter: EventEmitter | undefined = undefined; @@ -62,7 +63,7 @@ export function etsChecker() { name: 'etsChecker', buildStart() { const recordInfo = MemoryMonitor.recordStage(MemoryDefine.ROLLUP_PLUGIN_BUILD_START); - if (this.share.projectConfig.dependentModuleMap) { + if (isMixCompile()) { collectArkTSEvolutionModuleInfo(this.share); } initFileManagerInRollup(this.share); diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts index 16c5d5531b238e3ed8fd7811853ba92bd41d936b..efd2272a1671a12f2215716b9023f02d3ffee918 100644 --- a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts @@ -112,7 +112,7 @@ import { ProjectCollections } from 'arkguard'; import { interopTransformLog, interopTransform -} from '../../process_arkts_evolution'; +} from '../ark_compiler/interop/process_arkts_evolution'; const filter: any = createFilter(/(? Check whether useNormalizedOHMUrl is true.'; - expect(throwArkTsCompilerErrorStub.getCall(0).args[1] === errMsg).to.be.true; + expect(throwArkTsCompilerErrorStub.getCall(0).args[0].code === ErrorCode.ETS2BUNDLE_EXTERNAL_COLLECT_INTEROP_INFO_FAILED).to.be.true; throwArkTsCompilerErrorStub.restore(); }); diff --git a/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts b/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts index f731c20ebc193829fdfcfd9dd38b8b9ff4ec91bc..edef58a15730bc0b88942ac78f9abdf91aaaba54 100644 --- a/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts +++ b/compiler/test/ark_compiler_ut/interop/interop_manager.test.ts @@ -22,7 +22,7 @@ import { collectSDKInfo, isBridgeCode } from '../../../lib/fast_build/ark_compiler/interop/interop_manager'; -import { ARKTS_1_1, ARKTS_1_2, HYBRID } from '../../../lib/fast_build/ark_compiler/interop/type'; +import { ARKTS_1_1, ARKTS_1_2, ARKTS_HYBRID } from '../../../lib/fast_build/ark_compiler/interop/pre_define'; import { sdkConfigs } from '../../../main'; import { toUnixPath } from '../../../lib/utils'; @@ -108,7 +108,7 @@ mocha.describe('test interop_manager file api', function () { }); dependentModuleMap.set('hybrid', { - language: HYBRID, + language: ARKTS_HYBRID, packageName: 'hybrid', moduleName: 'hybrid', modulePath: '/MyApplication16/hybrid', diff --git a/compiler/test/ark_compiler_ut/module/module_mode.test.ts b/compiler/test/ark_compiler_ut/module/module_mode.test.ts index 3239995d81763fcecb976ee491e2cae97ebf8bc6..e5681f19200d18a6420e3aa17e12ed1009949027 100644 --- a/compiler/test/ark_compiler_ut/module/module_mode.test.ts +++ b/compiler/test/ark_compiler_ut/module/module_mode.test.ts @@ -102,7 +102,7 @@ import { LogData, LogDataFactory } from '../../../lib/fast_build/ark_compiler/logger'; -import { arkTSEvolutionModuleMap } from '../../../lib/process_arkts_evolution'; +import { arkTSEvolutionModuleMap } from '../../../lib/fast_build/ark_compiler/interop/process_arkts_evolution'; function checkGenerateEs2AbcCmdExpect(cmdArgs: Array, compatibleSdkVersion: string, byteCodeHar: boolean): void { const fileThreads: number = cpus(); @@ -829,7 +829,7 @@ mocha.describe('test module_mode file api', function () { 'language': '1.2' } }; - + process.env.mixCompile = 'true'; this.rollup.moduleInfos.push(moduleInfoMock); const sourceMapGenerator: SourceMapGenerator = SourceMapGenerator.initInstance(this.rollup); sourceMapGenerator.setNewSoureMaps(false); @@ -841,6 +841,7 @@ mocha.describe('test module_mode file api', function () { this.rollup.share.projectConfig.useNormalizedOHMUrl = false; this.rollup.share.allFiles.delete(arkTSEvoFile); SourceMapGenerator.cleanSourceMapObject(); + process.env.mixCompile = 'false'; }); mocha.it('3-1-1: test updateCachedSourceMaps under build debug: cacheSourceMapPath not exist', function () { diff --git a/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts b/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts deleted file mode 100644 index 108aba9481f7943e2fa8af60c1fe08b88006c939..0000000000000000000000000000000000000000 --- a/compiler/test/ark_compiler_ut/run_es2abc_standalone.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use rollupObject file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import mocha from 'mocha'; -import path from 'path'; -import fs from 'fs'; -import { - expect -} from 'chai'; -import { - COMPILE_CONTEXT_INFO_JSON, - FILESINFO_TXT, - MODULES_CACHE, - NPMENTRIES_TXT, - RELEASE, - SOURCEMAPS, -} from '../../lib/fast_build/ark_compiler/common/ark_define'; -import { - mergeCacheData, - mergeCompileContextInfo, - mergeSourceMap, -} from '../../lib/fast_build/ark_compiler/run_es2abc_standalone'; -import RollUpPluginMock from './mock/rollup_mock/rollup_plugin_mock'; - -let MERGE_CACHE_PATH; -let targetCachePath; - -mocha.describe('test run_es2abc_standalone file api', function () { - mocha.before(function () { - this.rollup = new RollUpPluginMock(); - this.rollup.build(); - MERGE_CACHE_PATH=path.join(this.rollup.share.projectConfig.projectRootPath, '/mergeCacheData') - targetCachePath=path.join(MERGE_CACHE_PATH,'/targetCacheDir') - if (!fs.existsSync(targetCachePath)) { - fs.mkdirSync(targetCachePath, { recursive: true }); - } - }); - - mocha.after(function () { - if (fs.existsSync(targetCachePath)) { - fs.rmSync(targetCachePath, { recursive: true, force: true }); - } - }) - - mocha.it('1-1: test mergeCacheData', function () { - - const cachePathList = [ - path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), - path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), - ]; - const fileNameList = [ - FILESINFO_TXT, - NPMENTRIES_TXT - ] - fileNameList.forEach(fileName => { - mergeCacheData(cachePathList, targetCachePath, fileName); - }) - - fileNameList.forEach(fileName => { - - const targetFilePath = path.resolve(targetCachePath, fileName); - const targetLineCount = countLines(targetFilePath); - - let sumOriginLineCount = 0; - cachePathList.forEach(cacheDir => { - const originFilePath = path.resolve(cacheDir, fileName); - if (fs.existsSync(originFilePath)) { - sumOriginLineCount += countLines(originFilePath); - } - }); - expect(targetLineCount).to.equal(sumOriginLineCount); - }); - }); - - mocha.it('1-2: test mergeSourceMap', function () { - const cachePathList = [ - path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), - path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), - ]; - - mergeSourceMap(cachePathList, targetCachePath) - - const mergedSourceMap = JSON.parse(fs.readFileSync(path.resolve(targetCachePath, SOURCEMAPS), 'utf-8')); - const expectSourceMap = JSON.parse(fs.readFileSync(path.join(MERGE_CACHE_PATH, './expect', SOURCEMAPS), 'utf-8')); - - expect(mergedSourceMap).to.deep.equal(expectSourceMap); - }); - - mocha.it('1-3: test mergeCompileContextInfo', function () { - const cachePathList = [ - path.resolve(MERGE_CACHE_PATH, './originCacheDir1'), - path.resolve(MERGE_CACHE_PATH, './originCacheDir2'), - ]; - - mergeCompileContextInfo(cachePathList, targetCachePath); - - const mergedCompileContext = JSON.parse( - fs.readFileSync(path.resolve(targetCachePath, COMPILE_CONTEXT_INFO_JSON), 'utf-8') - ); - - const expectCompileContext = JSON.parse( - fs.readFileSync(path.join(MERGE_CACHE_PATH, './expect',COMPILE_CONTEXT_INFO_JSON), 'utf-8') - ); - - expect(mergedCompileContext).to.deep.equal(expectCompileContext); - }); -}); - -function countLines(filePath) { - const content = fs.readFileSync(filePath, 'utf-8'); - return content.split(/\r?\n/).filter(line => line !== '').length; -} \ No newline at end of file