From 233560c7d45417fcfaf73aa281e117fd4d723557 Mon Sep 17 00:00:00 2001 From: houhaoyu Date: Wed, 17 Aug 2022 15:57:27 +0800 Subject: [PATCH 01/36] fixed 444b9fa from https://gitee.com/houhaoyu/developtools_ace-ets2bundle/pulls/944 houhaoyu@huawei.com extract common module in api9 fa Signed-off-by: houhaoyu Change-Id: I9d0af30d80bbd89eb3ad0e43895fa11f159def60 --- compiler/src/compile_info.ts | 2 +- compiler/webpack.config.js | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index b46aef6..e912ea9 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -183,7 +183,7 @@ export class ResultStates { return undefined; }\n` + `if (globalThis["__common_module_cache__${projectConfig.hashProjectPath}"]` + - ` && moduleId.indexOf("?name=") < 0 && isCommonModue(moduleId)) {\n` + + ` && String(moduleId).indexOf("?name=") < 0 && isCommonModue(moduleId)) {\n` + ` globalThis["__common_module_cache__${projectConfig.hashProjectPath}"]` + `[moduleId] = module;\n}`); }); diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 793cb95..4fc6383 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -202,7 +202,12 @@ function setProjectConfig(envArgs) { function setReleaseConfig(config) { const TerserPlugin = require('terser-webpack-plugin'); config.mode = 'production'; - config.optimization = { + if (process.env.compileMode !== 'moduleJson' && abilityConfig.abilityType === 'page') { + config.optimization = config.optimization; + } else { + config.optimization = {}; + } + Object.assign(config.optimization, { emitOnErrors: true, usedExports: false, minimize: true, @@ -219,7 +224,7 @@ function setReleaseConfig(config) { } } })] - }; + }); config.output.sourceMapFilename = '_releaseMap/[name].js.map'; } -- Gitee From e6ad549e6e550de0c42f233a0f3c60cb5fb13ab2 Mon Sep 17 00:00:00 2001 From: bojiang Date: Thu, 18 Aug 2022 10:55:16 +0800 Subject: [PATCH 02/36] fixed b239abe from https://gitee.com/BoJiang4702/developtools_ace-ets2bundle/pulls/954 jiangbo91@huawei.com error fix Signed-off-by: bojiang Change-Id: I5ca03132e2dbe3420a7c48e8e08cd2ad3e2bf556 --- compiler/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/main.js b/compiler/main.js index f49eae5..d17eeda 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -123,7 +123,7 @@ function buildManifest(manifest, aceConfigPath) { manifest.pages = getPages(moduleConfigJson); } else { throw Error('\u001b[31m'+ - 'EERROR: the config.json file miss key word module || module[abilities].' + + 'ERROR: the config.json file miss key word module || module[abilities].' + '\u001b[39m').message; } } catch (e) { -- Gitee From ff2946fcf7db94329daaacdbfb8d2283b44dd8fb Mon Sep 17 00:00:00 2001 From: bojiang Date: Thu, 18 Aug 2022 17:17:30 +0800 Subject: [PATCH 03/36] fixed 1817f00 from https://gitee.com/BoJiang4702/developtools_ace-ets2bundle/pulls/959 jiangbo91@huawei.com add parameter Signed-off-by: bojiang Change-Id: I671ce9e6b93491204da18b53924402fd38b16ed3 --- compiler/webpack.config.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 793cb95..34e9299 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -105,7 +105,8 @@ function initConfig(config) { plugins: [ '@babel/plugin-transform-modules-commonjs', '@babel/plugin-proposal-class-properties' - ] + ], + compact:false }, }, { loader: path.resolve(__dirname, 'lib/process_js_file.js')}, -- Gitee From 3c2089f5c95864c09bb38312014c54e471e616a5 Mon Sep 17 00:00:00 2001 From: Bo Jiang Date: Thu, 18 Aug 2022 09:39:58 +0000 Subject: [PATCH 04/36] update compiler/webpack.config.js. Signed-off-by: Bo Jiang --- compiler/webpack.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 34e9299..de4ddcf 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -106,7 +106,7 @@ function initConfig(config) { '@babel/plugin-transform-modules-commonjs', '@babel/plugin-proposal-class-properties' ], - compact:false + compact: false }, }, { loader: path.resolve(__dirname, 'lib/process_js_file.js')}, -- Gitee From fd36128681fcfa0ccf003581433047021259b1fd Mon Sep 17 00:00:00 2001 From: laibo102 Date: Thu, 18 Aug 2022 15:40:03 +0800 Subject: [PATCH 05/36] Bugfix: fixed init localStorageLink variable Signed-off-by: laibo102 Change-Id: I828b3dd1b3a64d0d69895989e9437f39fc10281b (cherry picked from commit a88d42c90a286a5dbdb36d26cb4dd86541d3a2a8) Signed-off-by: laibo102 --- compiler/src/process_component_class.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/compiler/src/process_component_class.ts b/compiler/src/process_component_class.ts index a0efe19..69b327f 100644 --- a/compiler/src/process_component_class.ts +++ b/compiler/src/process_component_class.ts @@ -294,9 +294,8 @@ function createLocalStroageCallExpression(node: ts.PropertyDeclaration, name: st ts.factory.createStringLiteral(localStorageLink && !localStorageProp ? Array.from(localStorageLink)[0] : !localStorageLink && localStorageProp ? Array.from(localStorageProp)[0] : COMPONENT_CONSTRUCTOR_UNDEFINED), - ts.factory.createNumericLiteral(node.initializer ? node.initializer.getText() : - COMPONENT_CONSTRUCTOR_UNDEFINED), ts.factory.createThis(), - ts.factory.createStringLiteral(name || COMPONENT_CONSTRUCTOR_UNDEFINED) + node.initializer ? node.initializer : ts.factory.createNumericLiteral(COMPONENT_CONSTRUCTOR_UNDEFINED), + ts.factory.createThis(), ts.factory.createStringLiteral(name || COMPONENT_CONSTRUCTOR_UNDEFINED) ] ); } -- Gitee From 3630bbef13786e927760d0655f94d0df3036d1f8 Mon Sep 17 00:00:00 2001 From: zhangbingce Date: Thu, 18 Aug 2022 21:24:06 +0800 Subject: [PATCH 06/36] fixed ac8dec3 from https://gitee.com/zhangbingce/developtools_ace-ets2bundle/pulls/969 bugfix of compile error in esmodule mode Signed-off-by: zhangbingce Change-Id: If03fae04a36eabdc8cefb341b051d598d3b4bdac --- compiler/src/validate_ui_syntax.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/src/validate_ui_syntax.ts b/compiler/src/validate_ui_syntax.ts index 6229fc5..9701ce4 100644 --- a/compiler/src/validate_ui_syntax.ts +++ b/compiler/src/validate_ui_syntax.ts @@ -1042,6 +1042,9 @@ export function processSystemApi(content: string, isProcessAllowList: boolean = } function collectSourcemapNames(sourcePath: string, changedName: string, originalName: string): void { + if (sourcePath == null) { + return; + } const cleanSourcePath: string = sourcePath.replace('.ets', '.js').replace('.ts', '.js'); if (!sourcemapNamesCollection.has(cleanSourcePath)) { return; -- Gitee From 9fb728415ee667d93d88fb702cafa6ecbbbc94a9 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Wed, 17 Aug 2022 10:31:05 +0800 Subject: [PATCH 07/36] fix mov filtermodule js file Signed-off-by: zhangrengao Change-Id: Ifb726aad0086043b16cc944f451649fe343d6d1b --- compiler/src/gen_abc_plugin.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index d6016aa..b0af0f9 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -687,7 +687,7 @@ function filterIntermediateModuleByHashJson(buildPath: string, moduleInfos: Arra updateJsonObject[input] = hashInputContentData; updateJsonObject[abcPath] = hashAbcContentData; mkdirsSync(path.dirname(moduleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(filterModuleInfos[i].tempFilePath)) { + if (projectConfig.buildArkMode === 'debug' && fs.existsSync(moduleInfos[i].tempFilePath)) { fs.copyFileSync(moduleInfos[i].tempFilePath, moduleInfos[i].buildFilePath); } fs.copyFileSync(genAbcFileName(moduleInfos[i].tempFilePath), genAbcFileName(moduleInfos[i].buildFilePath)); @@ -724,8 +724,8 @@ function writeModuleHashJson(): void { fs.copyFileSync(filterModuleInfos[i].tempFilePath, filterModuleInfos[i].buildFilePath); } fs.copyFileSync(genAbcFileName(filterModuleInfos[i].tempFilePath), genAbcFileName(filterModuleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(genSourceMapFileName(moduleInfos[i].tempFilePath))) { - fs.copyFileSync(genSourceMapFileName(moduleInfos[i].tempFilePath), genSourceMapFileName(moduleInfos[i].buildFilePath)); + if (projectConfig.buildArkMode === 'debug' && fs.existsSync(genSourceMapFileName(filterModuleInfos[i].tempFilePath))) { + fs.copyFileSync(genSourceMapFileName(filterModuleInfos[i].tempFilePath), genSourceMapFileName(filterModuleInfos[i].buildFilePath)); } } const hashFilePath: string = genHashJsonPath(buildPathInfo); -- Gitee From 204fc0c6d2a539587d1c3d8e9c4d3b97a56f15f7 Mon Sep 17 00:00:00 2001 From: houhaoyu Date: Sun, 14 Aug 2022 19:24:09 +0800 Subject: [PATCH 08/36] houhaoyu@huawei.com generate new id in builder function Signed-off-by: houhaoyu Change-Id: I1a4804df53ef24bdc2728ca23315435a5f6547ab --- compiler/src/pre_define.ts | 5 ++- compiler/src/process_component_build.ts | 2 +- compiler/src/process_component_class.ts | 12 ++++-- compiler/src/process_component_member.ts | 26 +++++++----- compiler/src/process_custom_component.ts | 6 ++- compiler/src/process_ui_syntax.ts | 50 ++++++++++++++++++++++-- 6 files changed, 81 insertions(+), 20 deletions(-) diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index 54ce5cc..a1698ab 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -265,4 +265,7 @@ export const SUCCESS: number = 0; export const FAIL: number = 1; export const TS2ABC: string = 'ts2abc'; -export const ES2ABC: string = 'es2abc'; \ No newline at end of file +export const ES2ABC: string = 'es2abc'; + +export const GENERATE_ID = 'generateId'; +export const _GENERATE_ID = '__generate__Id'; diff --git a/compiler/src/process_component_build.ts b/compiler/src/process_component_build.ts index 0c4f37e..8772ed8 100644 --- a/compiler/src/process_component_build.ts +++ b/compiler/src/process_component_build.ts @@ -249,7 +249,7 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme processForEachComponent(item, newStatements, log, isInnerBuilder); break; case ComponentType.customBuilderMethod: - if (INNER_CUSTOM_BUILDER_METHOD.has(name)) { + if (CUSTOM_BUILDER_METHOD.has(name)) { newStatements.push(addInnerBuilderParameter(item)); } else { newStatements.push(item); diff --git a/compiler/src/process_component_class.ts b/compiler/src/process_component_class.ts index 69b327f..6cf0021 100644 --- a/compiler/src/process_component_class.ts +++ b/compiler/src/process_component_class.ts @@ -324,10 +324,8 @@ function processComponentMethod(node: ts.MethodDeclaration, parentComponentName: node.type, processComponentBlock(node.body, false, log, true)); } else if (hasDecorator(node, COMPONENT_BUILDER_DECORATOR, customBuilder)) { CUSTOM_BUILDER_METHOD.add(name); - INNER_CUSTOM_BUILDER_METHOD.add(name) - node.parameters.push(ts.factory.createParameterDeclaration(undefined, undefined, undefined, - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), undefined, undefined, - ts.factory.createIdentifier(COMPONENT_IF_UNDEFINED))); + INNER_CUSTOM_BUILDER_METHOD.add(name); + node.parameters.push(createParentParameter()); const builderNode: ts.MethodDeclaration = ts.factory.updateMethodDeclaration(node, customBuilder, node.modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, processComponentBlock(node.body, false, log, false, true)); @@ -351,6 +349,12 @@ function processComponentMethod(node: ts.MethodDeclaration, parentComponentName: return updateItem; } +export function createParentParameter(): ts.ParameterDeclaration { + return ts.factory.createParameterDeclaration(undefined, undefined, undefined, + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), undefined, undefined, + ts.factory.createIdentifier(COMPONENT_IF_UNDEFINED)); +} + function processBuildMember(node: ts.MethodDeclaration, context: ts.TransformationContext, log: LogInfo[]): ts.MethodDeclaration { return ts.visitNode(node, visitBuild); diff --git a/compiler/src/process_component_member.ts b/compiler/src/process_component_member.ts index 95f1f6b..c432788 100644 --- a/compiler/src/process_component_member.ts +++ b/compiler/src/process_component_member.ts @@ -14,6 +14,7 @@ */ import ts from 'typescript'; +const path = require('path'); import { INNER_COMPONENT_MEMBER_DECORATORS, @@ -53,7 +54,9 @@ import { COMPONENT_BUILDERPARAM_DECORATOR, COMPONENT_LOCAL_STORAGE_LINK_DECORATOR, COMPONENT_LOCAL_STORAGE_PROP_DECORATOR, - COMPONENT_CONSTRUCTOR_PARENT + COMPONENT_CONSTRUCTOR_PARENT, + EXTNAME_ETS, + _GENERATE_ID } from './pre_define'; import { forbiddenUseStateType, @@ -77,6 +80,7 @@ import { isProperty } from './process_component_class'; import { globalProgram, projectConfig } from '../main'; +import { transformLog } from './process_ui_syntax'; export type ControllerType = { hasController: boolean @@ -594,13 +598,17 @@ function addCustomComponentId(node: ts.NewExpression, componentName: string, if (!argumentsArray) { argumentsArray = [ts.factory.createObjectLiteralExpression([], true)]; } - argumentsArray.unshift(ts.factory.createStringLiteral((++componentInfo.id).toString()), - isInnerBuilder ? ts.factory.createConditionalExpression( - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.QuestionToken), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createThis() - ) : ts.factory.createThis()); + ++componentInfo.id; + argumentsArray.unshift(isInnerBuilder ? ts.factory.createBinaryExpression( + ts.factory.createStringLiteral(path.basename(transformLog.sourceFile.fileName, EXTNAME_ETS) + '_'), + ts.factory.createToken(ts.SyntaxKind.PlusToken), ts.factory.createIdentifier(_GENERATE_ID)) : + ts.factory.createStringLiteral(componentInfo.id.toString()), + isInnerBuilder ? ts.factory.createConditionalExpression( + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), + ts.factory.createToken(ts.SyntaxKind.QuestionToken), + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), + ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createThis() + ) : ts.factory.createThis()); node = ts.factory.updateNewExpression(node, node.expression, node.typeArguments, argumentsArray); } else if (argumentsArray) { @@ -704,7 +712,7 @@ export function isSimpleType(typeNode: ts.TypeNode, program: ts.Program, log?: L referenceType = true; } if (basicType && referenceType && log) { - validateVariableType(typeNode, log); + validateVariableType(typeNode, log); return false; } } diff --git a/compiler/src/process_custom_component.ts b/compiler/src/process_custom_component.ts index 6fc9c2d..2b63cf0 100644 --- a/compiler/src/process_custom_component.ts +++ b/compiler/src/process_custom_component.ts @@ -33,7 +33,8 @@ import { CUSTOM_COMPONENT_NEEDS_UPDATE_FUNCTION, CUSTOM_COMPONENT_MARK_STATIC_FUNCTION, COMPONENT_COMMON, - COMPONENT_CONSTRUCTOR_PARENT + COMPONENT_CONSTRUCTOR_PARENT, + GENERATE_ID } from './pre_define'; import { propertyCollection, @@ -371,7 +372,8 @@ function createFindChildById(id: string, name: string, isInnerBuilder: boolean = ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createThis() )) : ts.factory.createThis(), ts.factory.createIdentifier( - `${CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID}`)), undefined, [ts.factory.createStringLiteral(id)]), + `${CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID}`)), undefined, [isInnerBuilder ? ts.factory.createCallExpression( + ts.factory.createIdentifier(GENERATE_ID), undefined, []) : ts.factory.createStringLiteral(id)]), ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name))))], ts.NodeFlags.Let)); } diff --git a/compiler/src/process_ui_syntax.ts b/compiler/src/process_ui_syntax.ts index d7b43a3..57eb5c0 100644 --- a/compiler/src/process_ui_syntax.ts +++ b/compiler/src/process_ui_syntax.ts @@ -17,7 +17,10 @@ import ts from 'typescript'; import path from 'path'; import { componentCollection } from './validate_ui_syntax'; -import { processComponentClass } from './process_component_class'; +import { + processComponentClass, + createParentParameter +} from './process_component_class'; import processImport from './process_import'; import { PAGE_ENTRY_FUNCTION_NAME, @@ -48,7 +51,11 @@ import { CUSTOM_DIALOG_CONTROLLER_BUILDER, ESMODULE, ARK, - COMPONENT_COMMON + COMPONENT_CONSTRUCTOR_PARENT, + COMPONENT_IF_UNDEFINED, + EXTNAME_ETS, + GENERATE_ID, + _GENERATE_ID } from './pre_define'; import { componentInfo, @@ -107,6 +114,7 @@ export function processUISyntax(program: ts.Program, ut = false): Function { }); GLOBAL_STYLE_FUNCTION.clear(); const statements: ts.Statement[] = Array.from(node.statements); + generateId(statements, node); INTERFACE_NODE_SET.forEach(item => { statements.unshift(item); }); @@ -139,9 +147,10 @@ export function processUISyntax(program: ts.Program, ut = false): Function { } else if (hasDecorator(node, COMPONENT_BUILDER_DECORATOR) && node.name && node.body && ts.isBlock(node.body)) { CUSTOM_BUILDER_METHOD.add(node.name.getText()); + node.parameters.push(createParentParameter()); node = ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, - processComponentBlock(node.body, false, transformLog.errors)); + processComponentBlock(node.body, false, transformLog.errors, false, true)); } else if (hasDecorator(node, COMPONENT_STYLES_DECORATOR)) { if (node.parameters.length === 0) { node = undefined; @@ -173,6 +182,41 @@ export function processUISyntax(program: ts.Program, ut = false): Function { }; } +function generateId(statements: ts.Statement[], node: ts.SourceFile): void { + statements.unshift( + ts.factory.createVariableStatement( + undefined, + ts.factory.createVariableDeclarationList( + [ts.factory.createVariableDeclaration( + ts.factory.createIdentifier(_GENERATE_ID), + undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), + ts.factory.createNumericLiteral("0") + )], + ts.NodeFlags.Let + ) + ), + ts.factory.createFunctionDeclaration( + undefined, + undefined, + undefined, + ts.factory.createIdentifier(GENERATE_ID), + undefined, + [], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + ts.factory.createBlock( + [ts.factory.createReturnStatement(ts.factory.createBinaryExpression( + ts.factory.createStringLiteral(path.basename(node.fileName, EXTNAME_ETS)+'_'), + ts.factory.createToken(ts.SyntaxKind.PlusToken),ts.factory.createPrefixUnaryExpression( + ts.SyntaxKind.PlusPlusToken, + ts.factory.createIdentifier(_GENERATE_ID) + )))], + true + ) + ) + ) +} + function isCustomDialogController(node: ts.Expression) { const tempParent: ts.Node = node.parent; // @ts-ignore -- Gitee From 3a9a1d956b42c7b63930acdee8bc2cc9b7700b97 Mon Sep 17 00:00:00 2001 From: lizhouze Date: Mon, 22 Aug 2022 14:29:57 +0800 Subject: [PATCH 09/36] lizhouze@huawei.com Signed-off-by: lizhouze --- compiler/server/build_pipe_server.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/compiler/server/build_pipe_server.js b/compiler/server/build_pipe_server.js index 33dad9a..02662da 100644 --- a/compiler/server/build_pipe_server.js +++ b/compiler/server/build_pipe_server.js @@ -17,6 +17,7 @@ const WebSocket = require('ws'); const ts = require('typescript'); const path = require('path'); const fs = require('fs'); +const process = require('child_process'); const { processComponentChild } = require('../lib/process_component_build'); const { createWatchCompilerHost } = require('../lib/ets_checker'); @@ -39,6 +40,7 @@ const pluginCommandChannelMessageHandlers = { 'compileComponent': handlePluginCompileComponent, 'default': () => {} }; +const es2abcFilePath = path.join(__dirname, '../bin/ark/build-win/bin/es2abc'); let previewCacheFilePath; const messages = []; @@ -133,10 +135,27 @@ function handlePluginCompileComponent(jsonData) { } } receivedMsg.data.log = log; - if (pluginSocket.readyState === WebSocket.OPEN){ - compileStatus = true; - receivedMsg_ = receivedMsg; - responseToPlugin(); + if (fs.existsSync(es2abcFilePath + '.exe') || fs.existsSync(es2abcFilePath)){ + es2abc(receivedMsg); + } +} + + +function es2abc(receivedMsg) { + const cmd = es2abcFilePath + ' --base64Input ' + + Buffer.from(receivedMsg.data.script).toString('base64') + ' --base64Output'; + try { + process.exec(cmd, (error, stdout, stderr) => { + if (stdout) { + receivedMsg.data.script = stdout; + } else { + receivedMsg.data.script = ""; + } + compileStatus = true; + receivedMsg_ = receivedMsg; + responseToPlugin(); + }) + } catch (e) { } } -- Gitee From fa046641d0c73bcfee86b63500000a4c8428862e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A1=E5=93=A5?= Date: Mon, 22 Aug 2022 12:39:10 +0000 Subject: [PATCH 10/36] update compiler/server/build_pipe_server.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 卡哥 --- compiler/server/build_pipe_server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/server/build_pipe_server.js b/compiler/server/build_pipe_server.js index 02662da..275a77b 100644 --- a/compiler/server/build_pipe_server.js +++ b/compiler/server/build_pipe_server.js @@ -17,7 +17,7 @@ const WebSocket = require('ws'); const ts = require('typescript'); const path = require('path'); const fs = require('fs'); -const process = require('child_process'); +const pipeProcess = require('child_process'); const { processComponentChild } = require('../lib/process_component_build'); const { createWatchCompilerHost } = require('../lib/ets_checker'); @@ -145,7 +145,7 @@ function es2abc(receivedMsg) { const cmd = es2abcFilePath + ' --base64Input ' + Buffer.from(receivedMsg.data.script).toString('base64') + ' --base64Output'; try { - process.exec(cmd, (error, stdout, stderr) => { + pipeProcess.exec(cmd, (error, stdout, stderr) => { if (stdout) { receivedMsg.data.script = stdout; } else { -- Gitee From b207928d64a3d651ddf23eb999c7250549ad5154 Mon Sep 17 00:00:00 2001 From: lizhouze Date: Tue, 23 Aug 2022 10:15:15 +0800 Subject: [PATCH 11/36] lizhouze@huawei.com Signed-off-by: lizhouze --- compiler/main.js | 32 ++++++++++++++++++++++++++++++++ compiler/webpack.config.js | 12 +++--------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/compiler/main.js b/compiler/main.js index d17eeda..bb36116 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -380,6 +380,37 @@ function loadModuleInfo(projectConfig, envArgs) { } } + +function checkAppResourcePath(appResourcePath, config) { + if (appResourcePath) { + readAppResource(resources, appResourcePath); + if (fs.existsSync(appResourcePath) && config.cache) { + config.cache.buildDependencies.config.push(appResourcePath); + } + if (!projectConfig.xtsMode) { + saveAppResourcePath(appResourcePath, appResourcePathSavePath); + if (fs.existsSync(appResourcePathSavePath) && config.cache) { + config.cache.buildDependencies.config.push(appResourcePathSavePath); + } + } + } +} + +function saveAppResourcePath(appResourcePath, appResourcePathSavePath) { + let isSave = false; + if (fs.existsSync(appResourcePathSavePath)) { + const saveContent = fs.readFileSync(appResourcePathSavePath); + if (appResourcePath !== saveContent) { + isSave = true; + } + } else { + isSave = true; + } + if (isSave) { + fs.writeFileSync(appResourcePathSavePath, appResourcePath); + } +} + const globalProgram = { program: null, watchProgram: null @@ -396,3 +427,4 @@ exports.readWorkerFile = readWorkerFile; exports.abilityPagesFullPath = abilityPagesFullPath; exports.loadModuleInfo = loadModuleInfo; exports.systemModules = systemModules; +exports.checkAppResourcePath = checkAppResourcePath; diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 93dad6d..1b204a6 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -24,12 +24,11 @@ const buildPipeServer = require('./server/build_pipe_server'); const { projectConfig, loadEntryObj, - readAppResource, - resources, loadWorker, abilityConfig, readWorkerFile, - loadModuleInfo + loadModuleInfo, + checkAppResourcePath } = require('./main'); const { ResultStates } = require('./lib/compile_info'); const { processUISyntax } = require('./lib/process_ui_syntax'); @@ -384,12 +383,7 @@ module.exports = (env, argv) => { } const appResourcePath = env.appResource || process.env.appResource; - if (appResourcePath) { - readAppResource(resources, appResourcePath); - if (fs.existsSync(appResourcePath) && config.cache) { - config.cache.buildDependencies.config.push(appResourcePath) - } - } + checkAppResourcePath(appResourcePath, config); config.output.library = projectConfig.hashProjectPath; return config; } -- Gitee From a924773efd0572b100f12970f55f3a1d217b22b0 Mon Sep 17 00:00:00 2001 From: houhaoyu Date: Tue, 23 Aug 2022 11:38:57 +0800 Subject: [PATCH 12/36] fixed 5dc686d from https://gitee.com/houhaoyu/developtools_ace-ets2bundle/pulls/998 houhaoyu@huawei.com fix checkneedupdatefiles endless circurlar Signed-off-by: houhaoyu Change-Id: I39ee8ab85c219fa498ce34146bfc53c9417cb9d8 --- compiler/src/compile_info.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index e912ea9..313926c 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -449,12 +449,19 @@ function updateErrorFileCache(diagnostic: ts.Diagnostic): void { function filterInput(rootFileNames: string[]): string[] { return rootFileNames.filter((file: string) => { const needUpdate: NeedUpdateFlag = { flag: false }; - checkNeedUpdateFiles(path.resolve(file), needUpdate); + const alreadyCheckedFiles: Set = new Set(); + checkNeedUpdateFiles(path.resolve(file), needUpdate, alreadyCheckedFiles); return needUpdate.flag; }); } -function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag): void { +function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag, alreadyCheckedFiles: Set): void { + if (alreadyCheckedFiles.has(file)) { + return; + } else { + alreadyCheckedFiles.add(file); + } + if (needUpdate.flag) { return; } @@ -467,7 +474,7 @@ function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag): void { return; } for (let i = 0; i < value.children.length; ++i) { - checkNeedUpdateFiles(value.children[i], needUpdate); + checkNeedUpdateFiles(value.children[i], needUpdate, alreadyCheckedFiles); } } else { cache[file] = { mtimeMs, children: [], error: false }; -- Gitee From 968c4acc256ad939fd04dc110aea70226a124e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A1=E5=93=A5?= Date: Tue, 23 Aug 2022 07:43:23 +0000 Subject: [PATCH 13/36] update compiler/main.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 卡哥 --- compiler/main.js | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/main.js b/compiler/main.js index bb36116..323042a 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -388,6 +388,7 @@ function checkAppResourcePath(appResourcePath, config) { config.cache.buildDependencies.config.push(appResourcePath); } if (!projectConfig.xtsMode) { + const appResourcePathSavePath = path.resolve(projectConfig.cachePath, 'resource_path.txt'); saveAppResourcePath(appResourcePath, appResourcePathSavePath); if (fs.existsSync(appResourcePathSavePath) && config.cache) { config.cache.buildDependencies.config.push(appResourcePathSavePath); -- Gitee From 9a9614414cd5c0a12e774ec431fd5f3096e00a5d Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Wed, 17 Aug 2022 10:26:56 +0800 Subject: [PATCH 14/36] fixed 3e86072 from https://gitee.com/zhangrengao1/developtools_ace-ets2bundle/pulls/966 fix clean webpack of incre compile Signed-off-by: zhangrengao Change-Id: I768960e2a0fdace7c170789d6a6fc22539110e96 --- compiler/src/gen_abc.ts | 19 ++---- compiler/src/gen_abc_plugin.ts | 117 +++++++++++++++++++++++---------- compiler/src/utils.ts | 19 ++++++ 3 files changed, 107 insertions(+), 48 deletions(-) diff --git a/compiler/src/gen_abc.ts b/compiler/src/gen_abc.ts index d39de1a..6dbb3cf 100644 --- a/compiler/src/gen_abc.ts +++ b/compiler/src/gen_abc.ts @@ -32,7 +32,9 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { const inputPaths: any = JSON.parse(jsonInput); for (let i = 0; i < inputPaths.length; ++i) { const input: string = inputPaths[i].path; - const singleCmd: any = `${cmd} "${input}"`; + const cacheOutputPath: string = inputPaths[i].cacheOutputPath; + const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, ".abc"); + const singleCmd: any = `${cmd} "${cacheOutputPath}" -o "${cacheAbcFilePath}" --source-file "${input}"`; logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); try { childProcess.execSync(singleCmd); @@ -40,16 +42,6 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); process.exit(FAIL); } - - const abcFile: string = input.replace(/\.js$/, '.abc'); - if (fs.existsSync(abcFile)) { - const abcFileNew: string = abcFile.replace(/_.abc$/, '.abc'); - fs.copyFileSync(abcFile, abcFileNew); - fs.unlinkSync(abcFile); - } else { - logger.error(red, `ETS:ERROR ${abcFile} is lost`, reset); - process.exit(FAIL); - } } return; @@ -59,8 +51,9 @@ function es2abcByWorkers(jsonInput: string, cmd: string): Promise { const inputPaths: any = JSON.parse(jsonInput); for (let i = 0; i < inputPaths.length; ++i) { const input: string = inputPaths[i].path; - const abcFile: string = input.replace(/_.js$/, '.abc'); - const singleCmd: any = `${cmd} "${input}" --output "${abcFile}"`; + const cacheOutputPath: string = inputPaths[i].cacheOutputPath; + const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, ".abc"); + const singleCmd: any = `${cmd} "${cacheOutputPath}" --output "${cacheAbcFilePath}" --source-file "${input}"`; logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); try { childProcess.execSync(singleCmd); diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index b0af0f9..8f37cea 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -28,7 +28,9 @@ import { genAbcFileName, mkdirsSync, genSourceMapFileName, - checkNodeModulesFile + checkNodeModulesFile, + compareNodeVersion, + removeDir } from './utils'; import { projectConfig } from '../main'; import { @@ -46,7 +48,8 @@ import { FAIL, EXTNAME_JS_MAP, TS2ABC, - ES2ABC + ES2ABC, + TEMPORARY } from './pre_define'; const firstFileEXT: string = '_.js'; @@ -62,7 +65,8 @@ let nodeJs: string; let delayCount = 0; interface File { path: string, - size: number + size: number, + cacheOutputPath: string } let intermediateJsBundle: Array = []; let fileterIntermediateJsBundle: Array = []; @@ -133,6 +137,11 @@ export class GenAbcPlugin { } } + if (!checkNodeModules()) { + process.exitCode = FAIL; + return; + } + compiler.hooks.compilation.tap('GenAbcPlugin', (compilation) => { if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { return; @@ -158,6 +167,7 @@ export class GenAbcPlugin { if (projectConfig.compileMode === ESMODULE) { return; } + removeDir(output); Object.keys(compilation.assets).forEach(key => { // choose *.js if (output && path.extname(key) === EXTNAME_JS) { @@ -343,14 +353,26 @@ function processEntryToGenAbc(entryInfos: Map): void { } function writeFileSync(inputString: string, output: string, jsBundleFile: string): void { - const parent: string = path.join(output, '..'); + let parent: string = path.join(output, '..'); + if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { + mkDir(parent); + } + let buildParentPath: string = path.join(projectConfig.buildPath, '..'); + let sufStr: string = output.replace(buildParentPath, ''); + let cacheOutputPath: string = ""; + if (process.env.cachePath) { + cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, sufStr); + } else { + cacheOutputPath = output; + } + parent = path.join(cacheOutputPath, '..'); if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { mkDir(parent); } - fs.writeFileSync(output, inputString); - if (fs.existsSync(output)) { - const fileSize: any = fs.statSync(output).size; - intermediateJsBundle.push({path: output, size: fileSize}); + fs.writeFileSync(cacheOutputPath, inputString); + if (fs.existsSync(cacheOutputPath)) { + const fileSize: any = fs.statSync(cacheOutputPath).size; + intermediateJsBundle.push({path: output, size: fileSize, cacheOutputPath: cacheOutputPath}); } else { logger.error(red, `ETS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); process.exitCode = FAIL; @@ -403,12 +425,8 @@ function splitJsBundlesBySize(bundleArray: Array, groupNumber: number): an } function invokeWorkersModuleToGenAbc(moduleInfos: Array): void { - if (fs.existsSync(buildPathInfo)) { - fs.rmdirSync(buildPathInfo, { recursive: true}); - } - if (fs.existsSync(projectConfig.nodeModulesPath)) { - fs.rmdirSync(projectConfig.nodeModulesPath, { recursive: true}); - } + removeDir(buildPathInfo); + removeDir(projectConfig.nodeModulesPath); invokeCluterModuleToAbc(); } @@ -463,8 +481,7 @@ function invokeCluterModuleToAbc(): void { const abcArgs: string[] = initAbcEnv(); const clusterNewApiVersion: number = 16; - const currentNodeVersion: number = parseInt(process.version.split('.')[0]); - const useNewApi: boolean = currentNodeVersion >= clusterNewApiVersion; + const useNewApi: boolean = compareNodeVersion(clusterNewApiVersion); if (useNewApi && cluster.isPrimary || !useNewApi && cluster.isMaster) { if (useNewApi) { @@ -767,20 +784,21 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil for (let i = 0; i < inputPaths.length; ++i) { const input: string = inputPaths[i].path; const abcPath: string = input.replace(/_.js$/, EXTNAME_ABC); - if (!fs.existsSync(input)) { - logger.error(red, `ETS:ERROR ${input} is lost`, reset); + const cacheOutputPath: string = inputPaths[i].cacheOutputPath; + const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, '.abc'); + if (!fs.existsSync(cacheOutputPath)) { + logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; break; } - if (fs.existsSync(abcPath)) { - const hashInputContentData: any = toHashData(input); - const hashAbcContentData: any = toHashData(abcPath); - if (jsonObject[input] === hashInputContentData && jsonObject[abcPath] === hashAbcContentData) { - updateJsonObject[input] = hashInputContentData; - updateJsonObject[abcPath] = hashAbcContentData; - if (!projectConfig.isPreview) { - fs.unlinkSync(input); - } + if (fs.existsSync(cacheAbcFilePath)) { + const hashInputContentData: any = toHashData(cacheOutputPath); + const hashAbcContentData: any = toHashData(cacheAbcFilePath); + if (jsonObject[cacheOutputPath] === hashInputContentData && jsonObject[cacheAbcFilePath] === hashAbcContentData) { + updateJsonObject[cacheOutputPath] = hashInputContentData; + updateJsonObject[cacheAbcFilePath] = hashAbcContentData; + mkdirsSync(path.dirname(abcPath)); + fs.copyFileSync(cacheAbcFilePath, abcPath); } else { fileterIntermediateJsBundle.push(inputPaths[i]); } @@ -797,18 +815,28 @@ function writeHashJson(): void { for (let i = 0; i < fileterIntermediateJsBundle.length; ++i) { const input:string = fileterIntermediateJsBundle[i].path; const abcPath: string = input.replace(/_.js$/, EXTNAME_ABC); - if (!fs.existsSync(input) || !fs.existsSync(abcPath)) { - logger.error(red, `ETS:ERROR ${input} is lost`, reset); + const cacheOutputPath: string = fileterIntermediateJsBundle[i].cacheOutputPath; + const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, '.abc'); + if (!fs.existsSync(cacheOutputPath) || !fs.existsSync(cacheAbcFilePath)) { + logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; break; } - const hashInputContentData: any = toHashData(input); - const hashAbcContentData: any = toHashData(abcPath); - hashJsonObject[input] = hashInputContentData; - hashJsonObject[abcPath] = hashAbcContentData; - if (!projectConfig.isPreview) { - fs.unlinkSync(input); + const hashInputContentData: any = toHashData(cacheOutputPath); + const hashAbcContentData: any = toHashData(cacheAbcFilePath); + hashJsonObject[cacheOutputPath] = hashInputContentData; + hashJsonObject[cacheAbcFilePath] = hashAbcContentData; + } + for (let i = 0; i < intermediateJsBundle.length; ++i) { + const abcFile: string = intermediateJsBundle[i].path.replace(/\_.js$/, ".abc"); + const cacheAbcFilePath: string = intermediateJsBundle[i].cacheOutputPath.replace(/\_.js$/, ".abc"); + if (!fs.existsSync(cacheAbcFilePath)) { + logger.error(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); + process.exitCode = FAIL; + break; } + mkdirsSync(path.dirname(abcFile)); + fs.copyFileSync(cacheAbcFilePath, abcFile); } const hashFilePath: string = genHashJsonPath(buildPathInfo); if (hashFilePath.length === 0) { @@ -841,3 +869,22 @@ function genHashJsonPath(buildPath: string): string { return ''; } } + +function checkNodeModules() { + if (process.env.panda === TS2ABC) { + let arkEntryPath: string = path.join(arkDir, 'build'); + if (isWin) { + arkEntryPath = path.join(arkDir, 'build-win'); + } else if (isMac) { + arkEntryPath = path.join(arkDir, 'build-mac'); + } + let nodeModulesPath: string = path.join(arkEntryPath, NODE_MODULES); + if (!(fs.existsSync(nodeModulesPath) && fs.statSync(nodeModulesPath).isDirectory())) { + logger.error(red, `ERROR: node_modules for ark compiler not found. + Please make sure switch to non-root user before runing "npm install" for safity requirements and try re-run "npm install" under ${arkEntryPath}`, reset); + return false; + } + } + + return true; +} diff --git a/compiler/src/utils.ts b/compiler/src/utils.ts index 88d8e61..4a1a473 100644 --- a/compiler/src/utils.ts +++ b/compiler/src/utils.ts @@ -479,3 +479,22 @@ export function genSourceMapFileName(temporaryFile: string): string { } return abcFile; } + +export function compareNodeVersion(nodeVersion: number = 16): boolean { + const currentNodeVersion: number = parseInt(process.versions.node.split('.')[0]); + if (currentNodeVersion >= nodeVersion) { + return true; + } + + return false; +} + +export function removeDir(dirName: string): void { + if (fs.existsSync(dirName)) { + if (compareNodeVersion()) { + fs.rmSync(dirName, { recursive: true}); + } else { + fs.rmdirSync(dirName, { recursive: true}); + } + } +} \ No newline at end of file -- Gitee From 7ec03b07b597ce3850e3c67ce4a355a16746902f Mon Sep 17 00:00:00 2001 From: bojiang Date: Tue, 23 Aug 2022 18:04:04 +0800 Subject: [PATCH 15/36] fixed abb2160 from https://gitee.com/BoJiang4702/developtools_ace-ets2bundle/pulls/989 jiangbo91@huawei.com Fix duplicate error in symbol printing log in file Signed-off-by: bojiang Change-Id: I2ec625038b6775a8f05ac7c56543a270fc53b928 --- compiler/src/compile_info.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index e912ea9..cf37c83 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -385,7 +385,7 @@ export class ResultStates { .replace(/\(Emitted value instead of an instance of Error\) BUILD/, '') .replace(/^ERROR/, 'ETS:ERROR'); this.printErrorMessage(errorMessage, true, errors[index]); - } else { + } else if (!/TS[0-9]+:/.test(errors[index].message.toString())) { let errorMessage: string = `${errors[index].message.replace(/\[tsl\]\s*/, '') .replace(/\u001b\[.*?m/g, '').replace(/\.ets\.ts/g, '.ets').trim()}\n`; errorMessage = this.filterModuleError(errorMessage) -- Gitee From d95be6d05e38f13cb3f8d8de5794f968e9a2e5d8 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Tue, 23 Aug 2022 20:03:26 +0800 Subject: [PATCH 16/36] fix xts abc size is empty Signed-off-by: zhangrengao Change-Id: I48f708915328d14e71bac0fe0d2bf874556f0bcd --- compiler/src/gen_abc_plugin.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 8f37cea..a8c4a3a 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -797,8 +797,10 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil if (jsonObject[cacheOutputPath] === hashInputContentData && jsonObject[cacheAbcFilePath] === hashAbcContentData) { updateJsonObject[cacheOutputPath] = hashInputContentData; updateJsonObject[cacheAbcFilePath] = hashAbcContentData; - mkdirsSync(path.dirname(abcPath)); - fs.copyFileSync(cacheAbcFilePath, abcPath); + if (!fs.existsSync(abcPath)) { + mkdirsSync(path.dirname(abcPath)); + fs.copyFileSync(cacheAbcFilePath, abcPath); + } } else { fileterIntermediateJsBundle.push(inputPaths[i]); } @@ -835,8 +837,13 @@ function writeHashJson(): void { process.exitCode = FAIL; break; } - mkdirsSync(path.dirname(abcFile)); - fs.copyFileSync(cacheAbcFilePath, abcFile); + if (!fs.existsSync(abcFile)) { + mkdirsSync(path.dirname(abcFile)); + fs.copyFileSync(cacheAbcFilePath, abcFile); + } + if (fs.existsSync(intermediateJsBundle[i].path)) { + fs.unlinkSync(intermediateJsBundle[i].path); + } } const hashFilePath: string = genHashJsonPath(buildPathInfo); if (hashFilePath.length === 0) { -- Gitee From ca613322777c7162eee544d4f7c627a7da086d16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A1=E5=93=A5?= Date: Tue, 23 Aug 2022 13:04:40 +0000 Subject: [PATCH 17/36] update compiler/server/build_pipe_server.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 卡哥 --- compiler/server/build_pipe_server.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/compiler/server/build_pipe_server.js b/compiler/server/build_pipe_server.js index 275a77b..1d13c0a 100644 --- a/compiler/server/build_pipe_server.js +++ b/compiler/server/build_pipe_server.js @@ -40,7 +40,7 @@ const pluginCommandChannelMessageHandlers = { 'compileComponent': handlePluginCompileComponent, 'default': () => {} }; -const es2abcFilePath = path.join(__dirname, '../bin/ark/build-win/bin/es2abc'); +let es2abcFilePath = path.join(__dirname, '../bin/ark/build-win/bin/es2abc'); let previewCacheFilePath; const messages = []; @@ -137,6 +137,11 @@ function handlePluginCompileComponent(jsonData) { receivedMsg.data.log = log; if (fs.existsSync(es2abcFilePath + '.exe') || fs.existsSync(es2abcFilePath)){ es2abc(receivedMsg); + } else { + es2abcFilePath = path.join(__dirname, '../bin/ark/build-mac/bin/es2abc'); + if (fs.existsSync(es2abcFilePath)) { + es2abc(receivedMsg); + } } } -- Gitee From ea82cfb69c6f681a67dcd328e5d590268386dba6 Mon Sep 17 00:00:00 2001 From: yfwang6 Date: Thu, 18 Aug 2022 14:21:32 +0800 Subject: [PATCH 18/36] fixed 1cdf627 from https://gitee.com/yfwang6/developtools_ace-ets2bundle/pulls/955 wangyongfei6@huawei.com componentid be compatible preview mode incremental compilation Signed-off-by: yfwang6 Change-Id: If2722ad6b95bd8edc496f47998d910e0b16368bb --- compiler/src/process_component_build.ts | 40 ++++++++++++++----------- compiler/src/process_ui_syntax.ts | 12 +++++++- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/compiler/src/process_component_build.ts b/compiler/src/process_component_build.ts index 8772ed8..4a46a41 100644 --- a/compiler/src/process_component_build.ts +++ b/compiler/src/process_component_build.ts @@ -932,24 +932,30 @@ function updateArgumentFor$$(argument: any): ts.Expression { function verifyComponentId(temp: any, node: ts.Identifier, propName: string, log: LogInfo[]): void { if (!newsupplement.isAcceleratePreview && propName === ATTRIBUTE_ID) { - const literalString: string = temp.arguments[0].text; - if (ID_ATTRS.has(literalString)) { - const errInfo: Map = ID_ATTRS.get(literalString); - log.push({ - type: LogType.ERROR, - message: `The current component id "${literalString}" is duplicate with ` + - `${errInfo.get('path')}:${errInfo.get('line')}:${errInfo.get('col')}.`, - pos: node.pos - }); + const id: string = temp.arguments[0].text; + const posOfNode: ts.LineAndCharacter = transformLog.sourceFile + .getLineAndCharacterOfPosition(getRealNodePos(node)); + const curFileName: string = transformLog.sourceFile.fileName.replace(/\.ts$/, ''); + const rPath: string = path.resolve(projectConfig.projectPath, curFileName) + .replace(/\\+/g, '/'); + const rLine: number = posOfNode.line + 1; + const rCol: number = posOfNode.character + 1; + if (ID_ATTRS.has(id)) { + const idInfo: Map = ID_ATTRS.get(id); + if (!(idInfo.get('path') === rPath && + idInfo.get('line') === rLine && + idInfo.get('col') === rCol)) { + log.push({ + type: LogType.WARN, + message: `The current component id "${id}" is duplicate with ` + + `${idInfo.get('path')}:${idInfo.get('line')}:${idInfo.get('col')}.`, + pos: node.pos + }); + } } else { - const posOfNode: ts.LineAndCharacter = transformLog.sourceFile - .getLineAndCharacterOfPosition(getRealNodePos(node)); - const curFileName: string = transformLog.sourceFile.fileName.replace(/\.ts$/, ''); - const rPath: string = path.resolve(projectConfig.projectPath, curFileName) - .replace(/\\+/g, '/'); - ID_ATTRS.set(literalString, new Map().set('path', rPath) - .set('line', posOfNode.line + 1) - .set('col', posOfNode.character + 1)); + ID_ATTRS.set(id, new Map().set('path', rPath) + .set('line', rLine) + .set('col', rCol)); } } } diff --git a/compiler/src/process_ui_syntax.ts b/compiler/src/process_ui_syntax.ts index 57eb5c0..13b4b2c 100644 --- a/compiler/src/process_ui_syntax.ts +++ b/compiler/src/process_ui_syntax.ts @@ -76,7 +76,8 @@ import { EXTEND_ATTRIBUTE, INNER_STYLE_FUNCTION, GLOBAL_STYLE_FUNCTION, - INTERFACE_NODE_SET + INTERFACE_NODE_SET, + ID_ATTRS } from './component_map'; import { localStorageLinkCollection, @@ -99,6 +100,7 @@ export function processUISyntax(program: ts.Program, ut = false): Function { pagesDir = path.resolve(path.dirname(node.fileName)); if (process.env.compiler === BUILD_ON) { transformLog.sourceFile = node; + preprocessIdAttrs(node.fileName); if (!ut && (path.basename(node.fileName) === 'app.ets' || /\.ts$/.test(node.fileName))) { node = ts.visitEachChild(node, processResourceNode, context); if (projectConfig.compileMode === ESMODULE && projectConfig.processTs === true @@ -217,6 +219,14 @@ function generateId(statements: ts.Statement[], node: ts.SourceFile): void { ) } +function preprocessIdAttrs(fileName: string): void { + for (const [id, idInfo] of ID_ATTRS) { + if (fileName === idInfo.get('path')) { + ID_ATTRS.delete(id); + } + } +} + function isCustomDialogController(node: ts.Expression) { const tempParent: ts.Node = node.parent; // @ts-ignore -- Gitee From db8dd705d98e525ee8bbe7f936a9b12d4dc20804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A1=E5=93=A5?= Date: Mon, 22 Aug 2022 13:15:39 +0000 Subject: [PATCH 19/36] fixed 2ad4f27 from https://gitee.com/kage1/developtools_ace-ets2bundle/pulls/991 update compiler/webpack.config.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 卡哥 --- compiler/webpack.config.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 1b204a6..fc1681f 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -28,7 +28,8 @@ const { abilityConfig, readWorkerFile, loadModuleInfo, - checkAppResourcePath + checkAppResourcePath, + addSDKBuildDependencies } = require('./main'); const { ResultStates } = require('./lib/compile_info'); const { processUISyntax } = require('./lib/process_ui_syntax'); -- Gitee From 7ff30bbce6d7fe53d2005d38f09337609f547226 Mon Sep 17 00:00:00 2001 From: lizhouze Date: Mon, 22 Aug 2022 16:13:23 +0800 Subject: [PATCH 20/36] fixed 8834ce8 from https://gitee.com/kage1/developtools_ace-ets2bundle/pulls/991 lizhouze@huawei.com Signed-off-by: lizhouze --- compiler/main.js | 14 ++++++++++++++ compiler/webpack.config.js | 1 + 2 files changed, 15 insertions(+) diff --git a/compiler/main.js b/compiler/main.js index 323042a..71760c4 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -66,6 +66,8 @@ function initProjectConfig(projectConfig) { path.resolve(__dirname, 'node_modules/.cache'); projectConfig.aceSoPath = projectConfig.aceSoPath || process.env.aceSoPath; projectConfig.xtsMode = /ets_loader_ark$/.test(__dirname); + projectConfig.localProertiesPath = projectConfig.localProertiesPath || process.env.localProertiesPath + projectConfig.projectProfilePath = projectConfig.projectProfilePath || process.env.projectProfilePath } function loadEntryObj(projectConfig) { @@ -412,6 +414,17 @@ function saveAppResourcePath(appResourcePath, appResourcePathSavePath) { } } +function addSDKBuildDependencies(config) { + if (projectConfig.localProertiesPath && + fs.existsSync(projectConfig.localProertiesPath) && config.cache) { + config.cache.buildDependencies.config.push(projectConfig.localProertiesPath) + } + if (projectConfig.projectProfilePath && + fs.existsSync(projectConfig.projectProfilePath) && config.cache) { + config.cache.buildDependencies.config.push(projectConfig.projectProfilePath) + } +} + const globalProgram = { program: null, watchProgram: null @@ -429,3 +442,4 @@ exports.abilityPagesFullPath = abilityPagesFullPath; exports.loadModuleInfo = loadModuleInfo; exports.systemModules = systemModules; exports.checkAppResourcePath = checkAppResourcePath; +exports.addSDKBuildDependencies = addSDKBuildDependencies; diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index fc1681f..69a06e7 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -385,6 +385,7 @@ module.exports = (env, argv) => { const appResourcePath = env.appResource || process.env.appResource; checkAppResourcePath(appResourcePath, config); + addSDKBuildDependencies(config); config.output.library = projectConfig.hashProjectPath; return config; } -- Gitee From 107161f7f534ec5e475333af43cae4aae588382c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=A1=E5=93=A5?= Date: Thu, 25 Aug 2022 03:36:27 +0000 Subject: [PATCH 21/36] update compiler/main.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 卡哥 --- compiler/main.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/main.js b/compiler/main.js index 71760c4..3e9f93e 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -66,7 +66,7 @@ function initProjectConfig(projectConfig) { path.resolve(__dirname, 'node_modules/.cache'); projectConfig.aceSoPath = projectConfig.aceSoPath || process.env.aceSoPath; projectConfig.xtsMode = /ets_loader_ark$/.test(__dirname); - projectConfig.localProertiesPath = projectConfig.localProertiesPath || process.env.localProertiesPath + projectConfig.localPropertiesPath = projectConfig.localPropertiesPath || process.env.localPropertiesPath projectConfig.projectProfilePath = projectConfig.projectProfilePath || process.env.projectProfilePath } @@ -415,9 +415,9 @@ function saveAppResourcePath(appResourcePath, appResourcePathSavePath) { } function addSDKBuildDependencies(config) { - if (projectConfig.localProertiesPath && - fs.existsSync(projectConfig.localProertiesPath) && config.cache) { - config.cache.buildDependencies.config.push(projectConfig.localProertiesPath) + if (projectConfig.localPropertiesPath && + fs.existsSync(projectConfig.localPropertiesPath) && config.cache) { + config.cache.buildDependencies.config.push(projectConfig.localPropertiesPath) } if (projectConfig.projectProfilePath && fs.existsSync(projectConfig.projectProfilePath) && config.cache) { -- Gitee From ada4ae4b967d2f50944f912298b0f9258a867d20 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Thu, 25 Aug 2022 22:28:48 +0800 Subject: [PATCH 22/36] fixed a4bcc10 from https://gitee.com/zhangrengao1/developtools_ace-ets2bundle/pulls/1016 Add sourcefile of module compiler Signed-off-by: zhangrengao Change-Id: Ie252dacee39b9ef1f8ed3dfeda68076593cb4ec9 --- compiler/src/gen_abc_plugin.ts | 2 ++ compiler/src/gen_module_abc.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index a8c4a3a..44645b9 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -372,6 +372,8 @@ function writeFileSync(inputString: string, output: string, jsBundleFile: string fs.writeFileSync(cacheOutputPath, inputString); if (fs.existsSync(cacheOutputPath)) { const fileSize: any = fs.statSync(cacheOutputPath).size; + output = toUnixPath(output); + cacheOutputPath = toUnixPath(cacheOutputPath); intermediateJsBundle.push({path: output, size: fileSize, cacheOutputPath: cacheOutputPath}); } else { logger.error(red, `ETS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); diff --git a/compiler/src/gen_module_abc.ts b/compiler/src/gen_module_abc.ts index 3490442..1426cee 100644 --- a/compiler/src/gen_module_abc.ts +++ b/compiler/src/gen_module_abc.ts @@ -60,7 +60,7 @@ function es2abcByWorkers(jsonInput: string, cmd: string): Promise { for (let i = 0; i < inputPaths.length; ++i) { const input: string = inputPaths[i].tempFilePath; const abcFile: string = input.replace(/\.js$/, '.abc'); - const singleCmd: any = `${cmd} "${input}" --output "${abcFile}"`; + const singleCmd: any = `${cmd} "${input}" --output "${abcFile}" --source-file "${input}"`; logger.debug('gen abc cmd is: ', singleCmd); try { childProcess.execSync(singleCmd); -- Gitee From 563b1a8ee67d6278db7a570d9566179381cb0204 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Fri, 26 Aug 2022 18:16:43 +0800 Subject: [PATCH 23/36] Fix cachePath is undefined Signed-off-by: zhangrengao Change-Id: Ib127f2f2f71b69602212a0c526bbf0e57dad1519 --- compiler/src/gen_abc_plugin.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 44645b9..fe1be97 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -142,6 +142,11 @@ export class GenAbcPlugin { return; } + removeDir(output); + if (projectConfig.compileMode === ESMODULE) { + removeDir(projectConfig.nodeModulesPath); + } + compiler.hooks.compilation.tap('GenAbcPlugin', (compilation) => { if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { return; @@ -167,7 +172,6 @@ export class GenAbcPlugin { if (projectConfig.compileMode === ESMODULE) { return; } - removeDir(output); Object.keys(compilation.assets).forEach(key => { // choose *.js if (output && path.extname(key) === EXTNAME_JS) { @@ -427,8 +431,6 @@ function splitJsBundlesBySize(bundleArray: Array, groupNumber: number): an } function invokeWorkersModuleToGenAbc(moduleInfos: Array): void { - removeDir(buildPathInfo); - removeDir(projectConfig.nodeModulesPath); invokeCluterModuleToAbc(); } @@ -843,7 +845,7 @@ function writeHashJson(): void { mkdirsSync(path.dirname(abcFile)); fs.copyFileSync(cacheAbcFilePath, abcFile); } - if (fs.existsSync(intermediateJsBundle[i].path)) { + if (process.env.cachePath === undefined && fs.existsSync(intermediateJsBundle[i].path)) { fs.unlinkSync(intermediateJsBundle[i].path); } } -- Gitee From 3e5e655e39e158b096153b7599374660adac6935 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Fri, 26 Aug 2022 22:14:41 +0800 Subject: [PATCH 24/36] Add clean webpack plugin Signed-off-by: zhangrengao Change-Id: Icf705c4b0dc1db7e5e705a8823f581bfa5bbc4be --- compiler/src/gen_abc_plugin.ts | 1 - compiler/webpack.config.js | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index fe1be97..5b11e15 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -142,7 +142,6 @@ export class GenAbcPlugin { return; } - removeDir(output); if (projectConfig.compileMode === ESMODULE) { removeDir(projectConfig.nodeModulesPath); } diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 69a06e7..ebb7678 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -17,6 +17,7 @@ const path = require('path'); const fs = require('fs'); const CopyPlugin = require('copy-webpack-plugin'); const Webpack = require('webpack'); +const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const { GenAbcPlugin } = require('./lib/gen_abc_plugin'); const { OHMResolverPlugin } = require('./lib/resolve_ohm_url'); const buildPipeServer = require('./server/build_pipe_server'); @@ -344,6 +345,25 @@ function setGenAbcPlugin(env, config) { } } +function setCleanWebpackPlugin(workerFile, config) { + let cleanPath = []; + cleanPath.push(projectConfig.buildPath); + if (workerFile) { + let workerFilesPath = Object.keys(workerFile); + for (let workerFilePath of workerFilesPath) { + cleanPath.push(path.join(projectConfig.buildPath, workerFilePath, '..')); + } + } + + config.plugins.push( + new CleanWebpackPlugin({ + dry: false, + dangerouslyAllowCleanPatternsOutsideProject: true, + cleanOnceBeforeBuildPatterns: cleanPath + }) + ); +} + module.exports = (env, argv) => { const config = {}; setProjectConfig(env); @@ -354,6 +374,7 @@ module.exports = (env, argv) => { const workerFile = readWorkerFile(); setOptimizationConfig(config, workerFile); setCopyPluginConfig(config); + setCleanWebpackPlugin(workerFile, config); if (env.isPreview !== "true") { loadWorker(projectConfig, workerFile); -- Gitee From 4eb2c1ba48233fb39864a1ec46dde4ad6f1d9696 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Sat, 27 Aug 2022 12:03:06 +0800 Subject: [PATCH 25/36] Fix clean webpack of esmodule Signed-off-by: zhangrengao Change-Id: I2302e7d209c5cc98735ab5a416a5839cdcbaa2bd --- compiler/src/gen_abc_plugin.ts | 1 + compiler/webpack.config.js | 3 +++ 2 files changed, 4 insertions(+) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 5b11e15..30dc6c0 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -143,6 +143,7 @@ export class GenAbcPlugin { } if (projectConfig.compileMode === ESMODULE) { + removeDir(output); removeDir(projectConfig.nodeModulesPath); } diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index ebb7678..a9c2391 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -346,6 +346,9 @@ function setGenAbcPlugin(env, config) { } function setCleanWebpackPlugin(workerFile, config) { + if (projectConfig.compileMode === 'esmodule') { + return; + } let cleanPath = []; cleanPath.push(projectConfig.buildPath); if (workerFile) { -- Gitee From 674219fdaefabc7c095181d71da11a9ecb043693 Mon Sep 17 00:00:00 2001 From: yfwang6 Date: Sat, 27 Aug 2022 10:41:32 +0800 Subject: [PATCH 26/36] fixed a48de73 from https://gitee.com/yfwang6/developtools_ace-ets2bundle/pulls/1042 fixed f872417 from https://gitee.com/yfwang6/developtools_ace-ets2bundle/pulls/1024 wangyongfei6@huawei.com watch callback do not trigger Signed-off-by: yfwang6 Change-Id: I638e4b1cf0c4c8af9f41071a4e8f5feee4c788c0 --- compiler/src/pre_define.ts | 5 ++--- compiler/src/process_component_constructor.ts | 2 +- compiler/src/process_component_member.ts | 9 +++------ 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index a1698ab..a1cfde8 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -68,9 +68,8 @@ export const INITIALIZE_CONSUME_FUNCTION: string = 'initializeConsume'; export const ADD_PROVIDED_VAR: string = 'addProvidedVar'; export const APP_STORAGE: string = 'AppStorage'; -export const APP_STORAGE_SET_AND_PROP: string = 'setAndProp'; -export const APP_STORAGE_SET_AND_LINK: string = 'setAndLink'; -export const APP_STORAGE_GET_OR_SET: string = 'GetOrCreate'; +export const APP_STORAGE_SET_AND_PROP: string = 'SetAndProp'; +export const APP_STORAGE_SET_AND_LINK: string = 'SetAndLink'; export const PAGE_ENTRY_FUNCTION_NAME: string = 'loadDocument'; export const STORE_PREVIEW_COMPONENTS: string = 'storePreviewComponents'; diff --git a/compiler/src/process_component_constructor.ts b/compiler/src/process_component_constructor.ts index 469c6c4..5b04845 100644 --- a/compiler/src/process_component_constructor.ts +++ b/compiler/src/process_component_constructor.ts @@ -168,5 +168,5 @@ export function addConstructor(ctorNode: any, watchMap: Map, ts.factory.createThis(), ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UPDATE_PARAMS)), undefined, [ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARAMS)])); return updateConstructor(updateConstructor(ctorNode, [], [callSuperStatement], true), [], - [updateWithValueParamsStatement, ...watchStatements], false, true, parentComponentName); + [...watchStatements, updateWithValueParamsStatement], false, true, parentComponentName); } diff --git a/compiler/src/process_component_member.ts b/compiler/src/process_component_member.ts index c432788..444a90c 100644 --- a/compiler/src/process_component_member.ts +++ b/compiler/src/process_component_member.ts @@ -44,7 +44,6 @@ import { APP_STORAGE, APP_STORAGE_SET_AND_PROP, APP_STORAGE_SET_AND_LINK, - APP_STORAGE_GET_OR_SET, COMPONENT_CONSTRUCTOR_UNDEFINED, SET_CONTROLLER_METHOD, SET_CONTROLLER_CTR, @@ -509,11 +508,9 @@ function updateStoragePropAndLinkProperty(node: ts.PropertyDeclaration, name: ts return ts.factory.createExpressionStatement(ts.factory.createBinaryExpression( createPropertyAccessExpressionWithThis(`__${name.getText()}`), ts.factory.createToken(ts.SyntaxKind.EqualsToken), ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(APP_STORAGE), - ts.factory.createIdentifier(APP_STORAGE_GET_OR_SET)), undefined, []), - ts.factory.createIdentifier(setFuncName)), undefined, [node.decorators[0].expression.arguments[0], - node.initializer, ts.factory.createThis()]))); + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(APP_STORAGE), + ts.factory.createIdentifier(setFuncName)), undefined, [node.decorators[0].expression.arguments[0], + node.initializer, ts.factory.createThis(), ts.factory.createStringLiteral(name.getText())]))); } else { validateAppStorageDecoractorsNonSingleKey(node, log); } -- Gitee From a6acddcdc547b2468eca5858105dbc6504ef2f9e Mon Sep 17 00:00:00 2001 From: yfwang6 Date: Mon, 29 Aug 2022 16:50:27 +0800 Subject: [PATCH 27/36] fixed ed6d4aa from https://gitee.com/yfwang6/developtools_ace-ets2bundle/pulls/1044 fixed 72cf5fd from https://gitee.com/yfwang6/developtools_ace-ets2bundle/pulls/1033 wangyongfei6@huawei.com ut for @watch do not work issue Signed-off-by: yfwang6 Change-Id: I552c9c470010c8d40d7102f6f1f216fce9261d3e --- .../application_state_management/@storageLink/@storageLink.ts | 4 ++-- .../application_state_management/@storageProp/@storageProp.ts | 4 ++-- .../application_state_management/appStorage/appStorage.ts | 4 ++-- compiler/test/ut/ui_state_management/others/@watch/@watch.ts | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts b/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts index 24e1600..8fc33b4 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts @@ -53,8 +53,8 @@ let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { constructor(compilerAssignedUniqueChildId, parent, params) { super(compilerAssignedUniqueChildId, parent); - this.__varA = AppStorage.GetOrCreate().setAndLink('varA', 2, this); - this.__lang = AppStorage.GetOrCreate().setAndProp('languageCode', 'en', this); + this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); + this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts b/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts index 24e1600..8fc33b4 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts @@ -53,8 +53,8 @@ let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { constructor(compilerAssignedUniqueChildId, parent, params) { super(compilerAssignedUniqueChildId, parent); - this.__varA = AppStorage.GetOrCreate().setAndLink('varA', 2, this); - this.__lang = AppStorage.GetOrCreate().setAndProp('languageCode', 'en', this); + this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); + this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts b/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts index 24e1600..8fc33b4 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts @@ -53,8 +53,8 @@ let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { constructor(compilerAssignedUniqueChildId, parent, params) { super(compilerAssignedUniqueChildId, parent); - this.__varA = AppStorage.GetOrCreate().setAndLink('varA', 2, this); - this.__lang = AppStorage.GetOrCreate().setAndProp('languageCode', 'en', this); + this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); + this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/others/@watch/@watch.ts b/compiler/test/ut/ui_state_management/others/@watch/@watch.ts index 6bd197a..1be5659 100644 --- a/compiler/test/ut/ui_state_management/others/@watch/@watch.ts +++ b/compiler/test/ut/ui_state_management/others/@watch/@watch.ts @@ -72,9 +72,9 @@ exports.expectResult = this.__totalPurchase = new ObservedPropertySimple(0, this, "totalPurchase"); this.__defArray = new ObservedPropertyObject(['c', 'g', 't', 'z'], this, "defArray"); this.__resultTip = new ObservedPropertySimple('', this, "resultTip"); - this.updateWithValueParams(params); this.declareWatch("shopBasket", this.onBasketUpdated); this.declareWatch("defArray", this.onPutItem); + this.updateWithValueParams(params); } updateWithValueParams(params) { if (params.shopBasket !== undefined) { -- Gitee From dbd5bcbc89896078ebf41081d733e145935ce51e Mon Sep 17 00:00:00 2001 From: bojiang Date: Fri, 2 Sep 2022 10:22:38 +0800 Subject: [PATCH 28/36] fixed 26a00b5 from https://gitee.com/BoJiang4702/developtools_ace-ets2bundle/pulls/1047 jiangbo91@huawei.com MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解决ets工程引用js文件watch模式下修改js文件内容预览器无法刷新 Signed-off-by: bojiang Change-Id: I7b0f2d9636cbe054fc12dd5283954cec357c169e --- compiler/src/compile_info.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index 681f5f6..16b2ba4 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -239,6 +239,17 @@ export class ResultStates { } this.printResult(); }); + + compiler.hooks.watchRun.tap('Listening State', (compiler: Compiler) => { + if (compiler.modifiedFiles) { + const isTsAndEtsFile: boolean = [...compiler.modifiedFiles].some((item: string) => { + return /.(ts|ets)$/.test(item); + }); + if (!isTsAndEtsFile) { + process.env.watchTs = 'end'; + } + } + }); } private printDiagnostic(diagnostic: ts.Diagnostic): void { -- Gitee From ff21e2a35486e150c6e01d6e8f7e95879b2acd2b Mon Sep 17 00:00:00 2001 From: houhaoyu Date: Wed, 21 Sep 2022 15:05:26 +0800 Subject: [PATCH 29/36] houhaoyu@huawei.com MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit npm包未收集ets范式 Signed-off-by: houhaoyu Change-Id: I4617bb3e76553ab590a00c8fd0f93d9ab1be5111 --- compiler/src/process_import.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/src/process_import.ts b/compiler/src/process_import.ts index 7f4a930..b9d774d 100644 --- a/compiler/src/process_import.ts +++ b/compiler/src/process_import.ts @@ -471,6 +471,9 @@ function getFileResolvePath(fileResolvePath: string, pagesDir: string, filePath: fileResolvePath = fileResolvePath + EXTNAME_ETS; } else if (isPackageJsonEntry(fileResolvePath)) { fileResolvePath = getPackageJsonEntry(fileResolvePath); + if (fs.statSync(fileResolvePath).isDirectory() && fs.existsSync(path.join(fileResolvePath, INDEX_ETS))) { + fileResolvePath = path.join(fileResolvePath, INDEX_ETS); + } } else if (fs.existsSync(path.join(fileResolvePath, INDEX_ETS))) { fileResolvePath = path.join(fileResolvePath, INDEX_ETS); } -- Gitee From 0a1836796f792c1ec05b3378fba1deef3f904990 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Wed, 21 Sep 2022 18:50:31 +0800 Subject: [PATCH 30/36] Fix preview mode abc file not work Signed-off-by: zhangrengao Change-Id: I91ed8817dd62b250f01c28a0de5c4a5f80e8c66c --- compiler/src/gen_abc_plugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 30dc6c0..cf67942 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -841,7 +841,7 @@ function writeHashJson(): void { process.exitCode = FAIL; break; } - if (!fs.existsSync(abcFile)) { + if (process.env.cachePath !== undefined) { mkdirsSync(path.dirname(abcFile)); fs.copyFileSync(cacheAbcFilePath, abcFile); } -- Gitee From 124e0404e91dc27a04d65cce1f70059d19ed162d Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Fri, 23 Sep 2022 10:52:45 +0800 Subject: [PATCH 31/36] pick gen abc plugin change to js Signed-off-by: zhangrengao Change-Id: I44cc39b5e91954f2b63f4202736f8c80d17de45c --- compiler/src/gen_abc.ts | 8 +-- compiler/src/gen_abc_plugin.ts | 95 +++++++++++++++++++--------------- 2 files changed, 57 insertions(+), 46 deletions(-) diff --git a/compiler/src/gen_abc.ts b/compiler/src/gen_abc.ts index 6dbb3cf..83f79f8 100644 --- a/compiler/src/gen_abc.ts +++ b/compiler/src/gen_abc.ts @@ -31,9 +31,9 @@ const reset: string = '\u001b[39m'; function js2abcByWorkers(jsonInput: string, cmd: string): Promise { const inputPaths: any = JSON.parse(jsonInput); for (let i = 0; i < inputPaths.length; ++i) { - const input: string = inputPaths[i].path; + const input: string = inputPaths[i].path.replace(/\.temp\.js$/, "_.js"); const cacheOutputPath: string = inputPaths[i].cacheOutputPath; - const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, ".abc"); + const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, ".abc"); const singleCmd: any = `${cmd} "${cacheOutputPath}" -o "${cacheAbcFilePath}" --source-file "${input}"`; logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); try { @@ -50,9 +50,9 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { function es2abcByWorkers(jsonInput: string, cmd: string): Promise { const inputPaths: any = JSON.parse(jsonInput); for (let i = 0; i < inputPaths.length; ++i) { - const input: string = inputPaths[i].path; + const input: string = inputPaths[i].path.replace(/\.temp\.js$/, "_.js"); const cacheOutputPath: string = inputPaths[i].cacheOutputPath; - const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, ".abc"); + const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, ".abc"); const singleCmd: any = `${cmd} "${cacheOutputPath}" --output "${cacheAbcFilePath}" --source-file "${input}"`; logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); try { diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index cf67942..196d489 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -49,10 +49,10 @@ import { EXTNAME_JS_MAP, TS2ABC, ES2ABC, - TEMPORARY + TEMPORARY, + SUCCESS } from './pre_define'; -const firstFileEXT: string = '_.js'; const genAbcScript: string = 'gen_abc.js'; const genModuleAbcScript: string = 'gen_module_abc.js'; let output: string; @@ -176,8 +176,8 @@ export class GenAbcPlugin { // choose *.js if (output && path.extname(key) === EXTNAME_JS) { const newContent: string = compilation.assets[key].source(); - const keyPath: string = key.replace(/\.js$/, firstFileEXT); - writeFileSync(newContent, path.resolve(output, keyPath), key); + const keyPath: string = key.replace(/\.js$/, ".temp.js"); + writeFileSync(newContent, output, keyPath, key); } }); }); @@ -356,16 +356,15 @@ function processEntryToGenAbc(entryInfos: Map): void { } } -function writeFileSync(inputString: string, output: string, jsBundleFile: string): void { +function writeFileSync(inputString: string, buildPath: string, keyPath: string, jsBundleFile: string): void { + let output = path.resolve(buildPath, keyPath); let parent: string = path.join(output, '..'); if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { mkDir(parent); } - let buildParentPath: string = path.join(projectConfig.buildPath, '..'); - let sufStr: string = output.replace(buildParentPath, ''); let cacheOutputPath: string = ""; if (process.env.cachePath) { - cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, sufStr); + cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, keyPath); } else { cacheOutputPath = output; } @@ -474,6 +473,9 @@ function initAbcEnv() : string[] { } function invokeCluterModuleToAbc(): void { + if (projectConfig.isPreview) { + process.exitCode = SUCCESS; + } filterIntermediateModuleByHashJson(buildPathInfo, moduleInfos); filterModuleInfos.forEach(moduleInfo => { if (moduleInfo.isCommonJs) { @@ -599,6 +601,9 @@ function judgeModuleWorkersToGenAbc(callback): void { } function invokeWorkersToGenAbc(): void { + if (projectConfig.isPreview) { + process.exitCode = SUCCESS; + } let cmdPrefix: string = ''; let maxWorkerNumber: number = 3; @@ -647,9 +652,9 @@ function invokeWorkersToGenAbc(): void { } count_++; if (count_ === workerNumber) { - writeHashJson(); - clearGlobalInfo(); + // for preview of with incre compile if (projectConfig.isPreview) { + processExtraAssetForBundle(); console.info(red, 'COMPILE RESULT:SUCCESS ', reset); } } @@ -657,13 +662,14 @@ function invokeWorkersToGenAbc(): void { }); process.on('exit', (code) => { - intermediateJsBundle.forEach((item) => { - const input = item.path; - if (fs.existsSync(input)) { - fs.unlinkSync(input); - } - }); + // for build options + processExtraAssetForBundle(); }); + + // for preview of without incre compile + if (workerNumber === 0 && projectConfig.isPreview) { + processExtraAssetForBundle(); + } } } @@ -786,10 +792,8 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil jsonObject = JSON.parse(jsonFile); fileterIntermediateJsBundle = []; for (let i = 0; i < inputPaths.length; ++i) { - const input: string = inputPaths[i].path; - const abcPath: string = input.replace(/_.js$/, EXTNAME_ABC); const cacheOutputPath: string = inputPaths[i].cacheOutputPath; - const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, '.abc'); + const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, '.abc'); if (!fs.existsSync(cacheOutputPath)) { logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; @@ -801,10 +805,6 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil if (jsonObject[cacheOutputPath] === hashInputContentData && jsonObject[cacheAbcFilePath] === hashAbcContentData) { updateJsonObject[cacheOutputPath] = hashInputContentData; updateJsonObject[cacheAbcFilePath] = hashAbcContentData; - if (!fs.existsSync(abcPath)) { - mkdirsSync(path.dirname(abcPath)); - fs.copyFileSync(cacheAbcFilePath, abcPath); - } } else { fileterIntermediateJsBundle.push(inputPaths[i]); } @@ -819,10 +819,8 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil function writeHashJson(): void { for (let i = 0; i < fileterIntermediateJsBundle.length; ++i) { - const input:string = fileterIntermediateJsBundle[i].path; - const abcPath: string = input.replace(/_.js$/, EXTNAME_ABC); const cacheOutputPath: string = fileterIntermediateJsBundle[i].cacheOutputPath; - const cacheAbcFilePath: string = cacheOutputPath.replace(/\_.js$/, '.abc'); + const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, '.abc'); if (!fs.existsSync(cacheOutputPath) || !fs.existsSync(cacheAbcFilePath)) { logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; @@ -833,22 +831,6 @@ function writeHashJson(): void { hashJsonObject[cacheOutputPath] = hashInputContentData; hashJsonObject[cacheAbcFilePath] = hashAbcContentData; } - for (let i = 0; i < intermediateJsBundle.length; ++i) { - const abcFile: string = intermediateJsBundle[i].path.replace(/\_.js$/, ".abc"); - const cacheAbcFilePath: string = intermediateJsBundle[i].cacheOutputPath.replace(/\_.js$/, ".abc"); - if (!fs.existsSync(cacheAbcFilePath)) { - logger.error(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); - process.exitCode = FAIL; - break; - } - if (process.env.cachePath !== undefined) { - mkdirsSync(path.dirname(abcFile)); - fs.copyFileSync(cacheAbcFilePath, abcFile); - } - if (process.env.cachePath === undefined && fs.existsSync(intermediateJsBundle[i].path)) { - fs.unlinkSync(intermediateJsBundle[i].path); - } - } const hashFilePath: string = genHashJsonPath(buildPathInfo); if (hashFilePath.length === 0) { return; @@ -899,3 +881,32 @@ function checkNodeModules() { return true; } + +function copyFileCachePathToBuildPath() { + for (let i = 0; i < intermediateJsBundle.length; ++i) { + const abcFile: string = intermediateJsBundle[i].path.replace(/\.temp\.js$/, ".abc"); + const cacheOutputPath: string = intermediateJsBundle[i].cacheOutputPath; + const cacheAbcFilePath: string = intermediateJsBundle[i].cacheOutputPath.replace(/\.temp\.js$/, ".abc"); + if (!fs.existsSync(cacheAbcFilePath)) { + logger.error(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); + break; + } + let parent: string = path.join(abcFile, '..'); + if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { + mkDir(parent); + } + // for preview mode, cache path and old abc file both exist, should copy abc file for updating + if (process.env.cachePath !== undefined) { + fs.copyFileSync(cacheAbcFilePath, abcFile); + } + if (process.env.cachePath === undefined && fs.existsSync(cacheOutputPath)) { + fs.unlinkSync(cacheOutputPath); + } + } +} + +function processExtraAssetForBundle() { + writeHashJson(); + copyFileCachePathToBuildPath(); + clearGlobalInfo(); +} \ No newline at end of file -- Gitee From 39286d2ef4d5eb083f5eb7650d191484ff5b0d4b Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Fri, 23 Sep 2022 14:47:38 +0800 Subject: [PATCH 32/36] Modify log level of ark & Implement different page of incre compile Signed-off-by: zhangrengao Change-Id: I0886b7f4931250ec134173080a78d1cfbe6a13be --- compiler/src/gen_abc.ts | 6 +++--- compiler/src/gen_abc_plugin.ts | 22 ++++++++++++++++------ compiler/src/gen_module_abc.ts | 6 +++--- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/compiler/src/gen_abc.ts b/compiler/src/gen_abc.ts index 83f79f8..5aab49b 100644 --- a/compiler/src/gen_abc.ts +++ b/compiler/src/gen_abc.ts @@ -39,7 +39,7 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { try { childProcess.execSync(singleCmd); } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); + logger.debug(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); process.exit(FAIL); } } @@ -58,7 +58,7 @@ function es2abcByWorkers(jsonInput: string, cmd: string): Promise { try { childProcess.execSync(singleCmd); } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); + logger.debug(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); process.exit(FAIL); } } @@ -75,7 +75,7 @@ if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd' } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { es2abcByWorkers(process.env['inputs'], process.env['cmd']); } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); + logger.debug(red, `ETS:ERROR please set panda module`, reset); process.exit(FAIL); } process.exit(SUCCESS); diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 196d489..ff62499 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -186,6 +186,9 @@ export class GenAbcPlugin { if (projectConfig.compileMode === ESMODULE) { return; } + if (intermediateJsBundle.length === 0) { + return; + } buildPathInfo = output; judgeWorkersToGenAbc(invokeWorkersToGenAbc); }); @@ -364,7 +367,9 @@ function writeFileSync(inputString: string, buildPath: string, keyPath: string, } let cacheOutputPath: string = ""; if (process.env.cachePath) { - cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, keyPath); + let buildDirArr: string[] = projectConfig.buildPath.split(path.sep); + let abilityDir: string = buildDirArr[buildDirArr.length - 1]; + cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, abilityDir, keyPath); } else { cacheOutputPath = output; } @@ -379,7 +384,7 @@ function writeFileSync(inputString: string, buildPath: string, keyPath: string, cacheOutputPath = toUnixPath(cacheOutputPath); intermediateJsBundle.push({path: output, size: fileSize, cacheOutputPath: cacheOutputPath}); } else { - logger.error(red, `ETS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); + logger.debug(red, `ETS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); process.exitCode = FAIL; } } @@ -703,7 +708,7 @@ function filterIntermediateModuleByHashJson(buildPath: string, moduleInfos: Arra const input: string = moduleInfos[i].tempFilePath; const abcPath: string = moduleInfos[i].abcFilePath; if (!fs.existsSync(input)) { - logger.error(red, `ETS:ERROR ${input} is lost`, reset); + logger.debug(red, `ETS:ERROR ${input} is lost`, reset); process.exitCode = FAIL; break; } @@ -795,7 +800,7 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil const cacheOutputPath: string = inputPaths[i].cacheOutputPath; const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, '.abc'); if (!fs.existsSync(cacheOutputPath)) { - logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); + logger.debug(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; break; } @@ -848,7 +853,11 @@ function genHashJsonPath(buildPath: string): string { logger.debug(red, `ETS:ERROR hash path does not exist`, reset); return ''; } - return path.join(process.env.cachePath, hashFile); + let buildDirArr: string[] = projectConfig.buildPath.split(path.sep); + let abilityDir: string = buildDirArr[buildDirArr.length - 1]; + let hashJsonPath: string = path.join(process.env.cachePath, TEMPORARY, abilityDir, hashFile); + mkdirsSync(path.dirname(hashJsonPath)); + return hashJsonPath; } else if (buildPath.indexOf(ARK) >= 0) { const dataTmps: string[] = buildPath.split(ARK); const hashPath: string = path.join(dataTmps[0], ARK); @@ -888,7 +897,8 @@ function copyFileCachePathToBuildPath() { const cacheOutputPath: string = intermediateJsBundle[i].cacheOutputPath; const cacheAbcFilePath: string = intermediateJsBundle[i].cacheOutputPath.replace(/\.temp\.js$/, ".abc"); if (!fs.existsSync(cacheAbcFilePath)) { - logger.error(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); + logger.debug(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); + process.exitCode = FAIL; break; } let parent: string = path.join(abcFile, '..'); diff --git a/compiler/src/gen_module_abc.ts b/compiler/src/gen_module_abc.ts index 1426cee..9d0ba80 100644 --- a/compiler/src/gen_module_abc.ts +++ b/compiler/src/gen_module_abc.ts @@ -47,7 +47,7 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { try { childProcess.execSync(singleCmd); } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${inputsStr} to abc `, reset); + logger.debug(red, `ETS:ERROR Failed to convert file ${inputsStr} to abc `, reset); process.exit(FAIL); } } @@ -65,7 +65,7 @@ function es2abcByWorkers(jsonInput: string, cmd: string): Promise { try { childProcess.execSync(singleCmd); } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); + logger.debug(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); process.exit(FAIL); } } @@ -84,7 +84,7 @@ if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd' } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { es2abcByWorkers(process.env['inputs'], process.env['cmd']); } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); + logger.debug(red, `ETS:ERROR please set panda module`, reset); process.exit(FAIL); } process.exit(SUCCESS); -- Gitee From 3fa677a4b86306d29ba954ce6decc55d393e4ecb Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Fri, 23 Sep 2022 14:59:17 +0800 Subject: [PATCH 33/36] Fix max listeners of preview mode Signed-off-by: zhangrengao Change-Id: I178938ef0d0e65296c052ae8098924fb6f89b1a9 --- compiler/src/gen_abc_plugin.ts | 63 ++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index ff62499..8939bb5 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -18,6 +18,7 @@ import * as path from 'path'; import cluster from 'cluster'; import process from 'process'; import os from 'os'; +import events from 'events'; import Compiler from 'webpack/lib/Compiler'; import { logger } from './compile_info'; import { @@ -62,7 +63,8 @@ let isDebug: boolean = false; let arkDir: string; let nodeJs: string; -let delayCount = 0; +let previewCount: number = 0; +let compileCount: number = 0; interface File { path: string, size: number, @@ -147,11 +149,15 @@ export class GenAbcPlugin { removeDir(projectConfig.nodeModulesPath); } + // for preview mode max listeners + events.EventEmitter.defaultMaxListeners = 100; + compiler.hooks.compilation.tap('GenAbcPlugin', (compilation) => { if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { return; } buildPathInfo = output; + previewCount++; compilation.hooks.finishModules.tap('finishModules', handleFinishModules.bind(this)); }); @@ -190,7 +196,8 @@ export class GenAbcPlugin { return; } buildPathInfo = output; - judgeWorkersToGenAbc(invokeWorkersToGenAbc); + previewCount++; + invokeWorkersToGenAbc(); }); } } @@ -200,12 +207,12 @@ function clearGlobalInfo() { if (!projectConfig.isPreview) { intermediateJsBundle = []; moduleInfos = []; + entryInfos = new Map(); } fileterIntermediateJsBundle = []; filterModuleInfos = []; commonJsModuleInfos = []; ESMModuleInfos = []; - entryInfos = new Map(); hashJsonObject = {}; moduleHashJsonObject = {}; } @@ -340,7 +347,7 @@ function handleFinishModules(modules, callback): any { } }); - judgeModuleWorkersToGenAbc(invokeWorkersModuleToGenAbc); + invokeWorkersModuleToGenAbc(moduleInfos); processEntryToGenAbc(entryInfos); } @@ -513,6 +520,9 @@ function invokeCluterModuleToAbc(): void { totalWorkerNumber += esmWorkerNumber; let count_ = 0; + if (projectConfig.isPreview) { + cluster.removeAllListeners("exit"); + } cluster.on('exit', (worker, code, signal) => { if (code === FAIL || process.exitCode === FAIL) { process.exitCode = FAIL; @@ -522,8 +532,14 @@ function invokeCluterModuleToAbc(): void { if (count_ === totalWorkerNumber) { writeModuleHashJson(); clearGlobalInfo(); - if (projectConfig.isPreview) { + if (projectConfig.isPreview && compileCount < previewCount) { + compileCount++; console.info(blue, 'COMPILE RESULT:SUCCESS ', reset); + if (compileCount >= previewCount) { + return; + } + invokeWorkersModuleToGenAbc(moduleInfos); + processEntryToGenAbc(entryInfos); } } logger.debug(`worker ${worker.process.pid} finished`); @@ -583,28 +599,6 @@ function splitModulesByNumber(moduleInfos: Array, workerNumber: numb return result; } -function judgeWorkersToGenAbc(callback): void { - const workerNum: number = Object.keys(cluster.workers).length; - if (workerNum === 0) { - callback(); - return; - } else { - delayCount++; - setTimeout(judgeWorkersToGenAbc.bind(null, callback), 50); - } -} - -function judgeModuleWorkersToGenAbc(callback): void { - const workerNum: number = Object.keys(cluster.workers).length; - if (workerNum === 0) { - callback(moduleInfos); - return; - } else { - delayCount++; - setTimeout(judgeModuleWorkersToGenAbc.bind(null, callback), 50); - } -} - function invokeWorkersToGenAbc(): void { if (projectConfig.isPreview) { process.exitCode = SUCCESS; @@ -650,6 +644,10 @@ function invokeWorkersToGenAbc(): void { } let count_ = 0; + if (projectConfig.isPreview) { + process.removeAllListeners("exit"); + cluster.removeAllListeners("exit"); + } cluster.on('exit', (worker, code, signal) => { if (code === FAIL || process.exitCode === FAIL) { process.exitCode = FAIL; @@ -658,9 +656,14 @@ function invokeWorkersToGenAbc(): void { count_++; if (count_ === workerNumber) { // for preview of with incre compile - if (projectConfig.isPreview) { + if (projectConfig.isPreview && compileCount < previewCount) { + compileCount++; processExtraAssetForBundle(); console.info(red, 'COMPILE RESULT:SUCCESS ', reset); + if (compileCount >= previewCount) { + return; + } + invokeWorkersToGenAbc(); } } logger.debug(`worker ${worker.process.pid} finished`); @@ -765,7 +768,7 @@ function writeModuleHashJson(): void { return; } // fix bug of multi trigger - if (!projectConfig.isPreview || delayCount < 1) { + if (!projectConfig.isPreview || previewCount < 1) { fs.writeFileSync(hashFilePath, JSON.stringify(moduleHashJsonObject)); } } @@ -841,7 +844,7 @@ function writeHashJson(): void { return; } // fix bug of multi trigger - if (!projectConfig.isPreview || delayCount < 1) { + if (!projectConfig.isPreview || previewCount < 1) { fs.writeFileSync(hashFilePath, JSON.stringify(hashJsonObject)); } } -- Gitee From 7f8715eb62342fdbf8a8c1576d8ed8e6d531d347 Mon Sep 17 00:00:00 2001 From: zhangbingce Date: Sun, 25 Sep 2022 19:33:26 +0800 Subject: [PATCH 34/36] bugfix of crash in debug mode--monthly0816 Signed-off-by: zhangbingce --- compiler/src/compile_info.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index 16b2ba4..bcb03ac 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -107,7 +107,7 @@ export class ResultStates { if (map && map.size != 0) { let names: Array = Array.from(map).flat(); let sourcemapObj: any = JSON.parse(assets[key]._value); - sourcemapObj.names = names; + sourcemapObj.nameMap = names; assets[key]._value = JSON.stringify(sourcemapObj); } } -- Gitee From 08887b8d7aa8b10dd240d2ae7e5409250147506f Mon Sep 17 00:00:00 2001 From: lizhouze Date: Tue, 27 Sep 2022 16:28:13 +0800 Subject: [PATCH 35/36] lizhouze@huawei.com Signed-off-by: lizhouze --- compiler/main.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/compiler/main.js b/compiler/main.js index 3e9f93e..1d89a90 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -298,7 +298,15 @@ function readWorkerFile() { } const relativePath = path.relative(projectConfig.projectPath, worker); if (filterWorker(relativePath)) { - workerFileEntry[relativePath.replace(/\.(ts|js)$/, '').replace(/\\/g, '/')] = worker; + const workerKey = relativePath.replace(/\.(ts|js)$/, '').replace(/\\/g, '/'); + if (workerFileEntry[workerKey]) { + throw Error( + '\u001b[31m ERROR: The worker file cannot use the same file name: \n' + + workerFileEntry[workerKey] + '\n' + worker + '\u001b[39m' + ).message; + } else { + workerFileEntry[workerKey] = worker; + } } }); return workerFileEntry; -- Gitee From 60bbbee7f8b383fe93de834285785e555f6a0afa Mon Sep 17 00:00:00 2001 From: houhaoyu Date: Mon, 10 Oct 2022 16:13:13 +0800 Subject: [PATCH 36/36] houhaoyu@huawe.com dongtaohua Signed-off-by: houhaoyu Change-Id: I7e824d98bdc44827a9975965b7857613019298ab --- compiler/src/ets_checker.ts | 47 ++++++++++++---- compiler/src/process_component_build.ts | 45 +++++++++++----- compiler/src/process_custom_component.ts | 36 +++++++++---- compiler/src/process_ui_syntax.ts | 69 ++++++++++++++++++++---- 4 files changed, 154 insertions(+), 43 deletions(-) diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index 8326ecc..6dab74f 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -33,7 +33,8 @@ import { STYLE_ADD_DOUBLE_DOLLAR, $$, PROPERTIES_ADD_DOUBLE_DOLLAR, - $$_BLOCK_INTERFACE + $$_BLOCK_INTERFACE, + COMPONENT_EXTEND_DECORATOR } from './pre_define'; import { getName } from './process_component_build'; import { INNER_COMPONENT_NAMES } from './component_map'; @@ -43,6 +44,8 @@ import { CacheFileName, cache } from './compile_info'; +import { hasDecorator } from './utils'; +import { isExtendFunction, isOriginalExtend } from './process_ui_syntax'; function readDeaclareFiles(): string[] { const declarationsFileNames: string[] = []; @@ -85,6 +88,12 @@ function setCompilerOptions() { }); } +interface extendInfo { + start: number, + end: number, + compName: string +} + export function createLanguageService(rootFileNames: string[]): ts.LanguageService { setCompilerOptions(); const files: ts.MapLike<{ version: number }> = {}; @@ -97,8 +106,9 @@ export function createLanguageService(rootFileNames: string[]): ts.LanguageServi return undefined; } if (/(? { + const subStr: string = content.substring(item.start, item.end); + const insert: string = subStr.replace(/(\s)\$(\.)/g, (origin, item1, item2) => { + return item1 + item.compName + 'Instance' + item2; + }); + content = content.slice(0, item.start) + insert + content.slice(item.end); + }); + return content; +} + function getResolveModule(modulePath: string, type): ts.ResolvedModuleFull { return { resolvedFileName: modulePath, @@ -255,18 +278,18 @@ export const decoratorParamsCollection: Set = new Set(); export const extendCollection: Set = new Set(); export const importModuleCollection: Set = new Set(); -function checkUISyntax(source: string, fileName: string): void { +function checkUISyntax(source: string, fileName: string, extendFunctionInfo: extendInfo[]): void { if (/\.ets$/.test(fileName)) { if (path.basename(fileName) !== 'app.ets') { const sourceFile: ts.SourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS); - parseAllNode(sourceFile, sourceFile); + parseAllNode(sourceFile, sourceFile, extendFunctionInfo); props.push(...dollarCollection, ...decoratorParamsCollection, ...extendCollection); } } } -function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile): void { +function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile, extendFunctionInfo: extendInfo[]): void { if (ts.isStructDeclaration(node)) { if (node.members) { node.members.forEach(item => { @@ -295,7 +318,13 @@ function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile): void { }); } } - node.getChildren().forEach((item: ts.Node) => parseAllNode(item, sourceFileNode)); + if (ts.isFunctionDeclaration(node) && hasDecorator(node, COMPONENT_EXTEND_DECORATOR)) { + if (node.body && node.body.statements && node.body.statements.length && + !isOriginalExtend(node.body)) { + extendFunctionInfo.push({start: node.pos, end: node.end, compName: isExtendFunction(node)}); + } + } + node.getChildren().forEach((item: ts.Node) => parseAllNode(item, sourceFileNode, extendFunctionInfo)); } function traverseBuild(node: ts.Node, index: number): void { diff --git a/compiler/src/process_component_build.ts b/compiler/src/process_component_build.ts index 4a46a41..9b496a3 100644 --- a/compiler/src/process_component_build.ts +++ b/compiler/src/process_component_build.ts @@ -94,6 +94,8 @@ import { import { projectConfig } from '../main'; import { transformLog, contextGlobal } from './process_ui_syntax'; import { props } from './compile_info'; +import { CUSTOM_COMPONENT } from './pre_define'; + export function processComponentBuild(node: ts.MethodDeclaration, log: LogInfo[]): ts.MethodDeclaration { @@ -113,10 +115,10 @@ export function processComponentBuild(node: ts.MethodDeclaration, } export function processComponentBlock(node: ts.Block, isLazy: boolean, log: LogInfo[], - isTransition: boolean = false, isInnerBuilder: boolean = false): ts.Block { + isTransition: boolean = false, isInnerBuilder: boolean = false, parent: string = undefined): ts.Block { const newStatements: ts.Statement[] = []; processComponentChild(node, newStatements, log, - {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, isInnerBuilder); + {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, isInnerBuilder, parent); if (isLazy) { newStatements.unshift(createRenderingInProgress(true)); } @@ -214,7 +216,7 @@ let sourceNode: ts.SourceFile; export function processComponentChild(node: ts.Block | ts.SourceFile, newStatements: ts.Statement[], log: LogInfo[], supplement: supplementType = {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, - isInnerBuilder: boolean = false): void { + isInnerBuilder: boolean = false, parent: string = undefined): void { if (supplement.isAcceleratePreview) { newsupplement = supplement; const compilerOptions = ts.readConfigFile( @@ -229,11 +231,13 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme if (ts.isExpressionStatement(item)) { checkEtsComponent(item, log); const name: string = getName(item); - switch (getComponentType(item, log, name)) { + switch (getComponentType(item, log, name, parent)) { case ComponentType.innerComponent: - processInnerComponent(item, newStatements, log); + parent = name; + processInnerComponent(item, newStatements, log, parent); break; case ComponentType.customComponent: + parent = undefined; if (!newsupplement.isAcceleratePreview) { if (item.expression && ts.isEtsComponentExpression(item.expression) && item.expression.body) { const expressionResult: ts.ExpressionStatement = @@ -246,9 +250,11 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme } break; case ComponentType.forEachComponent: + parent = undefined; processForEachComponent(item, newStatements, log, isInnerBuilder); break; case ComponentType.customBuilderMethod: + parent = undefined; if (CUSTOM_BUILDER_METHOD.has(name)) { newStatements.push(addInnerBuilderParameter(item)); } else { @@ -256,8 +262,13 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme } break; case ComponentType.builderParamMethod: + parent = undefined; newStatements.push(addInnerBuilderParameter(item)); break; + case ComponentType.function: + parent = undefined; + newStatements.push(item); + break; } } else if (ts.isIfStatement(item)) { processIfStatement(item, newStatements, log, isInnerBuilder); @@ -360,7 +371,8 @@ function parseEtsComponentExpression(node: ts.ExpressionStatement): EtsComponent return { etsComponentNode: etsComponentNode, hasAttr: hasAttr }; } -function processInnerComponent(node: ts.ExpressionStatement, newStatements: ts.Statement[], log: LogInfo[]): void { +function processInnerComponent(node: ts.ExpressionStatement, newStatements: ts.Statement[], + log: LogInfo[], parent: string = undefined): void { const res: CreateResult = createComponent(node, COMPONENT_CREATE_FUNCTION); newStatements.push(res.newNode); const nameResult: NameResult = { name: null }; @@ -408,7 +420,8 @@ function processInnerComponent(node: ts.ExpressionStatement, newStatements: ts.S if (etsComponentResult.hasAttr) { bindComponentAttr(node, res.identifierNode, newStatements, log); } - processComponentChild(etsComponentResult.etsComponentNode.body, newStatements, log); + processComponentChild(etsComponentResult.etsComponentNode.body, newStatements, log, + {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, false, parent); } else { bindComponentAttr(node, res.identifierNode, newStatements, log); } @@ -1154,9 +1167,9 @@ function traverseStateStylesAttr(temp: any, statements: ts.Statement[], bindComponentAttr(ts.factory.createExpressionStatement( item.initializer.properties[0].initializer), identifierNode, statements, log, false, true); } else { - if (!(ts.isObjectLiteralExpression(item.initializer) && item.initializer.properties.length === 0)) { - validateStateStyleSyntax(temp, log); - } + if (!(ts.isObjectLiteralExpression(item.initializer) && item.initializer.properties.length === 0)) { + validateStateStyleSyntax(temp, log); + } } if (item.name) { statements.push(createViewStackProcessor(item, false)); @@ -1294,7 +1307,8 @@ enum ComponentType { customComponent, forEachComponent, customBuilderMethod, - builderParamMethod + builderParamMethod, + function } function isEtsComponent(node: ts.ExpressionStatement): boolean { @@ -1310,7 +1324,7 @@ function isEtsComponent(node: ts.ExpressionStatement): boolean { } function getComponentType(node: ts.ExpressionStatement, log: LogInfo[], - name: string): ComponentType { + name: string, parent: string): ComponentType { if (isEtsComponent(node)) { if (componentCollection.customComponents.has(name)) { return ComponentType.customComponent; @@ -1326,6 +1340,9 @@ function getComponentType(node: ts.ExpressionStatement, log: LogInfo[], } else if (builderParamObjectCollection.get(componentCollection.currentClassName) && builderParamObjectCollection.get(componentCollection.currentClassName).has(name)) { return ComponentType.builderParamMethod; + } else if (CUSTOM_BUILDER_METHOD.has(parent) && ts.isCallExpression(node.expression) && + ts.isIdentifier(node.expression.expression)) { + return ComponentType.function; } else if (!isAttributeNode(node)) { log.push({ type: LogType.ERROR, @@ -1346,7 +1363,7 @@ export function validateStateStyleSyntax(temp: any, log: LogInfo[]): void { function getEtsComponentExpression(node:ts.ExpressionStatement): ts.EtsComponentExpression { let current: any = node.expression; - while(current) { + while (current) { if (ts.isEtsComponentExpression(current)) { return current; } @@ -1356,7 +1373,7 @@ function getEtsComponentExpression(node:ts.ExpressionStatement): ts.EtsComponent } function checkEtsComponent(node: ts.ExpressionStatement, log: LogInfo[]): void { - const etsComponentExpression: ts.EtsComponentExpression = getEtsComponentExpression(node); + const etsComponentExpression: ts.EtsComponentExpression = getEtsComponentExpression(node); if (etsComponentExpression) { checkAllNode( etsComponentExpression, diff --git a/compiler/src/process_custom_component.ts b/compiler/src/process_custom_component.ts index 2b63cf0..6c69be9 100644 --- a/compiler/src/process_custom_component.ts +++ b/compiler/src/process_custom_component.ts @@ -364,17 +364,31 @@ function createFindChildById(id: string, name: string, isInnerBuilder: boolean = return ts.factory.createVariableStatement(undefined, ts.factory.createVariableDeclarationList( [ts.factory.createVariableDeclaration(ts.factory.createIdentifier( `${CUSTOM_COMPONENT_EARLIER_CREATE_CHILD}${id}`), undefined, ts.factory.createTypeReferenceNode( - ts.factory.createIdentifier(name)), ts.factory.createAsExpression(ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(isInnerBuilder ? - ts.factory.createParenthesizedExpression(ts.factory.createConditionalExpression( - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.QuestionToken), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createThis() - )) : ts.factory.createThis(), ts.factory.createIdentifier( - `${CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID}`)), undefined, [isInnerBuilder ? ts.factory.createCallExpression( - ts.factory.createIdentifier(GENERATE_ID), undefined, []) : ts.factory.createStringLiteral(id)]), - ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name))))], ts.NodeFlags.Let)); + ts.factory.createIdentifier(name)), + ts.factory.createConditionalExpression( + ts.factory.createParenthesizedExpression( + ts.factory.createBinaryExpression( + createConditionParent(isInnerBuilder), + ts.factory.createToken(ts.SyntaxKind.AmpersandAmpersandToken), + ts.factory.createPropertyAccessExpression( + createConditionParent(isInnerBuilder), + ts.factory.createIdentifier(CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID) + ))), ts.factory.createToken(ts.SyntaxKind.QuestionToken), + ts.factory.createAsExpression(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(createConditionParent(isInnerBuilder), + ts.factory.createIdentifier(`${CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID}`)), undefined, + [isInnerBuilder ? ts.factory.createCallExpression(ts.factory.createIdentifier(GENERATE_ID), + undefined, []) : ts.factory.createStringLiteral(id)]), + ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name))), + ts.factory.createToken(ts.SyntaxKind.ColonToken), + ts.factory.createIdentifier('undefined')))], ts.NodeFlags.Let)); +} + +function createConditionParent(isInnerBuilder: boolean): ts.ParenthesizedExpression | ts.ThisExpression { + return isInnerBuilder ? ts.factory.createParenthesizedExpression(ts.factory.createConditionalExpression( + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), ts.factory.createToken(ts.SyntaxKind.QuestionToken), + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), ts.factory.createToken(ts.SyntaxKind.ColonToken), + ts.factory.createThis())) : ts.factory.createThis(); } function createCustomComponentIfStatement(id: string, node: ts.ExpressionStatement, diff --git a/compiler/src/process_ui_syntax.ts b/compiler/src/process_ui_syntax.ts index 13b4b2c..3f0b604 100644 --- a/compiler/src/process_ui_syntax.ts +++ b/compiler/src/process_ui_syntax.ts @@ -152,7 +152,7 @@ export function processUISyntax(program: ts.Program, ut = false): Function { node.parameters.push(createParentParameter()); node = ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, - processComponentBlock(node.body, false, transformLog.errors, false, true)); + processComponentBlock(node.body, false, transformLog.errors, false, true, node.name.getText())); } else if (hasDecorator(node, COMPONENT_STYLES_DECORATOR)) { if (node.parameters.length === 0) { node = undefined; @@ -479,10 +479,15 @@ function processExtend(node: ts.FunctionDeclaration, log: LogInfo[]): ts.Functio const componentName: string = isExtendFunction(node); if (componentName && node.body && node.body.statements.length) { const statementArray: ts.Statement[] = []; + let bodynode: ts.Block; const attrSet: ts.CallExpression = node.body.statements[0].expression; - const changeCompName: ts.ExpressionStatement = ts.factory.createExpressionStatement(processExtendBody(attrSet)); - bindComponentAttr(changeCompName as ts.ExpressionStatement, - ts.factory.createIdentifier(componentName), statementArray, log); + if (isOriginalExtend(node.body)) { + const changeCompName: ts.ExpressionStatement = ts.factory.createExpressionStatement(processExtendBody(attrSet)); + bindComponentAttr(changeCompName as ts.ExpressionStatement, + ts.factory.createIdentifier(componentName), statementArray, log); + } else { + bodynode = ts.visitEachChild(node.body, traverseExtendExpression, contextGlobal); + } let extendFunctionName: string; if (node.name.getText().startsWith('__' + componentName + '__')) { extendFunctionName = node.name.getText(); @@ -492,18 +497,64 @@ function processExtend(node: ts.FunctionDeclaration, log: LogInfo[]): ts.Functio } return ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, ts.factory.createIdentifier(extendFunctionName), node.typeParameters, - node.parameters, node.type, ts.factory.updateBlock(node.body, statementArray)); + node.parameters, node.type, isOriginalExtend(node.body) ? + ts.factory.updateBlock(node.body, statementArray) : bodynode); + } + function traverseExtendExpression(node: ts.Node): ts.Node { + if (ts.isExpressionStatement(node) && isDollarNode(node)) { + const changeCompName: ts.ExpressionStatement = + ts.factory.createExpressionStatement(processExtendBody(node.expression, componentName)); + const statementArray: ts.Statement[] = []; + bindComponentAttr(changeCompName, ts.factory.createIdentifier(componentName), statementArray, []); + return ts.factory.createCallExpression( + ts.factory.createParenthesizedExpression(ts.factory.createFunctionExpression( + undefined, undefined, undefined, undefined, [], undefined, + ts.factory.createBlock(statementArray, true))), undefined, []); + } + return ts.visitEachChild(node, traverseExtendExpression, contextGlobal); + } +} + +export function isOriginalExtend(node: ts.Block): boolean { + let innerNode: ts.Node = node.statements[0]; + if (node.statements.length === 1 && ts.isExpressionStatement(innerNode)) { + while (innerNode.expression) { + innerNode = innerNode.expression; + } + if (ts.isIdentifier(innerNode) && innerNode.pos && innerNode.end && innerNode.pos === innerNode.end && + innerNode.escapedText.toString().match(/Instance$/)) { + return true; + } } + return false; } -function processExtendBody(node: ts.Node): ts.Expression { +function isDollarNode(node: ts.ExpressionStatement): boolean { + let innerNode: ts.Node = node; + while (innerNode.expression) { + innerNode = innerNode.expression; + } + if (ts.isIdentifier(innerNode) && innerNode.getText() === '$') { + return true; + } else { + return false; + } +} + +function processExtendBody(node: ts.Node, componentName?: string): ts.Expression { switch (node.kind) { case ts.SyntaxKind.CallExpression: - return ts.factory.createCallExpression(processExtendBody(node.expression), undefined, node.arguments); + return ts.factory.createCallExpression(processExtendBody(node.expression, componentName), + undefined, node.arguments); case ts.SyntaxKind.PropertyAccessExpression: - return ts.factory.createPropertyAccessExpression(processExtendBody(node.expression), node.name); + return ts.factory.createPropertyAccessExpression( + processExtendBody(node.expression, componentName), node.name); case ts.SyntaxKind.Identifier: - return ts.factory.createIdentifier(node.escapedText.toString().replace(INSTANCE, '')); + if (!componentName) { + return ts.factory.createIdentifier(node.escapedText.toString().replace(INSTANCE, '')); + } else { + return ts.factory.createIdentifier(componentName); + } } } -- Gitee