diff --git a/.gitignore b/.gitignore
index d58f67497c540582a67729200f77c7d83fe28d08..87a1ace51e09e12f655bfdb37eb3280ca2ca17c9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,6 +20,3 @@ build-tools/dts_parser/mochawesome-report
#忽略本地typescript离线包
build-tools/dts_parser/deps/*
-
-# 忽略vscode的配置文件
-.vscode/
\ No newline at end of file
diff --git a/BUILD.gn b/BUILD.gn
index c61cb4ce5e12ddb21b87dd9f100b79c5c243b75f..d347ff0abc61c3126ea58261ebf0f7920befc382 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -11,71 +11,20 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import("//build/config/components/ets_frontend/ets2abc_config.gni")
import("//build/ohos.gni")
import("//build/ohos/notice/notice.gni")
import("//build/ohos_var.gni")
-import("//build/templates/bpf/ohos_bpf_config.gni")
import("//build/templates/metadata/module_info.gni")
import("interface_config.gni")
# 全局变量方法见 https://gitee.com/openharmony/build/blob/master/docs/cmake%E8%BD%ACgn%E6%8C%87%E5%AF%BC%E6%96%87%E6%A1%A3.md#gn%E5%B8%B8%E7%94%A8%E7%9A%84%E5%86%85%E7%BD%AE%E5%8F%98%E9%87%8F
-# 特殊场景没有拷贝interface接口信息,强基之后源码仓api不能直接使用,需要进行处理
-exists_path_tools = "//interface/sdk-js/exists_path.py"
-exists_path_args = [
- "--path",
- rebase_path(interface_sdk_path_ets1, root_build_dir),
-]
-has_interface_file =
- exec_script(exists_path_tools, exists_path_args, "trim string")
-
-if (has_interface_file != "True") {
- arkts_sdk_config_parser = "//build/ohos/sdk/parse_interface_sdk.py"
- ohos_sdk_arkts_description_file =
- "//out/sdk-interface/ohos_sdk_pub_description_std.json"
- if (host_os == "mac") {
- node_path = "//prebuilts/build-tools/common/nodejs/node-v16.20.2-darwin-x64/bin/node"
- npm_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-darwin-x64/bin/npm"
- } else {
- node_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-linux-x64/bin/node"
- npm_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-linux-x64/bin/npm"
- }
- arkts_sdk_args = [
- "--sdk-description-file",
- rebase_path("//build/ohos/sdk/ohos_sdk_description_std.json",
- root_build_dir),
- "--root-build-dir",
- rebase_path("//", root_build_dir),
- "--node-js",
- rebase_path(node_path, root_build_dir),
- "--output-arkts-sdk-desc-file",
- rebase_path(ohos_sdk_arkts_description_file, root_build_dir),
- "--sdk-build-public",
- "${sdk_build_public}",
- "--sdk-build-arkts",
- "${sdk_build_arkts}",
- "--npm-path",
- rebase_path(npm_path, root_build_dir),
- ]
- exec_script(arkts_sdk_config_parser, arkts_sdk_args)
-}
-
template("ohos_copy_internal") {
forward_variables_from(invoker, "*")
iv_input = invoker.iv_input
- # fullSDK中api路径
- input_project_dir = interface_sdk_path_ets1
- if (sdk_type == "ets2") {
- input_project_dir = interface_sdk_path_ets2
- }
-
# 调用build/templates/common/copy.gni中的ohos_copy方法
- # 将处理完成的文件输出到中间产物对应位置 out/sdk/obj/interface/sdk-js/${target_name}
+ # 将处理完成的文件输出到中间产物对应位置 out/sdk/obj/interface/sdk-js/$target_name
ohos_copy(target_name) {
# 该脚本根据传入的remove文件进行input文件规则检查,过滤不需要的文件
# remove文件没有对应$target_name的属性 则全部输出
@@ -86,23 +35,18 @@ template("ohos_copy_internal") {
process_arguments = [
"--input",
rebase_path(iv_input, root_build_dir),
- "--project-dir",
- rebase_path(input_project_dir, root_build_dir),
- "--base-dir",
- rebase_path("//interface/sdk-js", root_build_dir),
"--remove",
rebase_path("//interface/sdk-js/remove_list.json", root_build_dir),
"--ispublic",
"${sdk_build_public}",
"--name",
- "${target_name}",
+ "$target_name",
]
# 执行脚本
sources = exec_script(process_script, process_arguments, "value")
- outputs =
- [ target_out_dir + "/${sdk_type}/${target_name}/{{source_file_part}}" ]
- module_source_dir = target_out_dir + "/${sdk_type}/${target_name}"
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
module_install_name = ""
}
}
@@ -110,28 +54,29 @@ template("ohos_copy_internal") {
# 主要api处理template
template("ohos_declaration_template") {
forward_variables_from(invoker, "*")
- _module_info_target = "/ohos_declaration/${sdk_type}/${target_name}_info"
-
- # fullSDK中api路径
- input_project_dir = interface_sdk_path_ets1
- if (sdk_type == "ets2") {
- input_project_dir = interface_sdk_path_ets2
- }
- input_api_dir = input_project_dir + "/api"
+ _module_info_target = "/ohos_declaration/${target_name}_info"
action_with_pydeps(target_name) {
- inputs = [ input_project_dir + "/api" ]
- outputs = [ root_out_dir + "/ohos_declaration/${sdk_type}/${target_name}" ]
+ inputs = [ "//interface/sdk-js/api" ]
+ outputs = [ root_out_dir + "/ohos_declaration/$target_name" ]
# 处理api文件下全部文件,过滤特定文件
script = "//interface/sdk-js/remove_internal.py"
+
+ # fullSDK中api路径
+ input_api_dir = "//interface/sdk-js/api"
+ if (sdk_build_public || product_name == "ohos-sdk") {
+ script = "//out/sdk-public/public_interface/sdk-js/remove_internal.py"
+
+ # publicSDK中api路径,经过./build-tools/delete_systemapi_plugin.js脚本处理过systemapi的接口
+ input_api_dir = "//out/sdk-public/public_interface/sdk-js/api"
+ }
args = [
"--input",
rebase_path(input_api_dir, root_build_dir),
"--output",
- rebase_path(
- root_out_dir + "/ohos_declaration/${sdk_type}/${target_name}/",
- root_build_dir),
+ rebase_path(root_out_dir + "/ohos_declaration/$target_name/",
+ root_build_dir),
]
if (defined(deps)) {
deps += [ ":$_module_info_target" ]
@@ -144,94 +89,76 @@ template("ohos_declaration_template") {
module_type = "jsdoc"
module_install_name = ""
module_name = _target_name
- module_source_dir =
- root_out_dir + "/ohos_declaration/${sdk_type}/$_target_name"
+ module_source_dir = root_out_dir + "/ohos_declaration/$_target_name"
install_enable = false
}
}
# ets/api执行脚本
ohos_declaration_template("ohos_declaration_ets") {
- sdk_type = "ets"
}
-# ets2/api执行脚本
-ohos_declaration_template("ohos_declaration_ets2") {
- sdk_type = "ets2"
+# ets/api执行脚本
+ohos_copy("common_api") {
+ sources = common_api_src
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
+ module_install_name = ""
}
# ets/api/@internal/full执行脚本
ohos_copy_internal("ets_internal_api") {
- sdk_type = "ets"
- iv_input = interface_sdk_path_ets1 + "/api/@internal/ets"
+ iv_input = "//interface/sdk-js/api/@internal/ets"
}
# ets/arkts执行脚本
-ohos_copy_internal("bundle_arkts") {
- sdk_type = "ets"
- iv_input = interface_sdk_path_ets1 + "/arkts"
-}
-
-# ets1.2/arkts执行脚本
-ohos_copy_internal("bundle_arkts_ets1.2") {
- sdk_type = "ets2"
- iv_input = interface_sdk_path_ets2 + "/arkts"
-}
-
-ohos_copy_internal("ets_internal_api2") {
- sdk_type = "ets2"
- iv_input = interface_sdk_path_ets2 + "/api/@internal/ets"
+ohos_copy("bundle_arkts") {
+ sources = [ "//interface/sdk-js/arkts" ]
+ outputs = [ target_out_dir + "/$target_name" ]
+ module_source_dir = target_out_dir + "/$target_name"
+ module_install_name = ""
+ license_file = "./LICENCE.md"
}
if (!sdk_build_public) {
# ets/build-tools/ets-loader/declarations脚本
ohos_copy("bundle_api") {
- sdk_type = "ets"
sources = [ "api/bundle/bundleStatusCallback.d.ts" ]
- outputs =
- [ target_out_dir + "/${sdk_type}/${target_name}/{{source_file_part}}" ]
- module_source_dir = target_out_dir + "/${sdk_type}/${target_name}"
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
module_install_name = ""
}
}
# ets/component执行脚本
ohos_copy_internal("ets_component") {
- sdk_type = "ets"
- iv_input = interface_sdk_path_ets1 + "/api/@internal/component/ets"
-}
-
-# ets1.2/arkui/component执行脚本
-ohos_copy_internal("ets_component2") {
- sdk_type = "ets2"
- iv_input = "//out/arkui_transformer_api"
+ iv_input = "//interface/sdk-js/api/@internal/component/ets"
}
# ets/kits执行脚本
-ohos_copy_internal("bundle_kits") {
- sdk_type = "ets"
- iv_input = interface_sdk_path_ets1 + "/kits"
-}
-
-# ets2/kits执行脚本
-ohos_copy_internal("bundle_kits2") {
- sdk_type = "ets2"
- iv_input = interface_sdk_path_ets2 + "/kits"
+ohos_copy("bundle_kits") {
+ if (sdk_build_public || product_name == "ohos-sdk") {
+ sources = [ "//out/sdk-public/public_interface/sdk-js/kits" ]
+ } else {
+ sources = [ "//interface/sdk-js/kits" ]
+ }
+ outputs = [ target_out_dir + "/$target_name" ]
+ module_source_dir = target_out_dir + "/$target_name"
+ module_install_name = ""
}
# js/api执行脚本
ohos_declaration_template("ohos_declaration_common") {
- sdk_type = "ets"
}
# js/api/@internal/full执行脚本
ohos_copy_internal("internal_full") {
- iv_input = interface_sdk_path_ets1 + "/api/common/full"
+ iv_input = "//interface/sdk-js/api/common/full"
}
# js/api/@internal/lite执行脚本呢
ohos_copy_internal("internal_lite") {
- iv_input = interface_sdk_path_ets1 + "/api/common/lite"
+ iv_input = "//interface/sdk-js/api/common/lite"
}
# js/api/config执行脚本
@@ -240,8 +167,8 @@ ohos_copy("config") {
"api/config/css",
"api/config/hml",
]
- outputs = [ target_out_dir + "/${target_name}/{{source_file_part}}" ]
- module_source_dir = target_out_dir + "/${target_name}"
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
module_install_name = ""
}
@@ -252,126 +179,15 @@ ohos_copy("form_declaration") {
"api/form/css",
"api/form/hml",
]
- outputs = [ target_out_dir + "/${target_name}/{{source_file_part}}" ]
- module_source_dir = target_out_dir + "/${target_name}"
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
module_install_name = ""
}
# toolchains/syscapcheck执行脚本
ohos_copy("syscap_check") {
sources = [ "api/syscapCheck/sysCapSchema.json" ]
- outputs = [ target_out_dir + "/${target_name}/{{source_file_part}}" ]
- module_source_dir = target_out_dir + "/${target_name}"
+ outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ]
+ module_source_dir = target_out_dir + "/$target_name"
module_install_name = ""
}
-
-action("ohos_ets_api_tmp") {
- script = "//interface/sdk-js/ohos_copy_ets.py"
-
- args = [
- "--input",
- rebase_path("//interface/sdk-js/api"),
- "--output",
- rebase_path("$ohos_ets_api_tmp_path"),
- "--type",
- "ets2",
- "--source-root-dir",
- rebase_path("//"),
- "--node-js",
- rebase_path(nodejs, root_build_dir),
- ]
-
- outputs = [ "$ohos_ets_api_tmp_path" ]
-}
-
-action("ohos_ets_arkts_tmp") {
- script = "//interface/sdk-js/ohos_copy_ets.py"
-
- args = [
- "--input",
- rebase_path("//interface/sdk-js/arkts"),
- "--output",
- rebase_path("$ohos_ets_arkts_tmp_path"),
- "--type",
- "ets2",
- "--source-root-dir",
- rebase_path("//"),
- "--node-js",
- rebase_path(nodejs, root_build_dir),
- ]
-
- outputs = [ "$ohos_ets_arkts_tmp_path" ]
-}
-
-action("ohos_ets_kits_tmp") {
- script = "//interface/sdk-js/ohos_copy_ets.py"
-
- args = [
- "--input",
- rebase_path("//interface/sdk-js/kits"),
- "--output",
- rebase_path("$ohos_ets_kits_tmp_path"),
- "--type",
- "ets2",
- "--source-root-dir",
- rebase_path("//"),
- "--node-js",
- rebase_path(nodejs, root_build_dir),
- ]
-
- outputs = [ "$ohos_ets_kits_tmp_path" ]
-}
-
-action("ohos_ets_api_arkui_tmp") {
- deps = [ ":ohos_ets_api_tmp" ]
- script = "//interface/sdk-js/arkui_transformer.py"
-
- if (host_os == "mac") {
- node_path = "//prebuilts/build-tools/common/nodejs/node-v16.20.2-darwin-x64/bin/node"
- npm_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-darwin-x64/bin/npm"
- } else {
- node_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-linux-x64/bin/node"
- npm_path =
- "//prebuilts/build-tools/common/nodejs/node-v16.20.2-linux-x64/bin/npm"
- }
- args = [
- "--input",
- rebase_path(ohos_ets_api_tmp_path + "/@internal/component/ets",
- root_build_dir),
- "--output",
- rebase_path(ohos_ets_api_tmp_path + "/arkui/component", root_build_dir),
- "--source_root_dir",
- rebase_path("//", root_build_dir),
- "--npm-path",
- rebase_path(npm_path, root_build_dir),
- "--node-js",
- rebase_path(node_path, root_build_dir),
- ]
- outputs = [ "$ohos_ets_api_arkui_tmp_path" ]
-}
-
-ohos_copy("ohos_ets_arkts") {
- deps = [ ":ohos_ets_arkts_tmp" ]
- sources = [ ohos_ets_arkts_tmp_path ]
- outputs = [ ohos_ets_arkts_path ]
- part_name = "sdk"
- subsystem_name = "sdk"
-}
-
-ohos_copy("ohos_ets_kits") {
- deps = [ ":ohos_ets_kits_tmp" ]
- sources = [ ohos_ets_kits_tmp_path ]
- outputs = [ ohos_ets_kits_path ]
- part_name = "sdk"
- subsystem_name = "sdk"
-}
-
-ohos_copy("ohos_ets_api") {
- deps = [ ":ohos_ets_api_tmp" ]
- sources = [ ohos_ets_api_tmp_path ]
- outputs = [ ohos_ets_api_path ]
- part_name = "sdk"
- subsystem_name = "sdk"
-}
diff --git a/OAT.xml b/OAT.xml
index c3931061183e0fd0f53acbf4837b9a9681017b46..2ec3b5633794929f80ae462e639c48d22876e1ec 100644
--- a/OAT.xml
+++ b/OAT.xml
@@ -86,12 +86,6 @@ Note:If the text contains special characters, please escape them according to th
-
-
-
-
-
-
diff --git a/arkui_transformer.py b/arkui_transformer.py
deleted file mode 100755
index 0d00f1b74d9927acec37aaab6dc2df0be6e4567d..0000000000000000000000000000000000000000
--- a/arkui_transformer.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2025 Huawei Device Co., Ltd.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import argparse
-import sys
-import os
-import shutil
-import subprocess
-
-PARSE_ETS2_API = "interface/sdk-js/build-tools/arkui_transformer"
-PACKAGE_PATH = "build/arkui_transformer.js"
-
-
-def compile_package(options):
- tool_path = os.path.abspath(os.path.join(options.source_root_dir, PARSE_ETS2_API))
- npm = os.path.abspath(options.npm_path)
- package_path = os.path.abspath(os.path.join(options.source_root_dir, PARSE_ETS2_API, PACKAGE_PATH))
- nodejs = os.path.abspath(options.node_js)
- input_dir = os.path.abspath(options.input)
- output = os.path.abspath(options.output)
- custom_env = {
- 'PATH': f"{os.path.dirname(os.path.abspath(options.node_js))}:{os.environ.get('PATH')}",
- 'NODE_HOME': os.path.dirname(os.path.abspath(options.node_js)),
- }
-
- process = subprocess.run([npm, "run", "compile:arkui"], env=custom_env, cwd=tool_path, shell=False)
-
- if os.path.exists(package_path):
- p = subprocess.run([nodejs, package_path, "--input-dir", input_dir, "--target-dir", output], cwd=tool_path, shell=False)
- else:
- print("arkui_transformer: tool path does not exist")
-
- return process
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('--input', required=True)
- parser.add_argument('--output', required=True)
- parser.add_argument('--source_root_dir', required=True)
- parser.add_argument('--npm-path', required=True)
- parser.add_argument('--node-js', required=True)
- options = parser.parse_args()
- compile_package(options)
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/build-tools/arkui_transformer/.gitignore b/build-tools/arkui_transformer/.gitignore
deleted file mode 100644
index d16386367f7cd7dd3c1842c484239e9e82a25efc..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-build/
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/README.md b/build-tools/arkui_transformer/README.md
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/build-tools/arkui_transformer/config/arkui_config.json b/build-tools/arkui_transformer/config/arkui_config.json
deleted file mode 100644
index 890f2d737fd052f0b1f76ff5a6b231b7ea6bc02e..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/config/arkui_config.json
+++ /dev/null
@@ -1,134 +0,0 @@
-{
- "components": [
- "AbilityComponent",
- "AlphabetIndexer",
- "AnalogClock",
- "Animator",
- "ArcList",
- "ArcListItem",
- "Badge",
- "Blank",
- "Button",
- "Calendar",
- "CalendarPicker",
- "Camera",
- "Canvas",
- "Checkbox",
- "CheckboxGroup",
- "Circle",
- "ColorPicker",
- "ColorPickerDialog",
- "Column",
- "ColumnSplit",
- "ContentSlot",
- "Counter",
- "DataPanel",
- "DatePicker",
- "Divider",
- "DotMatrix",
- "EffectComponent",
- "Ellipse",
- "EmbeddedComponent",
- "Flex",
- "FolderStack",
- "FormComponent",
- "FormLink",
- "Gauge",
- "GeometryView",
- "Grid",
- "GridItem",
- "GridContainer",
- "Hyperlink",
- "Image",
- "ImageAnimator",
- "IndicatorComponent",
- "LazyVGridLayout",
- "Line",
- "LinearIndicator",
- "List",
- "ListItem",
- "ListItemGroup",
- "LoadingProgress",
- "Marquee",
- "MediaCachedImage",
- "Menu",
- "MenuItem",
- "MenuItemGroup",
- "MovingPhotoView",
- "NavDestination",
- "NavRouter",
- "Navigation",
- "Navigator",
- "NodeContainer",
- "Option",
- "Panel",
- "Particle",
- "Path",
- "PatternLock",
- "Piece",
- "PlatformView",
- "PluginComponent",
- "Polygon",
- "Polyline",
- "Progress",
- "QRCode",
- "Radio",
- "Rating",
- "Rect",
- "Refresh",
- "RelativeContainer",
- "RemoteWindow",
- "RootScene",
- "Row",
- "RowSplit",
- "RichText",
- "Screen",
- "Scroll",
- "ScrollBar",
- "Search",
- "Section",
- "Select",
- "Shape",
- "Sheet",
- "SideBarContainer",
- "Slider",
- "Span",
- "Stack",
- "Stepper",
- "StepperItem",
- "Swiper",
- "SymbolGlyph",
- "SymbolSpan",
- "TabContent",
- "Tabs",
- "Text",
- "TextPicker",
- "TextClock",
- "TextArea",
- "TextInput",
- "TextTimer",
- "TimePicker",
- "Toggle",
- "Video",
- "Web",
- "WindowScene",
- "WithTheme",
- "XComponent",
- "GridRow",
- "GridCol",
- "WaterFlow",
- "FlowItem",
- "ImageSpan",
- "LocationButton",
- "PasteButton",
- "SaveButton",
- "UIExtensionComponent",
- "IsolatedComponent",
- "RichEditor",
- "Component3D",
- "ContainerSpan",
- "ArcSwiper",
- "ArcScrollBar",
- "ArcAlphabetIndexer"
- ]
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/config/arkui_m3_white_list.json b/build-tools/arkui_transformer/config/arkui_m3_white_list.json
deleted file mode 100644
index ea4926b92b9da7869cf7dd2af99147aa93edcd8f..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/config/arkui_m3_white_list.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "useM3": [
- ]
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/config/none_arkui_files.json b/build-tools/arkui_transformer/config/none_arkui_files.json
deleted file mode 100644
index 489bd127ec7552a3ae4121b907ab015a6908d9b3..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/config/none_arkui_files.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "files": [
- "component3d"
- ]
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/package.json b/build-tools/arkui_transformer/package.json
deleted file mode 100644
index e7f81dda98b2965a0bfdf72d6211fb4e0e902735..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/package.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "name": "arkui_transformer",
- "version": "1.0.0",
- "main": "build/arkui_transformer.js",
- "scripts": {
- "compile:arkui": "rollup -c",
- "transform:arkui": "npm run compile:arkui && node . --input-dir ../../etstest --target-dir ../../api/arkui/component.test/",
- "transform:arkui:m3": "npm run compile:arkui && node . --input-dir ../../etstest --target-dir ../../api/arkui/component.test/ --use-memo-m3"
- },
- "author": "",
- "license": "ISC",
- "description": "",
- "dependencies": {
- "@types/node": "^18.0.0",
- "commander": "^10.0.0",
- "typescript": "^4.9.5"
- },
- "devDependencies": {
- "@rollup/plugin-node-resolve": "^16.0.1",
- "@rollup/plugin-typescript": "^12.1.2",
- "rollup": "^3.29.5",
- "tslib": "^2.8.1"
- }
-}
diff --git a/build-tools/arkui_transformer/pattern/arkts_component_decl.pattern b/build-tools/arkui_transformer/pattern/arkts_component_decl.pattern
deleted file mode 100644
index ae4a5689f43d30a2cb1166c2f8a791dd5f1b0275..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/pattern/arkts_component_decl.pattern
+++ /dev/null
@@ -1,8 +0,0 @@
-%COMPONENT_COMMENT%
-@memo
-@ComponentBuilder
-export declare function %COMPONENT_NAME%(
- %FUNCTION_PARAMETERS%
- @memo
- content_?: () => void,
-): UI%COMPONENT_NAME%Attribute
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/pattern/arkts_component_decl_m3.pattern b/build-tools/arkui_transformer/pattern/arkts_component_decl_m3.pattern
deleted file mode 100644
index c4b09a33d71ddcf0da96cb8120b149116a266cf0..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/pattern/arkts_component_decl_m3.pattern
+++ /dev/null
@@ -1,8 +0,0 @@
-%COMPONENT_COMMENT%
-@memo
-@ComponentBuilder
-export declare function %COMPONENT_NAME%(
- %FUNCTION_PARAMETERS%
- @memo
- content_?: () => void,
-): %COMPONENT_NAME%Attribute
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/rollup.config.mjs b/build-tools/arkui_transformer/rollup.config.mjs
deleted file mode 100644
index 04b82d532e98612df8e444818b07d1916ce4cdb8..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/rollup.config.mjs
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import typescript from '@rollup/plugin-typescript';
-import { nodeResolve } from '@rollup/plugin-node-resolve';
-
-export default {
- input: 'src/arkui_transformer.ts',
- output: {
- file: 'build/arkui_transformer.js',
- format: 'commonjs',
- sourcemap: true,
- banner: [
- "#!/usr/bin/env node",
- APACHE_LICENSE_HEADER()
- ].join("\n"),
- },
- external: ["commander", "typescript"],
- plugins: [
- typescript({
- tsconfig: './tsconfig.json'
- }),
- nodeResolve({
- extensions: ['.ts'],
- preferBuiltins: true
- }),
- ]
-};
-
-
-function APACHE_LICENSE_HEADER() {
- return `
-/**
-* @license
-* Copyright (c) ${new Date().getUTCFullYear()} Huawei Device Co., Ltd.
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-`
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/src/add_export.ts b/build-tools/arkui_transformer/src/add_export.ts
deleted file mode 100644
index f7143542737708332c917bebffa3fb4ca1b53d3b..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/add_export.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import * as ts from "typescript";
-
-export function exportAllTransformer(): ts.TransformerFactory {
- return (context) => {
- return (sourceFile) => {
- const exportModifier = ts.factory.createModifier(ts.SyntaxKind.ExportKeyword);
-
- const visitor = (node: ts.Node): ts.Node => {
- if (isTopLevelExportable(node)) {
- const modifiers = ts.getModifiers(node as ts.HasModifiers) || [];
- if (!hasExportModifier(modifiers)) {
- const newNode = updateNodeWithExport(node, modifiers, exportModifier);
- return newNode || node;
- }
- }
- return ts.visitEachChild(node, visitor, context);
- };
-
- return ts.visitNode(sourceFile, visitor);
- };
- };
-}
-
-function isTopLevelExportable(node: ts.Node): boolean {
- return ts.isFunctionDeclaration(node) ||
- ts.isClassDeclaration(node) ||
- ts.isVariableStatement(node) ||
- ts.isInterfaceDeclaration(node) ||
- ts.isTypeAliasDeclaration(node) ||
- ts.isEnumDeclaration(node) ||
- ts.isModuleDeclaration(node);
-}
-
-function hasExportModifier(modifiers: readonly ts.Modifier[]): boolean {
- return modifiers.some(m => m.kind === ts.SyntaxKind.ExportKeyword);
-}
-
-function hasDeclareModifier(modifiers: readonly ts.Modifier[]): boolean {
- return modifiers.some(m => m.kind === ts.SyntaxKind.DeclareKeyword);
-}
-
-function handleClassModifiers(existingModifiers: readonly ts.Modifier[]): ts.Modifier[] {
- const newModifiers = [...existingModifiers]
- if (!hasDeclareModifier(existingModifiers)) {
- newModifiers.unshift(ts.factory.createModifier(ts.SyntaxKind.DeclareKeyword));
- }
- if (!hasExportModifier(existingModifiers)) {
- newModifiers.unshift(ts.factory.createModifier(ts.SyntaxKind.ExportKeyword));
- }
- return newModifiers;
-}
-
-function updateNodeWithExport(
- node: ts.Node,
- existingModifiers: readonly ts.Modifier[],
- exportModifier: ts.Modifier
-): ts.Node {
- const newModifiers = [exportModifier, ...existingModifiers];
-
- switch (node.kind) {
- case ts.SyntaxKind.VariableStatement:
- return ts.factory.updateVariableStatement(
- node as ts.VariableStatement,
- newModifiers,
- (node as ts.VariableStatement).declarationList
- );
-
- case ts.SyntaxKind.FunctionDeclaration:
- const func = node as ts.FunctionDeclaration;
- return ts.factory.updateFunctionDeclaration(
- func,
- newModifiers,
- func.asteriskToken,
- func.name,
- func.typeParameters,
- func.parameters,
- func.type,
- func.body
- );
-
- case ts.SyntaxKind.ClassDeclaration:
- const cls = node as ts.ClassDeclaration;
- return ts.factory.updateClassDeclaration(
- cls,
- handleClassModifiers(existingModifiers),
- cls.name,
- cls.typeParameters,
- cls.heritageClauses,
- cls.members
- );
-
- case ts.SyntaxKind.InterfaceDeclaration:
- const intf = node as ts.InterfaceDeclaration;
- return ts.factory.updateInterfaceDeclaration(
- intf,
- newModifiers,
- intf.name,
- intf.typeParameters,
- intf.heritageClauses,
- intf.members
- );
-
- case ts.SyntaxKind.TypeAliasDeclaration:
- const type = node as ts.TypeAliasDeclaration;
- return ts.factory.updateTypeAliasDeclaration(
- type,
- newModifiers.filter(m => m.kind !== ts.SyntaxKind.DeclareKeyword),
- type.name,
- type.typeParameters,
- type.type
- );
-
- case ts.SyntaxKind.EnumDeclaration:
- const enm = node as ts.EnumDeclaration;
- return ts.factory.updateEnumDeclaration(
- enm,
- newModifiers,
- enm.name,
- enm.members
- );
-
- case ts.SyntaxKind.ModuleDeclaration:
- const mod = node as ts.ModuleDeclaration;
- return ts.factory.updateModuleDeclaration(
- mod,
- newModifiers,
- mod.name,
- mod.body
- );
-
- default:
- return node;
- }
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/src/add_import.ts b/build-tools/arkui_transformer/src/add_import.ts
deleted file mode 100644
index daf313dd4eb52be669777639ee4d1ce330f77a3f..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/add_import.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import * as ts from "typescript";
-import uiconfig from './arkui_config_util';
-import path from 'path';
-import { ComponentFile } from "./component_file";
-
-export function addImportTransformer(): ts.TransformerFactory {
- return (context) => {
- return (sourceFile) => {
- const [updatedSource, targetImport] = createTargetImport(sourceFile, context);
- const insertPosition = findBestInsertPosition(updatedSource);
-
- const newStatements = [
- ...updatedSource.statements.slice(0, insertPosition),
- ...targetImport,
- ...updatedSource.statements.slice(insertPosition)
- ];
-
- return ts.factory.updateSourceFile(
- updatedSource,
- newStatements,
- updatedSource.isDeclarationFile,
- updatedSource.referencedFiles,
- updatedSource.typeReferenceDirectives,
- updatedSource.hasNoDefaultLib,
- updatedSource.libReferenceDirectives
- );
- };
- };
-}
-
-function findBestInsertPosition(sourceFile: ts.SourceFile): number {
- let lastImportIndex = -1;
- sourceFile.statements.forEach((stmt, index) => {
- if (ts.isImportDeclaration(stmt)) {
- lastImportIndex = index;
- }
- });
-
- if (lastImportIndex !== -1) {
- return lastImportIndex + 1;
- }
-
- return 0;
-}
-
-function handleImportDeclaration(node: ts.ImportDeclaration): [ts.Node, boolean] {
- if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
- const moduleText = node.moduleSpecifier.text;
- const haveCommon = moduleText.includes("common");
- if (uiconfig.isComponentFile(moduleText)) {
- const importClause = node.importClause;
- const uiprefixImports: Set = new Set
- if (importClause && ts.isImportClause(importClause) && importClause.namedBindings && ts.isNamedImports(importClause.namedBindings)) {
- const namedImports = importClause.namedBindings.elements;
- const existingImports = namedImports.map((element) => element.name.text);
- existingImports.forEach((element) => {
- if (uiconfig.isUIHeritage(element)) {
- uiconfig.useMemoM3 || uiprefixImports.add(`UI${element}`)
- }
- })
- if (moduleText.includes("common")) {
- uiprefixImports.add('AttributeModifier');
- uiprefixImports.add('CommonMethod');
- uiconfig.useMemoM3 || uiprefixImports.add('UICommonMethod');
- }
-
- const addedImports = Array.from(uiprefixImports).filter((im) => !existingImports.includes(im));
- const pureModule = path.basename(moduleText)
- const updatedName = ComponentFile.snake2Camel(pureModule, true)
- const updatedModuleSpecifier = ts.factory.createStringLiteral(moduleText.replace(pureModule, updatedName));
- const updatedNode = ts.factory.updateImportDeclaration(
- node,
- undefined,
- ts.factory.updateImportClause(
- importClause,
- importClause.isTypeOnly,
- importClause.name,
- ts.factory.updateNamedImports(
- importClause.namedBindings,
- [
- ...namedImports,
- ...addedImports.map(im => { return ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(im)) }),
- ]
- )
- ),
- updatedModuleSpecifier,
- undefined
- );
- return [updatedNode, haveCommon]
- } else {
- throw new Error("Unexpected import clause structure");
- }
- }
- }
- return [node, false];
-}
-
-function createTargetImport(sourceFile: ts.SourceFile, context: ts.TransformationContext): [ts.SourceFile, ts.ImportDeclaration[]] {
- const targetImport: ts.ImportDeclaration[] = []
-
- const memoImport = ts.factory.createImportDeclaration(
- undefined,
- ts.factory.createImportClause(
- false,
- undefined,
- ts.factory.createNamedImports([
- ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier("memo")),
- ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier("ComponentBuilder"))
- ])
- ),
- ts.factory.createStringLiteral("./../stateManagement/runtime")
- );
- targetImport.push(memoImport)
-
- let haveCommonImportFlag = false;
- const newSource = ts.visitEachChild(sourceFile, (node) => {
- if (ts.isImportDeclaration(node)) {
- const [transNode, flag] = handleImportDeclaration(node)!;
- haveCommonImportFlag = flag ? flag : haveCommonImportFlag
- return transNode
- }
- return node;
- }, context)
-
- if (!haveCommonImportFlag) {
- const commonImport = ts.factory.createImportDeclaration(
- undefined,
- ts.factory.createImportClause(
- false,
- undefined,
- ts.factory.createNamedImports([
- ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier("AttributeModifier")),
- ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier("CommonMethod")),
- ...(uiconfig.useMemoM3 !== true ? [
- ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier("UICommonMethod"))
- ] : [])
- ])
- ),
- ts.factory.createStringLiteral("./common"),
- undefined
- )
- targetImport.push(commonImport)
- }
- return [newSource, targetImport]
-}
diff --git a/build-tools/arkui_transformer/src/arkui_config_util.ts b/build-tools/arkui_transformer/src/arkui_config_util.ts
deleted file mode 100644
index b0b2d91c044d047d44101ad43efcdbecac8de310..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/arkui_config_util.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { OptionValues } from "commander"
-import * as fs from "fs"
-
-import path from "path"
-
-export interface ArkUIConfig {
- components: Array
-}
-
-interface NoneUIConfig {
- files: Array
-}
-
-interface UseM3Config {
- useM3: Array
-}
-
-export class ArkUIConfigUtil {
- static instance: ArkUIConfigUtil = new ArkUIConfigUtil
- constructor() {
- this.config = JSON.parse(fs.readFileSync("./config/arkui_config.json", 'utf-8'))
- this.config.components.forEach(c => {
- this.componentSet.add(c)
- })
- this.noneUIconfig = JSON.parse(fs.readFileSync("./config/none_arkui_files.json", 'utf-8'))
- this.noneUIconfig.files.forEach(f => {
- this.noneUIFileSet.add(f)
- })
- const useM3Config: UseM3Config = JSON.parse(fs.readFileSync("./config/arkui_m3_white_list.json", 'utf-8'))
- this._useM3Files = useM3Config.useM3
- }
- // ui components
- private config: ArkUIConfig
- // None ui files
- private noneUIconfig: NoneUIConfig
- private noneUIFileSet: Set = new Set
- // Full set of component, should be manually mantained by config file
- private componentSet: Set = new Set
- // Component superclass set, generated by traversing the declartion AST
- private componentSuperclassSet: Set = new Set
- // All class/interface name related to component attribute heritage
- private componentHeritage: Set = new Set
- // All implement relationship of component heritage
- private componentHerirageRelation: Map = new Map
- // All component filename
- private componentFiles: Set = new Set
- private file2Attrbiute: Map = new Map
- private shouldNotHaveAttributeModifier: Set = new Set
- private _useMemoM3: boolean = false
- private _useM3Files: Array = []
- private _configPath: string = ''
- get useMemoM3(): boolean {
- return this._useMemoM3
- }
-
- set useMemoM3(value: boolean) {
- this._useMemoM3 = value
- }
-
- withM3File(file: string): boolean {
- if (this._useMemoM3) {
- return true;
- }
- return this._useM3Files.includes(path.basename(file))
- }
-
- get isHdsComponent(): boolean {
- return this._configPath.length > 0
- }
-
- public loadConfig(config: OptionValues): void {
- if (config.useMemoM3) {
- this._useMemoM3 = true
- }
-
- if (config.configPath != undefined && config.configPath != '') {
- this._configPath = config.configPath
- // exception process: avoid non-existing given path
- try {
- this.config = JSON.parse(fs.readFileSync(this._configPath + "/hds_uicomponents.json", 'utf-8'))
- this.componentSet.clear()
- this.config.components.forEach(c => {
- this.componentSet.add(c)
- })
- this.noneUIconfig = JSON.parse(fs.readFileSync(this._configPath + "/hds_non_uicomponents.json", 'utf-8'))
- this.noneUIFileSet.clear()
- this.noneUIconfig.files.forEach(f => {
- this.noneUIFileSet.add(f)
- })
- } catch (error) {
- this._configPath = ''
- console.log("Load given hds_uicomponents file failed!", error);
- }
- }
- }
- private getPureName(name: string): string {
- return path.basename(name).replaceAll(".d.ts", "").replaceAll(".d.ets", "").replaceAll("_","").toLowerCase()
- }
-
- public isRelatedToComponent(name: string): boolean {
- return this.componentSet.has(name) || this.componentSuperclassSet.has(name)
- }
- public isComponent(name: string, subfix: string): boolean {
- return this.componentSet.has(name.replaceAll(subfix, ""))
- }
- public addComponentSuperclass(name: string): void {
- if (!this.isComponent(name, 'Attribute')) {
- this.componentSuperclassSet.add(name);
- }
- }
- public addComponentAttributeHeritage(name: string[]): void {
- let prev: string | undefined = undefined
- name.forEach(n => {
- if (prev) {
- this.componentHerirageRelation.set(prev, n)
- }
- prev = n
- this.componentHeritage.add(n)
- })
- if (name.length == 1) {
- this.shouldNotHaveAttributeModifier.add(name[0])
- }
- }
- public getComponentSuperclass(name: string): string | undefined {
- return this.componentHerirageRelation.get(name)
- }
- public isUIHeritage(name: string): boolean {
- return this.componentHeritage.has(name)
- }
- public notUIFile(name: string): boolean {
- return this.noneUIFileSet.has(this.getPureName(name))
- }
- public addComponentFile(name: string): void {
- this.componentFiles.add(this.getPureName(name))
- }
- public isComponentFile(name: string): boolean {
- return this.componentFiles.has(this.getPureName(name))
- }
- public shouldHaveAttributeModifier(name: string): boolean {
- return !this.shouldNotHaveAttributeModifier.has(name) && this.isComponent(name, 'Attribute')
- }
-}
-
-export default ArkUIConfigUtil.instance
diff --git a/build-tools/arkui_transformer/src/arkui_transformer.ts b/build-tools/arkui_transformer/src/arkui_transformer.ts
deleted file mode 100644
index 672d9e3352c65186cd9d71da53393c237ff454fd..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/arkui_transformer.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { program } from "commander"
-import { exit } from "process"
-import * as ts from 'typescript';
-import * as path from 'path';
-import * as fs from 'fs';
-import { componentInterfaceCollector, interfaceTransformer, addMemoTransformer } from "./interface_converter"
-import { ComponentFile } from './component_file';
-import { exportAllTransformer } from './add_export'
-import { addImportTransformer } from './add_import'
-import uiconfig from './arkui_config_util'
-
-function getFiles(dir: string, fileFilter: (f: string) => boolean): string[] {
- const result: string[] = []
- const dirents = fs.readdirSync(dir, { withFileTypes: true })
- for (const entry of dirents) {
- const fullPath = path.join(dir, entry.name)
- if (entry.isFile() && fileFilter(fullPath) && !uiconfig.notUIFile(fullPath)) {
- let addFile: boolean = true
- if (uiconfig.isHdsComponent) {
- addFile = entry.name.startsWith("@hms.hds.")
- }
- if (addFile) {
- result.push(fullPath)
- uiconfig.addComponentFile(fullPath)
- }
- }
- }
- return result
-}
-
-function convertFiles(files: string[]): string[] {
- const result: string[] = []
- for (const file of files) {
- const dest = file.replace(".d.ets", ".d.ts")
- fs.copyFile(file, dest, () => { })
- result.push(dest)
- }
- return result
-}
-
-function printResult(source: string, file: ComponentFile) {
- const outPath = path.join(options.targetDir, file.outFileName)
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
- fs.writeFileSync(outPath, source.concat(file.concactSource))
-}
-
-function main() {
- uiconfig.loadConfig(options);
- const files = getFiles(options.inputDir, f => f.endsWith(".d.ets"));
- const program = ts.createProgram(files, { allowJs: true });
- const { printFile } = ts.createPrinter({ removeComments: false });
- const componentFileMap = new Map();
- const componentFileCallback = (f: string) => {
- return (context: ts.TransformationContext) => {
- return (sourceFile: ts.SourceFile) => {
- const componentFile = new ComponentFile(f, sourceFile);
- componentFileMap.set(f, componentFile);
- ts.transform(sourceFile, [componentInterfaceCollector(program, componentFile)]);
- return sourceFile;
- }
- }
- }
-
- const transformerCallback = (f: string) => {
- return (context: ts.TransformationContext) => {
- return (sourceFile: ts.SourceFile) => {
- const componentFile = componentFileMap.get(f)!;
- const result = ts.transform(sourceFile, [interfaceTransformer(program, componentFile), exportAllTransformer(), addImportTransformer()]);
- const transformedFile = ts.createSourceFile(f, printFile(result.transformed[0]), ts.ScriptTarget.Latest, true);
- const addMemoResult = ts.transform(transformedFile, [addMemoTransformer(componentFile)]);
- const transformedSource = ts.createPrinter().printFile(addMemoResult.transformed[0]);
- printResult(transformedSource, componentFile);
- return ts.createSourceFile("", "", ts.ScriptTarget.Latest, true);
- }
- }
- }
-
- // Step1 collect all component dependencies
- files.forEach(f => {
- try {
- const content = fs.readFileSync(f, 'utf-8');
- ts.transpileModule(content, {
- compilerOptions: {
- target: ts.ScriptTarget.ES2017,
- },
- fileName: f,
- transformers: { before: [componentFileCallback(f)] }
- })
- } catch (e) {
- console.log("Error collecting file: ", f, e);
- exit(1)
- }
- })
-
- // Step2 make transformation
- files.forEach(f => {
- try {
- const content = fs.readFileSync(f, 'utf-8');
- ts.transpileModule(content, {
- compilerOptions: {
- target: ts.ScriptTarget.ES2017,
- },
- fileName: f,
- transformers: { before: [transformerCallback(f)] }
- })
- } catch (e) {
- console.log("Error transforming file: ", f, e);
- exit(1)
- }
- })
-}
-
-function mock() {
- const mock_file = path.join(options.targetDir, "type-translated.d.ets")
- fs.mkdirSync(options.targetDir, { recursive: true })
- fs.writeFileSync(mock_file, "// WARNING! THIS FILE IS AUTO-GENERATED, DO NOT MAKE CHANGES, THEY WILL BE LOST ON NEXT GENERATION!\n")
-}
-
-const options = program
- .option('--input-dir ', "Path of where d.ets exist")
- .option('--target-dir ', "Path to generate d.ets file")
- .option('--config-path ', "Path to folder with config files")
- .option('--use-memo-m3', "Generate code with m3 @memo annotations and functions with @ComponentBuilder", false)
- .parse()
- .opts()
-
-mock()
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/src/component_file.ts b/build-tools/arkui_transformer/src/component_file.ts
deleted file mode 100644
index 89754a53cc85831efb23d13d8c05cae54656e4d1..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/component_file.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import * as ts from 'typescript';
-import * as path from 'path';
-
-export class ComponentFile {
- public componentName: string
- public outFileName: string
-
- static snake2Camel(name: string, low: boolean = false): string {
- if (!name.includes('_')) {
- return name;
- }
- return name
- .split('_')
- .filter(word => word !== '')
- .map((word, index) => {
- if (index === 0 && low) {
- return word.toLowerCase();
- }
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
- })
- .join('');
- }
-
- public appendAttribute(str: string) {
- this.attributeSource.push(str)
- }
-
- public appendFunction(str: string) {
- this.functionSource += str
- }
-
- get concactSource() {
- return [...this.attributeSource, this.functionSource].join('\n')
- }
-
- constructor(
- public fileName: string,
- public sourceFile: ts.SourceFile,
- public attributeSource: string[] = [],
- public functionSource: string = '',
- ) {
- const pureName = path.basename(this.fileName).replaceAll(".d.ts", "").replaceAll(".d.ets", "");
- this.componentName = ComponentFile.snake2Camel(pureName)
- this.outFileName = ComponentFile.snake2Camel(pureName, true).concat(".d.ets")
- }
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/src/interface_converter.ts b/build-tools/arkui_transformer/src/interface_converter.ts
deleted file mode 100644
index 5a8c874ca1b74e5b60c279a3a80e90d4813d2b09..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/interface_converter.ts
+++ /dev/null
@@ -1,470 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import * as ts from 'typescript';
-import * as fs from 'fs';
-import * as path from 'path';
-import { assert } from 'console';
-import uiconfig from './arkui_config_util'
-import { ComponentFile } from './component_file';
-import { analyzeBaseClasses, isComponentHerirage, getBaseClassName, removeDuplicateMethods, mergeUniqueOrdered } from './lib/attribute_utils'
-
-function readLangTemplate(): string {
- return uiconfig.useMemoM3 ? fs.readFileSync('./pattern/arkts_component_decl_m3.pattern', 'utf8') : fs.readFileSync('./pattern/arkts_component_decl.pattern', 'utf8')
-}
-
-function extractSignatureComment(
- signature: ts.CallSignatureDeclaration,
- sourceFile: ts.SourceFile
-): string {
- const jsDoc = (signature as any).jsDoc?.[0] as ts.JSDoc | undefined;
- if (!jsDoc) return '';
-
-
- const commentText = sourceFile.text
- .slice(jsDoc.getStart(sourceFile), jsDoc.getEnd())
-
- return commentText.split('\n').map((l, index) => {
- if (index == 0) {
- return l.trimStart();
- }
- return ' ' + l.trimStart()
- }).join('\n')
-}
-
-interface ComponnetFunctionInfo {
- sig: string[],
- comment: string
-}
-
-interface ComponentPram {
- name: string,
- type: string[],
- isOptional: boolean,
-}
-
-function getAllInterfaceCallSignature(node: ts.InterfaceDeclaration, originalCode: ts.SourceFile, mergeCallSig: boolean = false): Array {
- const signatureParams: Array = [];
- const comments: string[] = []
- const paramList: Array = []
-
- node.members.forEach(member => {
- if (ts.isCallSignatureDeclaration(member)) {
- const currentSignature: string[] = [];
- const currentParam: ComponentPram[] = []
- const comment = extractSignatureComment(member, originalCode);
- comments.push(comment);
-
- member.parameters.forEach(param => {
- currentSignature.push(param.getText(originalCode));
- currentParam.push({ name: (param.name as ts.Identifier).escapedText as string, type: [param.type!.getText(originalCode)], isOptional: !!param.questionToken });
- });
- signatureParams.push(currentSignature)
- paramList.push(currentParam)
- }
- });
-
- const result: Array = new Array
-
- if (mergeCallSig) {
- const mergedParamList: Array = []
- paramList.forEach((params, _) => {
- params.forEach((param, index) => {
- if (!mergedParamList[index]) {
- mergedParamList.push(param)
- if (index > 0) {
- (mergedParamList[index] as ComponentPram).isOptional = true;
- }
- } else {
- mergedParamList[index] = { name: param.name, type: mergeUniqueOrdered(mergedParamList[index].type, param.type), isOptional: mergedParamList[index].isOptional || param.isOptional }
- }
- })
- })
- const mergedSignature: string[] = [];
- mergedParamList.forEach((param, index) => {
- mergedSignature.push(`${param.name}${param.isOptional ? '?' : ''}: ${param.type.join(' | ')}`)
- })
- result.push({
- sig: mergedSignature,
- comment: ''
- })
- } else {
- for (let i = 0; i < signatureParams.length; i++) {
- result.push({ sig: signatureParams[i], comment: comments[i] })
- }
- }
- return result;
-}
-
-function handleComponentInterface(node: ts.InterfaceDeclaration, file: ComponentFile) {
- const result = getAllInterfaceCallSignature(node, file.sourceFile, !uiconfig.useMemoM3);
- const declPattern = readLangTemplate()
- const declComponentFunction: string[] = []
- const attributeName = node.name!.escapedText as string
- const componentName = attributeName.replaceAll('Interface', '');
- result.forEach(p => {
- declComponentFunction.push(declPattern
- .replaceAll("%COMPONENT_NAME%", componentName)
- .replaceAll("%FUNCTION_PARAMETERS%", p.sig?.map(it => `${it}, `).join("") ?? "")
- .replaceAll("%COMPONENT_COMMENT%", p.comment))
- })
- return declComponentFunction.join('\n')
-}
-
-function updateMethodDoc(node: ts.MethodDeclaration): ts.MethodDeclaration {
- const returnType = ts.factory.createThisTypeNode();
- if ('jsDoc' in node) {
- const paramNameType: Map = new Map();
- node.parameters.forEach(param => {
- paramNameType.set((param.name as ts.Identifier).escapedText!, param.type!);
- })
- const jsDoc = node.jsDoc as ts.JSDoc[];
- const updatedJsDoc = jsDoc.map((doc) => {
- const updatedTags = (doc.tags || []).map((tag: ts.JSDocTag) => {
- if (tag.tagName.escapedText === 'returns') {
- return ts.factory.updateJSDocReturnTag(
- tag as ts.JSDocReturnTag,
- tag.tagName,
- ts.factory.createJSDocTypeExpression(returnType),
- tag.comment
- )
- }
- if (tag.tagName.escapedText === 'param') {
- const paramTag = tag as ts.JSDocParameterTag
- return ts.factory.updateJSDocParameterTag(
- paramTag,
- paramTag.tagName,
- paramTag.name,
- paramTag.isBracketed,
- ts.factory.createJSDocTypeExpression(paramNameType.get((paramTag.name as ts.Identifier).escapedText!)!),
- paramTag.isNameFirst,
- paramTag.comment
- )
- }
- return tag
- })
- return ts.factory.updateJSDocComment(doc, doc.comment, updatedTags);
- });
- (node as any).jsDoc = updatedJsDoc
- }
- return node
-}
-
-function handleOptionalType(paramType: ts.TypeNode, wrapUndefined: boolean = true): ts.TypeNode {
- if (!ts.isTypeReferenceNode(paramType)) {
- return paramType;
- }
- const typeName = (paramType.typeName as ts.Identifier).escapedText;
-
- const wrapUndefinedOp = (type: ts.TypeNode) => {
- if (!wrapUndefined) {
- return type;
- }
- return ts.factory.createUnionTypeNode([
- ...(ts.isUnionTypeNode(type) ? type.types : [type]),
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
- ]);
- }
-
- // Check if the parameter type is Optional
- if (typeName === 'Optional' && paramType.typeArguments?.length === 1) {
- const innerType = paramType.typeArguments[0];
- return wrapUndefinedOp(innerType);
- }
- return wrapUndefinedOp(paramType);
-}
-
-function handleAttributeMember(node: ts.MethodDeclaration): ts.MethodSignature {
- const updatedParameters = node.parameters.map(param => {
- const paramType = param.type;
-
- // Ensure all other parameters are XX | undefined
- if (paramType) {
- if (ts.isTypeReferenceNode(paramType)) {
- return ts.factory.updateParameterDeclaration(
- param,
- undefined,
- param.dotDotDotToken,
- param.name,
- param.questionToken,
- handleOptionalType(paramType),
- param.initializer
- );
- } else if (ts.isUnionTypeNode(paramType)) {
- const removeOptionalTypes = paramType.types.map(type => {
- return handleOptionalType(type, false);
- })
- // Check if the union type already includes undefined
- const hasUndefined = removeOptionalTypes.some(
- type => type.kind === ts.SyntaxKind.UndefinedKeyword
- );
-
- if (!hasUndefined) {
- const updatedType = ts.factory.createUnionTypeNode([
- ...removeOptionalTypes,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
- ]);
-
- return ts.factory.updateParameterDeclaration(
- param,
- undefined,
- param.dotDotDotToken,
- param.name,
- param.questionToken,
- updatedType,
- param.initializer
- );
- }
- } else {
- // If not a union type, add | undefined
- const updatedType = ts.factory.createUnionTypeNode([
- paramType,
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
- ]);
-
- return ts.factory.updateParameterDeclaration(
- param,
- undefined,
- param.dotDotDotToken,
- param.name,
- param.questionToken,
- updatedType,
- param.initializer
- );
- }
- }
-
- return param;
- });
-
-
- const returnType = ts.factory.createThisTypeNode();
- const methodSignature = ts.factory.createMethodSignature(
- undefined,
- node.name,
- node.questionToken,
- node.typeParameters,
- updatedParameters,
- returnType
- );
-
- return methodSignature
-}
-
-function handleHeritageClause(node: ts.NodeArray | undefined): ts.HeritageClause[] {
- const heritageClauses: ts.HeritageClause[] = [];
- if (!node) {
- return heritageClauses;
- }
- node.forEach(clause => {
- const types = clause.types.map(type => {
- if (ts.isExpressionWithTypeArguments(type) &&
- ts.isIdentifier(type.expression) && type.typeArguments) {
-
- return ts.factory.updateExpressionWithTypeArguments(
- type,
- type.expression,
- [],
- );
- }
- return type;
- });
- const newClause = ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, types);
- heritageClauses.push(newClause);
- });
- return heritageClauses
-}
-
-function handleAttributeModifier(node: ts.ClassDeclaration, members: ts.MethodSignature[]) {
- if (!isComponentAttribute(node)) {
- members.forEach(m => {
- if ((m.name as ts.Identifier).escapedText === 'attributeModifier') {
- members.splice(members.indexOf(m), 1);
- }
- })
- return
- }
- members.push(
- ts.factory.createMethodSignature(
- undefined,
- ts.factory.createIdentifier("attributeModifier"),
- undefined,
- undefined,
- [ts.factory.createParameterDeclaration(
- undefined,
- undefined,
- ts.factory.createIdentifier("modifier"),
- undefined,
- ts.factory.createUnionTypeNode([
- ts.factory.createTypeReferenceNode(
- ts.factory.createIdentifier("AttributeModifier"),
- [ts.factory.createTypeReferenceNode(
- node.name!,
- undefined
- )]
- ),
- ts.factory.createTypeReferenceNode(
- ts.factory.createIdentifier("AttributeModifier"),
- [ts.factory.createTypeReferenceNode(
- ts.factory.createIdentifier("CommonMethod"),
- undefined
- )]
- ),
- ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)
- ]),
- undefined
- )],
- ts.factory.createThisTypeNode()
- )
- )
-}
-
-function transformComponentAttribute(node: ts.ClassDeclaration): ts.Node[] {
- const members = node.members.map(member => {
- if (!ts.isMethodDeclaration(member)) {
- return undefined;
- }
- return handleAttributeMember(member);
- }).filter((member): member is ts.MethodSignature => member !== undefined);
-
- const filetredMethos = removeDuplicateMethods(members)
-
- if (uiconfig.shouldHaveAttributeModifier(node.name!.escapedText as string)) {
- handleAttributeModifier(node, filetredMethos)
- }
-
- const exportModifier = ts.factory.createModifier(ts.SyntaxKind.ExportKeyword);
- const delcareModifier = ts.factory.createModifier(ts.SyntaxKind.DeclareKeyword);
-
- const heritageClauses = handleHeritageClause(node.heritageClauses)
-
- const noneUIAttribute = ts.factory.createInterfaceDeclaration(
- [exportModifier, delcareModifier],
- node.name as ts.Identifier,
- [],
- heritageClauses,
- filetredMethos
- );
- return [noneUIAttribute]
-}
-
-function getLeadingSpace(line: string): string {
- let leadingSpaces = '';
- for (const char of line) {
- if (char === ' ') {
- leadingSpaces += char;
- } else {
- break;
- }
- }
- return leadingSpaces;
-}
-
-function extractMethodName(code: string): string | undefined {
- const match = code.match(/^\s*([^(]+)/);
- if (!match) return undefined;
- return match[1].trim();
-}
-
-function addAttributeMemo(node: ts.ClassDeclaration, componentFile: ComponentFile) {
- const originalSource = componentFile.sourceFile;
- const commentRanges = ts.getLeadingCommentRanges(originalSource.text, node.pos);
- const classStart = commentRanges?.[0]?.pos ?? node.getStart(originalSource);
- const classEnd = node.getEnd();
- const originalCode = originalSource.text.substring(classStart, classEnd).split('\n');
-
- const functionSet: Set = new Set();
- node.members.forEach(m => {
- functionSet.add((m.name! as ts.Identifier).escapedText!)
- })
-
- const updatedCode: string[] = []
- originalCode.forEach(l => {
- const name = extractMethodName(l);
- if (!name) {
- updatedCode.push(l);
- return;
- }
- if (functionSet.has(name)) {
- updatedCode.push(getLeadingSpace(l) + "@memo")
- }
- updatedCode.push(l);
- })
- const attributeName = node.name!.escapedText!
- const superInterface = getBaseClassName(node)
- componentFile.appendAttribute(updatedCode.join('\n')
- .replace(`export declare interface ${attributeName}`, `export declare interface UI${attributeName}`)
- .replace(`extends ${superInterface}`, `extends UI${superInterface}`)
- )
-}
-
-function isComponentAttribute(node: ts.Node) {
- if (!(ts.isClassDeclaration(node) && node.name?.escapedText)) {
- return false;
- }
- return uiconfig.isComponent(node.name.escapedText, 'Attribute')
-}
-
-function isComponentInterface(node: ts.Node) {
- if (!(ts.isInterfaceDeclaration(node) && node.name?.escapedText)) {
- return false;
- }
- return uiconfig.isComponent(node.name.escapedText, 'Interface')
-}
-
-export function addMemoTransformer(componentFile: ComponentFile): ts.TransformerFactory {
- return (context) => {
- const visit: ts.Visitor = (node) => {
- if (isComponentHerirage(node) && !uiconfig.useMemoM3) {
- addAttributeMemo(node as ts.ClassDeclaration, componentFile)
- }
- return ts.visitEachChild(node, visit, context);
- }
- return (sourceFile) => { componentFile.sourceFile = sourceFile; return ts.visitNode(sourceFile, visit) };
- }
-}
-
-export function interfaceTransformer(program: ts.Program, componentFile: ComponentFile): ts.TransformerFactory {
- return (context) => {
- const visit: ts.Visitor = (node) => {
- if (isComponentInterface(node)) {
- componentFile.appendFunction(handleComponentInterface(node as ts.InterfaceDeclaration, componentFile))
- return undefined;
- }
- if (isComponentHerirage(node)) {
- return transformComponentAttribute(node as ts.ClassDeclaration)
- }
- return ts.visitEachChild(node, visit, context);
- };
-
- return (sourceFile) => ts.visitNode(sourceFile, visit);
- };
-}
-
-export function componentInterfaceCollector(program: ts.Program, componentFile: ComponentFile): ts.TransformerFactory {
- return (context) => {
- const visit: ts.Visitor = (node) => {
- if (isComponentAttribute(node)) {
- const attributeName = (node as ts.ClassDeclaration).name!.escapedText as string
- componentFile.componentName = attributeName.replaceAll('Attribute', '');
- const baseTypes = analyzeBaseClasses(node as ts.ClassDeclaration, componentFile.sourceFile, program);
- uiconfig.addComponentAttributeHeritage([attributeName, ...baseTypes])
- }
- return ts.visitEachChild(node, visit, context);
- };
-
- return (sourceFile) => ts.visitNode(sourceFile, visit);
- };
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/src/lib/attribute_utils.ts b/build-tools/arkui_transformer/src/lib/attribute_utils.ts
deleted file mode 100644
index 61a71c6091ce5f87c475395f3e011a4be76801c7..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/src/lib/attribute_utils.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-
-import * as ts from "typescript";
-
-import uiconfig from '../arkui_config_util'
-
-/**
- * Analyzes the base classes of a given class declaration and collects their names recursively.
- *
- * @param classNode - The TypeScript class declaration node to analyze.
- * @param sourceFile - The source file containing the class declaration.
- * @param program - The TypeScript program instance used for type checking.
- *
- * @returns void
- *
- * This function traverses the inheritance hierarchy of the specified class declaration,
- * extracting the names of all base classes. It uses the TypeScript type checker to resolve
- * symbols and declarations of base classes, ensuring accurate identification of inherited types.
- */
-export function analyzeBaseClasses(classNode: ts.ClassDeclaration, sourceFile: ts.SourceFile, program: ts.Program) {
- const className = classNode.name!.escapedText!;
- const baseTypes: string[] = [];
- const checker = program.getTypeChecker();
-
-
- const extractTypeName = (expr: ts.Expression): string | null => {
- if (ts.isIdentifier(expr)) {
- return expr.text;
- } else if (ts.isPropertyAccessExpression(expr)) {
- return `${extractTypeName(expr.expression)}.${expr.name.text}`;
- }
- return null;
- }
-
- const findBase = (currentClass: ts.ClassDeclaration) => {
- if (!currentClass.heritageClauses) return;
-
- for (const heritage of currentClass.heritageClauses) {
- if (heritage.token === ts.SyntaxKind.ExtendsKeyword) {
- for (const type of heritage.types) {
- const baseName = extractTypeName(type.expression);
- if (baseName) {
- baseTypes.push(baseName);
- const baseSymbol = checker.getSymbolAtLocation(type.expression);
- if (baseSymbol) {
- const baseDeclarations = baseSymbol.getDeclarations();
- if (baseDeclarations) {
- baseDeclarations.forEach(decl => {
- if (ts.isClassDeclaration(decl)) {
- findBase(decl);
- }
- });
- }
- }
- }
- }
- }
- }
- };
-
- findBase(classNode);
- return baseTypes
-}
-
-export function getBaseClassName(classNode: ts.ClassDeclaration): string | undefined {
- if (!classNode.heritageClauses) return undefined;
-
- for (const heritage of classNode.heritageClauses) {
- if (heritage.token === ts.SyntaxKind.ExtendsKeyword) {
- for (const type of heritage.types) {
- const baseName = type.expression.getText();
- return baseName;
- }
- }
- }
- return undefined;
-}
-
-export function isComponentHerirage(node: ts.Node): boolean {
- if (!ts.isClassDeclaration(node) && !ts.isInterfaceDeclaration(node)) {
- return false;
- }
- return uiconfig.isUIHeritage(node.name!.escapedText!)
-}
-
-export function removeDuplicateMethods(methods: ts.MethodSignature[]): ts.MethodSignature[] {
- const seenSignatures = new Set();
-
- return methods.filter(method => {
- const signatureKey = getMethodCharacteristic(method);
-
- if (seenSignatures.has(signatureKey)) {
- return false;
- }
-
- seenSignatures.add(signatureKey);
- return true;
- });
-}
-
-export function getMethodCharacteristic(
- node: ts.MethodSignature
-): string {
- const methodName = node.name.getText();
-
- const params = node.parameters.map((param) => {
- const typeNode = param.type;
- let typeText: string;
-
- if (typeNode) {
- if (ts.isUnionTypeNode(typeNode)) {
- const types = typeNode.types;
- typeText = types.map((t) => {
- if (ts.isTypeReferenceNode(t)) {
- return t.getText();
- }
- return t.kind.toString();
- }).join('|') || 'any';
- } else {
- throw new Error("UnExpected type node kind");
- }
- } else {
- throw new Error("UnExpected type node kind");
- }
-
- return typeText;
- });
-
- return `${methodName}(${params.join(',')})`;
-}
-
-export function mergeUniqueOrdered(arr1: string[], arr2: string[]): string[] {
- const seen = new Set();
- const result: string[] = [];
- for (const item of arr1) {
- if (!seen.has(item)) {
- seen.add(item);
- result.push(item);
- }
- }
-
- for (const item of arr2) {
- if (!seen.has(item)) {
- seen.add(item);
- result.push(item);
- }
- }
-
- return result;
-}
diff --git a/build-tools/arkui_transformer/tsconfig.arkui.json b/build-tools/arkui_transformer/tsconfig.arkui.json
deleted file mode 100644
index 0c98cc58610e3797dc574c8f94e88f42d4bdbab6..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/tsconfig.arkui.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "compilerOptions": {
- "allowJs": true,
- "noEmitOnError": true,
- "skipLibCheck": true,
- "plugins": [
- {
- "transform": "/home/leslie/openharmony/src/interface/sdk-js/build-tools/dist/arkui_transformer.js",
- }
- ],
- },
- "include": [
- "../etstest/foo.ts"
- ]
-}
\ No newline at end of file
diff --git a/build-tools/arkui_transformer/tsconfig.json b/build-tools/arkui_transformer/tsconfig.json
deleted file mode 100644
index d51cda3fc2d2e5248c2da7cd46bced2498f823c4..0000000000000000000000000000000000000000
--- a/build-tools/arkui_transformer/tsconfig.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "compilerOptions": {
- "module": "esnext",
- "target": "ESNext",
- "moduleResolution": "node",
- "outDir": "./build",
- "rootDir": "./src",
- "sourceMap": true,
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- },
- "include": [
- "src/*.ts"
- ]
-}
\ No newline at end of file
diff --git a/build-tools/delete_systemapi_plugin.js b/build-tools/delete_systemapi_plugin.js
index 9b52240365453a143398781e01c1187758986ff6..e3a439aa11d69c8730360f4c860e1bed48df8a2a 100644
--- a/build-tools/delete_systemapi_plugin.js
+++ b/build-tools/delete_systemapi_plugin.js
@@ -15,14 +15,10 @@
const path = require('path');
const fs = require('fs');
const ts = require('typescript');
-const commander = require('commander');
let sourceFile = null;
let lastNoteStr = '';
let lastNodeName = '';
-let etsType = 'ets';
-let componentEtsFiles = [];
-let componentEtsDeleteFiles = [];
const referencesMap = new Map();
const referencesModuleMap = new Map();
const kitFileNeedDeleteMap = new Map();
@@ -41,33 +37,14 @@ const PATT = {
REFERENCEURL_RIGHTSDK: /(..\/)(\S*)build-tools\/ets-loader\/declarations\/(\S*)/g,
REFERENCEURL_SDK: /(..\/)(\S*)component\/(\S*)/g,
};
-
-function start() {
- const program = new commander.Command();
- program
- .name('deleteSystemApi')
- .version('0.0.1');
- program
- .option('--input ', 'path name')
- .option('--output ', 'output path')
- .option('--type ', 'ets type')
- .action((opts) => {
- outputPath = opts.output;
- inputDir = opts.input;
- etsType = opts.type;
- collectDeclaration(opts.input);
- });
- program.parse(process.argv);
-}
-
-function collectDeclaration(inputDir) {
+function collectDeclaration(url) {
// 入口
try {
- const arktsPath = path.resolve(inputDir, '../arkts');
- const kitPath = path.resolve(inputDir, '../kits');
+ const utPath = path.resolve(__dirname, url);
+ const arktsPath = path.resolve(utPath, '../arkts');
+ const kitPath = path.resolve(utPath, '../kits');
const utFiles = [];
- collectComponentEtsFiles();
- readFile(inputDir, utFiles); // 读取文件
+ readFile(utPath, utFiles); // 读取文件
readFile(arktsPath, utFiles); // 读取文件
tsTransform(utFiles, deleteSystemApi);
tsTransformKitFile(kitPath);
@@ -76,20 +53,6 @@ function collectDeclaration(inputDir) {
}
}
-function collectComponentEtsFiles() {
- const ComponentDir = path.resolve(inputDir, '@internal', 'component', 'ets');
- readFile(ComponentDir, componentEtsFiles); // 读取文件
- const arkuiComponentDir = path.resolve(inputDir, 'arkui', 'component');
- readFile(arkuiComponentDir, componentEtsFiles); // 读取文件
- componentEtsFiles = componentEtsFiles.map(item => {
- return getPureName(item);
- });
-}
-
-function getPureName(name) {
- return path.basename(name).replace('.d.ts', '').replace('.d.ets', '').replace(/_/g, '').toLowerCase();
-}
-
/**
* 解析url目录下方的kit文件,删除对应systemapi
* @param { string } kitPath kit文件路径
@@ -140,10 +103,10 @@ function getKitNewSourceFile(sourceFile, kitName) {
copyrightMessage = sourceFile.getFullText().replace(sourceFile.getText(), '');
}
} else if (ts.isExportDeclaration(statement)) {
- const exportSpecifiers = statement.exportClause?.elements?.filter((item) => {
+ const exportSpecifiers = statement.exportClause.elements.filter((item) => {
return !needDeleteExportName.has(item.name.escapedText.toString());
});
- if (exportSpecifiers && exportSpecifiers.length !== 0) {
+ if (exportSpecifiers.length !== 0) {
statement.exportClause = factory.updateNamedExports(statement.exportClause, exportSpecifiers);
newStatements.push(statement);
}
@@ -153,21 +116,6 @@ function getKitNewSourceFile(sourceFile, kitName) {
return { sourceFile, copyrightMessage };
}
-function addImportToNeedDeleteExportName(importClause, needDeleteExportName) {
- if (importClause.name) {
- needDeleteExportName.add(importClause.name.escapedText.toString());
- }
- const namedBindings = importClause.namedBindings;
- if (namedBindings !== undefined && ts.isNamedImports(namedBindings)) {
- const elements = namedBindings.elements;
- elements.forEach((element) => {
- const exportName = element.propertyName ?
- element.propertyName.escapedText.toString() :
- element.name.escapedText.toString();
- needDeleteExportName.add(element.name.escapedText.toString());
- });
- }
-}
/**
* 根据节点和需要删除的节点数据生成新节点
* @param { ts.ImportDeclaration } statement 需要处理的import节点
@@ -184,12 +132,8 @@ function processKitImportDeclaration(statement, needDeleteExportName) {
}
const importPath = statement.moduleSpecifier.text.replace('../', '');
if (kitFileNeedDeleteMap === undefined || !kitFileNeedDeleteMap.has(importPath)) {
- const hasFilePath = hasFileByImportPath(importPath, inputDir);
- if (hasFilePath) {
- return statement;
- }
- addImportToNeedDeleteExportName(importClause, needDeleteExportName);
- return undefined;
+ const hasFilePath = hasFileByImportPath(importPath);
+ return hasFilePath ? statement : undefined;
}
const currImportInfo = kitFileNeedDeleteMap.get(importPath);
let defaultName = '';
@@ -234,34 +178,18 @@ function processKitImportDeclaration(statement, needDeleteExportName) {
/**
* 判断文件路径对应的文件是否存在
* @param {string} importPath kit文件import
- * @param {string} apiDir 引用接口所在目录
* @returns {boolean} importPath是否存在
*/
-function hasFileByImportPath(importPath, apiDir) {
- let fileDir = path.resolve(apiDir);
+function hasFileByImportPath(importPath) {
+ let fileDir = path.resolve(apiSourcePath);
if (importPath.startsWith('@arkts')) {
- fileDir = path.resolve(inputDir, '../arkts');
- }
- return isExistArkUIFile(path.resolve(inputDir, 'arkui', 'component'), importPath) ||
- isExistImportFile(fileDir, importPath);
-}
-
-function isExistArkUIFile(resolvedPath, importPath) {
- const filePath = path.resolve(resolvedPath, importPath);
- if (
- filePath.includes(path.resolve(inputDir, '@internal', 'component', 'ets')) ||
- filePath.includes(path.resolve(inputDir, 'arkui', 'component'))
- ) {
- const fileName = getPureName(filePath);
- return componentEtsFiles.includes(fileName);
+ fileDir = path.resolve(apiSourcePath, '../arkts');
}
- return isExistImportFile(resolvedPath, importPath);
-}
-
-function isExistImportFile(fileDir, importPath) {
- return ['.d.ts', '.d.ets'].some(ext => {
- return fs.existsSync(path.resolve(fileDir, `${importPath}${ext}`));
+ const flag = ['.d.ts', '.d.ets'].some(ext => {
+ const filePath = path.resolve(fileDir, `${importPath}${ext}`);
+ return fs.existsSync(filePath);
});
+ return flag;
}
/**
@@ -285,9 +213,6 @@ function processFileNameWithoutExt(filePath) {
.replace(/\.ets$/g, '');
}
-function isArkTsSpecialSyntax(content) {
- return /\@memo|(? {
const apiBaseName = path.basename(url);
- let content = fs.readFileSync(url, 'utf-8'); // 文件内容
- if (isArkTsSpecialSyntax(content)) {
- if (!/\@systemapi/.test(content)) {
- writeFile(url, content);
- }
- return;
- }
- if (/\.json/.test(url) || apiBaseName === 'index-full.d.ts' || !/\@systemapi/.test(content) && apiBaseName !== '@ohos.arkui.component.d.ets') {
+ if (/\.json/.test(url) || apiBaseName === 'index-full.d.ts') {
// 特殊类型文件处理
+ const content = fs.readFileSync(url, 'utf-8');
writeFile(url, content);
} else if (/\.d\.ts/.test(apiBaseName) || /\.d\.ets/.test(apiBaseName)) {
// dts文件处理
+ let content = fs.readFileSync(url, 'utf-8'); // 文件内容
const fileName = processFileName(url);
let references = content.match(PATT.GET_REFERENCE);
if (references) {
@@ -414,7 +334,10 @@ function readFile(dir, utFiles) {
}
function writeFile(url, data, option) {
- const newFilePath = path.resolve(outputPath, path.relative(inputDir.replace('api', ''), url));
+ if (fs.existsSync(outputPath)) {
+ fs.rmdirSync(outputPath, { recursive: true });
+ }
+ const newFilePath = path.resolve(outputPath, path.relative(__dirname, url));
fs.mkdir(path.dirname(newFilePath), { recursive: true }, (err) => {
if (err) {
console.log(`ERROR FOR CREATE PATH ${err}`);
@@ -603,8 +526,9 @@ function formatAllNodesImportDeclaration(node, statement, url, currReferencesMod
}
}
const importSpecifier = statement.moduleSpecifier.getText().replace(/[\'\"]/g, '');
- const fileDir = path.dirname(url);
- let hasImportSpecifierFile = hasFileByImportPath(importSpecifier, fileDir);
+ const dtsImportSpecifierPath = path.resolve(url, `../${importSpecifier}.d.ts`); // import 文件路径判断
+ const detsImportSpecifierPath = path.resolve(url, `../${importSpecifier}.d.ets`); // import 文件路径判断
+ let hasImportSpecifierFile = fs.existsSync(dtsImportSpecifierPath) || fs.existsSync(detsImportSpecifierPath);
let hasImportSpecifierInModules = globalModules.has(importSpecifier);
if ((hasImportSpecifierFile || hasImportSpecifierInModules) && clauseSet.size > 0) {
let currModule = [];
@@ -711,7 +635,7 @@ function deleteSystemApi(url) {
kitName = RegExp.$1.replace(/\s/g, '');
}
sourceFile = node;
- const deleteNode = processSourceFile(node, kitName, url); // 处理最外层节点
+ const deleteNode = processSourceFile(node, kitName); // 处理最外层节点
node = processVisitEachChild(context, deleteNode.node);
if (!isEmptyFile(node)) {
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
@@ -747,7 +671,7 @@ exports.deleteSystemApi = deleteSystemApi;
* @param kitName 当前文件kitName
* @returns
*/
-function processSourceFile(node, kitName, url) {
+function processSourceFile(node, kitName) {
let isCopyrightDeleted = false;
const newStatements = [];
const newStatementsWithoutExport = [];
@@ -760,15 +684,6 @@ function processSourceFile(node, kitName, url) {
isCopyrightDeleted = addNewStatements(node, newStatements, deleteSystemApiSet, needDeleteExport);
newStatements.forEach((statement) => {
const names = getExportIdentifierName(statement);
- if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && statement.moduleSpecifier.text.startsWith('./arkui/component/')) {
- const importPath = statement.moduleSpecifier.text.replace('./arkui/component/', '');
- const isDeleteSystemFile = componentEtsDeleteFiles.includes(getPureName(importPath));
- const hasEtsFile = componentEtsFiles.includes(getPureName(importPath));
- const existFile = isExistImportFile(path.dirname(url), statement.moduleSpecifier.text.toString());
- if (isDeleteSystemFile || !hasEtsFile && !existFile) {
- return;
- }
- }
if (names.length === 0) {
newStatementsWithoutExport.push(statement);
return;
@@ -1154,13 +1069,9 @@ function isEmptyFile(node) {
break;
}
}
- const fileName = getPureName(node.fileName.replace('.ts', '').replace('.ets', ''));
- if (isEmpty && componentEtsFiles.includes(fileName)) {
- componentEtsDeleteFiles.push(fileName);
- }
return isEmpty;
}
-let outputPath = '';
-let inputDir = '';
-start();
+const apiSourcePath = '../api';
+const outputPath = path.resolve(__dirname, 'output');
+collectDeclaration(apiSourcePath); //入口
diff --git a/build-tools/handleApiFiles.js b/build-tools/handleApiFiles.js
deleted file mode 100755
index 50b633576c7559bca90058b8eaf43605bb7a5174..0000000000000000000000000000000000000000
--- a/build-tools/handleApiFiles.js
+++ /dev/null
@@ -1,815 +0,0 @@
-/*
- * Copyright (c) 2025 Huawei Device Co., Ltd.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-const fs = require('fs');
-const path = require('path');
-const ts = require('typescript');
-const commander = require('commander');
-// 处理的目录类型
-let dirType = '';
-const deleteApiSet = new Set();
-const importNameSet = new Set();
-
-// 处理的目录类型,ets代表处理的是1.1目录,ets2代表处理的是1.2目录里有@arkts 1.1&1.2标签的文件,
-// noTagInEts2代表处理的是1.2目录里无标签的文件
-const DirType = {
- 'typeOne': 'ets',
- 'typeTwo': 'ets2',
- 'typeThree': 'noTagInEts2',
-};
-
-const NOT_COPY_DIR = ['build-tools', '.git', '.gitee'];
-
-function isEtsFile(path) {
- return path.endsWith('d.ets');
-}
-
-function isTsFile(path) {
- return path.endsWith('d.ts');
-}
-
-function hasEtsFile(path) {
- // 为StateManagement.d.ts设定白名单,在1.2打包的时候在Linux上有大小写不同的重名,碰到直接返回true
- if (path.includes('StateManagement.d.ts')) {
- console.log('StateManagement.d.ts is in white list, return true. path = ', path);
- return true;
- } else {
- return fs.existsSync(path.replace(/\.d\.[e]?ts$/g, '.d.ets'));
- }
-}
-
-function hasTsFile(path) {
- return fs.existsSync(path.replace(/\.d\.[e]?ts$/g, '.d.ts'));
-}
-
-/**
- * 配置参数
- */
-function start() {
- const program = new commander.Command();
- program
- .name('handleApiFile')
- .version('0.0.1');
- program
- .option('--path ', 'path name')
- .option('--type ', 'handle type')
- .option('--output [string]', 'output path')
- .action((opts) => {
- dirType = opts.type;
- handleApiFiles(opts.path, opts.type, opts.output);
- });
- program.parse(process.argv);
-}
-/**
- * 处理API文件的入口函数
- *
- * @param {*} rootPath
- * @param {*} type
- */
-function handleApiFiles(rootPath, type, output) {
- const allApiFilePathSet = new Set();
- const fileNames = fs.readdirSync(rootPath);
- const apiRootPath = rootPath.replace(/\\/g, '/');
- fileNames.forEach(fileName => {
- const apiPath = path.join(apiRootPath, fileName);
- const stat = fs.statSync(apiPath);
- if (NOT_COPY_DIR.includes(fileName)) {
- return;
- }
- if (stat.isDirectory()) {
- getApiFileName(apiPath, apiRootPath, allApiFilePathSet);
- } else {
- allApiFilePathSet.add(fileName);
- }
-
- });
-
- for (const apiRelativePath of allApiFilePathSet) {
- try {
- handleApiFileByType(apiRelativePath, rootPath, type, output);
- } catch (error) {
- console.log('error===>', error);
- }
- }
-}
-
-
-/**
- * 根据传入的type值去处理文件
- *
- * @param {*} apiRelativePath
- * @param {*} allApiFilePathSet
- * @param {*} rootPath
- * @param {*} type
- * @returns
- */
-function handleApiFileByType(apiRelativePath, rootPath, type, output) {
- const fullPath = path.join(rootPath, apiRelativePath);
- const isEndWithEts = isEtsFile(apiRelativePath);
- const isEndWithTs = isTsFile(apiRelativePath);
- const outputPath = output ? path.join(output, apiRelativePath) : fullPath;
- const fileContent = fs.readFileSync(fullPath, 'utf-8');
-
- if (!isEndWithEts && !isEndWithTs) {
- writeFile(outputPath, fileContent);
- return;
- }
- if (type === 'ets2' && !(hasEtsFile(fullPath) && isEndWithTs)) {
- handleFileInSecondType(apiRelativePath, fullPath, type, output);
- } else if (type === 'ets' && !(hasTsFile(fullPath) && isEndWithEts)) {
- handleFileInFirstType(apiRelativePath, fullPath, type, output);
- }
-}
-
-/**
- * 处理文件过滤 if arkts 1.1|1.2|1.1&1.2 定义
- *
- * @param {*} type
- * @param {*} fileContent
- * @returns
- */
-function handleArktsDefinition(type, fileContent) {
- let regx = /\/\*\*\* if arkts 1\.1 \*\/\s*([\s\S]*?)\s*\/\*\*\* endif \*\//g;
- let regx2 = /\/\*\*\* if arkts 1\.2 \*\/\s*([\s\S]*?)\s*\/\*\*\* endif \*\//g;
- let regx3 = /\/\*\*\* if arkts 1\.1\&1\.2 \*\/\s*([\s\S]*?)\s*\/\*\*\* endif \*\//g;
- fileContent = fileContent.replace(regx, (substring, p1) => {
- return type === 'ets' ? p1 : '';
- });
- fileContent = fileContent.replace(regx2, (substring, p1) => {
- if (type === 'ets2') {
- return p1.replace(/(\s*)(\*\s\@since)/g, '$1* @arkts 1.2$1$2');
- } else {
- return '';
- }
- });
- fileContent = fileContent.replace(regx3, (substring, p1) => {
- if (type === 'ets') {
- return p1;
- } else {
- return p1.replace(/(\s*)(\*\s\@since)/g, '$1* @arkts 1.2$1$2');
- }
- });
- return fileContent;
-}
-
-/**
- * 保留每个api最新一段jsdoc
- *
- * @param {*} fileContent
- * @returns
- */
-function saveLatestJsDoc(fileContent) {
- let regx = /(\/\*[\s\S]*?\*\*\/)/g;
-
- fileContent = fileContent.split('').reverse().join('');
- let preset = 0;
- fileContent = fileContent.replace(regx, (substring, p1, offset, str) => {
- if (!/ecnis@\s*\*/g.test(substring)) {
- return substring;
- }
- const preStr = str.substring(preset, offset);
- preset = offset + substring.length;
- if (/\S/g.test(preStr)) {
- return substring;
- }
- return '';
- });
- fileContent = fileContent.split('').reverse().join('');
- return fileContent;
-}
-
-/**
- * 处理ets目录
- *
- * @param {string} apiRelativePath
- * @param {string} fullPath
- * @returns
- */
-function handleFileInFirstType(apiRelativePath, fullPath, type, output) {
- const outputPath = output ? path.join(output, apiRelativePath) : fullPath;
- let fileContent = fs.readFileSync(fullPath, 'utf-8');
- //删除使用/*** if arkts 1.2 */
- fileContent = handleArktsDefinition(type, fileContent);
-
- const sourceFile = ts.createSourceFile(path.basename(apiRelativePath), fileContent, ts.ScriptTarget.ES2017, true);
- const secondRegx = /(?:@arkts1.2only|@arkts\s+>=\s*1.2|@arkts\s*1.2)/;
- const thirdRegx = /(?:\*\s*@arkts\s+1.1&1.2\s*(\r|\n)\s*)/;
- if (sourceFile.statements.length === 0) {
- // reference文件识别不到首段jsdoc,全文匹配1.2标签,有的话直接删除
- if (secondRegx.test(sourceFile.getFullText())) {
- return;
- }
- // 标有@arkts 1.1&1.2的声明文件,处理since版本号,删除@arkts 1.1&1.2标签
- if (thirdRegx.test(sourceFile.getFullText())) {
- fileContent = handleSinceInFirstType(deleteArktsTag(fileContent));
- writeFile(outputPath, fileContent);
- return;
- }
-
- handleNoTagFileInFirstType(sourceFile, outputPath, fileContent);
- return;
- }
- const firstNode = sourceFile.statements.find(statement => {
- return !ts.isExpressionStatement(statement);
- });
-
- if (firstNode) {
- const firstJsdocText = getFileJsdoc(firstNode);
- // 标有1.2标签的声明文件,不拷贝
- if (secondRegx.test(firstJsdocText)) {
- return;
- }
- // 标有@arkts 1.1&1.2的声明文件,处理since版本号,删除@arkts 1.1&1.2标签
- if (thirdRegx.test(firstJsdocText)) {
- fileContent = handleSinceInFirstType(deleteArktsTag(fileContent));
- writeFile(outputPath, fileContent);
- return;
- }
- }
-
- handleNoTagFileInFirstType(sourceFile, outputPath, fileContent);
-}
-
-/**
- * 处理1.1目录中无arkts标签的文件
- * @param {*} sourceFile
- * @param {*} outputPath
- * @returns
- */
-function handleNoTagFileInFirstType(sourceFile, outputPath, fileContent) {
- if (path.basename(outputPath) === 'index-full.d.ts') {
- writeFile(outputPath, fileContent);
- return;
- }
- fileContent = deleteApi(sourceFile);
-
- if (fileContent === '') {
- return;
- }
- fileContent = deleteArktsTag(fileContent);
- fileContent = joinFileJsdoc(fileContent, sourceFile);
-
- fileContent = handleSinceInFirstType(fileContent);
- writeFile(outputPath, fileContent);
-}
-
-/**
- * 删除指定的arkts标签
- *
- * @param {*} fileContent 文件内容
- * @param {*} regx 删除的正则表达式
- * @returns
- */
-function deleteArktsTag(fileContent) {
- const arktsTagRegx = /\*\s*@arkts\s+1.1&1.2\s*(\r|\n)\s*|\*\s*@arkts\s*1.2s*(\r|\n)\s*|\*\s*@arkts\s*1.1s*(\r|\n)\s*/g;
- fileContent = fileContent.replace(arktsTagRegx, (substring, p1) => {
- return '';
- });
- return fileContent;
-}
-
-/**
- * 生成1.1目录里文件时,需要去掉since标签里的1.2版本号
- *
- * @param {*} sourceFile
- * @param {*} fullPath
- */
-function handleSinceInFirstType(fileContent) {
- const regx = /@since\s+arkts\s*(\{.*\})/g;
- fileContent = fileContent.replace(regx, (substring, p1) => {
- return '@since ' + JSON.parse(p1.replace(/'/g, '"'))['1.1'];
- });
- return fileContent;
-}
-
-/**
- * 处理ets2目录
- *
- * @param {string} fullPath 文件完整路径
- * @returns
- */
-function handleFileInSecondType(apiRelativePath, fullPath, type, output) {
- const secondRegx = /(?:@arkts1.2only|@arkts\s+>=\s*1.2|@arkts\s*1.2)/;
- const thirdRegx = /(?:\*\s*@arkts\s+1.1&1.2\s*(\r|\n)\s*)/;
- const arktsRegx = /\/\*\*\* if arkts (1.1&)?1.2 \*\/\s*([\s\S]*?)\s*\/\*\*\* endif \*\//g;
- let fileContent = fs.readFileSync(fullPath, 'utf-8');
- let sourceFile = ts.createSourceFile(path.basename(fullPath), fileContent, ts.ScriptTarget.ES2017, true);
- const outputPath = output ? path.join(output, apiRelativePath) : fullPath;
- if (!secondRegx.test(fileContent) && !thirdRegx.test(fileContent) && arktsRegx.test(fileContent)) {
- saveApiByArktsDefinition(sourceFile, fileContent, outputPath);
- return;
- }
- //删除使用/*** if arkts 1.2 */
- fileContent = handleArktsDefinition(type, fileContent);
- sourceFile = ts.createSourceFile(path.basename(fullPath), fileContent, ts.ScriptTarget.ES2017, true);
- const regx = /(?:@arkts1.1only|@arkts\s+<=\s+1.1)/;
-
- if (sourceFile.statements.length === 0) {
- // 有1.2标签的文件,删除标记
- if (secondRegx.test(sourceFile.getFullText())) {
- writeFile(outputPath, deleteArktsTag(fileContent));
- return;
- }
- // 处理标有@arkts 1.1&1.2的声明文件
- if (thirdRegx.test(sourceFile.getFullText())) {
- handlehasTagFile(sourceFile, outputPath);
- return;
- }
- // 处理既没有@arkts 1.2,也没有@arkts 1.1&1.2的声明文件
- handleNoTagFileInSecondType(sourceFile, outputPath, fullPath);
- return;
- }
-
- const firstNode = sourceFile.statements.find(statement => {
- return !ts.isExpressionStatement(statement);
- });
-
- if (firstNode) {
- const firstJsdocText = getFileJsdoc(firstNode);
- if (regx.test(firstJsdocText)) {
- return;
- }
- // 有1.2标签的文件,删除标记
- if (secondRegx.test(firstJsdocText)) {
- writeFile(outputPath, deleteArktsTag(fileContent));
- return;
- }
- // 处理标有@arkts 1.1&1.2的声明文件
- if (thirdRegx.test(firstJsdocText)) {
- handlehasTagFile(sourceFile, outputPath);
- return;
- }
- }
-
- // 处理既没有@arkts 1.2,也没有@arkts 1.1&1.2的声明文件
- handleNoTagFileInSecondType(sourceFile, outputPath, fullPath);
-}
-
-/**
- * 获取文件jsdoc
- * @param {*} firstNode
- * @returns
- */
-function getFileJsdoc(firstNode) {
- const firstNodeJSDoc = firstNode.getFullText().replace(firstNode.getText(), '');
- const jsdocs = firstNodeJSDoc.split('*/');
- let fileJSDoc = '';
- for (let i = 0; i < jsdocs.length; i++) {
- const jsdoc = jsdocs[i];
- if (/\@file/.test(jsdoc)) {
- fileJSDoc = jsdoc;
- break;
- }
- }
- return fileJSDoc;
-}
-
-/**
- * 处理有@arkts 1.1&1.2标签的文件
- * @param {*} outputPath
- */
-function handlehasTagFile(sourceFile, outputPath) {
- dirType = DirType.typeTwo;
- let newContent = getDeletionContent(sourceFile);
- if (newContent === '') {
- return;
- }
- // 保留最后一段注释
- newContent = saveLatestJsDoc(newContent);
- writeFile(outputPath, deleteArktsTag(newContent));
-}
-
-/**
- * 处理1.2目录中无arkts标签的文件
- * @param {*} sourceFile
- * @param {*} outputPath
- * @returns
- */
-function handleNoTagFileInSecondType(sourceFile, outputPath, fullPath) {
- dirType = DirType.typeThree;
- const arktsTagRegx = /\*\s*@arkts\s+1.1&1.2\s*(\r|\n)\s*|@arkts\s*1.2/g;
- const fileContent = sourceFile.getFullText();
- let newContent = '';
- // API未标@arkts 1.2或@arkts 1.1&1.2标签,删除文件
- // TODO: 主干挑单临时处理
- writeFile(outputPath, saveLatestJsDoc(fileContent));
- return;
- if (!arktsTagRegx.test(fileContent)) {
- if (fullPath.endsWith('.d.ts') && hasEtsFile(fullPath) || fullPath.endsWith('.d.ets') && hasTsFile(fullPath)) {
- newContent = saveLatestJsDoc(fileContent);
- newContent = deleteArktsTag(newContent);
- writeFile(outputPath, newContent);
- }
- return;
- }
- newContent = getDeletionContent(sourceFile);
- if (newContent === '') {
- return;
- }
- // 保留最后一段注释
- newContent = saveLatestJsDoc(newContent);
- newContent = deleteArktsTag(newContent);
- writeFile(outputPath, newContent);
-}
-
-/**
- * 没有arkts标签,但有if arkts 1.2和1.1&1.2的情况
- * @param {*} sourceFile
- * @param {*} fileContent
- * @param {*} outputPath
- */
-function saveApiByArktsDefinition(sourceFile, fileContent, outputPath) {
- const regx = /\/\*\*\* if arkts (1.1&)?1.2 \*\/\s*([\s\S]*?)\s*\/\*\*\* endif \*\//g;
- const regex = /\/\*\r?\n\s*\*\s*Copyright[\s\S]*?limitations under the License\.\r?\n\s*\*\//g;
- const copyrightMessage = fileContent.match(regex)[0];
- const firstNode = sourceFile.statements.find(statement => {
- return !ts.isExpressionStatement(statement);
- });
- let fileJsdoc = firstNode ? getFileJsdoc(firstNode) + '*/\n' : '';
- let newContent = copyrightMessage + fileJsdoc + Array.from(fileContent.matchAll(regx), match => match[2]).join('\n');
-
- writeFile(outputPath, saveLatestJsDoc(newContent));
-}
-
-/**
- * 拼接上被删除的文件注释
- *
- * @param {*} deletionContent
- * @param {*} sourceFile
- * @returns
- */
-function joinFileJsdoc(deletionContent, sourceFile) {
- const fileJsdoc = sourceFile.getFullText().replace(sourceFile.getText(), '');
- const copyrightMessage = hasCopyright(fileJsdoc.split('*/')[0]) ? fileJsdoc.split('*/')[0] + '*/\r\n' : '';
- const regx = /@kit | @file/g;
- let kitMessage = '';
-
- if (regx.test(fileJsdoc)) {
- kitMessage = fileJsdoc.split('*/')[1] + '*/\r\n';
- }
- let newContent = deletionContent;
- const isHasCopyright = hasCopyright(deletionContent);
-
- if (!isHasCopyright && !regx.test(deletionContent)) {
- newContent = copyrightMessage + kitMessage + deletionContent;
- } else if (!isHasCopyright) {
- newContent = copyrightMessage + deletionContent;
- } else if (isHasCopyright && !/@kit | @file/g.test(deletionContent)) {
- const joinFileJsdoc = copyrightMessage + kitMessage;
- newContent = deletionContent.replace(copyrightMessage, joinFileJsdoc);
- }
-
- if (dirType !== DirType.typeOne) {
- // TODO:添加use static字符串
- }
- return newContent;
-}
-
-function getDeletionContent(sourceFile) {
- const deletionContent = deleteApi(sourceFile);
- if (deletionContent === '') {
- return '';
- }
- let newContent = joinFileJsdoc(deletionContent, sourceFile);
-
- // 处理since版本
- newContent = handleSinceInSecondType(newContent);
- return newContent;
-}
-
-/**
- * 重写文件内容
- * @param {*} outputPath
- * @param {*} fileContent
- */
-function writeFile(outputPath, fileContent) {
- const outputDir = path.dirname(outputPath);
- let newPath = outputPath;
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir, { recursive: true });
- }
-
- if (dirType !== DirType.typeOne && isTsFile(outputPath)) {
- newPath = outputPath.replace('.d.ts', '.d.ets');
- }
- fs.writeFileSync(newPath, fileContent);
-}
-
-/**
- * 添加use static字符串
- *
- * @param {*} fileContent 文件内容
- * @param {*} copyrightMessage 版权头内容
- * @returns
- */
-function addStaticString(fileContent, copyrightMessage) {
- const hasStaticMessage = /use\s+static/g.test(fileContent);
- const regex = /\/\*\r?\n\s*\*\s*Copyright[\s\S]*?limitations under the License\.\r?\n\s*\*\//g;
- const staticMessage = 'use static';
- let newContent = fileContent;
- if (!hasStaticMessage) {
- const newfileJsdoc = `${copyrightMessage}'${staticMessage}'\r\n`;
- newContent = newContent.replace(regex, newfileJsdoc);
- }
- return newContent;
-}
-
-/**
- * 判断新生成的文件内容有没有版权头
- *
- * @param {*} fileText 新生成的文件内容
- * @returns
- */
-function hasCopyright(fileText) {
- return /http(\:|\?:)\/\/www(\.|\/)apache\.org\/licenses\/LICENSE\-2\.0 | Copyright\s*\(c\)/gi.test(fileText);
-}
-
-// 创建 Transformer
-const transformer = (context) => {
- return (rootNode) => {
- const visit = (node) => {
- //struct节点下面会自动生成constructor节点, 置为undefined
- if (node.kind === ts.SyntaxKind.Constructor && node.parent.kind === ts.SyntaxKind.StructDeclaration) {
- return undefined;
- }
-
- // 判断是否为要删除的变量声明
- if (apiNodeTypeArr.includes(node.kind) && judgeIsDeleteApi(node)) {
- collectDeletionApiName(node);
- // 删除该节点
- return undefined;
- }
-
- // 非目标节点:继续遍历子节点
- return ts.visitEachChild(node, visit, context);
- };
- return ts.visitNode(rootNode, visit);
- };
-};
-
-/**
- * 删除API
- * @param {*} sourceFile
- * @returns
- */
-function deleteApi(sourceFile) {
- let result = ts.transform(sourceFile, [transformer]);
- const newSourceFile = result.transformed[0];
- if (isEmptyFile(newSourceFile)) {
- return '';
- }
-
- // 打印结果
- const printer = ts.createPrinter();
- let fileContent = printer.printFile(newSourceFile);
- result = ts.transform(newSourceFile, [transformExportApi]);
- fileContent = printer.printFile(result.transformed[0]);
- deleteApiSet.clear();
- return fileContent.replace(/export\s*(?:type\s*)?\{\s*\}\s*(;)?/g, '');
-}
-
-/**
- * api被删除后,对应的export api也需要被删除
- * @param {*} context
- * @returns
- */
-const transformExportApi = (context) => {
- return (rootNode) => {
- const importOrExportNodeVisitor = (node) => {
- if (ts.isImportClause(node) && node.name && ts.isIdentifier(node.name) ||
- ts.isImportSpecifier(node) && node.name && ts.isIdentifier(node.name)) {
- importNameSet.add(node.name?.getText());
- }
- // 剩下未被删除的API中,如果还有与被删除API名字一样的API,就将其从set集合中删掉
- if (apiNodeTypeArr.includes(node.kind) && deleteApiSet.has(node.name?.getText())) {
- deleteApiSet.delete(node.name?.getText());
- }
- // 非目标节点:继续遍历子节点
- return ts.visitEachChild(node, importOrExportNodeVisitor, context);
- };
- ts.visitNode(rootNode, importOrExportNodeVisitor);
-
- const allNodeVisitor = (node) => {
- // 判断是否为要删除的变量声明
- if (ts.isExportAssignment(node) && deleteApiSet.has(node.expression.escapedText.toString()) &&
- !importNameSet.has(node.expression.escapedText.toString())) {
- return undefined;
- }
-
- if (ts.isExportSpecifier(node) && deleteApiSet.has(node.name.escapedText.toString()) &&
- !importNameSet.has(node.name.escapedText.toString())) {
- return undefined;
- }
-
- // 非目标节点:继续遍历子节点
- return ts.visitEachChild(node, allNodeVisitor, context);
- };
- return ts.visitNode(rootNode, allNodeVisitor);
- };
-};
-
-function isEmptyFile(node) {
- let isEmpty = true;
- if (ts.isSourceFile(node) && node.statements) {
- const needExportName = new Set();
- for (let i = 0; i < node.statements.length; i++) {
- const statement = node.statements[i];
- if (ts.isExportDeclaration(statement) && statement.moduleSpecifier) {
- isEmpty = false;
- break;
- }
- if (judgeExportHasImport(statement, needExportName)) {
- continue;
- }
- isEmpty = false;
- break;
- }
- }
- return isEmpty;
-}
-
-function collectDeletionApiName(node) {
- if (!ts.isImportClause(node)) {
- deleteApiSet.add(node.name?.getText());
- return;
- }
-
- if (ts.isImportDeclaration(node) && node.importClause?.name) {
- deleteApiSet.add(node.importClause.name.escapedText.toString());
- return;
- }
- const namedBindings = node.namedBindings;
- if (namedBindings !== undefined && ts.isNamedImports(namedBindings)) {
- const elements = namedBindings.elements;
- elements.forEach((element) => {
- const exportName = element.propertyName ?
- element.propertyName.escapedText.toString() :
- element.name.escapedText.toString();
- deleteApiSet.add(exportName);
- });
- }
-}
-
-/**
- * 判断import节点和export节点。
- * 当前文本如果还有其他节点则不能删除,
- * 如果只有import和export则判断是否export导出import节点
- *
- * @param {*} statement
- * @param {*} needExportName
- * @returns
- */
-function judgeExportHasImport(statement, needExportName) {
- if (ts.isImportDeclaration(statement)) {
- processImportDeclaration(statement, needExportName);
- return true;
- } else if (ts.isExportAssignment(statement) &&
- !needExportName.has(statement.expression.escapedText.toString())) {
- return true;
- } else if (ts.isExportDeclaration(statement)) {
- return !statement.exportClause.elements.some((element) => {
- const exportName = element.propertyName ?
- element.propertyName.escapedText.toString() :
- element.name.escapedText.toString();
- return needExportName.has(exportName);
- });
- }
- return false;
-}
-
-function processImportDeclaration(statement, needExportName) {
- const importClause = statement.importClause;
- if (!ts.isImportClause(importClause)) {
- return;
- }
- if (importClause.name) {
- needExportName.add(importClause.name.escapedText.toString());
- }
- const namedBindings = importClause.namedBindings;
- if (namedBindings !== undefined && ts.isNamedImports(namedBindings)) {
- const elements = namedBindings.elements;
- elements.forEach((element) => {
- const exportName = element.propertyName ?
- element.propertyName.escapedText.toString() :
- element.name.escapedText.toString();
- needExportName.add(exportName);
- });
- }
-}
-
-/**
- * 判断node节点中是否有famodelonly/deprecated/arkts <=1.1标签
- *
- * @param {*} node
- * @returns
- */
-function judgeIsDeleteApi(node) {
- const notesContent = node.getFullText().replace(node.getText(), '').replace(/[\s]/g, '');
- const notesArr = notesContent.split(/\/\*\*/);
- const notesStr = notesArr[notesArr.length - 1];
- const sinceArr = notesStr.match(/@since\d+/);
- let sinceVersion = 20;
-
- if (dirType === DirType.typeOne) {
- return /@arkts1\.2(?!\d)/g.test(notesStr);
- }
-
- if (sinceArr) {
- sinceVersion = sinceArr[0].replace('@since', '');
- }
-
- if (dirType === DirType.typeTwo) {
- return (/@deprecated/g.test(notesStr) && sinceVersion < 20) || /@arkts<=1.1/g.test(notesStr);
- }
-
- if (dirType === DirType.typeThree) {
- return !/@arkts1\.2\*|@arkts1\.1&1\.2\*/g.test(notesStr);
- }
-
- return false;
-}
-
-/**
- * 生成1.2目录里文件时,需要去掉since标签里的dynamic版本号
- *
- * @param {*} fileContent
- * @returns
- */
-function handleSinceInSecondType(fileContent) {
- const regx = /@since\s+arkts\s*(\{.*\})/g;
- fileContent = fileContent.replace(regx, (substring, p1) => {
- return '@since ' + JSON.parse(p1.replace(/'/g, '"'))['1.2'];
- });
- return fileContent;
-}
-
-
-function deleteSameNameFile(fullPath) {
- try {
- fs.unlinkSync(fullPath);
- } catch (error) {
- console.error('delete file failed: ', error);
- }
-}
-
-/**
- *
- * @param { string } apiPath 需要处理的api文件所在路径
- * @param { string } rootPath ets文件夹路径
- * @returns { Set } 需要处理的api文件的相对于ets目录的路径
- */
-function getApiFileName(apiPath, rootPath, allApiFilePathSet) {
- const apiFilePathSet = new Set();
- const fileNames = fs.readdirSync(apiPath);
-
- fileNames.forEach(fileName => {
- const apiFilePath = path.join(apiPath, fileName).replace(/\\/g, '/');
- const stat = fs.statSync(apiFilePath);
-
- if (stat.isDirectory()) {
- getApiFileName(apiFilePath, rootPath, allApiFilePathSet);
- } else {
- const apiRelativePath = apiFilePath.replace(rootPath, '');
- allApiFilePathSet.add(apiRelativePath);
- }
- });
-
- return apiFilePathSet;
-}
-
-// 所有API的节点类型
-const apiNodeTypeArr = [
- ts.SyntaxKind.VariableStatement,
- ts.SyntaxKind.MethodDeclaration,
- ts.SyntaxKind.MethodSignature,
- ts.SyntaxKind.FunctionDeclaration,
- ts.SyntaxKind.Constructor,
- ts.SyntaxKind.ConstructSignature,
- ts.SyntaxKind.CallSignature,
- ts.SyntaxKind.PropertyDeclaration,
- ts.SyntaxKind.PropertySignature,
- ts.SyntaxKind.EnumMember,
- ts.SyntaxKind.EnumDeclaration,
- ts.SyntaxKind.TypeAliasDeclaration,
- ts.SyntaxKind.ClassDeclaration,
- ts.SyntaxKind.InterfaceDeclaration,
- ts.SyntaxKind.ModuleDeclaration,
- ts.SyntaxKind.StructDeclaration,
- ts.SyntaxKind.GetAccessor,
- ts.SyntaxKind.SetAccessor,
- ts.SyntaxKind.IndexSignature,
-];
-
-start();
diff --git a/build-tools/package.json b/build-tools/package.json
index 130a687306e991ba3933e28048350d2ba6514342..137f7588240339ae1c479dc9e7b76de2b5a56a03 100644
--- a/build-tools/package.json
+++ b/build-tools/package.json
@@ -4,13 +4,11 @@
"description": "",
"main": "delete_systemapi_plugin.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
- "postinstall": "cd arkui_transformer && npm install"
+ "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
- "commander": "^13.1.0",
"fs": "^0.0.1-security",
"path": "^0.12.7",
"typescript": "npm:ohos-typescript@4.9.5-r5"
diff --git a/build-tools/permissions_converter/convert.js b/build-tools/permissions_converter/convert.js
index 665a3a904ef319e4c154b6495f42ff440e0a3115..87f2a4d9544c2a5698365013333b2ea9625e085c 100644
--- a/build-tools/permissions_converter/convert.js
+++ b/build-tools/permissions_converter/convert.js
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022-2025 Huawei Device Co., Ltd.
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -16,7 +16,7 @@
const fs = require('fs');
const copyRight = `/*
- * Copyright (c) 2022-2025 Huawei Device Co., Ltd.
+ * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -50,21 +50,6 @@ const copyRight = `/*
* @atomicservice
* @since 11
*/\n`;
-
- const label_1_2 = `/**
- * @file Defines all permissions.
- * @kit AbilityKit
- */
-
- /**
- * Indicates permissions.
- *
- * @typedef Permissions
- * @syscap SystemCapability.Security.AccessToken
- * @atomicservice
- * @since 20
- */\n`;
-
const typeHead = 'export type Permissions =\n';
const typeTail = ';';
const tab = ' ';
@@ -74,7 +59,6 @@ const commentHead = `${tabs}/**\n`;
const commentBody = `${tabzz}* `;
const commentTail = `${tabzz}*/\n`;
const sinceTag = '@since ';
-const arkTS20Version = 20;
const deprecatedTag = '@deprecated ';
const orOperator = `${tabs}|${tab}`;
@@ -93,57 +77,33 @@ const getPermissions = downloadPath => {
return undefined;
};
-const getArkTsVersion = (permission, fileType) => {
- if (fileType === 'ts') {
- return permission.since;
- }
- if (permission.since <= 20) {
- if (permission.deprecated && permission.deprecated !== '') {
- const deprecatedVersion = permission.deprecated.replace(/[^\d]/g, '');
- if (parseInt(deprecatedVersion) <= 20) {
- return undefined;
- }
- return arkTS20Version;
- }
- return arkTS20Version;
- } else {
- return permission.since;
- }
-}
-
const convertJsonToDTS = (permissions, outputFilePath) => {
if (fs.existsSync(outputFilePath)) {
fs.unlinkSync(outputFilePath);
}
- const fileType = outputFilePath.substring(outputFilePath.lastIndexOf(".") + 1);
fs.appendFileSync(outputFilePath, copyRight, 'utf8');
- if (fileType === 'ts') {
- fs.appendFileSync(outputFilePath, label, 'utf8');
- } else {
- fs.appendFileSync(outputFilePath, label_1_2, 'utf8');
- }
+ fs.appendFileSync(outputFilePath, label, 'utf8');
fs.appendFileSync(outputFilePath, typeHead, 'utf8');
-
permissions.forEach((permission, index) => {
- const arkTsSinceVersion = getArkTsVersion(permission, fileType);
- if (arkTsSinceVersion === undefined) {
- return;
- }
- fs.appendFileSync(outputFilePath, commentHead, 'utf8');
- const since = `${commentBody}${sinceTag}${arkTsSinceVersion}\n`;
- fs.appendFileSync(outputFilePath, since, 'utf8');
- if (permission.deprecated) {
- const deprecated = `${commentBody}${deprecatedTag}${permission.deprecated}\n`;
- fs.appendFileSync(outputFilePath, deprecated, 'utf8');
+ if (permission.since || permission.deprecated) {
+ fs.appendFileSync(outputFilePath, commentHead, 'utf8');
+ if (permission.since) {
+ const since = `${commentBody}${sinceTag}${permission.since}\n`;
+ fs.appendFileSync(outputFilePath, since, 'utf8');
+ }
+ if (permission.deprecated) {
+ const deprecated = `${commentBody}${deprecatedTag}${permission.deprecated}\n`;
+ fs.appendFileSync(outputFilePath, deprecated, 'utf8');
+ }
+ fs.appendFileSync(outputFilePath, commentTail, 'utf8');
}
- fs.appendFileSync(outputFilePath, commentTail, 'utf8');
const permissionName = `${index === 0 ? tabs : orOperator}'${permission.name}'${
index === permissions.length - 1 ? '' : '\n'
}`;
fs.appendFileSync(outputFilePath, permissionName, 'utf8');
});
fs.appendFileSync(outputFilePath, typeTail, 'utf8');
- console.log('Convert module.json definePermissions to permissions successfully, filename = ' + outputFilePath);
+ console.log('Convert config.json definePermissions to permissions.d.ts successfully');
};
/**
diff --git a/bundle.json b/bundle.json
deleted file mode 100644
index fec963ac4234b3c140b598a41e3cfa64783f768b..0000000000000000000000000000000000000000
--- a/bundle.json
+++ /dev/null
@@ -1,50 +0,0 @@
-{
- "name": "@interface/sdk",
- "description": "openharmony sdk",
- "version": "3.1",
- "license": "Apache License 2.0",
- "homePage": "https://gitee.com/openharmony/interface_sdk-js",
- "repository": "https://gitee.com/openharmony/interface_sdk-js",
- "supplier": "Organization: OpenHarmony",
- "publishAs": "code-segment",
- "segment": {
- "destPath": "interface/sdk-js"
- },
- "readmePath": {
- "zh": "README_zh.md"
- },
- "dirs": {},
- "scripts": {},
- "component": {
- "name": "sdk",
- "description": "openharmony sdk",
- "subsystem": "sdk",
- "features": [],
- "adapted_system_type": [
- "mini",
- "small",
- "standard"
- ],
- "rom": "0KB",
- "ram": "0KB",
- "deps": {
- "components": [],
- "third_party": []
- },
- "build": {
- "sub_component": [],
- "inner_api": [
- {
- "name": "//interface/sdk-js:ohos_ets_api"
- },
- {
- "name": "//interface/sdk-js:ohos_ets_arkts"
- },
- {
- "name": "//interface/sdk-js:ohos_ets_kits"
- }
- ],
- "test": []
- }
- }
-}
\ No newline at end of file
diff --git a/exists_path.py b/exists_path.py
deleted file mode 100755
index f1402517c8d5847528f6189d60aa2260d8ce4dfd..0000000000000000000000000000000000000000
--- a/exists_path.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2025 Huawei Device Co., Ltd.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import argparse
-import sys
-import os
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('--path', required=True)
- options = parser.parse_args()
- print(str(os.path.exists(options.path)))
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/interface_config.gni b/interface_config.gni
index ecd433d2e9c9083b5e181560c90c8390ddcb4101..e5d3bd01fe002defeb3679db607b974b6265e7f0 100644
--- a/interface_config.gni
+++ b/interface_config.gni
@@ -19,10 +19,3 @@ common_api_src = [
"//interface/sdk-js/api/@system.prompt.d.ts",
"//interface/sdk-js/api/@system.router.d.ts",
]
-common_api_src_ets2 = [
- "//interface/sdk-js/api/@system.app.d.ts",
- "//interface/sdk-js/api/@system.configuration.d.ts",
- "//interface/sdk-js/api/@system.mediaquery.d.ts",
- "//interface/sdk-js/api/@system.prompt.d.ts",
-]
-sdk_type = "ets"
diff --git a/ohos_copy_ets.py b/ohos_copy_ets.py
deleted file mode 100755
index 6e57f3bae2a37b08718aaab80d29311530d85481..0000000000000000000000000000000000000000
--- a/ohos_copy_ets.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Copyright (c) 2021 Huawei Device Co., Ltd.
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import argparse
-import sys
-import os
-import shutil
-import subprocess
-
-INTERFACE_PATH = "interface/sdk-js"
-PARSE_ETS2_API = "interface/sdk-js/build-tools/handleApiFiles.js"
-
-
-def parse_ets2_api(options):
- nodejs = os.path.abspath(options.node_js)
- tool = os.path.abspath(os.path.join(options.source_root_dir,
- PARSE_ETS2_API))
-
- cwd_dir = os.path.abspath(os.path.join(
- options.source_root_dir, INTERFACE_PATH))
- input_dir = os.path.abspath(options.input)
- out_dir = os.path.abspath(options.output)
- process = subprocess.run([nodejs, tool, "--path", input_dir,
- "--output", out_dir, "--type",
- options.type], shell=False,
- cwd=os.path.abspath(os.path.join(
- options.source_root_dir, cwd_dir)),
- stdout=subprocess.PIPE)
- return process
-
-
-def parse_step(options):
- parse_ets2_api(options)
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('--input', required=True)
- parser.add_argument('--output', required=True)
- parser.add_argument('--type', required=True)
- parser.add_argument('--source-root-dir', required=True)
- parser.add_argument('--node-js', required=True)
- options = parser.parse_args()
- parse_step(options)
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/process_internal.py b/process_internal.py
index f34172db46a985761894d5dfc95c729d3a95f68c..67f9612277fba21609e5ac207fab05981b2e74a6 100755
--- a/process_internal.py
+++ b/process_internal.py
@@ -17,6 +17,7 @@ import os
import sys
import optparse
import json
+import re
def copy_files(options):
@@ -28,15 +29,12 @@ def copy_files(options):
'''
with open(options.remove) as f:
remove_dict = json.load(f)
- file_list = []
if options.name in remove_dict:
rm_name = remove_dict[options.name]
if 'base' in rm_name:
- for i, base_path in enumerate(rm_name['base']):
- base_full_path = os.path.join(
- options.project_dir, base_path)
- format_src = format_path(base_full_path, options.base_dir)
- file_list.append(format_src)
+ file_list = rm_name['base']
+ else:
+ file_list = []
for file in os.listdir(options.input):
src = os.path.join(options.input, file)
if os.path.isfile(src) and (
@@ -44,7 +42,7 @@ def copy_files(options):
'global_remove' in rm_name and (
file not in rm_name['global_remove']))):
# 当前文件不在全局删除属性中
- format_src = format_path(src, options.base_dir)
+ format_src = format_path(src)
if options.ispublic == 'true':
# publicSDK需要删除sdk_build_public_remove中的文件
if 'sdk_build_public_remove' not in rm_name:
@@ -55,16 +53,18 @@ def copy_files(options):
else:
file_list.append(format_src)
else:
+ file_list = []
for file in os.listdir(options.input):
src = os.path.join(options.input, file)
if os.path.isfile(src):
- format_src = format_path(src, options.base_dir)
+ format_src = format_path(src)
file_list.append(format_src)
return file_list
-def format_path(filepath, base_dir):
- return os.path.relpath(filepath, base_dir)
+def format_path(filepath):
+ '''删除api/前面所有内容,保留api/'''
+ return re.sub(r'.*(?=api/)', '', filepath)
def parse_args(args):
@@ -72,12 +72,9 @@ def parse_args(args):
parser = optparse.OptionParser()
parser.add_option('--input', help='d.ts document input path')
parser.add_option('--remove', help='d.ts to be remove path')
- parser.add_option('--base-dir', help='d.ts document base dir path')
- parser.add_option('--project-dir', help='current project dir path')
parser.add_option('--ispublic', help='whether or not sdk build public')
parser.add_option('--name', help='module label name')
options, _ = parser.parse_args(args)
- options.input = os.path.realpath(options.input)
return options
diff --git a/remove_list.json b/remove_list.json
index 49dc0656ea0f4852287a3da22711d1500b878724..5e26b0ee886455c6f24b152dad535c649e81ea3b 100644
--- a/remove_list.json
+++ b/remove_list.json
@@ -6,7 +6,9 @@
]
},
"ets_component": {
- "global_remove": [],
+ "global_remove": [
+ "inspector.d.ts"
+ ],
"sdk_build_public_remove": [
"ability_component.d.ts",
"animator.d.ts",
@@ -28,4 +30,4 @@
"featureability.d.ts"
]
}
-}
\ No newline at end of file
+}