@buaa_smat/hometrans 0.1.20 → 26.0.0-devecocli.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (992) hide show
  1. package/LICENSE +21 -21
  2. package/agents/build-fixer.md +406 -0
  3. package/agents/code-reviewer.md +461 -496
  4. package/agents/model-render-worker.md +34 -0
  5. package/agents/model-worker.md +23 -0
  6. package/agents/specgen-worker.md +18 -0
  7. package/commands/hometrans.md +17 -0
  8. package/devecocli-plugin/common.ts +2203 -0
  9. package/devecocli-plugin/install.ts +61 -0
  10. package/devecocli-plugin/uninstall.ts +26 -0
  11. package/devecocli-plugin/update.ts +66 -0
  12. package/index.js +1418 -0
  13. package/package.json +81 -64
  14. package/platforms/atomcode/agents/build-fixer.frontmatter.md +6 -0
  15. package/platforms/atomcode/agents/code-reviewer.frontmatter.md +6 -0
  16. package/platforms/atomcode/agents/model-render-worker.frontmatter.md +6 -0
  17. package/platforms/atomcode/agents/model-worker.frontmatter.md +6 -0
  18. package/platforms/atomcode/agents/specgen-worker.frontmatter.md +6 -0
  19. package/platforms/deveco/agents/build-fixer.frontmatter.md +5 -0
  20. package/platforms/deveco/agents/code-reviewer.frontmatter.md +5 -0
  21. package/platforms/deveco/agents/model-render-worker.frontmatter.md +5 -0
  22. package/platforms/deveco/agents/model-worker.frontmatter.md +5 -0
  23. package/platforms/deveco/agents/specgen-worker.frontmatter.md +5 -0
  24. package/platforms/opencode/agents/build-fixer.frontmatter.md +5 -0
  25. package/platforms/opencode/agents/code-reviewer.frontmatter.md +5 -0
  26. package/platforms/opencode/agents/model-render-worker.frontmatter.md +5 -0
  27. package/platforms/opencode/agents/model-worker.frontmatter.md +5 -0
  28. package/platforms/opencode/agents/specgen-worker.frontmatter.md +5 -0
  29. package/plugin.jsonc +12 -0
  30. package/skills/a2h-app-migrate/SKILL.md +181 -0
  31. package/skills/a2h-app-migrate/references/config.example.json +27 -0
  32. package/skills/a2h-app-migrate/references/specs.example.json +19 -0
  33. package/skills/a2h-app-migrate/references/stage-map.md +33 -0
  34. package/skills/a2h-app-migrate/references/workflow.yaml +1600 -0
  35. package/skills/a2h-app-migrate/scripts/android_index.mjs +109 -0
  36. package/skills/a2h-app-migrate/scripts/check_arch_done.mjs +80 -0
  37. package/skills/a2h-app-migrate/scripts/check_module_docs_done.mjs +95 -0
  38. package/skills/a2h-app-migrate/scripts/check_signing.mjs +152 -0
  39. package/skills/a2h-app-migrate/scripts/check_spec_gen_done.mjs +114 -0
  40. package/skills/a2h-app-migrate/scripts/check_spec_pipeline_done.mjs +277 -0
  41. package/skills/a2h-app-migrate/scripts/check_ui_batch_done.mjs +77 -0
  42. package/skills/a2h-app-migrate/scripts/check_utg_static_done.mjs +147 -0
  43. package/skills/a2h-app-migrate/scripts/cli_values.mjs +32 -0
  44. package/skills/a2h-app-migrate/scripts/env_preflight.mjs +1412 -0
  45. package/skills/a2h-app-migrate/scripts/human_review_gate.mjs +651 -0
  46. package/skills/a2h-app-migrate/scripts/infer_android_root.mjs +53 -0
  47. package/skills/a2h-app-migrate/scripts/json_io.mjs +35 -0
  48. package/skills/a2h-app-migrate/scripts/ledger.mjs +104 -0
  49. package/skills/a2h-app-migrate/scripts/lib-yaml-lite.mjs +288 -0
  50. package/skills/a2h-app-migrate/scripts/paths_preflight.mjs +881 -0
  51. package/skills/a2h-app-migrate/scripts/resume_plan.mjs +205 -0
  52. package/skills/a2h-app-migrate/scripts/reuse_static_utg.mjs +121 -0
  53. package/skills/a2h-app-migrate/scripts/run_dir.mjs +212 -0
  54. package/skills/a2h-app-migrate/scripts/spec_layout.mjs +30 -0
  55. package/skills/a2h-app-migrate/scripts/validate_workflow.mjs +455 -0
  56. package/skills/a2h-app-migrate/test/test_android_index.mjs +80 -0
  57. package/skills/a2h-app-migrate/test/test_apk_preflight.mjs +63 -0
  58. package/skills/a2h-app-migrate/test/test_arch_done.mjs +54 -0
  59. package/skills/a2h-app-migrate/test/test_build_fixer_contract.mjs +92 -0
  60. package/skills/a2h-app-migrate/test/test_config_example.mjs +42 -0
  61. package/skills/a2h-app-migrate/test/test_entry_guards.mjs +93 -0
  62. package/skills/a2h-app-migrate/test/test_env_requirements.mjs +544 -0
  63. package/skills/a2h-app-migrate/test/test_finalize.mjs +89 -0
  64. package/skills/a2h-app-migrate/test/test_gate_checkpoint.mjs +146 -0
  65. package/skills/a2h-app-migrate/test/test_hmos_fingerprint.mjs +68 -0
  66. package/skills/a2h-app-migrate/test/test_infer_android_root.mjs +91 -0
  67. package/skills/a2h-app-migrate/test/test_interaction.mjs +122 -0
  68. package/skills/a2h-app-migrate/test/test_json_io.mjs +32 -0
  69. package/skills/a2h-app-migrate/test/test_leaf_questions.mjs +109 -0
  70. package/skills/a2h-app-migrate/test/test_module_docs_done.mjs +53 -0
  71. package/skills/a2h-app-migrate/test/test_parse_args.mjs +69 -0
  72. package/skills/a2h-app-migrate/test/test_preflight_report.mjs +93 -0
  73. package/skills/a2h-app-migrate/test/test_resume_plan.mjs +144 -0
  74. package/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +100 -0
  75. package/skills/a2h-app-migrate/test/test_run_dir.mjs +315 -0
  76. package/skills/a2h-app-migrate/test/test_skill_doc.mjs +133 -0
  77. package/skills/a2h-app-migrate/test/test_spec_gen_done.mjs +133 -0
  78. package/skills/a2h-app-migrate/test/test_spec_gen_gate.mjs +158 -0
  79. package/skills/a2h-app-migrate/test/test_spec_pipeline_done.mjs +181 -0
  80. package/skills/a2h-app-migrate/test/test_specs_json_preflight.mjs +76 -0
  81. package/skills/a2h-app-migrate/test/test_ui_batch_done.mjs +53 -0
  82. package/skills/a2h-app-migrate/test/test_ui_batch_gate.mjs +226 -0
  83. package/skills/a2h-app-migrate/test/test_uniapp_preflight.mjs +83 -0
  84. package/skills/a2h-app-migrate/test/test_utg_dirs.mjs +39 -0
  85. package/skills/a2h-app-migrate/test/test_utg_static_done.mjs +168 -0
  86. package/skills/a2h-app-migrate/test/test_validate_races.mjs +50 -0
  87. package/skills/a2h-arch-generate/SKILL.md +375 -0
  88. package/skills/a2h-arch-generate/examples/reconcile-existing-project.md +107 -0
  89. package/skills/a2h-arch-generate/examples/simple-conversion-android.md +103 -0
  90. package/skills/a2h-arch-generate/examples/simple-conversion-backend.md +70 -0
  91. package/skills/a2h-arch-generate/examples/simple-conversion-uniapp.md +106 -0
  92. package/skills/{hmos-batch-ui-align/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md → a2h-arch-generate/references/arkts-mvvm-v2.md} +1407 -1407
  93. package/skills/a2h-arch-generate/references/artifact-contracts.generate.md +120 -0
  94. package/skills/a2h-arch-generate/references/artifact-contracts.reconcile.md +123 -0
  95. package/skills/a2h-arch-generate/references/bpta-layered-architecture-design.md +88 -0
  96. package/skills/a2h-arch-generate/references/clustering-guidance.md +33 -0
  97. package/skills/a2h-arch-generate/references/database-schema-recovery.md +107 -0
  98. package/skills/a2h-arch-generate/references/existing-target-annotation.md +68 -0
  99. package/skills/a2h-arch-generate/references/harmony-project-inspection.md +150 -0
  100. package/skills/a2h-arch-generate/references/harmony-target-architecture.md +94 -0
  101. package/skills/a2h-arch-generate/references/homegraph-workflow.md +120 -0
  102. package/skills/a2h-arch-generate/references/module-evidence-subagent.md +45 -0
  103. package/skills/a2h-arch-generate/references/reconciliation-model.md +204 -0
  104. package/skills/a2h-arch-generate/references/scope-policy.md +28 -0
  105. package/skills/a2h-arch-generate/references/semantic-review.md +65 -0
  106. package/skills/a2h-arch-generate/references/source-baseline.md +93 -0
  107. package/skills/a2h-arch-generate/references/source-ecosystems.md +54 -0
  108. package/skills/a2h-arch-generate/references/transformation-model.md +78 -0
  109. package/skills/a2h-arch-generate/scripts/check_module_staleness.mjs +284 -0
  110. package/skills/a2h-arch-generate/scripts/cleanup_intermediates.mjs +260 -0
  111. package/skills/a2h-arch-generate/scripts/compute_processing_order.mjs +325 -0
  112. package/skills/a2h-arch-generate/scripts/create_project.mjs +149 -0
  113. package/skills/a2h-arch-generate/scripts/dump_core_facts.mjs +151 -0
  114. package/skills/a2h-arch-generate/scripts/extract_core_components.mjs +167 -0
  115. package/skills/a2h-arch-generate/scripts/generate_source_baseline.mjs +363 -0
  116. package/skills/a2h-arch-generate/scripts/generate_state.mjs +60 -0
  117. package/skills/a2h-arch-generate/scripts/inspect_and_route.mjs +326 -0
  118. package/skills/a2h-arch-generate/scripts/inspect_android_project.mjs +3739 -0
  119. package/skills/a2h-arch-generate/scripts/inspect_harmony_target.mjs +800 -0
  120. package/skills/a2h-arch-generate/scripts/inspect_project.mjs +251 -0
  121. package/skills/a2h-arch-generate/scripts/inspect_uniapp_project.mjs +809 -0
  122. package/skills/a2h-arch-generate/scripts/lib/py_compat.mjs +1454 -0
  123. package/skills/a2h-arch-generate/scripts/module_create/create.mjs +136 -0
  124. package/skills/a2h-arch-generate/scripts/module_create/generate.mjs +636 -0
  125. package/skills/a2h-arch-generate/scripts/module_create/hap/build-profile.json5 +33 -0
  126. package/skills/a2h-arch-generate/scripts/module_create/hap/hvigorfile.ts +6 -0
  127. package/skills/a2h-arch-generate/scripts/module_create/hap/obfuscation-rules.txt +23 -0
  128. package/skills/a2h-arch-generate/scripts/module_create/hap/oh-package.json5 +10 -0
  129. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/applicationability/ApplicationAbility.ets +43 -0
  130. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/pages/Index.ets +23 -0
  131. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/module.json5 +26 -0
  132. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/color.json +8 -0
  133. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/float.json +8 -0
  134. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/string.json +16 -0
  135. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/background.png +0 -0
  136. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/foreground.png +0 -0
  137. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/layered_image.json +7 -0
  138. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/startIcon.png +0 -0
  139. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/profile/main_pages.json +5 -0
  140. package/skills/a2h-arch-generate/scripts/module_create/hap/src/mock/mock-config.json5 +2 -0
  141. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/Ability.test.ets +35 -0
  142. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/List.test.ets +5 -0
  143. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/module.json5 +11 -0
  144. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/List.test.ets +5 -0
  145. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/LocalUnit.test.ets +33 -0
  146. package/skills/a2h-arch-generate/scripts/module_create/har/Index.ets +1 -0
  147. package/skills/a2h-arch-generate/scripts/module_create/har/build-profile.json5 +36 -0
  148. package/skills/a2h-arch-generate/scripts/module_create/har/hvigorfile.ts +6 -0
  149. package/skills/a2h-arch-generate/scripts/module_create/har/obfuscation-rules.txt +23 -0
  150. package/skills/a2h-arch-generate/scripts/module_create/har/oh-package.json5 +9 -0
  151. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/ets/components/MainPage.ets +19 -0
  152. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/module.json5 +9 -0
  153. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/float.json +8 -0
  154. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/string.json +8 -0
  155. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/Ability.test.ets +35 -0
  156. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/List.test.ets +5 -0
  157. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/module.json5 +11 -0
  158. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/List.test.ets +5 -0
  159. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/LocalUnit.test.ets +33 -0
  160. package/skills/a2h-arch-generate/scripts/module_create/hsp/Index.ets +1 -0
  161. package/skills/a2h-arch-generate/scripts/module_create/hsp/build-profile.json5 +36 -0
  162. package/skills/a2h-arch-generate/scripts/module_create/hsp/consumer-rules.txt +0 -0
  163. package/skills/a2h-arch-generate/scripts/module_create/hsp/hvigorfile.ts +6 -0
  164. package/skills/a2h-arch-generate/scripts/module_create/hsp/obfuscation-rules.txt +23 -0
  165. package/skills/a2h-arch-generate/scripts/module_create/hsp/oh-package.json5 +10 -0
  166. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/pages/Index.ets +20 -0
  167. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/utils/Calc.ets +3 -0
  168. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/module.json5 +12 -0
  169. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/float.json +8 -0
  170. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/string.json +8 -0
  171. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/profile/main_pages.json +5 -0
  172. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/Ability.test.ets +35 -0
  173. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/List.test.ets +5 -0
  174. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/module.json5 +11 -0
  175. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/List.test.ets +5 -0
  176. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/LocalUnit.test.ets +33 -0
  177. package/skills/a2h-arch-generate/scripts/module_create/testdata/reconcile-layer-PROJECT_DESIGN.md +47 -0
  178. package/skills/a2h-arch-generate/scripts/module_create/testdata/single-entry-PROJECT_DESIGN.md +15 -0
  179. package/skills/a2h-arch-generate/scripts/module_create/testdata/three-layer-PROJECT_DESIGN.md +36 -0
  180. package/skills/a2h-arch-generate/scripts/module_create/testdata/verification-report.md +150 -0
  181. package/skills/a2h-arch-generate/scripts/resolve_android_stores.mjs +529 -0
  182. package/skills/a2h-arch-generate/scripts/scaffold_project.mjs +230 -0
  183. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/build.gradle +11 -0
  184. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/AndroidManifest.xml +12 -0
  185. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/MainActivity.kt +8 -0
  186. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/NotesStore.kt +17 -0
  187. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/build.gradle +3 -0
  188. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/settings.gradle +1 -0
  189. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/AppScope/app.json5 +8 -0
  190. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/build-profile.json5 +14 -0
  191. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/build-profile.json5 +7 -0
  192. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/oh-package.json5 +1 -0
  193. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/src/main/ets/utils/Format.ets +3 -0
  194. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/build-profile.json5 +7 -0
  195. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/oh-package.json5 +1 -0
  196. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/src/main/ets/pages/Home.ets +3 -0
  197. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/build-profile.json5 +7 -0
  198. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/oh-package.json5 +1 -0
  199. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/src/main/ets/engine/SyncEngine.ets +3 -0
  200. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/hvigorfile.ts +1 -0
  201. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/oh-package.json5 +1 -0
  202. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/build-profile.json5 +7 -0
  203. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/oh-package.json5 +9 -0
  204. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/src/main/ets/pages/Index.ets +7 -0
  205. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/App.vue +10 -0
  206. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/manifest.json +6 -0
  207. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages/index/index.vue +16 -0
  208. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages.json +5 -0
  209. package/skills/a2h-arch-generate/scripts/tests/e2e/run_e2e.mjs +548 -0
  210. package/skills/a2h-arch-generate/scripts/tests/run_tests.mjs +1122 -0
  211. package/skills/a2h-arch-generate/scripts/tests/test_cleanup.mjs +191 -0
  212. package/skills/a2h-arch-generate/scripts/tests/test_console_encoding.mjs +52 -0
  213. package/skills/a2h-arch-generate/scripts/tests/test_git_root.mjs +34 -0
  214. package/skills/a2h-arch-generate/scripts/tests/test_router.mjs +138 -0
  215. package/skills/a2h-arch-generate/scripts/validate_architecture_docs.mjs +829 -0
  216. package/skills/a2h-arch-generate/scripts/validate_data_docs.mjs +937 -0
  217. package/skills/a2h-arch-generate/scripts/validate_homegraph_artifacts.mjs +542 -0
  218. package/skills/a2h-arch-generate/scripts/validate_incremental_docs.mjs +415 -0
  219. package/skills/a2h-arkts-logic-coder/SKILL.md +125 -0
  220. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +6 -0
  221. package/skills/a2h-arkts-logic-coder/references/code-generation.md +124 -0
  222. package/skills/a2h-arkts-logic-coder/scripts/check_module_scope.ts +224 -0
  223. package/skills/a2h-arkts-logic-coder/scripts/check_mvvm.ts +377 -0
  224. package/skills/a2h-arkts-logic-coder/scripts/stop_check_hook.ts +443 -0
  225. package/skills/a2h-arkts-logic-coder/scripts/test_check_scripts.ts +211 -0
  226. package/skills/a2h-arkts-logic-coder/scripts/test_worktree_compat.ts +81 -0
  227. package/skills/a2h-batch-ui-align/SKILL.md +321 -0
  228. package/skills/a2h-batch-ui-align/assets/ColorUtils.ets +81 -0
  229. package/skills/a2h-batch-ui-align/flowchart.html +271 -0
  230. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +572 -0
  231. package/skills/a2h-batch-ui-align/references/incremental-scope.md +139 -0
  232. package/skills/a2h-batch-ui-align/references/lottie-integration.md +43 -0
  233. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2535 -2533
  234. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +558 -555
  235. package/skills/{hmos-incremental-ui-align/references → a2h-batch-ui-align/references/mappings}/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -117
  236. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/@Link/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/217/214/345/220/221/345/220/214/346/255/245.md +648 -648
  237. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm/@Observed/350/243/205/351/245/260/345/231/250/345/222/214@ObjectLink/350/243/205/351/245/260/345/231/250/357/274/232/345/265/214/345/245/227/347/261/273/345/257/271/350/261/241/345/261/236/346/200/247/345/217/230/345/214/226.md +2088 -2088
  238. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm/@Prop/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/215/225/345/220/221/345/220/214/346/255/245.md +1033 -1033
  239. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/@Provide/350/243/205/351/245/260/345/231/250/345/222/214@Consume/350/243/205/351/245/260/345/231/250/357/274/232/344/270/216/345/220/216/344/273/243/347/273/204/344/273/266/345/217/214/345/220/221/345/220/214/346/255/245.md +1183 -1183
  240. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/@State/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/347/212/266/346/200/201.md +576 -576
  241. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/@Track/350/243/205/351/245/260/345/231/250/357/274/232class/345/257/271/350/261/241/345/261/236/346/200/247/347/272/247/346/233/264/346/226/260.md +297 -297
  242. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/@Watch/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/346/233/264/346/224/271/351/200/232/347/237/245.md +395 -395
  243. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/AppStorage/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200/347/232/204UI/347/212/266/346/200/201/345/255/230/345/202/250.md +902 -902
  244. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm/Environment/357/274/232/350/256/276/345/244/207/347/216/257/345/242/203/346/237/245/350/257/242.md +106 -106
  245. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/LocalStorage/357/274/232/351/241/265/351/235/242/347/272/247UI/347/212/266/346/200/201/345/255/230/345/202/250.md +1178 -1178
  246. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md +911 -911
  247. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}/PersistentStorage/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +354 -354
  248. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243 → a2h-batch-ui-align/references/mvvm}//347/256/241/347/220/206/345/272/224/347/224/250/346/213/245/346/234/211/347/232/204/347/212/266/346/200/201/346/246/202/350/277/260.md +11 -11
  249. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md +206 -206
  250. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@Computed/350/243/205/351/245/260/345/231/250/357/274/232/350/256/241/347/256/227/345/261/236/346/200/247.md +373 -373
  251. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@Event/350/243/205/351/245/260/345/231/250/357/274/232/350/247/204/350/214/203/347/273/204/344/273/266/350/276/223/345/207/272.md +158 -158
  252. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/@Local/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/351/203/250/347/212/266/346/200/201.md +750 -750
  253. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@Monitor/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/344/277/256/346/224/271/345/274/202/346/255/245/347/233/221/345/220/254.md +1704 -1704
  254. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@ObservedV2/350/243/205/351/245/260/345/231/250/345/222/214@Trace/350/243/205/351/245/260/345/231/250/357/274/232/347/261/273/345/261/236/346/200/247/345/217/230/345/214/226/350/247/202/346/265/213.md +1012 -1012
  255. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@Once/350/243/205/351/245/260/345/231/250/357/274/232/345/210/235/345/247/213/345/214/226/345/220/214/346/255/245/344/270/200/346/254/241.md +164 -164
  256. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/@Param/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/244/226/351/203/250/350/276/223/345/205/245.md +840 -840
  257. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/@Provider/350/243/205/351/245/260/345/231/250/345/222/214@Consumer/350/243/205/351/245/260/345/231/250/357/274/232/350/267/250/347/273/204/344/273/266/345/261/202/347/272/247/345/217/214/345/220/221/345/220/214/346/255/245.md +856 -856
  258. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/@Type/350/243/205/351/245/260/345/231/250/357/274/232/346/240/207/350/256/260/347/261/273/345/261/236/346/200/247/347/232/204/347/261/273/345/236/213.md +83 -83
  259. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/AppStorageV2/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200UI/347/212/266/346/200/201/345/255/230/345/202/250.md +294 -294
  260. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -1407
  261. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}/PersistenceV2/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +1220 -1220
  262. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +47 -47
  263. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/references/mvvm-v2/_/350/243/205/351/245/260/345/231/250/351/200/237/346/237/245.md +133 -133
  264. package/skills/{hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2 → a2h-batch-ui-align/references/mvvm-v2}//347/212/266/346/200/201/347/256/241/347/220/206V1/345/220/221V2/350/277/201/347/247/273/344/270/216/346/267/267/347/224/250/346/214/207/345/257/274.md +840 -840
  265. package/skills/a2h-batch-ui-align/references/source-only-tier.md +32 -0
  266. package/skills/a2h-batch-ui-align/references/step3-capture.md +214 -0
  267. package/skills/a2h-batch-ui-align/references/step4-prepare.md +196 -0
  268. package/skills/a2h-batch-ui-align/references/step5-convert.md +205 -0
  269. package/skills/a2h-batch-ui-align/scripts/agent_cli.mjs +572 -0
  270. package/skills/{hmos-batch-ui-align → a2h-batch-ui-align}/scripts/android_parse_fast.ts +246 -39
  271. package/skills/a2h-batch-ui-align/scripts/answers_check.mjs +86 -0
  272. package/skills/a2h-batch-ui-align/scripts/arkts_static_check.ts +3858 -0
  273. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +1675 -0
  274. package/skills/a2h-batch-ui-align/scripts/databinding_analyzer_design.md +79 -0
  275. package/skills/a2h-batch-ui-align/scripts/detach.mjs +258 -0
  276. package/skills/a2h-batch-ui-align/scripts/export_ui_info.mjs +1644 -0
  277. package/skills/a2h-batch-ui-align/scripts/generate_pages_json.mjs +612 -0
  278. package/skills/a2h-batch-ui-align/scripts/group_commit.mjs +166 -0
  279. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +1627 -0
  280. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +1869 -0
  281. package/skills/a2h-batch-ui-align/scripts/group_watch.mjs +696 -0
  282. package/skills/a2h-batch-ui-align/scripts/harmony_index.mjs +218 -0
  283. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +208 -0
  284. package/skills/a2h-batch-ui-align/scripts/measure_pack.ts +1229 -0
  285. package/skills/a2h-batch-ui-align/scripts/occlusion.mjs +141 -0
  286. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +1179 -0
  287. package/skills/a2h-batch-ui-align/scripts/shell_contract.mjs +1036 -0
  288. package/skills/a2h-batch-ui-align/scripts/tests/agent_cli.test.mjs +217 -0
  289. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_align_tint.test.mjs +253 -0
  290. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_canvas_pct.test.mjs +312 -0
  291. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_fidelity.test.mjs +241 -0
  292. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_layout_placement.test.mjs +341 -0
  293. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_review_fixes.test.mjs +298 -0
  294. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_rules.test.mjs +365 -0
  295. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_shell.test.mjs +91 -0
  296. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_weight_color.test.mjs +445 -0
  297. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set.test.mjs +356 -0
  298. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set_scope.test.mjs +290 -0
  299. package/skills/a2h-batch-ui-align/scripts/tests/color_utils_asset.test.mjs +74 -0
  300. package/skills/a2h-batch-ui-align/scripts/tests/export_scroll_states.test.mjs +31 -0
  301. package/skills/a2h-batch-ui-align/scripts/tests/export_ui_info.test.mjs +564 -0
  302. package/skills/a2h-batch-ui-align/scripts/tests/generate_pages_json.test.mjs +123 -0
  303. package/skills/a2h-batch-ui-align/scripts/tests/group_commit.test.mjs +126 -0
  304. package/skills/a2h-batch-ui-align/scripts/tests/group_pack.test.mjs +241 -0
  305. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +1451 -0
  306. package/skills/a2h-batch-ui-align/scripts/tests/group_watch.test.mjs +215 -0
  307. package/skills/a2h-batch-ui-align/scripts/tests/harmony_index.test.mjs +95 -0
  308. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +115 -0
  309. package/skills/a2h-batch-ui-align/scripts/tests/measure_pack.test.mjs +170 -0
  310. package/skills/a2h-batch-ui-align/scripts/tests/occlusion.test.mjs +102 -0
  311. package/skills/a2h-batch-ui-align/scripts/tests/phase5_check.test.mjs +244 -0
  312. package/skills/a2h-batch-ui-align/scripts/tests/shell_contract.test.mjs +166 -0
  313. package/skills/a2h-batch-ui-align/scripts/tests/test_bfs_exit.ts +49 -0
  314. package/skills/a2h-batch-ui-align/scripts/tests/text_color_diff.test.mjs +219 -0
  315. package/skills/a2h-batch-ui-align/scripts/text_color_diff.mjs +470 -0
  316. package/skills/a2h-coldstart-smoke-gate/SKILL.md +57 -0
  317. package/skills/a2h-dashboard-render/SKILL.md +65 -0
  318. package/skills/a2h-dashboard-render/references/artifact-contract.jsonc +147 -0
  319. package/skills/a2h-dashboard-render/references/artifact-registry-spec.md +67 -0
  320. package/skills/a2h-dashboard-render/references/dashboard.config.example.json +19 -0
  321. package/skills/a2h-dashboard-render/references//347/234/213/346/235/277/350/257/264/346/230/216.md +83 -0
  322. package/skills/a2h-dashboard-render/scripts/artifact_contract.mjs +138 -0
  323. package/skills/a2h-dashboard-render/scripts/check-registry.mjs +87 -0
  324. package/skills/a2h-dashboard-render/scripts/dashboard.mjs +3215 -0
  325. package/skills/a2h-dashboard-render/scripts/device_capture.mjs +2010 -0
  326. package/skills/a2h-dashboard-render/scripts/page_capture.mjs +828 -0
  327. package/skills/a2h-dashboard-render/scripts/usage_readers.mjs +459 -0
  328. package/skills/a2h-dashboard-render/scripts/usage_worker.mjs +13 -0
  329. package/skills/a2h-dashboard-render/test/fixtures/page_capture/broken.xml +1 -0
  330. package/skills/a2h-dashboard-render/test/fixtures/page_capture/expected.json +156 -0
  331. package/skills/a2h-dashboard-render/test/fixtures/page_capture/hmos.json +1 -0
  332. package/skills/a2h-dashboard-render/test/fixtures/page_capture/list.xml +1 -0
  333. package/skills/a2h-dashboard-render/test/fixtures/page_capture/nested_scroll.xml +1 -0
  334. package/skills/a2h-dashboard-render/test/test_artifact_contract.mjs +170 -0
  335. package/skills/a2h-dashboard-render/test/test_cli_check_registry.mjs +99 -0
  336. package/skills/a2h-dashboard-render/test/test_dashboard_architecture.mjs +182 -0
  337. package/skills/a2h-dashboard-render/test/test_dashboard_build.mjs +64 -0
  338. package/skills/a2h-dashboard-render/test/test_dashboard_node.mjs +1172 -0
  339. package/skills/a2h-dashboard-render/test/test_dashboard_spec_pipeline.mjs +251 -0
  340. package/skills/a2h-dashboard-render/test/test_dashboard_ui_pipeline.mjs +81 -0
  341. package/skills/a2h-dashboard-render/test/test_device_capture_env.mjs +115 -0
  342. package/skills/a2h-dashboard-render/test/test_device_capture_policy.mjs +303 -0
  343. package/skills/a2h-dashboard-render/test/test_page_capture.mjs +147 -0
  344. package/skills/a2h-dashboard-render/test/test_usage_readers.mjs +444 -0
  345. package/skills/{hmos-fix-build-errors → a2h-fix-build-errors}/SKILL.md +305 -293
  346. package/skills/{hmos-fix-build-errors → a2h-fix-build-errors}/references/arkts-strict-patterns.md +219 -219
  347. package/skills/{hmos-fix-build-errors → a2h-fix-build-errors}/references/known-patterns.md +157 -157
  348. package/skills/{hmos-fix-build-errors → a2h-fix-build-errors}/references/rdb-entity-pattern.md +131 -131
  349. package/skills/a2h-module-semantic-docs/SKILL.md +227 -0
  350. package/skills/a2h-module-semantic-docs/scripts/commit_module_state.mjs +168 -0
  351. package/skills/a2h-module-semantic-docs/scripts/lib/py_compat.mjs +688 -0
  352. package/skills/a2h-module-semantic-docs/scripts/scan_modules.mjs +1021 -0
  353. package/skills/a2h-module-semantic-docs/test/golden/module_structure.json +187 -0
  354. package/skills/a2h-module-semantic-docs/test/golden/module_understanding.json +351 -0
  355. package/skills/a2h-module-semantic-docs/test/golden/module_update_plan.json +495 -0
  356. package/skills/a2h-module-semantic-docs/test/golden/project_directory_structure.json +157 -0
  357. package/skills/a2h-module-semantic-docs/test/test_scan_and_commit.mjs +388 -0
  358. package/skills/a2h-resource-convert/SKILL.md +369 -0
  359. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/code-vector-icon-rules.md +335 -335
  360. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/conversion-rules.md +687 -676
  361. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/dependency-analysis-rules.md +410 -410
  362. package/skills/a2h-resource-convert/references/incremental-page-migration.md +251 -0
  363. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/lottie-conversion-rules.md +219 -219
  364. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/resource-mapping-rules.md +493 -482
  365. package/skills/a2h-resource-convert/references/step3_5-dependency-filter.md +54 -0
  366. package/skills/a2h-resource-convert/references/step4-qualifiers-and-values.md +142 -0
  367. package/skills/a2h-resource-convert/references/step4-resource-types.md +249 -0
  368. package/skills/a2h-resource-convert/references/step5-reference-resolution.md +154 -0
  369. package/skills/a2h-resource-convert/references/step7-report-template.md +217 -0
  370. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/xml-drawable-to-svg-rules.md +630 -592
  371. package/skills/{hmos-resources-convert → a2h-resource-convert}/scripts/a2h_resource_convert.ts +2529 -2163
  372. package/skills/a2h-resource-convert/scripts/a2h_resource_incremental.ts +1072 -0
  373. package/skills/a2h-resource-convert/scripts/app_identity.ts +947 -0
  374. package/skills/{hmos-resources-convert → a2h-resource-convert}/scripts/code_vector_icons.ts +607 -591
  375. package/skills/a2h-resource-convert/scripts/extract_page_resources.ts +989 -0
  376. package/skills/a2h-resource-convert/scripts/extract_project_resources.ts +1464 -0
  377. package/skills/{hmos-resources-convert → a2h-resource-convert}/scripts/svg_fidelity_check.ts +632 -632
  378. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +182 -0
  379. package/skills/a2h-resource-convert/scripts/tests/app_identity.test.mjs +206 -0
  380. package/skills/a2h-spec-design/SKILL.md +336 -0
  381. package/skills/a2h-spec-design/scripts/inspect_spec_design_inputs.mjs +146 -0
  382. package/skills/a2h-spec-design/scripts/lib/py_compat.mjs +481 -0
  383. package/skills/a2h-spec-design/scripts/move_spec_technical_reference.mjs +159 -0
  384. package/skills/a2h-spec-design/scripts/resolve_module_design.mjs +102 -0
  385. package/skills/a2h-spec-design/scripts/validate_spec_design_output.mjs +285 -0
  386. package/skills/a2h-spec-design/test/golden/inspect_happy.json +20 -0
  387. package/skills/a2h-spec-design/test/golden/move_design.md +18 -0
  388. package/skills/a2h-spec-design/test/golden/move_design_crlf.md +18 -0
  389. package/skills/a2h-spec-design/test/golden/move_spec.md +7 -0
  390. package/skills/a2h-spec-design/test/golden/resolve_cases.json +36 -0
  391. package/skills/a2h-spec-design/test/golden/validate_issue_file.md +12 -0
  392. package/skills/a2h-spec-design/test/golden/validate_issues.json +57 -0
  393. package/skills/a2h-spec-design/test/test_spec_design_scripts.mjs +381 -0
  394. package/skills/a2h-spec-design-pipeline/SKILL.md +228 -0
  395. package/skills/a2h-spec-design-pipeline/package.json +4 -0
  396. package/skills/a2h-spec-design-pipeline/references/coding-loop.md +63 -0
  397. package/skills/a2h-spec-design-pipeline/references/execution-model.md +69 -0
  398. package/skills/a2h-spec-design-pipeline/references/final-report-template.md +24 -0
  399. package/skills/a2h-spec-design-pipeline/references/initialization.md +57 -0
  400. package/skills/a2h-spec-design-pipeline/references/merge-queue.md +21 -0
  401. package/skills/a2h-spec-design-pipeline/references/scripts.md +27 -0
  402. package/skills/a2h-spec-design-pipeline/references/specs.example.json +19 -0
  403. package/skills/a2h-spec-design-pipeline/references/state-and-resume.md +21 -0
  404. package/skills/a2h-spec-design-pipeline/scripts/atomic_write.ts +42 -0
  405. package/skills/a2h-spec-design-pipeline/scripts/audit_claims.ts +252 -0
  406. package/skills/a2h-spec-design-pipeline/scripts/branch_landed.ts +77 -0
  407. package/skills/a2h-spec-design-pipeline/scripts/deps_ready.ts +195 -0
  408. package/skills/a2h-spec-design-pipeline/scripts/ensure_wt_index.ts +651 -0
  409. package/skills/a2h-spec-design-pipeline/scripts/git_baseline.ts +124 -0
  410. package/skills/a2h-spec-design-pipeline/scripts/inflight.mjs +944 -0
  411. package/skills/a2h-spec-design-pipeline/scripts/lib/bgcli.mjs +95 -0
  412. package/skills/a2h-spec-design-pipeline/scripts/plan_groups.ts +502 -0
  413. package/skills/a2h-spec-design-pipeline/scripts/plan_waves.ts +475 -0
  414. package/skills/a2h-spec-design-pipeline/scripts/reconcile.mjs +218 -0
  415. package/skills/a2h-spec-design-pipeline/scripts/resolve_wiring.ts +164 -0
  416. package/skills/a2h-spec-design-pipeline/scripts/test_atomic_write.ts +44 -0
  417. package/skills/a2h-spec-design-pipeline/scripts/test_audit_claims.ts +301 -0
  418. package/skills/a2h-spec-design-pipeline/scripts/test_bgcli.mjs +64 -0
  419. package/skills/a2h-spec-design-pipeline/scripts/test_branch_landed.ts +87 -0
  420. package/skills/a2h-spec-design-pipeline/scripts/test_deps_ready.ts +265 -0
  421. package/skills/a2h-spec-design-pipeline/scripts/test_ensure_wt_index.ts +675 -0
  422. package/skills/a2h-spec-design-pipeline/scripts/test_git_baseline.ts +105 -0
  423. package/skills/a2h-spec-design-pipeline/scripts/test_inflight.mjs +452 -0
  424. package/skills/a2h-spec-design-pipeline/scripts/test_plan_groups.ts +375 -0
  425. package/skills/a2h-spec-design-pipeline/scripts/test_plan_waves.ts +561 -0
  426. package/skills/a2h-spec-design-pipeline/scripts/test_reconcile.mjs +182 -0
  427. package/skills/a2h-spec-design-pipeline/scripts/test_resolve_wiring.ts +138 -0
  428. package/skills/a2h-spec-design-pipeline/scripts/test_watchdog.mjs +289 -0
  429. package/skills/a2h-spec-design-pipeline/scripts/watchdog.mjs +441 -0
  430. package/skills/a2h-spec-generate/SKILL.md +285 -0
  431. package/skills/a2h-spec-generate/package.json +9 -0
  432. package/skills/a2h-spec-generate/references/batch-mode.md +151 -0
  433. package/skills/a2h-spec-generate/references/delete-blast-radius.md +3 -0
  434. package/skills/a2h-spec-generate/references/fusion-task-contract.md +114 -0
  435. package/skills/a2h-spec-generate/references/input-formats.md +27 -0
  436. package/skills/a2h-spec-generate/references/library-evidence.md +3 -0
  437. package/skills/a2h-spec-generate/references/method-discipline.md +64 -0
  438. package/skills/a2h-spec-generate/references/optional-gates.json +45 -0
  439. package/skills/a2h-spec-generate/references/recall-guide.md +83 -0
  440. package/skills/a2h-spec-generate/references/recall-terse.md +3 -0
  441. package/skills/a2h-spec-generate/references/recall-uniapp.md +10 -0
  442. package/skills/a2h-spec-generate/references/requirement-scope.md +122 -0
  443. package/skills/a2h-spec-generate/references/review-checklist.md +21 -0
  444. package/skills/a2h-spec-generate/references/spec-sample-complex.md +80 -0
  445. package/skills/a2h-spec-generate/references/spec-sample-transfer.md +43 -0
  446. package/skills/a2h-spec-generate/references/spec-samples.md +65 -0
  447. package/skills/a2h-spec-generate/references/specs.schema.json +79 -0
  448. package/skills/a2h-spec-generate/references/synthesis-rules.md +143 -0
  449. package/skills/a2h-spec-generate/references/transfer-file.md +5 -0
  450. package/skills/a2h-spec-generate/references/transfer-socket.md +5 -0
  451. package/skills/a2h-spec-generate/references/worker-rules.md +126 -0
  452. package/skills/a2h-spec-generate/scripts/check-fused-spec.mjs +514 -0
  453. package/skills/a2h-spec-generate/scripts/check_spec.ts +361 -0
  454. package/skills/a2h-spec-generate/scripts/collect-specs.mjs +470 -0
  455. package/skills/a2h-spec-generate/scripts/detect-project.mjs +271 -0
  456. package/skills/a2h-spec-generate/scripts/ensure-index.mjs +188 -0
  457. package/skills/a2h-spec-generate/scripts/feature-stem.mjs +150 -0
  458. package/skills/a2h-spec-generate/scripts/inspect-uniapp.mjs +733 -0
  459. package/skills/{hmos-spec-generate → a2h-spec-generate}/scripts/parse_requirements.ts +515 -515
  460. package/skills/a2h-spec-generate/scripts/prepare-facts.mjs +307 -0
  461. package/skills/a2h-spec-generate/scripts/publication-verdict.mjs +171 -0
  462. package/skills/a2h-spec-generate/scripts/publish-specs.mjs +280 -0
  463. package/skills/a2h-spec-generate/scripts/render-tasks.mjs +399 -0
  464. package/skills/a2h-spec-generate/scripts/report.mjs +132 -0
  465. package/skills/a2h-spec-generate/scripts/reqgen/assets/dashboard.html +149 -0
  466. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-api.js +49 -0
  467. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-code-view.js +140 -0
  468. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-format.js +16 -0
  469. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-handoff.js +42 -0
  470. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-splitters.js +78 -0
  471. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-state.js +47 -0
  472. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-tree.js +194 -0
  473. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-virtual-list.js +118 -0
  474. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz.css +245 -0
  475. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz.html +99 -0
  476. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz.js +220 -0
  477. package/skills/a2h-spec-generate/scripts/reqgen/package-lock.json +47 -0
  478. package/skills/a2h-spec-generate/scripts/reqgen/package.json +23 -0
  479. package/skills/a2h-spec-generate/scripts/reqgen/src/agent-render/serve.ts +95 -0
  480. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/callback-call-sites.ts +82 -0
  481. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/area-ownership.ts +496 -0
  482. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/build.ts +2217 -0
  483. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/callback-flow.ts +386 -0
  484. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/component-variants.ts +845 -0
  485. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/index.ts +24 -0
  486. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/names/index.ts +22 -0
  487. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/names/policy.ts +572 -0
  488. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/names/traceability.ts +580 -0
  489. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/req-model/build.ts +1270 -0
  490. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/req-model/index.ts +10 -0
  491. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/req-model/projection.ts +804 -0
  492. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/req-model/render-projection.ts +51 -0
  493. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/source-facts/android-interaction-registry.ts +286 -0
  494. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/source-facts/builder.ts +453 -0
  495. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/source-facts/compose-api-registry.ts +526 -0
  496. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/source-facts/index.ts +15 -0
  497. package/skills/a2h-spec-generate/scripts/reqgen/src/connector/index.ts +1 -0
  498. package/skills/a2h-spec-generate/scripts/reqgen/src/connector/utg-inbound.ts +763 -0
  499. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/area-graph.ts +383 -0
  500. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/artifact.ts +68 -0
  501. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/common.ts +88 -0
  502. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/diagnostic.ts +64 -0
  503. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/gap-audit.ts +113 -0
  504. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/index.ts +12 -0
  505. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/name-traceability.ts +108 -0
  506. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/raw-fact.ts +377 -0
  507. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/req-model.ts +238 -0
  508. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/run.ts +134 -0
  509. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/semantic-completeness.ts +35 -0
  510. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/source-facts.ts +48 -0
  511. package/skills/a2h-spec-generate/scripts/reqgen/src/contracts/utg.ts +133 -0
  512. package/skills/a2h-spec-generate/scripts/reqgen/src/core/output-guard.ts +42 -0
  513. package/skills/a2h-spec-generate/scripts/reqgen/src/core/stable-id.ts +118 -0
  514. package/skills/a2h-spec-generate/scripts/reqgen/src/cross-area-tally-cli.ts +179 -0
  515. package/skills/a2h-spec-generate/scripts/reqgen/src/dashboard-cli.ts +188 -0
  516. package/skills/a2h-spec-generate/scripts/reqgen/src/dump/dump.ts +1184 -0
  517. package/skills/a2h-spec-generate/scripts/reqgen/src/dump/index.ts +1 -0
  518. package/skills/a2h-spec-generate/scripts/reqgen/src/dump-cli.ts +373 -0
  519. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/area-facts.ts +1014 -0
  520. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/area-output.ts +32 -0
  521. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/schema.ts +142 -0
  522. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/selfcheck.ts +312 -0
  523. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/spec-bindings.ts +310 -0
  524. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +685 -0
  525. package/skills/a2h-spec-generate/scripts/reqgen/src/graph/paths.ts +575 -0
  526. package/skills/a2h-spec-generate/scripts/reqgen/src/homegraph-cli.ts +50 -0
  527. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/android-resource-resolver.ts +391 -0
  528. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/androidx-preference-contracts.ts +44 -0
  529. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/contracts.ts +640 -0
  530. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/cross-area.ts +207 -0
  531. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/finalizer.ts +1297 -0
  532. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/identity.ts +186 -0
  533. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/index.ts +16 -0
  534. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/planner.ts +312 -0
  535. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/preference-enrichment.ts +793 -0
  536. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/raw-facts.ts +355 -0
  537. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/rules.ts +271 -0
  538. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/scanner.ts +666 -0
  539. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/schema.ts +365 -0
  540. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/stable-key.ts +144 -0
  541. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/task-contract.ts +301 -0
  542. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/tree-sitter-adapter.ts +923 -0
  543. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/uniapp-utg-adapter.ts +543 -0
  544. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/xml-adapter.ts +262 -0
  545. package/skills/a2h-spec-generate/scripts/reqgen/src/model/assemble.ts +2079 -0
  546. package/skills/a2h-spec-generate/scripts/reqgen/src/model/contracts.ts +157 -0
  547. package/skills/a2h-spec-generate/scripts/reqgen/src/model/finalize.ts +809 -0
  548. package/skills/a2h-spec-generate/scripts/reqgen/src/model/index.ts +17 -0
  549. package/skills/a2h-spec-generate/scripts/reqgen/src/model/io.ts +165 -0
  550. package/skills/a2h-spec-generate/scripts/reqgen/src/model/prepare.ts +806 -0
  551. package/skills/a2h-spec-generate/scripts/reqgen/src/model/query.ts +360 -0
  552. package/skills/a2h-spec-generate/scripts/reqgen/src/model/seeds.ts +218 -0
  553. package/skills/a2h-spec-generate/scripts/reqgen/src/model/spec-bindings-sidecar.ts +240 -0
  554. package/skills/a2h-spec-generate/scripts/reqgen/src/model/task.ts +359 -0
  555. package/skills/a2h-spec-generate/scripts/reqgen/src/model-cli.ts +500 -0
  556. package/skills/a2h-spec-generate/scripts/reqgen/src/pipeline/index.ts +7 -0
  557. package/skills/a2h-spec-generate/scripts/reqgen/src/pipeline/output.ts +307 -0
  558. package/skills/a2h-spec-generate/scripts/reqgen/src/requirement-scope.ts +172 -0
  559. package/skills/a2h-spec-generate/scripts/reqgen/src/source-cov/index.ts +1 -0
  560. package/skills/a2h-spec-generate/scripts/reqgen/src/source-cov/source-cov.ts +176 -0
  561. package/skills/a2h-spec-generate/scripts/reqgen/src/source-index/homegraph.ts +1039 -0
  562. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/area-graph.ts +490 -0
  563. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/index.ts +23 -0
  564. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/req-model.ts +957 -0
  565. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/req-text.ts +248 -0
  566. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/semantic-area-graph.ts +1600 -0
  567. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/types.ts +10 -0
  568. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/artifact-data.ts +201 -0
  569. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-api.ts +74 -0
  570. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-code-view.ts +180 -0
  571. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-format.ts +18 -0
  572. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-handoff.ts +55 -0
  573. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-splitters.ts +78 -0
  574. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-state.ts +66 -0
  575. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-tree.ts +232 -0
  576. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-virtual-list.ts +179 -0
  577. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz.ts +240 -0
  578. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/contracts.d.ts +86 -0
  579. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/index.ts +3 -0
  580. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/server.ts +239 -0
  581. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/source-project.ts +316 -0
  582. package/skills/a2h-spec-generate/scripts/reqgen/src/viz-cli.ts +200 -0
  583. package/skills/a2h-spec-generate/scripts/reqgen/test/control-fact-join.test.ts +50 -0
  584. package/skills/a2h-spec-generate/scripts/reqgen/test/control-name-uniapp.test.ts +75 -0
  585. package/skills/a2h-spec-generate/scripts/reqgen/test/cross-area-anchor.test.ts +256 -0
  586. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-area-facts.test.ts +576 -0
  587. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-contract.test.ts +290 -0
  588. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-finalize.test.ts +1323 -0
  589. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-prepare.test.ts +574 -0
  590. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-scope.test.ts +339 -0
  591. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-selfcheck.test.ts +831 -0
  592. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +548 -0
  593. package/skills/a2h-spec-generate/scripts/reqgen/test/model-cli-blockers.test.ts +117 -0
  594. package/skills/a2h-spec-generate/scripts/reqgen/test/model-scope.test.ts +396 -0
  595. package/skills/a2h-spec-generate/scripts/reqgen/test/model-seeds.test.ts +175 -0
  596. package/skills/a2h-spec-generate/scripts/reqgen/test/model-task-contract.test.ts +298 -0
  597. package/skills/a2h-spec-generate/scripts/reqgen/test/model-v4.test.ts +1061 -0
  598. package/skills/a2h-spec-generate/scripts/reqgen/test/specgen-completeness.test.ts +286 -0
  599. package/skills/a2h-spec-generate/scripts/reqgen/test/stagem-stored-path.test.ts +25 -0
  600. package/skills/a2h-spec-generate/scripts/reqgen/test/uniapp-scanner.test.ts +159 -0
  601. package/skills/a2h-spec-generate/scripts/reqgen/tsconfig.json +16 -0
  602. package/skills/a2h-spec-generate/scripts/reqgen/tsconfig.viz-client.json +12 -0
  603. package/skills/{hmos-spec-generate → a2h-spec-generate}/template/REQ.txt +22 -22
  604. package/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +632 -0
  605. package/skills/a2h-spec-generate/test/check-spec.test.ts +200 -0
  606. package/skills/a2h-spec-generate/test/collect-specs.test.mjs +538 -0
  607. package/skills/a2h-spec-generate/test/detect-project.test.mjs +37 -0
  608. package/skills/a2h-spec-generate/test/ensure-index.test.mjs +45 -0
  609. package/skills/a2h-spec-generate/test/feature-stem.test.mjs +147 -0
  610. package/skills/a2h-spec-generate/test/fixtures/android/app/src/main/AndroidManifest.xml +3 -0
  611. package/skills/a2h-spec-generate/test/fixtures/android/build.gradle +3 -0
  612. package/skills/a2h-spec-generate/test/fixtures/android/settings.gradle +3 -0
  613. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/package.json +9 -0
  614. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/App.vue +8 -0
  615. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/components/MyCard.vue +9 -0
  616. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/feature/editor/index.vue +1 -0
  617. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/main.ts +6 -0
  618. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/manifest.json +4 -0
  619. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/detail/index.vue +1 -0
  620. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/home/index.vue +33 -0
  621. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/settings/index.vue +1 -0
  622. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages.json +23 -0
  623. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/services/items.ts +3 -0
  624. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/tsconfig.json +8 -0
  625. package/skills/a2h-spec-generate/test/fixtures/unknown/README.txt +1 -0
  626. package/skills/a2h-spec-generate/test/inspect-uniapp.test.mjs +54 -0
  627. package/skills/a2h-spec-generate/test/publication-verdict.test.mjs +157 -0
  628. package/skills/a2h-spec-generate/test/publish-specs.test.mjs +282 -0
  629. package/skills/a2h-spec-generate/test/render-tasks.test.mjs +593 -0
  630. package/skills/a2h-utg-explorer/SKILL.md +120 -0
  631. package/skills/a2h-utg-explorer/assets/final_viewer.html +64 -0
  632. package/skills/a2h-utg-explorer/assets/u2.LICENSE +21 -0
  633. package/skills/a2h-utg-explorer/assets/u2.NOTICE +25 -0
  634. package/skills/a2h-utg-explorer/assets/u2.jar +0 -0
  635. package/skills/a2h-utg-explorer/references/architecture.md +270 -0
  636. package/skills/a2h-utg-explorer/references/protocol.md +9 -0
  637. package/skills/a2h-utg-explorer/scripts/app_settings.mjs +143 -0
  638. package/skills/a2h-utg-explorer/scripts/audit.mjs +167 -0
  639. package/skills/a2h-utg-explorer/scripts/close_phases.mjs +66 -0
  640. package/skills/a2h-utg-explorer/scripts/compile_tasks.mjs +749 -0
  641. package/skills/a2h-utg-explorer/scripts/d_prereqs.mjs +597 -0
  642. package/skills/a2h-utg-explorer/scripts/device_health.mjs +227 -0
  643. package/skills/a2h-utg-explorer/scripts/direct_launch.mjs +276 -0
  644. package/skills/a2h-utg-explorer/scripts/evidence.mjs +108 -0
  645. package/skills/a2h-utg-explorer/scripts/final_utg.mjs +428 -0
  646. package/skills/a2h-utg-explorer/scripts/hint_check.mjs +89 -0
  647. package/skills/a2h-utg-explorer/scripts/plan.mjs +258 -0
  648. package/skills/a2h-utg-explorer/scripts/promote_dynamic.mjs +170 -0
  649. package/skills/a2h-utg-explorer/scripts/recover.mjs +467 -0
  650. package/skills/a2h-utg-explorer/scripts/recover_b.mjs +542 -0
  651. package/skills/a2h-utg-explorer/scripts/recover_d.mjs +369 -0
  652. package/skills/a2h-utg-explorer/scripts/rejudge.mjs +203 -0
  653. package/skills/a2h-utg-explorer/scripts/report.mjs +143 -0
  654. package/skills/a2h-utg-explorer/scripts/run_cycle.mjs +844 -0
  655. package/skills/a2h-utg-explorer/scripts/run_device.mjs +137 -0
  656. package/skills/a2h-utg-explorer/scripts/tests/attest.test.mjs +66 -0
  657. package/skills/a2h-utg-explorer/scripts/tests/chain.test.mjs +45 -0
  658. package/skills/a2h-utg-explorer/scripts/tests/compose_identity.test.mjs +243 -0
  659. package/skills/a2h-utg-explorer/scripts/tests/coverage_rules.test.mjs +104 -0
  660. package/skills/a2h-utg-explorer/scripts/tests/d_prereqs.test.mjs +223 -0
  661. package/skills/a2h-utg-explorer/scripts/tests/device_health.test.mjs +88 -0
  662. package/skills/a2h-utg-explorer/scripts/tests/device_lock_retry.test.mjs +187 -0
  663. package/skills/a2h-utg-explorer/scripts/tests/direct_launch.test.mjs +130 -0
  664. package/skills/a2h-utg-explorer/scripts/tests/explorer_review_fixes.test.mjs +136 -0
  665. package/skills/a2h-utg-explorer/scripts/tests/final_utg.test.mjs +135 -0
  666. package/skills/a2h-utg-explorer/scripts/tests/first_round_phases.test.mjs +16 -0
  667. package/skills/a2h-utg-explorer/scripts/tests/generalization_fixes.test.mjs +251 -0
  668. package/skills/a2h-utg-explorer/scripts/tests/hint_check.test.mjs +42 -0
  669. package/skills/a2h-utg-explorer/scripts/tests/interruptions.test.mjs +162 -0
  670. package/skills/a2h-utg-explorer/scripts/tests/node_coverage.test.mjs +193 -0
  671. package/skills/a2h-utg-explorer/scripts/tests/overflow_prefix.test.mjs +204 -0
  672. package/skills/a2h-utg-explorer/scripts/tests/page_identity_tiers.test.mjs +355 -0
  673. package/skills/a2h-utg-explorer/scripts/tests/pipeline.test.mjs +240 -0
  674. package/skills/a2h-utg-explorer/scripts/tests/recover.test.mjs +212 -0
  675. package/skills/a2h-utg-explorer/scripts/tests/recover_b.test.mjs +173 -0
  676. package/skills/a2h-utg-explorer/scripts/tests/recover_d.test.mjs +267 -0
  677. package/skills/a2h-utg-explorer/scripts/tests/review_fixes.test.mjs +213 -0
  678. package/skills/a2h-utg-explorer/scripts/tests/robustness_fixes.test.mjs +345 -0
  679. package/skills/a2h-utg-explorer/scripts/tests/run_cycle.test.mjs +453 -0
  680. package/skills/a2h-utg-explorer/scripts/tests/runner_capabilities.test.mjs +131 -0
  681. package/skills/a2h-utg-explorer/scripts/tests/scope.test.mjs +229 -0
  682. package/skills/a2h-utg-explorer/scripts/tests/scroll_sweep.test.mjs +336 -0
  683. package/skills/a2h-utg-explorer/scripts/tests/semantics.test.mjs +102 -0
  684. package/skills/a2h-utg-explorer/scripts/tests/state_ambiguity.test.mjs +92 -0
  685. package/skills/a2h-utg-explorer/scripts/tests/twin_opener.test.mjs +119 -0
  686. package/skills/a2h-utg-explorer/scripts/tests/u2_backend.test.mjs +346 -0
  687. package/skills/a2h-utg-explorer/scripts/tests/ui_state_anchors.test.mjs +112 -0
  688. package/skills/a2h-utg-explorer/scripts/tests/variant_strings.test.mjs +63 -0
  689. package/skills/a2h-utg-explorer/scripts/tests/worklist_parts.test.mjs +24 -0
  690. package/skills/a2h-utg-explorer/scripts/utg_explorer/_device_io.mjs +244 -0
  691. package/skills/a2h-utg-explorer/scripts/utg_explorer/_py.mjs +2097 -0
  692. package/skills/a2h-utg-explorer/scripts/utg_explorer/adapters.mjs +1231 -0
  693. package/skills/a2h-utg-explorer/scripts/utg_explorer/attest.mjs +63 -0
  694. package/skills/a2h-utg-explorer/scripts/utg_explorer/chain.mjs +63 -0
  695. package/skills/a2h-utg-explorer/scripts/utg_explorer/coverage.mjs +89 -0
  696. package/skills/a2h-utg-explorer/scripts/utg_explorer/device_lock.mjs +46 -0
  697. package/skills/a2h-utg-explorer/scripts/utg_explorer/semantics.mjs +1200 -0
  698. package/skills/a2h-utg-explorer/scripts/utg_explorer/task_runner.mjs +1558 -0
  699. package/skills/a2h-utg-explorer/scripts/variant.mjs +75 -0
  700. package/skills/a2h-utg-explorer/scripts/worklist_parts.mjs +122 -0
  701. package/skills/a2h-utg-static/SKILL.md +361 -0
  702. package/skills/a2h-utg-static/config.json +19 -0
  703. package/skills/a2h-utg-static/references/extractors.md +217 -0
  704. package/skills/a2h-utg-static/references/ui-elements-static-utg-schema.md +248 -0
  705. package/skills/a2h-utg-static/references/view-interactions.md +215 -0
  706. package/skills/a2h-utg-static/scripts/_graph.mjs +361 -0
  707. package/skills/a2h-utg-static/scripts/_py.mjs +2177 -0
  708. package/skills/a2h-utg-static/scripts/_spawn.mjs +45 -0
  709. package/skills/a2h-utg-static/scripts/activity_nav.mjs +738 -0
  710. package/skills/a2h-utg-static/scripts/activity_widgets.mjs +254 -0
  711. package/skills/a2h-utg-static/scripts/adapter_nav.mjs +229 -0
  712. package/skills/a2h-utg-static/scripts/androidfragment_nav.mjs +208 -0
  713. package/skills/a2h-utg-static/scripts/assemble.mjs +2065 -0
  714. package/skills/a2h-utg-static/scripts/audit.mjs +268 -0
  715. package/skills/a2h-utg-static/scripts/carry_answers.mjs +201 -0
  716. package/skills/a2h-utg-static/scripts/click_paths.mjs +594 -0
  717. package/skills/a2h-utg-static/scripts/compose_body_text.mjs +226 -0
  718. package/skills/a2h-utg-static/scripts/compose_merge.mjs +263 -0
  719. package/skills/a2h-utg-static/scripts/compose_nav.mjs +1216 -0
  720. package/skills/a2h-utg-static/scripts/compose_navbar_nav.mjs +238 -0
  721. package/skills/a2h-utg-static/scripts/compose_overlay.mjs +2760 -0
  722. package/skills/a2h-utg-static/scripts/compose_titles.mjs +365 -0
  723. package/skills/a2h-utg-static/scripts/compose_widgets.mjs +498 -0
  724. package/skills/a2h-utg-static/scripts/dialog_listener_nav.mjs +237 -0
  725. package/skills/a2h-utg-static/scripts/dialogshow_nav.mjs +308 -0
  726. package/skills/a2h-utg-static/scripts/fragfactory_nav.mjs +170 -0
  727. package/skills/a2h-utg-static/scripts/fragment_nav.mjs +1136 -0
  728. package/skills/a2h-utg-static/scripts/guard_subjects.mjs +162 -0
  729. package/skills/a2h-utg-static/scripts/hg_query.mjs +137 -0
  730. package/skills/a2h-utg-static/scripts/host_resolve.mjs +393 -0
  731. package/skills/a2h-utg-static/scripts/hybrid_bundle.mjs +165 -0
  732. package/skills/a2h-utg-static/scripts/hybrid_pages.mjs +713 -0
  733. package/skills/a2h-utg-static/scripts/hybrid_scope.mjs +660 -0
  734. package/skills/a2h-utg-static/scripts/interaction_sites.mjs +267 -0
  735. package/skills/a2h-utg-static/scripts/io_utils.mjs +59 -0
  736. package/skills/a2h-utg-static/scripts/label_resolve.mjs +864 -0
  737. package/skills/a2h-utg-static/scripts/launch_extras.mjs +91 -0
  738. package/skills/a2h-utg-static/scripts/layout_resolve.mjs +148 -0
  739. package/skills/a2h-utg-static/scripts/manifest.mjs +483 -0
  740. package/skills/a2h-utg-static/scripts/measure/measure_corpus.mjs +297 -0
  741. package/skills/a2h-utg-static/scripts/measure/measure_guards.mjs +98 -0
  742. package/skills/a2h-utg-static/scripts/media_browse_nav.mjs +356 -0
  743. package/skills/a2h-utg-static/scripts/menu_nav.mjs +603 -0
  744. package/skills/a2h-utg-static/scripts/navactions_nav.mjs +255 -0
  745. package/skills/a2h-utg-static/scripts/nl_hints.mjs +453 -0
  746. package/skills/a2h-utg-static/scripts/orphan_overlay_nav.mjs +89 -0
  747. package/skills/a2h-utg-static/scripts/phase_plan.mjs +108 -0
  748. package/skills/a2h-utg-static/scripts/phase_planner.mjs +119 -0
  749. package/skills/a2h-utg-static/scripts/plaindialog_nav.mjs +411 -0
  750. package/skills/a2h-utg-static/scripts/preference_nav.mjs +761 -0
  751. package/skills/a2h-utg-static/scripts/preference_widgets.mjs +142 -0
  752. package/skills/a2h-utg-static/scripts/presenter_nav.mjs +490 -0
  753. package/skills/a2h-utg-static/scripts/registry_nav.mjs +288 -0
  754. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +870 -0
  755. package/skills/a2h-utg-static/scripts/scope_utils.mjs +430 -0
  756. package/skills/a2h-utg-static/scripts/screen_merge.mjs +287 -0
  757. package/skills/a2h-utg-static/scripts/screen_nav.mjs +279 -0
  758. package/skills/a2h-utg-static/scripts/single_host_nav.mjs +291 -0
  759. package/skills/a2h-utg-static/scripts/starter_nav.mjs +198 -0
  760. package/skills/a2h-utg-static/scripts/state_guard.mjs +579 -0
  761. package/skills/a2h-utg-static/scripts/static_prior.mjs +904 -0
  762. package/skills/a2h-utg-static/scripts/tests/_zipw.mjs +28 -0
  763. package/skills/a2h-utg-static/scripts/tests/probe_autoload.mjs +108 -0
  764. package/skills/a2h-utg-static/scripts/tests/probe_layout_fragments.mjs +90 -0
  765. package/skills/a2h-utg-static/scripts/tests/probe_unknown_scope.mjs +61 -0
  766. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +1261 -0
  767. package/skills/a2h-utg-static/scripts/tests/test_activity_alias_launcher.mjs +90 -0
  768. package/skills/a2h-utg-static/scripts/tests/test_activity_supertype_chain.mjs +106 -0
  769. package/skills/a2h-utg-static/scripts/tests/test_bottom_sheet_container.mjs +58 -0
  770. package/skills/a2h-utg-static/scripts/tests/test_branch_guard.mjs +19 -0
  771. package/skills/a2h-utg-static/scripts/tests/test_callee_string_default.mjs +30 -0
  772. package/skills/a2h-utg-static/scripts/tests/test_carry_answers.mjs +103 -0
  773. package/skills/a2h-utg-static/scripts/tests/test_chrome_tokens.mjs +60 -0
  774. package/skills/a2h-utg-static/scripts/tests/test_commented_out_trigger.mjs +111 -0
  775. package/skills/a2h-utg-static/scripts/tests/test_commit_scope.mjs +113 -0
  776. package/skills/a2h-utg-static/scripts/tests/test_compose_file_private_route.mjs +117 -0
  777. package/skills/a2h-utg-static/scripts/tests/test_compose_nested_graph.mjs +166 -0
  778. package/skills/a2h-utg-static/scripts/tests/test_compose_route_holder_collision.mjs +112 -0
  779. package/skills/a2h-utg-static/scripts/tests/test_compose_vm_nav.mjs +284 -0
  780. package/skills/a2h-utg-static/scripts/tests/test_custom_source_root.mjs +71 -0
  781. package/skills/a2h-utg-static/scripts/tests/test_defensive_null_guard.mjs +77 -0
  782. package/skills/a2h-utg-static/scripts/tests/test_dialog_orphan_entries.mjs +99 -0
  783. package/skills/a2h-utg-static/scripts/tests/test_dialog_page_owner.mjs +69 -0
  784. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_builder_forms.mjs +96 -0
  785. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_java_factory.mjs +37 -0
  786. package/skills/a2h-utg-static/scripts/tests/test_disabled_guard.mjs +42 -0
  787. package/skills/a2h-utg-static/scripts/tests/test_drawer_panel_gesture.mjs +140 -0
  788. package/skills/a2h-utg-static/scripts/tests/test_edge_dedupe_by_gesture.mjs +111 -0
  789. package/skills/a2h-utg-static/scripts/tests/test_edge_provenance_lint.mjs +70 -0
  790. package/skills/a2h-utg-static/scripts/tests/test_enclosing_gesture.mjs +69 -0
  791. package/skills/a2h-utg-static/scripts/tests/test_external_surface_roots.mjs +43 -0
  792. package/skills/a2h-utg-static/scripts/tests/test_find_package_indirect.mjs +67 -0
  793. package/skills/a2h-utg-static/scripts/tests/test_forwarding_wrapper.mjs +38 -0
  794. package/skills/a2h-utg-static/scripts/tests/test_fragment_containment.mjs +85 -0
  795. package/skills/a2h-utg-static/scripts/tests/test_fragment_helper_trigger.mjs +92 -0
  796. package/skills/a2h-utg-static/scripts/tests/test_graph.mjs +55 -0
  797. package/skills/a2h-utg-static/scripts/tests/test_guard_clause.mjs +86 -0
  798. package/skills/a2h-utg-static/scripts/tests/test_hint_language.mjs +119 -0
  799. package/skills/a2h-utg-static/scripts/tests/test_host_kind_by_chain.mjs +68 -0
  800. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundle_attribution.mjs +74 -0
  801. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundled_pages.mjs +181 -0
  802. package/skills/a2h-utg-static/scripts/tests/test_hybrid_scope.mjs +293 -0
  803. package/skills/a2h-utg-static/scripts/tests/test_hybrid_title_renders.mjs +118 -0
  804. package/skills/a2h-utg-static/scripts/tests/test_interaction_sites.mjs +272 -0
  805. package/skills/a2h-utg-static/scripts/tests/test_item_data_instance.mjs +51 -0
  806. package/skills/a2h-utg-static/scripts/tests/test_kotlin_fn_spans.mjs +69 -0
  807. package/skills/a2h-utg-static/scripts/tests/test_label_accessor_forms.mjs +187 -0
  808. package/skills/a2h-utg-static/scripts/tests/test_label_source.mjs +70 -0
  809. package/skills/a2h-utg-static/scripts/tests/test_launch_intent_guard.mjs +67 -0
  810. package/skills/a2h-utg-static/scripts/tests/test_layout_declared_fragment.mjs +103 -0
  811. package/skills/a2h-utg-static/scripts/tests/test_listener_call_forms.mjs +79 -0
  812. package/skills/a2h-utg-static/scripts/tests/test_listener_receiver_binding.mjs +47 -0
  813. package/skills/a2h-utg-static/scripts/tests/test_manifest_exported_default.mjs +40 -0
  814. package/skills/a2h-utg-static/scripts/tests/test_manifest_filters_modules.mjs +84 -0
  815. package/skills/a2h-utg-static/scripts/tests/test_manifest_srcfile.mjs +68 -0
  816. package/skills/a2h-utg-static/scripts/tests/test_mode_and_cb_param.mjs +172 -0
  817. package/skills/a2h-utg-static/scripts/tests/test_module_namespace.mjs +33 -0
  818. package/skills/a2h-utg-static/scripts/tests/test_module_strings.mjs +44 -0
  819. package/skills/a2h-utg-static/scripts/tests/test_multiple_entry_contracts.mjs +80 -0
  820. package/skills/a2h-utg-static/scripts/tests/test_nav_graph_xml.mjs +35 -0
  821. package/skills/a2h-utg-static/scripts/tests/test_nl_hint_grammar.mjs +42 -0
  822. package/skills/a2h-utg-static/scripts/tests/test_nl_hints_gate.mjs +85 -0
  823. package/skills/a2h-utg-static/scripts/tests/test_node_id_collision.mjs +57 -0
  824. package/skills/a2h-utg-static/scripts/tests/test_non_gesture_step_flag.mjs +62 -0
  825. package/skills/a2h-utg-static/scripts/tests/test_out_of_scope_and_settings.mjs +72 -0
  826. package/skills/a2h-utg-static/scripts/tests/test_overload_and_climb.mjs +86 -0
  827. package/skills/a2h-utg-static/scripts/tests/test_pager_page_source.mjs +78 -0
  828. package/skills/a2h-utg-static/scripts/tests/test_pager_position_zero.mjs +65 -0
  829. package/skills/a2h-utg-static/scripts/tests/test_pager_variant_guard.mjs +172 -0
  830. package/skills/a2h-utg-static/scripts/tests/test_pipeline_llm_phases.mjs +107 -0
  831. package/skills/a2h-utg-static/scripts/tests/test_plain_dialog_nodes.mjs +167 -0
  832. package/skills/a2h-utg-static/scripts/tests/test_plaindialog_shared_anchor.mjs +117 -0
  833. package/skills/a2h-utg-static/scripts/tests/test_preference_click_nav.mjs +98 -0
  834. package/skills/a2h-utg-static/scripts/tests/test_preference_host_binding.mjs +87 -0
  835. package/skills/a2h-utg-static/scripts/tests/test_preference_nesting.mjs +183 -0
  836. package/skills/a2h-utg-static/scripts/tests/test_preference_widgets.mjs +48 -0
  837. package/skills/a2h-utg-static/scripts/tests/test_read_text_crlf.mjs +41 -0
  838. package/skills/a2h-utg-static/scripts/tests/test_resolver_tier_parity.mjs +126 -0
  839. package/skills/a2h-utg-static/scripts/tests/test_result_launcher.mjs +142 -0
  840. package/skills/a2h-utg-static/scripts/tests/test_review_fixes.mjs +135 -0
  841. package/skills/a2h-utg-static/scripts/tests/test_route_token_words.mjs +66 -0
  842. package/skills/a2h-utg-static/scripts/tests/test_same_name_decl_scope.mjs +236 -0
  843. package/skills/a2h-utg-static/scripts/tests/test_scope_utils.mjs +85 -0
  844. package/skills/a2h-utg-static/scripts/tests/test_sealed_dialog_state.mjs +148 -0
  845. package/skills/a2h-utg-static/scripts/tests/test_shared_overlay_split.mjs +63 -0
  846. package/skills/a2h-utg-static/scripts/tests/test_slug_parity.mjs +58 -0
  847. package/skills/a2h-utg-static/scripts/tests/test_starter_node_id.mjs +41 -0
  848. package/skills/a2h-utg-static/scripts/tests/test_state_guard_arity.mjs +109 -0
  849. package/skills/a2h-utg-static/scripts/tests/test_state_guard_commented_candidates.mjs +68 -0
  850. package/skills/a2h-utg-static/scripts/tests/test_state_guard_model_gates.mjs +127 -0
  851. package/skills/a2h-utg-static/scripts/tests/test_state_specific_hop.mjs +130 -0
  852. package/skills/a2h-utg-static/scripts/tests/test_synthetic_label_identity.mjs +51 -0
  853. package/skills/a2h-utg-static/scripts/tests/test_template_method_layout.mjs +81 -0
  854. package/skills/a2h-utg-static/scripts/tests/test_template_title.mjs +58 -0
  855. package/skills/a2h-utg-static/scripts/tests/test_trigger_id_spelling.mjs +68 -0
  856. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_action_override.mjs +91 -0
  857. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_flow_filter.mjs +110 -0
  858. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_nl_hint_key.mjs +89 -0
  859. package/skills/a2h-utg-static/scripts/tests/test_uiless_host_fold.mjs +98 -0
  860. package/skills/a2h-utg-static/scripts/tests/test_uniapp_source.mjs +231 -0
  861. package/skills/a2h-utg-static/scripts/tests/test_view_click_refs.mjs +104 -0
  862. package/skills/a2h-utg-static/scripts/tests/test_view_id_label.mjs +69 -0
  863. package/skills/a2h-utg-static/scripts/tests/test_view_interactions.mjs +346 -0
  864. package/skills/a2h-utg-static/scripts/tests/test_viewpage_nav.mjs +340 -0
  865. package/skills/a2h-utg-static/scripts/tests/test_vm_nav_helper_navigate.mjs +98 -0
  866. package/skills/a2h-utg-static/scripts/tests/test_widget_class_scope.mjs +92 -0
  867. package/skills/a2h-utg-static/scripts/tests/test_window_nav_kotlin.mjs +158 -0
  868. package/skills/a2h-utg-static/scripts/tests/test_worklist_parts.mjs +65 -0
  869. package/skills/a2h-utg-static/scripts/uniapp_nav.mjs +1119 -0
  870. package/skills/a2h-utg-static/scripts/uniapp_widgets.mjs +244 -0
  871. package/skills/a2h-utg-static/scripts/utg_html.mjs +721 -0
  872. package/skills/a2h-utg-static/scripts/view_interactions.mjs +799 -0
  873. package/skills/a2h-utg-static/scripts/view_widgets.mjs +512 -0
  874. package/skills/a2h-utg-static/scripts/viewpage_nav.mjs +589 -0
  875. package/skills/a2h-utg-static/scripts/vm_nav.mjs +422 -0
  876. package/skills/a2h-utg-static/scripts/window_nav.mjs +240 -0
  877. package/skills/a2h-utg-static/scripts/worklist_parts.mjs +154 -0
  878. package/skills/a2h-utg-static/tools/convert_static_utg_to_ui_elements.ts +769 -0
  879. package/skills/a2h-utg-static/tools/package.json +3 -0
  880. package/README.md +0 -445
  881. package/agents/logic-coder.md +0 -224
  882. package/agents/logic-context-builder.md +0 -212
  883. package/agents/scripts/hmos-precheck/backends/arkts.mjs +0 -567
  884. package/agents/scripts/hmos-precheck/backends/arkts_diff.mjs +0 -159
  885. package/agents/scripts/hmos-precheck/backends/arkts_project_rules.mjs +0 -398
  886. package/agents/scripts/hmos-precheck/backends/codelinter.mjs +0 -250
  887. package/agents/scripts/hmos-precheck/backends/project_integrity.mjs +0 -321
  888. package/agents/scripts/hmos-precheck/backends/static_precheck.mjs +0 -247
  889. package/agents/scripts/hmos-precheck/core/config.mjs +0 -184
  890. package/agents/scripts/hmos-precheck/core/diagnostic_scope.mjs +0 -20
  891. package/agents/scripts/hmos-precheck/core/process_adapter.mjs +0 -47
  892. package/agents/scripts/hmos-precheck/core/project_catalog.mjs +0 -50
  893. package/agents/scripts/hmos-precheck/core/result_projection.mjs +0 -147
  894. package/agents/scripts/hmos-precheck/core/scope_plan.mjs +0 -131
  895. package/agents/scripts/hmos-precheck/core/sdk_context.mjs +0 -67
  896. package/agents/scripts/hmos-precheck/docs/architecture.md +0 -37
  897. package/agents/scripts/hmos-precheck/docs/performance-optimization.md +0 -28
  898. package/agents/scripts/hmos-precheck/docs/upstream-reference.json +0 -19
  899. package/agents/scripts/hmos-precheck/docs/validation.md +0 -50
  900. package/agents/scripts/hmos-precheck/index.mjs +0 -17
  901. package/agents/scripts/hmos-precheck/invocation.mjs +0 -231
  902. package/agents/scripts/hmos-precheck/rules/rule_case_matrix.csv +0 -32
  903. package/agents/scripts/hmos-precheck/rules/rule_inventory.csv +0 -64
  904. package/agents/scripts/hmos-precheck/rules/rule_inventory.mjs +0 -59
  905. package/agents/scripts/hmos-precheck/rules/rule_policy.mjs +0 -54
  906. package/agents/scripts/platform_query.mjs +0 -626
  907. package/agents/scripts/platform_query.test.mjs +0 -422
  908. package/agents/self-test-fixer.md +0 -298
  909. package/agents/self-tester.md +0 -55
  910. package/agents/test-case-generation-generator.md +0 -317
  911. package/agents/test-case-generation-validator.md +0 -231
  912. package/dist/cli/config-store.js +0 -310
  913. package/dist/cli/config.js +0 -44
  914. package/dist/cli/env-vars.js +0 -127
  915. package/dist/cli/index.js +0 -56
  916. package/dist/cli/init.js +0 -1187
  917. package/dist/cli/uninstall.js +0 -427
  918. package/dist/utils/regex.js +0 -8
  919. package/env-requirements.json +0 -179
  920. package/resource/choose_editor.png +0 -0
  921. package/resource/convert_pipeline_process.svg +0 -103
  922. package/resource/project_architecture.svg +0 -122
  923. package/resource/set_environment.png +0 -0
  924. package/resource/set_multimodel.png +0 -0
  925. package/resource/set_sdk.png +0 -0
  926. package/resource/title_dark.png +0 -0
  927. package/skills/hmos-batch-ui-align/SKILL.md +0 -413
  928. package/skills/hmos-batch-ui-align/references/conversion-procedure.md +0 -661
  929. package/skills/hmos-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +0 -117
  930. package/skills/hmos-batch-ui-align/references/mvvm/@Link/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -648
  931. package/skills/hmos-batch-ui-align/references/mvvm/@Provide/350/243/205/351/245/260/345/231/250/345/222/214@Consume/350/243/205/351/245/260/345/231/250/357/274/232/344/270/216/345/220/216/344/273/243/347/273/204/344/273/266/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -1183
  932. package/skills/hmos-batch-ui-align/references/mvvm/@State/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/347/212/266/346/200/201.md +0 -576
  933. package/skills/hmos-batch-ui-align/references/mvvm/@Track/350/243/205/351/245/260/345/231/250/357/274/232class/345/257/271/350/261/241/345/261/236/346/200/247/347/272/247/346/233/264/346/226/260.md +0 -297
  934. package/skills/hmos-batch-ui-align/references/mvvm/@Watch/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/346/233/264/346/224/271/351/200/232/347/237/245.md +0 -395
  935. package/skills/hmos-batch-ui-align/references/mvvm/AppStorage/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200/347/232/204UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -903
  936. package/skills/hmos-batch-ui-align/references/mvvm/LocalStorage/357/274/232/351/241/265/351/235/242/347/272/247UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -1178
  937. package/skills/hmos-batch-ui-align/references/mvvm/PersistentStorage/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +0 -355
  938. package/skills/hmos-batch-ui-align/references/mvvm//347/256/241/347/220/206/345/272/224/347/224/250/346/213/245/346/234/211/347/232/204/347/212/266/346/200/201/346/246/202/350/277/260.md +0 -11
  939. package/skills/hmos-batch-ui-align/references/mvvm-v2/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md +0 -206
  940. package/skills/hmos-batch-ui-align/references/mvvm-v2/@Local/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/351/203/250/347/212/266/346/200/201.md +0 -750
  941. package/skills/hmos-batch-ui-align/references/mvvm-v2/@Param/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/244/226/351/203/250/350/276/223/345/205/245.md +0 -840
  942. package/skills/hmos-batch-ui-align/references/mvvm-v2/@Provider/350/243/205/351/245/260/345/231/250/345/222/214@Consumer/350/243/205/351/245/260/345/231/250/357/274/232/350/267/250/347/273/204/344/273/266/345/261/202/347/272/247/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -856
  943. package/skills/hmos-batch-ui-align/references/mvvm-v2/AppStorageV2/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -294
  944. package/skills/hmos-batch-ui-align/references/mvvm-v2/PersistenceV2/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +0 -1220
  945. package/skills/hmos-batch-ui-align/references/mvvm-v2//347/212/266/346/200/201/347/256/241/347/220/206V1/345/220/221V2/350/277/201/347/247/273/344/270/216/346/267/267/347/224/250/346/214/207/345/257/274.md +0 -840
  946. package/skills/hmos-batch-ui-align/scripts/arkts_static_check.ts +0 -1592
  947. package/skills/hmos-batch-ui-align/scripts/measure_pack.ts +0 -752
  948. package/skills/hmos-convert-pipeline/SKILL.md +0 -486
  949. package/skills/hmos-incremental-ui-align/README.md +0 -251
  950. package/skills/hmos-incremental-ui-align/SKILL.md +0 -375
  951. package/skills/hmos-incremental-ui-align/diff_analysis.md +0 -53
  952. package/skills/hmos-incremental-ui-align/page_align.md +0 -62
  953. package/skills/hmos-incremental-ui-align/references/Comparison_Template.md +0 -38
  954. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Observed/350/243/205/351/245/260/345/231/250/345/222/214@ObjectLink/350/243/205/351/245/260/345/231/250/357/274/232/345/265/214/345/245/227/347/261/273/345/257/271/350/261/241/345/261/236/346/200/247/345/217/230/345/214/226.md +0 -2089
  955. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Prop/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/215/225/345/220/221/345/220/214/346/255/245.md +0 -1033
  956. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/Environment/357/274/232/350/256/276/345/244/207/347/216/257/345/242/203/346/237/245/350/257/242.md +0 -106
  957. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/MVVM/346/250/241/345/274/217V1.md +0 -911
  958. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Computed/350/243/205/351/245/260/345/231/250/357/274/232/350/256/241/347/256/227/345/261/236/346/200/247.md +0 -373
  959. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Event/350/243/205/351/245/260/345/231/250/357/274/232/350/247/204/350/214/203/347/273/204/344/273/266/350/276/223/345/207/272.md +0 -158
  960. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Monitor/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/344/277/256/346/224/271/345/274/202/346/255/245/347/233/221/345/220/254.md +0 -1704
  961. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@ObservedV2/350/243/205/351/245/260/345/231/250/345/222/214@Trace/350/243/205/351/245/260/345/231/250/357/274/232/347/261/273/345/261/236/346/200/247/345/217/230/345/214/226/350/247/202/346/265/213.md +0 -1012
  962. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Once/350/243/205/351/245/260/345/231/250/357/274/232/345/210/235/345/247/213/345/214/226/345/220/214/346/255/245/344/270/200/346/254/241.md +0 -164
  963. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Type/350/243/205/351/245/260/345/231/250/357/274/232/346/240/207/350/256/260/347/261/273/345/261/236/346/200/247/347/232/204/347/261/273/345/236/213.md +0 -83
  964. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +0 -47
  965. package/skills/hmos-incremental-ui-align/references/State_Model_Template.md +0 -74
  966. package/skills/hmos-incremental-ui-align/references/UI_Analysis_Template.md +0 -34
  967. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +0 -2533
  968. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-interaction-mapping-reference.md +0 -555
  969. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.ts +0 -937
  970. package/skills/hmos-incremental-ui-align/scripts/extract_checklist.ts +0 -343
  971. package/skills/hmos-incremental-ui-align/scripts/navigation-capure.md +0 -76
  972. package/skills/hmos-incremental-ui-align/scripts/page_capture.ts +0 -977
  973. package/skills/hmos-incremental-ui-align/scripts/page_capture_burst.ts +0 -188
  974. package/skills/hmos-integration-test/README.md +0 -341
  975. package/skills/hmos-integration-test/SKILL.md +0 -464
  976. package/skills/hmos-integration-test/scripts/report-tool.ts +0 -791
  977. package/skills/hmos-integration-test/scripts/resolve-metadata-tool.ts +0 -125
  978. package/skills/hmos-integration-test/scripts/self-test-runner.ts +0 -756
  979. package/skills/hmos-integration-test/scripts/testcases-tool.ts +0 -239
  980. package/skills/hmos-resources-convert/SKILL.md +0 -891
  981. package/skills/hmos-spec-generate/SKILL.md +0 -404
  982. package/skills/hmos-test-case-generation/README.md +0 -241
  983. package/skills/hmos-test-case-generation/SKILL.md +0 -324
  984. package/skills/hmos-test-case-generation/references/contract.md +0 -315
  985. package/skills/hmos-test-case-generation/references/review-notes-template.md +0 -84
  986. package/skills/hmos-test-case-generation/references/ui-elements-schema.md +0 -142
  987. package/skills/hmos-test-case-generation/tools/convert_to_ui_elements.ts +0 -550
  988. package/skills/hmos-test-case-generation/tools/validate.ts +0 -1312
  989. package/tools/bfs-crawl/README.md +0 -73
  990. package/tools/bfs-crawl/android_viewtree_bfs_crawler.ts +0 -1662
  991. /package/{README.en.md → skills/a2h-arch-generate/scripts/module_create/har/consumer-rules.txt} +0 -0
  992. /package/skills/{hmos-spec-generate → a2h-spec-generate}/template/REQ.xlsx +0 -0
@@ -1,2163 +1,2529 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Android → HarmonyOS 资源转换器(规范实现,第一期)
4
- *
5
- * 本脚本是 hmos-resources-convert skill 的**唯一**转换实现。agent 不再自行编写
6
- * 转换脚本——历史上每个 cell 各写一套(10 个 cell、3 种语言、约 1 万行),
7
- * 导致同一份 APK 跑出互不相同的结果、计数口径不一致、部分 cell 还引入了
8
- * 浮动版本的 npm 依赖。
9
- *
10
- * 覆盖范围(第一期):
11
- * - values/*.xml → base/element/*.json(string / color / float / integer /
12
- * boolean / strarray / intarray / plural)
13
- * - 限定符目录映射(密度、语言地区、横竖屏、深色、API 级别剥离、屏幕尺寸跳过)
14
- * - 媒体文件直拷 + 点九图重命名(.9.png → _9.png)
15
- * - raw/ → rawfile/,font/ → rawfile/fonts/,xml/ → base/profile/
16
- * - 不可映射类型(layout / menu / anim / animator / color / interpolator …)留记录
17
- * - inventory + mapping 记录(条目级),供报告与 mapping 文档使用
18
- *
19
- * 尚未覆盖(后续期次,当前只登记为 pending,不静默丢弃):
20
- * - XML drawable → SVG(vector / shape / layer-list / selector)
21
- * - adaptive-icon → layered-image JSON + 纯色 PNG
22
- * - 引用解析链、系统资源表、fallback
23
- *
24
- * 零第三方依赖,仅使用 Node 内置模块。需要 Node >= 22.18(原生 strip-types)。
25
- *
26
- * 用法:
27
- * node a2h_resource_convert.ts --res <decoded res dir> --harmony <harmony project dir>
28
- * [--records <path>] [--dry-run] [--quiet]
29
- *
30
- * 退出码:
31
- * 0 转换完成(pending 项不算失败,但会计数并在 records 中留行)
32
- * 1 存在转换失败项
33
- * 2 用法错误 / 路径不存在
34
- */
35
-
36
- import * as fs from 'node:fs';
37
- import * as path from 'node:path';
38
- import * as zlib from 'node:zlib';
39
-
40
- // ─────────────────────────────────────────────
41
- // 常量表
42
- // ─────────────────────────────────────────────
43
-
44
- /** Android 密度限定符 → HarmonyOS 密度限定符。见 conversion-rules.md「Density Qualifiers」。 */
45
- const DENSITY: Record<string, string | null> = {
46
- ldpi: 'sdpi', mdpi: 'mdpi', tvdpi: 'ldpi', hdpi: 'ldpi',
47
- xhdpi: 'xldpi', xxhdpi: 'xxldpi', xxxhdpi: 'xxxldpi',
48
- nodpi: null, anydpi: null, // → base,不产生限定符
49
- };
50
-
51
- const ORIENTATION: Record<string, string> = { land: 'horizontal', port: 'vertical' };
52
- const COLORMODE: Record<string, string> = { night: 'dark', notnight: 'light' };
53
-
54
- /** 静默剥离:无 HarmonyOS 对应物,但不影响资源本身的适用性。 */
55
- const STRIP_RE = /^(v\d+|ldrtl|ldltr|round|notround|highdr|lowdr|long|notlong)$/;
56
-
57
- /** 整目录跳过:屏幕尺寸类限定符,HarmonyOS 无等价物,转过去会是错的。 */
58
- const SKIP_RE = /^(sw\d+dp|w\d+dp|h\d+dp|small|normal|large|xlarge)$/;
59
-
60
- /** 设备类型限定符 → HarmonyOS 设备限定符。 */
61
- const DEVICE: Record<string, string> = {
62
- watch: 'wearable', television: 'tv', car: 'car', desk: 'phone', appliance: 'phone',
63
- };
64
-
65
- const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg']);
66
- const FONT_EXT = new Set(['.ttf', '.otf', '.ttc']);
67
-
68
- /** 目录类型 → 处理方式。 */
69
- const UNMAPPABLE_TYPES = new Set([
70
- 'layout', 'menu', 'anim', 'animator', 'color', 'interpolator',
71
- 'transition', 'navigation', 'id', 'ids',
72
- ]);
73
-
74
- /**
75
- * Android 框架内置颜色。见 SKILL.md Step 5.2。
76
- * HarmonyOS 没有 Android 系统资源概念,`@android:` 引用**绝不能**留在输出里。
77
- */
78
- const ANDROID_SYSTEM_COLORS: Record<string, string> = {
79
- white: '#ffffffff', black: '#ff000000', transparent: '#00000000',
80
- background_dark: '#ff000000', background_light: '#ffffffff', darker_gray: '#ffaaaaaa',
81
- holo_blue_bright: '#ff00ddff', holo_blue_dark: '#ff0099cc', holo_blue_light: '#ff33b5e5',
82
- holo_green_dark: '#ff669900', holo_green_light: '#ff99cc00',
83
- holo_orange_dark: '#ffff8800', holo_orange_light: '#ffffbb33',
84
- holo_purple: '#ffaa66cc', holo_red_dark: '#ffcc0000', holo_red_light: '#ffff4444',
85
- primary_text_dark: '#ffffffff', primary_text_light: '#de000000',
86
- secondary_text_dark: '#b3ffffff', secondary_text_light: '#8a000000',
87
- tab_indicator_text: '#ff808080',
88
- tertiary_text_dark: '#80ffffff', tertiary_text_light: '#54000000',
89
- widget_edittext_dark: '#ff000000',
90
- };
91
-
92
- /** Android 框架内置尺寸。见 SKILL.md Step 5.2。 */
93
- const ANDROID_SYSTEM_DIMENS: Record<string, string> = {
94
- app_icon_size: '48vp',
95
- thumbnail_width: '96vp',
96
- thumbnail_height: '96vp',
97
- dialog_min_width_major: '65%',
98
- dialog_min_width_minor: '95%',
99
- notification_large_icon_width: '64vp',
100
- notification_large_icon_height: '64vp',
101
- };
102
-
103
- /** Android 框架内置字符串(英文取值)。 */
104
- const ANDROID_SYSTEM_STRINGS: Record<string, string> = {
105
- ok: 'OK', cancel: 'Cancel', yes: 'Yes', no: 'No',
106
- copy: 'Copy', cut: 'Cut', paste: 'Paste', selectAll: 'Select all',
107
- search_go: 'Search', unknownName: 'Unknown',
108
- };
109
-
110
- /** 无法解析时按类型使用的兜底值。见 SKILL.md Step 5.2「Fallback values by type」。 */
111
- const FALLBACK_BY_KEY: Record<string, unknown> = {
112
- color: '#ff000000', float: '0vp', string: '', integer: 0, boolean: false,
113
- };
114
-
115
- /**
116
- * 解码后的 APK 里,枚举属性是数字而不是名字(aapt 编译后的值)。
117
- * 直接把数字写进 SVG 会得到非法的 `stroke-linecap="2"`。
118
- */
119
- const STROKE_LINECAP = ['butt', 'round', 'square'];
120
- const STROKE_LINEJOIN = ['miter', 'round', 'bevel'];
121
-
122
- /** Android 尺寸单位 → HarmonyOS 单位 / 换算系数。 */
123
- const DIMEN_UNITS: Array<{ re: RegExp; unit: string; factor: number }> = [
124
- { re: /^(-?[\d.]+)dip$/i, unit: 'vp', factor: 1 },
125
- { re: /^(-?[\d.]+)dp$/i, unit: 'vp', factor: 1 },
126
- { re: /^(-?[\d.]+)sp$/i, unit: 'fp', factor: 1 },
127
- { re: /^(-?[\d.]+)px$/i, unit: 'px', factor: 1 },
128
- { re: /^(-?[\d.]+)pt$/i, unit: 'vp', factor: 1.33 },
129
- { re: /^(-?[\d.]+)in$/i, unit: 'vp', factor: 160 },
130
- { re: /^(-?[\d.]+)mm$/i, unit: 'vp', factor: 6.3 },
131
- { re: /^(-?[\d.]+)$/, unit: 'vp', factor: 1 },
132
- ];
133
-
134
- /** Android values 标签 → HarmonyOS element 文件名与 JSON 根键。 */
135
- const ELEMENT_KIND: Record<string, { file: string; key: string }> = {
136
- string: { file: 'string.json', key: 'string' },
137
- color: { file: 'color.json', key: 'color' },
138
- dimen: { file: 'float.json', key: 'float' },
139
- integer: { file: 'integer.json', key: 'integer' },
140
- bool: { file: 'boolean.json', key: 'boolean' },
141
- 'string-array': { file: 'strarray.json', key: 'strarray' },
142
- 'integer-array': { file: 'intarray.json', key: 'intarray' },
143
- plurals: { file: 'plural.json', key: 'plural' },
144
- };
145
-
146
- /** 这些 values 标签在 HarmonyOS 没有等价物,登记为 unmappable。 */
147
- const VALUES_UNMAPPABLE = new Set([
148
- 'style', 'declare-styleable', 'attr', 'item', 'eat-comment', 'skip', 'fraction', 'macro',
149
- ]);
150
-
151
- // ─────────────────────────────────────────────
152
- // 类型
153
- // ─────────────────────────────────────────────
154
-
155
- interface XmlNode {
156
- name: string;
157
- attrs: Record<string, string>;
158
- children: XmlNode[];
159
- /** 元素内部的原始源码片段(含子标签),字符串资源需要它 */
160
- inner: string;
161
- }
162
-
163
- /** Android 资源清单行。字段对齐 references/resource-mapping-rules.md §2.1。 */
164
- interface InventoryRecord {
165
- androidResourcePath: string;
166
- androidResourceName: string;
167
- function: string;
168
- screens: string;
169
- sourceCategory: string;
170
- typeCategory: string;
171
- status: string;
172
- notes: string;
173
- }
174
-
175
- /** Android ↔ HarmonyOS 映射行。字段对齐 §2.2。 */
176
- interface MappingRecord {
177
- androidResourcePath: string;
178
- androidScreens: string;
179
- androidSourceCategory: string;
180
- androidTypeCategory: string;
181
- harmonyTarget: string;
182
- mappingKind: string;
183
- notes: string;
184
- }
185
-
186
- interface QualifierPlan {
187
- /** HarmonyOS 限定符目录名,`base` 表示无限定符 */
188
- dir: string;
189
- /** 整目录跳过时的原因 */
190
- skip: string | null;
191
- stripped: string[];
192
- }
193
-
194
- // ─────────────────────────────────────────────
195
- // 工具
196
- // ─────────────────────────────────────────────
197
-
198
- function fail(msg: string): never {
199
- console.error(`[a2h_resource_convert] ${msg}`);
200
- process.exit(2);
201
- }
202
-
203
- const ENTITIES: Record<string, string> = {
204
- amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
205
- };
206
-
207
- function decodeEntities(s: string): string {
208
- return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (m, body: string) => {
209
- if (body[0] === '#') {
210
- const code = body[1] === 'x' || body[1] === 'X'
211
- ? parseInt(body.slice(2), 16)
212
- : parseInt(body.slice(1), 10);
213
- return Number.isFinite(code) ? String.fromCodePoint(code) : m;
214
- }
215
- return ENTITIES[body] ?? m;
216
- });
217
- }
218
-
219
- // ─────────────────────────────────────────────
220
- // 极简 XML 解析器
221
- // ─────────────────────────────────────────────
222
-
223
- /**
224
- * 只覆盖 Android 资源 XML 需要的语法:元素、属性、文本、CDATA、注释、
225
- * 声明与 DOCTYPE。不做 DTD、实体声明、命名空间解析(属性名按原样保留,
226
- * 调用方用 localName 比对)。
227
- */
228
- function parseXml(src: string): XmlNode {
229
- let i = 0;
230
- const n = src.length;
231
-
232
- function skipUntil(marker: string): void {
233
- const at = src.indexOf(marker, i);
234
- i = at < 0 ? n : at + marker.length;
235
- }
236
-
237
- function parseAttrs(end: number): Record<string, string> {
238
- const attrs: Record<string, string> = {};
239
- const re = /([^\s=/>]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
240
- const slice = src.slice(i, end);
241
- let m: RegExpExecArray | null;
242
- while ((m = re.exec(slice)) !== null) {
243
- attrs[m[1]] = decodeEntities(m[3] ?? m[4] ?? '');
244
- }
245
- return attrs;
246
- }
247
-
248
- function parseNode(): XmlNode | null {
249
- while (i < n) {
250
- const lt = src.indexOf('<', i);
251
- if (lt < 0) return null;
252
- i = lt;
253
- if (src.startsWith('<!--', i)) { skipUntil('-->'); continue; }
254
- if (src.startsWith('<?', i)) { skipUntil('?>'); continue; }
255
- if (src.startsWith('<!DOCTYPE', i) || src.startsWith('<!', i)) { skipUntil('>'); continue; }
256
- if (src.startsWith('</', i)) return null;
257
- break;
258
- }
259
- if (i >= n) return null;
260
-
261
- const gt = src.indexOf('>', i);
262
- if (gt < 0) return null;
263
- const selfClosing = src[gt - 1] === '/';
264
- const head = src.slice(i + 1, selfClosing ? gt - 1 : gt);
265
- const name = head.split(/[\s/]/, 1)[0];
266
- const attrs = parseAttrs(gt);
267
- i = gt + 1;
268
-
269
- const node: XmlNode = { name, attrs, children: [], inner: '' };
270
- if (selfClosing) return node;
271
-
272
- const innerStart = i;
273
- // 逐段消费,直到遇到本元素的结束标签
274
- while (i < n) {
275
- const lt = src.indexOf('<', i);
276
- if (lt < 0) { i = n; break; }
277
- if (src.startsWith('<![CDATA[', lt)) {
278
- i = lt; skipUntil(']]>'); continue;
279
- }
280
- if (src.startsWith('<!--', lt)) { i = lt; skipUntil('-->'); continue; }
281
- if (src.startsWith(`</${name}`, lt)) {
282
- node.inner = src.slice(innerStart, lt);
283
- i = src.indexOf('>', lt);
284
- i = i < 0 ? n : i + 1;
285
- return node;
286
- }
287
- i = lt;
288
- const child = parseNode();
289
- if (child) node.children.push(child);
290
- else { i = lt + 1; }
291
- }
292
- node.inner = src.slice(innerStart);
293
- return node;
294
- }
295
-
296
- const root = parseNode();
297
- return root ?? { name: '', attrs: {}, children: [], inner: '' };
298
- }
299
-
300
- /** 属性按 localName 取值(忽略 `android:` 之类的前缀)。 */
301
- function attr(node: XmlNode, local: string): string | undefined {
302
- for (const [k, v] of Object.entries(node.attrs)) {
303
- if (k === local || k.endsWith(`:${local}`)) return v;
304
- }
305
- return undefined;
306
- }
307
-
308
- // ─────────────────────────────────────────────
309
- // 值转换
310
- // ─────────────────────────────────────────────
311
-
312
- /**
313
- * Android 字符串字面量 → HarmonyOS 字符串值。
314
- *
315
- * 顺序很重要:先取 CDATA / 去标签,再解实体,再解 Android 反斜杠转义,
316
- * 最后剥掉 Android 的成对外层引号(那对引号是用来保护首尾空白的语法,
317
- * 不是文本内容——SKILL.md Step 6.11 专门校验这一点)。
318
- */
319
- function normalizeString(inner: string): string {
320
- let s = inner;
321
- const cdata = [...s.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)];
322
- if (cdata.length > 0) s = cdata.map((m) => m[1]).join('');
323
- s = decodeEntities(s);
324
- s = s.replace(/\\(['"@?\\])/g, '$1').replace(/\\n/g, '\n').replace(/\\t/g, '\t');
325
- if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) s = s.slice(1, -1);
326
- return s;
327
- }
328
-
329
- /** `#RGB` / `#ARGB` / `#RRGGBB` / `#AARRGGBB` → `#AARRGGBB`(小写)。 */
330
- function normalizeColor(raw: string): string | null {
331
- const v = raw.trim();
332
- const m = /^#([0-9a-fA-F]{3,8})$/.exec(v);
333
- if (!m) return null;
334
- const h = m[1].toLowerCase();
335
- if (h.length === 3) return `#ff${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}`;
336
- if (h.length === 4) return `#${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}${h[3]}${h[3]}`;
337
- if (h.length === 6) return `#ff${h}`;
338
- if (h.length === 8) return `#${h}`;
339
- return null;
340
- }
341
-
342
- /** Android 尺寸 → HarmonyOS 尺寸字符串。无法解析时返回 null(调用方登记 fallback)。 */
343
- function normalizeDimen(raw: string): string | null {
344
- const v = raw.trim();
345
- for (const { re, unit, factor } of DIMEN_UNITS) {
346
- const m = re.exec(v);
347
- if (!m) continue;
348
- const num = parseFloat(m[1]);
349
- if (!Number.isFinite(num)) return null;
350
- // 一律收敛到 3 位小数:resources.arsc 里的定点数解码后常带浮点噪声
351
- // (例如 6.500001dip),原样输出会把噪声带进 HarmonyOS 资源。
352
- const scaled = Math.round(num * factor * 1000) / 1000;
353
- return `${scaled}${unit}`;
354
- }
355
- return null;
356
- }
357
-
358
- function normalizeInteger(raw: string): number | null {
359
- const v = raw.trim();
360
- const parsed = /^0[xX]/.test(v) ? parseInt(v, 16) : parseInt(v, 10);
361
- return Number.isFinite(parsed) ? parsed : null;
362
- }
363
-
364
- // ─────────────────────────────────────────────
365
- // 纯色 PNG 生成(zlib + 手写 PNG 封装,避免引入 pngjs)
366
- // ─────────────────────────────────────────────
367
-
368
- let CRC_TABLE: Int32Array | null = null;
369
-
370
- function crc32(buf: Buffer): number {
371
- if (!CRC_TABLE) {
372
- CRC_TABLE = new Int32Array(256);
373
- for (let n = 0; n < 256; n++) {
374
- let c = n;
375
- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
376
- CRC_TABLE[n] = c;
377
- }
378
- }
379
- let c = -1;
380
- for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
381
- return (c ^ -1) >>> 0;
382
- }
383
-
384
- function pngChunk(type: string, data: Buffer): Buffer {
385
- const len = Buffer.alloc(4);
386
- len.writeUInt32BE(data.length, 0);
387
- const body = Buffer.concat([Buffer.from(type, 'latin1'), data]);
388
- const crc = Buffer.alloc(4);
389
- crc.writeUInt32BE(crc32(body), 0);
390
- return Buffer.concat([len, body, crc]);
391
- }
392
-
393
- /** 生成 size×size 的纯色 RGBA PNG。`#AARRGGBB` 输入。 */
394
- function solidPng(argb: string, size = 108): Buffer {
395
- const h = argb.replace('#', '');
396
- const a = parseInt(h.slice(0, 2), 16);
397
- const r = parseInt(h.slice(2, 4), 16);
398
- const g = parseInt(h.slice(4, 6), 16);
399
- const b = parseInt(h.slice(6, 8), 16);
400
-
401
- const row = Buffer.alloc(1 + size * 4);
402
- for (let x = 0; x < size; x++) {
403
- row[1 + x * 4] = r; row[2 + x * 4] = g; row[3 + x * 4] = b; row[4 + x * 4] = a;
404
- }
405
- const raw = Buffer.concat(Array.from({ length: size }, () => row));
406
-
407
- const ihdr = Buffer.alloc(13);
408
- ihdr.writeUInt32BE(size, 0);
409
- ihdr.writeUInt32BE(size, 4);
410
- ihdr[8] = 8; // bit depth
411
- ihdr[9] = 6; // color type RGBA
412
- return Buffer.concat([
413
- Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
414
- pngChunk('IHDR', ihdr),
415
- pngChunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
416
- pngChunk('IEND', Buffer.alloc(0)),
417
- ]);
418
- }
419
-
420
- // ─────────────────────────────────────────────
421
- // XML drawable → SVG
422
- // ─────────────────────────────────────────────
423
-
424
- interface SvgPaint {
425
- color: string;
426
- opacity: number | null;
427
- }
428
-
429
- /** `#AARRGGBB` / `#RRGGBB` / 简写 → SVG 的 `#RRGGBB` + 独立 opacity。 */
430
- function androidColorToSvg(raw: string): SvgPaint | null {
431
- const c = normalizeColor(raw);
432
- if (!c) return null;
433
- const h = c.slice(1);
434
- const alpha = parseInt(h.slice(0, 2), 16) / 255;
435
- return {
436
- color: `#${h.slice(2)}`,
437
- opacity: alpha >= 0.999 ? null : Math.round(alpha * 1000) / 1000,
438
- };
439
- }
440
-
441
- /** `24dp` / `24dip` / `24` → `24`(SVG 用户单位)。 */
442
- function svgNum(raw: string | undefined, fallback: number): number {
443
- if (!raw) return fallback;
444
- const m = /^(-?[\d.]+)/.exec(raw.trim());
445
- const v = m ? parseFloat(m[1]) : NaN;
446
- return Number.isFinite(v) ? v : fallback;
447
- }
448
-
449
- function esc(s: string): string {
450
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
451
- }
452
-
453
- // ─────────────────────────────────────────────
454
- // 限定符目录解析
455
- // ─────────────────────────────────────────────
456
-
457
- /**
458
- * `drawable-zh-rCN-night-hdpi` → { type: 'drawable', plan: { dir: 'zh_CN-dark-ldpi' } }
459
- *
460
- * 输出顺序遵循 HarmonyOS 约定:
461
- * MCC_MNC-language_script_country-orientation-device-colormode-density
462
- */
463
- function planQualifiers(dirName: string): { type: string; plan: QualifierPlan } {
464
- const segs = dirName.split('-');
465
- const type = segs[0];
466
- const rest = segs.slice(1);
467
-
468
- let language = '';
469
- let script = '';
470
- let region = '';
471
- let orientation = '';
472
- let device = '';
473
- let colormode = '';
474
- let density = '';
475
- const stripped: string[] = [];
476
-
477
- for (let k = 0; k < rest.length; k++) {
478
- const q = rest[k];
479
- if (SKIP_RE.test(q)) {
480
- return { type, plan: { dir: '', skip: `Unsupported qualifier: ${q} — no HarmonyOS equivalent`, stripped } };
481
- }
482
- if (STRIP_RE.test(q)) { stripped.push(q); continue; }
483
- if (q in DENSITY) {
484
- const d = DENSITY[q];
485
- if (d) density = d; else stripped.push(q); // nodpi / anydpi → base
486
- continue;
487
- }
488
- if (q in ORIENTATION) { orientation = ORIENTATION[q]; continue; }
489
- if (q in COLORMODE) { colormode = COLORMODE[q]; continue; }
490
- if (q in DEVICE) { device = DEVICE[q]; continue; }
491
- if (/^b\+/.test(q)) { // BCP 47:b+sr+Latn
492
- const parts = q.slice(2).split('+');
493
- language = parts[0] ?? '';
494
- if (parts[1] && parts[1].length === 4) script = parts[1];
495
- if (parts[2]) region = parts[2];
496
- continue;
497
- }
498
- // 地区限定符:ISO 3166-1 两位字母(rCN),或 UN M.49 三位数字(r419 = 拉丁美洲)。
499
- // 只认两位字母的话,`values-es-r419` 会被当成无法识别而剥离,直接并进通用 `es`——
500
- // 拉美西班牙语会覆盖掉欧洲西班牙语,是静默的错译。HarmonyOS 的地区位同样接受三位数字。
501
- if (/^r(?:[A-Z]{2}|\d{3})$/.test(q) && language) { region = q.slice(1); continue; }
502
- if (/^[a-z]{2,3}$/.test(q) && !language) { language = q; continue; }
503
- if (/^mcc\d+$/.test(q) || /^mnc\d+$/.test(q)) { stripped.push(q); continue; }
504
- stripped.push(q); // 其余未识别限定符:剥离,不拒绝
505
- }
506
-
507
- const locale = [language, script, region].filter(Boolean).join('_');
508
- const dir = [locale, orientation, device, colormode, density].filter(Boolean).join('-') || 'base';
509
- return { type, plan: { dir, skip: null, stripped } };
510
- }
511
-
512
- // ─────────────────────────────────────────────
513
- // 转换主体
514
- // ─────────────────────────────────────────────
515
-
516
- interface ElementEntry {
517
- name: string;
518
- value: unknown;
519
- /** Android 侧原始文本,引用解析回溯时要用 */
520
- raw: string;
521
- sourcePath: string;
522
- }
523
-
524
- /** 一条引用解析记录,供报告的「Resource Reference Resolution」小节使用。 */
525
- interface ResolutionRecord {
526
- file: string;
527
- name: string;
528
- reference: string;
529
- resolved: string;
530
- chain: string;
531
- kind: 'project' | 'system' | 'fallback' | 'theme-attr';
532
- }
533
-
534
- class Converter {
535
- resDir: string;
536
- outRoot: string;
537
- dryRun: boolean;
538
-
539
- /** qualifierDir → elementFile → name → entry */
540
- elements = new Map<string, Map<string, Map<string, ElementEntry>>>();
541
- /** base 限定符下的原始 color / dimen 值,供 SVG 转换时就地解析引用 */
542
- rawColors = new Map<string, string>();
543
- rawDimens = new Map<string, string>();
544
- /** base 限定符下的原始 string 值,pathData 可能以 `@string/xxx` 形式引用它们 */
545
- rawStrings = new Map<string, string>();
546
- rawIntegers = new Map<string, string>();
547
- rawBools = new Map<string, string>();
548
- resolutions: ResolutionRecord[] = [];
549
- /** 每处理一个文件记一条,用于报告里的「限定符映射」聚合表 */
550
- qualifierUse: Array<{ android: string; harmony: string }> = [];
551
- /** 已生成的纯色 PNG,避免重复生成 */
552
- generatedPngs = new Set<string>();
553
- inventory: InventoryRecord[] = [];
554
- mappings: MappingRecord[] = [];
555
- warnings: string[] = [];
556
- conflicts: string[] = [];
557
- counts = {
558
- valuesEntries: 0, mediaCopied: 0, ninePatchRenamed: 0,
559
- rawCopied: 0, fontCopied: 0, profileCopied: 0,
560
- unmappable: 0, skippedQualifierDirs: 0, failed: 0,
561
- svgConverted: 0, layeredImages: 0, solidPngGenerated: 0, systemColorsResolved: 0,
562
- referencesResolved: 0, systemReferencesResolved: 0, fallbacksApplied: 0,
563
- unresolvedPaint: 0, mediaTargetCollisions: 0,
564
- };
565
-
566
- constructor(resDir: string, harmonyDir: string, dryRun: boolean) {
567
- this.resDir = resDir;
568
- this.outRoot = path.join(harmonyDir, 'entry', 'src', 'main', 'resources');
569
- this.dryRun = dryRun;
570
- }
571
-
572
- // ── 记录 ──
573
-
574
- inv(r: Partial<InventoryRecord> & { androidResourcePath: string; androidResourceName: string }): void {
575
- this.inventory.push({
576
- function: '', screens: 'Common', sourceCategory: '应用自身资源',
577
- typeCategory: 'drawable', status: 'converted', notes: '', ...r,
578
- });
579
- }
580
-
581
- map(r: Partial<MappingRecord> & { androidResourcePath: string }): void {
582
- this.mappings.push({
583
- androidScreens: 'Common', androidSourceCategory: '应用自身资源',
584
- androidTypeCategory: 'drawable', harmonyTarget: 'N/A',
585
- mappingKind: 'unmappable', notes: '', ...r,
586
- });
587
- }
588
-
589
- /**
590
- * 资源来源类别推断。仅使用可证据化的前缀约定,
591
- * 见 resource-mapping-rules.md §7.3;无证据时归为应用自身资源。
592
- */
593
- sourceCategory(name: string): string {
594
- return /^(abc_|mtrl_|material_|design_|m3_|androidx_|exo_|preference_|common_|gcm_|fcm_|play_)/.test(name)
595
- ? '第三方库资源'
596
- : '应用自身资源';
597
- }
598
-
599
- /** 目标媒体路径 → 已占用它的 Android 源文件与其限定符个数 */
600
- claimedTargets = new Map<string, { source: string; quals: number }>();
601
-
602
- /**
603
- * 多个 Android 源可能落到同一个 HarmonyOS 目标:`drawable/x.xml` 与
604
- * `drawable-anydpi/x.xml`(anydpi→base)、`drawable-v31/x.xml`(v31 剥离)都写
605
- * `base/media/x.svg`。HarmonyOS 表达不了这些限定符,必须择一。
606
- *
607
- * 规则:**限定符更少者胜**——无限定符的资源是无条件生效的那一份。
608
- * 落败者不静默丢弃,仍产出 unmappable 映射行说明原因。
609
- * 返回 false 表示本次不应写入。
610
- */
611
- claimTarget(targetRel: string, relFile: string, androidPath: string, type: string): boolean {
612
- const quals = relFile.split('/')[0].split('-').length - 1;
613
- const prev = this.claimedTargets.get(targetRel);
614
- if (!prev) {
615
- this.claimedTargets.set(targetRel, { source: relFile, quals });
616
- return true;
617
- }
618
- this.counts.mediaTargetCollisions++;
619
- const loser = quals < prev.quals ? prev.source : relFile;
620
- const winner = quals < prev.quals ? relFile : prev.source;
621
- const note = `HarmonyOS target collision on ${targetRel}: kept res/${winner} (fewer qualifiers), dropped res/${loser}`;
622
- this.warnings.push(note);
623
- this.map({
624
- androidResourcePath: `res/${loser}`, androidTypeCategory: type,
625
- androidSourceCategory: this.sourceCategory(path.basename(loser).replace(/\.[^.]+$/, '')),
626
- mappingKind: 'unmappable', notes: note,
627
- });
628
- if (quals < prev.quals) {
629
- this.claimedTargets.set(targetRel, { source: relFile, quals });
630
- return true;
631
- }
632
- return false;
633
- }
634
-
635
- write(rel: string, data: string | Buffer): void {
636
- if (this.dryRun) return;
637
- const full = path.join(this.outRoot, rel);
638
- fs.mkdirSync(path.dirname(full), { recursive: true });
639
- fs.writeFileSync(full, data);
640
- }
641
-
642
- // ── values ──
643
-
644
- addElement(qdir: string, file: string, entry: ElementEntry): void {
645
- let byFile = this.elements.get(qdir);
646
- if (!byFile) { byFile = new Map(); this.elements.set(qdir, byFile); }
647
- let byName = byFile.get(file);
648
- if (!byName) { byName = new Map(); byFile.set(file, byName); }
649
- const prev = byName.get(entry.name);
650
- if (prev && prev.sourcePath !== entry.sourcePath) {
651
- // Android 语义:后定义覆盖先定义
652
- this.conflicts.push(`${qdir}/${file}#${entry.name}: ${prev.sourcePath} → ${entry.sourcePath}`);
653
- }
654
- byName.set(entry.name, entry);
655
- }
656
-
657
- processValuesFile(relFile: string, qdir: string): void {
658
- const src = fs.readFileSync(path.join(this.resDir, relFile), 'utf8');
659
- const root = parseXml(src);
660
- if (root.name !== 'resources') return;
661
-
662
- for (const el of root.children) {
663
- const name = attr(el, 'name');
664
- if (!name) continue;
665
- const tag = el.name;
666
- const androidPath = `res/${relFile}#${tag}/${name}`;
667
- const sourceCategory = this.sourceCategory(name);
668
-
669
- if (VALUES_UNMAPPABLE.has(tag)) {
670
- this.counts.unmappable++;
671
- this.inv({
672
- androidResourcePath: androidPath, androidResourceName: name,
673
- function: `${tag} resource`, sourceCategory, typeCategory: 'values',
674
- status: 'unmappable', notes: `Android ${tag} has no HarmonyOS equivalent`,
675
- });
676
- this.map({
677
- androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
678
- androidTypeCategory: 'values', mappingKind: 'unmappable',
679
- notes: `Android ${tag} has no HarmonyOS equivalent`,
680
- });
681
- continue;
682
- }
683
-
684
- const kind = ELEMENT_KIND[tag];
685
- if (!kind) {
686
- this.counts.unmappable++;
687
- this.inv({
688
- androidResourcePath: androidPath, androidResourceName: name,
689
- function: `${tag} resource`, sourceCategory, typeCategory: 'values',
690
- status: 'unmappable', notes: `unrecognized values tag: ${tag}`,
691
- });
692
- this.map({
693
- androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
694
- androidTypeCategory: 'values', notes: `unrecognized values tag: ${tag}`,
695
- });
696
- continue;
697
- }
698
-
699
- // base 限定符的原始值先入表,SVG 转换要靠它解析 @color / @dimen 引用
700
- if (qdir === 'base') {
701
- if (tag === 'color') this.rawColors.set(name, decodeEntities(el.inner).trim());
702
- else if (tag === 'dimen') this.rawDimens.set(name, decodeEntities(el.inner).trim());
703
- else if (tag === 'string') this.rawStrings.set(name, normalizeString(el.inner));
704
- else if (tag === 'integer') this.rawIntegers.set(name, decodeEntities(el.inner).trim());
705
- else if (tag === 'bool') this.rawBools.set(name, decodeEntities(el.inner).trim());
706
- }
707
-
708
- const value = this.convertValue(tag, el, androidPath);
709
- if (value === undefined) { this.counts.failed++; continue; }
710
-
711
- this.addElement(qdir, kind.file, {
712
- name, value, raw: decodeEntities(el.inner).trim(), sourcePath: androidPath,
713
- });
714
- this.counts.valuesEntries++;
715
- const target = `resources/${qdir}/element/${kind.file}#${name}`;
716
- this.inv({
717
- androidResourcePath: androidPath, androidResourceName: name,
718
- function: `${tag} value resource`, sourceCategory, typeCategory: 'values',
719
- status: 'converted',
720
- });
721
- this.map({
722
- androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
723
- androidTypeCategory: 'values', harmonyTarget: target, mappingKind: 'merged into json',
724
- });
725
- }
726
- }
727
-
728
- /** 返回 undefined 表示转换失败(已计数并告警)。 */
729
- convertValue(tag: string, el: XmlNode, androidPath: string): unknown {
730
- const raw = el.inner;
731
- switch (tag) {
732
- case 'string':
733
- return normalizeString(raw);
734
- case 'color': {
735
- const c = normalizeColor(decodeEntities(raw));
736
- if (c) return c;
737
- // 引用留给后续期次解析;此处按规则转成 HarmonyOS 引用语法
738
- return this.toHarmonyRef(raw.trim(), androidPath, 'color');
739
- }
740
- case 'dimen': {
741
- const d = normalizeDimen(decodeEntities(raw));
742
- if (d) return d;
743
- return this.toHarmonyRef(raw.trim(), androidPath, 'float');
744
- }
745
- case 'integer': {
746
- const v = normalizeInteger(decodeEntities(raw));
747
- if (v !== null) return v;
748
- this.warnings.push(`${androidPath}: integer 无法解析 (${raw.trim()}),暂留引用待后续解析`);
749
- return this.toHarmonyRef(raw.trim(), androidPath, 'integer');
750
- }
751
- case 'bool': {
752
- const t = decodeEntities(raw).trim().toLowerCase();
753
- if (t === 'true') return true;
754
- if (t === 'false') return false;
755
- return this.toHarmonyRef(raw.trim(), androidPath, 'boolean');
756
- }
757
- case 'string-array':
758
- return el.children
759
- .filter((c) => c.name === 'item')
760
- .map((c) => ({ value: normalizeString(c.inner) }));
761
- case 'integer-array':
762
- return el.children
763
- .filter((c) => c.name === 'item')
764
- .map((c) => ({ value: normalizeInteger(decodeEntities(c.inner)) ?? 0 }));
765
- case 'plurals':
766
- return el.children
767
- .filter((c) => c.name === 'item')
768
- .map((c) => ({ quantity: attr(c, 'quantity') ?? 'other', value: normalizeString(c.inner) }));
769
- default:
770
- return undefined;
771
- }
772
- }
773
-
774
- /** `@color/x` → `$color:x`;`?attr/x` 与 `@android:` 留原样,由后续期次处理。 */
775
- toHarmonyRef(raw: string, androidPath: string, expect: string): string {
776
- const m = /^@(?:([a-zA-Z0-9._]+):)?([a-z]+)\/(.+)$/.exec(raw);
777
- if (m && m[1] !== 'android') {
778
- const t = m[2] === 'dimen' ? 'float' : m[2] === 'bool' ? 'boolean' : m[2];
779
- return `$${t}:${m[3]}`;
780
- }
781
- this.warnings.push(`${androidPath}: 未解析的 ${expect} 值 "${raw}"(待后续期次解析)`);
782
- return raw;
783
- }
784
-
785
- /**
786
- * 引用解析 pass:把 element JSON 里残留的 `$type:name` / `@type/name` /
787
- * `@android:type/name` 解析成具体值。
788
- *
789
- * 为什么必须做:HarmonyOS 没有 Android 系统资源概念,`@android:` 留在输出里
790
- * 会直接编译失败;`$color:x` 若指向的资源不存在也一样。
791
- * 解析不出的按类型兜底并记录——**绝不静默留下未解析引用**。
792
- *
793
- * 链路最多 5 层(SKILL.md Step 5.2)。跨限定符时以 base 的值为准。
794
- */
795
- resolveReferences(): void {
796
- const rawOf: Record<string, Map<string, string>> = {
797
- color: this.rawColors, float: this.rawDimens, string: this.rawStrings,
798
- integer: this.rawIntegers, boolean: this.rawBools,
799
- };
800
- const androidType: Record<string, string> = {
801
- color: 'color', dimen: 'float', string: 'string', integer: 'integer', bool: 'boolean',
802
- };
803
-
804
- /** 把一个 Android 原始文本解析成具体值;返回 null 表示解析不出。 */
805
- const resolve = (
806
- key: string, raw: string, chain: string[], depth: number,
807
- ): { value: unknown; kind: ResolutionRecord['kind'] } | null => {
808
- const v = raw.trim();
809
- if (depth >= 5) return null;
810
-
811
- if (v.startsWith('?')) return null; // 主题属性,静态不可解析
812
-
813
- const sys = /^@android:([a-z]+)\/(.+)$/.exec(v);
814
- if (sys) {
815
- const table = sys[1] === 'color' ? ANDROID_SYSTEM_COLORS
816
- : sys[1] === 'dimen' ? ANDROID_SYSTEM_DIMENS
817
- : sys[1] === 'string' ? ANDROID_SYSTEM_STRINGS : null;
818
- const hit = table?.[sys[2]];
819
- if (hit !== undefined) {
820
- chain.push(v);
821
- return { value: key === 'integer' ? Number(hit) : hit, kind: 'system' };
822
- }
823
- return null;
824
- }
825
-
826
- const ref = /^@(?:[a-zA-Z0-9._]+:)?([a-z]+)\/(.+)$/.exec(v);
827
- if (ref) {
828
- const targetKey = androidType[ref[1]];
829
- if (!targetKey) return null;
830
- const next = rawOf[targetKey]?.get(ref[2]);
831
- if (next === undefined) return null;
832
- chain.push(v);
833
- return resolve(key, next, chain, depth + 1);
834
- }
835
-
836
- // 到达字面量:按目标类型做最终转换
837
- switch (key) {
838
- case 'color': { const c = normalizeColor(v); return c ? { value: c, kind: 'project' } : null; }
839
- case 'float': { const d = normalizeDimen(v); return d ? { value: d, kind: 'project' } : null; }
840
- case 'integer': { const n = normalizeInteger(v); return n === null ? null : { value: n, kind: 'project' }; }
841
- case 'boolean': {
842
- const t = v.toLowerCase();
843
- return t === 'true' || t === 'false' ? { value: t === 'true', kind: 'project' } : null;
844
- }
845
- default: return { value: v, kind: 'project' };
846
- }
847
- };
848
-
849
- for (const [qdir, byFile] of this.elements) {
850
- for (const [file, byName] of byFile) {
851
- const key = Object.values(ELEMENT_KIND).find((k) => k.file === file)!.key;
852
- if (!(key in FALLBACK_BY_KEY)) continue; // 数组 / plural 不做标量解析
853
-
854
- for (const entry of byName.values()) {
855
- const cur = entry.value;
856
- const unresolved = typeof cur === 'string' && (cur.startsWith('$') || cur.startsWith('@') || cur.startsWith('?'));
857
- if (!unresolved) continue;
858
-
859
- const chain: string[] = [];
860
- const got = resolve(key, entry.raw, chain, 0);
861
- const loc = `${qdir}/element/${file}`;
862
-
863
- if (got) {
864
- entry.value = got.value;
865
- this.counts.referencesResolved++;
866
- if (got.kind === 'system') this.counts.systemReferencesResolved++;
867
- this.resolutions.push({
868
- file: loc, name: entry.name, reference: entry.raw,
869
- resolved: String(got.value), chain: [entry.raw, ...chain].join(' → '), kind: got.kind,
870
- });
871
- continue;
872
- }
873
-
874
- entry.value = FALLBACK_BY_KEY[key];
875
- this.counts.fallbacksApplied++;
876
- this.resolutions.push({
877
- file: loc, name: entry.name, reference: entry.raw,
878
- resolved: String(entry.value), chain: entry.raw,
879
- kind: entry.raw.trim().startsWith('?') ? 'theme-attr' : 'fallback',
880
- });
881
- this.warnings.push(
882
- `${loc}#${entry.name}: 无法解析 ${entry.raw},按类型兜底为 ${JSON.stringify(entry.value)}`,
883
- );
884
- }
885
- }
886
- }
887
- }
888
-
889
- /**
890
- * 写出 element JSON。
891
- *
892
- * 若目标文件在 HarmonyOS 工程中已存在(DevEco 脚手架会生成
893
- * base/element/{string,color,float}.json),**合并**而不是覆盖:
894
- * 已有条目保持原有顺序在前,同名条目的值被转换结果替换(脚手架默认值
895
- * 可以被覆盖),其余转换条目按 name 排序追加。
896
- * 见 SKILL.md「Important Notes」最后一条。
897
- */
898
- flushElements(): void {
899
- for (const [qdir, byFile] of [...this.elements].sort()) {
900
- for (const [file, byName] of [...byFile].sort()) {
901
- const key = Object.values(ELEMENT_KIND).find((k) => k.file === file)!.key;
902
- const rel = path.join(qdir, 'element', file);
903
- const converted = new Map([...byName].map(([n, e]) => [n, e.value]));
904
-
905
- const out: Array<{ name: string; value: unknown }> = [];
906
- const taken = new Set<string>();
907
- const existingPath = path.join(this.outRoot, rel);
908
- if (fs.existsSync(existingPath)) {
909
- try {
910
- const prev = JSON.parse(fs.readFileSync(existingPath, 'utf8')) as Record<string, Array<{ name: string; value: unknown }>>;
911
- for (const e of prev[key] ?? []) {
912
- if (!e || typeof e.name !== 'string') continue;
913
- taken.add(e.name);
914
- const replaced = converted.has(e.name);
915
- const next = replaced ? converted.get(e.name) : e.value;
916
- out.push({ name: e.name, value: next });
917
- // 只在**值真的变了**时告警:重复运行同一转换不应刷出上万条噪声,
918
- // 而脚手架默认值被真实资源替换是值得记一笔的事。
919
- if (replaced && JSON.stringify(next) !== JSON.stringify(e.value)) {
920
- this.warnings.push(`${rel}#${e.name}: 覆盖 HarmonyOS 工程中已有条目(原值 ${JSON.stringify(e.value)})`);
921
- }
922
- }
923
- } catch (err) {
924
- this.warnings.push(`${rel}: 已有文件无法解析,按新建处理 (${(err as Error).message})`);
925
- }
926
- }
927
-
928
- for (const [name, value] of [...converted].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
929
- if (!taken.has(name)) out.push({ name, value });
930
- }
931
-
932
- if (out.length === 0) continue; // 空文件不产出
933
- this.write(rel, `${JSON.stringify({ [key]: out }, null, 2)}\n`);
934
- }
935
- }
936
- }
937
-
938
- // ── 引用就地解析(供 SVG / layered-image 使用)──
939
-
940
- /** `@color/x` → `#AARRGGBB`,跟随引用链最多 5 层。`@android:color/*` 交给系统表(三期)。 */
941
- resolveColor(raw: string, depth = 0): string | null {
942
- const v = raw.trim();
943
- if (!v) return null;
944
- const direct = normalizeColor(v);
945
- if (direct) return direct;
946
- if (depth >= 5) return null;
947
- const m = /^@(?:([a-zA-Z0-9._]+):)?color\/(.+)$/.exec(v);
948
- if (!m) return null;
949
- if (m[1] === 'android') {
950
- const sys = ANDROID_SYSTEM_COLORS[m[2]];
951
- if (sys) { this.counts.systemColorsResolved++; return sys; }
952
- this.warnings.push(`未知的 Android 系统颜色 @android:color/${m[2]},回退 #ff000000`);
953
- return '#ff000000';
954
- }
955
- const next = this.rawColors.get(m[2]);
956
- if (next !== undefined) return this.resolveColor(next, depth + 1);
957
- return null;
958
- }
959
-
960
- /**
961
- * `android:pathData` 可以是 `@string/xxx` 引用——解码后的 APK 里很常见
962
- * (AppCompat 的密码可见性动画就是这么写的)。必须解析成真实 pathData:
963
- * 把 `@string/...` 原样写进 SVG 的 `d` 会产出无法渲染的文件,而只数
964
- * clipPath 个数的存在性检查发现不了。
965
- */
966
- resolvePathData(raw: string | undefined, where: string): string | null {
967
- if (!raw) return null;
968
- const v = raw.trim();
969
- const m = /^@(?:([a-zA-Z0-9._]+):)?string\/(.+)$/.exec(v);
970
- if (!m) return v;
971
- const s = m[1] === 'android' ? undefined : this.rawStrings.get(m[2]);
972
- if (s === undefined) {
973
- this.warnings.push(`${where}: pathData 引用 ${v} 无法解析,已跳过该 path(不写入非法 d)`);
974
- return null;
975
- }
976
- return s;
977
- }
978
-
979
- /**
980
- * `fillColor="@drawable/$icon__0"`:aapt 把 vector 内联的 `<gradient>` 抽成了独立
981
- * drawable 资源,解码后落在 `res/drawable/_icon__0.xml`(`$` 写作 `_`)。
982
- * 不跟进去解析,这些路径只能回退成 `#000000`——渐变会被画成一块死黑,
983
- * 而且保真度检查器的 GRADIENT_LOST 规则只看内联 `<gradient>`,同样发现不了。
984
- */
985
- loadReferencedGradient(ref: string | undefined): XmlNode | null {
986
- if (!ref) return null;
987
- const m = /^@(?:[a-zA-Z0-9._]+:)?drawable\/(.+)$/.exec(ref.trim());
988
- if (!m) return null;
989
- // 无限定符的 `drawable/` 优先,其次任意 `drawable*` 限定符目录——
990
- // 抽出来的渐变有时只存在于 `drawable-v31/` 之类的目录里。
991
- const dirs = ['drawable', ...fs.readdirSync(this.resDir)
992
- .filter((d) => d !== 'drawable' && d.startsWith('drawable'))
993
- .sort()];
994
- for (const n of [m[1], m[1].replace(/\$/g, '_')]) {
995
- for (const d of dirs) {
996
- const p = path.join(this.resDir, d, `${n}.xml`);
997
- if (!fs.existsSync(p)) continue;
998
- try {
999
- const root = parseXml(fs.readFileSync(p, 'utf8'));
1000
- return root.name === 'gradient' ? root : null;
1001
- } catch {
1002
- return null;
1003
- }
1004
- }
1005
- }
1006
- return null;
1007
- }
1008
-
1009
- resolveDimen(raw: string, depth = 0): string | null {
1010
- const v = raw.trim();
1011
- if (!v) return null;
1012
- if (/^-?[\d.]/.test(v)) return v;
1013
- if (depth >= 5) return null;
1014
- const m = /^@(?:([a-zA-Z0-9._]+):)?dimen\/(.+)$/.exec(v);
1015
- if (m && m[1] !== 'android') {
1016
- const next = this.rawDimens.get(m[2]);
1017
- if (next !== undefined) return this.resolveDimen(next, depth + 1);
1018
- }
1019
- return null;
1020
- }
1021
-
1022
- /** 把 Android 颜色属性转成 SVG 的 paint 属性串。返回 null 表示无法解析。 */
1023
- paintAttrs(rawColor: string | undefined, kind: 'fill' | 'stroke', alphaAttr?: string): string | null {
1024
- if (rawColor === undefined) return null;
1025
- const resolved = this.resolveColor(rawColor);
1026
- if (!resolved) return null;
1027
- const p = androidColorToSvg(resolved)!;
1028
- let s = ` ${kind}="${p.color}"`;
1029
- const explicit = alphaAttr !== undefined ? parseFloat(alphaAttr) : NaN;
1030
- const alpha = Number.isFinite(explicit)
1031
- ? (p.opacity ?? 1) * explicit
1032
- : p.opacity;
1033
- if (alpha !== null && alpha < 0.999) s += ` ${kind}-opacity="${Math.round(alpha * 1000) / 1000}"`;
1034
- return s;
1035
- }
1036
-
1037
- // ── XML drawable → SVG ──
1038
-
1039
- /**
1040
- * `<vector>` → SVG。
1041
- *
1042
- * 三条容易出错、且 svg_fidelity_check.ts 会判 error 的规则在这里落实:
1043
- * 1. fill 三分支:有 fillColor 用它;无 fillColor 但有 strokeColor 必须显式 fill="none";
1044
- * 两者皆无才用平台默认黑。
1045
- * 2. clip-path 是几何而非装饰,必须保留,且被裁剪组内的每条 path 都要引用它。
1046
- * 3. `<aapt:attr name="android:fillColor">` 里的渐变与属性形式同等对待,
1047
- * 否则会退到黑色默认分支,整块变纯黑。
1048
- */
1049
- vectorToSvg(root: XmlNode, name: string): string {
1050
- const vw = svgNum(attr(root, 'viewportWidth'), 24);
1051
- const vh = svgNum(attr(root, 'viewportHeight'), 24);
1052
- const w = svgNum(attr(root, 'width'), vw);
1053
- const h = svgNum(attr(root, 'height'), vh);
1054
- const alpha = attr(root, 'alpha');
1055
-
1056
- const defs: string[] = [];
1057
- const body: string[] = [];
1058
- let clipSeq = 0;
1059
- let gradSeq = 0;
1060
-
1061
- const emitGradient = (g: XmlNode): string | null => {
1062
- const id = `${name}_grad_${++gradSeq}`;
1063
- const type = attr(g, 'type') ?? 'linear';
1064
- const stops: string[] = [];
1065
- const items = g.children.filter((c) => c.name === 'item');
1066
- if (items.length > 0) {
1067
- for (const it of items) {
1068
- const col = this.resolveColor(attr(it, 'color') ?? '');
1069
- if (!col) continue;
1070
- const p = androidColorToSvg(col)!;
1071
- const off = svgNum(attr(it, 'offset'), 0) * 100;
1072
- stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1073
- }
1074
- } else {
1075
- const seq: Array<[string | undefined, number]> = [
1076
- [attr(g, 'startColor'), 0], [attr(g, 'centerColor'), 50], [attr(g, 'endColor'), 100],
1077
- ];
1078
- for (const [c, off] of seq) {
1079
- if (c === undefined) continue;
1080
- const col = this.resolveColor(c);
1081
- if (!col) continue;
1082
- const p = androidColorToSvg(col)!;
1083
- stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1084
- }
1085
- }
1086
- if (stops.length === 0) return null;
1087
-
1088
- if (type === 'radial') {
1089
- const cx = svgNum(attr(g, 'centerX'), 0.5) * 100;
1090
- const cy = svgNum(attr(g, 'centerY'), 0.5) * 100;
1091
- defs.push(`<radialGradient id="${id}" cx="${cx}%" cy="${cy}%" r="50%">${stops.join('')}</radialGradient>`);
1092
- } else {
1093
- // sweep 在 SVG 1.1 无原生等价物,按 linear 近似并告警
1094
- if (type === 'sweep') {
1095
- this.warnings.push(`${name}: sweep gradient 无 SVG 1.1 等价物,已用 linearGradient 近似`);
1096
- }
1097
- const ang = svgNum(attr(g, 'angle'), 0);
1098
- const rad = (ang * Math.PI) / 180;
1099
- const x1 = Math.round(50 + 50 * Math.cos(rad + Math.PI));
1100
- const y1 = Math.round(50 - 50 * Math.sin(rad + Math.PI));
1101
- const x2 = Math.round(50 + 50 * Math.cos(rad));
1102
- const y2 = Math.round(50 - 50 * Math.sin(rad));
1103
- defs.push(`<linearGradient id="${id}" x1="${x1}%" y1="${y1}%" x2="${x2}%" y2="${y2}%">${stops.join('')}</linearGradient>`);
1104
- }
1105
- return id;
1106
- };
1107
-
1108
- const emitPath = (p: XmlNode, clipRef: string | null, indent: string): void => {
1109
- const d = this.resolvePathData(attr(p, 'pathData'), name);
1110
- if (!d) return;
1111
- let a = '';
1112
-
1113
- // 渐变优先于属性色:aapt:attr 是子元素形式的 fillColor
1114
- let gradId: string | null = null;
1115
- for (const child of p.children) {
1116
- if (child.name !== 'aapt:attr' && !child.name.endsWith(':attr')) continue;
1117
- if ((attr(child, 'name') ?? '').endsWith('fillColor')) {
1118
- const g = child.children.find((c) => c.name === 'gradient');
1119
- if (g) gradId = emitGradient(g);
1120
- }
1121
- }
1122
- // 编译过的 APK 里,同样的内联渐变被 aapt 抽成了独立 drawable,
1123
- // 只在属性里留下 `@drawable/$icon__0` 这样的引用。不跟进去解析就会回退成黑色。
1124
- if (!gradId) {
1125
- const g = this.loadReferencedGradient(attr(p, 'fillColor'));
1126
- if (g) gradId = emitGradient(g);
1127
- }
1128
-
1129
- const fillColor = attr(p, 'fillColor');
1130
- const strokeColor = attr(p, 'strokeColor');
1131
- if (gradId) {
1132
- a += ` fill="url(#${gradId})"`;
1133
- } else {
1134
- const fill = this.paintAttrs(fillColor, 'fill', attr(p, 'fillAlpha'));
1135
- if (fill) a += fill;
1136
- else if (fillColor !== undefined) {
1137
- // 有 fillColor 属性但解析不出(多为被裁掉的库资源)。按规则用默认值,
1138
- // 但必须记录——否则渲染成黑色而无人知道原因。
1139
- this.warnings.push(`${name}: fillColor ${fillColor} 无法解析,回退 #000000`);
1140
- this.counts.unresolvedPaint++;
1141
- a += ' fill="#000000"';
1142
- }
1143
- else if (strokeColor !== undefined) a += ' fill="none"'; // 描边专用路径:必须显式 none
1144
- else a += ' fill="#000000"'; // 两者皆无:平台默认
1145
- }
1146
-
1147
- const stroke = this.paintAttrs(strokeColor, 'stroke', attr(p, 'strokeAlpha'));
1148
- if (stroke) {
1149
- a += stroke;
1150
- const sw = attr(p, 'strokeWidth');
1151
- if (sw) a += ` stroke-width="${svgNum(sw, 1)}"`;
1152
- // 解码后的 APK 里这些枚举是数字,直接写会得到非法的 stroke-linecap="2"
1153
- const cap = attr(p, 'strokeLineCap');
1154
- if (cap) a += ` stroke-linecap="${/^\d+$/.test(cap) ? STROKE_LINECAP[+cap] ?? 'butt' : cap}"`;
1155
- const join = attr(p, 'strokeLineJoin');
1156
- if (join) a += ` stroke-linejoin="${/^\d+$/.test(join) ? STROKE_LINEJOIN[+join] ?? 'miter' : join}"`;
1157
- const miter = attr(p, 'strokeMiterLimit');
1158
- if (miter) a += ` stroke-miterlimit="${svgNum(miter, 4)}"`;
1159
- }
1160
-
1161
- const ft = attr(p, 'fillType');
1162
- if (ft !== undefined && (ft.toLowerCase() === 'evenodd' || ft === '1')) a += ' fill-rule="evenodd"';
1163
-
1164
- // trimPath* 无 SVG 静态等价物;trimPathEnd=0 表示这条描边被完全裁掉(不可见)
1165
- const trimEnd = attr(p, 'trimPathEnd');
1166
- if (trimEnd !== undefined && parseFloat(trimEnd) === 0) {
1167
- this.warnings.push(`${name}: path 的 trimPathEnd=0(Android 侧初始不可见),SVG 无等价物,已按可见输出`);
1168
- }
1169
- if (clipRef) a += ` clip-path="url(#${clipRef})"`;
1170
- body.push(`${indent}<path d="${esc(d)}"${a}/>`);
1171
- };
1172
-
1173
- const walk = (node: XmlNode, inheritedClip: string | null, indent: string): void => {
1174
- // 本层的 clip-path 先登记,供同层及子层的 path 引用
1175
- let clipRef = inheritedClip;
1176
- for (const c of node.children) {
1177
- if (c.name !== 'clip-path') continue;
1178
- const d = this.resolvePathData(attr(c, 'pathData'), name);
1179
- if (!d) continue;
1180
- const id = attr(c, 'name') ? `${name}_${attr(c, 'name')}` : `${name}_clip_${++clipSeq}`;
1181
- defs.push(`<clipPath id="${id}"><path d="${esc(d)}"/></clipPath>`);
1182
- clipRef = id;
1183
- }
1184
-
1185
- for (const c of node.children) {
1186
- if (c.name === 'path') emitPath(c, clipRef, indent);
1187
- else if (c.name === 'group') {
1188
- const tx = svgNum(attr(c, 'translateX'), 0);
1189
- const ty = svgNum(attr(c, 'translateY'), 0);
1190
- const sx = svgNum(attr(c, 'scaleX'), 1);
1191
- const sy = svgNum(attr(c, 'scaleY'), 1);
1192
- const rot = svgNum(attr(c, 'rotation'), 0);
1193
- const px = svgNum(attr(c, 'pivotX'), 0);
1194
- const py = svgNum(attr(c, 'pivotY'), 0);
1195
- const parts: string[] = [];
1196
- if (tx !== 0 || ty !== 0) parts.push(`translate(${tx},${ty})`);
1197
- if (sx !== 1 || sy !== 1) parts.push(`scale(${sx},${sy})`);
1198
- if (rot !== 0) parts.push(`rotate(${rot},${px},${py})`);
1199
- const t = parts.length > 0 ? ` transform="${parts.join(' ')}"` : '';
1200
- body.push(`${indent}<g${t}>`);
1201
- walk(c, clipRef, `${indent} `);
1202
- body.push(`${indent}</g>`);
1203
- }
1204
- }
1205
- };
1206
-
1207
- walk(root, null, ' ');
1208
-
1209
- const tint = attr(root, 'tint');
1210
- if (tint) this.warnings.push(`${name}: android:tint 无 SVG 直接等价物,已忽略(需在 ArkUI 侧用 fillColor 着色)`);
1211
-
1212
- const op = alpha && parseFloat(alpha) < 0.999 ? ` opacity="${parseFloat(alpha)}"` : '';
1213
- const defsBlock = defs.length > 0 ? ` <defs>${defs.join('')}</defs>\n` : '';
1214
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${vw} ${vh}"${op}>\n${defsBlock}${body.join('\n')}\n</svg>\n`;
1215
- }
1216
-
1217
- /** `<shape>` → SVG。矩形 / 椭圆 / 线 / 环。 */
1218
- shapeToSvg(root: XmlNode, name: string): string {
1219
- const shape = (attr(root, 'shape') ?? 'rectangle').toLowerCase();
1220
- const size = root.children.find((c) => c.name === 'size');
1221
- const w = svgNum(size ? attr(size, 'width') : undefined, 24);
1222
- const h = svgNum(size ? attr(size, 'height') : undefined, 24);
1223
- if (!size) this.warnings.push(`${name}: <shape> 无 <size>,按 24x24 默认画布输出`);
1224
-
1225
- const solid = root.children.find((c) => c.name === 'solid');
1226
- const strokeEl = root.children.find((c) => c.name === 'stroke');
1227
- const corners = root.children.find((c) => c.name === 'corners');
1228
- const gradEl = root.children.find((c) => c.name === 'gradient');
1229
-
1230
- const defs: string[] = [];
1231
- let fillAttr = ' fill="none"';
1232
- if (gradEl) {
1233
- const id = `${name}_grad`;
1234
- const stops: string[] = [];
1235
- for (const [c, off] of [[attr(gradEl, 'startColor'), 0], [attr(gradEl, 'centerColor'), 50], [attr(gradEl, 'endColor'), 100]] as Array<[string | undefined, number]>) {
1236
- if (c === undefined) continue;
1237
- const col = this.resolveColor(c);
1238
- if (!col) continue;
1239
- const p = androidColorToSvg(col)!;
1240
- stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1241
- }
1242
- if (stops.length > 0) {
1243
- const ang = svgNum(attr(gradEl, 'angle'), 0);
1244
- const rad = (ang * Math.PI) / 180;
1245
- defs.push(`<linearGradient id="${id}" x1="${Math.round(50 + 50 * Math.cos(rad + Math.PI))}%" y1="${Math.round(50 - 50 * Math.sin(rad + Math.PI))}%" x2="${Math.round(50 + 50 * Math.cos(rad))}%" y2="${Math.round(50 - 50 * Math.sin(rad))}%">${stops.join('')}</linearGradient>`);
1246
- fillAttr = ` fill="url(#${id})"`;
1247
- }
1248
- } else if (solid) {
1249
- fillAttr = this.paintAttrs(attr(solid, 'color'), 'fill') ?? ' fill="none"';
1250
- }
1251
-
1252
- let strokeAttr = '';
1253
- let strokeW = 0;
1254
- if (strokeEl) {
1255
- const s = this.paintAttrs(attr(strokeEl, 'color'), 'stroke');
1256
- if (s) {
1257
- strokeW = svgNum(attr(strokeEl, 'width'), 1);
1258
- strokeAttr = `${s} stroke-width="${strokeW}"`;
1259
- const dw = attr(strokeEl, 'dashWidth');
1260
- const dg = attr(strokeEl, 'dashGap');
1261
- if (dw && dg) strokeAttr += ` stroke-dasharray="${svgNum(dw, 0)},${svgNum(dg, 0)}"`;
1262
- }
1263
- }
1264
-
1265
- let el: string;
1266
- if (shape === 'oval') {
1267
- el = w === h
1268
- ? `<circle cx="${w / 2}" cy="${h / 2}" r="${w / 2}"${fillAttr}${strokeAttr}/>`
1269
- : `<ellipse cx="${w / 2}" cy="${h / 2}" rx="${w / 2}" ry="${h / 2}"${fillAttr}${strokeAttr}/>`;
1270
- } else if (shape === 'line') {
1271
- el = `<line x1="0" y1="${h / 2}" x2="${w}" y2="${h / 2}"${strokeAttr || ' stroke="#000000" stroke-width="1"'}/>`;
1272
- } else if (shape === 'ring') {
1273
- const innerR = attr(root, 'innerRadius')
1274
- ? svgNum(attr(root, 'innerRadius'), 0)
1275
- : w / (2 * svgNum(attr(root, 'innerRadiusRatio'), 3));
1276
- const thickness = attr(root, 'thickness')
1277
- ? svgNum(attr(root, 'thickness'), 0)
1278
- : w / (2 * svgNum(attr(root, 'thicknessRatio'), 9));
1279
- const ringPaint = solid ? (this.paintAttrs(attr(solid, 'color'), 'stroke') ?? ' stroke="#000000"') : ' stroke="#000000"';
1280
- el = `<circle cx="${w / 2}" cy="${h / 2}" r="${innerR + thickness / 2}" fill="none"${ringPaint} stroke-width="${thickness}"/>`;
1281
- } else {
1282
- const r = corners ? svgNum(attr(corners, 'radius'), 0) : 0;
1283
- const rr = r > 0 ? ` rx="${r}" ry="${r}"` : '';
1284
- const inset = strokeW / 2;
1285
- el = `<rect x="${inset}" y="${inset}" width="${w - strokeW}" height="${h - strokeW}"${rr}${fillAttr}${strokeAttr}/>`;
1286
- }
1287
-
1288
- const defsBlock = defs.length > 0 ? ` <defs>${defs.join('')}</defs>\n` : '';
1289
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">\n${defsBlock} ${el}\n</svg>\n`;
1290
- }
1291
-
1292
- /**
1293
- * `<layer-list>` → 单个 SVG,`<item>` 按文档序自下而上叠放,inset 折算为坐标偏移。
1294
- *
1295
- * 画布尺寸必须从内容推导,不能写死:layer-list 里常内嵌一个带 viewport 的
1296
- * `<vector>`,写死 100x100 会让整个图标相对源素材被缩放(保真检查报
1297
- * VIEWBOX_MISMATCH)。取所有内层元素中最大的固有尺寸;都没有才退到 100x100。
1298
- */
1299
- layerListToSvg(root: XmlNode, name: string): string {
1300
- const items = root.children.filter((c) => c.name === 'item');
1301
-
1302
- let W = 0;
1303
- let H = 0;
1304
- for (const item of items) {
1305
- for (const inner of item.children) {
1306
- if (inner.name === 'vector') {
1307
- W = Math.max(W, svgNum(attr(inner, 'viewportWidth'), 0));
1308
- H = Math.max(H, svgNum(attr(inner, 'viewportHeight'), 0));
1309
- } else if (inner.name === 'shape') {
1310
- const size = inner.children.find((c) => c.name === 'size');
1311
- if (size) {
1312
- W = Math.max(W, svgNum(attr(size, 'width'), 0));
1313
- H = Math.max(H, svgNum(attr(size, 'height'), 0));
1314
- }
1315
- }
1316
- }
1317
- }
1318
- const derived = W > 0 && H > 0;
1319
- if (!derived) {
1320
- W = 100; H = 100;
1321
- this.warnings.push(`${name}: layer-list 内层无固有尺寸,按 100x100 默认画布输出`);
1322
- }
1323
-
1324
- const layers: string[] = [];
1325
- for (const item of items) {
1326
- const l = svgNum(attr(item, 'left'), 0);
1327
- const t = svgNum(attr(item, 'top'), 0);
1328
- const r = svgNum(attr(item, 'right'), 0);
1329
- const b = svgNum(attr(item, 'bottom'), 0);
1330
-
1331
- // `<color>` item:整块底色,直接铺满画布
1332
- const colorEl = item.children.find((c) => c.name === 'color');
1333
- if (colorEl) {
1334
- const paint = this.paintAttrs(attr(colorEl, 'color'), 'fill');
1335
- if (paint) layers.push(` <rect x="0" y="0" width="${W}" height="${H}"${paint}/>`);
1336
- else this.warnings.push(`${name}: layer-list 的 <color> item 颜色 ${attr(colorEl, 'color')} 无法解析,该层已跳过`);
1337
- continue;
1338
- }
1339
-
1340
- const inner = item.children.find((c) => c.name === 'shape' || c.name === 'vector');
1341
- if (!inner) {
1342
- const ref = attr(item, 'drawable');
1343
- this.warnings.push(`${name}: layer-list 的 item 引用 ${ref ?? '(未知)'},未内联`);
1344
- continue;
1345
- }
1346
- const sub = inner.name === 'shape'
1347
- ? this.shapeToSvg(inner, `${name}_layer${layers.length}`)
1348
- : this.vectorToSvg(inner, `${name}_layer${layers.length}`);
1349
- const innerBody = sub.replace(/^<svg[^>]*>\n?/, '').replace(/<\/svg>\n?$/, '').trim();
1350
-
1351
- // 内层自身的坐标系尺寸,用于把 inset 折算成 scale
1352
- const iw = inner.name === 'vector' ? svgNum(attr(inner, 'viewportWidth'), W) : W;
1353
- const ih = inner.name === 'vector' ? svgNum(attr(inner, 'viewportHeight'), H) : H;
1354
- const sw = W - l - r;
1355
- const sh = H - t - b;
1356
- const parts: string[] = [];
1357
- if (l !== 0 || t !== 0) parts.push(`translate(${l},${t})`);
1358
- if (sw !== iw || sh !== ih) {
1359
- parts.push(`scale(${Math.round((sw / iw) * 10000) / 10000},${Math.round((sh / ih) * 10000) / 10000})`);
1360
- }
1361
- layers.push(parts.length > 0
1362
- ? ` <g transform="${parts.join(' ')}">\n ${innerBody}\n </g>`
1363
- : ` ${innerBody}`);
1364
- }
1365
-
1366
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">\n${layers.join('\n')}\n</svg>\n`;
1367
- }
1368
-
1369
- /** `<selector>` → 默认态 SVG。默认态 = 无 state_* 属性的 item,否则取最后一项。 */
1370
- selectorDefault(root: XmlNode): XmlNode | null {
1371
- const items = root.children.filter((c) => c.name === 'item');
1372
- if (items.length === 0) return null;
1373
- const noState = items.find((it) => !Object.keys(it.attrs).some((k) => k.includes('state_')));
1374
- return noState ?? items[items.length - 1];
1375
- }
1376
-
1377
- /** 分发:读根元素决定转换方式。返回 null 表示不可映射。 */
1378
- xmlDrawableToSvg(root: XmlNode, name: string): { svg: string; kind: string; notes: string } | null {
1379
- switch (root.name) {
1380
- case 'vector':
1381
- return { svg: this.vectorToSvg(root, name), kind: 'svg conversion', notes: '' };
1382
- case 'shape':
1383
- return { svg: this.shapeToSvg(root, name), kind: 'svg conversion', notes: '' };
1384
- case 'layer-list':
1385
- return { svg: this.layerListToSvg(root, name), kind: 'svg conversion', notes: 'layer-list flattened into stacked SVG groups' };
1386
- case 'selector': {
1387
- const def = this.selectorDefault(root);
1388
- if (!def) return null;
1389
- const states = root.children
1390
- .filter((c) => c.name === 'item')
1391
- .flatMap((it) => Object.keys(it.attrs).filter((k) => k.includes('state_')).map((k) => k.split(':').pop()!));
1392
- const notes = `state variants dropped (${[...new Set(states)].join(', ') || 'none'}); implement state handling in ArkUI component code`;
1393
- const inner = def.children.find((c) => c.name === 'shape' || c.name === 'vector');
1394
- if (inner) {
1395
- const out = this.xmlDrawableToSvg(inner, name);
1396
- return out ? { ...out, notes } : null;
1397
- }
1398
- const ref = attr(def, 'drawable');
1399
- this.warnings.push(`${name}: selector 默认项引用 ${ref ?? '(未知)'},未内联`);
1400
- return null;
1401
- }
1402
- case 'inset': {
1403
- const inner = root.children.find((c) => c.name === 'shape' || c.name === 'vector' || c.name === 'selector');
1404
- if (!inner) return null;
1405
- const out = this.xmlDrawableToSvg(inner, name);
1406
- return out ? { ...out, notes: 'inset wrapper flattened; inner drawable converted' } : null;
1407
- }
1408
- default:
1409
- return null;
1410
- }
1411
- }
1412
-
1413
- /** `<adaptive-icon>` → layered-image JSON(+ 必要时生成纯色背景 PNG)。 */
1414
- adaptiveIcon(root: XmlNode, name: string, qdir: string, androidPath: string): void {
1415
- const out: Record<string, string> = {};
1416
- const sourceCategory = this.sourceCategory(name);
1417
- const extraTargets: Array<{ target: string; kind: string; notes: string }> = [];
1418
-
1419
- for (const layer of ['background', 'foreground'] as const) {
1420
- const el = root.children.find((c) => c.name === layer);
1421
- if (!el) continue;
1422
- const ref = attr(el, 'drawable') ?? attr(el, 'color');
1423
- if (!ref) {
1424
- // 该层没有 android:drawable / android:color,而是内联了一个子 drawable
1425
- // (`<foreground><vector …/></foreground>`,快捷方式图标常见写法)。
1426
- // HarmonyOS layered-image 只接受 $media:,所以把内联图形单独落成一个媒体文件再引用它。
1427
- // 早期实现在这里直接 continue,整层图形被静默丢弃,且不留任何记录。
1428
- this.inlineAdaptiveLayer(el, layer, name, qdir, androidPath, sourceCategory, out, extraTargets);
1429
- continue;
1430
- }
1431
-
1432
- const media = /^@(?:[a-zA-Z0-9._]+:)?(?:drawable|mipmap)\/(.+)$/.exec(ref);
1433
- if (media) { out[layer] = `$media:${media[1]}`; continue; }
1434
-
1435
- const colorRef = /^@(?:[a-zA-Z0-9._]+:)?color\/(.+)$/.exec(ref);
1436
- const literal = normalizeColor(ref);
1437
- if (colorRef || literal) {
1438
- const colorName = colorRef ? colorRef[1] : `${name}_${layer}`;
1439
- const hex = literal ?? this.resolveColor(ref);
1440
- if (!hex) {
1441
- this.warnings.push(`${androidPath}: layered-image 的 ${layer} 颜色 ${ref} 无法解析,使用占位引用`);
1442
- out[layer] = `$media:${colorName}_bg`;
1443
- continue;
1444
- }
1445
- const png = `${colorName}_bg.png`;
1446
- if (!this.generatedPngs.has(png)) {
1447
- this.write(path.join(qdir, 'media', png), solidPng(hex));
1448
- this.generatedPngs.add(png);
1449
- extraTargets.push({
1450
- target: `resources/${qdir}/media/${png}`,
1451
- kind: 'generated media',
1452
- notes: 'solid-color PNG generated because layered-image accepts only $media references',
1453
- });
1454
- }
1455
- out[layer] = `$media:${colorName}_bg`;
1456
- continue;
1457
- }
1458
- this.warnings.push(`${androidPath}: layered-image 的 ${layer} 引用 ${ref} 无法识别`);
1459
- }
1460
-
1461
- // monochrome 不进 JSON,但它引用的 drawable 仍是真实资源,按普通 drawable 处理
1462
- const mono = root.children.find((c) => c.name === 'monochrome');
1463
- if (mono) {
1464
- this.warnings.push(`${androidPath}: monochrome 层无 HarmonyOS layered-image 等价物,已从 JSON 省略(其引用的 drawable 仍按普通资源转换)`);
1465
- }
1466
-
1467
- const jsonName = `${name}_layered_image.json`;
1468
- this.write(path.join(qdir, 'media', jsonName), `${JSON.stringify({ 'layered-image': out }, null, 2)}\n`);
1469
- this.counts.layeredImages++;
1470
-
1471
- this.inv({
1472
- androidResourcePath: androidPath, androidResourceName: name,
1473
- function: 'Adaptive launcher icon', screens: 'Launcher', sourceCategory,
1474
- typeCategory: 'mipmap', status: 'converted',
1475
- });
1476
- this.map({
1477
- androidResourcePath: androidPath, androidScreens: 'Launcher',
1478
- androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1479
- harmonyTarget: `resources/${qdir}/media/${jsonName}`, mappingKind: 'layered-image conversion',
1480
- });
1481
- for (const t of extraTargets) {
1482
- this.map({
1483
- androidResourcePath: androidPath, androidScreens: 'Launcher',
1484
- androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1485
- harmonyTarget: t.target, mappingKind: t.kind, notes: t.notes,
1486
- });
1487
- }
1488
- }
1489
-
1490
- /**
1491
- * `<adaptive-icon>` 某一层内联了子 drawable(没有 `android:drawable` / `android:color`)时的处理。
1492
- * 把内联图形单独转成一个媒体文件,再用 `$media:` 引用它——这是 layered-image 唯一接受的形式。
1493
- * 转不出来的情况登记为 unmappable,绝不静默丢层。
1494
- */
1495
- inlineAdaptiveLayer(
1496
- el: XmlNode,
1497
- layer: 'background' | 'foreground',
1498
- name: string,
1499
- qdir: string,
1500
- androidPath: string,
1501
- sourceCategory: string,
1502
- out: Record<string, string>,
1503
- extraTargets: Array<{ target: string; kind: string; notes: string }>,
1504
- ): void {
1505
- const child = el.children.find((c) => c.name);
1506
- if (!child) {
1507
- this.warnings.push(`${androidPath}: layered-image 的 ${layer} 层既无 drawable/color 属性也无内联子元素,已省略该层`);
1508
- return;
1509
- }
1510
-
1511
- // `<bitmap android:src="@drawable/x"/>` 只是个引用包装,直接引用目标即可。
1512
- if (child.name === 'bitmap') {
1513
- const src = attr(child, 'src');
1514
- const m = src ? /^@(?:[a-zA-Z0-9._]+:)?(?:drawable|mipmap)\/(.+)$/.exec(src) : null;
1515
- if (m) { out[layer] = `$media:${m[1]}`; return; }
1516
- }
1517
-
1518
- const inlineName = `${name}_${layer}`;
1519
- const conv = this.xmlDrawableToSvg(child, inlineName);
1520
- if (!conv) {
1521
- this.counts.unmappable++;
1522
- this.warnings.push(`${androidPath}: layered-image 的 ${layer} 层内联 <${child.name}> 无静态 SVG 等价物,该层未产出媒体文件`);
1523
- this.map({
1524
- androidResourcePath: `${androidPath}#${layer}`, androidScreens: 'Launcher',
1525
- androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1526
- harmonyTarget: 'N/A', mappingKind: 'unmappable',
1527
- notes: `inline <${child.name}> in <${layer}> has no static SVG equivalent`,
1528
- });
1529
- return;
1530
- }
1531
-
1532
- this.write(path.join(qdir, 'media', `${inlineName}.svg`), conv.svg);
1533
- this.counts.svgConverted++;
1534
- out[layer] = `$media:${inlineName}`;
1535
- extraTargets.push({
1536
- target: `resources/${qdir}/media/${inlineName}.svg`,
1537
- kind: conv.kind,
1538
- notes: `inline <${child.name}> in <${layer}> extracted to its own media file; layered-image accepts only $media references${conv.notes ? `; ${conv.notes}` : ''}`,
1539
- });
1540
- }
1541
-
1542
- // ── 文件类资源 ──
1543
-
1544
- processFileResource(relFile: string, type: string, qdir: string): void {
1545
- const base = path.basename(relFile);
1546
- const ext = path.extname(base).toLowerCase();
1547
- const androidPath = `res/${relFile}`;
1548
- const resName = base.replace(/\.9\.png$/i, '').replace(/\.[^.]+$/, '');
1549
- const sourceCategory = this.sourceCategory(resName);
1550
-
1551
- const record = (target: string, kind: string, status: string, notes = '', fn = ''): void => {
1552
- this.inv({
1553
- androidResourcePath: androidPath, androidResourceName: resName,
1554
- function: fn || `${type} resource`, sourceCategory, typeCategory: type,
1555
- status, notes,
1556
- });
1557
- this.map({
1558
- androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
1559
- androidTypeCategory: type, harmonyTarget: target, mappingKind: kind, notes,
1560
- });
1561
- };
1562
-
1563
- if (type === 'font') {
1564
- if (FONT_EXT.has(ext)) {
1565
- const target = path.join('rawfile', 'fonts', base);
1566
- this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1567
- this.counts.fontCopied++;
1568
- record(`resources/${target.split(path.sep).join('/')}`, 'direct copy', 'converted', '', 'Font resource');
1569
- } else {
1570
- this.counts.unmappable++;
1571
- record('N/A', 'unmappable', 'unmappable', 'font family XML has no HarmonyOS equivalent', 'Font family definition');
1572
- }
1573
- return;
1574
- }
1575
-
1576
- if (type === 'raw') {
1577
- const target = path.join('rawfile', base);
1578
- this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1579
- this.counts.rawCopied++;
1580
- record(`resources/rawfile/${base}`, 'direct copy', 'converted', '', 'Raw file resource');
1581
- return;
1582
- }
1583
-
1584
- if (type === 'xml') {
1585
- const target = path.join(qdir, 'profile', base);
1586
- this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1587
- this.counts.profileCopied++;
1588
- record(`resources/${qdir}/profile/${base}`, 'direct copy', 'converted', '', 'Configuration XML');
1589
- return;
1590
- }
1591
-
1592
- // drawable / mipmap
1593
- if (/\.9\.png$/i.test(base)) {
1594
- const renamed = base.replace(/\.9\.png$/i, '_9.png');
1595
- const target = path.join(qdir, 'media', renamed);
1596
- if (!this.claimTarget(target, relFile, androidPath, type)) return;
1597
- this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1598
- this.counts.ninePatchRenamed++;
1599
- this.counts.mediaCopied++;
1600
- record(
1601
- `resources/${qdir}/media/${renamed}`, 'rename', 'converted',
1602
- 'nine-patch stretch behavior is lost; reimplement with a resizable Image in ArkUI',
1603
- 'Nine-patch image',
1604
- );
1605
- return;
1606
- }
1607
-
1608
- if (IMAGE_EXT.has(ext)) {
1609
- const target = path.join(qdir, 'media', base);
1610
- if (!this.claimTarget(target, relFile, androidPath, type)) return;
1611
- this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1612
- this.counts.mediaCopied++;
1613
- record(`resources/${qdir}/media/${base}`, 'direct copy', 'converted', '', 'Image resource');
1614
- return;
1615
- }
1616
-
1617
- if (ext === '.xml') {
1618
- const root = parseXml(fs.readFileSync(path.join(this.resDir, relFile), 'utf8'));
1619
-
1620
- if (root.name === 'adaptive-icon') {
1621
- this.adaptiveIcon(root, resName, qdir, androidPath);
1622
- return;
1623
- }
1624
-
1625
- const out = this.xmlDrawableToSvg(root, resName);
1626
- if (!out) {
1627
- this.counts.unmappable++;
1628
- record(
1629
- 'N/A', 'unmappable', 'unmappable',
1630
- `<${root.name}> has no static SVG equivalent (runtime behavior)`,
1631
- `${root.name} drawable`,
1632
- );
1633
- return;
1634
- }
1635
-
1636
- const target = path.join(qdir, 'media', `${resName}.svg`);
1637
- if (!this.claimTarget(target, relFile, androidPath, type)) return;
1638
- this.write(target, out.svg);
1639
- this.counts.svgConverted++;
1640
- record(`resources/${qdir}/media/${resName}.svg`, out.kind, 'converted', out.notes, `${root.name} drawable`);
1641
- return;
1642
- }
1643
-
1644
- this.counts.unmappable++;
1645
- record('N/A', 'unmappable', 'unmappable', `unhandled extension: ${ext}`);
1646
- }
1647
-
1648
- // ── 目录遍历 ──
1649
-
1650
- run(): void {
1651
- const dirs = fs.readdirSync(this.resDir, { withFileTypes: true })
1652
- .filter((d) => d.isDirectory())
1653
- .map((d) => d.name)
1654
- .sort();
1655
-
1656
- // 第一遍只处理 values:SVG 转换需要 color / dimen 查找表就位。
1657
- // 目录名字典序会让 drawable 排在 values 前面,所以必须分两遍。
1658
- for (const dirName of dirs) {
1659
- const { type, plan } = planQualifiers(dirName);
1660
- if (type !== 'values' || plan.skip) continue;
1661
- for (const f of fs.readdirSync(path.join(this.resDir, dirName)).sort()) {
1662
- if (!f.endsWith('.xml')) continue;
1663
- this.qualifierUse.push({ android: dirName, harmony: `${plan.dir}/element` });
1664
- this.processValuesFile(`${dirName}/${f}`, plan.dir);
1665
- }
1666
- }
1667
-
1668
- for (const dirName of dirs) {
1669
- const { type, plan } = planQualifiers(dirName);
1670
- const files = fs.readdirSync(path.join(this.resDir, dirName)).sort();
1671
-
1672
- if (plan.skip) {
1673
- this.counts.skippedQualifierDirs++;
1674
- for (const f of files) {
1675
- this.counts.unmappable++;
1676
- this.inv({
1677
- androidResourcePath: `res/${dirName}/${f}`, androidResourceName: f.replace(/\.[^.]+$/, ''),
1678
- function: `${type} resource`, sourceCategory: this.sourceCategory(f),
1679
- typeCategory: type, status: 'unmapped', notes: plan.skip,
1680
- });
1681
- this.map({
1682
- androidResourcePath: `res/${dirName}/${f}`, androidTypeCategory: type,
1683
- androidSourceCategory: this.sourceCategory(f),
1684
- mappingKind: 'unmappable', notes: plan.skip,
1685
- });
1686
- }
1687
- continue;
1688
- }
1689
-
1690
- if (type === 'values') continue; // 已在第一遍处理
1691
-
1692
- if (UNMAPPABLE_TYPES.has(type)) {
1693
- for (const f of files) {
1694
- this.counts.unmappable++;
1695
- const name = f.replace(/\.[^.]+$/, '');
1696
- this.inv({
1697
- androidResourcePath: `res/${dirName}/${f}`, androidResourceName: name,
1698
- function: `${type} resource`, sourceCategory: this.sourceCategory(name),
1699
- typeCategory: type, status: 'unmappable',
1700
- notes: `Android ${type} has no HarmonyOS equivalent (ArkUI is declarative)`,
1701
- });
1702
- this.map({
1703
- androidResourcePath: `res/${dirName}/${f}`, androidTypeCategory: type,
1704
- androidSourceCategory: this.sourceCategory(name), mappingKind: 'unmappable',
1705
- notes: `Android ${type} has no HarmonyOS equivalent`,
1706
- });
1707
- }
1708
- continue;
1709
- }
1710
-
1711
- for (const f of files) {
1712
- this.qualifierUse.push({ android: dirName, harmony: `${plan.dir}/media` });
1713
- this.processFileResource(`${dirName}/${f}`, type, plan.dir);
1714
- }
1715
- }
1716
-
1717
- this.resolveReferences();
1718
- this.flushElements();
1719
- }
1720
- }
1721
-
1722
- // ─────────────────────────────────────────────
1723
- // Markdown 生成
1724
- // ─────────────────────────────────────────────
1725
-
1726
- /** markdown 表格单元格转义:`|` 会断表,换行会断行。 */
1727
- function cell(v: string): string {
1728
- return (v ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').trim() || ' ';
1729
- }
1730
-
1731
- interface DocContext {
1732
- apkPath: string;
1733
- resSource: string;
1734
- resDir: string;
1735
- harmonyDir: string;
1736
- appModule: string;
1737
- androidCommit: string;
1738
- iconSnapshotRef: string;
1739
- buildResult: string;
1740
- /** code_vector_icons.ts 的 --json 产物(可选) */
1741
- icons: {
1742
- counts?: Record<string, number>;
1743
- icons?: Array<Record<string, unknown>>;
1744
- ref?: string;
1745
- /** dex 引用绝大多数无源码出处 ⇒ material-icons-extended 整包未被 R8 收缩 */
1746
- libraryLikelyUnshrunk?: boolean;
1747
- } | null;
1748
- /** svg_fidelity_check.ts 的 --json 产物(可选) */
1749
- fidelity: { findings?: Array<Record<string, string>>; counts?: Record<string, number> } | null;
1750
- }
1751
-
1752
- /** 文档生成所需的全部数据。Converter 结构上即满足,records JSON 也能反序列化成它。 */
1753
- interface RecordsBundle {
1754
- counts: Record<string, number>;
1755
- warnings: string[];
1756
- conflicts: string[];
1757
- resolutions: ResolutionRecord[];
1758
- inventory: InventoryRecord[];
1759
- mappings: MappingRecord[];
1760
- qualifierUse: Array<{ android: string; harmony: string }>;
1761
- }
1762
-
1763
- class DocWriter {
1764
- conv: RecordsBundle;
1765
- ctx: DocContext;
1766
-
1767
- constructor(conv: RecordsBundle, ctx: DocContext) {
1768
- this.conv = conv;
1769
- this.ctx = ctx;
1770
- }
1771
-
1772
- private counts(): Record<string, number> {
1773
- return this.conv.counts;
1774
- }
1775
-
1776
- /** 按某个字段聚合计数,用于报告里的概览表。 */
1777
- private groupBy<T>(rows: T[], key: (r: T) => string): Array<[string, number]> {
1778
- const m = new Map<string, number>();
1779
- for (const r of rows) m.set(key(r), (m.get(r ? key(r) : '') ?? 0) + 1);
1780
- return [...m].sort((a, b) => b[1] - a[1]);
1781
- }
1782
-
1783
- /**
1784
- * 转换报告:面向人阅读,因此用**聚合**表格,不逐条罗列 10 万级资源。
1785
- * 逐条审计由 resource_mapping 文档承担(那份有「绝不省略」的硬要求)。
1786
- */
1787
- report(): string {
1788
- const c = this.counts();
1789
- const o: string[] = [];
1790
- const p = (s = ''): void => { o.push(s); };
1791
-
1792
- p('# Android to HarmonyOS Resource Conversion Report');
1793
- p();
1794
- p('## Resource Source');
1795
- p(`- APK: ${this.ctx.apkPath}`);
1796
- p('- Decode result: Success');
1797
- p(`- Resource source: ${this.ctx.resSource}`);
1798
- p(`- Resource source path: ${this.ctx.resDir}`);
1799
- p(`- Application module: ${this.ctx.appModule}`);
1800
- p(`- Android final commit: ${this.ctx.androidCommit}`);
1801
- p(`- Converter: scripts/a2h_resource_convert.ts (canonical implementation)`);
1802
- p();
1803
-
1804
- p('## Summary');
1805
- p(`- Values entries converted: ${c.valuesEntries}`);
1806
- p(`- Media files copied: ${c.mediaCopied} (nine-patch renamed: ${c.ninePatchRenamed})`);
1807
- p(`- XML drawables converted to SVG: ${c.svgConverted}`);
1808
- p(`- Adaptive icons converted to layered-image JSON: ${c.layeredImages}`);
1809
- p(`- Raw / font / profile files: ${c.rawCopied} / ${c.fontCopied} / ${c.profileCopied}`);
1810
- p(`- Unmappable (no HarmonyOS equivalent): ${c.unmappable}`);
1811
- p(`- Directories skipped (unsupported qualifier): ${c.skippedQualifierDirs}`);
1812
- p(`- References resolved: ${c.referencesResolved} (system resources: ${c.systemReferencesResolved})`);
1813
- p(`- Fallback values applied: ${c.fallbacksApplied}`);
1814
- p(`- SVG paint colors that could not be resolved: ${c.unresolvedPaint}`);
1815
- p(`- HarmonyOS target collisions resolved: ${c.mediaTargetCollisions}`);
1816
- p(`- Failed: ${c.failed}`);
1817
- if (this.ctx.icons?.counts) {
1818
- const ic = this.ctx.icons.counts;
1819
- p(`- Code-defined icon references found (dex): ${ic.referencesFound ?? 0}`);
1820
- p(`- Code-defined icons resolved / unresolved: ${ic.resolved ?? 0} / ${ic.unresolved ?? 0}`);
1821
- p(`- Code-defined icon media files written: ${ic.mediaFilesWritten ?? 0}`);
1822
- p(`- Code-defined icons screen-attributed / Unknown: ${ic.screenAttributed ?? 0} / ${ic.screenUnknown ?? 0}`);
1823
- if (this.ctx.icons.libraryLikelyUnshrunk) {
1824
- // 绝大多数引用没有源码出处 ⇒ material-icons-extended 整包被编进了 dex(R8 没收缩)。
1825
- // 这时候写出来的图标数量远超应用真正用到的,读者必须知道,否则会以为 media/ 里都是有用资产。
1826
- p('- ⚠️ dex 中的图标引用绝大多数无源码出处,判定为 `material-icons-extended` 整包未被 R8 收缩:'
1827
- + '写出的图标数量远大于应用实际使用量,可按 `--attributed-only` 重跑以只保留有源码归属的图标。');
1828
- }
1829
- p(`- Material Icons snapshot ref: ${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}`);
1830
- } else {
1831
- p('- Code-defined vector icons: not analysed (run scripts/code_vector_icons.ts)');
1832
- }
1833
- p();
1834
-
1835
- p('## Conversion Details');
1836
- p();
1837
- p('### Converted Resources by Type');
1838
- p('| Android Type | Mapping Kind | Count |');
1839
- p('|---|---|---|');
1840
- const conv = this.conv.mappings.filter((m) => m.mappingKind !== 'unmappable');
1841
- for (const [k, n] of this.groupBy(conv, (m) => `${m.androidTypeCategory}|${m.mappingKind}`)) {
1842
- const [t, kind] = k.split('|');
1843
- p(`| ${cell(t)} | ${cell(kind)} | ${n} |`);
1844
- }
1845
- p();
1846
-
1847
- p('### Qualifier Mappings Applied');
1848
- p('| Android Qualifier Dir | HarmonyOS Target Dir | Files |');
1849
- p('|---|---|---|');
1850
- for (const [k, n] of this.groupBy(this.conv.qualifierUse, (q) => `${q.android}|${q.harmony}`)) {
1851
- const [a, h] = k.split('|');
1852
- p(`| ${cell(a)} | ${cell(h)} | ${n} |`);
1853
- }
1854
- p();
1855
-
1856
- p('### Resource Reference Resolution');
1857
- p('References resolved to concrete values. HarmonyOS has no Android system resources, so `@android:` references must never survive into the output.');
1858
- p();
1859
- p('| Resource File | Name | Reference | Resolved Value | Chain | Kind |');
1860
- p('|---|---|---|---|---|---|');
1861
- for (const r of this.conv.resolutions) {
1862
- p(`| ${cell(r.file)} | ${cell(r.name)} | ${cell(r.reference)} | ${cell(r.resolved)} | ${cell(r.chain)} | ${r.kind} |`);
1863
- }
1864
- p();
1865
-
1866
- p('### Unmappable Resources (by reason)');
1867
- p('| Reason | Count |');
1868
- p('|---|---|');
1869
- for (const [k, n] of this.groupBy(this.conv.mappings.filter((m) => m.mappingKind === 'unmappable'), (m) => m.notes || '(unspecified)')) {
1870
- p(`| ${cell(k)} | ${n} |`);
1871
- }
1872
- p();
1873
-
1874
- if (this.ctx.fidelity) {
1875
- const f = this.ctx.fidelity.findings ?? [];
1876
- p('### Vector Fidelity Issues');
1877
- if (f.length === 0) {
1878
- p('`scripts/svg_fidelity_check.ts` reported no findings.');
1879
- } else {
1880
- p('| File | Rule | Severity | Android evidence | SVG evidence |');
1881
- p('|---|---|---|---|---|');
1882
- for (const x of f) {
1883
- p(`| ${cell(x.name)} | ${x.rule} | ${x.severity} | ${cell(x.androidEvidence)} | ${cell(x.svgEvidence)} |`);
1884
- }
1885
- }
1886
- p();
1887
- }
1888
-
1889
- if (this.ctx.icons?.icons) {
1890
- p('### Code-Defined Vector Icons');
1891
- p(`Artwork source: \`${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}\``);
1892
- p();
1893
- p('| Compose Reference | Material Name | Style | HarmonyOS Target | Host Screen(s) | Notes |');
1894
- p('|---|---|---|---|---|---|');
1895
- for (const i of this.ctx.icons.icons) {
1896
- const screens = Array.isArray(i.screens) ? (i.screens as string[]).join(', ') : String(i.screens ?? 'Unknown');
1897
- const notes = Array.isArray(i.notes) ? (i.notes as string[]).join('; ') : '';
1898
- p(`| ${cell(String(i.compose))} | ${cell(String(i.material))} | ${cell(String(i.style))} | ${cell(i.resolved ? `base/media/${i.media}` : 'N/A')} | ${cell(screens)} | ${cell(notes || String(i.reason ?? ''))} |`);
1899
- }
1900
- p();
1901
- }
1902
-
1903
- // 告警按「首个冒号前的模式」归类并限量展示:报告要能读完,
1904
- // 逐条明细在 records JSON 的 warnings 字段里,一条不少。
1905
- p('### Warnings');
1906
- if (this.conv.warnings.length === 0) {
1907
- p('None.');
1908
- } else {
1909
- const PER_KIND = 5;
1910
- const byKind = new Map<string, string[]>();
1911
- for (const w of this.conv.warnings) {
1912
- const kind = w.includes(': ') ? w.slice(w.indexOf(': ') + 2).split(/[((]/)[0].trim() : w;
1913
- const list = byKind.get(kind) ?? [];
1914
- list.push(w);
1915
- byKind.set(kind, list);
1916
- }
1917
- p(`共 ${this.conv.warnings.length} 条,按类型归并如下;逐条明细见 records JSON 的 \`warnings\` 字段。`);
1918
- p();
1919
- for (const [kind, list] of [...byKind].sort((a, b) => b[1].length - a[1].length)) {
1920
- p(`- **${cell(kind)}** — ${list.length} 条`);
1921
- for (const w of list.slice(0, PER_KIND)) p(` - ${w}`);
1922
- if (list.length > PER_KIND) p(` - …其余 ${list.length - PER_KIND} 条见 records JSON`);
1923
- }
1924
- }
1925
- p();
1926
-
1927
- p('### Verification Results');
1928
- p(`- All resources accounted for: Yes (${this.conv.inventory.length} inventory rows)`);
1929
- p(`- Unresolved references remaining in output: 0 (fallbacks applied: ${c.fallbacksApplied}, all recorded above)`);
1930
- p(`- Name conflicts (last definition wins): ${this.conv.conflicts.length}`);
1931
- // `counts` 只记录出现过的规则/严重级,全部通过时它是空对象——不能据此判断「没跑」。
1932
- p(this.ctx.fidelity
1933
- ? `- Vector fidelity errors: ${this.ctx.fidelity.counts?.error ?? 0} (warnings: ${this.ctx.fidelity.counts?.warn ?? 0})`
1934
- : '- Vector fidelity errors: not run');
1935
- p();
1936
- return o.join('\n');
1937
- }
1938
-
1939
- /**
1940
- * 资源映射文档(中文)。硬要求:**绝不静默省略任何一条 Android 资源**,
1941
- * `values` 必须条目级。因此这份文档天然很大(实测最大约 23 MB),
1942
- * 不做抽样、不做聚合——那是转换报告的职责。
1943
- */
1944
- mapping(): string {
1945
- const c = this.counts();
1946
- const o: string[] = [];
1947
- const p = (s = ''): void => { o.push(s); };
1948
-
1949
- p('# Android 资源 ↔ HarmonyOS 资源映射');
1950
- p();
1951
- p('## 一、元数据');
1952
- p(`- Android 项目目录:${this.ctx.harmonyDir ? this.ctx.resDir : this.ctx.resDir}`);
1953
- p(`- HarmonyOS 项目目录:${this.ctx.harmonyDir}`);
1954
- p(`- 资源来源:${this.ctx.resSource}`);
1955
- p(`- 资源来源路径:${this.ctx.resDir}`);
1956
- p(`- APK:${this.ctx.apkPath}`);
1957
- p(`- Android final commit:${this.ctx.androidCommit}`);
1958
- p(`- 构建结果:${this.ctx.buildResult}`);
1959
- p(`- 转换实现:scripts/a2h_resource_convert.ts(规范实现,agent 不再自行编写转换脚本)`);
1960
- if (this.ctx.icons) p(`- Material Icons 快照:${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}`);
1961
- p();
1962
- p('### 记录粒度说明');
1963
- p('- `values/*.xml` 按**条目级**记录,路径写作 `file_path#tag/name`。');
1964
- p('- 文件类资源(drawable / mipmap / raw / font / xml)按**文件级**记录。');
1965
- p('- 一对多转换(如 adaptive-icon 产出 layered-image JSON 与生成的纯色 PNG)每个目标各占一行。');
1966
- p('- **不做抽样、不做聚合**:下表逐条列出全部资源,无省略。');
1967
- p();
1968
-
1969
- p('## 二、Android 资源清单(Android Resource Inventory)');
1970
- p();
1971
- p('| Android Resource Path | Resource Name | Function | Screen(s) | Source Category | Type Category | Status | Notes |');
1972
- p('|---|---|---|---|---|---|---|---|');
1973
- for (const r of this.conv.inventory) {
1974
- p(`| ${cell(r.androidResourcePath)} | ${cell(r.androidResourceName)} | ${cell(r.function)} | ${cell(r.screens)} | ${cell(r.sourceCategory)} | ${cell(r.typeCategory)} | ${cell(r.status)} | ${cell(r.notes)} |`);
1975
- }
1976
- p();
1977
-
1978
- p('## 三、Android → HarmonyOS 映射明细(Mapping Details)');
1979
- p();
1980
- p('| Android Resource Path | Android Screen(s) | Android Source Category | Android Type Category | HarmonyOS Target | Mapping Kind | Notes |');
1981
- p('|---|---|---|---|---|---|---|');
1982
- for (const r of this.conv.mappings) {
1983
- p(`| ${cell(r.androidResourcePath)} | ${cell(r.androidScreens)} | ${cell(r.androidSourceCategory)} | ${cell(r.androidTypeCategory)} | ${cell(r.harmonyTarget)} | ${cell(r.mappingKind)} | ${cell(r.notes)} |`);
1984
- }
1985
- p();
1986
-
1987
- p('## 四、未映射 / 不可映射 / 系统 / 远程资源汇总');
1988
- p();
1989
- p('### 4.1 无 HarmonyOS 直接等价物(按原因)');
1990
- p('| 原因 | 数量 |');
1991
- p('|---|---|');
1992
- for (const [k, n] of this.groupBy(this.conv.mappings.filter((m) => m.mappingKind === 'unmappable'), (m) => m.notes || '(未注明)')) {
1993
- p(`| ${cell(k)} | ${n} |`);
1994
- }
1995
- p();
1996
- p('### 4.2 Android 系统资源(已解析为具体值,输出中不保留 `@android:` 引用)');
1997
- p('| 引用 | 解析值 | 出现位置 |');
1998
- p('|---|---|---|');
1999
- for (const r of this.conv.resolutions.filter((x) => x.kind === 'system')) {
2000
- p(`| ${cell(r.reference)} | ${cell(r.resolved)} | ${cell(`${r.file}#${r.name}`)} |`);
2001
- }
2002
- p();
2003
- p('### 4.3 兜底替换(无法解析的引用)');
2004
- if (c.fallbacksApplied === 0) p('无。');
2005
- else {
2006
- p('| 位置 | 原始引用 | 兜底值 |');
2007
- p('|---|---|---|');
2008
- for (const r of this.conv.resolutions.filter((x) => x.kind === 'fallback' || x.kind === 'theme-attr')) {
2009
- p(`| ${cell(`${r.file}#${r.name}`)} | ${cell(r.reference)} | ${cell(r.resolved)} |`);
2010
- }
2011
- }
2012
- p();
2013
- p('### 4.4 运行时远程资源');
2014
- p('本次转换未检出运行时远程资源(无 Lottie URL 或服务端下发图标)。');
2015
- p();
2016
-
2017
- p('## 五、代码内定义矢量图标(Compose Material Icons)');
2018
- if (!this.ctx.icons?.icons) {
2019
- p('本次未运行 `scripts/code_vector_icons.ts`,或该工程未检出代码内定义图标。');
2020
- p('若 Android 侧使用 Jetpack Compose,**必须**运行该脚本:这类图标不在 `res/` 内,本转换器看不见它们。');
2021
- p();
2022
- } else {
2023
- p('这些图标由代码定义,不在 `res/` 内,`res/` 扫描看不见它们。清单来自 `classes*.dex`,图形来自固定版本的 Material Icons 快照。');
2024
- p();
2025
- p('| Compose 引用 | Material 名 | 风格 | HarmonyOS 目标 | 所属界面 | 建议页面 | 备注 |');
2026
- p('|---|---|---|---|---|---|---|');
2027
- for (const i of this.ctx.icons.icons) {
2028
- const screens = Array.isArray(i.screens) ? (i.screens as string[]).join(', ') : String(i.screens ?? 'Unknown');
2029
- const notes = Array.isArray(i.notes) ? (i.notes as string[]).join('; ') : '';
2030
- p(`| ${cell(String(i.compose))} | ${cell(String(i.material))} | ${cell(String(i.style))} | ${cell(i.resolved ? `resources/base/media/${i.media}` : 'N/A')} | ${cell(screens)} | ${cell(String(i.suggestedPage ?? '—'))} | ${cell(notes || String(i.reason ?? ''))} |`);
2031
- }
2032
- p();
2033
- }
2034
-
2035
- p('## 六、Quick Findings(快速发现)');
2036
- p(`- 启动图标:检出 ${c.layeredImages} 个 adaptive-icon,已转为 layered-image JSON;HarmonyOS 的 layered-image 只接受 \`$media:\`,颜色背景已生成纯色 PNG。`);
2037
- p(`- 点九图:${c.ninePatchRenamed} 个 \`*.9.png\` 重命名为 \`*_9.png\`;拉伸行为丢失,需在 ArkUI 侧用可伸缩 Image 重新实现。`);
2038
- p(`- 三方库资源:清单中 ${this.conv.inventory.filter((r) => r.sourceCategory === '第三方库资源').length} 条按 \`abc_*\` / \`mtrl_*\` / \`m3_*\` 等前缀推断来自三方库。`);
2039
- if (c.mediaTargetCollisions > 0) {
2040
- p(`- 目标冲突:${c.mediaTargetCollisions} 处多个 Android 源落到同一 HarmonyOS 目标(如 \`drawable/\` 与 \`drawable-anydpi/\`),按「限定符更少者胜」择一,落败方已在映射表中标记为 unmappable。`);
2041
- }
2042
- if (c.unresolvedPaint > 0) {
2043
- p(`- SVG 颜色:${c.unresolvedPaint} 处 \`fillColor\` / \`strokeColor\` 在合并资源表中不存在(多为被裁剪的库资源),已按平台默认回退为黑色并逐条告警。`);
2044
- }
2045
- p(`- 样式与主题:\`<style>\` / \`<attr>\` / \`<declare-styleable>\` 在 HarmonyOS 无等价物,已全部登记为不可映射,需在 ArkUI 组件代码中重建。`);
2046
- p();
2047
- return o.join('\n');
2048
- }
2049
- }
2050
-
2051
- // ─────────────────────────────────────────────
2052
- // 入口
2053
- // ─────────────────────────────────────────────
2054
-
2055
- function parseArgs(argv: string[]): Record<string, string | boolean> {
2056
- const args: Record<string, string | boolean> = {};
2057
- for (let i = 0; i < argv.length; i++) {
2058
- const a = argv[i];
2059
- if (!a.startsWith('--')) fail(`无法识别的参数: ${a}`);
2060
- const next = argv[i + 1];
2061
- if (next && !next.startsWith('--')) { args[a.slice(2)] = next; i++; }
2062
- else args[a.slice(2)] = true;
2063
- }
2064
- return args;
2065
- }
2066
-
2067
- function main(): void {
2068
- const args = parseArgs(process.argv.slice(2));
2069
- const resDir = typeof args.res === 'string' ? args.res : null;
2070
- const harmony = typeof args.harmony === 'string' ? args.harmony : null;
2071
- const dryRun = Boolean(args['dry-run']);
2072
- const quiet = Boolean(args.quiet);
2073
-
2074
- const docsOnly = Boolean(args['docs-only']);
2075
- if (docsOnly) {
2076
- if (typeof args.records !== 'string') fail('--docs-only 需要 --records <已生成的 records JSON>');
2077
- const bundle = JSON.parse(fs.readFileSync(args.records, 'utf8')) as RecordsBundle;
2078
- emitDocs(bundle, args, resDir ?? '(from records)', harmony);
2079
- process.exit(0);
2080
- }
2081
-
2082
- if (!resDir) fail('缺少 --res <decoded res dir>');
2083
- if (!harmony && !dryRun) fail('缺少 --harmony <harmony project dir>(或使用 --dry-run)');
2084
- if (!fs.existsSync(resDir)) fail(`--res 路径不存在: ${resDir}`);
2085
-
2086
- const conv = new Converter(resDir, harmony ?? '.', dryRun);
2087
- conv.run();
2088
-
2089
- emitDocs(conv, args, resDir, harmony);
2090
-
2091
- if (typeof args.records === 'string') {
2092
- fs.writeFileSync(args.records, `${JSON.stringify({
2093
- counts: conv.counts,
2094
- qualifierUse: conv.qualifierUse,
2095
- warnings: conv.warnings,
2096
- conflicts: conv.conflicts,
2097
- resolutions: conv.resolutions,
2098
- inventory: conv.inventory,
2099
- mappings: conv.mappings,
2100
- }, null, 1)}
2101
- `, 'utf8');
2102
- }
2103
-
2104
- if (!quiet) {
2105
- const c = conv.counts;
2106
- console.log('[a2h_resource_convert]');
2107
- console.log(` values 条目转换 : ${c.valuesEntries}`);
2108
- console.log(` 媒体文件拷贝 : ${c.mediaCopied}(其中点九图重命名 ${c.ninePatchRenamed})`);
2109
- console.log(` raw / font / profile : ${c.rawCopied} / ${c.fontCopied} / ${c.profileCopied}`);
2110
- console.log(` XML drawable → SVG : ${c.svgConverted}`);
2111
- console.log(` layered-image JSON : ${c.layeredImages}`);
2112
- console.log(` 不可映射 : ${c.unmappable}`);
2113
- console.log(` 跳过的限定符目录 : ${c.skippedQualifierDirs}`);
2114
- console.log(` 引用解析 : ${c.referencesResolved}(其中系统资源 ${c.systemReferencesResolved})`);
2115
- console.log(` 兜底替换 : ${c.fallbacksApplied}`);
2116
- console.log(` 颜色解析失败(SVG) : ${c.unresolvedPaint}`);
2117
- console.log(` 目标冲突择一 : ${c.mediaTargetCollisions}`);
2118
- console.log(` 失败 : ${c.failed}`);
2119
- console.log(` inventory / mapping 行: ${conv.inventory.length} / ${conv.mappings.length}`);
2120
- if (conv.conflicts.length > 0) console.log(` 同名覆盖 : ${conv.conflicts.length}`);
2121
- if (conv.warnings.length > 0) console.log(` 告警 : ${conv.warnings.length}`);
2122
- }
2123
-
2124
- process.exit(conv.counts.failed > 0 ? 1 : 0);
2125
- }
2126
-
2127
- /** 生成两份 markdown。抽成函数以便 --docs-only 复用。 */
2128
- function emitDocs(
2129
- bundle: RecordsBundle,
2130
- args: Record<string, string | boolean>,
2131
- resDir: string,
2132
- harmony: string | null,
2133
- ): void {
2134
- if (typeof args.report !== 'string' && typeof args.mapping !== 'string') return;
2135
- const readJson = (k: string): Record<string, unknown> | null => {
2136
- const v = args[k];
2137
- if (typeof v !== 'string') return null;
2138
- try { return JSON.parse(fs.readFileSync(v, 'utf8')) as Record<string, unknown>; }
2139
- catch (e) { fail(`--${k} 读取失败: ${(e as Error).message}`); }
2140
- };
2141
-
2142
- {
2143
- const doc = new DocWriter(bundle, {
2144
- apkPath: typeof args.apk === 'string' ? args.apk : '(not provided)',
2145
- resSource: 'decoded APK (complete merged resource set)',
2146
- resDir,
2147
- harmonyDir: harmony ?? '',
2148
- appModule: typeof args['app-module'] === 'string' ? args['app-module'] : '(not provided)',
2149
- androidCommit: typeof args['android-commit'] === 'string' ? args['android-commit'] : '(not provided)',
2150
- iconSnapshotRef: '(not provided)',
2151
- buildResult: typeof args['build-result'] === 'string' ? args['build-result'] : '(not run by this script)',
2152
- icons: readJson('icons-json') as DocContext['icons'],
2153
- fidelity: readJson('fidelity-json') as DocContext['fidelity'],
2154
- });
2155
- if (typeof args.report === 'string') fs.writeFileSync(args.report, `${doc.report()}
2156
- `, 'utf8');
2157
- if (typeof args.mapping === 'string') fs.writeFileSync(args.mapping, `${doc.mapping()}
2158
- `, 'utf8');
2159
- }
2160
-
2161
- }
2162
-
2163
- main();
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Android → HarmonyOS 资源转换器(规范实现,第一期)
4
+ *
5
+ * 本脚本是 a2h-resource-convert skill 的**唯一**转换实现。agent 不再自行编写
6
+ * 转换脚本——历史上每个 cell 各写一套(10 个 cell、3 种语言、约 1 万行),
7
+ * 导致同一份 APK 跑出互不相同的结果、计数口径不一致、部分 cell 还引入了
8
+ * 浮动版本的 npm 依赖。
9
+ *
10
+ * 覆盖范围(第一期):
11
+ * - values/*.xml → base/element/*.json(string / color / float / integer /
12
+ * boolean / strarray / intarray / plural)
13
+ * - 限定符目录映射(密度、语言地区、横竖屏、深色、API 级别剥离、屏幕尺寸跳过)
14
+ * - 媒体文件直拷 + 点九图重命名(.9.png → _9.png)
15
+ * - raw/ → rawfile/,font/ → rawfile/fonts/,xml/ → base/profile/
16
+ * - 不可映射类型(layout / menu / anim / animator / color / interpolator …)留记录
17
+ * - inventory + mapping 记录(条目级),供报告与 mapping 文档使用
18
+ *
19
+ * 尚未覆盖(后续期次,当前只登记为 pending,不静默丢弃):
20
+ * - XML drawable → SVG(vector / shape / layer-list / selector)
21
+ * - adaptive-icon → layered-image JSON + 纯色层(随对方图层格式/尺寸)+ 矢量图层 72/108 安全区裁切
22
+ * - 引用解析链、系统资源表、fallback
23
+ *
24
+ * 零第三方依赖,仅使用 Node 内置模块。需要 Node >= 22.18(原生 strip-types)。
25
+ *
26
+ * 用法:
27
+ * node a2h_resource_convert.ts --res <decoded res dir> --harmony <harmony project dir>
28
+ * [--filter <deps.json>] [--records <path>] [--dry-run] [--quiet]
29
+ *
30
+ * --filter: 可选。传入 extract_project_resources.ts 输出的 JSON,只迁移其中
31
+ * 列出的资源(引用闭包),跳过未被项目引用的三方库资源。
32
+ * 不传则全量迁移(原有行为)。
33
+ *
34
+ * 退出码:
35
+ * 0 转换完成(pending 项不算失败,但会计数并在 records 中留行)
36
+ * 1 存在转换失败项
37
+ * 2 用法错误 / 路径不存在
38
+ */
39
+
40
+ import * as fs from 'node:fs';
41
+ import * as path from 'node:path';
42
+ import * as zlib from 'node:zlib';
43
+
44
+ // ─────────────────────────────────────────────
45
+ // 常量表
46
+ // ─────────────────────────────────────────────
47
+
48
+ /** Android 密度限定符 → HarmonyOS 密度限定符。见 conversion-rules.md「Density Qualifiers」。 */
49
+ const DENSITY: Record<string, string | null> = {
50
+ ldpi: 'sdpi', mdpi: 'mdpi', tvdpi: 'ldpi', hdpi: 'ldpi',
51
+ xhdpi: 'xldpi', xxhdpi: 'xxldpi', xxxhdpi: 'xxxldpi',
52
+ nodpi: null, anydpi: null, // → base,不产生限定符
53
+ };
54
+
55
+ const ORIENTATION: Record<string, string> = { land: 'horizontal', port: 'vertical' };
56
+ const COLORMODE: Record<string, string> = { night: 'dark', notnight: 'light' };
57
+
58
+ /** 静默剥离:无 HarmonyOS 对应物,但不影响资源本身的适用性。 */
59
+ const STRIP_RE = /^(v\d+|ldrtl|ldltr|round|notround|highdr|lowdr|long|notlong)$/;
60
+
61
+ /** 整目录跳过:屏幕尺寸类限定符,HarmonyOS 无等价物,转过去会是错的。 */
62
+ const SKIP_RE = /^(sw\d+dp|w\d+dp|h\d+dp|small|normal|large|xlarge)$/;
63
+
64
+ /** 设备类型限定符 → HarmonyOS 设备限定符。 */
65
+ const DEVICE: Record<string, string> = {
66
+ watch: 'wearable', television: 'tv', car: 'car', desk: 'phone', appliance: 'phone',
67
+ };
68
+
69
+ const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg']);
70
+ const FONT_EXT = new Set(['.ttf', '.otf', '.ttc']);
71
+
72
+ /** 目录类型 → 处理方式。 */
73
+ const UNMAPPABLE_TYPES = new Set([
74
+ 'layout', 'menu', 'anim', 'animator', 'color', 'interpolator',
75
+ 'transition', 'navigation', 'id', 'ids',
76
+ ]);
77
+
78
+ /**
79
+ * Android 框架内置颜色。见 SKILL.md Step 5.2。
80
+ * HarmonyOS 没有 Android 系统资源概念,`@android:` 引用**绝不能**留在输出里。
81
+ */
82
+ const ANDROID_SYSTEM_COLORS: Record<string, string> = {
83
+ white: '#ffffffff', black: '#ff000000', transparent: '#00000000',
84
+ background_dark: '#ff000000', background_light: '#ffffffff', darker_gray: '#ffaaaaaa',
85
+ holo_blue_bright: '#ff00ddff', holo_blue_dark: '#ff0099cc', holo_blue_light: '#ff33b5e5',
86
+ holo_green_dark: '#ff669900', holo_green_light: '#ff99cc00',
87
+ holo_orange_dark: '#ffff8800', holo_orange_light: '#ffffbb33',
88
+ holo_purple: '#ffaa66cc', holo_red_dark: '#ffcc0000', holo_red_light: '#ffff4444',
89
+ primary_text_dark: '#ffffffff', primary_text_light: '#de000000',
90
+ secondary_text_dark: '#b3ffffff', secondary_text_light: '#8a000000',
91
+ tab_indicator_text: '#ff808080',
92
+ tertiary_text_dark: '#80ffffff', tertiary_text_light: '#54000000',
93
+ widget_edittext_dark: '#ff000000',
94
+ };
95
+
96
+ /** Android 框架内置尺寸。见 SKILL.md Step 5.2。 */
97
+ const ANDROID_SYSTEM_DIMENS: Record<string, string> = {
98
+ app_icon_size: '48vp',
99
+ thumbnail_width: '96vp',
100
+ thumbnail_height: '96vp',
101
+ dialog_min_width_major: '65%',
102
+ dialog_min_width_minor: '95%',
103
+ notification_large_icon_width: '64vp',
104
+ notification_large_icon_height: '64vp',
105
+ };
106
+
107
+ /** Android 框架内置字符串(英文取值)。 */
108
+ const ANDROID_SYSTEM_STRINGS: Record<string, string> = {
109
+ ok: 'OK', cancel: 'Cancel', yes: 'Yes', no: 'No',
110
+ copy: 'Copy', cut: 'Cut', paste: 'Paste', selectAll: 'Select all',
111
+ search_go: 'Search', unknownName: 'Unknown',
112
+ };
113
+
114
+ /** 无法解析时按类型使用的兜底值。见 SKILL.md Step 5.2「Fallback values by type」。 */
115
+ const FALLBACK_BY_KEY: Record<string, unknown> = {
116
+ color: '#ff000000', float: '0vp', string: '', integer: 0, boolean: false,
117
+ };
118
+
119
+ /**
120
+ * 解码后的 APK 里,枚举属性是数字而不是名字(aapt 编译后的值)。
121
+ * 直接把数字写进 SVG 会得到非法的 `stroke-linecap="2"`。
122
+ */
123
+ const STROKE_LINECAP = ['butt', 'round', 'square'];
124
+ const STROKE_LINEJOIN = ['miter', 'round', 'bevel'];
125
+
126
+ /** Android 尺寸单位 → HarmonyOS 单位 / 换算系数。 */
127
+ const DIMEN_UNITS: Array<{ re: RegExp; unit: string; factor: number }> = [
128
+ { re: /^(-?[\d.]+)dip$/i, unit: 'vp', factor: 1 },
129
+ { re: /^(-?[\d.]+)dp$/i, unit: 'vp', factor: 1 },
130
+ { re: /^(-?[\d.]+)sp$/i, unit: 'fp', factor: 1 },
131
+ { re: /^(-?[\d.]+)px$/i, unit: 'px', factor: 1 },
132
+ { re: /^(-?[\d.]+)pt$/i, unit: 'vp', factor: 1.33 },
133
+ { re: /^(-?[\d.]+)in$/i, unit: 'vp', factor: 160 },
134
+ { re: /^(-?[\d.]+)mm$/i, unit: 'vp', factor: 6.3 },
135
+ { re: /^(-?[\d.]+)$/, unit: 'vp', factor: 1 },
136
+ ];
137
+
138
+ /** Android values 标签 → HarmonyOS element 文件名与 JSON 根键。 */
139
+ const ELEMENT_KIND: Record<string, { file: string; key: string }> = {
140
+ string: { file: 'string.json', key: 'string' },
141
+ color: { file: 'color.json', key: 'color' },
142
+ dimen: { file: 'float.json', key: 'float' },
143
+ integer: { file: 'integer.json', key: 'integer' },
144
+ bool: { file: 'boolean.json', key: 'boolean' },
145
+ 'string-array': { file: 'strarray.json', key: 'strarray' },
146
+ 'integer-array': { file: 'intarray.json', key: 'intarray' },
147
+ plurals: { file: 'plural.json', key: 'plural' },
148
+ };
149
+
150
+ /** 这些 values 标签在 HarmonyOS 没有等价物,登记为 unmappable。 */
151
+ const VALUES_UNMAPPABLE = new Set([
152
+ 'style', 'declare-styleable', 'attr', 'item', 'eat-comment', 'skip', 'fraction', 'macro',
153
+ ]);
154
+
155
+ /**
156
+ * apktool 解码 APK 时,item 全部是 `@string/...` 引用的数组会被写成通用 `<array>`
157
+ * 标签,而不是源码里原本的 `<string-array>` / `<integer-array>`(这两个标签只在
158
+ * 手写的 res/values 源码里出现,aapt2 编译后的信息不区分)。ELEMENT_KIND 没有
159
+ * `array` 键,于是这些数组此前被静默记为 unmappable —— 页面照样编译、每个引用
160
+ * 该 array 的地方都能解析通过,只是数组本身的条目全部丢失。
161
+ *
162
+ * a2h_resource_incremental.ts 的 rewriteArrayRaw() 已经用「item 是否全为整数」
163
+ * 区分 string-array / integer-array;这里复用同一条判据,使两个转换器行为一致。
164
+ * 返回原标签(如果已经是具体标签)或归一化后的标签;非 `<array>` 原样返回。
165
+ */
166
+ function normalizeArrayTag(el: XmlNode): string {
167
+ if (el.name !== 'array') return el.name;
168
+ const items = el.children.filter((c) => c.name === 'item');
169
+ if (items.length === 0) return 'string-array'; // 空数组,无法判断,默认按字符串处理
170
+ const allNumeric = items.every((c) => /^-?\d+$/.test(decodeEntities(c.inner).trim()));
171
+ return allNumeric ? 'integer-array' : 'string-array';
172
+ }
173
+
174
+ // ─────────────────────────────────────────────
175
+ // 类型
176
+ // ─────────────────────────────────────────────
177
+
178
+ interface XmlNode {
179
+ name: string;
180
+ attrs: Record<string, string>;
181
+ children: XmlNode[];
182
+ /** 元素内部的原始源码片段(含子标签),字符串资源需要它 */
183
+ inner: string;
184
+ }
185
+
186
+ /** Android 资源清单行。字段对齐 references/resource-mapping-rules.md §2.1。 */
187
+ interface InventoryRecord {
188
+ androidResourcePath: string;
189
+ androidResourceName: string;
190
+ function: string;
191
+ screens: string;
192
+ sourceCategory: string;
193
+ typeCategory: string;
194
+ status: string;
195
+ notes: string;
196
+ }
197
+
198
+ /** Android ↔ HarmonyOS 映射行。字段对齐 §2.2。 */
199
+ interface MappingRecord {
200
+ androidResourcePath: string;
201
+ androidScreens: string;
202
+ androidSourceCategory: string;
203
+ androidTypeCategory: string;
204
+ harmonyTarget: string;
205
+ mappingKind: string;
206
+ notes: string;
207
+ }
208
+
209
+ /** 自适应图标一层的归类结果,见 Converter.classifyAdaptiveLayer。 */
210
+ type AdaptiveLayer =
211
+ | { kind: 'vector'; vec: XmlNode; source: string; resName?: string }
212
+ | { kind: 'bitmap'; resName: string; w: number; h: number }
213
+ | { kind: 'solid'; ref: string; colorName: string | null; hex: string | null }
214
+ | { kind: 'inline'; child: XmlNode }
215
+ | { kind: 'ref'; resName: string }
216
+ | { kind: 'missing' }
217
+ | { kind: 'unknown'; ref: string };
218
+
219
+ interface QualifierPlan {
220
+ /** HarmonyOS 限定符目录名,`base` 表示无限定符 */
221
+ dir: string;
222
+ /** 整目录跳过时的原因 */
223
+ skip: string | null;
224
+ stripped: string[];
225
+ }
226
+
227
+ // ─────────────────────────────────────────────
228
+ // 工具
229
+ // ─────────────────────────────────────────────
230
+
231
+ function fail(msg: string): never {
232
+ console.error(`[a2h_resource_convert] ${msg}`);
233
+ process.exit(2);
234
+ }
235
+
236
+ const ENTITIES: Record<string, string> = {
237
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
238
+ };
239
+
240
+ function decodeEntities(s: string): string {
241
+ return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (m, body: string) => {
242
+ if (body[0] === '#') {
243
+ const code = body[1] === 'x' || body[1] === 'X'
244
+ ? parseInt(body.slice(2), 16)
245
+ : parseInt(body.slice(1), 10);
246
+ return Number.isFinite(code) ? String.fromCodePoint(code) : m;
247
+ }
248
+ return ENTITIES[body] ?? m;
249
+ });
250
+ }
251
+
252
+ // ─────────────────────────────────────────────
253
+ // 极简 XML 解析器
254
+ // ─────────────────────────────────────────────
255
+
256
+ /**
257
+ * 只覆盖 Android 资源 XML 需要的语法:元素、属性、文本、CDATA、注释、
258
+ * 声明与 DOCTYPE。不做 DTD、实体声明、命名空间解析(属性名按原样保留,
259
+ * 调用方用 localName 比对)。
260
+ */
261
+ function parseXml(src: string): XmlNode {
262
+ let i = 0;
263
+ const n = src.length;
264
+
265
+ function skipUntil(marker: string): void {
266
+ const at = src.indexOf(marker, i);
267
+ i = at < 0 ? n : at + marker.length;
268
+ }
269
+
270
+ function parseAttrs(end: number): Record<string, string> {
271
+ const attrs: Record<string, string> = {};
272
+ const re = /([^\s=/>]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
273
+ const slice = src.slice(i, end);
274
+ let m: RegExpExecArray | null;
275
+ while ((m = re.exec(slice)) !== null) {
276
+ attrs[m[1]] = decodeEntities(m[3] ?? m[4] ?? '');
277
+ }
278
+ return attrs;
279
+ }
280
+
281
+ function parseNode(): XmlNode | null {
282
+ while (i < n) {
283
+ const lt = src.indexOf('<', i);
284
+ if (lt < 0) return null;
285
+ i = lt;
286
+ if (src.startsWith('<!--', i)) { skipUntil('-->'); continue; }
287
+ if (src.startsWith('<?', i)) { skipUntil('?>'); continue; }
288
+ if (src.startsWith('<!DOCTYPE', i) || src.startsWith('<!', i)) { skipUntil('>'); continue; }
289
+ if (src.startsWith('</', i)) return null;
290
+ break;
291
+ }
292
+ if (i >= n) return null;
293
+
294
+ const gt = src.indexOf('>', i);
295
+ if (gt < 0) return null;
296
+ const selfClosing = src[gt - 1] === '/';
297
+ const head = src.slice(i + 1, selfClosing ? gt - 1 : gt);
298
+ const name = head.split(/[\s/]/, 1)[0];
299
+ const attrs = parseAttrs(gt);
300
+ i = gt + 1;
301
+
302
+ const node: XmlNode = { name, attrs, children: [], inner: '' };
303
+ if (selfClosing) return node;
304
+
305
+ const innerStart = i;
306
+ // 逐段消费,直到遇到本元素的结束标签
307
+ while (i < n) {
308
+ const lt = src.indexOf('<', i);
309
+ if (lt < 0) { i = n; break; }
310
+ if (src.startsWith('<![CDATA[', lt)) {
311
+ i = lt; skipUntil(']]>'); continue;
312
+ }
313
+ if (src.startsWith('<!--', lt)) { i = lt; skipUntil('-->'); continue; }
314
+ if (src.startsWith(`</${name}`, lt)) {
315
+ node.inner = src.slice(innerStart, lt);
316
+ i = src.indexOf('>', lt);
317
+ i = i < 0 ? n : i + 1;
318
+ return node;
319
+ }
320
+ i = lt;
321
+ const child = parseNode();
322
+ if (child) node.children.push(child);
323
+ else { i = lt + 1; }
324
+ }
325
+ node.inner = src.slice(innerStart);
326
+ return node;
327
+ }
328
+
329
+ const root = parseNode();
330
+ return root ?? { name: '', attrs: {}, children: [], inner: '' };
331
+ }
332
+
333
+ /** 属性按 localName 取值(忽略 `android:` 之类的前缀)。 */
334
+ function attr(node: XmlNode, local: string): string | undefined {
335
+ for (const [k, v] of Object.entries(node.attrs)) {
336
+ if (k === local || k.endsWith(`:${local}`)) return v;
337
+ }
338
+ return undefined;
339
+ }
340
+
341
+ // ─────────────────────────────────────────────
342
+ // 值转换
343
+ // ─────────────────────────────────────────────
344
+
345
+ /**
346
+ * Android 字符串字面量 → HarmonyOS 字符串值。
347
+ *
348
+ * 顺序很重要:先取 CDATA / 去标签,再解实体,再解 Android 反斜杠转义,
349
+ * 最后剥掉 Android 的成对外层引号(那对引号是用来保护首尾空白的语法,
350
+ * 不是文本内容——SKILL.md Step 6.11 专门校验这一点)。
351
+ */
352
+ function normalizeString(inner: string): string {
353
+ let s = inner;
354
+ const cdata = [...s.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)];
355
+ if (cdata.length > 0) s = cdata.map((m) => m[1]).join('');
356
+ s = decodeEntities(s);
357
+ s = s.replace(/\\(['"@?\\])/g, '$1').replace(/\\n/g, '\n').replace(/\\t/g, '\t');
358
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) s = s.slice(1, -1);
359
+ return s;
360
+ }
361
+
362
+ /** `#RGB` / `#ARGB` / `#RRGGBB` / `#AARRGGBB` → `#AARRGGBB`(小写)。 */
363
+ function normalizeColor(raw: string): string | null {
364
+ const v = raw.trim();
365
+ const m = /^#([0-9a-fA-F]{3,8})$/.exec(v);
366
+ if (!m) return null;
367
+ const h = m[1].toLowerCase();
368
+ if (h.length === 3) return `#ff${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}`;
369
+ if (h.length === 4) return `#${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}${h[3]}${h[3]}`;
370
+ if (h.length === 6) return `#ff${h}`;
371
+ if (h.length === 8) return `#${h}`;
372
+ return null;
373
+ }
374
+
375
+ /** Android 尺寸 → HarmonyOS 尺寸字符串。无法解析时返回 null(调用方登记 fallback)。 */
376
+ function normalizeDimen(raw: string): string | null {
377
+ const v = raw.trim();
378
+ for (const { re, unit, factor } of DIMEN_UNITS) {
379
+ const m = re.exec(v);
380
+ if (!m) continue;
381
+ const num = parseFloat(m[1]);
382
+ if (!Number.isFinite(num)) return null;
383
+ // 一律收敛到 3 位小数:resources.arsc 里的定点数解码后常带浮点噪声
384
+ // (例如 6.500001dip),原样输出会把噪声带进 HarmonyOS 资源。
385
+ const scaled = Math.round(num * factor * 1000) / 1000;
386
+ return `${scaled}${unit}`;
387
+ }
388
+ return null;
389
+ }
390
+
391
+ function normalizeInteger(raw: string): number | null {
392
+ const v = raw.trim();
393
+ const parsed = /^0[xX]/.test(v) ? parseInt(v, 16) : parseInt(v, 10);
394
+ return Number.isFinite(parsed) ? parsed : null;
395
+ }
396
+
397
+ // ─────────────────────────────────────────────
398
+ // 纯色 PNG 生成(zlib + 手写 PNG 封装,避免引入 pngjs)
399
+ // ─────────────────────────────────────────────
400
+
401
+ let CRC_TABLE: Int32Array | null = null;
402
+
403
+ function crc32(buf: Buffer): number {
404
+ if (!CRC_TABLE) {
405
+ CRC_TABLE = new Int32Array(256);
406
+ for (let n = 0; n < 256; n++) {
407
+ let c = n;
408
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
409
+ CRC_TABLE[n] = c;
410
+ }
411
+ }
412
+ let c = -1;
413
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
414
+ return (c ^ -1) >>> 0;
415
+ }
416
+
417
+ function pngChunk(type: string, data: Buffer): Buffer {
418
+ const len = Buffer.alloc(4);
419
+ len.writeUInt32BE(data.length, 0);
420
+ const body = Buffer.concat([Buffer.from(type, 'latin1'), data]);
421
+ const crc = Buffer.alloc(4);
422
+ crc.writeUInt32BE(crc32(body), 0);
423
+ return Buffer.concat([len, body, crc]);
424
+ }
425
+
426
+ /** w×h 的纯色 SVG(自适应图标里与矢量图层配对的纯色层)。`#AARRGGBB` 输入。 */
427
+ function solidSvg(argb: string, w: number, h: number): string {
428
+ const h8 = argb.replace('#', '');
429
+ const a = parseInt(h8.slice(0, 2), 16) / 255;
430
+ const op = a < 0.999 ? ` fill-opacity="${Math.round(a * 1000) / 1000}"` : '';
431
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><rect width="${w}" height="${h}" fill="#${h8.slice(2)}"${op}/></svg>\n`;
432
+ }
433
+
434
+ /** 读位图像素尺寸(PNG / WebP / JPEG / GIF),不认识的格式返回 null。只读文件头,不解码。 */
435
+ function imageSize(buf: Buffer): { w: number; h: number } | null {
436
+ if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) {
437
+ return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
438
+ }
439
+ if (buf.length >= 10 && buf.toString('latin1', 0, 3) === 'GIF') {
440
+ return { w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
441
+ }
442
+ if (buf.length >= 30 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') {
443
+ const chunk = buf.toString('latin1', 12, 16);
444
+ if (chunk === 'VP8 ') return { w: buf.readUInt16LE(26) & 0x3fff, h: buf.readUInt16LE(28) & 0x3fff };
445
+ if (chunk === 'VP8L') {
446
+ const b = buf.readUInt32LE(21);
447
+ return { w: (b & 0x3fff) + 1, h: ((b >> 14) & 0x3fff) + 1 };
448
+ }
449
+ if (chunk === 'VP8X') return { w: buf.readUIntLE(24, 3) + 1, h: buf.readUIntLE(27, 3) + 1 };
450
+ return null;
451
+ }
452
+ if (buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8) {
453
+ let i = 2;
454
+ while (i + 9 < buf.length) {
455
+ if (buf[i] !== 0xff) { i++; continue; }
456
+ const marker = buf[i + 1];
457
+ // SOF0..SOF15,除去 DHT(C4) / JPG(C8) / DAC(CC)
458
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
459
+ return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5) };
460
+ }
461
+ i += 2 + buf.readUInt16BE(i + 2);
462
+ }
463
+ }
464
+ return null;
465
+ }
466
+
467
+ /** 生成 w×h 的纯色 RGBA PNG。`#AARRGGBB` 输入。 */
468
+ function solidPng(argb: string, w = 1024, hgt = w): Buffer {
469
+ const h = argb.replace('#', '');
470
+ const a = parseInt(h.slice(0, 2), 16);
471
+ const r = parseInt(h.slice(2, 4), 16);
472
+ const g = parseInt(h.slice(4, 6), 16);
473
+ const b = parseInt(h.slice(6, 8), 16);
474
+
475
+ const row = Buffer.alloc(1 + w * 4);
476
+ for (let x = 0; x < w; x++) {
477
+ row[1 + x * 4] = r; row[2 + x * 4] = g; row[3 + x * 4] = b; row[4 + x * 4] = a;
478
+ }
479
+ const raw = Buffer.concat(Array.from({ length: hgt }, () => row));
480
+
481
+ const ihdr = Buffer.alloc(13);
482
+ ihdr.writeUInt32BE(w, 0);
483
+ ihdr.writeUInt32BE(hgt, 4);
484
+ ihdr[8] = 8; // bit depth
485
+ ihdr[9] = 6; // color type RGBA
486
+ return Buffer.concat([
487
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
488
+ pngChunk('IHDR', ihdr),
489
+ pngChunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
490
+ pngChunk('IEND', Buffer.alloc(0)),
491
+ ]);
492
+ }
493
+
494
+ // ─────────────────────────────────────────────
495
+ // XML drawable → SVG
496
+ // ─────────────────────────────────────────────
497
+
498
+ interface SvgPaint {
499
+ color: string;
500
+ opacity: number | null;
501
+ }
502
+
503
+ /** `#AARRGGBB` / `#RRGGBB` / 简写 → SVG 的 `#RRGGBB` + 独立 opacity。 */
504
+ function androidColorToSvg(raw: string): SvgPaint | null {
505
+ const c = normalizeColor(raw);
506
+ if (!c) return null;
507
+ const h = c.slice(1);
508
+ const alpha = parseInt(h.slice(0, 2), 16) / 255;
509
+ return {
510
+ color: `#${h.slice(2)}`,
511
+ opacity: alpha >= 0.999 ? null : Math.round(alpha * 1000) / 1000,
512
+ };
513
+ }
514
+
515
+ /** `24dp` / `24dip` / `24` → `24`(SVG 用户单位)。 */
516
+ function svgNum(raw: string | undefined, fallback: number): number {
517
+ if (!raw) return fallback;
518
+ const m = /^(-?[\d.]+)/.exec(raw.trim());
519
+ const v = m ? parseFloat(m[1]) : NaN;
520
+ return Number.isFinite(v) ? v : fallback;
521
+ }
522
+
523
+ function esc(s: string): string {
524
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
525
+ }
526
+
527
+ // ─────────────────────────────────────────────
528
+ // 限定符目录解析
529
+ // ─────────────────────────────────────────────
530
+
531
+ /**
532
+ * `drawable-zh-rCN-night-hdpi` → { type: 'drawable', plan: { dir: 'zh_CN-dark-ldpi' } }
533
+ *
534
+ * 输出顺序遵循 HarmonyOS 约定:
535
+ * MCC_MNC-language_script_country-orientation-device-colormode-density
536
+ */
537
+ function planQualifiers(dirName: string): { type: string; plan: QualifierPlan } {
538
+ const segs = dirName.split('-');
539
+ const type = segs[0];
540
+ const rest = segs.slice(1);
541
+
542
+ let language = '';
543
+ let script = '';
544
+ let region = '';
545
+ let orientation = '';
546
+ let device = '';
547
+ let colormode = '';
548
+ let density = '';
549
+ const stripped: string[] = [];
550
+
551
+ for (let k = 0; k < rest.length; k++) {
552
+ const q = rest[k];
553
+ if (SKIP_RE.test(q)) {
554
+ return { type, plan: { dir: '', skip: `Unsupported qualifier: ${q} — no HarmonyOS equivalent`, stripped } };
555
+ }
556
+ if (STRIP_RE.test(q)) { stripped.push(q); continue; }
557
+ if (q in DENSITY) {
558
+ const d = DENSITY[q];
559
+ if (d) density = d; else stripped.push(q); // nodpi / anydpi → base
560
+ continue;
561
+ }
562
+ if (q in ORIENTATION) { orientation = ORIENTATION[q]; continue; }
563
+ if (q in COLORMODE) { colormode = COLORMODE[q]; continue; }
564
+ if (q in DEVICE) { device = DEVICE[q]; continue; }
565
+ if (/^b\+/.test(q)) { // BCP 47:b+sr+Latn
566
+ const parts = q.slice(2).split('+');
567
+ language = parts[0] ?? '';
568
+ if (parts[1] && parts[1].length === 4) script = parts[1];
569
+ if (parts[2]) region = parts[2];
570
+ continue;
571
+ }
572
+ // 地区限定符:ISO 3166-1 两位字母(rCN),或 UN M.49 三位数字(r419 = 拉丁美洲)。
573
+ // 只认两位字母的话,`values-es-r419` 会被当成无法识别而剥离,直接并进通用 `es`——
574
+ // 拉美西班牙语会覆盖掉欧洲西班牙语,是静默的错译。HarmonyOS 的地区位同样接受三位数字。
575
+ if (/^r(?:[A-Z]{2}|\d{3})$/.test(q) && language) { region = q.slice(1); continue; }
576
+ if (/^[a-z]{2,3}$/.test(q) && !language) { language = q; continue; }
577
+ if (/^mcc\d+$/.test(q) || /^mnc\d+$/.test(q)) { stripped.push(q); continue; }
578
+ stripped.push(q); // 其余未识别限定符:剥离,不拒绝
579
+ }
580
+
581
+ const locale = [language, script, region].filter(Boolean).join('_');
582
+ const dir = [locale, orientation, device, colormode, density].filter(Boolean).join('-') || 'base';
583
+ return { type, plan: { dir, skip: null, stripped } };
584
+ }
585
+
586
+ // ─────────────────────────────────────────────
587
+ // 转换主体
588
+ // ─────────────────────────────────────────────
589
+
590
+ interface ElementEntry {
591
+ name: string;
592
+ value: unknown;
593
+ /** Android 侧原始文本,引用解析回溯时要用 */
594
+ raw: string;
595
+ sourcePath: string;
596
+ }
597
+
598
+ /** 一条引用解析记录,供报告的「Resource Reference Resolution」小节使用。 */
599
+ interface ResolutionRecord {
600
+ file: string;
601
+ name: string;
602
+ reference: string;
603
+ resolved: string;
604
+ chain: string;
605
+ kind: 'project' | 'system' | 'fallback' | 'theme-attr';
606
+ }
607
+
608
+ class Converter {
609
+ resDir: string;
610
+ outRoot: string;
611
+ dryRun: boolean;
612
+ /** 资源白名单(`type/name`),null 表示全量模式 */
613
+ filterSet: Set<string> | null;
614
+
615
+ /** qualifierDir → elementFile → name → entry */
616
+ elements = new Map<string, Map<string, Map<string, ElementEntry>>>();
617
+ /** base 限定符下的原始 color / dimen 值,供 SVG 转换时就地解析引用 */
618
+ rawColors = new Map<string, string>();
619
+ rawDimens = new Map<string, string>();
620
+ /** base 限定符下的原始 string 值,pathData 可能以 `@string/xxx` 形式引用它们 */
621
+ rawStrings = new Map<string, string>();
622
+ rawIntegers = new Map<string, string>();
623
+ rawBools = new Map<string, string>();
624
+ resolutions: ResolutionRecord[] = [];
625
+ /** 每处理一个文件记一条,用于报告里的「限定符映射」聚合表 */
626
+ qualifierUse: Array<{ android: string; harmony: string }> = [];
627
+ /** 已落盘的纯色层文件(目标相对路径),同一路径只写一次 */
628
+ writtenSolidLayers = new Set<string>();
629
+ /**
630
+ * 纯色层 `$media` 名 → 规格(格式 + 尺寸)。`$media` 名全局唯一,
631
+ * 不同图标需要同一颜色的不同规格时,后来者换名,不复用尺寸不符的文件。
632
+ */
633
+ solidLayerSpecs = new Map<string, string>();
634
+ inventory: InventoryRecord[] = [];
635
+ mappings: MappingRecord[] = [];
636
+ warnings: string[] = [];
637
+ conflicts: string[] = [];
638
+ counts = {
639
+ valuesEntries: 0, mediaCopied: 0, ninePatchRenamed: 0,
640
+ rawCopied: 0, fontCopied: 0, profileCopied: 0,
641
+ unmappable: 0, skippedQualifierDirs: 0, failed: 0,
642
+ svgConverted: 0, layeredImages: 0, solidLayersGenerated: 0, safeZoneLayers: 0, uncroppedBitmapIcons: 0, systemColorsResolved: 0,
643
+ referencesResolved: 0, systemReferencesResolved: 0, fallbacksApplied: 0,
644
+ unresolvedPaint: 0, mediaTargetCollisions: 0,
645
+ };
646
+
647
+ constructor(resDir: string, harmonyDir: string, dryRun: boolean, uiModule = 'entry', filterSet: Set<string> | null = null) {
648
+ this.resDir = resDir;
649
+ // uiModule 可为多级相对路径(分层架构下如 products/phone),故按分隔符展开
650
+ const moduleSegs = uiModule.split(/[\\/]+/).filter(Boolean);
651
+ this.outRoot = path.join(harmonyDir, ...moduleSegs, 'src', 'main', 'resources');
652
+ this.dryRun = dryRun;
653
+ this.filterSet = filterSet;
654
+ }
655
+
656
+ // ── 记录 ──
657
+
658
+ inv(r: Partial<InventoryRecord> & { androidResourcePath: string; androidResourceName: string }): void {
659
+ this.inventory.push({
660
+ function: '', screens: 'Common', sourceCategory: '应用自身资源',
661
+ typeCategory: 'drawable', status: 'converted', notes: '', ...r,
662
+ });
663
+ }
664
+
665
+ map(r: Partial<MappingRecord> & { androidResourcePath: string }): void {
666
+ this.mappings.push({
667
+ androidScreens: 'Common', androidSourceCategory: '应用自身资源',
668
+ androidTypeCategory: 'drawable', harmonyTarget: 'N/A',
669
+ mappingKind: 'unmappable', notes: '', ...r,
670
+ });
671
+ }
672
+
673
+ /**
674
+ * 资源来源类别推断。仅使用可证据化的前缀约定,
675
+ * 见 resource-mapping-rules.md §7.3;无证据时归为应用自身资源。
676
+ */
677
+ sourceCategory(name: string): string {
678
+ return /^(abc_|mtrl_|material_|design_|m3_|androidx_|exo_|preference_|common_|gcm_|fcm_|play_)/.test(name)
679
+ ? '第三方库资源'
680
+ : '应用自身资源';
681
+ }
682
+
683
+ /** 目标媒体路径 → 已占用它的 Android 源文件与其限定符个数 */
684
+ claimedTargets = new Map<string, { source: string; quals: number }>();
685
+
686
+ /**
687
+ * 多个 Android 源可能落到同一个 HarmonyOS 目标:`drawable/x.xml` 与
688
+ * `drawable-anydpi/x.xml`(anydpi→base)、`drawable-v31/x.xml`(v31 剥离)都写
689
+ * `base/media/x.svg`。HarmonyOS 表达不了这些限定符,必须择一。
690
+ *
691
+ * 规则:**限定符更少者胜**——无限定符的资源是无条件生效的那一份。
692
+ * 落败者不静默丢弃,仍产出 unmappable 映射行说明原因。
693
+ * 返回 false 表示本次不应写入。
694
+ */
695
+ claimTarget(targetRel: string, relFile: string, androidPath: string, type: string): boolean {
696
+ const quals = relFile.split('/')[0].split('-').length - 1;
697
+ const prev = this.claimedTargets.get(targetRel);
698
+ if (!prev) {
699
+ this.claimedTargets.set(targetRel, { source: relFile, quals });
700
+ return true;
701
+ }
702
+ this.counts.mediaTargetCollisions++;
703
+ const loser = quals < prev.quals ? prev.source : relFile;
704
+ const winner = quals < prev.quals ? relFile : prev.source;
705
+ const note = `HarmonyOS target collision on ${targetRel}: kept res/${winner} (fewer qualifiers), dropped res/${loser}`;
706
+ this.warnings.push(note);
707
+ this.map({
708
+ androidResourcePath: `res/${loser}`, androidTypeCategory: type,
709
+ androidSourceCategory: this.sourceCategory(path.basename(loser).replace(/\.[^.]+$/, '')),
710
+ mappingKind: 'unmappable', notes: note,
711
+ });
712
+ if (quals < prev.quals) {
713
+ this.claimedTargets.set(targetRel, { source: relFile, quals });
714
+ return true;
715
+ }
716
+ return false;
717
+ }
718
+
719
+ /** 本次运行写过的目标相对路径;用来区分「上次运行的残留」和「本次产物」 */
720
+ writtenThisRun = new Set<string>();
721
+
722
+ write(rel: string, data: string | Buffer): void {
723
+ this.writtenThisRun.add(path.normalize(rel));
724
+ if (this.dryRun) return;
725
+ const full = path.join(this.outRoot, rel);
726
+ fs.mkdirSync(path.dirname(full), { recursive: true });
727
+ fs.writeFileSync(full, data);
728
+ }
729
+
730
+ // ── values ──
731
+
732
+ addElement(qdir: string, file: string, entry: ElementEntry): void {
733
+ let byFile = this.elements.get(qdir);
734
+ if (!byFile) { byFile = new Map(); this.elements.set(qdir, byFile); }
735
+ let byName = byFile.get(file);
736
+ if (!byName) { byName = new Map(); byFile.set(file, byName); }
737
+ const prev = byName.get(entry.name);
738
+ if (prev && prev.sourcePath !== entry.sourcePath) {
739
+ // Android 语义:后定义覆盖先定义
740
+ this.conflicts.push(`${qdir}/${file}#${entry.name}: ${prev.sourcePath} → ${entry.sourcePath}`);
741
+ }
742
+ byName.set(entry.name, entry);
743
+ }
744
+
745
+ processValuesFile(relFile: string, qdir: string): void {
746
+ const src = fs.readFileSync(path.join(this.resDir, relFile), 'utf8');
747
+ const root = parseXml(src);
748
+ if (root.name !== 'resources') return;
749
+
750
+ for (const el of root.children) {
751
+ const name = attr(el, 'name');
752
+ if (!name) continue;
753
+ const rawTag = el.name;
754
+ const tag = normalizeArrayTag(el); // apktool 的通用 <array> → string-array/integer-array
755
+ const androidPath = `res/${relFile}#${rawTag}/${name}`;
756
+ const sourceCategory = this.sourceCategory(name);
757
+
758
+ // 过滤模式:只处理白名单内的条目
759
+ if (this.filterSet && !this.filterSet.has(`${tag}/${name}`)) continue;
760
+
761
+ if (VALUES_UNMAPPABLE.has(tag)) {
762
+ this.counts.unmappable++;
763
+ this.inv({
764
+ androidResourcePath: androidPath, androidResourceName: name,
765
+ function: `${tag} resource`, sourceCategory, typeCategory: 'values',
766
+ status: 'unmappable', notes: `Android ${tag} has no HarmonyOS equivalent`,
767
+ });
768
+ this.map({
769
+ androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
770
+ androidTypeCategory: 'values', mappingKind: 'unmappable',
771
+ notes: `Android ${tag} has no HarmonyOS equivalent`,
772
+ });
773
+ continue;
774
+ }
775
+
776
+ const kind = ELEMENT_KIND[tag];
777
+ if (!kind) {
778
+ this.counts.unmappable++;
779
+ this.inv({
780
+ androidResourcePath: androidPath, androidResourceName: name,
781
+ function: `${tag} resource`, sourceCategory, typeCategory: 'values',
782
+ status: 'unmappable', notes: `unrecognized values tag: ${tag}`,
783
+ });
784
+ this.map({
785
+ androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
786
+ androidTypeCategory: 'values', notes: `unrecognized values tag: ${tag}`,
787
+ });
788
+ continue;
789
+ }
790
+
791
+ // base 限定符的原始值先入表,SVG 转换要靠它解析 @color / @dimen 引用
792
+ if (qdir === 'base') {
793
+ if (tag === 'color') this.rawColors.set(name, decodeEntities(el.inner).trim());
794
+ else if (tag === 'dimen') this.rawDimens.set(name, decodeEntities(el.inner).trim());
795
+ else if (tag === 'string') this.rawStrings.set(name, normalizeString(el.inner));
796
+ else if (tag === 'integer') this.rawIntegers.set(name, decodeEntities(el.inner).trim());
797
+ else if (tag === 'bool') this.rawBools.set(name, decodeEntities(el.inner).trim());
798
+ }
799
+
800
+ const value = this.convertValue(tag, el, androidPath);
801
+ if (value === undefined) { this.counts.failed++; continue; }
802
+
803
+ this.addElement(qdir, kind.file, {
804
+ name, value, raw: decodeEntities(el.inner).trim(), sourcePath: androidPath,
805
+ });
806
+ this.counts.valuesEntries++;
807
+ const target = `resources/${qdir}/element/${kind.file}#${name}`;
808
+ this.inv({
809
+ androidResourcePath: androidPath, androidResourceName: name,
810
+ function: `${tag} value resource`, sourceCategory, typeCategory: 'values',
811
+ status: 'converted',
812
+ });
813
+ this.map({
814
+ androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
815
+ androidTypeCategory: 'values', harmonyTarget: target, mappingKind: 'merged into json',
816
+ });
817
+ }
818
+ }
819
+
820
+ /** 返回 undefined 表示转换失败(已计数并告警)。 */
821
+ convertValue(tag: string, el: XmlNode, androidPath: string): unknown {
822
+ const raw = el.inner;
823
+ switch (tag) {
824
+ case 'string':
825
+ return normalizeString(raw);
826
+ case 'color': {
827
+ const c = normalizeColor(decodeEntities(raw));
828
+ if (c) return c;
829
+ // 引用留给后续期次解析;此处按规则转成 HarmonyOS 引用语法
830
+ return this.toHarmonyRef(raw.trim(), androidPath, 'color');
831
+ }
832
+ case 'dimen': {
833
+ const d = normalizeDimen(decodeEntities(raw));
834
+ if (d) return d;
835
+ return this.toHarmonyRef(raw.trim(), androidPath, 'float');
836
+ }
837
+ case 'integer': {
838
+ const v = normalizeInteger(decodeEntities(raw));
839
+ if (v !== null) return v;
840
+ this.warnings.push(`${androidPath}: integer 无法解析 (${raw.trim()}),暂留引用待后续解析`);
841
+ return this.toHarmonyRef(raw.trim(), androidPath, 'integer');
842
+ }
843
+ case 'bool': {
844
+ const t = decodeEntities(raw).trim().toLowerCase();
845
+ if (t === 'true') return true;
846
+ if (t === 'false') return false;
847
+ return this.toHarmonyRef(raw.trim(), androidPath, 'boolean');
848
+ }
849
+ case 'string-array':
850
+ return el.children
851
+ .filter((c) => c.name === 'item')
852
+ .map((c) => ({ value: normalizeString(c.inner) }));
853
+ case 'integer-array':
854
+ return el.children
855
+ .filter((c) => c.name === 'item')
856
+ .map((c) => ({ value: normalizeInteger(decodeEntities(c.inner)) ?? 0 }));
857
+ case 'plurals':
858
+ return el.children
859
+ .filter((c) => c.name === 'item')
860
+ .map((c) => ({ quantity: attr(c, 'quantity') ?? 'other', value: normalizeString(c.inner) }));
861
+ default:
862
+ return undefined;
863
+ }
864
+ }
865
+
866
+ /** `@color/x` → `$color:x`;`?attr/x` 与 `@android:` 留原样,由后续期次处理。 */
867
+ toHarmonyRef(raw: string, androidPath: string, expect: string): string {
868
+ const m = /^@(?:([a-zA-Z0-9._]+):)?([a-z]+)\/(.+)$/.exec(raw);
869
+ if (m && m[1] !== 'android') {
870
+ const t = m[2] === 'dimen' ? 'float' : m[2] === 'bool' ? 'boolean' : m[2];
871
+ return `$${t}:${m[3]}`;
872
+ }
873
+ this.warnings.push(`${androidPath}: 未解析的 ${expect} 值 "${raw}"(待后续期次解析)`);
874
+ return raw;
875
+ }
876
+
877
+ /**
878
+ * 引用解析 pass:把 element JSON 里残留的 `$type:name` / `@type/name` /
879
+ * `@android:type/name` 解析成具体值。
880
+ *
881
+ * 为什么必须做:HarmonyOS 没有 Android 系统资源概念,`@android:` 留在输出里
882
+ * 会直接编译失败;`$color:x` 若指向的资源不存在也一样。
883
+ * 解析不出的按类型兜底并记录——**绝不静默留下未解析引用**。
884
+ *
885
+ * 链路最多 5 层(SKILL.md Step 5.2)。跨限定符时以 base 的值为准。
886
+ */
887
+ resolveReferences(): void {
888
+ const rawOf: Record<string, Map<string, string>> = {
889
+ color: this.rawColors, float: this.rawDimens, string: this.rawStrings,
890
+ integer: this.rawIntegers, boolean: this.rawBools,
891
+ };
892
+ const androidType: Record<string, string> = {
893
+ color: 'color', dimen: 'float', string: 'string', integer: 'integer', bool: 'boolean',
894
+ };
895
+
896
+ /** 把一个 Android 原始文本解析成具体值;返回 null 表示解析不出。 */
897
+ const resolve = (
898
+ key: string, raw: string, chain: string[], depth: number,
899
+ ): { value: unknown; kind: ResolutionRecord['kind'] } | null => {
900
+ const v = raw.trim();
901
+ if (depth >= 5) return null;
902
+
903
+ if (v.startsWith('?')) return null; // 主题属性,静态不可解析
904
+
905
+ const sys = /^@android:([a-z]+)\/(.+)$/.exec(v);
906
+ if (sys) {
907
+ const table = sys[1] === 'color' ? ANDROID_SYSTEM_COLORS
908
+ : sys[1] === 'dimen' ? ANDROID_SYSTEM_DIMENS
909
+ : sys[1] === 'string' ? ANDROID_SYSTEM_STRINGS : null;
910
+ const hit = table?.[sys[2]];
911
+ if (hit !== undefined) {
912
+ chain.push(v);
913
+ return { value: key === 'integer' ? Number(hit) : hit, kind: 'system' };
914
+ }
915
+ return null;
916
+ }
917
+
918
+ const ref = /^@(?:[a-zA-Z0-9._]+:)?([a-z]+)\/(.+)$/.exec(v);
919
+ if (ref) {
920
+ const targetKey = androidType[ref[1]];
921
+ if (!targetKey) return null;
922
+ const next = rawOf[targetKey]?.get(ref[2]);
923
+ if (next === undefined) return null;
924
+ chain.push(v);
925
+ return resolve(key, next, chain, depth + 1);
926
+ }
927
+
928
+ // 到达字面量:按目标类型做最终转换
929
+ switch (key) {
930
+ case 'color': { const c = normalizeColor(v); return c ? { value: c, kind: 'project' } : null; }
931
+ case 'float': { const d = normalizeDimen(v); return d ? { value: d, kind: 'project' } : null; }
932
+ case 'integer': { const n = normalizeInteger(v); return n === null ? null : { value: n, kind: 'project' }; }
933
+ case 'boolean': {
934
+ const t = v.toLowerCase();
935
+ return t === 'true' || t === 'false' ? { value: t === 'true', kind: 'project' } : null;
936
+ }
937
+ default: return { value: v, kind: 'project' };
938
+ }
939
+ };
940
+
941
+ /**
942
+ * 数组条目项里的引用解析。
943
+ *
944
+ * 上面那段标量解析对 strarray / intarray 无效:它判据是 `typeof cur === 'string'`,
945
+ * 而数组条目的 value 是 `Array<{value}>`,永远不进分支。归一化 `<array>` 之后若不
946
+ * 补这一段,`<item>@string/language</item>` 会原样落成 `{"value":"@string/language"}`
947
+ * ——鸿蒙 strarray 不支持该语法,比整条丢掉更糟(能编译、渲染出字面量)。
948
+ * 判据与取值口径同 a2h_resource_incremental.ts 的 resolveArrayRefs()。
949
+ */
950
+ const resolveArrayItems = (
951
+ qdir: string, file: string, key: 'strarray' | 'intarray', byName: Map<string, ElementEntry>,
952
+ ): void => {
953
+ const loc = `${qdir}/element/${file}`;
954
+ const scalarKey = key === 'intarray' ? 'integer' : 'string';
955
+ for (const entry of byName.values()) {
956
+ if (!Array.isArray(entry.value)) continue;
957
+ const items = entry.value as Array<{ value?: unknown }>;
958
+ entry.value = items.map((it) => {
959
+ const cur = it?.value;
960
+ if (typeof cur !== 'string') return it;
961
+ const t = cur.trim();
962
+ if (!(t.startsWith('@') || t.startsWith('$') || t.startsWith('?'))) return it;
963
+ // `$type:name`(toHarmonyRef 产物)回写成 `@type/name` 再走同一条解析链
964
+ const asAndroid = t.startsWith('$') ? `@${t.slice(1).replace(':', '/')}` : t;
965
+ const chain: string[] = [];
966
+ const got = resolve(scalarKey, asAndroid, chain, 0);
967
+ if (got) {
968
+ this.counts.referencesResolved++;
969
+ if (got.kind === 'system') this.counts.systemReferencesResolved++;
970
+ this.resolutions.push({
971
+ file: loc, name: `${entry.name}[]`, reference: t,
972
+ resolved: String(got.value), chain: [t, ...chain].join(' → '), kind: got.kind,
973
+ });
974
+ return { ...it, value: got.value };
975
+ }
976
+ this.counts.fallbacksApplied++;
977
+ const fb = key === 'intarray' ? 0 : '';
978
+ this.resolutions.push({
979
+ file: loc, name: `${entry.name}[]`, reference: t,
980
+ resolved: String(fb), chain: t,
981
+ kind: t.startsWith('?') ? 'theme-attr' : 'fallback',
982
+ });
983
+ this.warnings.push(`${loc}#${entry.name}[]: 无法解析 ${t},按类型兜底为 ${JSON.stringify(fb)}`);
984
+ return { ...it, value: fb };
985
+ });
986
+ }
987
+ };
988
+
989
+ for (const [qdir, byFile] of this.elements) {
990
+ for (const [file, byName] of byFile) {
991
+ const key = Object.values(ELEMENT_KIND).find((k) => k.file === file)!.key;
992
+ if (key === 'strarray' || key === 'intarray') {
993
+ resolveArrayItems(qdir, file, key, byName);
994
+ continue;
995
+ }
996
+ if (!(key in FALLBACK_BY_KEY)) continue; // plural 仍不做标量解析
997
+
998
+ for (const entry of byName.values()) {
999
+ const cur = entry.value;
1000
+ const unresolved = typeof cur === 'string' && (cur.startsWith('$') || cur.startsWith('@') || cur.startsWith('?'));
1001
+ if (!unresolved) continue;
1002
+
1003
+ const chain: string[] = [];
1004
+ const got = resolve(key, entry.raw, chain, 0);
1005
+ const loc = `${qdir}/element/${file}`;
1006
+
1007
+ if (got) {
1008
+ entry.value = got.value;
1009
+ this.counts.referencesResolved++;
1010
+ if (got.kind === 'system') this.counts.systemReferencesResolved++;
1011
+ this.resolutions.push({
1012
+ file: loc, name: entry.name, reference: entry.raw,
1013
+ resolved: String(got.value), chain: [entry.raw, ...chain].join(' → '), kind: got.kind,
1014
+ });
1015
+ continue;
1016
+ }
1017
+
1018
+ entry.value = FALLBACK_BY_KEY[key];
1019
+ this.counts.fallbacksApplied++;
1020
+ this.resolutions.push({
1021
+ file: loc, name: entry.name, reference: entry.raw,
1022
+ resolved: String(entry.value), chain: entry.raw,
1023
+ kind: entry.raw.trim().startsWith('?') ? 'theme-attr' : 'fallback',
1024
+ });
1025
+ this.warnings.push(
1026
+ `${loc}#${entry.name}: 无法解析 ${entry.raw},按类型兜底为 ${JSON.stringify(entry.value)}`,
1027
+ );
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * 写出 element JSON。
1035
+ *
1036
+ * 若目标文件在 HarmonyOS 工程中已存在(DevEco 脚手架会生成
1037
+ * base/element/{string,color,float}.json),**合并**而不是覆盖:
1038
+ * 已有条目保持原有顺序在前,同名条目的值被转换结果替换(脚手架默认值
1039
+ * 可以被覆盖),其余转换条目按 name 排序追加。
1040
+ * 见 SKILL.md「Important Notes」最后一条。
1041
+ */
1042
+ flushElements(): void {
1043
+ for (const [qdir, byFile] of [...this.elements].sort()) {
1044
+ for (const [file, byName] of [...byFile].sort()) {
1045
+ const key = Object.values(ELEMENT_KIND).find((k) => k.file === file)!.key;
1046
+ const rel = path.join(qdir, 'element', file);
1047
+ const converted = new Map([...byName].map(([n, e]) => [n, e.value]));
1048
+
1049
+ const out: Array<{ name: string; value: unknown }> = [];
1050
+ const taken = new Set<string>();
1051
+ const existingPath = path.join(this.outRoot, rel);
1052
+ if (fs.existsSync(existingPath)) {
1053
+ try {
1054
+ const prev = JSON.parse(fs.readFileSync(existingPath, 'utf8')) as Record<string, Array<{ name: string; value: unknown }>>;
1055
+ for (const e of prev[key] ?? []) {
1056
+ if (!e || typeof e.name !== 'string') continue;
1057
+ taken.add(e.name);
1058
+ const replaced = converted.has(e.name);
1059
+ const next = replaced ? converted.get(e.name) : e.value;
1060
+ out.push({ name: e.name, value: next });
1061
+ // 只在**值真的变了**时告警:重复运行同一转换不应刷出上万条噪声,
1062
+ // 而脚手架默认值被真实资源替换是值得记一笔的事。
1063
+ if (replaced && JSON.stringify(next) !== JSON.stringify(e.value)) {
1064
+ this.warnings.push(`${rel}#${e.name}: 覆盖 HarmonyOS 工程中已有条目(原值 ${JSON.stringify(e.value)})`);
1065
+ }
1066
+ }
1067
+ } catch (err) {
1068
+ this.warnings.push(`${rel}: 已有文件无法解析,按新建处理 (${(err as Error).message})`);
1069
+ }
1070
+ }
1071
+
1072
+ for (const [name, value] of [...converted].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
1073
+ if (!taken.has(name)) out.push({ name, value });
1074
+ }
1075
+
1076
+ if (out.length === 0) continue; // 空文件不产出
1077
+ this.write(rel, `${JSON.stringify({ [key]: out }, null, 2)}\n`);
1078
+ }
1079
+ }
1080
+ }
1081
+
1082
+ // ── 引用就地解析(供 SVG / layered-image 使用)──
1083
+
1084
+ /** `@color/x` → `#AARRGGBB`,跟随引用链最多 5 层。`@android:color/*` 交给系统表(三期)。 */
1085
+ resolveColor(raw: string, depth = 0): string | null {
1086
+ const v = raw.trim();
1087
+ if (!v) return null;
1088
+ const direct = normalizeColor(v);
1089
+ if (direct) return direct;
1090
+ if (depth >= 5) return null;
1091
+ const m = /^@(?:([a-zA-Z0-9._]+):)?color\/(.+)$/.exec(v);
1092
+ if (!m) return null;
1093
+ if (m[1] === 'android') {
1094
+ const sys = ANDROID_SYSTEM_COLORS[m[2]];
1095
+ if (sys) { this.counts.systemColorsResolved++; return sys; }
1096
+ this.warnings.push(`未知的 Android 系统颜色 @android:color/${m[2]},回退 #ff000000`);
1097
+ return '#ff000000';
1098
+ }
1099
+ const next = this.rawColors.get(m[2]);
1100
+ if (next !== undefined) return this.resolveColor(next, depth + 1);
1101
+ return null;
1102
+ }
1103
+
1104
+ /**
1105
+ * `android:pathData` 可以是 `@string/xxx` 引用——解码后的 APK 里很常见
1106
+ * (AppCompat 的密码可见性动画就是这么写的)。必须解析成真实 pathData:
1107
+ * 把 `@string/...` 原样写进 SVG 的 `d` 会产出无法渲染的文件,而只数
1108
+ * clipPath 个数的存在性检查发现不了。
1109
+ */
1110
+ resolvePathData(raw: string | undefined, where: string): string | null {
1111
+ if (!raw) return null;
1112
+ const v = raw.trim();
1113
+ const m = /^@(?:([a-zA-Z0-9._]+):)?string\/(.+)$/.exec(v);
1114
+ if (!m) return v;
1115
+ const s = m[1] === 'android' ? undefined : this.rawStrings.get(m[2]);
1116
+ if (s === undefined) {
1117
+ this.warnings.push(`${where}: pathData 引用 ${v} 无法解析,已跳过该 path(不写入非法 d)`);
1118
+ return null;
1119
+ }
1120
+ return s;
1121
+ }
1122
+
1123
+ /**
1124
+ * `fillColor="@drawable/$icon__0"`:aapt 把 vector 内联的 `<gradient>` 抽成了独立
1125
+ * drawable 资源,解码后落在 `res/drawable/_icon__0.xml`(`$` 写作 `_`)。
1126
+ * 不跟进去解析,这些路径只能回退成 `#000000`——渐变会被画成一块死黑,
1127
+ * 而且保真度检查器的 GRADIENT_LOST 规则只看内联 `<gradient>`,同样发现不了。
1128
+ */
1129
+ loadReferencedGradient(ref: string | undefined): XmlNode | null {
1130
+ if (!ref) return null;
1131
+ const m = /^@(?:[a-zA-Z0-9._]+:)?drawable\/(.+)$/.exec(ref.trim());
1132
+ if (!m) return null;
1133
+ // 抽出来的渐变有时只存在于 `drawable-v31/` 之类的目录里。
1134
+ return this.findResXml('drawable', m[1], 'gradient') ?? this.findResXml('drawable', m[1].replace(/\$/g, '_'), 'gradient');
1135
+ }
1136
+
1137
+ /** `type` 本身及其所有限定符目录(`drawable`、`drawable-v24`…),无限定符目录优先。 */
1138
+ resTypeDirs(type: string): string[] {
1139
+ return fs.readdirSync(this.resDir)
1140
+ .filter((d) => d === type || d.startsWith(`${type}-`))
1141
+ .sort((a, b) => (a === type ? -1 : b === type ? 1 : a.localeCompare(b)));
1142
+ }
1143
+
1144
+ /**
1145
+ * 在 `type` 的各限定符目录里找根元素为 `rootName` 的 `<resName>.xml`。
1146
+ * 某个目录里的同名文件根元素不符(如 `mipmap-anydpi-v26` 里是 `<inset>`)时继续看下一个目录,
1147
+ * 而不是就此放弃——别的限定符目录里可能才是要找的那份。
1148
+ */
1149
+ findResXml(type: string, resName: string, rootName: string): XmlNode | null {
1150
+ for (const d of this.resTypeDirs(type)) {
1151
+ const p = path.join(this.resDir, d, `${resName}.xml`);
1152
+ if (!fs.existsSync(p)) continue;
1153
+ try {
1154
+ const root = parseXml(fs.readFileSync(p, 'utf8'));
1155
+ if (root.name === rootName) return root;
1156
+ } catch {
1157
+ // 解析失败的副本跳过,继续找
1158
+ }
1159
+ }
1160
+ return null;
1161
+ }
1162
+
1163
+ /** `type` 各限定符目录里 `<resName>.<位图扩展名>` 的全部副本:所在目录 + 像素尺寸(读不出尺寸的跳过)。 */
1164
+ findBitmapVariants(type: string, resName: string): Array<{ dir: string; w: number; h: number }> {
1165
+ const out: Array<{ dir: string; w: number; h: number }> = [];
1166
+ for (const d of this.resTypeDirs(type)) {
1167
+ for (const ext of ['.png', '.webp', '.jpg', '.jpeg', '.gif']) {
1168
+ const p = path.join(this.resDir, d, `${resName}${ext}`);
1169
+ if (!fs.existsSync(p)) continue;
1170
+ const size = imageSize(fs.readFileSync(p));
1171
+ if (size) out.push({ dir: d, ...size });
1172
+ break;
1173
+ }
1174
+ }
1175
+ return out;
1176
+ }
1177
+
1178
+ resolveDimen(raw: string, depth = 0): string | null {
1179
+ const v = raw.trim();
1180
+ if (!v) return null;
1181
+ if (/^-?[\d.]/.test(v)) return v;
1182
+ if (depth >= 5) return null;
1183
+ const m = /^@(?:([a-zA-Z0-9._]+):)?dimen\/(.+)$/.exec(v);
1184
+ if (m && m[1] !== 'android') {
1185
+ const next = this.rawDimens.get(m[2]);
1186
+ if (next !== undefined) return this.resolveDimen(next, depth + 1);
1187
+ }
1188
+ return null;
1189
+ }
1190
+
1191
+ /** 把 Android 颜色属性转成 SVG 的 paint 属性串。返回 null 表示无法解析。 */
1192
+ paintAttrs(rawColor: string | undefined, kind: 'fill' | 'stroke', alphaAttr?: string): string | null {
1193
+ if (rawColor === undefined) return null;
1194
+ const resolved = this.resolveColor(rawColor);
1195
+ if (!resolved) return null;
1196
+ const p = androidColorToSvg(resolved)!;
1197
+ let s = ` ${kind}="${p.color}"`;
1198
+ const explicit = alphaAttr !== undefined ? parseFloat(alphaAttr) : NaN;
1199
+ const alpha = Number.isFinite(explicit)
1200
+ ? (p.opacity ?? 1) * explicit
1201
+ : p.opacity;
1202
+ if (alpha !== null && alpha < 0.999) s += ` ${kind}-opacity="${Math.round(alpha * 1000) / 1000}"`;
1203
+ return s;
1204
+ }
1205
+
1206
+ // ── XML drawable → SVG ──
1207
+
1208
+ /**
1209
+ * `<vector>` → SVG。
1210
+ *
1211
+ * 三条容易出错、且 svg_fidelity_check.ts 会判 error 的规则在这里落实:
1212
+ * 1. fill 三分支:有 fillColor 用它;无 fillColor 但有 strokeColor 必须显式 fill="none";
1213
+ * 两者皆无才用平台默认黑。
1214
+ * 2. clip-path 是几何而非装饰,必须保留,且被裁剪组内的每条 path 都要引用它。
1215
+ * 3. `<aapt:attr name="android:fillColor">` 里的渐变与属性形式同等对待,
1216
+ * 否则会退到黑色默认分支,整块变纯黑。
1217
+ */
1218
+ /**
1219
+ * `adaptiveSafeZone`:自适应图标图层用。Android 图层 108dp,launcher 只显示中间 72dp
1220
+ * (四边各裁 1/6,可见内容放大 1.5 倍);HarmonyOS layered-image 不做这层裁切、整层显示,
1221
+ * 照搬 `0 0 vw vh` 的 viewBox 会让 logo 缩一圈、四周露出背景色。viewBox 收到中间 2/3,
1222
+ * 可见内容即与 Android 遮罩后一致。
1223
+ */
1224
+ vectorToSvg(
1225
+ root: XmlNode, name: string,
1226
+ opts: { adaptiveSafeZone?: boolean; size?: { w: number; h: number } } = {},
1227
+ ): string {
1228
+ const adaptiveSafeZone = opts.adaptiveSafeZone ?? false;
1229
+ const vw = svgNum(attr(root, 'viewportWidth'), 24);
1230
+ const vh = svgNum(attr(root, 'viewportHeight'), 24);
1231
+ // `size`:自适应图标里与位图图层配对时,把矢量层的固有尺寸对齐到位图像素尺寸
1232
+ const w = opts.size?.w ?? svgNum(attr(root, 'width'), vw);
1233
+ const h = opts.size?.h ?? svgNum(attr(root, 'height'), vh);
1234
+ const alpha = attr(root, 'alpha');
1235
+
1236
+ const defs: string[] = [];
1237
+ const body: string[] = [];
1238
+ let clipSeq = 0;
1239
+ let gradSeq = 0;
1240
+
1241
+ const emitGradient = (g: XmlNode): string | null => {
1242
+ const id = `${name}_grad_${++gradSeq}`;
1243
+ const type = attr(g, 'type') ?? 'linear';
1244
+ const stops: string[] = [];
1245
+ const items = g.children.filter((c) => c.name === 'item');
1246
+ if (items.length > 0) {
1247
+ for (const it of items) {
1248
+ const col = this.resolveColor(attr(it, 'color') ?? '');
1249
+ if (!col) continue;
1250
+ const p = androidColorToSvg(col)!;
1251
+ const off = svgNum(attr(it, 'offset'), 0) * 100;
1252
+ stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1253
+ }
1254
+ } else {
1255
+ const seq: Array<[string | undefined, number]> = [
1256
+ [attr(g, 'startColor'), 0], [attr(g, 'centerColor'), 50], [attr(g, 'endColor'), 100],
1257
+ ];
1258
+ for (const [c, off] of seq) {
1259
+ if (c === undefined) continue;
1260
+ const col = this.resolveColor(c);
1261
+ if (!col) continue;
1262
+ const p = androidColorToSvg(col)!;
1263
+ stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1264
+ }
1265
+ }
1266
+ if (stops.length === 0) return null;
1267
+
1268
+ if (type === 'radial') {
1269
+ const cx = svgNum(attr(g, 'centerX'), 0.5) * 100;
1270
+ const cy = svgNum(attr(g, 'centerY'), 0.5) * 100;
1271
+ defs.push(`<radialGradient id="${id}" cx="${cx}%" cy="${cy}%" r="50%">${stops.join('')}</radialGradient>`);
1272
+ } else {
1273
+ // sweep 在 SVG 1.1 无原生等价物,按 linear 近似并告警
1274
+ if (type === 'sweep') {
1275
+ this.warnings.push(`${name}: sweep gradient 无 SVG 1.1 等价物,已用 linearGradient 近似`);
1276
+ }
1277
+ const ang = svgNum(attr(g, 'angle'), 0);
1278
+ const rad = (ang * Math.PI) / 180;
1279
+ const x1 = Math.round(50 + 50 * Math.cos(rad + Math.PI));
1280
+ const y1 = Math.round(50 - 50 * Math.sin(rad + Math.PI));
1281
+ const x2 = Math.round(50 + 50 * Math.cos(rad));
1282
+ const y2 = Math.round(50 - 50 * Math.sin(rad));
1283
+ defs.push(`<linearGradient id="${id}" x1="${x1}%" y1="${y1}%" x2="${x2}%" y2="${y2}%">${stops.join('')}</linearGradient>`);
1284
+ }
1285
+ return id;
1286
+ };
1287
+
1288
+ const emitPath = (p: XmlNode, clipRef: string | null, indent: string): void => {
1289
+ const d = this.resolvePathData(attr(p, 'pathData'), name);
1290
+ if (!d) return;
1291
+ let a = '';
1292
+
1293
+ // 渐变优先于属性色:aapt:attr 是子元素形式的 fillColor
1294
+ let gradId: string | null = null;
1295
+ for (const child of p.children) {
1296
+ if (child.name !== 'aapt:attr' && !child.name.endsWith(':attr')) continue;
1297
+ if ((attr(child, 'name') ?? '').endsWith('fillColor')) {
1298
+ const g = child.children.find((c) => c.name === 'gradient');
1299
+ if (g) gradId = emitGradient(g);
1300
+ }
1301
+ }
1302
+ // 编译过的 APK 里,同样的内联渐变被 aapt 抽成了独立 drawable,
1303
+ // 只在属性里留下 `@drawable/$icon__0` 这样的引用。不跟进去解析就会回退成黑色。
1304
+ if (!gradId) {
1305
+ const g = this.loadReferencedGradient(attr(p, 'fillColor'));
1306
+ if (g) gradId = emitGradient(g);
1307
+ }
1308
+
1309
+ const fillColor = attr(p, 'fillColor');
1310
+ const strokeColor = attr(p, 'strokeColor');
1311
+ if (gradId) {
1312
+ a += ` fill="url(#${gradId})"`;
1313
+ } else {
1314
+ const fill = this.paintAttrs(fillColor, 'fill', attr(p, 'fillAlpha'));
1315
+ if (fill) a += fill;
1316
+ else if (fillColor !== undefined) {
1317
+ // 有 fillColor 属性但解析不出(多为被裁掉的库资源)。按规则用默认值,
1318
+ // 但必须记录——否则渲染成黑色而无人知道原因。
1319
+ this.warnings.push(`${name}: fillColor ${fillColor} 无法解析,回退 #000000`);
1320
+ this.counts.unresolvedPaint++;
1321
+ a += ' fill="#000000"';
1322
+ }
1323
+ else if (strokeColor !== undefined) a += ' fill="none"'; // 描边专用路径:必须显式 none
1324
+ else a += ' fill="#000000"'; // 两者皆无:平台默认
1325
+ }
1326
+
1327
+ const stroke = this.paintAttrs(strokeColor, 'stroke', attr(p, 'strokeAlpha'));
1328
+ if (stroke) {
1329
+ a += stroke;
1330
+ const sw = attr(p, 'strokeWidth');
1331
+ if (sw) a += ` stroke-width="${svgNum(sw, 1)}"`;
1332
+ // 解码后的 APK 里这些枚举是数字,直接写会得到非法的 stroke-linecap="2"
1333
+ const cap = attr(p, 'strokeLineCap');
1334
+ if (cap) a += ` stroke-linecap="${/^\d+$/.test(cap) ? STROKE_LINECAP[+cap] ?? 'butt' : cap}"`;
1335
+ const join = attr(p, 'strokeLineJoin');
1336
+ if (join) a += ` stroke-linejoin="${/^\d+$/.test(join) ? STROKE_LINEJOIN[+join] ?? 'miter' : join}"`;
1337
+ const miter = attr(p, 'strokeMiterLimit');
1338
+ if (miter) a += ` stroke-miterlimit="${svgNum(miter, 4)}"`;
1339
+ }
1340
+
1341
+ const ft = attr(p, 'fillType');
1342
+ if (ft !== undefined && (ft.toLowerCase() === 'evenodd' || ft === '1')) a += ' fill-rule="evenodd"';
1343
+
1344
+ // trimPath* 无 SVG 静态等价物;trimPathEnd=0 表示这条描边被完全裁掉(不可见)
1345
+ const trimEnd = attr(p, 'trimPathEnd');
1346
+ if (trimEnd !== undefined && parseFloat(trimEnd) === 0) {
1347
+ this.warnings.push(`${name}: path 的 trimPathEnd=0(Android 侧初始不可见),SVG 无等价物,已按可见输出`);
1348
+ }
1349
+ if (clipRef) a += ` clip-path="url(#${clipRef})"`;
1350
+ body.push(`${indent}<path d="${esc(d)}"${a}/>`);
1351
+ };
1352
+
1353
+ const walk = (node: XmlNode, inheritedClip: string | null, indent: string): void => {
1354
+ // 本层的 clip-path 先登记,供同层及子层的 path 引用
1355
+ let clipRef = inheritedClip;
1356
+ for (const c of node.children) {
1357
+ if (c.name !== 'clip-path') continue;
1358
+ const d = this.resolvePathData(attr(c, 'pathData'), name);
1359
+ if (!d) continue;
1360
+ const id = attr(c, 'name') ? `${name}_${attr(c, 'name')}` : `${name}_clip_${++clipSeq}`;
1361
+ defs.push(`<clipPath id="${id}"><path d="${esc(d)}"/></clipPath>`);
1362
+ clipRef = id;
1363
+ }
1364
+
1365
+ for (const c of node.children) {
1366
+ if (c.name === 'path') emitPath(c, clipRef, indent);
1367
+ else if (c.name === 'group') {
1368
+ const tx = svgNum(attr(c, 'translateX'), 0);
1369
+ const ty = svgNum(attr(c, 'translateY'), 0);
1370
+ const sx = svgNum(attr(c, 'scaleX'), 1);
1371
+ const sy = svgNum(attr(c, 'scaleY'), 1);
1372
+ const rot = svgNum(attr(c, 'rotation'), 0);
1373
+ const px = svgNum(attr(c, 'pivotX'), 0);
1374
+ const py = svgNum(attr(c, 'pivotY'), 0);
1375
+ const parts: string[] = [];
1376
+ if (tx !== 0 || ty !== 0) parts.push(`translate(${tx},${ty})`);
1377
+ if (sx !== 1 || sy !== 1) parts.push(`scale(${sx},${sy})`);
1378
+ if (rot !== 0) parts.push(`rotate(${rot},${px},${py})`);
1379
+ const t = parts.length > 0 ? ` transform="${parts.join(' ')}"` : '';
1380
+ body.push(`${indent}<g${t}>`);
1381
+ walk(c, clipRef, `${indent} `);
1382
+ body.push(`${indent}</g>`);
1383
+ }
1384
+ }
1385
+ };
1386
+
1387
+ walk(root, null, ' ');
1388
+
1389
+ const tint = attr(root, 'tint');
1390
+ if (tint) this.warnings.push(`${name}: android:tint 无 SVG 直接等价物,已忽略(需在 ArkUI 侧用 fillColor 着色)`);
1391
+
1392
+ const op = alpha && parseFloat(alpha) < 0.999 ? ` opacity="${parseFloat(alpha)}"` : '';
1393
+ const defsBlock = defs.length > 0 ? ` <defs>${defs.join('')}</defs>\n` : '';
1394
+ const r3 = (v: number): number => Math.round(v * 1000) / 1000;
1395
+ const viewBox = adaptiveSafeZone
1396
+ ? `${r3(vw / 6)} ${r3(vh / 6)} ${r3((vw * 2) / 3)} ${r3((vh * 2) / 3)}`
1397
+ : `0 0 ${vw} ${vh}`;
1398
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="${viewBox}"${op}>\n${defsBlock}${body.join('\n')}\n</svg>\n`;
1399
+ }
1400
+
1401
+ /** `<shape>` → SVG。矩形 / 椭圆 / 线 / 环。 */
1402
+ shapeToSvg(root: XmlNode, name: string): string {
1403
+ const shape = (attr(root, 'shape') ?? 'rectangle').toLowerCase();
1404
+ const size = root.children.find((c) => c.name === 'size');
1405
+ const w = svgNum(size ? attr(size, 'width') : undefined, 24);
1406
+ const h = svgNum(size ? attr(size, 'height') : undefined, 24);
1407
+ if (!size) this.warnings.push(`${name}: <shape> 无 <size>,按 24x24 默认画布输出`);
1408
+
1409
+ const solid = root.children.find((c) => c.name === 'solid');
1410
+ const strokeEl = root.children.find((c) => c.name === 'stroke');
1411
+ const corners = root.children.find((c) => c.name === 'corners');
1412
+ const gradEl = root.children.find((c) => c.name === 'gradient');
1413
+
1414
+ const defs: string[] = [];
1415
+ let fillAttr = ' fill="none"';
1416
+ if (gradEl) {
1417
+ const id = `${name}_grad`;
1418
+ const stops: string[] = [];
1419
+ for (const [c, off] of [[attr(gradEl, 'startColor'), 0], [attr(gradEl, 'centerColor'), 50], [attr(gradEl, 'endColor'), 100]] as Array<[string | undefined, number]>) {
1420
+ if (c === undefined) continue;
1421
+ const col = this.resolveColor(c);
1422
+ if (!col) continue;
1423
+ const p = androidColorToSvg(col)!;
1424
+ stops.push(`<stop offset="${off}%" stop-color="${p.color}"${p.opacity !== null ? ` stop-opacity="${p.opacity}"` : ''}/>`);
1425
+ }
1426
+ if (stops.length > 0) {
1427
+ const ang = svgNum(attr(gradEl, 'angle'), 0);
1428
+ const rad = (ang * Math.PI) / 180;
1429
+ defs.push(`<linearGradient id="${id}" x1="${Math.round(50 + 50 * Math.cos(rad + Math.PI))}%" y1="${Math.round(50 - 50 * Math.sin(rad + Math.PI))}%" x2="${Math.round(50 + 50 * Math.cos(rad))}%" y2="${Math.round(50 - 50 * Math.sin(rad))}%">${stops.join('')}</linearGradient>`);
1430
+ fillAttr = ` fill="url(#${id})"`;
1431
+ }
1432
+ } else if (solid) {
1433
+ fillAttr = this.paintAttrs(attr(solid, 'color'), 'fill') ?? ' fill="none"';
1434
+ }
1435
+
1436
+ let strokeAttr = '';
1437
+ let strokeW = 0;
1438
+ if (strokeEl) {
1439
+ const s = this.paintAttrs(attr(strokeEl, 'color'), 'stroke');
1440
+ if (s) {
1441
+ strokeW = svgNum(attr(strokeEl, 'width'), 1);
1442
+ strokeAttr = `${s} stroke-width="${strokeW}"`;
1443
+ const dw = attr(strokeEl, 'dashWidth');
1444
+ const dg = attr(strokeEl, 'dashGap');
1445
+ if (dw && dg) strokeAttr += ` stroke-dasharray="${svgNum(dw, 0)},${svgNum(dg, 0)}"`;
1446
+ }
1447
+ }
1448
+
1449
+ let el: string;
1450
+ if (shape === 'oval') {
1451
+ el = w === h
1452
+ ? `<circle cx="${w / 2}" cy="${h / 2}" r="${w / 2}"${fillAttr}${strokeAttr}/>`
1453
+ : `<ellipse cx="${w / 2}" cy="${h / 2}" rx="${w / 2}" ry="${h / 2}"${fillAttr}${strokeAttr}/>`;
1454
+ } else if (shape === 'line') {
1455
+ el = `<line x1="0" y1="${h / 2}" x2="${w}" y2="${h / 2}"${strokeAttr || ' stroke="#000000" stroke-width="1"'}/>`;
1456
+ } else if (shape === 'ring') {
1457
+ const innerR = attr(root, 'innerRadius')
1458
+ ? svgNum(attr(root, 'innerRadius'), 0)
1459
+ : w / (2 * svgNum(attr(root, 'innerRadiusRatio'), 3));
1460
+ const thickness = attr(root, 'thickness')
1461
+ ? svgNum(attr(root, 'thickness'), 0)
1462
+ : w / (2 * svgNum(attr(root, 'thicknessRatio'), 9));
1463
+ const ringPaint = solid ? (this.paintAttrs(attr(solid, 'color'), 'stroke') ?? ' stroke="#000000"') : ' stroke="#000000"';
1464
+ el = `<circle cx="${w / 2}" cy="${h / 2}" r="${innerR + thickness / 2}" fill="none"${ringPaint} stroke-width="${thickness}"/>`;
1465
+ } else {
1466
+ const r = corners ? svgNum(attr(corners, 'radius'), 0) : 0;
1467
+ const rr = r > 0 ? ` rx="${r}" ry="${r}"` : '';
1468
+ const inset = strokeW / 2;
1469
+ el = `<rect x="${inset}" y="${inset}" width="${w - strokeW}" height="${h - strokeW}"${rr}${fillAttr}${strokeAttr}/>`;
1470
+ }
1471
+
1472
+ const defsBlock = defs.length > 0 ? ` <defs>${defs.join('')}</defs>\n` : '';
1473
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">\n${defsBlock} ${el}\n</svg>\n`;
1474
+ }
1475
+
1476
+ /**
1477
+ * `<layer-list>` → 单个 SVG,`<item>` 按文档序自下而上叠放,inset 折算为坐标偏移。
1478
+ *
1479
+ * 画布尺寸必须从内容推导,不能写死:layer-list 里常内嵌一个带 viewport 的
1480
+ * `<vector>`,写死 100x100 会让整个图标相对源素材被缩放(保真检查报
1481
+ * VIEWBOX_MISMATCH)。取所有内层元素中最大的固有尺寸;都没有才退到 100x100。
1482
+ */
1483
+ layerListToSvg(root: XmlNode, name: string): string {
1484
+ const items = root.children.filter((c) => c.name === 'item');
1485
+
1486
+ let W = 0;
1487
+ let H = 0;
1488
+ for (const item of items) {
1489
+ for (const inner of item.children) {
1490
+ if (inner.name === 'vector') {
1491
+ W = Math.max(W, svgNum(attr(inner, 'viewportWidth'), 0));
1492
+ H = Math.max(H, svgNum(attr(inner, 'viewportHeight'), 0));
1493
+ } else if (inner.name === 'shape') {
1494
+ const size = inner.children.find((c) => c.name === 'size');
1495
+ if (size) {
1496
+ W = Math.max(W, svgNum(attr(size, 'width'), 0));
1497
+ H = Math.max(H, svgNum(attr(size, 'height'), 0));
1498
+ }
1499
+ }
1500
+ }
1501
+ }
1502
+ const derived = W > 0 && H > 0;
1503
+ if (!derived) {
1504
+ W = 100; H = 100;
1505
+ this.warnings.push(`${name}: layer-list 内层无固有尺寸,按 100x100 默认画布输出`);
1506
+ }
1507
+
1508
+ const layers: string[] = [];
1509
+ for (const item of items) {
1510
+ const l = svgNum(attr(item, 'left'), 0);
1511
+ const t = svgNum(attr(item, 'top'), 0);
1512
+ const r = svgNum(attr(item, 'right'), 0);
1513
+ const b = svgNum(attr(item, 'bottom'), 0);
1514
+
1515
+ // `<color>` item:整块底色,直接铺满画布
1516
+ const colorEl = item.children.find((c) => c.name === 'color');
1517
+ if (colorEl) {
1518
+ const paint = this.paintAttrs(attr(colorEl, 'color'), 'fill');
1519
+ if (paint) layers.push(` <rect x="0" y="0" width="${W}" height="${H}"${paint}/>`);
1520
+ else this.warnings.push(`${name}: layer-list 的 <color> item 颜色 ${attr(colorEl, 'color')} 无法解析,该层已跳过`);
1521
+ continue;
1522
+ }
1523
+
1524
+ const inner = item.children.find((c) => c.name === 'shape' || c.name === 'vector');
1525
+ if (!inner) {
1526
+ const ref = attr(item, 'drawable');
1527
+ this.warnings.push(`${name}: layer-list 的 item 引用 ${ref ?? '(未知)'},未内联`);
1528
+ continue;
1529
+ }
1530
+ const sub = inner.name === 'shape'
1531
+ ? this.shapeToSvg(inner, `${name}_layer${layers.length}`)
1532
+ : this.vectorToSvg(inner, `${name}_layer${layers.length}`);
1533
+ const innerBody = sub.replace(/^<svg[^>]*>\n?/, '').replace(/<\/svg>\n?$/, '').trim();
1534
+
1535
+ // 内层自身的坐标系尺寸,用于把 inset 折算成 scale
1536
+ const iw = inner.name === 'vector' ? svgNum(attr(inner, 'viewportWidth'), W) : W;
1537
+ const ih = inner.name === 'vector' ? svgNum(attr(inner, 'viewportHeight'), H) : H;
1538
+ const sw = W - l - r;
1539
+ const sh = H - t - b;
1540
+ const parts: string[] = [];
1541
+ if (l !== 0 || t !== 0) parts.push(`translate(${l},${t})`);
1542
+ if (sw !== iw || sh !== ih) {
1543
+ parts.push(`scale(${Math.round((sw / iw) * 10000) / 10000},${Math.round((sh / ih) * 10000) / 10000})`);
1544
+ }
1545
+ layers.push(parts.length > 0
1546
+ ? ` <g transform="${parts.join(' ')}">\n ${innerBody}\n </g>`
1547
+ : ` ${innerBody}`);
1548
+ }
1549
+
1550
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">\n${layers.join('\n')}\n</svg>\n`;
1551
+ }
1552
+
1553
+ /** `<selector>` → 默认态 SVG。默认态 = 无 state_* 属性的 item,否则取最后一项。 */
1554
+ selectorDefault(root: XmlNode): XmlNode | null {
1555
+ const items = root.children.filter((c) => c.name === 'item');
1556
+ if (items.length === 0) return null;
1557
+ const noState = items.find((it) => !Object.keys(it.attrs).some((k) => k.includes('state_')));
1558
+ return noState ?? items[items.length - 1];
1559
+ }
1560
+
1561
+ /** 分发:读根元素决定转换方式。返回 null 表示不可映射。 */
1562
+ xmlDrawableToSvg(root: XmlNode, name: string): { svg: string; kind: string; notes: string } | null {
1563
+ switch (root.name) {
1564
+ case 'vector':
1565
+ return { svg: this.vectorToSvg(root, name), kind: 'svg conversion', notes: '' };
1566
+ case 'shape':
1567
+ return { svg: this.shapeToSvg(root, name), kind: 'svg conversion', notes: '' };
1568
+ case 'layer-list':
1569
+ return { svg: this.layerListToSvg(root, name), kind: 'svg conversion', notes: 'layer-list flattened into stacked SVG groups' };
1570
+ case 'selector': {
1571
+ const def = this.selectorDefault(root);
1572
+ if (!def) return null;
1573
+ const states = root.children
1574
+ .filter((c) => c.name === 'item')
1575
+ .flatMap((it) => Object.keys(it.attrs).filter((k) => k.includes('state_')).map((k) => k.split(':').pop()!));
1576
+ const notes = `state variants dropped (${[...new Set(states)].join(', ') || 'none'}); implement state handling in ArkUI component code`;
1577
+ const inner = def.children.find((c) => c.name === 'shape' || c.name === 'vector');
1578
+ if (inner) {
1579
+ const out = this.xmlDrawableToSvg(inner, name);
1580
+ return out ? { ...out, notes } : null;
1581
+ }
1582
+ const ref = attr(def, 'drawable');
1583
+ this.warnings.push(`${name}: selector 默认项引用 ${ref ?? '(未知)'},未内联`);
1584
+ return null;
1585
+ }
1586
+ case 'inset': {
1587
+ const inner = root.children.find((c) => c.name === 'shape' || c.name === 'vector' || c.name === 'selector');
1588
+ if (!inner) return null;
1589
+ const out = this.xmlDrawableToSvg(inner, name);
1590
+ return out ? { ...out, notes: 'inset wrapper flattened; inner drawable converted' } : null;
1591
+ }
1592
+ default:
1593
+ return null;
1594
+ }
1595
+ }
1596
+
1597
+ /**
1598
+ * 自适应图标的一层归类成什么(先归类两层,再决定裁切与纯色层尺寸——二者互相依赖)。
1599
+ * - vector:drawable/mipmap 引用、内联 `<vector>`、`<bitmap src=@drawable/vector>` 包装
1600
+ * - bitmap:引用的是位图(带各密度副本的像素尺寸,取最大的一份)
1601
+ * - solid:`@color/` 或字面颜色
1602
+ * - inline:内联的其他 drawable(shape / layer-list…),按原逻辑抽成独立 SVG
1603
+ * - ref:引用到的是 XML 非 vector drawable 或找不到文件,原样 `$media:` 引用
1604
+ */
1605
+ classifyAdaptiveLayer(el: XmlNode): AdaptiveLayer {
1606
+ const ref = attr(el, 'drawable') ?? attr(el, 'color');
1607
+ if (!ref) {
1608
+ const child = el.children.find((c) => c.name);
1609
+ if (!child) return { kind: 'missing' };
1610
+ if (child.name === 'vector') return { kind: 'vector', vec: child, source: 'inline <vector>' };
1611
+ if (child.name === 'bitmap') {
1612
+ const src = attr(child, 'src');
1613
+ const m = src ? /^@(?:[a-zA-Z0-9._]+:)?(drawable|mipmap)\/(.+)$/.exec(src) : null;
1614
+ if (m) return this.classifyMediaRef(m[1], m[2]);
1615
+ }
1616
+ return { kind: 'inline', child };
1617
+ }
1618
+ const media = /^@(?:[a-zA-Z0-9._]+:)?(drawable|mipmap)\/(.+)$/.exec(ref);
1619
+ if (media) return this.classifyMediaRef(media[1], media[2]);
1620
+ const colorRef = /^@(?:[a-zA-Z0-9._]+:)?color\/(.+)$/.exec(ref);
1621
+ const literal = normalizeColor(ref);
1622
+ if (colorRef || literal) {
1623
+ return { kind: 'solid', ref, colorName: colorRef ? colorRef[1] : null, hex: literal ?? this.resolveColor(ref) };
1624
+ }
1625
+ return { kind: 'unknown', ref };
1626
+ }
1627
+
1628
+ /** `@drawable/x` / `@mipmap/x` 只在**它自己的**类型目录里找(同名 mipmap 不能顶替 drawable)。 */
1629
+ classifyMediaRef(type: string, resName: string): AdaptiveLayer {
1630
+ const vec = this.findResXml(type, resName, 'vector');
1631
+ if (vec) return { kind: 'vector', vec, source: `@${type}/${resName}`, resName };
1632
+ const variants = this.findBitmapVariants(type, resName);
1633
+ if (variants.length > 0) {
1634
+ const best = variants.reduce((a, b) => (b.w * b.h > a.w * a.h ? b : a));
1635
+ return { kind: 'bitmap', resName, w: best.w, h: best.h };
1636
+ }
1637
+ return { kind: 'ref', resName };
1638
+ }
1639
+
1640
+ /** `<adaptive-icon>` → layered-image JSON(+ 必要时生成纯色层、矢量图层安全区裁切副本)。 */
1641
+ adaptiveIcon(root: XmlNode, name: string, qdir: string, androidPath: string): void {
1642
+ const out: Record<string, string> = {};
1643
+ const sourceCategory = this.sourceCategory(name);
1644
+ const extraTargets: Array<{ target: string; kind: string; notes: string }> = [];
1645
+
1646
+ const layers = (['background', 'foreground'] as const)
1647
+ .map((layer) => {
1648
+ const el = root.children.find((c) => c.name === layer);
1649
+ return el ? { layer, el, cls: this.classifyAdaptiveLayer(el) } : null;
1650
+ })
1651
+ .filter((x): x is { layer: 'background' | 'foreground'; el: XmlNode; cls: AdaptiveLayer } => x !== null);
1652
+
1653
+ // HarmonyOS 桌面按各图层**自身尺寸**合成、不拉伸,也不做 Android 的 72/108 安全区裁切
1654
+ // (WeatherApp 2026-10-22 实机复现:108px 纯色 PNG 配 1024 矢量前景 → 左上角小三角)。
1655
+ // 所以各层必须同尺寸、同比例:
1656
+ // - 有位图层时,以位图像素尺寸为准;矢量层与纯色层都对齐到它。位图本身无法改 viewBox,
1657
+ // 整图显示(即 HarmonyOS 不裁切),矢量层也就**不裁切**,否则两层相对比例偏离 Android。
1658
+ // - 只有矢量 + 纯色时,矢量层裁到中间 2/3,纯色层取第一个矢量层的尺寸。
1659
+ // - 两层都是纯色(或无可参照)时,纯色层取 1024(DevEco 模板图层尺寸)。
1660
+ const bitmap = layers.find((l) => l.cls.kind === 'bitmap')?.cls as Extract<AdaptiveLayer, { kind: 'bitmap' }> | undefined;
1661
+ const firstVec = layers.find((l) => l.cls.kind === 'vector')?.cls as Extract<AdaptiveLayer, { kind: 'vector' }> | undefined;
1662
+ const crop = !bitmap;
1663
+ const target: { w: number; h: number } | null = bitmap
1664
+ ? { w: bitmap.w, h: bitmap.h }
1665
+ : firstVec
1666
+ ? {
1667
+ w: svgNum(attr(firstVec.vec, 'width'), svgNum(attr(firstVec.vec, 'viewportWidth'), 108)),
1668
+ h: svgNum(attr(firstVec.vec, 'height'), svgNum(attr(firstVec.vec, 'viewportHeight'), 108)),
1669
+ }
1670
+ : null;
1671
+ const solidFormat: 'svg' | 'png' = bitmap || !firstVec ? 'png' : 'svg';
1672
+ const solidSize = target ?? { w: 1024, h: 1024 };
1673
+
1674
+ for (const { layer, cls } of layers) {
1675
+ switch (cls.kind) {
1676
+ case 'missing':
1677
+ this.warnings.push(`${androidPath}: layered-image 的 ${layer} 层既无 drawable/color 属性也无内联子元素,已省略该层`);
1678
+ break;
1679
+ case 'unknown':
1680
+ this.warnings.push(`${androidPath}: layered-image 的 ${layer} 引用 ${cls.ref} 无法识别`);
1681
+ break;
1682
+ case 'bitmap':
1683
+ case 'ref':
1684
+ out[layer] = `$media:${cls.resName}`;
1685
+ break;
1686
+ case 'inline':
1687
+ this.inlineAdaptiveLayer(cls.child, layer, name, qdir, androidPath, sourceCategory, out, extraTargets);
1688
+ break;
1689
+ case 'vector': {
1690
+ // 另出一份专供 layered-image 的 SVG(裁切和/或对齐尺寸);被引用的原 drawable 照常转换,
1691
+ // 页面里可能直接引用它,不能动。内联 vector 本就要单独落盘,同样走这里。
1692
+ const layerName = `${name}_${layer}_layer`;
1693
+ const size = bitmap ? target! : undefined;
1694
+ this.write(path.join(qdir, 'media', `${layerName}.svg`),
1695
+ this.vectorToSvg(cls.vec, layerName, { adaptiveSafeZone: crop, size }));
1696
+ this.counts.safeZoneLayers++;
1697
+ out[layer] = `$media:${layerName}`;
1698
+ const how = [
1699
+ crop ? 'cropped to Android adaptive-icon 72/108 safe zone (HarmonyOS layered-image shows the full layer)' : '',
1700
+ size ? `sized ${size.w}x${size.h} to match bitmap layer @${bitmap!.resName}; not cropped because the bitmap layer cannot be` : '',
1701
+ ].filter(Boolean).join('; ');
1702
+ extraTargets.push({
1703
+ target: `resources/${qdir}/media/${layerName}.svg`,
1704
+ kind: 'svg conversion',
1705
+ notes: `layer vector ${cls.source} ${how}`,
1706
+ });
1707
+ break;
1708
+ }
1709
+ case 'solid': {
1710
+ if (!cls.hex) {
1711
+ const ph = cls.colorName ?? `${name}_${layer}`;
1712
+ this.warnings.push(`${androidPath}: layered-image 的 ${layer} 颜色 ${cls.ref} 无法解析,使用占位引用`);
1713
+ out[layer] = `$media:${ph}_bg`;
1714
+ break;
1715
+ }
1716
+ out[layer] = `$media:${this.solidLayer(cls.colorName ?? `${name}_${layer}`, cls.hex, solidFormat, solidSize, qdir, extraTargets)}`;
1717
+ break;
1718
+ }
1719
+ }
1720
+ }
1721
+ if (bitmap) {
1722
+ this.counts.uncroppedBitmapIcons++;
1723
+ this.warnings.push(
1724
+ `${androidPath}: layered-image 含位图层 @${bitmap.resName}(${bitmap.w}x${bitmap.h}),HarmonyOS 整层显示、不做 72/108 安全区裁切,` +
1725
+ '图标内容会比 Android 小一圈;如需一致,请按中间 2/3 裁切该位图后替换');
1726
+ }
1727
+
1728
+ // monochrome 不进 JSON,但它引用的 drawable 仍是真实资源,按普通 drawable 处理
1729
+ const mono = root.children.find((c) => c.name === 'monochrome');
1730
+ if (mono) {
1731
+ this.warnings.push(`${androidPath}: monochrome 层无 HarmonyOS layered-image 等价物,已从 JSON 省略(其引用的 drawable 仍按普通资源转换)`);
1732
+ }
1733
+
1734
+ const jsonName = `${name}_layered_image.json`;
1735
+ this.write(path.join(qdir, 'media', jsonName), `${JSON.stringify({ 'layered-image': out }, null, 2)}\n`);
1736
+ this.counts.layeredImages++;
1737
+
1738
+ this.inv({
1739
+ androidResourcePath: androidPath, androidResourceName: name,
1740
+ function: 'Adaptive launcher icon', screens: 'Launcher', sourceCategory,
1741
+ typeCategory: 'mipmap', status: 'converted',
1742
+ });
1743
+ this.map({
1744
+ androidResourcePath: androidPath, androidScreens: 'Launcher',
1745
+ androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1746
+ harmonyTarget: `resources/${qdir}/media/${jsonName}`, mappingKind: 'layered-image conversion',
1747
+ });
1748
+ for (const t of extraTargets) {
1749
+ this.map({
1750
+ androidResourcePath: androidPath, androidScreens: 'Launcher',
1751
+ androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1752
+ harmonyTarget: t.target, mappingKind: t.kind, notes: t.notes,
1753
+ });
1754
+ }
1755
+ }
1756
+
1757
+ /**
1758
+ * 落一个纯色层,返回其 `$media` 名。`$media` 名在模块内全局唯一(与 qdir 无关),
1759
+ * 因此按「名字 → 规格」去重:同名同规格复用;同名不同规格(另一个图标配的是不同颜色/尺寸/格式的
1760
+ * 图层)换成 `<名>_bg_<rgb>_<w>x<h>`,绝不复用规格不符的文件。每个 qdir 各自落盘。
1761
+ */
1762
+ solidLayer(
1763
+ colorName: string, hex: string, format: 'svg' | 'png', size: { w: number; h: number },
1764
+ qdir: string, extraTargets: Array<{ target: string; kind: string; notes: string }>,
1765
+ ): string {
1766
+ const spec = `${format}:${size.w}x${size.h}:${hex}`;
1767
+ let media = `${colorName}_bg`;
1768
+ const prev = this.solidLayerSpecs.get(media);
1769
+ // 换名必须把规格的每一维都带上(含颜色),否则同名同尺寸、颜色不同的两层会撞到同一个文件
1770
+ if (prev !== undefined && prev !== spec) {
1771
+ media = `${colorName}_bg_${hex.replace(/^#/, '').toLowerCase()}_${size.w}x${size.h}${format === 'svg' ? '_svg' : ''}`;
1772
+ }
1773
+ this.solidLayerSpecs.set(media, spec);
1774
+
1775
+ const file = `${media}.${format}`;
1776
+ const rel = path.join(qdir, 'media', file);
1777
+ if (this.writtenSolidLayers.has(rel)) return media;
1778
+ this.writtenSolidLayers.add(rel);
1779
+ // 转换器直接写进工程 resources/,不清旧产物。旧版纯色层恒为 PNG,新版可能出 SVG:
1780
+ // 在旧工程上重跑会留下 x.png + x.svg 两个文件同叫 $media:x。删掉上次运行残留的另一扩展名文件;
1781
+ // 本次运行自己写的(真实同名冲突)不动,只告警。
1782
+ const other = path.join(qdir, 'media', `${media}.${format === 'svg' ? 'png' : 'svg'}`);
1783
+ const otherFull = path.join(this.outRoot, other);
1784
+ if (this.writtenThisRun.has(path.normalize(other))) {
1785
+ this.warnings.push(`${other}: 与纯色层 ${file} 同名(同一个 $media:${media}),需人工处理重名`);
1786
+ } else if (!this.dryRun && fs.existsSync(otherFull)) {
1787
+ fs.rmSync(otherFull);
1788
+ this.warnings.push(`${other}: 上次转换残留的同名纯色层,已删除(本次产出 ${file},避免 $media:${media} 重名)`);
1789
+ }
1790
+ this.write(rel, format === 'svg' ? solidSvg(hex, size.w, size.h) : solidPng(hex, size.w, size.h));
1791
+ this.counts.solidLayersGenerated++;
1792
+ extraTargets.push({
1793
+ target: `resources/${qdir}/media/${file}`,
1794
+ kind: 'generated media',
1795
+ notes: `solid-color layer generated (${format.toUpperCase()} ${size.w}x${size.h}, matches the other layer) because layered-image accepts only $media references`,
1796
+ });
1797
+ return media;
1798
+ }
1799
+
1800
+ /**
1801
+ * `<adaptive-icon>` 某一层内联了非 vector 的子 drawable(shape / layer-list…)时的处理。
1802
+ * 把内联图形单独转成一个媒体文件,再用 `$media:` 引用它——这是 layered-image 唯一接受的形式。
1803
+ * 转不出来的情况登记为 unmappable,绝不静默丢层。
1804
+ */
1805
+ inlineAdaptiveLayer(
1806
+ child: XmlNode,
1807
+ layer: 'background' | 'foreground',
1808
+ name: string,
1809
+ qdir: string,
1810
+ androidPath: string,
1811
+ sourceCategory: string,
1812
+ out: Record<string, string>,
1813
+ extraTargets: Array<{ target: string; kind: string; notes: string }>,
1814
+ ): void {
1815
+ const inlineName = `${name}_${layer}`;
1816
+ const conv = this.xmlDrawableToSvg(child, inlineName);
1817
+ if (!conv) {
1818
+ this.counts.unmappable++;
1819
+ this.warnings.push(`${androidPath}: layered-image 的 ${layer} 层内联 <${child.name}> 无静态 SVG 等价物,该层未产出媒体文件`);
1820
+ this.map({
1821
+ androidResourcePath: `${androidPath}#${layer}`, androidScreens: 'Launcher',
1822
+ androidSourceCategory: sourceCategory, androidTypeCategory: 'mipmap',
1823
+ harmonyTarget: 'N/A', mappingKind: 'unmappable',
1824
+ notes: `inline <${child.name}> in <${layer}> has no static SVG equivalent`,
1825
+ });
1826
+ return;
1827
+ }
1828
+
1829
+ this.write(path.join(qdir, 'media', `${inlineName}.svg`), conv.svg);
1830
+ this.counts.svgConverted++;
1831
+ out[layer] = `$media:${inlineName}`;
1832
+ extraTargets.push({
1833
+ target: `resources/${qdir}/media/${inlineName}.svg`,
1834
+ kind: conv.kind,
1835
+ notes: `inline <${child.name}> in <${layer}> extracted to its own media file; layered-image accepts only $media references${conv.notes ? `; ${conv.notes}` : ''}`,
1836
+ });
1837
+ }
1838
+
1839
+ // ── 文件类资源 ──
1840
+
1841
+ processFileResource(relFile: string, type: string, qdir: string): void {
1842
+ const base = path.basename(relFile);
1843
+ const ext = path.extname(base).toLowerCase();
1844
+ const androidPath = `res/${relFile}`;
1845
+ const resName = base.replace(/\.9\.png$/i, '').replace(/\.[^.]+$/, '');
1846
+ const sourceCategory = this.sourceCategory(resName);
1847
+
1848
+ const record = (target: string, kind: string, status: string, notes = '', fn = ''): void => {
1849
+ this.inv({
1850
+ androidResourcePath: androidPath, androidResourceName: resName,
1851
+ function: fn || `${type} resource`, sourceCategory, typeCategory: type,
1852
+ status, notes,
1853
+ });
1854
+ this.map({
1855
+ androidResourcePath: androidPath, androidSourceCategory: sourceCategory,
1856
+ androidTypeCategory: type, harmonyTarget: target, mappingKind: kind, notes,
1857
+ });
1858
+ };
1859
+
1860
+ if (type === 'font') {
1861
+ if (FONT_EXT.has(ext)) {
1862
+ const target = path.join('rawfile', 'fonts', base);
1863
+ this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1864
+ this.counts.fontCopied++;
1865
+ record(`resources/${target.split(path.sep).join('/')}`, 'direct copy', 'converted', '', 'Font resource');
1866
+ } else {
1867
+ this.counts.unmappable++;
1868
+ record('N/A', 'unmappable', 'unmappable', 'font family XML has no HarmonyOS equivalent', 'Font family definition');
1869
+ }
1870
+ return;
1871
+ }
1872
+
1873
+ if (type === 'raw') {
1874
+ const target = path.join('rawfile', base);
1875
+ this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1876
+ this.counts.rawCopied++;
1877
+ record(`resources/rawfile/${base}`, 'direct copy', 'converted', '', 'Raw file resource');
1878
+ return;
1879
+ }
1880
+
1881
+ if (type === 'xml') {
1882
+ const target = path.join(qdir, 'profile', base);
1883
+ this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1884
+ this.counts.profileCopied++;
1885
+ record(`resources/${qdir}/profile/${base}`, 'direct copy', 'converted', '', 'Configuration XML');
1886
+ return;
1887
+ }
1888
+
1889
+ // drawable / mipmap
1890
+ if (/\.9\.png$/i.test(base)) {
1891
+ const renamed = base.replace(/\.9\.png$/i, '_9.png');
1892
+ const target = path.join(qdir, 'media', renamed);
1893
+ if (!this.claimTarget(target, relFile, androidPath, type)) return;
1894
+ this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1895
+ this.counts.ninePatchRenamed++;
1896
+ this.counts.mediaCopied++;
1897
+ record(
1898
+ `resources/${qdir}/media/${renamed}`, 'rename', 'converted',
1899
+ 'nine-patch stretch behavior is lost; reimplement with a resizable Image in ArkUI',
1900
+ 'Nine-patch image',
1901
+ );
1902
+ return;
1903
+ }
1904
+
1905
+ if (IMAGE_EXT.has(ext)) {
1906
+ const target = path.join(qdir, 'media', base);
1907
+ if (!this.claimTarget(target, relFile, androidPath, type)) return;
1908
+ this.write(target, fs.readFileSync(path.join(this.resDir, relFile)));
1909
+ this.counts.mediaCopied++;
1910
+ record(`resources/${qdir}/media/${base}`, 'direct copy', 'converted', '', 'Image resource');
1911
+ return;
1912
+ }
1913
+
1914
+ if (ext === '.xml') {
1915
+ const root = parseXml(fs.readFileSync(path.join(this.resDir, relFile), 'utf8'));
1916
+
1917
+ if (root.name === 'adaptive-icon') {
1918
+ this.adaptiveIcon(root, resName, qdir, androidPath);
1919
+ return;
1920
+ }
1921
+
1922
+ const out = this.xmlDrawableToSvg(root, resName);
1923
+ if (!out) {
1924
+ this.counts.unmappable++;
1925
+ record(
1926
+ 'N/A', 'unmappable', 'unmappable',
1927
+ `<${root.name}> has no static SVG equivalent (runtime behavior)`,
1928
+ `${root.name} drawable`,
1929
+ );
1930
+ return;
1931
+ }
1932
+
1933
+ const target = path.join(qdir, 'media', `${resName}.svg`);
1934
+ if (!this.claimTarget(target, relFile, androidPath, type)) return;
1935
+ this.write(target, out.svg);
1936
+ this.counts.svgConverted++;
1937
+ record(`resources/${qdir}/media/${resName}.svg`, out.kind, 'converted', out.notes, `${root.name} drawable`);
1938
+ return;
1939
+ }
1940
+
1941
+ this.counts.unmappable++;
1942
+ record('N/A', 'unmappable', 'unmappable', `unhandled extension: ${ext}`);
1943
+ }
1944
+
1945
+ // ── 目录遍历 ──
1946
+
1947
+ run(): void {
1948
+ const dirs = fs.readdirSync(this.resDir, { withFileTypes: true })
1949
+ .filter((d) => d.isDirectory())
1950
+ .map((d) => d.name)
1951
+ .sort();
1952
+
1953
+ // 第一遍只处理 values:SVG 转换需要 color / dimen 查找表就位。
1954
+ // 目录名字典序会让 drawable 排在 values 前面,所以必须分两遍。
1955
+ for (const dirName of dirs) {
1956
+ const { type, plan } = planQualifiers(dirName);
1957
+ if (type !== 'values' || plan.skip) continue;
1958
+ for (const f of fs.readdirSync(path.join(this.resDir, dirName)).sort()) {
1959
+ if (!f.endsWith('.xml')) continue;
1960
+ this.qualifierUse.push({ android: dirName, harmony: `${plan.dir}/element` });
1961
+ this.processValuesFile(`${dirName}/${f}`, plan.dir);
1962
+ }
1963
+ }
1964
+
1965
+ for (const dirName of dirs) {
1966
+ const { type, plan } = planQualifiers(dirName);
1967
+ const files = fs.readdirSync(path.join(this.resDir, dirName)).sort();
1968
+
1969
+ if (plan.skip) {
1970
+ this.counts.skippedQualifierDirs++;
1971
+ for (const f of files) {
1972
+ this.counts.unmappable++;
1973
+ this.inv({
1974
+ androidResourcePath: `res/${dirName}/${f}`, androidResourceName: f.replace(/\.[^.]+$/, ''),
1975
+ function: `${type} resource`, sourceCategory: this.sourceCategory(f),
1976
+ typeCategory: type, status: 'unmapped', notes: plan.skip,
1977
+ });
1978
+ this.map({
1979
+ androidResourcePath: `res/${dirName}/${f}`, androidTypeCategory: type,
1980
+ androidSourceCategory: this.sourceCategory(f),
1981
+ mappingKind: 'unmappable', notes: plan.skip,
1982
+ });
1983
+ }
1984
+ continue;
1985
+ }
1986
+
1987
+ if (type === 'values') continue; // 已在第一遍处理
1988
+
1989
+ if (UNMAPPABLE_TYPES.has(type)) {
1990
+ for (const f of files) {
1991
+ const name = f.replace(/\.[^.]+$/, '');
1992
+ // 过滤模式:只记录白名单内的资源
1993
+ if (this.filterSet && !this.filterSet.has(`${type}/${name}`)) continue;
1994
+ this.counts.unmappable++;
1995
+ this.inv({
1996
+ androidResourcePath: `res/${dirName}/${f}`, androidResourceName: name,
1997
+ function: `${type} resource`, sourceCategory: this.sourceCategory(name),
1998
+ typeCategory: type, status: 'unmappable',
1999
+ notes: `Android ${type} has no HarmonyOS equivalent (ArkUI is declarative)`,
2000
+ });
2001
+ this.map({
2002
+ androidResourcePath: `res/${dirName}/${f}`, androidTypeCategory: type,
2003
+ androidSourceCategory: this.sourceCategory(name), mappingKind: 'unmappable',
2004
+ notes: `Android ${type} has no HarmonyOS equivalent`,
2005
+ });
2006
+ }
2007
+ continue;
2008
+ }
2009
+
2010
+ for (const f of files) {
2011
+ const name = f.replace(/\.9\.png$/i, '').replace(/\.[^.]+$/, '');
2012
+ // 过滤模式:只处理白名单内的资源
2013
+ if (this.filterSet && !this.filterSet.has(`${type}/${name}`)) continue;
2014
+ this.qualifierUse.push({ android: dirName, harmony: `${plan.dir}/media` });
2015
+ this.processFileResource(`${dirName}/${f}`, type, plan.dir);
2016
+ }
2017
+ }
2018
+
2019
+ this.resolveReferences();
2020
+ this.flushElements();
2021
+ }
2022
+ }
2023
+
2024
+ // ─────────────────────────────────────────────
2025
+ // Markdown 生成
2026
+ // ─────────────────────────────────────────────
2027
+
2028
+ /** markdown 表格单元格转义:`|` 会断表,换行会断行。 */
2029
+ function cell(v: string): string {
2030
+ return (v ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').trim() || ' ';
2031
+ }
2032
+
2033
+ interface DocContext {
2034
+ apkPath: string;
2035
+ resSource: string;
2036
+ resDir: string;
2037
+ /** Android 源工程根目录(--android-project),与 resDir 是两个不同的路径。 */
2038
+ androidProjectDir: string;
2039
+ harmonyDir: string;
2040
+ appModule: string;
2041
+ androidCommit: string;
2042
+ iconSnapshotRef: string;
2043
+ buildResult: string;
2044
+ /** code_vector_icons.ts 的 --json 产物(可选) */
2045
+ icons: {
2046
+ counts?: Record<string, number>;
2047
+ icons?: Array<Record<string, unknown>>;
2048
+ ref?: string;
2049
+ /** dex 引用绝大多数无源码出处 ⇒ material-icons-extended 整包未被 R8 收缩 */
2050
+ libraryLikelyUnshrunk?: boolean;
2051
+ } | null;
2052
+ /** svg_fidelity_check.ts 的 --json 产物(可选) */
2053
+ fidelity: { findings?: Array<Record<string, string>>; counts?: Record<string, number> } | null;
2054
+ /** app_identity.ts 的 --json 产物(可选) */
2055
+ appIdentity: {
2056
+ android?: { icon?: string; roundIcon?: string; label?: string };
2057
+ resolved?: {
2058
+ appIcon?: string | null;
2059
+ appLabel?: string | null;
2060
+ labelValue?: string | null;
2061
+ labelQualifiers?: string[];
2062
+ };
2063
+ warnings?: string[];
2064
+ } | null;
2065
+ }
2066
+
2067
+ /** 文档生成所需的全部数据。Converter 结构上即满足,records JSON 也能反序列化成它。 */
2068
+ interface RecordsBundle {
2069
+ counts: Record<string, number>;
2070
+ warnings: string[];
2071
+ conflicts: string[];
2072
+ resolutions: ResolutionRecord[];
2073
+ inventory: InventoryRecord[];
2074
+ mappings: MappingRecord[];
2075
+ qualifierUse: Array<{ android: string; harmony: string }>;
2076
+ }
2077
+
2078
+ class DocWriter {
2079
+ conv: RecordsBundle;
2080
+ ctx: DocContext;
2081
+
2082
+ constructor(conv: RecordsBundle, ctx: DocContext) {
2083
+ this.conv = conv;
2084
+ this.ctx = ctx;
2085
+ }
2086
+
2087
+ private counts(): Record<string, number> {
2088
+ return this.conv.counts;
2089
+ }
2090
+
2091
+ /** 按某个字段聚合计数,用于报告里的概览表。 */
2092
+ private groupBy<T>(rows: T[], key: (r: T) => string): Array<[string, number]> {
2093
+ const m = new Map<string, number>();
2094
+ for (const r of rows) m.set(key(r), (m.get(r ? key(r) : '') ?? 0) + 1);
2095
+ return [...m].sort((a, b) => b[1] - a[1]);
2096
+ }
2097
+
2098
+ /**
2099
+ * 转换报告:面向人阅读,因此用**聚合**表格,不逐条罗列 10 万级资源。
2100
+ * 逐条审计由 resource_mapping 文档承担(那份有「绝不省略」的硬要求)。
2101
+ */
2102
+ report(): string {
2103
+ const c = this.counts();
2104
+ const o: string[] = [];
2105
+ const p = (s = ''): void => { o.push(s); };
2106
+
2107
+ p('# Android to HarmonyOS Resource Conversion Report');
2108
+ p();
2109
+ p('## Resource Source');
2110
+ p(`- APK: ${this.ctx.apkPath}`);
2111
+ p('- Decode result: Success');
2112
+ p(`- Resource source: ${this.ctx.resSource}`);
2113
+ p(`- Resource source path: ${this.ctx.resDir}`);
2114
+ p(`- Application module: ${this.ctx.appModule}`);
2115
+ p(`- Android final commit: ${this.ctx.androidCommit}`);
2116
+ p(`- Converter: scripts/a2h_resource_convert.ts (canonical implementation)`);
2117
+ p();
2118
+
2119
+ p('## Summary');
2120
+ p(`- Values entries converted: ${c.valuesEntries}`);
2121
+ p(`- Media files copied: ${c.mediaCopied} (nine-patch renamed: ${c.ninePatchRenamed})`);
2122
+ p(`- XML drawables converted to SVG: ${c.svgConverted}`);
2123
+ p(`- Adaptive icons converted to layered-image JSON: ${c.layeredImages}`);
2124
+ p(`- Adaptive-icon layer SVGs (safe-zone crop / size match): ${c.safeZoneLayers}; solid-color layers generated: ${c.solidLayersGenerated}`);
2125
+ if (c.uncroppedBitmapIcons > 0) {
2126
+ // 最常见的组合(位图前景 + 纯色背景)恰好落在这里,单条 warning 容易被淹没,摘要里单列
2127
+ p(`- **Known limitation** — adaptive icons with a bitmap layer, NOT cropped to the 72/108 safe zone: ${c.uncroppedBitmapIcons}. ` +
2128
+ 'They render ~1/3 smaller than on Android; crop the bitmap to its center 2/3 by hand if they must match.');
2129
+ }
2130
+ p(`- Raw / font / profile files: ${c.rawCopied} / ${c.fontCopied} / ${c.profileCopied}`);
2131
+ p(`- Unmappable (no HarmonyOS equivalent): ${c.unmappable}`);
2132
+ p(`- Directories skipped (unsupported qualifier): ${c.skippedQualifierDirs}`);
2133
+ p(`- References resolved: ${c.referencesResolved} (system resources: ${c.systemReferencesResolved})`);
2134
+ p(`- Fallback values applied: ${c.fallbacksApplied}`);
2135
+ p(`- SVG paint colors that could not be resolved: ${c.unresolvedPaint}`);
2136
+ p(`- HarmonyOS target collisions resolved: ${c.mediaTargetCollisions}`);
2137
+ p(`- Failed: ${c.failed}`);
2138
+ if (this.ctx.icons?.counts) {
2139
+ const ic = this.ctx.icons.counts;
2140
+ p(`- Code-defined icon references found (dex): ${ic.referencesFound ?? 0}`);
2141
+ p(`- Code-defined icons resolved / unresolved: ${ic.resolved ?? 0} / ${ic.unresolved ?? 0}`);
2142
+ p(`- Code-defined icon media files written: ${ic.mediaFilesWritten ?? 0}`);
2143
+ p(`- Code-defined icons screen-attributed / Unknown: ${ic.screenAttributed ?? 0} / ${ic.screenUnknown ?? 0}`);
2144
+ if (this.ctx.icons.libraryLikelyUnshrunk) {
2145
+ // 绝大多数引用没有源码出处 ⇒ material-icons-extended 整包被编进了 dex(R8 没收缩)。
2146
+ // 这时候写出来的图标数量远超应用真正用到的,读者必须知道,否则会以为 media/ 里都是有用资产。
2147
+ p('- ⚠️ dex 中的图标引用绝大多数无源码出处,判定为 `material-icons-extended` 整包未被 R8 收缩:'
2148
+ + '写出的图标数量远大于应用实际使用量,可按 `--attributed-only` 重跑以只保留有源码归属的图标。');
2149
+ }
2150
+ p(`- Material Icons snapshot ref: ${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}`);
2151
+ } else {
2152
+ p('- Code-defined vector icons: not analysed (run scripts/code_vector_icons.ts)');
2153
+ }
2154
+ // 应用图标 / 应用名。这几行 a2h-ui-transfer 会 grep 作为 App-identity gate,
2155
+ // 标签文字不要改。
2156
+ const idn = this.ctx.appIdentity;
2157
+ if (idn) {
2158
+ const r = idn.resolved ?? {};
2159
+ // 原因要按字段挑,不能一律取 warnings[0]:图标的告警贴到应用名那行上,
2160
+ // 读者会照着错的原因去排查。
2161
+ const why = (re: RegExp): string => {
2162
+ const hit = (idn.warnings ?? []).find((w) => re.test(w));
2163
+ return hit ? `未改写(${hit})` : '未改写';
2164
+ };
2165
+ p(`- App icon: ${idn.android?.icon || '(none)'} → ${r.appIcon ?? why(/图标/)}`);
2166
+ p(`- App name: ${idn.android?.label || '(none)'} → ${r.appLabel ?? why(/应用名|label/)}`
2167
+ + (r.labelValue != null ? ` = "${r.labelValue}"` : ''));
2168
+ p(`- App name locales written to AppScope: ${(r.labelQualifiers ?? []).join(', ') || '(none)'}`);
2169
+ p(`- App identity gate: ${r.appIcon && r.appLabel ? 'PASS' : 'FAIL(应用图标或应用名未落地)'}`);
2170
+ } else {
2171
+ p('- App identity (launcher icon + app name): not run (run scripts/app_identity.ts)');
2172
+ }
2173
+ p();
2174
+
2175
+ p('## Conversion Details');
2176
+ p();
2177
+ p('### Converted Resources by Type');
2178
+ p('| Android Type | Mapping Kind | Count |');
2179
+ p('|---|---|---|');
2180
+ const conv = this.conv.mappings.filter((m) => m.mappingKind !== 'unmappable');
2181
+ for (const [k, n] of this.groupBy(conv, (m) => `${m.androidTypeCategory}|${m.mappingKind}`)) {
2182
+ const [t, kind] = k.split('|');
2183
+ p(`| ${cell(t)} | ${cell(kind)} | ${n} |`);
2184
+ }
2185
+ p();
2186
+
2187
+ p('### Qualifier Mappings Applied');
2188
+ p('| Android Qualifier Dir | HarmonyOS Target Dir | Files |');
2189
+ p('|---|---|---|');
2190
+ for (const [k, n] of this.groupBy(this.conv.qualifierUse, (q) => `${q.android}|${q.harmony}`)) {
2191
+ const [a, h] = k.split('|');
2192
+ p(`| ${cell(a)} | ${cell(h)} | ${n} |`);
2193
+ }
2194
+ p();
2195
+
2196
+ p('### Resource Reference Resolution');
2197
+ p('References resolved to concrete values. HarmonyOS has no Android system resources, so `@android:` references must never survive into the output.');
2198
+ p();
2199
+ p('| Resource File | Name | Reference | Resolved Value | Chain | Kind |');
2200
+ p('|---|---|---|---|---|---|');
2201
+ for (const r of this.conv.resolutions) {
2202
+ p(`| ${cell(r.file)} | ${cell(r.name)} | ${cell(r.reference)} | ${cell(r.resolved)} | ${cell(r.chain)} | ${r.kind} |`);
2203
+ }
2204
+ p();
2205
+
2206
+ p('### Unmappable Resources (by reason)');
2207
+ p('| Reason | Count |');
2208
+ p('|---|---|');
2209
+ for (const [k, n] of this.groupBy(this.conv.mappings.filter((m) => m.mappingKind === 'unmappable'), (m) => m.notes || '(unspecified)')) {
2210
+ p(`| ${cell(k)} | ${n} |`);
2211
+ }
2212
+ p();
2213
+
2214
+ if (this.ctx.fidelity) {
2215
+ const f = this.ctx.fidelity.findings ?? [];
2216
+ p('### Vector Fidelity Issues');
2217
+ if (f.length === 0) {
2218
+ p('`scripts/svg_fidelity_check.ts` reported no findings.');
2219
+ } else {
2220
+ p('| File | Rule | Severity | Android evidence | SVG evidence |');
2221
+ p('|---|---|---|---|---|');
2222
+ for (const x of f) {
2223
+ p(`| ${cell(x.name)} | ${x.rule} | ${x.severity} | ${cell(x.androidEvidence)} | ${cell(x.svgEvidence)} |`);
2224
+ }
2225
+ }
2226
+ p();
2227
+ }
2228
+
2229
+ if (this.ctx.icons?.icons) {
2230
+ p('### Code-Defined Vector Icons');
2231
+ p(`Artwork source: \`${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}\``);
2232
+ p();
2233
+ p('| Compose Reference | Material Name | Style | HarmonyOS Target | Host Screen(s) | Notes |');
2234
+ p('|---|---|---|---|---|---|');
2235
+ for (const i of this.ctx.icons.icons) {
2236
+ const screens = Array.isArray(i.screens) ? (i.screens as string[]).join(', ') : String(i.screens ?? 'Unknown');
2237
+ const notes = Array.isArray(i.notes) ? (i.notes as string[]).join('; ') : '';
2238
+ p(`| ${cell(String(i.compose))} | ${cell(String(i.material))} | ${cell(String(i.style))} | ${cell(i.resolved ? `base/media/${i.media}` : 'N/A')} | ${cell(screens)} | ${cell(notes || String(i.reason ?? ''))} |`);
2239
+ }
2240
+ p();
2241
+ }
2242
+
2243
+ // 告警按「首个冒号前的模式」归类并限量展示:报告要能读完,
2244
+ // 逐条明细在 records JSON 的 warnings 字段里,一条不少。
2245
+ p('### Warnings');
2246
+ if (this.conv.warnings.length === 0) {
2247
+ p('None.');
2248
+ } else {
2249
+ const PER_KIND = 5;
2250
+ const byKind = new Map<string, string[]>();
2251
+ for (const w of this.conv.warnings) {
2252
+ const kind = w.includes(': ') ? w.slice(w.indexOf(': ') + 2).split(/[((]/)[0].trim() : w;
2253
+ const list = byKind.get(kind) ?? [];
2254
+ list.push(w);
2255
+ byKind.set(kind, list);
2256
+ }
2257
+ p(`共 ${this.conv.warnings.length} 条,按类型归并如下;逐条明细见 records JSON 的 \`warnings\` 字段。`);
2258
+ p();
2259
+ for (const [kind, list] of [...byKind].sort((a, b) => b[1].length - a[1].length)) {
2260
+ p(`- **${cell(kind)}** — ${list.length} 条`);
2261
+ for (const w of list.slice(0, PER_KIND)) p(` - ${w}`);
2262
+ if (list.length > PER_KIND) p(` - …其余 ${list.length - PER_KIND} 条见 records JSON`);
2263
+ }
2264
+ }
2265
+ p();
2266
+
2267
+ p('### Verification Results');
2268
+ p(`- All resources accounted for: Yes (${this.conv.inventory.length} inventory rows)`);
2269
+ p(`- Unresolved references remaining in output: 0 (fallbacks applied: ${c.fallbacksApplied}, all recorded above)`);
2270
+ p(`- Name conflicts (last definition wins): ${this.conv.conflicts.length}`);
2271
+ // `counts` 只记录出现过的规则/严重级,全部通过时它是空对象——不能据此判断「没跑」。
2272
+ p(this.ctx.fidelity
2273
+ ? `- Vector fidelity errors: ${this.ctx.fidelity.counts?.error ?? 0} (warnings: ${this.ctx.fidelity.counts?.warn ?? 0})`
2274
+ : '- Vector fidelity errors: not run');
2275
+ p();
2276
+ return o.join('\n');
2277
+ }
2278
+
2279
+ /**
2280
+ * 资源映射文档(中文)。硬要求:**绝不静默省略任何一条 Android 资源**,
2281
+ * `values` 必须条目级。因此这份文档天然很大(实测最大约 23 MB),
2282
+ * 不做抽样、不做聚合——那是转换报告的职责。
2283
+ */
2284
+ mapping(): string {
2285
+ const c = this.counts();
2286
+ const o: string[] = [];
2287
+ const p = (s = ''): void => { o.push(s); };
2288
+
2289
+ p('# Android 资源 ↔ HarmonyOS 资源映射');
2290
+ p();
2291
+ p('## 一、元数据');
2292
+ p(`- Android 项目目录:${this.ctx.androidProjectDir}`);
2293
+ p(`- HarmonyOS 项目目录:${this.ctx.harmonyDir}`);
2294
+ p(`- 资源来源:${this.ctx.resSource}`);
2295
+ p(`- 资源来源路径:${this.ctx.resDir}`);
2296
+ p(`- APK:${this.ctx.apkPath}`);
2297
+ p(`- Android final commit:${this.ctx.androidCommit}`);
2298
+ p(`- 构建结果:${this.ctx.buildResult}`);
2299
+ p(`- 转换实现:scripts/a2h_resource_convert.ts(规范实现,agent 不再自行编写转换脚本)`);
2300
+ if (this.ctx.icons) p(`- Material Icons 快照:${this.ctx.icons.ref ?? this.ctx.iconSnapshotRef}`);
2301
+ p();
2302
+ p('### 记录粒度说明');
2303
+ p('- `values/*.xml` 按**条目级**记录,路径写作 `file_path#tag/name`。');
2304
+ p('- 文件类资源(drawable / mipmap / raw / font / xml)按**文件级**记录。');
2305
+ p('- 一对多转换(如 adaptive-icon 产出 layered-image JSON 与生成的纯色 PNG)每个目标各占一行。');
2306
+ p('- **不做抽样、不做聚合**:下表逐条列出全部资源,无省略。');
2307
+ p();
2308
+
2309
+ p('## 二、Android 资源清单(Android Resource Inventory)');
2310
+ p();
2311
+ p('| Android Resource Path | Resource Name | Function | Screen(s) | Source Category | Type Category | Status | Notes |');
2312
+ p('|---|---|---|---|---|---|---|---|');
2313
+ for (const r of this.conv.inventory) {
2314
+ p(`| ${cell(r.androidResourcePath)} | ${cell(r.androidResourceName)} | ${cell(r.function)} | ${cell(r.screens)} | ${cell(r.sourceCategory)} | ${cell(r.typeCategory)} | ${cell(r.status)} | ${cell(r.notes)} |`);
2315
+ }
2316
+ p();
2317
+
2318
+ p('## 三、Android → HarmonyOS 映射明细(Mapping Details)');
2319
+ p();
2320
+ p('| Android Resource Path | Android Screen(s) | Android Source Category | Android Type Category | HarmonyOS Target | Mapping Kind | Notes |');
2321
+ p('|---|---|---|---|---|---|---|');
2322
+ for (const r of this.conv.mappings) {
2323
+ p(`| ${cell(r.androidResourcePath)} | ${cell(r.androidScreens)} | ${cell(r.androidSourceCategory)} | ${cell(r.androidTypeCategory)} | ${cell(r.harmonyTarget)} | ${cell(r.mappingKind)} | ${cell(r.notes)} |`);
2324
+ }
2325
+ p();
2326
+
2327
+ p('## 四、未映射 / 不可映射 / 系统 / 远程资源汇总');
2328
+ p();
2329
+ p('### 4.1 无 HarmonyOS 直接等价物(按原因)');
2330
+ p('| 原因 | 数量 |');
2331
+ p('|---|---|');
2332
+ for (const [k, n] of this.groupBy(this.conv.mappings.filter((m) => m.mappingKind === 'unmappable'), (m) => m.notes || '(未注明)')) {
2333
+ p(`| ${cell(k)} | ${n} |`);
2334
+ }
2335
+ p();
2336
+ p('### 4.2 Android 系统资源(已解析为具体值,输出中不保留 `@android:` 引用)');
2337
+ p('| 引用 | 解析值 | 出现位置 |');
2338
+ p('|---|---|---|');
2339
+ for (const r of this.conv.resolutions.filter((x) => x.kind === 'system')) {
2340
+ p(`| ${cell(r.reference)} | ${cell(r.resolved)} | ${cell(`${r.file}#${r.name}`)} |`);
2341
+ }
2342
+ p();
2343
+ p('### 4.3 兜底替换(无法解析的引用)');
2344
+ if (c.fallbacksApplied === 0) p('无。');
2345
+ else {
2346
+ p('| 位置 | 原始引用 | 兜底值 |');
2347
+ p('|---|---|---|');
2348
+ for (const r of this.conv.resolutions.filter((x) => x.kind === 'fallback' || x.kind === 'theme-attr')) {
2349
+ p(`| ${cell(`${r.file}#${r.name}`)} | ${cell(r.reference)} | ${cell(r.resolved)} |`);
2350
+ }
2351
+ }
2352
+ p();
2353
+ p('### 4.4 运行时远程资源');
2354
+ p('本次转换未检出运行时远程资源(无 Lottie URL 或服务端下发图标)。');
2355
+ p();
2356
+
2357
+ p('## 五、代码内定义矢量图标(Compose Material Icons)');
2358
+ if (!this.ctx.icons?.icons) {
2359
+ p('本次未运行 `scripts/code_vector_icons.ts`,或该工程未检出代码内定义图标。');
2360
+ p('若 Android 侧使用 Jetpack Compose,**必须**运行该脚本:这类图标不在 `res/` 内,本转换器看不见它们。');
2361
+ p();
2362
+ } else {
2363
+ p('这些图标由代码定义,不在 `res/` 内,`res/` 扫描看不见它们。清单来自 `classes*.dex`,图形来自固定版本的 Material Icons 快照。');
2364
+ p();
2365
+ p('| Compose 引用 | Material 名 | 风格 | HarmonyOS 目标 | 所属界面 | 建议页面 | 备注 |');
2366
+ p('|---|---|---|---|---|---|---|');
2367
+ for (const i of this.ctx.icons.icons) {
2368
+ const screens = Array.isArray(i.screens) ? (i.screens as string[]).join(', ') : String(i.screens ?? 'Unknown');
2369
+ const notes = Array.isArray(i.notes) ? (i.notes as string[]).join('; ') : '';
2370
+ p(`| ${cell(String(i.compose))} | ${cell(String(i.material))} | ${cell(String(i.style))} | ${cell(i.resolved ? `resources/base/media/${i.media}` : 'N/A')} | ${cell(screens)} | ${cell(String(i.suggestedPage ?? '—'))} | ${cell(notes || String(i.reason ?? ''))} |`);
2371
+ }
2372
+ p();
2373
+ }
2374
+
2375
+ p('## 六、Quick Findings(快速发现)');
2376
+ p(`- 启动图标:检出 ${c.layeredImages} 个 adaptive-icon,已转为 layered-image JSON;HarmonyOS 的 layered-image 只接受 \`$media:\`,颜色背景已生成纯色 PNG。`);
2377
+ p(`- 点九图:${c.ninePatchRenamed} 个 \`*.9.png\` 重命名为 \`*_9.png\`;拉伸行为丢失,需在 ArkUI 侧用可伸缩 Image 重新实现。`);
2378
+ p(`- 三方库资源:清单中 ${this.conv.inventory.filter((r) => r.sourceCategory === '第三方库资源').length} 条按 \`abc_*\` / \`mtrl_*\` / \`m3_*\` 等前缀推断来自三方库。`);
2379
+ if (c.mediaTargetCollisions > 0) {
2380
+ p(`- 目标冲突:${c.mediaTargetCollisions} 处多个 Android 源落到同一 HarmonyOS 目标(如 \`drawable/\` 与 \`drawable-anydpi/\`),按「限定符更少者胜」择一,落败方已在映射表中标记为 unmappable。`);
2381
+ }
2382
+ if (c.unresolvedPaint > 0) {
2383
+ p(`- SVG 颜色:${c.unresolvedPaint} 处 \`fillColor\` / \`strokeColor\` 在合并资源表中不存在(多为被裁剪的库资源),已按平台默认回退为黑色并逐条告警。`);
2384
+ }
2385
+ p(`- 样式与主题:\`<style>\` / \`<attr>\` / \`<declare-styleable>\` 在 HarmonyOS 无等价物,已全部登记为不可映射,需在 ArkUI 组件代码中重建。`);
2386
+ p();
2387
+ return o.join('\n');
2388
+ }
2389
+ }
2390
+
2391
+ // ─────────────────────────────────────────────
2392
+ // 入口
2393
+ // ─────────────────────────────────────────────
2394
+
2395
+ function parseArgs(argv: string[]): Record<string, string | boolean> {
2396
+ const args: Record<string, string | boolean> = {};
2397
+ for (let i = 0; i < argv.length; i++) {
2398
+ const a = argv[i];
2399
+ if (!a.startsWith('--')) fail(`无法识别的参数: ${a}`);
2400
+ const next = argv[i + 1];
2401
+ if (next && !next.startsWith('--')) { args[a.slice(2)] = next; i++; }
2402
+ else args[a.slice(2)] = true;
2403
+ }
2404
+ return args;
2405
+ }
2406
+
2407
+ function main(): void {
2408
+ const args = parseArgs(process.argv.slice(2));
2409
+ const resDir = typeof args.res === 'string' ? args.res : null;
2410
+ const harmony = typeof args.harmony === 'string' ? args.harmony : null;
2411
+ const dryRun = Boolean(args['dry-run']);
2412
+ const quiet = Boolean(args.quiet);
2413
+
2414
+ const docsOnly = Boolean(args['docs-only']);
2415
+ if (docsOnly) {
2416
+ if (typeof args.records !== 'string') fail('--docs-only 需要 --records <已生成的 records JSON>');
2417
+ const bundle = JSON.parse(fs.readFileSync(args.records, 'utf8')) as RecordsBundle;
2418
+ emitDocs(bundle, args, resDir ?? '(from records)', harmony);
2419
+ process.exit(0);
2420
+ }
2421
+
2422
+ if (!resDir) fail('缺少 --res <decoded res dir>');
2423
+ if (!harmony && !dryRun) fail('缺少 --harmony <harmony project dir>(或使用 --dry-run)');
2424
+ if (!fs.existsSync(resDir)) fail(`--res 路径不存在: ${resDir}`);
2425
+
2426
+ // 过滤模式:读取 extract_project_resources.ts 输出的 JSON,构建 type/name 白名单
2427
+ let filterSet: Set<string> | null = null;
2428
+ if (typeof args.filter === 'string') {
2429
+ if (!fs.existsSync(args.filter)) fail(`--filter 路径不存在: ${args.filter}`);
2430
+ const filterJson = JSON.parse(fs.readFileSync(args.filter, 'utf8')) as {
2431
+ resources: Array<{ type: string; name: string }>;
2432
+ };
2433
+ filterSet = new Set<string>();
2434
+ // `<array>` / `<string-array>` / `<integer-array>` 是同一种资源类型的三种拼写:
2435
+ // aapt2 编译后不再区分,extract_project_resources.ts 一律记为 `array`,而本转换器
2436
+ // 按 item 内容归一化成 string-array/integer-array(见 normalizeArrayTag)。三种拼写
2437
+ // 互相登记别名,否则白名单里的数组会被静默丢弃 —— 既不转换,也不记 unmappable 行。
2438
+ const ARRAY_TAGS = ['array', 'string-array', 'integer-array'];
2439
+ for (const r of filterJson.resources) {
2440
+ filterSet.add(`${r.type}/${r.name}`);
2441
+ if (ARRAY_TAGS.includes(r.type)) {
2442
+ for (const t of ARRAY_TAGS) filterSet.add(`${t}/${r.name}`);
2443
+ }
2444
+ }
2445
+ if (!quiet) console.log(`[a2h_resource_convert] 过滤模式: 白名单 ${filterSet.size} 个资源`);
2446
+ }
2447
+
2448
+ const uiModule = typeof args['ui-module'] === 'string' ? args['ui-module'] : 'entry';
2449
+ const conv = new Converter(resDir, harmony ?? '.', dryRun, uiModule, filterSet);
2450
+ conv.run();
2451
+
2452
+ emitDocs(conv, args, resDir, harmony);
2453
+
2454
+ if (typeof args.records === 'string') {
2455
+ fs.writeFileSync(args.records, `${JSON.stringify({
2456
+ counts: conv.counts,
2457
+ qualifierUse: conv.qualifierUse,
2458
+ warnings: conv.warnings,
2459
+ conflicts: conv.conflicts,
2460
+ resolutions: conv.resolutions,
2461
+ inventory: conv.inventory,
2462
+ mappings: conv.mappings,
2463
+ }, null, 1)}
2464
+ `, 'utf8');
2465
+ }
2466
+
2467
+ if (!quiet) {
2468
+ const c = conv.counts;
2469
+ console.log('[a2h_resource_convert]');
2470
+ console.log(` values 条目转换 : ${c.valuesEntries}`);
2471
+ console.log(` 媒体文件拷贝 : ${c.mediaCopied}(其中点九图重命名 ${c.ninePatchRenamed})`);
2472
+ console.log(` raw / font / profile : ${c.rawCopied} / ${c.fontCopied} / ${c.profileCopied}`);
2473
+ console.log(` XML drawable → SVG : ${c.svgConverted}`);
2474
+ console.log(` layered-image JSON : ${c.layeredImages}`);
2475
+ console.log(` 图标图层 SVG / 纯色层: ${c.safeZoneLayers} / ${c.solidLayersGenerated}`);
2476
+ console.log(` 不可映射 : ${c.unmappable}`);
2477
+ console.log(` 跳过的限定符目录 : ${c.skippedQualifierDirs}`);
2478
+ console.log(` 引用解析 : ${c.referencesResolved}(其中系统资源 ${c.systemReferencesResolved})`);
2479
+ console.log(` 兜底替换 : ${c.fallbacksApplied}`);
2480
+ console.log(` 颜色解析失败(SVG) : ${c.unresolvedPaint}`);
2481
+ console.log(` 目标冲突择一 : ${c.mediaTargetCollisions}`);
2482
+ console.log(` 失败 : ${c.failed}`);
2483
+ console.log(` inventory / mapping 行: ${conv.inventory.length} / ${conv.mappings.length}`);
2484
+ if (conv.conflicts.length > 0) console.log(` 同名覆盖 : ${conv.conflicts.length}`);
2485
+ if (conv.warnings.length > 0) console.log(` 告警 : ${conv.warnings.length}`);
2486
+ }
2487
+
2488
+ process.exit(conv.counts.failed > 0 ? 1 : 0);
2489
+ }
2490
+
2491
+ /** 生成两份 markdown。抽成函数以便 --docs-only 复用。 */
2492
+ function emitDocs(
2493
+ bundle: RecordsBundle,
2494
+ args: Record<string, string | boolean>,
2495
+ resDir: string,
2496
+ harmony: string | null,
2497
+ ): void {
2498
+ if (typeof args.report !== 'string' && typeof args.mapping !== 'string') return;
2499
+ const readJson = (k: string): Record<string, unknown> | null => {
2500
+ const v = args[k];
2501
+ if (typeof v !== 'string') return null;
2502
+ try { return JSON.parse(fs.readFileSync(v, 'utf8')) as Record<string, unknown>; }
2503
+ catch (e) { fail(`--${k} 读取失败: ${(e as Error).message}`); }
2504
+ };
2505
+
2506
+ {
2507
+ const doc = new DocWriter(bundle, {
2508
+ apkPath: typeof args.apk === 'string' ? args.apk : '(not provided)',
2509
+ resSource: 'decoded APK (complete merged resource set)',
2510
+ resDir,
2511
+ androidProjectDir: typeof args['android-project'] === 'string' ? args['android-project'] : '(not provided)',
2512
+ harmonyDir: harmony ?? '',
2513
+ appModule: typeof args['app-module'] === 'string' ? args['app-module'] : '(not provided)',
2514
+ androidCommit: typeof args['android-commit'] === 'string' ? args['android-commit'] : '(not provided)',
2515
+ iconSnapshotRef: '(not provided)',
2516
+ buildResult: typeof args['build-result'] === 'string' ? args['build-result'] : '(not run by this script)',
2517
+ icons: readJson('icons-json') as DocContext['icons'],
2518
+ fidelity: readJson('fidelity-json') as DocContext['fidelity'],
2519
+ appIdentity: readJson('app-identity-json') as DocContext['appIdentity'],
2520
+ });
2521
+ if (typeof args.report === 'string') fs.writeFileSync(args.report, `${doc.report()}
2522
+ `, 'utf8');
2523
+ if (typeof args.mapping === 'string') fs.writeFileSync(args.mapping, `${doc.mapping()}
2524
+ `, 'utf8');
2525
+ }
2526
+
2527
+ }
2528
+
2529
+ main();