@buaa_smat/hometrans 26.0.0-devecocli.2 → 26.0.0-devecocli.4

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 (497) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/plugin.jsonc +1 -1
  4. package/skills/a2h-app-migrate/references/specs.example.json +19 -19
  5. package/skills/a2h-app-migrate/scripts/env_preflight.mjs +38 -14
  6. package/skills/a2h-app-migrate/scripts/infer_android_root.mjs +3 -3
  7. package/skills/a2h-app-migrate/scripts/json_io.mjs +35 -35
  8. package/skills/a2h-app-migrate/scripts/lib-yaml-lite.mjs +288 -288
  9. package/skills/a2h-app-migrate/scripts/paths_preflight.mjs +183 -15
  10. package/skills/a2h-app-migrate/test/test_arch_done.mjs +54 -54
  11. package/skills/a2h-app-migrate/test/test_env_requirements.mjs +40 -1
  12. package/skills/a2h-app-migrate/test/test_gate_checkpoint.mjs +146 -146
  13. package/skills/a2h-app-migrate/test/test_hmos_fingerprint.mjs +68 -68
  14. package/skills/a2h-app-migrate/test/test_json_io.mjs +32 -32
  15. package/skills/a2h-app-migrate/test/test_module_docs_done.mjs +53 -53
  16. package/skills/a2h-app-migrate/test/test_parse_args.mjs +69 -69
  17. package/skills/a2h-app-migrate/test/test_preflight_report.mjs +11 -1
  18. package/skills/a2h-app-migrate/test/test_spec_pipeline_done.mjs +181 -181
  19. package/skills/a2h-app-migrate/test/test_ui_batch_done.mjs +53 -53
  20. package/skills/a2h-app-migrate/test/test_ui_batch_gate.mjs +226 -226
  21. package/skills/a2h-app-migrate/test/test_uniapp_preflight.mjs +83 -0
  22. package/skills/a2h-app-migrate/test/test_utg_dirs.mjs +39 -39
  23. package/skills/a2h-arch-generate/examples/reconcile-existing-project.md +107 -107
  24. package/skills/a2h-arch-generate/examples/simple-conversion-android.md +103 -103
  25. package/skills/a2h-arch-generate/examples/simple-conversion-backend.md +70 -70
  26. package/skills/a2h-arch-generate/examples/simple-conversion-uniapp.md +106 -106
  27. package/skills/a2h-arch-generate/references/arkts-mvvm-v2.md +1407 -1407
  28. package/skills/a2h-arch-generate/references/artifact-contracts.generate.md +120 -120
  29. package/skills/a2h-arch-generate/references/artifact-contracts.reconcile.md +123 -123
  30. package/skills/a2h-arch-generate/references/bpta-layered-architecture-design.md +87 -87
  31. package/skills/a2h-arch-generate/references/database-schema-recovery.md +107 -107
  32. package/skills/a2h-arch-generate/references/existing-target-annotation.md +68 -68
  33. package/skills/a2h-arch-generate/references/harmony-project-inspection.md +150 -150
  34. package/skills/a2h-arch-generate/references/harmony-target-architecture.md +94 -94
  35. package/skills/a2h-arch-generate/references/reconciliation-model.md +204 -204
  36. package/skills/a2h-arch-generate/references/scope-policy.md +28 -28
  37. package/skills/a2h-arch-generate/references/semantic-review.md +65 -65
  38. package/skills/a2h-arch-generate/references/source-ecosystems.md +54 -54
  39. package/skills/a2h-arch-generate/references/transformation-model.md +78 -78
  40. package/skills/a2h-arch-generate/scripts/create_project.mjs +149 -149
  41. package/skills/a2h-arch-generate/scripts/generate_state.mjs +60 -60
  42. package/skills/a2h-arch-generate/scripts/inspect_and_route.mjs +326 -326
  43. package/skills/a2h-arch-generate/scripts/inspect_uniapp_project.mjs +809 -809
  44. package/skills/a2h-arch-generate/scripts/lib/py_compat.mjs +1454 -1454
  45. package/skills/a2h-arch-generate/scripts/module_create/create.mjs +136 -136
  46. package/skills/a2h-arch-generate/scripts/module_create/generate.mjs +636 -636
  47. package/skills/a2h-arch-generate/scripts/module_create/hap/build-profile.json5 +32 -32
  48. package/skills/a2h-arch-generate/scripts/module_create/hap/hvigorfile.ts +5 -5
  49. package/skills/a2h-arch-generate/scripts/module_create/hap/obfuscation-rules.txt +22 -22
  50. package/skills/a2h-arch-generate/scripts/module_create/hap/oh-package.json5 +10 -10
  51. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/applicationability/ApplicationAbility.ets +43 -43
  52. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/pages/Index.ets +22 -22
  53. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/module.json5 +25 -25
  54. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/color.json +7 -7
  55. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/float.json +8 -8
  56. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/string.json +15 -15
  57. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/layered_image.json +6 -6
  58. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/profile/main_pages.json +5 -5
  59. package/skills/a2h-arch-generate/scripts/module_create/hap/src/mock/mock-config.json5 +1 -1
  60. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/Ability.test.ets +34 -34
  61. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/List.test.ets +4 -4
  62. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/module.json5 +11 -11
  63. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/List.test.ets +4 -4
  64. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/LocalUnit.test.ets +32 -32
  65. package/skills/a2h-arch-generate/scripts/module_create/har/Index.ets +1 -1
  66. package/skills/a2h-arch-generate/scripts/module_create/har/build-profile.json5 +36 -36
  67. package/skills/a2h-arch-generate/scripts/module_create/har/hvigorfile.ts +5 -5
  68. package/skills/a2h-arch-generate/scripts/module_create/har/obfuscation-rules.txt +22 -22
  69. package/skills/a2h-arch-generate/scripts/module_create/har/oh-package.json5 +9 -9
  70. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/ets/components/MainPage.ets +19 -19
  71. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/module.json5 +9 -9
  72. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/float.json +8 -8
  73. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/string.json +8 -8
  74. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/Ability.test.ets +34 -34
  75. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/List.test.ets +4 -4
  76. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/module.json5 +11 -11
  77. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/List.test.ets +4 -4
  78. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/LocalUnit.test.ets +32 -32
  79. package/skills/a2h-arch-generate/scripts/module_create/hsp/build-profile.json5 +35 -35
  80. package/skills/a2h-arch-generate/scripts/module_create/hsp/hvigorfile.ts +5 -5
  81. package/skills/a2h-arch-generate/scripts/module_create/hsp/obfuscation-rules.txt +22 -22
  82. package/skills/a2h-arch-generate/scripts/module_create/hsp/oh-package.json5 +9 -9
  83. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/pages/Index.ets +19 -19
  84. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/utils/Calc.ets +2 -2
  85. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/module.json5 +11 -11
  86. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/float.json +8 -8
  87. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/string.json +7 -7
  88. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/profile/main_pages.json +5 -5
  89. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/Ability.test.ets +34 -34
  90. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/List.test.ets +4 -4
  91. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/module.json5 +10 -10
  92. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/List.test.ets +4 -4
  93. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/LocalUnit.test.ets +32 -32
  94. package/skills/a2h-arch-generate/scripts/module_create/testdata/reconcile-layer-PROJECT_DESIGN.md +47 -47
  95. package/skills/a2h-arch-generate/scripts/module_create/testdata/single-entry-PROJECT_DESIGN.md +15 -15
  96. package/skills/a2h-arch-generate/scripts/module_create/testdata/three-layer-PROJECT_DESIGN.md +36 -36
  97. package/skills/a2h-arch-generate/scripts/resolve_android_stores.mjs +529 -529
  98. package/skills/a2h-arch-generate/scripts/scaffold_project.mjs +230 -230
  99. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/build.gradle +11 -11
  100. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/AndroidManifest.xml +12 -12
  101. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/MainActivity.kt +8 -8
  102. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/NotesStore.kt +17 -17
  103. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/build.gradle +3 -3
  104. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/settings.gradle +1 -1
  105. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/AppScope/app.json5 +8 -8
  106. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/build-profile.json5 +14 -14
  107. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/build-profile.json5 +7 -7
  108. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/oh-package.json5 +1 -1
  109. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/src/main/ets/utils/Format.ets +3 -3
  110. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/build-profile.json5 +7 -7
  111. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/oh-package.json5 +1 -1
  112. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/src/main/ets/pages/Home.ets +3 -3
  113. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/build-profile.json5 +7 -7
  114. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/oh-package.json5 +1 -1
  115. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/src/main/ets/engine/SyncEngine.ets +3 -3
  116. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/hvigorfile.ts +1 -1
  117. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/oh-package.json5 +1 -1
  118. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/build-profile.json5 +7 -7
  119. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/oh-package.json5 +9 -9
  120. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/src/main/ets/pages/Index.ets +7 -7
  121. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/App.vue +10 -10
  122. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/manifest.json +6 -6
  123. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages/index/index.vue +16 -16
  124. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages.json +5 -5
  125. package/skills/a2h-arch-generate/scripts/tests/test_console_encoding.mjs +52 -52
  126. package/skills/a2h-arch-generate/scripts/tests/test_git_root.mjs +34 -34
  127. package/skills/a2h-arch-generate/scripts/tests/test_router.mjs +138 -138
  128. package/skills/a2h-arch-generate/scripts/validate_data_docs.mjs +937 -937
  129. package/skills/a2h-arch-generate/scripts/validate_homegraph_artifacts.mjs +542 -542
  130. package/skills/a2h-arch-generate/scripts/validate_incremental_docs.mjs +415 -415
  131. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +6 -6
  132. package/skills/a2h-arkts-logic-coder/scripts/check_module_scope.ts +224 -224
  133. package/skills/a2h-arkts-logic-coder/scripts/check_mvvm.ts +377 -377
  134. package/skills/a2h-arkts-logic-coder/scripts/stop_check_hook.ts +443 -443
  135. package/skills/a2h-arkts-logic-coder/scripts/test_check_scripts.ts +211 -211
  136. package/skills/a2h-arkts-logic-coder/scripts/test_worktree_compat.ts +81 -81
  137. package/skills/a2h-batch-ui-align/SKILL.md +19 -7
  138. package/skills/a2h-batch-ui-align/flowchart.html +271 -271
  139. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +57 -8
  140. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2535 -2533
  141. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +558 -558
  142. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -117
  143. package/skills/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
  144. package/skills/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
  145. package/skills/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
  146. package/skills/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
  147. package/skills/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
  148. package/skills/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
  149. package/skills/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
  150. package/skills/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
  151. package/skills/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
  152. package/skills/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
  153. package/skills/a2h-batch-ui-align/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md +911 -911
  154. package/skills/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
  155. package/skills/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
  156. package/skills/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
  157. package/skills/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
  158. package/skills/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
  159. package/skills/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
  160. package/skills/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
  161. package/skills/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
  162. package/skills/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
  163. package/skills/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
  164. package/skills/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
  165. package/skills/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
  166. package/skills/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
  167. package/skills/a2h-batch-ui-align/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -1407
  168. package/skills/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
  169. package/skills/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
  170. package/skills/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
  171. package/skills/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
  172. package/skills/a2h-batch-ui-align/references/step3-capture.md +4 -1
  173. package/skills/a2h-batch-ui-align/references/step4-prepare.md +7 -3
  174. package/skills/a2h-batch-ui-align/references/step5-convert.md +8 -5
  175. package/skills/a2h-batch-ui-align/scripts/answers_check.mjs +86 -86
  176. package/skills/a2h-batch-ui-align/scripts/arkts_static_check.ts +1191 -2
  177. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +1675 -1656
  178. package/skills/a2h-batch-ui-align/scripts/databinding_analyzer_design.md +79 -79
  179. package/skills/a2h-batch-ui-align/scripts/detach.mjs +258 -258
  180. package/skills/a2h-batch-ui-align/scripts/export_ui_info.mjs +130 -10
  181. package/skills/a2h-batch-ui-align/scripts/generate_pages_json.mjs +612 -612
  182. package/skills/a2h-batch-ui-align/scripts/group_commit.mjs +166 -166
  183. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +1627 -1437
  184. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +1869 -1869
  185. package/skills/a2h-batch-ui-align/scripts/harmony_index.mjs +218 -218
  186. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +208 -208
  187. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +1179 -1124
  188. package/skills/a2h-batch-ui-align/scripts/shell_contract.mjs +1036 -996
  189. package/skills/a2h-batch-ui-align/scripts/tests/agent_cli.test.mjs +217 -217
  190. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_align_tint.test.mjs +253 -253
  191. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_canvas_pct.test.mjs +312 -0
  192. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_fidelity.test.mjs +241 -0
  193. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_layout_placement.test.mjs +365 -0
  194. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_review_fixes.test.mjs +298 -0
  195. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_rules.test.mjs +365 -365
  196. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_shell.test.mjs +91 -72
  197. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_weight_color.test.mjs +120 -0
  198. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set.test.mjs +356 -345
  199. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set_scope.test.mjs +290 -290
  200. package/skills/a2h-batch-ui-align/scripts/tests/export_scroll_states.test.mjs +31 -0
  201. package/skills/a2h-batch-ui-align/scripts/tests/export_ui_info.test.mjs +57 -0
  202. package/skills/a2h-batch-ui-align/scripts/tests/generate_pages_json.test.mjs +123 -123
  203. package/skills/a2h-batch-ui-align/scripts/tests/group_commit.test.mjs +126 -126
  204. package/skills/a2h-batch-ui-align/scripts/tests/group_pack.test.mjs +241 -189
  205. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +1451 -1451
  206. package/skills/a2h-batch-ui-align/scripts/tests/group_watch.test.mjs +215 -215
  207. package/skills/a2h-batch-ui-align/scripts/tests/harmony_index.test.mjs +95 -95
  208. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +115 -115
  209. package/skills/a2h-batch-ui-align/scripts/tests/phase5_check.test.mjs +244 -244
  210. package/skills/a2h-batch-ui-align/scripts/tests/shell_contract.test.mjs +166 -130
  211. package/skills/a2h-batch-ui-align/scripts/tests/test_bfs_exit.ts +49 -49
  212. package/skills/a2h-batch-ui-align/scripts/tests/text_color_diff.test.mjs +219 -0
  213. package/skills/a2h-batch-ui-align/scripts/text_color_diff.mjs +470 -0
  214. package/skills/a2h-dashboard-render/references/artifact-registry-spec.md +67 -67
  215. package/skills/a2h-dashboard-render/references/dashboard.config.example.json +19 -19
  216. package/skills/a2h-dashboard-render/scripts/artifact_contract.mjs +138 -138
  217. package/skills/a2h-dashboard-render/scripts/check-registry.mjs +87 -87
  218. package/skills/a2h-dashboard-render/test/fixtures/page_capture/expected.json +155 -155
  219. package/skills/a2h-dashboard-render/test/fixtures/page_capture/hmos.json +1 -1
  220. package/skills/a2h-dashboard-render/test/fixtures/page_capture/list.xml +1 -1
  221. package/skills/a2h-dashboard-render/test/fixtures/page_capture/nested_scroll.xml +1 -1
  222. package/skills/a2h-dashboard-render/test/test_cli_check_registry.mjs +99 -99
  223. package/skills/a2h-dashboard-render/test/test_dashboard_build.mjs +64 -64
  224. package/skills/a2h-dashboard-render/test/test_page_capture.mjs +147 -147
  225. package/skills/a2h-fix-build-errors/references/arkts-strict-patterns.md +219 -219
  226. package/skills/a2h-fix-build-errors/references/known-patterns.md +157 -157
  227. package/skills/a2h-fix-build-errors/references/rdb-entity-pattern.md +131 -131
  228. package/skills/a2h-module-semantic-docs/scripts/commit_module_state.mjs +168 -168
  229. package/skills/a2h-module-semantic-docs/scripts/lib/py_compat.mjs +688 -688
  230. package/skills/a2h-module-semantic-docs/scripts/scan_modules.mjs +1021 -1021
  231. package/skills/a2h-module-semantic-docs/test/golden/module_structure.json +187 -187
  232. package/skills/a2h-module-semantic-docs/test/golden/module_understanding.json +351 -351
  233. package/skills/a2h-module-semantic-docs/test/golden/module_update_plan.json +495 -495
  234. package/skills/a2h-module-semantic-docs/test/golden/project_directory_structure.json +157 -157
  235. package/skills/a2h-module-semantic-docs/test/test_scan_and_commit.mjs +388 -388
  236. package/skills/a2h-resource-convert/references/code-vector-icon-rules.md +335 -335
  237. package/skills/a2h-resource-convert/references/conversion-rules.md +687 -687
  238. package/skills/a2h-resource-convert/references/dependency-analysis-rules.md +410 -410
  239. package/skills/a2h-resource-convert/references/incremental-page-migration.md +250 -250
  240. package/skills/a2h-resource-convert/references/lottie-conversion-rules.md +219 -219
  241. package/skills/a2h-resource-convert/references/resource-mapping-rules.md +493 -493
  242. package/skills/a2h-resource-convert/references/step3_5-dependency-filter.md +54 -54
  243. package/skills/a2h-resource-convert/references/step4-qualifiers-and-values.md +142 -142
  244. package/skills/a2h-resource-convert/references/step4-resource-types.md +249 -249
  245. package/skills/a2h-resource-convert/references/step5-reference-resolution.md +154 -154
  246. package/skills/a2h-resource-convert/references/step7-report-template.md +217 -217
  247. package/skills/a2h-resource-convert/references/xml-drawable-to-svg-rules.md +630 -630
  248. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +2529 -2529
  249. package/skills/a2h-resource-convert/scripts/a2h_resource_incremental.ts +1072 -1072
  250. package/skills/a2h-resource-convert/scripts/code_vector_icons.ts +607 -607
  251. package/skills/a2h-resource-convert/scripts/extract_page_resources.ts +989 -989
  252. package/skills/a2h-resource-convert/scripts/extract_project_resources.ts +1464 -1464
  253. package/skills/a2h-resource-convert/scripts/svg_fidelity_check.ts +632 -632
  254. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +182 -182
  255. package/skills/a2h-spec-design/scripts/inspect_spec_design_inputs.mjs +146 -146
  256. package/skills/a2h-spec-design/scripts/lib/py_compat.mjs +481 -481
  257. package/skills/a2h-spec-design/scripts/move_spec_technical_reference.mjs +159 -159
  258. package/skills/a2h-spec-design/scripts/resolve_module_design.mjs +102 -102
  259. package/skills/a2h-spec-design/scripts/validate_spec_design_output.mjs +285 -285
  260. package/skills/a2h-spec-design/test/golden/inspect_happy.json +20 -20
  261. package/skills/a2h-spec-design/test/golden/move_design.md +18 -18
  262. package/skills/a2h-spec-design/test/golden/move_spec.md +7 -7
  263. package/skills/a2h-spec-design/test/golden/resolve_cases.json +36 -36
  264. package/skills/a2h-spec-design/test/golden/validate_issue_file.md +12 -12
  265. package/skills/a2h-spec-design/test/golden/validate_issues.json +57 -57
  266. package/skills/a2h-spec-design/test/test_spec_design_scripts.mjs +381 -381
  267. package/skills/a2h-spec-design-pipeline/package.json +4 -4
  268. package/skills/a2h-spec-design-pipeline/references/execution-model.md +69 -69
  269. package/skills/a2h-spec-design-pipeline/references/final-report-template.md +24 -24
  270. package/skills/a2h-spec-design-pipeline/references/specs.example.json +19 -19
  271. package/skills/a2h-spec-design-pipeline/scripts/atomic_write.ts +42 -42
  272. package/skills/a2h-spec-design-pipeline/scripts/audit_claims.ts +252 -252
  273. package/skills/a2h-spec-design-pipeline/scripts/branch_landed.ts +77 -77
  274. package/skills/a2h-spec-design-pipeline/scripts/deps_ready.ts +195 -195
  275. package/skills/a2h-spec-design-pipeline/scripts/git_baseline.ts +124 -124
  276. package/skills/a2h-spec-design-pipeline/scripts/lib/bgcli.mjs +95 -95
  277. package/skills/a2h-spec-design-pipeline/scripts/plan_waves.ts +475 -475
  278. package/skills/a2h-spec-design-pipeline/scripts/resolve_wiring.ts +164 -164
  279. package/skills/a2h-spec-design-pipeline/scripts/test_atomic_write.ts +44 -44
  280. package/skills/a2h-spec-design-pipeline/scripts/test_audit_claims.ts +301 -301
  281. package/skills/a2h-spec-design-pipeline/scripts/test_bgcli.mjs +64 -64
  282. package/skills/a2h-spec-design-pipeline/scripts/test_branch_landed.ts +87 -87
  283. package/skills/a2h-spec-design-pipeline/scripts/test_deps_ready.ts +265 -265
  284. package/skills/a2h-spec-design-pipeline/scripts/test_git_baseline.ts +105 -105
  285. package/skills/a2h-spec-design-pipeline/scripts/test_plan_waves.ts +561 -561
  286. package/skills/a2h-spec-design-pipeline/scripts/test_resolve_wiring.ts +138 -138
  287. package/skills/a2h-spec-design-pipeline/scripts/test_watchdog.mjs +289 -289
  288. package/skills/a2h-spec-design-pipeline/scripts/watchdog.mjs +441 -441
  289. package/skills/a2h-spec-generate/scripts/parse_requirements.ts +515 -515
  290. package/skills/a2h-spec-generate/template/REQ.txt +22 -22
  291. package/skills/a2h-spec-generate/test/detect-project.test.mjs +37 -37
  292. package/skills/a2h-spec-generate/test/fixtures/android/app/src/main/AndroidManifest.xml +3 -3
  293. package/skills/a2h-spec-generate/test/fixtures/android/build.gradle +3 -3
  294. package/skills/a2h-spec-generate/test/fixtures/android/settings.gradle +3 -3
  295. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/package.json +9 -9
  296. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/App.vue +8 -8
  297. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/components/MyCard.vue +9 -9
  298. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/feature/editor/index.vue +1 -1
  299. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/main.ts +6 -6
  300. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/manifest.json +4 -4
  301. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/detail/index.vue +1 -1
  302. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/home/index.vue +33 -33
  303. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/settings/index.vue +1 -1
  304. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages.json +23 -23
  305. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/services/items.ts +3 -3
  306. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/tsconfig.json +8 -8
  307. package/skills/a2h-spec-generate/test/fixtures/unknown/README.txt +1 -1
  308. package/skills/a2h-spec-generate/test/inspect-uniapp.test.mjs +54 -54
  309. package/skills/a2h-utg-explorer/SKILL.md +1 -1
  310. package/skills/a2h-utg-explorer/assets/final_viewer.html +64 -64
  311. package/skills/a2h-utg-explorer/assets/u2.LICENSE +21 -21
  312. package/skills/a2h-utg-explorer/assets/u2.NOTICE +25 -25
  313. package/skills/a2h-utg-explorer/references/protocol.md +9 -9
  314. package/skills/a2h-utg-explorer/scripts/app_settings.mjs +143 -143
  315. package/skills/a2h-utg-explorer/scripts/close_phases.mjs +66 -66
  316. package/skills/a2h-utg-explorer/scripts/d_prereqs.mjs +597 -597
  317. package/skills/a2h-utg-explorer/scripts/device_health.mjs +227 -227
  318. package/skills/a2h-utg-explorer/scripts/evidence.mjs +108 -108
  319. package/skills/a2h-utg-explorer/scripts/final_utg.mjs +61 -9
  320. package/skills/a2h-utg-explorer/scripts/hint_check.mjs +89 -89
  321. package/skills/a2h-utg-explorer/scripts/plan.mjs +258 -258
  322. package/skills/a2h-utg-explorer/scripts/promote_dynamic.mjs +170 -170
  323. package/skills/a2h-utg-explorer/scripts/recover_d.mjs +380 -302
  324. package/skills/a2h-utg-explorer/scripts/report.mjs +143 -143
  325. package/skills/a2h-utg-explorer/scripts/run_cycle.mjs +18 -2
  326. package/skills/a2h-utg-explorer/scripts/run_device.mjs +137 -137
  327. package/skills/a2h-utg-explorer/scripts/tests/attest.test.mjs +66 -66
  328. package/skills/a2h-utg-explorer/scripts/tests/chain.test.mjs +45 -45
  329. package/skills/a2h-utg-explorer/scripts/tests/compose_identity.test.mjs +37 -1
  330. package/skills/a2h-utg-explorer/scripts/tests/coverage_rules.test.mjs +104 -104
  331. package/skills/a2h-utg-explorer/scripts/tests/d_prereqs.test.mjs +223 -223
  332. package/skills/a2h-utg-explorer/scripts/tests/device_health.test.mjs +88 -88
  333. package/skills/a2h-utg-explorer/scripts/tests/device_lock_retry.test.mjs +187 -187
  334. package/skills/a2h-utg-explorer/scripts/tests/direct_launch.test.mjs +130 -130
  335. package/skills/a2h-utg-explorer/scripts/tests/explorer_review_fixes.test.mjs +136 -136
  336. package/skills/a2h-utg-explorer/scripts/tests/final_utg.test.mjs +135 -135
  337. package/skills/a2h-utg-explorer/scripts/tests/generalization_fixes.test.mjs +251 -251
  338. package/skills/a2h-utg-explorer/scripts/tests/hint_check.test.mjs +42 -42
  339. package/skills/a2h-utg-explorer/scripts/tests/interruptions.test.mjs +162 -162
  340. package/skills/a2h-utg-explorer/scripts/tests/node_coverage.test.mjs +193 -193
  341. package/skills/a2h-utg-explorer/scripts/tests/overflow_prefix.test.mjs +204 -204
  342. package/skills/a2h-utg-explorer/scripts/tests/page_identity_tiers.test.mjs +355 -355
  343. package/skills/a2h-utg-explorer/scripts/tests/pipeline.test.mjs +240 -240
  344. package/skills/a2h-utg-explorer/scripts/tests/recover_b.test.mjs +173 -173
  345. package/skills/a2h-utg-explorer/scripts/tests/recover_d.test.mjs +280 -207
  346. package/skills/a2h-utg-explorer/scripts/tests/review_fixes.test.mjs +213 -213
  347. package/skills/a2h-utg-explorer/scripts/tests/robustness_fixes.test.mjs +345 -345
  348. package/skills/a2h-utg-explorer/scripts/tests/runner_capabilities.test.mjs +131 -131
  349. package/skills/a2h-utg-explorer/scripts/tests/scope.test.mjs +229 -229
  350. package/skills/a2h-utg-explorer/scripts/tests/scroll_sweep.test.mjs +336 -321
  351. package/skills/a2h-utg-explorer/scripts/tests/semantics.test.mjs +102 -102
  352. package/skills/a2h-utg-explorer/scripts/tests/state_ambiguity.test.mjs +92 -0
  353. package/skills/a2h-utg-explorer/scripts/tests/u2_backend.test.mjs +346 -346
  354. package/skills/a2h-utg-explorer/scripts/tests/worklist_parts.test.mjs +24 -24
  355. package/skills/a2h-utg-explorer/scripts/utg_explorer/_device_io.mjs +244 -244
  356. package/skills/a2h-utg-explorer/scripts/utg_explorer/_py.mjs +2097 -2097
  357. package/skills/a2h-utg-explorer/scripts/utg_explorer/adapters.mjs +18 -0
  358. package/skills/a2h-utg-explorer/scripts/utg_explorer/attest.mjs +63 -63
  359. package/skills/a2h-utg-explorer/scripts/utg_explorer/chain.mjs +63 -63
  360. package/skills/a2h-utg-explorer/scripts/utg_explorer/coverage.mjs +89 -89
  361. package/skills/a2h-utg-explorer/scripts/utg_explorer/device_lock.mjs +46 -46
  362. package/skills/a2h-utg-explorer/scripts/utg_explorer/semantics.mjs +66 -2
  363. package/skills/a2h-utg-explorer/scripts/utg_explorer/task_runner.mjs +53 -4
  364. package/skills/a2h-utg-explorer/scripts/variant.mjs +75 -75
  365. package/skills/a2h-utg-explorer/scripts/worklist_parts.mjs +122 -122
  366. package/skills/a2h-utg-static/config.json +19 -19
  367. package/skills/a2h-utg-static/references/ui-elements-static-utg-schema.md +248 -248
  368. package/skills/a2h-utg-static/references/view-interactions.md +215 -215
  369. package/skills/a2h-utg-static/scripts/_graph.mjs +361 -361
  370. package/skills/a2h-utg-static/scripts/_py.mjs +2177 -2177
  371. package/skills/a2h-utg-static/scripts/_spawn.mjs +45 -45
  372. package/skills/a2h-utg-static/scripts/activity_widgets.mjs +254 -254
  373. package/skills/a2h-utg-static/scripts/adapter_nav.mjs +229 -229
  374. package/skills/a2h-utg-static/scripts/androidfragment_nav.mjs +208 -208
  375. package/skills/a2h-utg-static/scripts/audit.mjs +268 -268
  376. package/skills/a2h-utg-static/scripts/carry_answers.mjs +201 -201
  377. package/skills/a2h-utg-static/scripts/compose_body_text.mjs +60 -0
  378. package/skills/a2h-utg-static/scripts/dialog_listener_nav.mjs +237 -237
  379. package/skills/a2h-utg-static/scripts/guard_subjects.mjs +162 -162
  380. package/skills/a2h-utg-static/scripts/hg_query.mjs +137 -137
  381. package/skills/a2h-utg-static/scripts/hybrid_bundle.mjs +165 -165
  382. package/skills/a2h-utg-static/scripts/hybrid_pages.mjs +713 -713
  383. package/skills/a2h-utg-static/scripts/hybrid_scope.mjs +660 -660
  384. package/skills/a2h-utg-static/scripts/interaction_sites.mjs +267 -267
  385. package/skills/a2h-utg-static/scripts/io_utils.mjs +59 -59
  386. package/skills/a2h-utg-static/scripts/measure/measure_corpus.mjs +297 -297
  387. package/skills/a2h-utg-static/scripts/measure/measure_guards.mjs +98 -98
  388. package/skills/a2h-utg-static/scripts/media_browse_nav.mjs +356 -356
  389. package/skills/a2h-utg-static/scripts/orphan_overlay_nav.mjs +89 -89
  390. package/skills/a2h-utg-static/scripts/phase_plan.mjs +108 -108
  391. package/skills/a2h-utg-static/scripts/phase_planner.mjs +119 -119
  392. package/skills/a2h-utg-static/scripts/plaindialog_nav.mjs +411 -411
  393. package/skills/a2h-utg-static/scripts/preference_widgets.mjs +142 -142
  394. package/skills/a2h-utg-static/scripts/presenter_nav.mjs +490 -490
  395. package/skills/a2h-utg-static/scripts/registry_nav.mjs +288 -288
  396. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +870 -870
  397. package/skills/a2h-utg-static/scripts/screen_merge.mjs +287 -287
  398. package/skills/a2h-utg-static/scripts/screen_nav.mjs +279 -279
  399. package/skills/a2h-utg-static/scripts/starter_nav.mjs +198 -198
  400. package/skills/a2h-utg-static/scripts/static_prior.mjs +904 -904
  401. package/skills/a2h-utg-static/scripts/tests/_zipw.mjs +28 -28
  402. package/skills/a2h-utg-static/scripts/tests/probe_autoload.mjs +108 -108
  403. package/skills/a2h-utg-static/scripts/tests/probe_layout_fragments.mjs +90 -90
  404. package/skills/a2h-utg-static/scripts/tests/probe_unknown_scope.mjs +61 -61
  405. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +1261 -1261
  406. package/skills/a2h-utg-static/scripts/tests/test_activity_alias_launcher.mjs +90 -90
  407. package/skills/a2h-utg-static/scripts/tests/test_bottom_sheet_container.mjs +58 -58
  408. package/skills/a2h-utg-static/scripts/tests/test_branch_guard.mjs +19 -19
  409. package/skills/a2h-utg-static/scripts/tests/test_carry_answers.mjs +103 -103
  410. package/skills/a2h-utg-static/scripts/tests/test_chrome_tokens.mjs +60 -60
  411. package/skills/a2h-utg-static/scripts/tests/test_commented_out_trigger.mjs +111 -111
  412. package/skills/a2h-utg-static/scripts/tests/test_commit_scope.mjs +113 -113
  413. package/skills/a2h-utg-static/scripts/tests/test_compose_vm_nav.mjs +23 -1
  414. package/skills/a2h-utg-static/scripts/tests/test_defensive_null_guard.mjs +77 -77
  415. package/skills/a2h-utg-static/scripts/tests/test_dialog_orphan_entries.mjs +99 -99
  416. package/skills/a2h-utg-static/scripts/tests/test_dialog_page_owner.mjs +69 -69
  417. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_java_factory.mjs +37 -37
  418. package/skills/a2h-utg-static/scripts/tests/test_disabled_guard.mjs +42 -42
  419. package/skills/a2h-utg-static/scripts/tests/test_drawer_panel_gesture.mjs +140 -140
  420. package/skills/a2h-utg-static/scripts/tests/test_edge_dedupe_by_gesture.mjs +111 -111
  421. package/skills/a2h-utg-static/scripts/tests/test_edge_provenance_lint.mjs +70 -70
  422. package/skills/a2h-utg-static/scripts/tests/test_enclosing_gesture.mjs +69 -69
  423. package/skills/a2h-utg-static/scripts/tests/test_external_surface_roots.mjs +43 -43
  424. package/skills/a2h-utg-static/scripts/tests/test_find_package_indirect.mjs +67 -67
  425. package/skills/a2h-utg-static/scripts/tests/test_forwarding_wrapper.mjs +38 -38
  426. package/skills/a2h-utg-static/scripts/tests/test_fragment_containment.mjs +85 -85
  427. package/skills/a2h-utg-static/scripts/tests/test_fragment_helper_trigger.mjs +92 -92
  428. package/skills/a2h-utg-static/scripts/tests/test_graph.mjs +55 -55
  429. package/skills/a2h-utg-static/scripts/tests/test_guard_clause.mjs +86 -86
  430. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundle_attribution.mjs +74 -74
  431. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundled_pages.mjs +181 -181
  432. package/skills/a2h-utg-static/scripts/tests/test_hybrid_scope.mjs +293 -293
  433. package/skills/a2h-utg-static/scripts/tests/test_hybrid_title_renders.mjs +118 -118
  434. package/skills/a2h-utg-static/scripts/tests/test_interaction_sites.mjs +272 -272
  435. package/skills/a2h-utg-static/scripts/tests/test_item_data_instance.mjs +51 -51
  436. package/skills/a2h-utg-static/scripts/tests/test_kotlin_fn_spans.mjs +69 -69
  437. package/skills/a2h-utg-static/scripts/tests/test_label_accessor_forms.mjs +187 -187
  438. package/skills/a2h-utg-static/scripts/tests/test_label_source.mjs +70 -70
  439. package/skills/a2h-utg-static/scripts/tests/test_launch_intent_guard.mjs +67 -67
  440. package/skills/a2h-utg-static/scripts/tests/test_layout_declared_fragment.mjs +103 -103
  441. package/skills/a2h-utg-static/scripts/tests/test_listener_call_forms.mjs +79 -79
  442. package/skills/a2h-utg-static/scripts/tests/test_listener_receiver_binding.mjs +47 -47
  443. package/skills/a2h-utg-static/scripts/tests/test_manifest_exported_default.mjs +40 -40
  444. package/skills/a2h-utg-static/scripts/tests/test_manifest_filters_modules.mjs +84 -84
  445. package/skills/a2h-utg-static/scripts/tests/test_mode_and_cb_param.mjs +172 -172
  446. package/skills/a2h-utg-static/scripts/tests/test_module_namespace.mjs +33 -33
  447. package/skills/a2h-utg-static/scripts/tests/test_multiple_entry_contracts.mjs +80 -80
  448. package/skills/a2h-utg-static/scripts/tests/test_nav_graph_xml.mjs +35 -35
  449. package/skills/a2h-utg-static/scripts/tests/test_nl_hints_gate.mjs +85 -85
  450. package/skills/a2h-utg-static/scripts/tests/test_node_id_collision.mjs +57 -57
  451. package/skills/a2h-utg-static/scripts/tests/test_non_gesture_step_flag.mjs +62 -62
  452. package/skills/a2h-utg-static/scripts/tests/test_out_of_scope_and_settings.mjs +72 -72
  453. package/skills/a2h-utg-static/scripts/tests/test_overload_and_climb.mjs +86 -86
  454. package/skills/a2h-utg-static/scripts/tests/test_pager_page_source.mjs +78 -78
  455. package/skills/a2h-utg-static/scripts/tests/test_pager_position_zero.mjs +65 -65
  456. package/skills/a2h-utg-static/scripts/tests/test_pager_variant_guard.mjs +172 -172
  457. package/skills/a2h-utg-static/scripts/tests/test_pipeline_llm_phases.mjs +107 -107
  458. package/skills/a2h-utg-static/scripts/tests/test_plain_dialog_nodes.mjs +167 -167
  459. package/skills/a2h-utg-static/scripts/tests/test_plaindialog_shared_anchor.mjs +117 -117
  460. package/skills/a2h-utg-static/scripts/tests/test_preference_click_nav.mjs +98 -98
  461. package/skills/a2h-utg-static/scripts/tests/test_preference_nesting.mjs +183 -183
  462. package/skills/a2h-utg-static/scripts/tests/test_preference_widgets.mjs +48 -48
  463. package/skills/a2h-utg-static/scripts/tests/test_read_text_crlf.mjs +41 -41
  464. package/skills/a2h-utg-static/scripts/tests/test_resolver_tier_parity.mjs +126 -126
  465. package/skills/a2h-utg-static/scripts/tests/test_review_fixes.mjs +135 -135
  466. package/skills/a2h-utg-static/scripts/tests/test_scope_utils.mjs +85 -85
  467. package/skills/a2h-utg-static/scripts/tests/test_sealed_dialog_state.mjs +148 -148
  468. package/skills/a2h-utg-static/scripts/tests/test_shared_overlay_split.mjs +63 -63
  469. package/skills/a2h-utg-static/scripts/tests/test_slug_parity.mjs +58 -58
  470. package/skills/a2h-utg-static/scripts/tests/test_starter_node_id.mjs +41 -41
  471. package/skills/a2h-utg-static/scripts/tests/test_state_guard_arity.mjs +109 -109
  472. package/skills/a2h-utg-static/scripts/tests/test_state_guard_commented_candidates.mjs +68 -68
  473. package/skills/a2h-utg-static/scripts/tests/test_state_guard_model_gates.mjs +127 -127
  474. package/skills/a2h-utg-static/scripts/tests/test_state_specific_hop.mjs +130 -130
  475. package/skills/a2h-utg-static/scripts/tests/test_synthetic_label_identity.mjs +51 -51
  476. package/skills/a2h-utg-static/scripts/tests/test_template_method_layout.mjs +81 -81
  477. package/skills/a2h-utg-static/scripts/tests/test_trigger_id_spelling.mjs +68 -68
  478. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_action_override.mjs +91 -91
  479. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_flow_filter.mjs +110 -110
  480. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_nl_hint_key.mjs +89 -89
  481. package/skills/a2h-utg-static/scripts/tests/test_uiless_host_fold.mjs +98 -98
  482. package/skills/a2h-utg-static/scripts/tests/test_uniapp_source.mjs +231 -231
  483. package/skills/a2h-utg-static/scripts/tests/test_view_click_refs.mjs +104 -104
  484. package/skills/a2h-utg-static/scripts/tests/test_view_id_label.mjs +69 -69
  485. package/skills/a2h-utg-static/scripts/tests/test_view_interactions.mjs +346 -346
  486. package/skills/a2h-utg-static/scripts/tests/test_viewpage_nav.mjs +340 -273
  487. package/skills/a2h-utg-static/scripts/tests/test_widget_class_scope.mjs +92 -92
  488. package/skills/a2h-utg-static/scripts/tests/test_window_nav_kotlin.mjs +158 -158
  489. package/skills/a2h-utg-static/scripts/tests/test_worklist_parts.mjs +65 -65
  490. package/skills/a2h-utg-static/scripts/uniapp_nav.mjs +1119 -1119
  491. package/skills/a2h-utg-static/scripts/uniapp_widgets.mjs +244 -244
  492. package/skills/a2h-utg-static/scripts/utg_html.mjs +721 -721
  493. package/skills/a2h-utg-static/scripts/viewpage_nav.mjs +589 -485
  494. package/skills/a2h-utg-static/scripts/window_nav.mjs +240 -240
  495. package/skills/a2h-utg-static/scripts/worklist_parts.mjs +154 -154
  496. package/skills/a2h-utg-static/tools/convert_static_utg_to_ui_elements.ts +769 -769
  497. package/skills/a2h-utg-static/tools/package.json +3 -3
@@ -1,1437 +1,1627 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Per-group source + resource pack: the files a conversion agent must read, found once.
4
- *
5
- * (Node >= 22.18, ESM, zero dependencies. Behaviour-identical port of
6
- * group_pack.py: same args, exit codes, stdout and output files.)
7
- *
8
- * Measured on a 14-group run, an agent spent ~28% of its turns *discovering* inputs
9
- * rather than converting: globbing for the Fragment/layout/style files of its own
10
- * group (14%), and grepping color.json / string.json / media/ one name at a time to
11
- * see whether a resource exists in the Harmony project (14%, one dump of a 51 KB
12
- * string.json). Every one of those answers is a pure function of the Android tree,
13
- * resource_mapping.md and the Harmony resources -- the same for every agent.
14
- *
15
- * This script resolves them per group and writes <out>/<GID>.md:
16
- *
17
- * * Source files, by relation: the member classes (meta.json `declared_at`), their
18
- * base-class chain, the layouts / pref XMLs / menus they reference (R.layout.x,
19
- * FooBinding, R.xml.x, R.menu.x, `<include>`), custom views used in those layouts,
20
- * and their in-project UI imports (dialogs, adapters, views...). Absolute paths
21
- * and line counts, so the agent issues one batched read.
22
- * * Style references -> the file:line that defines them.
23
- * * Resource table: every R.x.y / @x/y the group's files use -> its Harmony target
24
- * from resource_mapping.md, whether it exists on disk, and its value (string /
25
- * colour incl. dark / float), so no agent greps the resource JSON.
26
- *
27
- * Nothing here is a conclusion: it is a reading list plus lookups. The agent still
28
- * reads the files and still owns every decision; a file the pack missed is read as
29
- * before.
30
- *
31
- * group_pack.mjs build <harmony_dir> --android <android_dir> [--groups G001,G002]
32
- * group_pack.mjs lookup <harmony_dir> --android <android_dir> string/foo color/bar ...
33
- */
34
-
35
- import * as fs from 'node:fs';
36
- import * as path from 'node:path';
37
- import { fileURLToPath, pathToFileURL } from 'node:url';
38
-
39
- const DOC = `Per-group source + resource pack: the files a conversion agent must read, found once.
40
-
41
- Measured on a 14-group run, an agent spent ~28% of its turns *discovering* inputs
42
- rather than converting: globbing for the Fragment/layout/style files of its own
43
- group (14%), and grepping color.json / string.json / media/ one name at a time to
44
- see whether a resource exists in the Harmony project (14%, one dump of a 51 KB
45
- string.json). Every one of those answers is a pure function of the Android tree,
46
- resource_mapping.md and the Harmony resources -- the same for every agent.
47
-
48
- This script resolves them per group and writes <out>/<GID>.md:
49
-
50
- * Source files, by relation: the member classes (meta.json \`declared_at\`), their
51
- base-class chain, the layouts / pref XMLs / menus they reference (R.layout.x,
52
- FooBinding, R.xml.x, R.menu.x, \`<include>\`), custom views used in those layouts,
53
- and their in-project UI imports (dialogs, adapters, views...). Absolute paths
54
- and line counts, so the agent issues one batched read.
55
- * Style references -> the file:line that defines them.
56
- * Resource table: every R.x.y / @x/y the group's files use -> its Harmony target
57
- from resource_mapping.md, whether it exists on disk, and its value (string /
58
- colour incl. dark / float), so no agent greps the resource JSON.
59
-
60
- Nothing here is a conclusion: it is a reading list plus lookups. The agent still
61
- reads the files and still owns every decision; a file the pack missed is read as
62
- before.
63
-
64
- group_pack.mjs build <harmony_dir> --android <android_dir> [--groups G001,G002]
65
- group_pack.mjs lookup <harmony_dir> --android <android_dir> string/foo color/bar ...
66
- `;
67
-
68
- // ---------------------------------------------------------------- Python compat
69
- // Outputs are a contract read by other scripts and agents: byte-identical to the
70
- // Python version (json.dumps(indent=1, ensure_ascii=False), CRLF text writes on
71
- // Windows, pathlib semantics, Python sort/regex semantics).
72
-
73
- const IS_WIN = process.platform === 'win32';
74
- const EOL = IS_WIN ? '\r\n' : '\n';
75
-
76
- /** A float from json.loads: written back with Python repr. */
77
- export class PyFloat {
78
- constructor(value) { this.value = value; }
79
- valueOf() { return this.value; }
80
- }
81
-
82
- const KEY_ORDER = Symbol('pyKeyOrder');
83
- const INDEX_KEY = /^(?:0|[1-9][0-9]*)$/;
84
-
85
- function floatRepr(x, json) {
86
- if (!Number.isFinite(x)) {
87
- if (Number.isNaN(x)) { return json ? 'NaN' : 'nan'; }
88
- return x > 0 ? (json ? 'Infinity' : 'inf') : (json ? '-Infinity' : '-inf');
89
- }
90
- if (x === 0) { return Object.is(x, -0) ? '-0.0' : '0.0'; }
91
- const [m, e] = Math.abs(x).toExponential().split('e');
92
- const digits = m.replace('.', '');
93
- const exp = Number(e);
94
- let s;
95
- if (exp >= -4 && exp < 16) {
96
- if (exp >= 0) {
97
- const ip = digits.slice(0, exp + 1).padEnd(exp + 1, '0');
98
- s = ip + '.' + (digits.slice(exp + 1) || '0');
99
- } else {
100
- s = '0.' + '0'.repeat(-exp - 1) + digits;
101
- }
102
- } else {
103
- s = digits[0] + (digits.length > 1 ? '.' + digits.slice(1) : '') + 'e' + (exp < 0 ? '-' : '+') +
104
- String(Math.abs(exp)).padStart(2, '0');
105
- }
106
- return (x < 0 ? '-' : '') + s;
107
- }
108
-
109
- /** json.loads: floats -> PyFloat, unsafe ints -> BigInt, key order kept. */
110
- function pyJsonLoads(text) {
111
- let i = 0;
112
- const n = text.length;
113
- const fail = (msg) => { throw new SyntaxError(`${msg}: char ${i}`); };
114
- const ws = () => {
115
- while (i < n) {
116
- const c = text.charCodeAt(i);
117
- if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) { i++; } else { break; }
118
- }
119
- };
120
- const NUM = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/y;
121
- const str = () => {
122
- i++;
123
- let out = '';
124
- let start = i;
125
- for (;;) {
126
- if (i >= n) { fail('Unterminated string'); }
127
- const c = text.charCodeAt(i);
128
- if (c === 0x22) { out += text.slice(start, i); i++; return out; }
129
- if (c < 0x20) { fail('Invalid control character'); }
130
- if (c === 0x5c) {
131
- out += text.slice(start, i);
132
- const esc = text[i + 1];
133
- const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[esc];
134
- if (simple !== undefined) {
135
- out += simple;
136
- i += 2;
137
- } else if (esc === 'u') {
138
- const hex = text.slice(i + 2, i + 6);
139
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) { fail('Invalid \\uXXXX escape'); }
140
- out += String.fromCharCode(parseInt(hex, 16));
141
- i += 6;
142
- } else {
143
- fail('Invalid \\escape');
144
- }
145
- start = i;
146
- continue;
147
- }
148
- i++;
149
- }
150
- };
151
- const value = () => {
152
- ws();
153
- const c = text[i];
154
- if (c === '{') {
155
- i++;
156
- const o = {};
157
- const order = [];
158
- let hasIndex = false;
159
- ws();
160
- if (text[i] === '}') { i++; return o; }
161
- for (;;) {
162
- ws();
163
- if (text[i] !== '"') { fail('Expecting property name enclosed in double quotes'); }
164
- const k = str();
165
- ws();
166
- if (text[i] !== ':') { fail("Expecting ':' delimiter"); }
167
- i++;
168
- const v = value();
169
- if (!Object.hasOwn(o, k)) {
170
- order.push(k);
171
- if (INDEX_KEY.test(k)) { hasIndex = true; }
172
- }
173
- if (k === '__proto__') {
174
- Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
175
- } else {
176
- o[k] = v;
177
- }
178
- ws();
179
- if (text[i] === ',') { i++; continue; }
180
- if (text[i] === '}') { i++; break; }
181
- fail("Expecting ',' delimiter");
182
- }
183
- if (hasIndex) { o[KEY_ORDER] = order; }
184
- return o;
185
- }
186
- if (c === '[') {
187
- i++;
188
- const a = [];
189
- ws();
190
- if (text[i] === ']') { i++; return a; }
191
- for (;;) {
192
- a.push(value());
193
- ws();
194
- if (text[i] === ',') { i++; continue; }
195
- if (text[i] === ']') { i++; break; }
196
- fail("Expecting ',' delimiter");
197
- }
198
- return a;
199
- }
200
- if (c === '"') { return str(); }
201
- if (text.startsWith('null', i)) { i += 4; return null; }
202
- if (text.startsWith('true', i)) { i += 4; return true; }
203
- if (text.startsWith('false', i)) { i += 5; return false; }
204
- if (text.startsWith('NaN', i)) { i += 3; return new PyFloat(NaN); }
205
- if (text.startsWith('Infinity', i)) { i += 8; return new PyFloat(Infinity); }
206
- if (text.startsWith('-Infinity', i)) { i += 9; return new PyFloat(-Infinity); }
207
- NUM.lastIndex = i;
208
- const m = NUM.exec(text);
209
- if (!m) { fail('Expecting value'); }
210
- i += m[0].length;
211
- if (m[1] !== undefined || m[2] !== undefined) { return new PyFloat(Number(m[0])); }
212
- const num = Number(m[0]);
213
- return Number.isSafeInteger(num) ? (num === 0 ? 0 : num) : BigInt(m[0]);
214
- };
215
- const v = value();
216
- ws();
217
- if (i !== n) { fail('Extra data'); }
218
- return v;
219
- }
220
-
221
- function keysOf(o) {
222
- const ks = Object.keys(o);
223
- const ord = o[KEY_ORDER];
224
- if (!ord) { return ks; }
225
- const present = new Set(ks);
226
- const out = ord.filter((k) => present.has(k));
227
- const seen = new Set(out);
228
- for (const k of ks) { if (!seen.has(k)) { out.push(k); } }
229
- return out;
230
- }
231
-
232
- /** json.dumps key coercion for a Map key (str / int / float / bool / None). */
233
- function jsonKey(k) {
234
- if (typeof k === 'string') { return k; }
235
- if (k === null || k === undefined) { return 'null'; }
236
- if (k === true) { return 'true'; }
237
- if (k === false) { return 'false'; }
238
- if (k instanceof PyFloat) { return floatRepr(k.value, true); }
239
- if (typeof k === 'number' || typeof k === 'bigint') { return String(k); }
240
- throw new TypeError(`keys must be str, int, float, bool or None, not ${pyType(k)}`);
241
- }
242
-
243
- /** json.dumps(v, ensure_ascii=False, indent=indent); a Map is a dict in insertion order. */
244
- function pyJsonDumps(v, indent, level = 0) {
245
- if (v === null || v === undefined) { return 'null'; }
246
- if (v === true) { return 'true'; }
247
- if (v === false) { return 'false'; }
248
- if (typeof v === 'bigint') { return v.toString(); }
249
- if (v instanceof PyFloat) { return floatRepr(v.value, true); }
250
- if (typeof v === 'number') { return Number.isInteger(v) ? (Object.is(v, -0) ? '0' : String(v)) : floatRepr(v, true); }
251
- if (typeof v === 'string') { return JSON.stringify(v); }
252
- const pad = '\n' + ' '.repeat(indent * (level + 1));
253
- const end = '\n' + ' '.repeat(indent * level);
254
- if (Array.isArray(v)) {
255
- if (v.length === 0) { return '[]'; }
256
- return '[' + pad + v.map((x) => pyJsonDumps(x, indent, level + 1)).join(',' + pad) + end + ']';
257
- }
258
- const entries = v instanceof Map ? [...v].map(([k, x]) => [jsonKey(k), x]) : keysOf(v).map((k) => [k, v[k]]);
259
- if (entries.length === 0) { return '{}'; }
260
- return '{' + pad + entries.map(([k, x]) => JSON.stringify(k) + ': ' + pyJsonDumps(x, indent, level + 1))
261
- .join(',' + pad) + end + '}';
262
- }
263
-
264
- function pyType(v) {
265
- if (v === null || v === undefined) { return 'NoneType'; }
266
- if (typeof v === 'boolean') { return 'bool'; }
267
- if (typeof v === 'number') { return Number.isInteger(v) ? 'int' : 'float'; }
268
- if (typeof v === 'bigint') { return 'int'; }
269
- if (v instanceof PyFloat) { return 'float'; }
270
- if (typeof v === 'string') { return 'str'; }
271
- if (Array.isArray(v)) { return 'list'; }
272
- return 'dict';
273
- }
274
-
275
- const isDict = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof PyFloat);
276
-
277
- function truthy(v) {
278
- if (v === null || v === undefined || v === false) { return false; }
279
- if (v === true) { return true; }
280
- if (typeof v === 'number') { return v !== 0; }
281
- if (typeof v === 'bigint') { return v !== 0n; }
282
- if (v instanceof PyFloat) { return v.value !== 0; }
283
- if (typeof v === 'string' || Array.isArray(v)) { return v.length > 0; }
284
- if (v instanceof Map || v instanceof Set) { return v.size > 0; }
285
- return Object.keys(v).length > 0;
286
- }
287
-
288
- /** `a or b`. */
289
- const or = (a, b) => (truthy(a) ? a : b);
290
-
291
- /** d.get(k, default) on a json value: AttributeError unless it is a dict. */
292
- function dget(d, k, dflt = null) {
293
- if (!isDict(d)) { throw new TypeError(`'${pyType(d)}' object has no attribute 'get'`); }
294
- return Object.hasOwn(d, k) ? d[k] : dflt;
295
- }
296
-
297
- /** d[k]. */
298
- function dsub(d, k) {
299
- if (typeof d === 'string' || Array.isArray(d)) { throw new TypeError(`${pyType(d)} indices must be integers`); }
300
- if (!isDict(d)) { throw new TypeError(`'${pyType(d)}' object is not subscriptable`); }
301
- if (!Object.hasOwn(d, k)) { throw new Error(`KeyError: '${k}'`); }
302
- return d[k];
303
- }
304
-
305
- /** `for x in v` over a json value. */
306
- function pyIter(v) {
307
- if (Array.isArray(v)) { return v; }
308
- if (typeof v === 'string') { return [...v]; }
309
- if (isDict(v)) { return keysOf(v); }
310
- throw new TypeError(`'${pyType(v)}' object is not iterable`);
311
- }
312
-
313
- function cmpStr(a, b) {
314
- if (!/[\uD800-\uDFFF]/.test(a) && !/[\uD800-\uDFFF]/.test(b)) { return a < b ? -1 : a > b ? 1 : 0; }
315
- const x = [...a];
316
- const y = [...b];
317
- for (let i = 0; i < Math.min(x.length, y.length); i++) {
318
- const d = x[i].codePointAt(0) - y[i].codePointAt(0);
319
- if (d !== 0) { return d < 0 ? -1 : 1; }
320
- }
321
- return x.length < y.length ? -1 : x.length > y.length ? 1 : 0;
322
- }
323
-
324
- /** Python `<` for sort keys: bool/int as numbers, str by code point, arrays element-wise. */
325
- function pyCmp(a, b) {
326
- const na = typeof a === 'boolean' ? Number(a) : a;
327
- const nb = typeof b === 'boolean' ? Number(b) : b;
328
- if (typeof na === 'number' && typeof nb === 'number') { return na < nb ? -1 : na > nb ? 1 : 0; }
329
- if (typeof a === 'string' && typeof b === 'string') { return cmpStr(a, b); }
330
- if (Array.isArray(a) && Array.isArray(b)) {
331
- for (let i = 0; i < Math.min(a.length, b.length); i++) {
332
- const c = pyCmp(a[i], b[i]);
333
- if (c !== 0) { return c; }
334
- }
335
- return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
336
- }
337
- throw new TypeError(`'<' not supported between instances of '${pyType(a)}' and '${pyType(b)}'`);
338
- }
339
-
340
- /** sorted(items, key=key): stable. */
341
- function sortedBy(items, key = (x) => x) {
342
- const dec = [...items].map((v, i) => [key(v), i, v]);
343
- dec.sort((p, q) => pyCmp(p[0], q[0]) || p[1] - q[1]);
344
- return dec.map((d) => d[2]);
345
- }
346
-
347
- const NON_PRINTABLE = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;
348
-
349
- function strRepr(s) {
350
- const q = s.includes("'") && !s.includes('"') ? '"' : "'";
351
- let r = q;
352
- for (const ch of s) {
353
- const cp = ch.codePointAt(0);
354
- if (ch === q || ch === '\\') { r += '\\' + ch; }
355
- else if (ch === '\t') { r += '\\t'; }
356
- else if (ch === '\n') { r += '\\n'; }
357
- else if (ch === '\r') { r += '\\r'; }
358
- else if (ch !== ' ' && NON_PRINTABLE.test(ch)) {
359
- r += cp < 0x100 ? '\\x' + cp.toString(16).padStart(2, '0')
360
- : cp < 0x10000 ? '\\u' + cp.toString(16).padStart(4, '0') : '\\U' + cp.toString(16).padStart(8, '0');
361
- } else { r += ch; }
362
- }
363
- return r + q;
364
- }
365
-
366
- function pyRepr(v) {
367
- if (v === null || v === undefined) { return 'None'; }
368
- if (v === true) { return 'True'; }
369
- if (v === false) { return 'False'; }
370
- if (typeof v === 'bigint') { return v.toString(); }
371
- if (v instanceof PyFloat) { return floatRepr(v.value, false); }
372
- if (typeof v === 'number') { return Number.isInteger(v) ? String(v === 0 ? 0 : v) : floatRepr(v, false); }
373
- if (typeof v === 'string') { return strRepr(v); }
374
- if (Array.isArray(v)) { return '[' + v.map(pyRepr).join(', ') + ']'; }
375
- return '{' + keysOf(v).map((k) => strRepr(k) + ': ' + pyRepr(v[k])).join(', ') + '}';
376
- }
377
-
378
- /** str(v) / f"{v}". */
379
- const pyStr = (v) => (typeof v === 'string' ? v : pyRepr(v));
380
-
381
- /** Python str.isspace() characters (for \s and strip()). */
382
- const SP = '\\t\\n\\v\\f\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000';
383
- const pyStrip = (s) => s.replace(new RegExp(`^[${SP}]+|[${SP}]+$`, 'gu'), '');
384
-
385
- const LINE_BREAK = new RegExp('\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029]');
386
-
387
- /** str.splitlines(). */
388
- function splitlines(s) {
389
- if (s === '') { return []; }
390
- const parts = s.split(LINE_BREAK);
391
- if (parts[parts.length - 1] === '') { parts.pop(); }
392
- return parts;
393
- }
394
-
395
- const READ = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
396
- const STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
397
-
398
- /** Path.read_text(encoding="utf-8", errors="replace"), "" on OSError. */
399
- function _read(p) {
400
- let buf;
401
- try { buf = fs.readFileSync(p); } catch { return ''; }
402
- return READ.decode(buf).replace(/\r\n?/g, '\n');
403
- }
404
-
405
- function _load(p, dflt = null) {
406
- return isFile(p) ? pyJsonLoads(STRICT.decode(fs.readFileSync(p)).replace(/\r\n?/g, '\n')) : dflt;
407
- }
408
-
409
- function isFile(p) {
410
- try { return fs.statSync(p, { throwIfNoEntry: false })?.isFile() ?? false; } catch { return false; }
411
- }
412
- function isDir(p) {
413
- try { return fs.statSync(p, { throwIfNoEntry: false })?.isDirectory() ?? false; } catch { return false; }
414
- }
415
-
416
- // ---------------------------------------------------------------- paths (pathlib semantics)
417
- // A path is a normalised string (str(Path(x))); equality / dict keys are case-folded on Windows.
418
-
419
- const SEP = IS_WIN ? '\\' : '/';
420
-
421
- function splitPath(p) {
422
- if (IS_WIN) {
423
- const s = String(p).replace(/\//g, '\\');
424
- let drive = '';
425
- let rest = s;
426
- const unc = /^\\\\([^\\]+)\\([^\\]+)/.exec(s);
427
- if (unc) { drive = unc[0]; rest = s.slice(drive.length); }
428
- else if (/^[A-Za-z]:/.test(s)) { drive = s.slice(0, 2); rest = s.slice(2); }
429
- const root = rest.startsWith('\\') ? '\\' : '';
430
- return { drive, root, parts: rest.split('\\').filter((x) => x !== '' && x !== '.') };
431
- }
432
- const s = String(p);
433
- const root = s.startsWith('//') && !s.startsWith('///') ? '//' : s.startsWith('/') ? '/' : '';
434
- return { drive: '', root, parts: s.split('/').filter((x) => x !== '' && x !== '.') };
435
- }
436
-
437
- const fmt = ({ drive, root, parts }) => drive + root + parts.join(SEP) || '.';
438
-
439
- /** str(Path(p)). */
440
- export const pathStr = (p) => fmt(splitPath(p));
441
-
442
- /** Path(a) / b / c ... */
443
- function pJoin(a, ...segs) {
444
- let cur = splitPath(a);
445
- for (const s of segs) {
446
- const n = splitPath(s);
447
- if (n.root || (n.drive && n.drive.toLowerCase() !== cur.drive.toLowerCase())) {
448
- cur = { drive: n.drive || cur.drive, root: n.root, parts: n.parts };
449
- } else if (n.drive) {
450
- cur = { drive: n.drive, root: cur.root, parts: [...cur.parts, ...n.parts] };
451
- } else {
452
- cur = { ...cur, parts: [...cur.parts, ...n.parts] };
453
- }
454
- }
455
- return fmt(cur);
456
- }
457
-
458
- /** Path.parts. */
459
- function pParts(p) {
460
- const s = splitPath(p);
461
- return s.drive || s.root ? [s.drive + s.root, ...s.parts] : s.parts;
462
- }
463
- const pName = (p) => { const s = splitPath(p).parts; return s.length ? s[s.length - 1] : ''; };
464
- function pSuffix(p) {
465
- const n = pName(p);
466
- const i = n.lastIndexOf('.');
467
- return i > 0 && i < n.length - 1 ? n.slice(i) : '';
468
- }
469
- const pStem = (p) => { const n = pName(p); const x = pSuffix(p); return x ? n.slice(0, -x.length) : n; };
470
- function pParent(p) {
471
- const s = splitPath(p);
472
- return s.parts.length ? fmt({ ...s, parts: s.parts.slice(0, -1) }) : fmt(s);
473
- }
474
- /** Key for path equality / hashing. */
475
- const pKey = (p) => (IS_WIN ? pathStr(p).toLowerCase() : pathStr(p));
476
- /** PurePath `<` order. */
477
- const pOrder = (p) => (IS_WIN ? pathStr(p).toLowerCase().split('\\') : pathStr(p).split('/'));
478
-
479
- /** Entries of a directory in os.scandir order (no sort). Throws on OSError. */
480
- function listDir(d) {
481
- const names = [];
482
- const h = fs.opendirSync(d);
483
- try {
484
- for (let e = h.readSync(); e !== null; e = h.readSync()) { names.push(e.name); }
485
- } finally { h.closeSync(); }
486
- return names.map((nm) => pJoin(d, nm));
487
- }
488
-
489
- /** Path(d).glob("*.<ext>"): scandir order, case-insensitive on Windows, [] when missing. */
490
- function globExt(d, ext) {
491
- let all;
492
- try { all = listDir(d); } catch { return []; }
493
- return all.filter((p) => (IS_WIN ? pName(p).toLowerCase().endsWith(ext.toLowerCase()) : pName(p).endsWith(ext)));
494
- }
495
-
496
- // ---------------------------------------------------------------- patterns
497
- // Python `re` (str patterns) is Unicode-aware: \w = alnum + "_", \b is built on
498
- // that \w, \s = str.isspace(), \d = Nd. Spelled out here so the 'u' JS regexes
499
- // match exactly what the Python ones did. re.M `^`/`$` only treat "\n" as a line
500
- // break (JS's 'm' also breaks on CR, LS and PS), hence the explicit anchors.
501
-
502
- const W = '[\\p{L}\\p{N}_]';
503
- const WC = '\\p{L}\\p{N}_';
504
- const B = `(?:(?<=${W})(?!${W})|(?<!${W})(?=${W}))`;
505
- const S = `[${SP}]`;
506
- const NS = `[^${SP}]`;
507
- const BOL = '(?<![^\\n])';
508
- const EOLA = '(?![^\\n])';
509
- const KINDS_R = 'layout|xml|menu|string|color|drawable|mipmap|dimen|style|plurals|array|integer|bool|font|raw|anim';
510
-
511
- export const SKIP_DIRS = new Set(['build', '.git', '.gradle', '.idea', 'node_modules', '.cxx', 'intermediates']);
512
- export const SRC_EXT = ['.java', '.kt'];
513
- export const UI_SUFFIX = new RegExp('(Dialog|Fragment|Activity|View|Adapter|ViewHolder|Holder|Layout|' +
514
- 'Preference|Sheet|Menu|Handler|Item|Row|Bar|Button|Widget)$', 'u');
515
- export const R_REF = new RegExp(`${B}R\\.(${KINDS_R})\\.(${W}+)`, 'gu');
516
- export const X_REF = new RegExp(`@(${KINDS_R})/([${WC}.]+)`, 'gu');
517
- export const BINDING = new RegExp(`${B}([A-Z]${W}*?)Binding${B}`, 'gu');
518
- export const IMPORT = new RegExp(`${BOL}${S}*import${S}+(?:static${S}+)?([${WC}.]+?)(?:\\.\\*)?${S}*;?${S}*${EOLA}`, 'gu');
519
- export const EXTENDS_JAVA = new RegExp(`${B}class${S}+(${W}+)(?:<[^>{]*>)?${S}+extends${S}+([${WC}.]+)`, 'u');
520
- export const EXTENDS_KT = new RegExp(`${B}class${S}+(${W}+)[^:{]*:${S}*([${WC}.]+)${S}*\\(`, 'u');
521
- export const ASSET_LIT = new RegExp(`"([${WC}./-]+\\.(?:csv|json|txt|xml|html|md))"`, 'gu');
522
- export const CLASS_TOKEN = new RegExp(`${B}([A-Z]${W}+)${B}`, 'gu');
523
- export const CUSTOM_TAG = new RegExp(`<([a-z]${W}*(?:\\.${W}+)+)[${SP}>/]`, 'gu');
524
- export const FILE_TYPES = new Set(['layout', 'xml', 'menu', 'drawable', 'mipmap', 'font', 'raw', 'anim']);
525
- export const VALUE_JSON = new Map([['string', 'string'], ['color', 'color'], ['dimen', 'float'], ['integer', 'integer'],
526
- ['bool', 'boolean'], ['plurals', 'plural']]);
527
- export const TABLE_TYPES = ['string', 'plurals', 'color', 'dimen', 'integer', 'bool', 'drawable', 'mipmap',
528
- 'array', 'font', 'raw'];
529
- export const MAX_RELATED = 30;
530
- export const MAPPINGS = path.join(path.dirname(path.dirname(fs.realpathSync.native(fileURLToPath(import.meta.url)))),
531
- 'references', 'mappings');
532
- export const XML_TAG = new RegExp(`<([A-Za-z][${WC}.]*)[${SP}>/]`, 'gu');
533
- export const LISTENER = new RegExp(`${B}(?:set|add)?On(${W}+?)(?:Change)?Listener${B}`, 'gu');
534
- export const HEADING = new RegExp(`^(#{2,4})${S}+(.*${NS})${S}*$`, 'u');
535
- export const ASCII_WORD = /[A-Za-z][A-Za-z0-9]+/g;
536
- // Heading words that name a category, not a widget: never a match on their own.
537
- export const GENERIC = new Set(['Android', 'HarmonyOS', 'API', 'UI', 'Mapping', 'Reference', 'View', 'Layout', 'Text',
538
- 'Image', 'Button', 'Event', 'Events', 'New', 'vs', 'and', 'or', 'the']);
539
- const VIEW_CLASS = new RegExp(`class="([${WC}.$]+)"`, 'gu');
540
- const EMBEDDED = new RegExp(`(?:android:name|android:fragment|app:fragment)="([${WC}.]+)"`, 'gu');
541
- const R_LAYOUT = new RegExp(`${B}R\\.layout\\.(${W}+)`, 'gu');
542
- const MAP_KEY = new RegExp(`#(${W}+)/(.+)$`, 'u');
543
- const STRIP_LINE = /:\p{Nd}+(?=\n?$)/gu;
544
- const UPPER = /^\p{Uppercase}$/u;
545
-
546
- /** re.findall: the group (1 group) or the tuple of groups. */
547
- function findall(re, text) {
548
- return [...text.matchAll(re)].map((m) => (m.length === 2 ? m[1] : m.slice(1)));
549
- }
550
- /** set(xs) iterated: first-occurrence order. */
551
- const uniq = (xs) => [...new Set(xs)];
552
- const last = (xs) => xs[xs.length - 1];
553
- const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
554
-
555
- export function mappingSections(root = MAPPINGS) {
556
- // [(file, start, end, level, heading, words)] for every ##..#### heading.
557
- const out = [];
558
- for (const f of sortedBy(globExt(pathStr(root), '.md'), pOrder)) {
559
- const lines = splitlines(_read(f));
560
- const heads = [];
561
- lines.forEach((l, i) => { const m = HEADING.exec(l); if (m) { heads.push([i + 1, m[1].length, m[2]]); } });
562
- heads.forEach(([i, lvl, h], k) => {
563
- const nx = heads.slice(k + 1).find(([, l2]) => l2 <= lvl);
564
- const end = nx ? nx[0] - 1 : lines.length;
565
- const words = new Set((h.split('→')[0].match(ASCII_WORD) || []).filter((w) => !GENERIC.has(w)));
566
- out.push([f, i, end, lvl, h, words]);
567
- });
568
- }
569
- return out;
570
- }
571
-
572
- export function usedNames(pack, uiInfo, group) {
573
- // Widget class short names (layout tags, captured view trees) and listener
574
- // kinds (setOnClickListener -> Click) the group's own files use.
575
- const names = new Set();
576
- for (const [p, rel] of pack.files.values()) {
577
- if (rel === 'related') { continue; }
578
- const text = _read(p);
579
- if (pSuffix(p) === '.xml') {
580
- for (const t of findall(XML_TAG, text)) { names.add(last(t.split('.'))); }
581
- } else {
582
- for (const t of findall(LISTENER, text)) { names.add(t); }
583
- for (const t of findall(CLASS_TOKEN, text)) {
584
- if (['View', 'Layout', 'Bar', 'Sheet', 'Dialog', 'Pager'].some((x) => t.endsWith(x))) { names.add(t); }
585
- }
586
- }
587
- }
588
- for (const d of pyIter(or(dget(group, 'page_dirs'), []))) {
589
- const vx = pJoin(uiInfo, d, 'view.xml');
590
- if (isFile(vx)) {
591
- for (const c of findall(VIEW_CLASS, _read(vx))) { names.add(last(c.split('.'))); }
592
- }
593
- }
594
- return names;
595
- }
596
-
597
- // The interaction reference titles its sections in Chinese ("点击手势", "滑动手势"):
598
- // an Android signal -> the heading word that names it.
599
- export const SIGNAL_WORDS = new Map(Object.entries({
600
- Click: '点击', ItemClick: '点击', LongClick: '长按', ItemLongClick: '长按',
601
- Touch: '触摸', Scroll: '滑动', Fling: '滑动', Swipe: '滑动', Drag: '拖', Refresh: '滑动',
602
- SwipeRefreshLayout: '滑动', MotionLayout: '动画', ItemTouchHelper: '滑动删除',
603
- ObjectAnimator: '属性动画', ValueAnimator: '属性动画', AnimatorListener: '动画监听',
604
- FocusChange: '焦点', Key: '键盘', EditorAction: '键盘',
605
- }));
606
- export const WHOLE_FILE_BELOW = 12_000; // a reference this small is listed whole
607
-
608
- const secKey = (s) => [pKey(s[0]), s[1], s[2], s[3], s[4]].join('\u0000');
609
-
610
- export function mappingIndex(names, sections = null) {
611
- // Deepest matching section per (file, name): the agent reads exactly those
612
- // line ranges instead of paging through a 175 KB reference.
613
- sections = sections ?? mappingSections();
614
- names = new Set(names);
615
- const picked = new Map(); // (file, word) -> {f, w, sec}
616
- for (const [f, a, b, lvl, h, words] of sections) {
617
- const hit = new Set([...words].filter((w) => names.has(w)));
618
- if (pName(f).includes('interaction')) {
619
- // Chinese signal words name interaction sections only; elsewhere
620
- // "动画" also titles unrelated sections (Compose animation APIs).
621
- for (const n of names) { const sw = SIGNAL_WORDS.get(n); if (sw && h.includes(sw)) { hit.add(n); } }
622
- }
623
- for (const w of sortedBy(hit)) {
624
- const k = pKey(f) + '\u0000' + w;
625
- const cur = picked.get(k)?.sec;
626
- if (cur === undefined || lvl > cur[3] || (lvl === cur[3] && a < cur[1])) {
627
- picked.set(k, { f, w, sec: [f, a, b, lvl, h] });
628
- }
629
- }
630
- }
631
- const rows = new Map(); // sec -> {sec, ws}
632
- for (const { w, sec } of picked.values()) {
633
- const k = secKey(sec);
634
- if (!rows.has(k)) { rows.set(k, { sec, ws: new Set() }); }
635
- rows.get(k).ws.add(w);
636
- }
637
- // A used class with no section of its own but named in a table row: point
638
- // at those lines (MotionLayout is a row of the ConstraintLayout tables).
639
- const files = new Map();
640
- for (const s of sections) { if (!files.has(pKey(s[0]))) { files.set(pKey(s[0]), s[0]); } }
641
- for (const f of sortedBy(files.values(), pOrder)) {
642
- if (fs.statSync(f).size < WHOLE_FILE_BELOW || pName(f).includes('interaction')) { continue; }
643
- const covered = new Set([...picked.values()].filter((x) => pKey(x.f) === pKey(f)).map((x) => x.w));
644
- const lines = splitlines(_read(f));
645
- for (const w of sortedBy([...names].filter((x) => !covered.has(x) && !GENERIC.has(x)))) {
646
- const cps = [...w];
647
- if (!(cps.length > 5 && UPPER.test(cps[0]) && cps.slice(1).some((c) => UPPER.test(c)))) {
648
- continue; // CamelCase class names only, not prose words
649
- }
650
- const re = new RegExp(`${B}${reEscape(w)}${B}`, 'u');
651
- const hits = [];
652
- lines.forEach((l, i) => { if (re.test(l)) { hits.push(i + 1); } });
653
- if (hits.length) {
654
- const sec = [f, hits[0], hits[0], 9, `rows naming ${w}: lines ${hits.slice(0, 6).join(', ')}`];
655
- rows.set(secKey(sec), { sec, ws: new Set([w]) });
656
- }
657
- }
658
- }
659
- for (const f of files.values()) {
660
- if (fs.statSync(f).size < WHOLE_FILE_BELOW) {
661
- const n = splitlines(_read(f)).length;
662
- for (const [k, v] of [...rows]) { if (pKey(v.sec[0]) === pKey(f)) { rows.delete(k); } }
663
- const sec = [f, 1, n, 1, '(whole file — small)'];
664
- rows.set(secKey(sec), { sec, ws: new Set(['all']) });
665
- }
666
- }
667
- return sortedBy([...rows.values()].map(({ sec, ws }) => [sec, sortedBy(ws)]), (r) => [pathStr(r[0][0]), r[0][1]]);
668
- }
669
-
670
- export function snake(camel) {
671
- return camel.replace(/(?<!^)(?=[A-Z])/g, '_').toLowerCase();
672
- }
673
-
674
- // ---------------------------------------------------------------- Android index
675
-
676
- /** Name -> files for sources and resources, excluding build outputs. */
677
- export class AndroidIndex {
678
- constructor(root) {
679
- this.root = pathStr(root);
680
- this.by_class = new Map(); // stem -> [path]
681
- this.by_fqcn = new Map(); // fqcn -> path
682
- this.res = new Map(); // "kind\0name" -> [path]
683
- this.values = [];
684
- this.assets = new Map(); // name -> [path]
685
- this._defs = new Map();
686
- for (const p of this._walk(this.root)) {
687
- const parts = pParts(p);
688
- const suf = pSuffix(p);
689
- if (SRC_EXT.includes(suf) && (parts.includes('java') || parts.includes('kotlin'))) {
690
- if (!this.by_class.has(pStem(p))) { this.by_class.set(pStem(p), []); }
691
- this.by_class.get(pStem(p)).push(p);
692
- const k = parts.includes('java') ? 'java' : 'kotlin';
693
- const rel = parts.slice(parts.lastIndexOf(k) + 1);
694
- this.by_fqcn.set(rel.join('.').slice(0, -suf.length), p);
695
- } else if (parts.includes('assets') && parts.includes('src')) {
696
- if (!this.assets.has(pName(p))) { this.assets.set(pName(p), []); }
697
- this.assets.get(pName(p)).push(p);
698
- } else if (parts.length >= 3 && parts[parts.length - 3] === 'res') {
699
- const kind = parts[parts.length - 2].split('-')[0];
700
- if (kind === 'values') {
701
- if (suf === '.xml') { this.values.push(p); }
702
- } else {
703
- const key = kind + '\u0000' + pStem(p).split('.')[0];
704
- if (!this.res.has(key)) { this.res.set(key, []); }
705
- this.res.get(key).push(p);
706
- }
707
- }
708
- }
709
- }
710
-
711
- * _walk(d) {
712
- let entries;
713
- try { entries = listDir(d); } catch { return; }
714
- for (const e of entries) {
715
- if (isDir(e)) {
716
- const nm = pName(e);
717
- if (!SKIP_DIRS.has(nm) && !nm.startsWith('.')) { yield* this._walk(e); }
718
- } else {
719
- yield e;
720
- }
721
- }
722
- }
723
-
724
- /** Prefer src/main and unqualified resource dirs. */
725
- static _rank(p) {
726
- const s = pathStr(p).replace(/\\/g, '/');
727
- return [!s.includes('/src/main/'), pName(pParent(p)).includes('-'), [...s].length];
728
- }
729
-
730
- res_file(kind, name) {
731
- const hits = this.res.get(kind + '\u0000' + name) || [];
732
- return hits.length ? sortedBy(hits, AndroidIndex._rank)[0] : null;
733
- }
734
-
735
- cls(name, imports = [], near = null) {
736
- if (typeof name !== 'string') { throw new TypeError(`argument of type '${pyType(name)}' is not iterable`); }
737
- if (name.includes('.') && this.by_fqcn.has(name)) { return this.by_fqcn.get(name); }
738
- const simple = last(name.split('.'));
739
- for (const imp of imports) {
740
- if (imp.endsWith('.' + simple) && this.by_fqcn.has(imp)) { return this.by_fqcn.get(imp); }
741
- }
742
- const hits = this.by_class.get(simple) || [];
743
- if (near !== null) {
744
- const same = hits.filter((h) => pKey(pParent(h)) === pKey(pParent(near)));
745
- if (same.length) { return same[0]; }
746
- }
747
- return hits.length >= 1 ? sortedBy(hits, AndroidIndex._rank)[0] : null;
748
- }
749
-
750
- /** name -> [file, line] of the first `<tag name="...">` in values/*.xml. */
751
- value_defs(tag) {
752
- if (!this._defs.has(tag)) {
753
- const pat = new RegExp(`<${tag}${S}+name="([^"]+)"`, 'u');
754
- const found = new Map();
755
- for (const p of sortedBy(this.values, AndroidIndex._rank)) {
756
- splitlines(_read(p)).forEach((line, i) => {
757
- const m = pat.exec(line);
758
- if (m && !found.has(m[1])) { found.set(m[1], [p, i + 1]); }
759
- });
760
- }
761
- this._defs.set(tag, found);
762
- }
763
- return this._defs.get(tag);
764
- }
765
- }
766
-
767
- // ---------------------------------------------------------------- Harmony resources
768
-
769
- /** Key of a (qual, kind, name) value: name keeps its json type (1 != "1"). */
770
- function valKey(qual, kind, name) {
771
- if (Array.isArray(name) || isDict(name)) { throw new TypeError(`unhashable type: '${pyType(name)}'`); }
772
- return [qual, kind, typeof name === 'string' ? 's:' + name : 'o:' + pyRepr(name)].join('\u0000');
773
- }
774
-
775
- export class HarmonyRes {
776
- constructor(harmonyDir, module = 'entry') {
777
- this.base = pJoin(harmonyDir, module, 'src', 'main', 'resources');
778
- this.mapping = new Map(); // "kind\0name" -> [[target, kind]]
779
- const mp = pJoin(harmonyDir, '.hometrans', 'resource_mapping.md');
780
- if (isFile(mp)) { this._parse_mapping(mp); }
781
- this.values = new Map();
782
- for (const qual of ['base', 'zh_CN', 'dark']) {
783
- for (const f of globExt(pJoin(this.base, qual, 'element'), '.json')) {
784
- const data = or(_load(f, {}), {});
785
- if (!isDict(data)) { throw new TypeError(`'${pyType(data)}' object has no attribute 'items'`); }
786
- for (const kind of keysOf(data)) {
787
- const rows = data[kind];
788
- for (const r of Array.isArray(rows) ? rows : []) {
789
- if (isDict(r) && Object.hasOwn(r, 'name')) {
790
- this.values.set(valKey(qual, kind, r.name), Object.hasOwn(r, 'value') ? r.value : null);
791
- }
792
- }
793
- }
794
- }
795
- }
796
- }
797
-
798
- _parse_mapping(p) {
799
- let inDetail = false;
800
- for (const line of splitlines(_read(p))) {
801
- if (line.startsWith('## ')) {
802
- inDetail = line.includes('Mapping Details') || line.includes('映射明细');
803
- continue;
804
- }
805
- if (!inDetail || !line.startsWith('| res/')) { continue; }
806
- const t = pyStrip(line).replace(/^\|+|\|+$/g, '');
807
- const cols = t.split('|').map(pyStrip);
808
- if (cols.length < 6) { continue; }
809
- const [src, target, kind] = [cols[0], cols[4], cols[5]];
810
- let key;
811
- if (src.includes('#')) {
812
- const m = MAP_KEY.exec(src);
813
- key = m ? [m[1], m[2]] : null;
814
- } else {
815
- key = [pName(pParent(src)).split('-')[0], pStem(src).split('.')[0]];
816
- }
817
- if (key) {
818
- const k = key.join('\u0000');
819
- if (!this.mapping.has(k)) { this.mapping.set(k, []); }
820
- this.mapping.get(k).push([target, kind]);
821
- }
822
- }
823
- }
824
-
825
- value(kind, name) {
826
- const jk = VALUE_JSON.get(kind);
827
- if (!jk) { return null; }
828
- const out = {};
829
- for (const qual of ['base', 'zh_CN', 'dark']) {
830
- const v = this.values.get(valKey(qual, jk, name));
831
- if (v !== undefined && v !== null) { out[qual] = v; }
832
- }
833
- return Object.keys(out).length ? out : null;
834
- }
835
-
836
- row(kind, name) {
837
- const targets = this.mapping.get(kind + '\u0000' + name) || [];
838
- const t0 = targets.find(([t]) => t && t !== 'N/A');
839
- const tgt = t0 ? t0[0] : null;
840
- const status = targets.length ? targets[0][1] : 'not in mapping';
841
- let exists = null;
842
- if (tgt) {
843
- const f = tgt.split('#')[0];
844
- const p = f.startsWith('resources/') ? pJoin(pParent(this.base), f) : pJoin(this.base, f);
845
- exists = isFile(p) && (!tgt.includes('#') || this.value(kind, name) !== null || !VALUE_JSON.has(kind));
846
- }
847
- const hname = tgt && tgt.includes('#') ? last(tgt.split('#')) : (tgt ? pStem(tgt) : null);
848
- let ref = null;
849
- if (tgt && tgt.includes('#')) {
850
- ref = `app.${pStem(tgt.split('#')[0])}.${hname}`; // element/string.json#x
851
- } else if (tgt && tgt.includes('/media/')) {
852
- ref = `app.media.${hname}`;
853
- } else if (tgt && tgt.includes('/rawfile/')) {
854
- ref = 'rawfile ' + tgt.slice(tgt.indexOf('/rawfile/') + '/rawfile/'.length);
855
- }
856
- return { android: `${kind}/${name}`, harmony: tgt, ref: ref || tgt,
857
- status, exists, value: this.value(kind, hname || name) };
858
- }
859
- }
860
-
861
- // ---------------------------------------------------------------- pack
862
-
863
- export class Pack {
864
- constructor(idx) {
865
- this.idx = idx;
866
- this.files = new Map(); // pKey -> [path, relation, reason]
867
- this.refs = new Map(); // "kind\0name" -> [kind, name]
868
- this.styles = new Set();
869
- this.arrays = new Set();
870
- this.assets = new Map(); // pKey -> path
871
- }
872
-
873
- has(p) { return this.files.has(pKey(p)); }
874
-
875
- add(p, relation, why) {
876
- if (p === null || p === undefined) { return false; }
877
- p = pathStr(p);
878
- if (this.files.has(pKey(p))) { return false; }
879
- this.files.set(pKey(p), [p, relation, why]);
880
- return true;
881
- }
882
-
883
- /** A host Activity contributes its window chrome: itself, its base chain and its own
884
- * layouts -- not every screen it can show (its R.xml.* are sibling pref screens). */
885
- scan_host(p, label) {
886
- if (!this.add(p, 'host', `host activity of ${pyStr(label)}`)) { return; }
887
- const text = _read(p);
888
- const names = [...findall(BINDING, text).map(snake), ...findall(R_LAYOUT, text)];
889
- for (const name of sortedBy(uniq(names))) {
890
- const lay = this.idx.res_file('layout', name);
891
- if (lay && this.add(lay, 'host', `layout of ${pName(p)}`)) { this.scan_xml(lay, 'host'); }
892
- }
893
- const m = EXTENDS_JAVA.exec(text) || EXTENDS_KT.exec(text);
894
- const base = m ? this.idx.cls(m[2], findall(IMPORT, text), p) : null;
895
- if (base !== null && !this.has(base)) { this.scan_host(base, label); }
896
- }
897
-
898
- scan_source(p, relation, followBase = true) {
899
- const text = _read(p);
900
- const imports = findall(IMPORT, text);
901
- for (const lit of uniq(findall(ASSET_LIT, text))) {
902
- for (const a of (this.idx.assets.get(last(lit.split('/'))) || []).slice(0, 1)) {
903
- if (!this.assets.has(pKey(a))) { this.assets.set(pKey(a), a); }
904
- }
905
- }
906
- for (const [kind, name] of findall(R_REF, text)) { this._ref(kind, name, p, relation); }
907
- for (const b of uniq(findall(BINDING, text))) {
908
- const lay = this.idx.res_file('layout', snake(b));
909
- if (lay && this.add(lay, relation, `${b}Binding in ${pName(p)}`)) { this.scan_xml(lay, relation); }
910
- }
911
- if (followBase) {
912
- const m = EXTENDS_JAVA.exec(text) || EXTENDS_KT.exec(text);
913
- if (m) {
914
- const base = this.idx.cls(m[2], imports, p);
915
- if (base && this.add(base, 'base', `base of ${m[1]}`)) { this.scan_source(base, 'base', true); }
916
- }
917
- }
918
- return imports;
919
- }
920
-
921
- _addRef(kind, name) {
922
- const k = kind + '\u0000' + name;
923
- if (!this.refs.has(k)) { this.refs.set(k, [kind, name]); }
924
- }
925
-
926
- _ref(kind, name, src, relation) {
927
- if (['layout', 'xml', 'menu'].includes(kind)) {
928
- const f = this.idx.res_file(kind, name);
929
- if (f && this.add(f, relation, `R.${kind}.${name} in ${pName(src)}`)) { this.scan_xml(f, relation); }
930
- } else if (kind === 'style') {
931
- this.styles.add(name.replace(/_/g, '.'));
932
- } else {
933
- if (kind === 'array') { this.arrays.add(name); }
934
- this._addRef(kind, name);
935
- }
936
- }
937
-
938
- scan_xml(p, relation) {
939
- const text = _read(p);
940
- for (const [kind, name] of findall(X_REF, text)) {
941
- if (['layout', 'xml', 'menu'].includes(kind)) {
942
- const f = this.idx.res_file(kind, name);
943
- if (f && this.add(f, relation, `@${kind}/${name} in ${pName(p)}`)) { this.scan_xml(f, relation); }
944
- } else if (kind === 'style') {
945
- this.styles.add(name);
946
- } else {
947
- if (kind === 'array') { this.arrays.add(name); }
948
- this._addRef(kind, name);
949
- }
950
- }
951
- for (const tag of uniq(findall(CUSTOM_TAG, text))) {
952
- if (['android.', 'androidx.', 'com.google.'].some((x) => tag.startsWith(x))) { continue; }
953
- const c = this.idx.cls(tag);
954
- if (c && this.add(c, 'custom-view', `<${last(tag.split('.'))}> in ${pName(p)}`)) {
955
- this.scan_source(c, 'custom-view', false);
956
- }
957
- }
958
- // fragments embedded by layout: <fragment android:name>, FragmentContainerView, prefs
959
- for (const m of text.matchAll(EMBEDDED)) {
960
- const c = m[1].includes('.') ? this.idx.cls(m[1]) : null;
961
- if (c && this.add(c, relation, `embedded fragment in ${pName(p)}`)) { this.scan_source(c, relation, false); }
962
- }
963
- }
964
- }
965
-
966
- function _memberClasses(meta, idx, android) {
967
- // A page's own sources: its class (declared_at; the activity class when declared_at
968
- // is only the manifest), its attached nodes, its layouts, its extends_base.
969
- const out = [];
970
- const locs = [dget(meta, 'declared_at'), ...pyIter(or(dget(meta, 'attached_nodes'), [])).map((a) => dget(a, 'declared_at'))];
971
- for (const loc of locs) {
972
- if (!truthy(loc)) { continue; }
973
- if (typeof loc !== 'string') { throw new TypeError('expected string or bytes-like object'); }
974
- let p = pJoin(android, loc.replace(STRIP_LINE, ''));
975
- if (pName(p) === 'AndroidManifest.xml') {
976
- const act = or(dget(or(dget(meta, 'activity_info'), {}), 'activity'), dget(meta, 'label'));
977
- p = truthy(act) ? idx.cls(act) : null;
978
- } else if (!isFile(p) && SRC_EXT.includes(pSuffix(p))) {
979
- p = idx.cls(pStem(p)); // static UTG recorded the class in another module
980
- }
981
- if (p !== null && isFile(p)) { out.push(p); }
982
- }
983
- const hints = or(dget(meta, 'source_hints'), {});
984
- for (const lf of pyIter(or(dget(hints, 'layout_files'), []))) {
985
- const p = pJoin(android, lf);
986
- if (isFile(p)) { out.push(p); }
987
- }
988
- if (truthy(dget(hints, 'extends_base'))) {
989
- const c = idx.cls(dsub(hints, 'extends_base'));
990
- if (c) { out.push(c); }
991
- }
992
- return out;
993
- }
994
-
995
- export function buildGroup(group, uiInfo, idx, hres, android) {
996
- const pack = new Pack(idx);
997
- const hosts = [];
998
- for (const d of pyIter(or(dget(group, 'page_dirs'), []))) {
999
- const meta = or(_load(pJoin(uiInfo, d, 'meta.json'), {}), {});
1000
- const label = dget(meta, 'label', d);
1001
- const members = _memberClasses(meta, idx, android);
1002
- for (const p of members) {
1003
- if (pSuffix(p) === '.xml') {
1004
- if (pack.add(p, 'member', `layout of ${pyStr(label)}`)) { pack.scan_xml(p, 'member'); }
1005
- } else if (pack.add(p, 'member', `class of ${pyStr(label)}`)) {
1006
- pack.scan_source(p, 'member');
1007
- }
1008
- }
1009
- // the Activity hosting a fragment/dialog owns its toolbar and window chrome
1010
- const act = dget(or(dget(meta, 'activity_info'), {}), 'activity');
1011
- const h = truthy(act) ? idx.cls(act) : null;
1012
- if (h !== null && !members.some((m) => pKey(m) === pKey(h))) { hosts.push([h, label]); }
1013
- }
1014
- for (const [h, label] of hosts) { pack.scan_host(h, label); }
1015
- // one level of related classes from member/base sources: same-package types the
1016
- // code names (no import line), and in-project imports that look like UI classes
1017
- let related = 0;
1018
- for (const [p, rel] of [...pack.files.values()]) {
1019
- if (!['member', 'base'].includes(rel) || !SRC_EXT.includes(pSuffix(p))) { continue; }
1020
- const text = _read(p);
1021
- const cands = [];
1022
- for (const tok of sortedBy(uniq(findall(CLASS_TOKEN, text)))) {
1023
- for (const h of idx.by_class.get(tok) || []) {
1024
- if (pKey(pParent(h)) === pKey(pParent(p)) && pKey(h) !== pKey(p)) { cands.push([h, `same package, used by ${pName(p)}`]); }
1025
- }
1026
- }
1027
- for (const imp of findall(IMPORT, text)) {
1028
- if (idx.by_fqcn.has(imp) && UI_SUFFIX.test(last(imp.split('.')))) {
1029
- cands.push([idx.by_fqcn.get(imp), `imported by ${pName(p)}`]);
1030
- }
1031
- }
1032
- for (const [c, why] of cands) {
1033
- if (related >= MAX_RELATED) { break; }
1034
- if (pack.add(c, 'related', why)) {
1035
- pack.scan_source(c, 'related', false);
1036
- related += 1;
1037
- }
1038
- }
1039
- }
1040
- return pack;
1041
- }
1042
-
1043
- /**
1044
- * Inline budget (characters): measured on AntennaPod 10-15 (54 conversion agents), an agent
1045
- * made a median 52 read/grep calls, about half of its ~52 turns at ~25 s each, and 26% of
1046
- * its reads re-read a file it had read already. The pack listed most of what it read
1047
- * (592 of 722 Android reads, 224 slices of the mapping reference) but made the agent fetch
1048
- * each one. Inlined, the member / base / custom-view sources, the mapping sections and the
1049
- * style blocks arrive with the pack in one read. Bigger files stay listed: a pack past the
1050
- * host's read size is read in pages, which costs the turns it was meant to save.
1051
- */
1052
- /**
1053
- * The whole pack must come back from ONE read: opencode / DevEco cap a read at 50 KB
1054
- * (2000 lines, 2000 chars a line), so a pack past that is read in pages. `pack` bytes
1055
- * is the cap for the finished file; the inline part gets what the list leaves of it.
1056
- */
1057
- export const INLINE = { file: 9000, lines: 220, pack: 48 * 1024, rels: ['member', 'base', 'custom-view'] };
1058
-
1059
- const fence = (p) => (pSuffix(p) === '.xml' ? 'xml' : pSuffix(p) === '.kt' ? 'kotlin' : 'java');
1060
-
1061
- /** `text` with line numbers, as the read tool shows it, so citations (`file:line`) still work. */
1062
- function numbered(text, from = 1) {
1063
- return splitlines(text).map((l, i) => `${String(from + i).padStart(5)} ${l}`).join('\n');
1064
- }
1065
-
1066
- /** Lines a..b (1-based, inclusive) of a file. */
1067
- function slice(p, a, b) {
1068
- return splitlines(_read(p)).slice(a - 1, b);
1069
- }
1070
-
1071
- /**
1072
- * The inlined part of a pack: member sources first (they are read anyway), then mapping
1073
- * sections and style blocks, then base / custom-view sources, until `room` bytes. Returns
1074
- * {lines, inlined: Set of pKey, chars}; whatever did not fit stays a listed path.
1075
- */
1076
- export function inlineBlock(pack, idxRows, styles, room, budget = INLINE) {
1077
- const inlined = new Set(); let used = 0;
1078
- const bytes = (s) => Buffer.byteLength(s, 'utf8') + (s.match(/\n/g)?.length ?? 0); // CRLF on disk
1079
- const take = (chunk) => {
1080
- const n = bytes(chunk);
1081
- if (used + n > room) return false;
1082
- used += n; return true;
1083
- };
1084
- const files = [...pack.files.values()].filter(([, r]) => budget.rels.includes(r))
1085
- .sort((x, y) => budget.rels.indexOf(x[1]) - budget.rels.indexOf(y[1]) || cmpStr(pathStr(x[0]), pathStr(y[0])));
1086
- const src = [];
1087
- const addSources = (rels) => {
1088
- for (const [p, rel] of files) {
1089
- if (!rels.includes(rel)) continue;
1090
- const text = _read(p);
1091
- if (text.length > budget.file || splitlines(text).length > budget.lines) continue;
1092
- const chunk = `### ${rel}: \`${p}\`\n\n\`\`\`${fence(p)}\n${numbered(text)}\n\`\`\`\n`;
1093
- if (take(chunk)) { inlined.add(pKey(p)); src.push(chunk); }
1094
- }
1095
- };
1096
- addSources(['member']);
1097
- const maps = [];
1098
- for (const [[f, a, b, , h]] of idxRows) {
1099
- if (b - a + 1 > budget.lines) continue;
1100
- const chunk = `### ${h} — \`${pName(f)}\` lines ${a}-${b}\n\n${slice(f, a, b).join('\n')}\n`;
1101
- if (take(chunk)) { inlined.add(`${pKey(f)}#${a}`); maps.push(chunk); }
1102
- }
1103
- const sty = [];
1104
- for (const [name, hit] of styles) {
1105
- const lines = splitlines(_read(hit[0]));
1106
- let end = hit[1];
1107
- while (end < lines.length && end - hit[1] < 40 && !/<\/style>/.test(lines[end - 1])) end += 1;
1108
- const chunk = `- \`${name}\` (\`${pName(hit[0])}:${hit[1]}\`)\n\n\`\`\`xml\n${numbered(lines.slice(hit[1] - 1, end).join('\n'), hit[1])}\n\`\`\`\n`;
1109
- if (take(chunk)) { inlined.add(`${pKey(hit[0])}#${hit[1]}`); sty.push(chunk); }
1110
- }
1111
- addSources(budget.rels.filter((r) => r !== 'member'));
1112
- const lines = [];
1113
- if (src.length) lines.push('## Inlined sources (already read for you — do not read these files again)', '', ...src);
1114
- if (maps.length) lines.push('## Inlined mapping-reference sections', '', ...maps);
1115
- if (sty.length) lines.push('## Inlined style definitions', '', ...sty);
1116
- return { lines, inlined, chars: used };
1117
- }
1118
-
1119
- export function render(group, pack, idx, hres, android, uiInfo = null, { inline = false } = {}) {
1120
- const relOrder = ['member', 'base', 'host', 'custom-view', 'related'];
1121
- const lines = [`# Source pack — ${pyStr(dsub(group, 'id'))}`,
1122
- '',
1123
- 'Reading list resolved by `group_pack.mjs` from meta.json `declared_at`, R.* / @* ' +
1124
- 'references, base classes, the host Activity and same-package / UI imports. **Read the ' +
1125
- '`member` and `base` files in one batched turn**; `host` (toolbar / window chrome) and ' +
1126
- '`related` ones in the next batch, as the conversion needs them. ' +
1127
- 'A file missing here is read as before — this list is a starting point, not a limit.',
1128
- ''];
1129
- const idxRows = uiInfo !== null ? mappingIndex(usedNames(pack, uiInfo, group)) : [];
1130
- const styles = idx.value_defs('style');
1131
- const styleHits = sortedBy([...pack.styles]).filter((x) => styles.get(x)).map((x) => [x, styles.get(x)]);
1132
- let inl = { lines: [], inlined: new Set() };
1133
- if (inline) {
1134
- // room = the one-read cap less the list itself (rendered once without inlining) and the
1135
- // ' — **inlined**' marks and header line inlining adds
1136
- const plain = render(group, pack, idx, hres, android, uiInfo, { inline: false });
1137
- const room = INLINE.pack - Buffer.byteLength(plain, 'utf8') - (plain.match(/\n/g)?.length ?? 0) - 4096;
1138
- if (room > 2048) inl = inlineBlock(pack, idxRows, styleHits, room);
1139
- }
1140
- const mark = (k) => (inl.inlined.has(k) ? ' — **inlined**' : '');
1141
- if (inl.inlined.size) {
1142
- lines.push('Entries marked **inlined** are reproduced at the end of this pack with their line numbers: ' +
1143
- 'cite them as `file:line` and do not read them again.', '');
1144
- }
1145
- for (const r of relOrder) {
1146
- const rows = [...pack.files.values()].filter(([, rr]) => rr === r).map(([p, , why]) => [p, why]);
1147
- if (!rows.length) { continue; }
1148
- lines.push(`## ${r} (${rows.length})`, '');
1149
- for (const [p, why] of sortedBy(rows, (x) => [pSuffix(x[0]) !== '.java' && pSuffix(x[0]) !== '.kt', pathStr(x[0])])) {
1150
- const n = splitlines(_read(p)).length;
1151
- lines.push(`- \`${p}\` — ${n} lines — ${why}${mark(pKey(p))}`);
1152
- }
1153
- lines.push('');
1154
- }
1155
- if (idxRows.length) {
1156
- lines.push('## Mapping-reference sections for the widgets and listeners used here', '',
1157
- 'The sections of `references/mappings/*.md` whose heading names a widget class or ' +
1158
- "listener this group's files and captured view trees use. Read them by line range " +
1159
- '(`offset` = start, `limit` = end - start + 1) in one batched turn instead of paging ' +
1160
- 'through the whole reference. A widget with no row here has no dedicated section: ' +
1161
- 'search the reference as before.', '');
1162
- for (const [[f, a, b, , h], ws] of idxRows) { lines.push(`- \`${f}\` lines ${a}-${b} — ${h} — for ${ws.join(', ')}${mark(`${pKey(f)}#${a}`)}`); }
1163
- lines.push('');
1164
- }
1165
- if (pack.styles.size) {
1166
- lines.push('## Style definitions', '');
1167
- for (const s of sortedBy(pack.styles)) {
1168
- const hit = styles.get(s);
1169
- lines.push(hit ? `- \`${s}\` → \`${hit[0]}:${hit[1]}\`${mark(`${pKey(hit[0])}#${hit[1]}`)}`
1170
- : `- \`${s}\` → (not in project values; library/platform style)`);
1171
- }
1172
- lines.push('');
1173
- }
1174
- if (pack.arrays.size || pack.assets.size) {
1175
- const arrays = idx.value_defs('(?:string-|integer-)?array');
1176
- lines.push('## Arrays and assets', '');
1177
- for (const a of sortedBy(pack.arrays)) {
1178
- const hit = arrays.get(a);
1179
- lines.push(hit ? `- array \`${a}\` → \`${hit[0]}:${hit[1]}\`` : `- array \`${a}\` → (not found)`);
1180
- }
1181
- for (const a of sortedBy(pack.assets.values(), pathStr)) {
1182
- lines.push(`- asset \`${a}\` — ${splitlines(_read(a)).length} lines`);
1183
- }
1184
- lines.push('');
1185
- }
1186
- const refs = sortedBy([...pack.refs.values()].filter((r) => TABLE_TYPES.includes(r[0])));
1187
- if (refs.length) {
1188
- lines.push('## Resources referenced by these files → Harmony',
1189
- '',
1190
- 'From resource_mapping.md + the Harmony resource files. `exists` = present on disk ' +
1191
- "now; `ref` goes into `$r('...')`; values shown for base / zh_CN / dark. Rows with " +
1192
- '`exists`=NO or ref N/A need the resource-fidelity handling of conversion-procedure.md.',
1193
- '',
1194
- '| Android | ref | status | exists | value |',
1195
- '|---|---|---|---|---|');
1196
- for (const [kind, name] of refs) {
1197
- const r = hres.row(kind, name);
1198
- const v = r.value;
1199
- let vs = v ? Object.entries(v).map(([q, x]) => `${q}=${[...pyStr(x)].slice(0, 60).join('')}`).join('; ') : '';
1200
- vs = vs.replace(/\|/g, '\\|').replace(/\n/g, ' ');
1201
- const ex = r.exists === true ? 'yes' : r.exists === false ? 'NO' : '-';
1202
- lines.push(`| ${kind}/${name} | ${r.ref || 'N/A'} | ${r.status} | ${ex} | ${vs} |`);
1203
- }
1204
- lines.push('');
1205
- }
1206
- if (inl.lines.length) lines.push(...inl.lines);
1207
- return lines.join('\n');
1208
- }
1209
-
1210
- export function _ctx(hp, android) {
1211
- const meta = pJoin(hp, '.hometrans');
1212
- const progress = or(_load(pJoin(meta, 'batch_progress.json'), {}), {});
1213
- const uiInfo = pathStr(or(dget(progress, 'ui_info_root'), pJoin(meta, 'ui_info')));
1214
- const module = or(dget(progress, 'ui_module'), 'entry');
1215
- const plan = dget(or(_load(pJoin(uiInfo, 'conversion_set.json'), {}), {}), 'plan', {});
1216
- return [uiInfo, dget(plan, 'groups', []), new AndroidIndex(android), new HarmonyRes(hp, module)];
1217
- }
1218
-
1219
- export function build(hp, android, out = null, only = null, { inline = true } = {}) {
1220
- const [uiInfo, groups, idx, hres] = _ctx(hp, android);
1221
- out = pathStr(or(out, pJoin(hp, '.hometrans', 'work', 'group_packs')));
1222
- if (isFile(out)) { throw new Error(`FileExistsError: ${out}`); }
1223
- fs.mkdirSync(out, { recursive: true });
1224
- const report = new Map();
1225
- for (const g of pyIter(groups)) {
1226
- if (only && !only.has(dsub(g, 'id'))) { continue; }
1227
- const pack = buildGroup(g, uiInfo, idx, hres, android);
1228
- const text = render(g, pack, idx, hres, android, uiInfo, { inline });
1229
- const gid = dsub(g, 'id');
1230
- const file = pJoin(out, `${pyStr(gid)}.md`);
1231
- fs.writeFileSync(file, IS_WIN ? text.replace(/\n/g, '\r\n') : text, 'utf8');
1232
- const k = typeof gid === 'string' ? gid : jsonKey(gid);
1233
- report.set(k, new Map([['files', pack.files.size], ['resources', pack.refs.size],
1234
- ['styles', pack.styles.size], ['mapping_sections', text.split(' — for ').length - 1]]));
1235
- }
1236
- return new Map([['out', out], ['groups', report]]);
1237
- }
1238
-
1239
- export function lookup(hp, android, names) {
1240
- const hres = new HarmonyRes(hp, or(dget(or(_load(pJoin(hp, '.hometrans', 'batch_progress.json'), {}), {}),
1241
- 'ui_module'), 'entry'));
1242
- const rows = [];
1243
- for (const n of names) {
1244
- const s = n.replaceAll('R.', '').replaceAll('@', '').replace('.', '/');
1245
- const i = s.indexOf('/');
1246
- const [kind, name] = i < 0 ? [s, ''] : [s.slice(0, i), s.slice(i + 1)];
1247
- rows.push(hres.row(kind, name));
1248
- }
1249
- return rows;
1250
- }
1251
-
1252
- // ---------------------------------------------------------------- argparse equivalent
1253
- // Mirrors this CLI's argparse (Python 3.13) behaviour: unique long-option prefixes,
1254
- // `--opt=value`, `--`, interleaved positionals (mode, harmony_dir, names*),
1255
- // usage/help layout (width = terminal columns - 2), errors -> usage + exit 2.
1256
-
1257
- function termColumns() {
1258
- const env = Number.parseInt(process.env.COLUMNS ?? '', 10);
1259
- if (env > 0) { return env; }
1260
- return process.stdout.isTTY && process.stdout.columns ? process.stdout.columns : 80;
1261
- }
1262
-
1263
- function usage(prog) {
1264
- const width = termColumns() - 2;
1265
- const opt = ['[-h]', '--android ANDROID', '[--groups GROUPS]', '[--out OUT]'];
1266
- const pos = ['{build,lookup}', 'harmony_dir', '[names ...]'];
1267
- const full = [prog, ...opt, ...pos].join(' ');
1268
- if ('usage: '.length + full.length <= width) { return 'usage: ' + full; }
1269
- const getLines = (parts, indent, prefix) => {
1270
- const lines = [];
1271
- let line = [];
1272
- let len = prefix !== undefined ? prefix.length - 1 : indent.length - 1;
1273
- for (const part of parts) {
1274
- if (len + 1 + part.length > width && line.length) {
1275
- lines.push(indent + line.join(' '));
1276
- line = [];
1277
- len = indent.length - 1;
1278
- }
1279
- line.push(part);
1280
- len += part.length + 1;
1281
- }
1282
- if (line.length) { lines.push(indent + line.join(' ')); }
1283
- if (prefix !== undefined) { lines[0] = lines[0].slice(indent.length); }
1284
- return lines;
1285
- };
1286
- let lines;
1287
- if ('usage: '.length + prog.length <= 0.75 * width) {
1288
- const indent = ' '.repeat('usage: '.length + prog.length + 1);
1289
- lines = getLines([prog, ...opt], indent, prog);
1290
- if (pos.length) { lines.push(...getLines(pos, indent)); }
1291
- } else {
1292
- const indent = ' '.repeat('usage: '.length);
1293
- lines = getLines([...opt, ...pos], indent);
1294
- if (lines.length > 1) { lines = [...getLines(opt, indent), ...getLines(pos, indent)]; }
1295
- lines = [prog, ...lines];
1296
- }
1297
- return 'usage: ' + lines.join('\n');
1298
- }
1299
-
1300
- function helpText(prog) {
1301
- const rows = [
1302
- ['{build,lookup}', null], ['harmony_dir', null], ['names', 'lookup: type/name ... (e.g. string/foo R.color.bar)'],
1303
- ];
1304
- const opts = [['-h, --help', 'show this help message and exit'], ['--android ANDROID', 'android_project_dir'],
1305
- ['--groups GROUPS', 'build: comma-separated ids (default: all)'],
1306
- ['--out OUT', 'build: output dir (default .hometrans/work/group_packs)']];
1307
- const width = termColumns() - 2;
1308
- const maxPos = Math.min(24, Math.max(width - 20, 4));
1309
- const longest = Math.max(...[...rows, ...opts].map(([inv]) => inv.length + 2));
1310
- const helpPos = Math.min(longest + 2, maxPos);
1311
- const item = ([inv, help]) => {
1312
- if (!help) { return [' ' + inv]; }
1313
- if (inv.length + 2 <= helpPos - 2) { return [' ' + inv.padEnd(helpPos - 4) + ' ' + help]; }
1314
- return [' ' + inv, ' '.repeat(helpPos) + help];
1315
- };
1316
- return [usage(prog), '', DOC.trimEnd(), '', 'positional arguments:', ...rows.flatMap(item), '',
1317
- 'options:', ...opts.flatMap(item)].join('\n') + '\n';
1318
- }
1319
-
1320
- function parseArgs(argv, prog) {
1321
- const fail = (msg) => {
1322
- process.stderr.write((usage(prog) + '\n' + `${prog}: error: ${msg}\n`).replace(/\n/g, EOL));
1323
- process.exit(2);
1324
- };
1325
- const LONG = ['--help', '--android', '--groups', '--out'];
1326
- // classify: 'O' option, 'A' argument; the first '--' ends options and is dropped
1327
- const kinds = [];
1328
- const args = [];
1329
- let rest = false;
1330
- for (const s of argv) {
1331
- if (!rest && s === '--') { rest = true; continue; }
1332
- let k = 'A';
1333
- if (!rest && s.startsWith('-') && s !== '-') {
1334
- if (/^-\d+$|^-\d*\.\d+$/.test(s)) { k = 'A'; }
1335
- else if (s.includes(' ') && !LONG.includes(s.split('=')[0]) && s.split('=')[0] !== '-h') { k = 'A'; }
1336
- else { k = 'O'; }
1337
- }
1338
- kinds.push(k);
1339
- args.push(s);
1340
- }
1341
- const res = { mode: null, harmony_dir: null, names: null, android: null, groups: '', out: null };
1342
- const seen = new Set();
1343
- const extras = [];
1344
- const posActs = ['mode', 'harmony_dir', 'names'];
1345
- let pi = 0; // next positional action
1346
- const take = (act, vals) => {
1347
- if (act === 'mode') {
1348
- if (!['build', 'lookup'].includes(vals[0])) {
1349
- fail(`argument mode: invalid choice: ${pyRepr(vals[0])} (choose from build, lookup)`);
1350
- }
1351
- res.mode = vals[0];
1352
- } else if (act === 'harmony_dir') { res.harmony_dir = vals[0]; }
1353
- else { res.names = vals; }
1354
- seen.add(act);
1355
- };
1356
- // consume a run of 'A' args with the remaining positionals (greedy, names = '*')
1357
- const consumePos = (start, end, more) => {
1358
- let n = end - start;
1359
- let i = start;
1360
- const need = posActs.slice(pi);
1361
- // how many fixed (exactly-one) actions can be satisfied
1362
- const fixed = need.filter((a) => a !== 'names');
1363
- let use = Math.min(n, fixed.length);
1364
- for (let k = 0; k < use; k++) { take(fixed[k], [args[i]]); i++; pi++; }
1365
- if (pi === 2 && use === fixed.length) {
1366
- const left = end - i;
1367
- if (left > 0 || !more) { take('names', args.slice(i, end)); i = end; pi++; }
1368
- }
1369
- return i;
1370
- };
1371
- let i = 0;
1372
- while (i < args.length) {
1373
- if (kinds[i] === 'A') {
1374
- let j = i;
1375
- while (j < args.length && kinds[j] === 'A') { j++; }
1376
- const stop = consumePos(i, j, j < args.length);
1377
- extras.push(...args.slice(stop, j));
1378
- i = j;
1379
- continue;
1380
- }
1381
- const s = args[i];
1382
- const eq = s.startsWith('--') ? s.indexOf('=') : -1;
1383
- const key = eq >= 0 ? s.slice(0, eq) : s;
1384
- let opt = null;
1385
- let explicit = eq >= 0 ? s.slice(eq + 1) : null;
1386
- if (key === '-h' || LONG.includes(key)) { opt = key === '-h' ? '--help' : key; }
1387
- else if (key.startsWith('--')) {
1388
- const hits = LONG.filter((o) => o.startsWith(key));
1389
- if (hits.length === 1) { opt = hits[0]; }
1390
- } else if (s.startsWith('-h') && !s.startsWith('--')) {
1391
- opt = '--help';
1392
- explicit = s.slice(2);
1393
- }
1394
- if (!opt) { extras.push(s); i++; continue; }
1395
- if (opt === '--help') {
1396
- if (explicit !== null && explicit !== '') {
1397
- fail(`argument -h/--help: ignored explicit argument ${pyRepr(explicit.replace(/^=/, ''))}`);
1398
- }
1399
- process.stdout.write(helpText(prog).replace(/\n/g, EOL));
1400
- process.exit(0);
1401
- }
1402
- const dest = opt.slice(2);
1403
- if (explicit !== null) { res[dest] = explicit; i++; }
1404
- else if (i + 1 < args.length && kinds[i + 1] === 'A') { res[dest] = args[i + 1]; i += 2; }
1405
- else { fail(`argument ${opt}: expected one argument`); }
1406
- seen.add(dest);
1407
- }
1408
- if (pi === 2) { take('names', []); pi++; }
1409
- const missing = [];
1410
- if (!seen.has('mode')) { missing.push('mode'); }
1411
- if (!seen.has('harmony_dir')) { missing.push('harmony_dir'); }
1412
- if (!seen.has('android')) { missing.push('--android'); }
1413
- if (missing.length) { fail(`the following arguments are required: ${missing.join(', ')}`); }
1414
- if (extras.length) { fail(`unrecognized arguments: ${extras.join(' ')}`); }
1415
- if (res.names === null) { res.names = []; }
1416
- return res;
1417
- }
1418
-
1419
- export function main(argv = process.argv.slice(2)) {
1420
- const prog = path.basename(process.argv[1] || 'group_pack.mjs');
1421
- const a = parseArgs(argv, prog);
1422
- let res;
1423
- if (a.mode === 'build') {
1424
- const only = new Set(a.groups.split(',').map(pyStrip).filter((g) => g));
1425
- // inlining is on unless GROUP_PACK_INLINE=0 (a host whose read tool truncates large files)
1426
- res = build(a.harmony_dir, a.android, a.out, only.size ? only : null,
1427
- { inline: process.env.GROUP_PACK_INLINE !== '0' });
1428
- } else {
1429
- res = lookup(a.harmony_dir, a.android, a.names);
1430
- }
1431
- process.stdout.write((pyJsonDumps(res, 1) + '\n').replace(/\n/g, EOL));
1432
- return 0;
1433
- }
1434
-
1435
- if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
1436
- process.exitCode = main();
1437
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Per-group source + resource pack: the files a conversion agent must read, found once.
4
+ *
5
+ * (Node >= 22.18, ESM, zero dependencies. Behaviour-identical port of
6
+ * group_pack.py: same args, exit codes, stdout and output files.)
7
+ *
8
+ * Measured on a 14-group run, an agent spent ~28% of its turns *discovering* inputs
9
+ * rather than converting: globbing for the Fragment/layout/style files of its own
10
+ * group (14%), and grepping color.json / string.json / media/ one name at a time to
11
+ * see whether a resource exists in the Harmony project (14%, one dump of a 51 KB
12
+ * string.json). Every one of those answers is a pure function of the Android tree,
13
+ * resource_mapping.md and the Harmony resources -- the same for every agent.
14
+ *
15
+ * This script resolves them per group and writes <out>/<GID>.md:
16
+ *
17
+ * * Source files, by relation: the member classes (meta.json `declared_at`), their
18
+ * base-class chain, the layouts / pref XMLs / menus they reference (R.layout.x,
19
+ * FooBinding, R.xml.x, R.menu.x, `<include>`), custom views used in those layouts,
20
+ * and their in-project UI imports (dialogs, adapters, views...). Absolute paths
21
+ * and line counts, so the agent issues one batched read.
22
+ * * Style references -> the file:line that defines them.
23
+ * * Resource table: every R.x.y / @x/y the group's files use -> its Harmony target
24
+ * from resource_mapping.md, whether it exists on disk, and its value (string /
25
+ * colour incl. dark / float), so no agent greps the resource JSON.
26
+ *
27
+ * Nothing here is a conclusion: it is a reading list plus lookups. The agent still
28
+ * reads the files and still owns every decision; a file the pack missed is read as
29
+ * before.
30
+ *
31
+ * group_pack.mjs build <harmony_dir> --android <android_dir> [--groups G001,G002]
32
+ * group_pack.mjs lookup <harmony_dir> --android <android_dir> string/foo color/bar ...
33
+ */
34
+
35
+ import * as fs from 'node:fs';
36
+ import * as path from 'node:path';
37
+ import { fileURLToPath, pathToFileURL } from 'node:url';
38
+
39
+ const DOC = `Per-group source + resource pack: the files a conversion agent must read, found once.
40
+
41
+ Measured on a 14-group run, an agent spent ~28% of its turns *discovering* inputs
42
+ rather than converting: globbing for the Fragment/layout/style files of its own
43
+ group (14%), and grepping color.json / string.json / media/ one name at a time to
44
+ see whether a resource exists in the Harmony project (14%, one dump of a 51 KB
45
+ string.json). Every one of those answers is a pure function of the Android tree,
46
+ resource_mapping.md and the Harmony resources -- the same for every agent.
47
+
48
+ This script resolves them per group and writes <out>/<GID>.md:
49
+
50
+ * Source files, by relation: the member classes (meta.json \`declared_at\`), their
51
+ base-class chain, the layouts / pref XMLs / menus they reference (R.layout.x,
52
+ FooBinding, R.xml.x, R.menu.x, \`<include>\`), custom views used in those layouts,
53
+ and their in-project UI imports (dialogs, adapters, views...). Absolute paths
54
+ and line counts, so the agent issues one batched read.
55
+ * Style references -> the file:line that defines them.
56
+ * Resource table: every R.x.y / @x/y the group's files use -> its Harmony target
57
+ from resource_mapping.md, whether it exists on disk, and its value (string /
58
+ colour incl. dark / float), so no agent greps the resource JSON.
59
+
60
+ Nothing here is a conclusion: it is a reading list plus lookups. The agent still
61
+ reads the files and still owns every decision; a file the pack missed is read as
62
+ before.
63
+
64
+ group_pack.mjs build <harmony_dir> --android <android_dir> [--groups G001,G002]
65
+ group_pack.mjs lookup <harmony_dir> --android <android_dir> string/foo color/bar ...
66
+ `;
67
+
68
+ // ---------------------------------------------------------------- Python compat
69
+ // Outputs are a contract read by other scripts and agents: byte-identical to the
70
+ // Python version (json.dumps(indent=1, ensure_ascii=False), CRLF text writes on
71
+ // Windows, pathlib semantics, Python sort/regex semantics).
72
+
73
+ const IS_WIN = process.platform === 'win32';
74
+ const EOL = IS_WIN ? '\r\n' : '\n';
75
+
76
+ /** A float from json.loads: written back with Python repr. */
77
+ export class PyFloat {
78
+ constructor(value) { this.value = value; }
79
+ valueOf() { return this.value; }
80
+ }
81
+
82
+ const KEY_ORDER = Symbol('pyKeyOrder');
83
+ const INDEX_KEY = /^(?:0|[1-9][0-9]*)$/;
84
+
85
+ function floatRepr(x, json) {
86
+ if (!Number.isFinite(x)) {
87
+ if (Number.isNaN(x)) { return json ? 'NaN' : 'nan'; }
88
+ return x > 0 ? (json ? 'Infinity' : 'inf') : (json ? '-Infinity' : '-inf');
89
+ }
90
+ if (x === 0) { return Object.is(x, -0) ? '-0.0' : '0.0'; }
91
+ const [m, e] = Math.abs(x).toExponential().split('e');
92
+ const digits = m.replace('.', '');
93
+ const exp = Number(e);
94
+ let s;
95
+ if (exp >= -4 && exp < 16) {
96
+ if (exp >= 0) {
97
+ const ip = digits.slice(0, exp + 1).padEnd(exp + 1, '0');
98
+ s = ip + '.' + (digits.slice(exp + 1) || '0');
99
+ } else {
100
+ s = '0.' + '0'.repeat(-exp - 1) + digits;
101
+ }
102
+ } else {
103
+ s = digits[0] + (digits.length > 1 ? '.' + digits.slice(1) : '') + 'e' + (exp < 0 ? '-' : '+') +
104
+ String(Math.abs(exp)).padStart(2, '0');
105
+ }
106
+ return (x < 0 ? '-' : '') + s;
107
+ }
108
+
109
+ /** json.loads: floats -> PyFloat, unsafe ints -> BigInt, key order kept. */
110
+ function pyJsonLoads(text) {
111
+ let i = 0;
112
+ const n = text.length;
113
+ const fail = (msg) => { throw new SyntaxError(`${msg}: char ${i}`); };
114
+ const ws = () => {
115
+ while (i < n) {
116
+ const c = text.charCodeAt(i);
117
+ if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) { i++; } else { break; }
118
+ }
119
+ };
120
+ const NUM = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/y;
121
+ const str = () => {
122
+ i++;
123
+ let out = '';
124
+ let start = i;
125
+ for (;;) {
126
+ if (i >= n) { fail('Unterminated string'); }
127
+ const c = text.charCodeAt(i);
128
+ if (c === 0x22) { out += text.slice(start, i); i++; return out; }
129
+ if (c < 0x20) { fail('Invalid control character'); }
130
+ if (c === 0x5c) {
131
+ out += text.slice(start, i);
132
+ const esc = text[i + 1];
133
+ const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[esc];
134
+ if (simple !== undefined) {
135
+ out += simple;
136
+ i += 2;
137
+ } else if (esc === 'u') {
138
+ const hex = text.slice(i + 2, i + 6);
139
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) { fail('Invalid \\uXXXX escape'); }
140
+ out += String.fromCharCode(parseInt(hex, 16));
141
+ i += 6;
142
+ } else {
143
+ fail('Invalid \\escape');
144
+ }
145
+ start = i;
146
+ continue;
147
+ }
148
+ i++;
149
+ }
150
+ };
151
+ const value = () => {
152
+ ws();
153
+ const c = text[i];
154
+ if (c === '{') {
155
+ i++;
156
+ const o = {};
157
+ const order = [];
158
+ let hasIndex = false;
159
+ ws();
160
+ if (text[i] === '}') { i++; return o; }
161
+ for (;;) {
162
+ ws();
163
+ if (text[i] !== '"') { fail('Expecting property name enclosed in double quotes'); }
164
+ const k = str();
165
+ ws();
166
+ if (text[i] !== ':') { fail("Expecting ':' delimiter"); }
167
+ i++;
168
+ const v = value();
169
+ if (!Object.hasOwn(o, k)) {
170
+ order.push(k);
171
+ if (INDEX_KEY.test(k)) { hasIndex = true; }
172
+ }
173
+ if (k === '__proto__') {
174
+ Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
175
+ } else {
176
+ o[k] = v;
177
+ }
178
+ ws();
179
+ if (text[i] === ',') { i++; continue; }
180
+ if (text[i] === '}') { i++; break; }
181
+ fail("Expecting ',' delimiter");
182
+ }
183
+ if (hasIndex) { o[KEY_ORDER] = order; }
184
+ return o;
185
+ }
186
+ if (c === '[') {
187
+ i++;
188
+ const a = [];
189
+ ws();
190
+ if (text[i] === ']') { i++; return a; }
191
+ for (;;) {
192
+ a.push(value());
193
+ ws();
194
+ if (text[i] === ',') { i++; continue; }
195
+ if (text[i] === ']') { i++; break; }
196
+ fail("Expecting ',' delimiter");
197
+ }
198
+ return a;
199
+ }
200
+ if (c === '"') { return str(); }
201
+ if (text.startsWith('null', i)) { i += 4; return null; }
202
+ if (text.startsWith('true', i)) { i += 4; return true; }
203
+ if (text.startsWith('false', i)) { i += 5; return false; }
204
+ if (text.startsWith('NaN', i)) { i += 3; return new PyFloat(NaN); }
205
+ if (text.startsWith('Infinity', i)) { i += 8; return new PyFloat(Infinity); }
206
+ if (text.startsWith('-Infinity', i)) { i += 9; return new PyFloat(-Infinity); }
207
+ NUM.lastIndex = i;
208
+ const m = NUM.exec(text);
209
+ if (!m) { fail('Expecting value'); }
210
+ i += m[0].length;
211
+ if (m[1] !== undefined || m[2] !== undefined) { return new PyFloat(Number(m[0])); }
212
+ const num = Number(m[0]);
213
+ return Number.isSafeInteger(num) ? (num === 0 ? 0 : num) : BigInt(m[0]);
214
+ };
215
+ const v = value();
216
+ ws();
217
+ if (i !== n) { fail('Extra data'); }
218
+ return v;
219
+ }
220
+
221
+ function keysOf(o) {
222
+ const ks = Object.keys(o);
223
+ const ord = o[KEY_ORDER];
224
+ if (!ord) { return ks; }
225
+ const present = new Set(ks);
226
+ const out = ord.filter((k) => present.has(k));
227
+ const seen = new Set(out);
228
+ for (const k of ks) { if (!seen.has(k)) { out.push(k); } }
229
+ return out;
230
+ }
231
+
232
+ /** json.dumps key coercion for a Map key (str / int / float / bool / None). */
233
+ function jsonKey(k) {
234
+ if (typeof k === 'string') { return k; }
235
+ if (k === null || k === undefined) { return 'null'; }
236
+ if (k === true) { return 'true'; }
237
+ if (k === false) { return 'false'; }
238
+ if (k instanceof PyFloat) { return floatRepr(k.value, true); }
239
+ if (typeof k === 'number' || typeof k === 'bigint') { return String(k); }
240
+ throw new TypeError(`keys must be str, int, float, bool or None, not ${pyType(k)}`);
241
+ }
242
+
243
+ /** json.dumps(v, ensure_ascii=False, indent=indent); a Map is a dict in insertion order. */
244
+ function pyJsonDumps(v, indent, level = 0) {
245
+ if (v === null || v === undefined) { return 'null'; }
246
+ if (v === true) { return 'true'; }
247
+ if (v === false) { return 'false'; }
248
+ if (typeof v === 'bigint') { return v.toString(); }
249
+ if (v instanceof PyFloat) { return floatRepr(v.value, true); }
250
+ if (typeof v === 'number') { return Number.isInteger(v) ? (Object.is(v, -0) ? '0' : String(v)) : floatRepr(v, true); }
251
+ if (typeof v === 'string') { return JSON.stringify(v); }
252
+ const pad = '\n' + ' '.repeat(indent * (level + 1));
253
+ const end = '\n' + ' '.repeat(indent * level);
254
+ if (Array.isArray(v)) {
255
+ if (v.length === 0) { return '[]'; }
256
+ return '[' + pad + v.map((x) => pyJsonDumps(x, indent, level + 1)).join(',' + pad) + end + ']';
257
+ }
258
+ const entries = v instanceof Map ? [...v].map(([k, x]) => [jsonKey(k), x]) : keysOf(v).map((k) => [k, v[k]]);
259
+ if (entries.length === 0) { return '{}'; }
260
+ return '{' + pad + entries.map(([k, x]) => JSON.stringify(k) + ': ' + pyJsonDumps(x, indent, level + 1))
261
+ .join(',' + pad) + end + '}';
262
+ }
263
+
264
+ function pyType(v) {
265
+ if (v === null || v === undefined) { return 'NoneType'; }
266
+ if (typeof v === 'boolean') { return 'bool'; }
267
+ if (typeof v === 'number') { return Number.isInteger(v) ? 'int' : 'float'; }
268
+ if (typeof v === 'bigint') { return 'int'; }
269
+ if (v instanceof PyFloat) { return 'float'; }
270
+ if (typeof v === 'string') { return 'str'; }
271
+ if (Array.isArray(v)) { return 'list'; }
272
+ return 'dict';
273
+ }
274
+
275
+ const isDict = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof PyFloat);
276
+
277
+ function truthy(v) {
278
+ if (v === null || v === undefined || v === false) { return false; }
279
+ if (v === true) { return true; }
280
+ if (typeof v === 'number') { return v !== 0; }
281
+ if (typeof v === 'bigint') { return v !== 0n; }
282
+ if (v instanceof PyFloat) { return v.value !== 0; }
283
+ if (typeof v === 'string' || Array.isArray(v)) { return v.length > 0; }
284
+ if (v instanceof Map || v instanceof Set) { return v.size > 0; }
285
+ return Object.keys(v).length > 0;
286
+ }
287
+
288
+ /** `a or b`. */
289
+ const or = (a, b) => (truthy(a) ? a : b);
290
+
291
+ /** d.get(k, default) on a json value: AttributeError unless it is a dict. */
292
+ function dget(d, k, dflt = null) {
293
+ if (!isDict(d)) { throw new TypeError(`'${pyType(d)}' object has no attribute 'get'`); }
294
+ return Object.hasOwn(d, k) ? d[k] : dflt;
295
+ }
296
+
297
+ /** d[k]. */
298
+ function dsub(d, k) {
299
+ if (typeof d === 'string' || Array.isArray(d)) { throw new TypeError(`${pyType(d)} indices must be integers`); }
300
+ if (!isDict(d)) { throw new TypeError(`'${pyType(d)}' object is not subscriptable`); }
301
+ if (!Object.hasOwn(d, k)) { throw new Error(`KeyError: '${k}'`); }
302
+ return d[k];
303
+ }
304
+
305
+ /** `for x in v` over a json value. */
306
+ function pyIter(v) {
307
+ if (Array.isArray(v)) { return v; }
308
+ if (typeof v === 'string') { return [...v]; }
309
+ if (isDict(v)) { return keysOf(v); }
310
+ throw new TypeError(`'${pyType(v)}' object is not iterable`);
311
+ }
312
+
313
+ function cmpStr(a, b) {
314
+ if (!/[\uD800-\uDFFF]/.test(a) && !/[\uD800-\uDFFF]/.test(b)) { return a < b ? -1 : a > b ? 1 : 0; }
315
+ const x = [...a];
316
+ const y = [...b];
317
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
318
+ const d = x[i].codePointAt(0) - y[i].codePointAt(0);
319
+ if (d !== 0) { return d < 0 ? -1 : 1; }
320
+ }
321
+ return x.length < y.length ? -1 : x.length > y.length ? 1 : 0;
322
+ }
323
+
324
+ /** Python `<` for sort keys: bool/int as numbers, str by code point, arrays element-wise. */
325
+ function pyCmp(a, b) {
326
+ const na = typeof a === 'boolean' ? Number(a) : a;
327
+ const nb = typeof b === 'boolean' ? Number(b) : b;
328
+ if (typeof na === 'number' && typeof nb === 'number') { return na < nb ? -1 : na > nb ? 1 : 0; }
329
+ if (typeof a === 'string' && typeof b === 'string') { return cmpStr(a, b); }
330
+ if (Array.isArray(a) && Array.isArray(b)) {
331
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
332
+ const c = pyCmp(a[i], b[i]);
333
+ if (c !== 0) { return c; }
334
+ }
335
+ return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
336
+ }
337
+ throw new TypeError(`'<' not supported between instances of '${pyType(a)}' and '${pyType(b)}'`);
338
+ }
339
+
340
+ /** sorted(items, key=key): stable. */
341
+ function sortedBy(items, key = (x) => x) {
342
+ const dec = [...items].map((v, i) => [key(v), i, v]);
343
+ dec.sort((p, q) => pyCmp(p[0], q[0]) || p[1] - q[1]);
344
+ return dec.map((d) => d[2]);
345
+ }
346
+
347
+ const NON_PRINTABLE = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u;
348
+
349
+ function strRepr(s) {
350
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
351
+ let r = q;
352
+ for (const ch of s) {
353
+ const cp = ch.codePointAt(0);
354
+ if (ch === q || ch === '\\') { r += '\\' + ch; }
355
+ else if (ch === '\t') { r += '\\t'; }
356
+ else if (ch === '\n') { r += '\\n'; }
357
+ else if (ch === '\r') { r += '\\r'; }
358
+ else if (ch !== ' ' && NON_PRINTABLE.test(ch)) {
359
+ r += cp < 0x100 ? '\\x' + cp.toString(16).padStart(2, '0')
360
+ : cp < 0x10000 ? '\\u' + cp.toString(16).padStart(4, '0') : '\\U' + cp.toString(16).padStart(8, '0');
361
+ } else { r += ch; }
362
+ }
363
+ return r + q;
364
+ }
365
+
366
+ function pyRepr(v) {
367
+ if (v === null || v === undefined) { return 'None'; }
368
+ if (v === true) { return 'True'; }
369
+ if (v === false) { return 'False'; }
370
+ if (typeof v === 'bigint') { return v.toString(); }
371
+ if (v instanceof PyFloat) { return floatRepr(v.value, false); }
372
+ if (typeof v === 'number') { return Number.isInteger(v) ? String(v === 0 ? 0 : v) : floatRepr(v, false); }
373
+ if (typeof v === 'string') { return strRepr(v); }
374
+ if (Array.isArray(v)) { return '[' + v.map(pyRepr).join(', ') + ']'; }
375
+ return '{' + keysOf(v).map((k) => strRepr(k) + ': ' + pyRepr(v[k])).join(', ') + '}';
376
+ }
377
+
378
+ /** str(v) / f"{v}". */
379
+ const pyStr = (v) => (typeof v === 'string' ? v : pyRepr(v));
380
+
381
+ /** Python str.isspace() characters (for \s and strip()). */
382
+ const SP = '\\t\\n\\v\\f\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000';
383
+ const pyStrip = (s) => s.replace(new RegExp(`^[${SP}]+|[${SP}]+$`, 'gu'), '');
384
+
385
+ const LINE_BREAK = new RegExp('\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029]');
386
+
387
+ /** str.splitlines(). */
388
+ function splitlines(s) {
389
+ if (s === '') { return []; }
390
+ const parts = s.split(LINE_BREAK);
391
+ if (parts[parts.length - 1] === '') { parts.pop(); }
392
+ return parts;
393
+ }
394
+
395
+ const READ = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
396
+ const STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
397
+
398
+ /** Path.read_text(encoding="utf-8", errors="replace"), "" on OSError. */
399
+ function _read(p) {
400
+ let buf;
401
+ try { buf = fs.readFileSync(p); } catch { return ''; }
402
+ return READ.decode(buf).replace(/\r\n?/g, '\n');
403
+ }
404
+
405
+ function _load(p, dflt = null) {
406
+ return isFile(p) ? pyJsonLoads(STRICT.decode(fs.readFileSync(p)).replace(/\r\n?/g, '\n')) : dflt;
407
+ }
408
+
409
+ function isFile(p) {
410
+ try { return fs.statSync(p, { throwIfNoEntry: false })?.isFile() ?? false; } catch { return false; }
411
+ }
412
+ function isDir(p) {
413
+ try { return fs.statSync(p, { throwIfNoEntry: false })?.isDirectory() ?? false; } catch { return false; }
414
+ }
415
+
416
+ // ---------------------------------------------------------------- paths (pathlib semantics)
417
+ // A path is a normalised string (str(Path(x))); equality / dict keys are case-folded on Windows.
418
+
419
+ const SEP = IS_WIN ? '\\' : '/';
420
+
421
+ function splitPath(p) {
422
+ if (IS_WIN) {
423
+ const s = String(p).replace(/\//g, '\\');
424
+ let drive = '';
425
+ let rest = s;
426
+ const unc = /^\\\\([^\\]+)\\([^\\]+)/.exec(s);
427
+ if (unc) { drive = unc[0]; rest = s.slice(drive.length); }
428
+ else if (/^[A-Za-z]:/.test(s)) { drive = s.slice(0, 2); rest = s.slice(2); }
429
+ const root = rest.startsWith('\\') ? '\\' : '';
430
+ return { drive, root, parts: rest.split('\\').filter((x) => x !== '' && x !== '.') };
431
+ }
432
+ const s = String(p);
433
+ const root = s.startsWith('//') && !s.startsWith('///') ? '//' : s.startsWith('/') ? '/' : '';
434
+ return { drive: '', root, parts: s.split('/').filter((x) => x !== '' && x !== '.') };
435
+ }
436
+
437
+ const fmt = ({ drive, root, parts }) => drive + root + parts.join(SEP) || '.';
438
+
439
+ /** str(Path(p)). */
440
+ export const pathStr = (p) => fmt(splitPath(p));
441
+
442
+ /** Path(a) / b / c ... */
443
+ function pJoin(a, ...segs) {
444
+ let cur = splitPath(a);
445
+ for (const s of segs) {
446
+ const n = splitPath(s);
447
+ if (n.root || (n.drive && n.drive.toLowerCase() !== cur.drive.toLowerCase())) {
448
+ cur = { drive: n.drive || cur.drive, root: n.root, parts: n.parts };
449
+ } else if (n.drive) {
450
+ cur = { drive: n.drive, root: cur.root, parts: [...cur.parts, ...n.parts] };
451
+ } else {
452
+ cur = { ...cur, parts: [...cur.parts, ...n.parts] };
453
+ }
454
+ }
455
+ return fmt(cur);
456
+ }
457
+
458
+ /** Path.parts. */
459
+ function pParts(p) {
460
+ const s = splitPath(p);
461
+ return s.drive || s.root ? [s.drive + s.root, ...s.parts] : s.parts;
462
+ }
463
+ const pName = (p) => { const s = splitPath(p).parts; return s.length ? s[s.length - 1] : ''; };
464
+ function pSuffix(p) {
465
+ const n = pName(p);
466
+ const i = n.lastIndexOf('.');
467
+ return i > 0 && i < n.length - 1 ? n.slice(i) : '';
468
+ }
469
+ const pStem = (p) => { const n = pName(p); const x = pSuffix(p); return x ? n.slice(0, -x.length) : n; };
470
+ function pParent(p) {
471
+ const s = splitPath(p);
472
+ return s.parts.length ? fmt({ ...s, parts: s.parts.slice(0, -1) }) : fmt(s);
473
+ }
474
+ /** Key for path equality / hashing. */
475
+ const pKey = (p) => (IS_WIN ? pathStr(p).toLowerCase() : pathStr(p));
476
+ /** PurePath `<` order. */
477
+ const pOrder = (p) => (IS_WIN ? pathStr(p).toLowerCase().split('\\') : pathStr(p).split('/'));
478
+
479
+ /** Entries of a directory in os.scandir order (no sort). Throws on OSError. */
480
+ function listDir(d) {
481
+ const names = [];
482
+ const h = fs.opendirSync(d);
483
+ try {
484
+ for (let e = h.readSync(); e !== null; e = h.readSync()) { names.push(e.name); }
485
+ } finally { h.closeSync(); }
486
+ return names.map((nm) => pJoin(d, nm));
487
+ }
488
+
489
+ /** Path(d).glob("*.<ext>"): scandir order, case-insensitive on Windows, [] when missing. */
490
+ function globExt(d, ext) {
491
+ let all;
492
+ try { all = listDir(d); } catch { return []; }
493
+ return all.filter((p) => (IS_WIN ? pName(p).toLowerCase().endsWith(ext.toLowerCase()) : pName(p).endsWith(ext)));
494
+ }
495
+
496
+ // ---------------------------------------------------------------- patterns
497
+ // Python `re` (str patterns) is Unicode-aware: \w = alnum + "_", \b is built on
498
+ // that \w, \s = str.isspace(), \d = Nd. Spelled out here so the 'u' JS regexes
499
+ // match exactly what the Python ones did. re.M `^`/`$` only treat "\n" as a line
500
+ // break (JS's 'm' also breaks on CR, LS and PS), hence the explicit anchors.
501
+
502
+ const W = '[\\p{L}\\p{N}_]';
503
+ const WC = '\\p{L}\\p{N}_';
504
+ const B = `(?:(?<=${W})(?!${W})|(?<!${W})(?=${W}))`;
505
+ const S = `[${SP}]`;
506
+ const NS = `[^${SP}]`;
507
+ const BOL = '(?<![^\\n])';
508
+ const EOLA = '(?![^\\n])';
509
+ const KINDS_R = 'layout|xml|menu|string|color|drawable|mipmap|dimen|style|plurals|array|integer|bool|font|raw|anim';
510
+
511
+ export const SKIP_DIRS = new Set(['build', '.git', '.gradle', '.idea', 'node_modules', '.cxx', 'intermediates']);
512
+ export const SRC_EXT = ['.java', '.kt'];
513
+ export const UI_SUFFIX = new RegExp('(Dialog|Fragment|Activity|View|Adapter|ViewHolder|Holder|Layout|' +
514
+ 'Preference|Sheet|Menu|Handler|Item|Row|Bar|Button|Widget)$', 'u');
515
+ export const R_REF = new RegExp(`${B}R\\.(${KINDS_R})\\.(${W}+)`, 'gu');
516
+ export const X_REF = new RegExp(`@(${KINDS_R})/([${WC}.]+)`, 'gu');
517
+ export const BINDING = new RegExp(`${B}([A-Z]${W}*?)Binding${B}`, 'gu');
518
+ export const IMPORT = new RegExp(`${BOL}${S}*import${S}+(?:static${S}+)?([${WC}.]+?)(?:\\.\\*)?${S}*;?${S}*${EOLA}`, 'gu');
519
+ export const EXTENDS_JAVA = new RegExp(`${B}class${S}+(${W}+)(?:<[^>{]*>)?${S}+extends${S}+([${WC}.]+)`, 'u');
520
+ export const EXTENDS_KT = new RegExp(`${B}class${S}+(${W}+)[^:{]*:${S}*([${WC}.]+)${S}*\\(`, 'u');
521
+ export const ASSET_LIT = new RegExp(`"([${WC}./-]+\\.(?:csv|json|txt|xml|html|md))"`, 'gu');
522
+ export const CLASS_TOKEN = new RegExp(`${B}([A-Z]${W}+)${B}`, 'gu');
523
+ export const CUSTOM_TAG = new RegExp(`<([a-z]${W}*(?:\\.${W}+)+)[${SP}>/]`, 'gu');
524
+ export const FILE_TYPES = new Set(['layout', 'xml', 'menu', 'drawable', 'mipmap', 'font', 'raw', 'anim']);
525
+ export const VALUE_JSON = new Map([['string', 'string'], ['color', 'color'], ['dimen', 'float'], ['integer', 'integer'],
526
+ ['bool', 'boolean'], ['plurals', 'plural']]);
527
+ export const TABLE_TYPES = ['string', 'plurals', 'color', 'dimen', 'integer', 'bool', 'drawable', 'mipmap',
528
+ 'array', 'font', 'raw'];
529
+ export const MAX_RELATED = 30;
530
+ export const MAPPINGS = path.join(path.dirname(path.dirname(fs.realpathSync.native(fileURLToPath(import.meta.url)))),
531
+ 'references', 'mappings');
532
+ export const XML_TAG = new RegExp(`<([A-Za-z][${WC}.]*)[${SP}>/]`, 'gu');
533
+ export const LISTENER = new RegExp(`${B}(?:set|add)?On(${W}+?)(?:Change)?Listener${B}`, 'gu');
534
+ export const HEADING = new RegExp(`^(#{2,4})${S}+(.*${NS})${S}*$`, 'u');
535
+ export const ASCII_WORD = /[A-Za-z][A-Za-z0-9]+/g;
536
+ // Heading words that name a category, not a widget: never a match on their own.
537
+ export const GENERIC = new Set(['Android', 'HarmonyOS', 'API', 'UI', 'Mapping', 'Reference', 'View', 'Layout', 'Text',
538
+ 'Image', 'Button', 'Event', 'Events', 'New', 'vs', 'and', 'or', 'the']);
539
+ const VIEW_CLASS = new RegExp(`class="([${WC}.$]+)"`, 'gu');
540
+ const EMBEDDED = new RegExp(`(?:android:name|android:fragment|app:fragment)="([${WC}.]+)"`, 'gu');
541
+ const R_LAYOUT = new RegExp(`${B}R\\.layout\\.(${W}+)`, 'gu');
542
+ const MAP_KEY = new RegExp(`#(${W}+)/(.+)$`, 'u');
543
+ const STRIP_LINE = /:\p{Nd}+(?=\n?$)/gu;
544
+ const UPPER = /^\p{Uppercase}$/u;
545
+
546
+ /** re.findall: the group (1 group) or the tuple of groups. */
547
+ function findall(re, text) {
548
+ return [...text.matchAll(re)].map((m) => (m.length === 2 ? m[1] : m.slice(1)));
549
+ }
550
+ /** set(xs) iterated: first-occurrence order. */
551
+ const uniq = (xs) => [...new Set(xs)];
552
+ const last = (xs) => xs[xs.length - 1];
553
+ const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
554
+
555
+ export function mappingSections(root = MAPPINGS) {
556
+ // [(file, start, end, level, heading, words)] for every ##..#### heading.
557
+ const out = [];
558
+ for (const f of sortedBy(globExt(pathStr(root), '.md'), pOrder)) {
559
+ const lines = splitlines(_read(f));
560
+ const heads = [];
561
+ lines.forEach((l, i) => { const m = HEADING.exec(l); if (m) { heads.push([i + 1, m[1].length, m[2]]); } });
562
+ heads.forEach(([i, lvl, h], k) => {
563
+ const nx = heads.slice(k + 1).find(([, l2]) => l2 <= lvl);
564
+ const end = nx ? nx[0] - 1 : lines.length;
565
+ const words = new Set((h.split('→')[0].match(ASCII_WORD) || []).filter((w) => !GENERIC.has(w)));
566
+ out.push([f, i, end, lvl, h, words]);
567
+ });
568
+ }
569
+ return out;
570
+ }
571
+
572
+ export function usedNames(pack, uiInfo, group) {
573
+ // Widget class short names (layout tags, captured view trees) and listener
574
+ // kinds (setOnClickListener -> Click) the group's own files use.
575
+ const names = new Set();
576
+ for (const [p, rel] of pack.files.values()) {
577
+ if (rel === 'related') { continue; }
578
+ const text = _read(p);
579
+ if (pSuffix(p) === '.xml') {
580
+ for (const t of findall(XML_TAG, text)) { names.add(last(t.split('.'))); }
581
+ } else {
582
+ for (const t of findall(LISTENER, text)) { names.add(t); }
583
+ for (const t of findall(CLASS_TOKEN, text)) {
584
+ if (['View', 'Layout', 'Bar', 'Sheet', 'Dialog', 'Pager'].some((x) => t.endsWith(x))) { names.add(t); }
585
+ }
586
+ }
587
+ }
588
+ for (const d of pyIter(or(dget(group, 'page_dirs'), []))) {
589
+ const vx = pJoin(uiInfo, d, 'view.xml');
590
+ if (isFile(vx)) {
591
+ for (const c of findall(VIEW_CLASS, _read(vx))) { names.add(last(c.split('.'))); }
592
+ }
593
+ }
594
+ return names;
595
+ }
596
+
597
+ // The interaction reference titles its sections in Chinese ("点击手势", "滑动手势"):
598
+ // an Android signal -> the heading word that names it.
599
+ export const SIGNAL_WORDS = new Map(Object.entries({
600
+ Click: '点击', ItemClick: '点击', LongClick: '长按', ItemLongClick: '长按',
601
+ Touch: '触摸', Scroll: '滑动', Fling: '滑动', Swipe: '滑动', Drag: '拖', Refresh: '滑动',
602
+ SwipeRefreshLayout: '滑动', MotionLayout: '动画', ItemTouchHelper: '滑动删除',
603
+ ObjectAnimator: '属性动画', ValueAnimator: '属性动画', AnimatorListener: '动画监听',
604
+ FocusChange: '焦点', Key: '键盘', EditorAction: '键盘',
605
+ }));
606
+ export const WHOLE_FILE_BELOW = 12_000; // a reference this small is listed whole
607
+
608
+ const secKey = (s) => [pKey(s[0]), s[1], s[2], s[3], s[4]].join('\u0000');
609
+
610
+ export function mappingIndex(names, sections = null) {
611
+ // Deepest matching section per (file, name): the agent reads exactly those
612
+ // line ranges instead of paging through a 175 KB reference.
613
+ sections = sections ?? mappingSections();
614
+ names = new Set(names);
615
+ const picked = new Map(); // (file, word) -> {f, w, sec}
616
+ for (const [f, a, b, lvl, h, words] of sections) {
617
+ const hit = new Set([...words].filter((w) => names.has(w)));
618
+ if (pName(f).includes('interaction')) {
619
+ // Chinese signal words name interaction sections only; elsewhere
620
+ // "动画" also titles unrelated sections (Compose animation APIs).
621
+ for (const n of names) { const sw = SIGNAL_WORDS.get(n); if (sw && h.includes(sw)) { hit.add(n); } }
622
+ }
623
+ for (const w of sortedBy(hit)) {
624
+ const k = pKey(f) + '\u0000' + w;
625
+ const cur = picked.get(k)?.sec;
626
+ if (cur === undefined || lvl > cur[3] || (lvl === cur[3] && a < cur[1])) {
627
+ picked.set(k, { f, w, sec: [f, a, b, lvl, h] });
628
+ }
629
+ }
630
+ }
631
+ const rows = new Map(); // sec -> {sec, ws}
632
+ for (const { w, sec } of picked.values()) {
633
+ const k = secKey(sec);
634
+ if (!rows.has(k)) { rows.set(k, { sec, ws: new Set() }); }
635
+ rows.get(k).ws.add(w);
636
+ }
637
+ // A used class with no section of its own but named in a table row: point
638
+ // at those lines (MotionLayout is a row of the ConstraintLayout tables).
639
+ const files = new Map();
640
+ for (const s of sections) { if (!files.has(pKey(s[0]))) { files.set(pKey(s[0]), s[0]); } }
641
+ for (const f of sortedBy(files.values(), pOrder)) {
642
+ if (fs.statSync(f).size < WHOLE_FILE_BELOW || pName(f).includes('interaction')) { continue; }
643
+ const covered = new Set([...picked.values()].filter((x) => pKey(x.f) === pKey(f)).map((x) => x.w));
644
+ const lines = splitlines(_read(f));
645
+ for (const w of sortedBy([...names].filter((x) => !covered.has(x) && !GENERIC.has(x)))) {
646
+ const cps = [...w];
647
+ if (!(cps.length > 5 && UPPER.test(cps[0]) && cps.slice(1).some((c) => UPPER.test(c)))) {
648
+ continue; // CamelCase class names only, not prose words
649
+ }
650
+ const re = new RegExp(`${B}${reEscape(w)}${B}`, 'u');
651
+ const hits = [];
652
+ lines.forEach((l, i) => { if (re.test(l)) { hits.push(i + 1); } });
653
+ if (hits.length) {
654
+ const sec = [f, hits[0], hits[0], 9, `rows naming ${w}: lines ${hits.slice(0, 6).join(', ')}`];
655
+ rows.set(secKey(sec), { sec, ws: new Set([w]) });
656
+ }
657
+ }
658
+ }
659
+ for (const f of files.values()) {
660
+ if (fs.statSync(f).size < WHOLE_FILE_BELOW) {
661
+ const n = splitlines(_read(f)).length;
662
+ for (const [k, v] of [...rows]) { if (pKey(v.sec[0]) === pKey(f)) { rows.delete(k); } }
663
+ const sec = [f, 1, n, 1, '(whole file — small)'];
664
+ rows.set(secKey(sec), { sec, ws: new Set(['all']) });
665
+ }
666
+ }
667
+ return sortedBy([...rows.values()].map(({ sec, ws }) => [sec, sortedBy(ws)]), (r) => [pathStr(r[0][0]), r[0][1]]);
668
+ }
669
+
670
+ export function snake(camel) {
671
+ return camel.replace(/(?<!^)(?=[A-Z])/g, '_').toLowerCase();
672
+ }
673
+
674
+ // ---------------------------------------------------------------- Android index
675
+
676
+ /** Name -> files for sources and resources, excluding build outputs. */
677
+ export class AndroidIndex {
678
+ constructor(root) {
679
+ this.root = pathStr(root);
680
+ this.by_class = new Map(); // stem -> [path]
681
+ this.by_fqcn = new Map(); // fqcn -> path
682
+ this.res = new Map(); // "kind\0name" -> [path]
683
+ this.values = [];
684
+ this.assets = new Map(); // name -> [path]
685
+ this._defs = new Map();
686
+ for (const p of this._walk(this.root)) {
687
+ const parts = pParts(p);
688
+ const suf = pSuffix(p);
689
+ if (SRC_EXT.includes(suf) && (parts.includes('java') || parts.includes('kotlin'))) {
690
+ if (!this.by_class.has(pStem(p))) { this.by_class.set(pStem(p), []); }
691
+ this.by_class.get(pStem(p)).push(p);
692
+ const k = parts.includes('java') ? 'java' : 'kotlin';
693
+ const rel = parts.slice(parts.lastIndexOf(k) + 1);
694
+ this.by_fqcn.set(rel.join('.').slice(0, -suf.length), p);
695
+ } else if (parts.includes('assets') && parts.includes('src')) {
696
+ if (!this.assets.has(pName(p))) { this.assets.set(pName(p), []); }
697
+ this.assets.get(pName(p)).push(p);
698
+ } else if (parts.length >= 3 && parts[parts.length - 3] === 'res') {
699
+ const kind = parts[parts.length - 2].split('-')[0];
700
+ if (kind === 'values') {
701
+ if (suf === '.xml') { this.values.push(p); }
702
+ } else {
703
+ const key = kind + '\u0000' + pStem(p).split('.')[0];
704
+ if (!this.res.has(key)) { this.res.set(key, []); }
705
+ this.res.get(key).push(p);
706
+ }
707
+ }
708
+ }
709
+ }
710
+
711
+ * _walk(d) {
712
+ let entries;
713
+ try { entries = listDir(d); } catch { return; }
714
+ for (const e of entries) {
715
+ if (isDir(e)) {
716
+ const nm = pName(e);
717
+ if (!SKIP_DIRS.has(nm) && !nm.startsWith('.')) { yield* this._walk(e); }
718
+ } else {
719
+ yield e;
720
+ }
721
+ }
722
+ }
723
+
724
+ /** Prefer src/main and unqualified resource dirs. */
725
+ static _rank(p) {
726
+ const s = pathStr(p).replace(/\\/g, '/');
727
+ return [!s.includes('/src/main/'), pName(pParent(p)).includes('-'), [...s].length];
728
+ }
729
+
730
+ res_file(kind, name) {
731
+ const hits = this.res.get(kind + '\u0000' + name) || [];
732
+ return hits.length ? sortedBy(hits, AndroidIndex._rank)[0] : null;
733
+ }
734
+
735
+ cls(name, imports = [], near = null) {
736
+ if (typeof name !== 'string') { throw new TypeError(`argument of type '${pyType(name)}' is not iterable`); }
737
+ if (name.includes('.') && this.by_fqcn.has(name)) { return this.by_fqcn.get(name); }
738
+ const simple = last(name.split('.'));
739
+ for (const imp of imports) {
740
+ if (imp.endsWith('.' + simple) && this.by_fqcn.has(imp)) { return this.by_fqcn.get(imp); }
741
+ }
742
+ const hits = this.by_class.get(simple) || [];
743
+ if (near !== null) {
744
+ const same = hits.filter((h) => pKey(pParent(h)) === pKey(pParent(near)));
745
+ if (same.length) { return same[0]; }
746
+ }
747
+ return hits.length >= 1 ? sortedBy(hits, AndroidIndex._rank)[0] : null;
748
+ }
749
+
750
+ /** name -> [file, line] of the first `<tag name="...">` in values/*.xml. */
751
+ value_defs(tag) {
752
+ if (!this._defs.has(tag)) {
753
+ const pat = new RegExp(`<${tag}${S}+name="([^"]+)"`, 'u');
754
+ const found = new Map();
755
+ for (const p of sortedBy(this.values, AndroidIndex._rank)) {
756
+ splitlines(_read(p)).forEach((line, i) => {
757
+ const m = pat.exec(line);
758
+ if (m && !found.has(m[1])) { found.set(m[1], [p, i + 1]); }
759
+ });
760
+ }
761
+ this._defs.set(tag, found);
762
+ }
763
+ return this._defs.get(tag);
764
+ }
765
+ }
766
+
767
+ // ---------------------------------------------------------------- Harmony resources
768
+
769
+ /** Key of a (qual, kind, name) value: name keeps its json type (1 != "1"). */
770
+ function valKey(qual, kind, name) {
771
+ if (Array.isArray(name) || isDict(name)) { throw new TypeError(`unhashable type: '${pyType(name)}'`); }
772
+ return [qual, kind, typeof name === 'string' ? 's:' + name : 'o:' + pyRepr(name)].join('\u0000');
773
+ }
774
+
775
+ export class HarmonyRes {
776
+ constructor(harmonyDir, module = 'entry') {
777
+ this.base = pJoin(harmonyDir, module, 'src', 'main', 'resources');
778
+ this.mapping = new Map(); // "kind\0name" -> [[target, kind]]
779
+ const mp = pJoin(harmonyDir, '.hometrans', 'resource_mapping.md');
780
+ if (isFile(mp)) { this._parse_mapping(mp); }
781
+ this.values = new Map();
782
+ for (const qual of ['base', 'zh_CN', 'dark']) {
783
+ for (const f of globExt(pJoin(this.base, qual, 'element'), '.json')) {
784
+ const data = or(_load(f, {}), {});
785
+ if (!isDict(data)) { throw new TypeError(`'${pyType(data)}' object has no attribute 'items'`); }
786
+ for (const kind of keysOf(data)) {
787
+ const rows = data[kind];
788
+ for (const r of Array.isArray(rows) ? rows : []) {
789
+ if (isDict(r) && Object.hasOwn(r, 'name')) {
790
+ this.values.set(valKey(qual, kind, r.name), Object.hasOwn(r, 'value') ? r.value : null);
791
+ }
792
+ }
793
+ }
794
+ }
795
+ }
796
+ }
797
+
798
+ _parse_mapping(p) {
799
+ let inDetail = false;
800
+ for (const line of splitlines(_read(p))) {
801
+ if (line.startsWith('## ')) {
802
+ inDetail = line.includes('Mapping Details') || line.includes('映射明细');
803
+ continue;
804
+ }
805
+ if (!inDetail || !line.startsWith('| res/')) { continue; }
806
+ const t = pyStrip(line).replace(/^\|+|\|+$/g, '');
807
+ const cols = t.split('|').map(pyStrip);
808
+ if (cols.length < 6) { continue; }
809
+ const [src, target, kind] = [cols[0], cols[4], cols[5]];
810
+ let key;
811
+ if (src.includes('#')) {
812
+ const m = MAP_KEY.exec(src);
813
+ key = m ? [m[1], m[2]] : null;
814
+ } else {
815
+ key = [pName(pParent(src)).split('-')[0], pStem(src).split('.')[0]];
816
+ }
817
+ if (key) {
818
+ const k = key.join('\u0000');
819
+ if (!this.mapping.has(k)) { this.mapping.set(k, []); }
820
+ this.mapping.get(k).push([target, kind]);
821
+ }
822
+ }
823
+ }
824
+
825
+ value(kind, name) {
826
+ const jk = VALUE_JSON.get(kind);
827
+ if (!jk) { return null; }
828
+ const out = {};
829
+ for (const qual of ['base', 'zh_CN', 'dark']) {
830
+ const v = this.values.get(valKey(qual, jk, name));
831
+ if (v !== undefined && v !== null) { out[qual] = v; }
832
+ }
833
+ return Object.keys(out).length ? out : null;
834
+ }
835
+
836
+ row(kind, name) {
837
+ const targets = this.mapping.get(kind + '\u0000' + name) || [];
838
+ const t0 = targets.find(([t]) => t && t !== 'N/A');
839
+ const tgt = t0 ? t0[0] : null;
840
+ const status = targets.length ? targets[0][1] : 'not in mapping';
841
+ let exists = null;
842
+ if (tgt) {
843
+ const f = tgt.split('#')[0];
844
+ const p = f.startsWith('resources/') ? pJoin(pParent(this.base), f) : pJoin(this.base, f);
845
+ exists = isFile(p) && (!tgt.includes('#') || this.value(kind, name) !== null || !VALUE_JSON.has(kind));
846
+ }
847
+ const hname = tgt && tgt.includes('#') ? last(tgt.split('#')) : (tgt ? pStem(tgt) : null);
848
+ let ref = null;
849
+ if (tgt && tgt.includes('#')) {
850
+ ref = `app.${pStem(tgt.split('#')[0])}.${hname}`; // element/string.json#x
851
+ } else if (tgt && tgt.includes('/media/')) {
852
+ ref = `app.media.${hname}`;
853
+ } else if (tgt && tgt.includes('/rawfile/')) {
854
+ ref = 'rawfile ' + tgt.slice(tgt.indexOf('/rawfile/') + '/rawfile/'.length);
855
+ }
856
+ return { android: `${kind}/${name}`, harmony: tgt, ref: ref || tgt,
857
+ status, exists, value: this.value(kind, hname || name) };
858
+ }
859
+ }
860
+
861
+ // ---------------------------------------------------------------- pack
862
+
863
+ export class Pack {
864
+ constructor(idx) {
865
+ this.idx = idx;
866
+ this.files = new Map(); // pKey -> [path, relation, reason]
867
+ this.refs = new Map(); // "kind\0name" -> [kind, name]
868
+ this.styles = new Set();
869
+ this.arrays = new Set();
870
+ this.assets = new Map(); // pKey -> path
871
+ }
872
+
873
+ has(p) { return this.files.has(pKey(p)); }
874
+
875
+ add(p, relation, why) {
876
+ if (p === null || p === undefined) { return false; }
877
+ p = pathStr(p);
878
+ if (this.files.has(pKey(p))) { return false; }
879
+ this.files.set(pKey(p), [p, relation, why]);
880
+ return true;
881
+ }
882
+
883
+ /** A host Activity contributes its window chrome: itself, its base chain and its own
884
+ * layouts -- not every screen it can show (its R.xml.* are sibling pref screens). */
885
+ scan_host(p, label) {
886
+ if (!this.add(p, 'host', `host activity of ${pyStr(label)}`)) { return; }
887
+ const text = _read(p);
888
+ const names = [...findall(BINDING, text).map(snake), ...findall(R_LAYOUT, text)];
889
+ for (const name of sortedBy(uniq(names))) {
890
+ const lay = this.idx.res_file('layout', name);
891
+ if (lay && this.add(lay, 'host', `layout of ${pName(p)}`)) { this.scan_xml(lay, 'host'); }
892
+ }
893
+ const m = EXTENDS_JAVA.exec(text) || EXTENDS_KT.exec(text);
894
+ const base = m ? this.idx.cls(m[2], findall(IMPORT, text), p) : null;
895
+ if (base !== null && !this.has(base)) { this.scan_host(base, label); }
896
+ }
897
+
898
+ scan_source(p, relation, followBase = true) {
899
+ const text = _read(p);
900
+ const imports = findall(IMPORT, text);
901
+ for (const lit of uniq(findall(ASSET_LIT, text))) {
902
+ for (const a of (this.idx.assets.get(last(lit.split('/'))) || []).slice(0, 1)) {
903
+ if (!this.assets.has(pKey(a))) { this.assets.set(pKey(a), a); }
904
+ }
905
+ }
906
+ for (const [kind, name] of findall(R_REF, text)) { this._ref(kind, name, p, relation); }
907
+ for (const b of uniq(findall(BINDING, text))) {
908
+ const lay = this.idx.res_file('layout', snake(b));
909
+ if (lay && this.add(lay, relation, `${b}Binding in ${pName(p)}`)) { this.scan_xml(lay, relation); }
910
+ }
911
+ if (followBase) {
912
+ const m = EXTENDS_JAVA.exec(text) || EXTENDS_KT.exec(text);
913
+ if (m) {
914
+ const base = this.idx.cls(m[2], imports, p);
915
+ if (base && this.add(base, 'base', `base of ${m[1]}`)) { this.scan_source(base, 'base', true); }
916
+ }
917
+ }
918
+ return imports;
919
+ }
920
+
921
+ _addRef(kind, name) {
922
+ const k = kind + '\u0000' + name;
923
+ if (!this.refs.has(k)) { this.refs.set(k, [kind, name]); }
924
+ }
925
+
926
+ _ref(kind, name, src, relation) {
927
+ if (['layout', 'xml', 'menu'].includes(kind)) {
928
+ const f = this.idx.res_file(kind, name);
929
+ if (f && this.add(f, relation, `R.${kind}.${name} in ${pName(src)}`)) { this.scan_xml(f, relation); }
930
+ } else if (kind === 'style') {
931
+ this.styles.add(name.replace(/_/g, '.'));
932
+ } else {
933
+ if (kind === 'array') { this.arrays.add(name); }
934
+ this._addRef(kind, name);
935
+ }
936
+ }
937
+
938
+ scan_xml(p, relation) {
939
+ const text = _read(p);
940
+ for (const [kind, name] of findall(X_REF, text)) {
941
+ if (['layout', 'xml', 'menu'].includes(kind)) {
942
+ const f = this.idx.res_file(kind, name);
943
+ if (f && this.add(f, relation, `@${kind}/${name} in ${pName(p)}`)) { this.scan_xml(f, relation); }
944
+ } else if (kind === 'style') {
945
+ this.styles.add(name);
946
+ } else {
947
+ if (kind === 'array') { this.arrays.add(name); }
948
+ this._addRef(kind, name);
949
+ }
950
+ }
951
+ for (const tag of uniq(findall(CUSTOM_TAG, text))) {
952
+ if (['android.', 'androidx.', 'com.google.'].some((x) => tag.startsWith(x))) { continue; }
953
+ const c = this.idx.cls(tag);
954
+ if (c && this.add(c, 'custom-view', `<${last(tag.split('.'))}> in ${pName(p)}`)) {
955
+ this.scan_source(c, 'custom-view', false);
956
+ }
957
+ }
958
+ // fragments embedded by layout: <fragment android:name>, FragmentContainerView, prefs
959
+ for (const m of text.matchAll(EMBEDDED)) {
960
+ const c = m[1].includes('.') ? this.idx.cls(m[1]) : null;
961
+ if (c && this.add(c, relation, `embedded fragment in ${pName(p)}`)) { this.scan_source(c, relation, false); }
962
+ }
963
+ }
964
+ }
965
+
966
+ function _memberClasses(meta, idx, android) {
967
+ // A page's own sources: its class (declared_at; the activity class when declared_at
968
+ // is only the manifest), its attached nodes, its layouts, its extends_base.
969
+ const out = [];
970
+ const locs = [dget(meta, 'declared_at'), ...pyIter(or(dget(meta, 'attached_nodes'), [])).map((a) => dget(a, 'declared_at'))];
971
+ for (const loc of locs) {
972
+ if (!truthy(loc)) { continue; }
973
+ if (typeof loc !== 'string') { throw new TypeError('expected string or bytes-like object'); }
974
+ let p = pJoin(android, loc.replace(STRIP_LINE, ''));
975
+ if (pName(p) === 'AndroidManifest.xml') {
976
+ const act = or(dget(or(dget(meta, 'activity_info'), {}), 'activity'), dget(meta, 'label'));
977
+ p = truthy(act) ? idx.cls(act) : null;
978
+ } else if (!isFile(p) && SRC_EXT.includes(pSuffix(p))) {
979
+ p = idx.cls(pStem(p)); // static UTG recorded the class in another module
980
+ }
981
+ if (p !== null && isFile(p)) { out.push(p); }
982
+ }
983
+ const hints = or(dget(meta, 'source_hints'), {});
984
+ for (const lf of pyIter(or(dget(hints, 'layout_files'), []))) {
985
+ const p = pJoin(android, lf);
986
+ if (isFile(p)) { out.push(p); }
987
+ }
988
+ if (truthy(dget(hints, 'extends_base'))) {
989
+ const c = idx.cls(dsub(hints, 'extends_base'));
990
+ if (c) { out.push(c); }
991
+ }
992
+ return out;
993
+ }
994
+
995
+ export function buildGroup(group, uiInfo, idx, hres, android) {
996
+ const pack = new Pack(idx);
997
+ const hosts = [];
998
+ for (const d of pyIter(or(dget(group, 'page_dirs'), []))) {
999
+ const meta = or(_load(pJoin(uiInfo, d, 'meta.json'), {}), {});
1000
+ const label = dget(meta, 'label', d);
1001
+ const members = _memberClasses(meta, idx, android);
1002
+ for (const p of members) {
1003
+ if (pSuffix(p) === '.xml') {
1004
+ if (pack.add(p, 'member', `layout of ${pyStr(label)}`)) { pack.scan_xml(p, 'member'); }
1005
+ } else if (pack.add(p, 'member', `class of ${pyStr(label)}`)) {
1006
+ pack.scan_source(p, 'member');
1007
+ }
1008
+ }
1009
+ // the Activity hosting a fragment/dialog owns its toolbar and window chrome
1010
+ const act = dget(or(dget(meta, 'activity_info'), {}), 'activity');
1011
+ const h = truthy(act) ? idx.cls(act) : null;
1012
+ if (h !== null && !members.some((m) => pKey(m) === pKey(h))) { hosts.push([h, label]); }
1013
+ }
1014
+ for (const [h, label] of hosts) { pack.scan_host(h, label); }
1015
+ // one level of related classes from member/base sources: same-package types the
1016
+ // code names (no import line), and in-project imports that look like UI classes
1017
+ let related = 0;
1018
+ for (const [p, rel] of [...pack.files.values()]) {
1019
+ if (!['member', 'base'].includes(rel) || !SRC_EXT.includes(pSuffix(p))) { continue; }
1020
+ const text = _read(p);
1021
+ const cands = [];
1022
+ for (const tok of sortedBy(uniq(findall(CLASS_TOKEN, text)))) {
1023
+ for (const h of idx.by_class.get(tok) || []) {
1024
+ if (pKey(pParent(h)) === pKey(pParent(p)) && pKey(h) !== pKey(p)) { cands.push([h, `same package, used by ${pName(p)}`]); }
1025
+ }
1026
+ }
1027
+ for (const imp of findall(IMPORT, text)) {
1028
+ if (idx.by_fqcn.has(imp) && UI_SUFFIX.test(last(imp.split('.')))) {
1029
+ cands.push([idx.by_fqcn.get(imp), `imported by ${pName(p)}`]);
1030
+ }
1031
+ }
1032
+ for (const [c, why] of cands) {
1033
+ if (related >= MAX_RELATED) { break; }
1034
+ if (pack.add(c, 'related', why)) {
1035
+ pack.scan_source(c, 'related', false);
1036
+ related += 1;
1037
+ }
1038
+ }
1039
+ }
1040
+ return pack;
1041
+ }
1042
+
1043
+ /**
1044
+ * Inline budget (characters): measured on AntennaPod 10-15 (54 conversion agents), an agent
1045
+ * made a median 52 read/grep calls, about half of its ~52 turns at ~25 s each, and 26% of
1046
+ * its reads re-read a file it had read already. The pack listed most of what it read
1047
+ * (592 of 722 Android reads, 224 slices of the mapping reference) but made the agent fetch
1048
+ * each one. Inlined, the member / base / custom-view sources, the mapping sections and the
1049
+ * style blocks arrive with the pack in one read. Bigger files stay listed: a pack past the
1050
+ * host's read size is read in pages, which costs the turns it was meant to save.
1051
+ */
1052
+ /**
1053
+ * The whole pack must come back from ONE read: opencode / DevEco cap a read at 50 KB
1054
+ * (2000 lines, 2000 chars a line), so a pack past that is read in pages. `pack` bytes
1055
+ * is the cap for the finished file; the inline part gets what the list leaves of it.
1056
+ */
1057
+ export const INLINE = { file: 9000, lines: 220, pack: 48 * 1024, rels: ['member', 'base', 'custom-view'] };
1058
+
1059
+ const fence = (p) => (pSuffix(p) === '.xml' ? 'xml' : pSuffix(p) === '.kt' ? 'kotlin' : 'java');
1060
+
1061
+ /** `text` with line numbers, as the read tool shows it, so citations (`file:line`) still work. */
1062
+ function numbered(text, from = 1) {
1063
+ return splitlines(text).map((l, i) => `${String(from + i).padStart(5)} ${l}`).join('\n');
1064
+ }
1065
+
1066
+ /** Lines a..b (1-based, inclusive) of a file. */
1067
+ function slice(p, a, b) {
1068
+ return splitlines(_read(p)).slice(a - 1, b);
1069
+ }
1070
+
1071
+ /**
1072
+ * The inlined part of a pack: member sources first (they are read anyway), then mapping
1073
+ * sections and style blocks, then base / custom-view sources, until `room` bytes. Returns
1074
+ * {lines, inlined: Set of pKey, chars}; whatever did not fit stays a listed path.
1075
+ */
1076
+ export function inlineBlock(pack, idxRows, styles, room, budget = INLINE) {
1077
+ const inlined = new Set(); let used = 0;
1078
+ const bytes = (s) => Buffer.byteLength(s, 'utf8') + (s.match(/\n/g)?.length ?? 0); // CRLF on disk
1079
+ const take = (chunk) => {
1080
+ const n = bytes(chunk);
1081
+ if (used + n > room) return false;
1082
+ used += n; return true;
1083
+ };
1084
+ const files = [...pack.files.values()].filter(([, r]) => budget.rels.includes(r))
1085
+ .sort((x, y) => budget.rels.indexOf(x[1]) - budget.rels.indexOf(y[1]) || cmpStr(pathStr(x[0]), pathStr(y[0])));
1086
+ const src = [];
1087
+ const addSources = (rels) => {
1088
+ for (const [p, rel] of files) {
1089
+ if (!rels.includes(rel)) continue;
1090
+ const text = _read(p);
1091
+ if (text.length > budget.file || splitlines(text).length > budget.lines) continue;
1092
+ const chunk = `### ${rel}: \`${p}\`\n\n\`\`\`${fence(p)}\n${numbered(text)}\n\`\`\`\n`;
1093
+ if (take(chunk)) { inlined.add(pKey(p)); src.push(chunk); }
1094
+ }
1095
+ };
1096
+ addSources(['member']);
1097
+ const maps = [];
1098
+ for (const [[f, a, b, , h]] of idxRows) {
1099
+ if (b - a + 1 > budget.lines) continue;
1100
+ const chunk = `### ${h} — \`${pName(f)}\` lines ${a}-${b}\n\n${slice(f, a, b).join('\n')}\n`;
1101
+ if (take(chunk)) { inlined.add(`${pKey(f)}#${a}`); maps.push(chunk); }
1102
+ }
1103
+ const sty = [];
1104
+ for (const [name, hit] of styles) {
1105
+ const lines = splitlines(_read(hit[0]));
1106
+ let end = hit[1];
1107
+ while (end < lines.length && end - hit[1] < 40 && !/<\/style>/.test(lines[end - 1])) end += 1;
1108
+ const chunk = `- \`${name}\` (\`${pName(hit[0])}:${hit[1]}\`)\n\n\`\`\`xml\n${numbered(lines.slice(hit[1] - 1, end).join('\n'), hit[1])}\n\`\`\`\n`;
1109
+ if (take(chunk)) { inlined.add(`${pKey(hit[0])}#${hit[1]}`); sty.push(chunk); }
1110
+ }
1111
+ addSources(budget.rels.filter((r) => r !== 'member'));
1112
+ const lines = [];
1113
+ if (src.length) lines.push('## Inlined sources (already read for you — do not read these files again)', '', ...src);
1114
+ if (maps.length) lines.push('## Inlined mapping-reference sections', '', ...maps);
1115
+ if (sty.length) lines.push('## Inlined style definitions', '', ...sty);
1116
+ return { lines, inlined, chars: used };
1117
+ }
1118
+
1119
+ /**
1120
+ * Every frame of every state the group converts against, labelled by the static node it shows.
1121
+ *
1122
+ * A group's `page_dirs` are its members' own dirs plus the captured dirs of nodes attached to
1123
+ * them (build_conversion_set folds a captured ui-state / panel / menu into its host's group).
1124
+ * One dir = one state; inside it `view.xml` + `view_vpN.xml` + `view_scroll_N.xml` are frames
1125
+ * of that state, each with its screenshot unless FLAG_SECURE blocked it. Handing an agent only
1126
+ * `meta.screenshot` lost every other frame and every attached state: captured states were then
1127
+ * converted from source branches as if never seen.
1128
+ *
1129
+ * -> {entries: [{page_dir, node, relation, tier, label, frames: [{view_xml, screenshot,
1130
+ * blocked}], missing: [path], measure_summary}], uncaptured: [{node, kind, label, host}]}
1131
+ * Paths are absolute. `missing` = a declared file that does not exist (Step 4.1 fails the page).
1132
+ */
1133
+ export function referenceEvidence(group, uiInfo) {
1134
+ const relation = new Map(pyIter(or(dget(group, 'members'), [])).map((m) => [dget(m, 'node'), dget(m, 'relation')]));
1135
+ const dirs = pyIter(or(dget(group, 'page_dirs'), [])).map(pyStr);
1136
+ // attached_nodes: in meta.json for a source-only page, in its pages.json row for a captured one
1137
+ const rows = new Map(pyIter(or(dget(or(_load(pJoin(uiInfo, 'pages.json'), {}), {}), 'pages'), []))
1138
+ .map((p) => [pName(pyStr(dget(p, 'page_dir'))), or(dget(p, 'attached_nodes'), [])]));
1139
+ const entries = [];
1140
+ const attached = new Map();
1141
+ for (const d of dirs) {
1142
+ const dir = pJoin(uiInfo, d);
1143
+ const meta = or(_load(pJoin(dir, 'meta.json'), {}), {});
1144
+ const node = pyStr(or(dget(meta, 'static_node'), d));
1145
+ const abs = (rel) => pathStr(pJoin(uiInfo, rel));
1146
+ const shots = new Set(pyIter(or(dget(meta, 'screenshots'), [])).map(pyStr));
1147
+ const blocked = new Map(pyIter(or(dget(meta, 'screenshots_blocked'), [])).map((b) => [pyStr(dget(b, 'view_xml')), pyStr(dget(b, 'reason'))]));
1148
+ const frames = []; const missing = [];
1149
+ for (const vx of pyIter(or(dget(meta, 'view_xmls'), [])).map(pyStr)) {
1150
+ // view.xml <-> screenshot.png, view_vp1.xml <-> screenshot_vp1.png, view_scroll_2.xml <-> screenshot_scroll_2.png
1151
+ const shot = vx.replace(/\/view(_[^/]*)?\.xml$/, (_, t) => `/screenshot${t || ''}.png`);
1152
+ const frame = { view_xml: abs(vx), screenshot: shots.has(shot) ? abs(shot) : null, blocked: blocked.get(vx) ?? null };
1153
+ if (!isFile(frame.view_xml)) { missing.push(frame.view_xml); }
1154
+ if (frame.screenshot && !isFile(frame.screenshot)) { missing.push(frame.screenshot); }
1155
+ frames.push(frame);
1156
+ }
1157
+ const summary = pJoin(dir, 'measure_summary.txt');
1158
+ const density = Number(dget(dget(or(_load(pJoin(dir, 'measure_pack.json'), {}), {}), 'density') ?? {}, 'value')) ||
1159
+ Number(dget(dget(meta, 'device_info') ?? {}, 'density')) || 0;
1160
+ entries.push({ page_dir: pathStr(dir), node, relation: relation.get(node) ?? 'attached',
1161
+ tier: pyStr(or(dget(meta, 'evidence_tier'), 'captured')), label: pyStr(or(dget(meta, 'label'), node)),
1162
+ frames, missing, measure_summary: isFile(summary) ? pathStr(summary) : null, density });
1163
+ for (const a of [...pyIter(or(dget(meta, 'attached_nodes'), [])), ...pyIter(rows.get(pName(d)) ?? [])]) {
1164
+ attached.set(pyStr(dget(a, 'id')), [a, node]);
1165
+ }
1166
+ }
1167
+ // Attached nodes no dir of this group shows: converted from their source branch alone.
1168
+ const shown = new Set(entries.map((e) => e.node));
1169
+ const uncaptured = [...attached].filter(([id]) => !shown.has(id)).map(([id, [a, host]]) => ({
1170
+ node: id, kind: pyStr(or(dget(a, 'kind'), '')), label: pyStr(or(dget(a, 'label'), id)), host }));
1171
+ return { entries, uncaptured: sortedBy(uncaptured, (u) => u.node) };
1172
+ }
1173
+
1174
+ /**
1175
+ * Container geometry of a uiautomator view tree in dp: every node with children that is at least
1176
+ * 40% of the root's width, with its insets from its parent and whether it spans the parent's
1177
+ * content column (`full`: same width as the widest sibling container, or parent width minus equal
1178
+ * insets). Measured on where2study5 settings (FLAG_SECURE, tree-only): the agent read the cards'
1179
+ * inner text start (x=94px) as the content edge and guessed a tablet mode; the card box itself
1180
+ * ([52..1028]) said full width. Computing the insets removes that reading step. `density` 0 = px.
1181
+ */
1182
+ export function treeGeometry(viewXml, density, limit = 40) {
1183
+ let xml = '';
1184
+ try { xml = fs.readFileSync(viewXml, 'utf8'); } catch { return []; }
1185
+ const d = density > 0 ? density : 1;
1186
+ const round = (v) => Math.round((v / d) * 10) / 10;
1187
+ const nodes = [];
1188
+ const stack = [];
1189
+ const re = /<node\b([^>]*?)(\/?)>|<\/node>/g;
1190
+ let m;
1191
+ while ((m = re.exec(xml)) !== null) {
1192
+ if (m[0] === '</node>') { stack.pop(); continue; }
1193
+ const attr = (k) => (new RegExp(`\\b${k}="([^"]*)"`).exec(m[1]) ?? [])[1] ?? '';
1194
+ const b = /\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(attr('bounds'));
1195
+ const parent = stack.length ? stack[stack.length - 1] : null;
1196
+ const n = { idx: nodes.length, cls: attr('class').split('.').pop(), text: attr('text').slice(0, 24),
1197
+ b: b ? b.slice(1).map(Number) : null, parent, kids: 0 };
1198
+ nodes.push(n);
1199
+ if (parent) parent.kids++;
1200
+ if (m[2] !== '/') stack.push(n);
1201
+ }
1202
+ const root = nodes.find((n) => n.b);
1203
+ if (!root) return [];
1204
+ const rootW = root.b[2] - root.b[0];
1205
+ const out = [];
1206
+ for (const n of nodes) {
1207
+ if (!n.b || !n.parent || !n.parent.b || n.kids === 0) continue;
1208
+ const w = n.b[2] - n.b[0];
1209
+ if (w < rootW * 0.4) continue;
1210
+ const p = n.parent.b;
1211
+ const insetL = n.b[0] - p[0];
1212
+ const insetR = p[2] - n.b[2];
1213
+ const sibs = nodes.filter((s) => s.parent === n.parent && s.b && s.kids > 0);
1214
+ const widest = Math.max(...sibs.map((s) => s.b[2] - s.b[0]));
1215
+ const full = Math.abs(insetL - insetR) <= 2 * d && (w >= widest - 2 * d);
1216
+ out.push({ idx: n.idx, cls: n.cls, x: round(n.b[0]), w: round(w), insetL: round(insetL), insetR: round(insetR), full, text: n.text });
1217
+ if (out.length >= limit) break;
1218
+ }
1219
+ return out;
1220
+ }
1221
+
1222
+ /**
1223
+ * Text drawn on a Canvas by the group's Android sources: `drawText` calls and the Paint text sizes
1224
+ * they use. Custom-view text has no node in the view tree and no measurement, so nothing else hands
1225
+ * these sizes to the agent. Measured on where2study5's teaching calendar: the agent copied
1226
+ * `sp(9f)` / `sp(17f)` / `sp(8f)` as Canvas `'9px'` / `'bold 17px'` / `'8px'`, about 1/2.6 of the
1227
+ * Android size (GATE canvas-font-px-literal now catches the unit; this list is what to check against).
1228
+ */
1229
+ export function canvasTextInventory(files, limit = 40) {
1230
+ const out = [];
1231
+ for (const p of files) {
1232
+ if (!/\.(kt|java)$/.test(p)) continue;
1233
+ const text = _read(p);
1234
+ // only custom views: a TextView's `textSize = 12f` is already sp and has a view-tree node
1235
+ if (!/\bdrawText\s*\(/.test(text) || !/\bonDraw\s*\(/.test(text)) continue;
1236
+ splitlines(text).forEach((line, i) => {
1237
+ if (out.length >= limit) return;
1238
+ if (/^\s*(import|\/\/|\*)/.test(line)) return;
1239
+ // Paint sizes are px, so the source converts them: sp(…) / dp(…) / applyDimension / * density
1240
+ const paintSize = /\btextSize\s*=|\bsetTextSize\s*\(/.test(line) &&
1241
+ /\b(sp|dp|spToPx|dpToPx)\s*\(|applyDimension|density|scaledDensity|getDimension/.test(line);
1242
+ if (paintSize || /\bdrawText\s*\(/.test(line)) {
1243
+ out.push(`- \`${p}:${i + 1}\` — \`${line.trim().slice(0, 140)}\``);
1244
+ }
1245
+ });
1246
+ }
1247
+ return out;
1248
+ }
1249
+
1250
+ /** Markdown of referenceEvidence: what REFERENCE_SCREENSHOTS / REFERENCE_VIEW_TREES carry. */
1251
+ export function renderEvidence(ev) {
1252
+ const lines = ['## Reference evidence — one state per directory, every frame',
1253
+ '',
1254
+ 'Each `###` is one state of this group (the member page, or a node attached to it) with ' +
1255
+ 'every captured frame of that state. Read **all** of them: viewports / scroll frames are ' +
1256
+ 'the same state at other offsets; an attached state is converted against its own frames, ' +
1257
+ 'not from source branches. A `blocked` frame has a view tree but no screenshot (the app ' +
1258
+ 'forbids screen capture): bounds from the tree, colours from source/theme.',
1259
+ ''];
1260
+ for (const e of ev.entries) {
1261
+ const treeOnly = e.frames.length > 0 && e.frames.every((f) => !f.screenshot && f.blocked);
1262
+ lines.push(`### ${e.node} — ${e.label} (${e.relation}, ${e.tier}${treeOnly ? ', **tree-only**' : ''})`, '');
1263
+ if (treeOnly) {
1264
+ lines.push('**Tree-only state: no frame has pixels** (all FLAG_SECURE-blocked). Nothing downstream ' +
1265
+ 'can compare your output with a picture, so geometry must come from the table below, not from ' +
1266
+ 'your own reading of `bounds`: a card is the container whose box spans the column, its text sits ' +
1267
+ 'one padding further in. Every container marked `full` is `.width(\'100%\')` (or a weight) in ' +
1268
+ 'ArkUI; colours, borders and corner radii come from the Android source, never from the tree.', '');
1269
+ const geo = treeGeometry(e.frames[0].view_xml, e.density);
1270
+ if (geo.length) {
1271
+ lines.push('| node | class | x dp | width dp | inset from parent L/R dp | |', '|---|---|---|---|---|---|');
1272
+ for (const g of geo) {
1273
+ lines.push(`| ${g.idx} | ${g.cls} | ${g.x} | ${g.w} | ${g.insetL} / ${g.insetR} | ${g.full ? 'full' : ''}${g.text ? ` "${g.text}"` : ''} |`);
1274
+ }
1275
+ lines.push('');
1276
+ }
1277
+ }
1278
+ if (!e.frames.length) { lines.push('- no capture (source-only)'); }
1279
+ for (const f of e.frames) {
1280
+ const shot = f.screenshot ? `\`${f.screenshot}\`` : (f.blocked ? `no screenshot (blocked: ${f.blocked})` : 'no screenshot');
1281
+ lines.push(`- view tree \`${f.view_xml}\` — screenshot ${shot}`);
1282
+ }
1283
+ if (e.measure_summary) { lines.push(`- MEASUREMENT_PACK: \`${e.measure_summary}\``); }
1284
+ for (const m of e.missing) { lines.push(`- **MISSING** \`${m}\` (Step 4.1: page failed)`); }
1285
+ lines.push('');
1286
+ }
1287
+ if (ev.uncaptured.length) {
1288
+ lines.push('### Attached states with no capture — convert from their source branch', '');
1289
+ for (const u of ev.uncaptured) { lines.push(`- ${u.node} — ${u.label} (${u.kind}, on ${u.host})`); }
1290
+ lines.push('');
1291
+ }
1292
+ return lines;
1293
+ }
1294
+
1295
+ export function render(group, pack, idx, hres, android, uiInfo = null, { inline = false } = {}) {
1296
+ const relOrder = ['member', 'base', 'host', 'custom-view', 'related'];
1297
+ const lines = [`# Source pack — ${pyStr(dsub(group, 'id'))}`,
1298
+ '',
1299
+ 'Reading list resolved by `group_pack.mjs` from meta.json `declared_at`, R.* / @* ' +
1300
+ 'references, base classes, the host Activity and same-package / UI imports. **Read the ' +
1301
+ '`member` and `base` files in one batched turn**; `host` (toolbar / window chrome) and ' +
1302
+ '`related` ones in the next batch, as the conversion needs them. ' +
1303
+ 'A file missing here is read as before — this list is a starting point, not a limit.',
1304
+ ''];
1305
+ if (uiInfo !== null) { lines.push(...renderEvidence(referenceEvidence(group, uiInfo))); }
1306
+ const idxRows = uiInfo !== null ? mappingIndex(usedNames(pack, uiInfo, group)) : [];
1307
+ const styles = idx.value_defs('style');
1308
+ const styleHits = sortedBy([...pack.styles]).filter((x) => styles.get(x)).map((x) => [x, styles.get(x)]);
1309
+ let inl = { lines: [], inlined: new Set() };
1310
+ if (inline) {
1311
+ // room = the one-read cap less the list itself (rendered once without inlining) and the
1312
+ // ' — **inlined**' marks and header line inlining adds
1313
+ const plain = render(group, pack, idx, hres, android, uiInfo, { inline: false });
1314
+ const room = INLINE.pack - Buffer.byteLength(plain, 'utf8') - (plain.match(/\n/g)?.length ?? 0) - 4096;
1315
+ if (room > 2048) inl = inlineBlock(pack, idxRows, styleHits, room);
1316
+ }
1317
+ const mark = (k) => (inl.inlined.has(k) ? ' — **inlined**' : '');
1318
+ if (inl.inlined.size) {
1319
+ lines.push('Entries marked **inlined** are reproduced at the end of this pack with their line numbers: ' +
1320
+ 'cite them as `file:line` and do not read them again.', '');
1321
+ }
1322
+ for (const r of relOrder) {
1323
+ const rows = [...pack.files.values()].filter(([, rr]) => rr === r).map(([p, , why]) => [p, why]);
1324
+ if (!rows.length) { continue; }
1325
+ lines.push(`## ${r} (${rows.length})`, '');
1326
+ for (const [p, why] of sortedBy(rows, (x) => [pSuffix(x[0]) !== '.java' && pSuffix(x[0]) !== '.kt', pathStr(x[0])])) {
1327
+ const n = splitlines(_read(p)).length;
1328
+ lines.push(`- \`${p}\` — ${n} lines — ${why}${mark(pKey(p))}`);
1329
+ }
1330
+ lines.push('');
1331
+ }
1332
+ const canvasText = canvasTextInventory([...pack.files.values()].map(([p]) => pathStr(p)));
1333
+ if (canvasText.length) {
1334
+ lines.push('## Canvas-drawn text (no view-tree node, no measurement)', '',
1335
+ 'Every `drawText` and Paint text size in this group\'s custom views. Port each size with its ' +
1336
+ 'unit: Android `sp(N)` → Canvas `font` `\'Nvp\'` (or `fp2px(N)` + `px` to follow the font scale); ' +
1337
+ 'a Canvas `px` is a physical pixel (GATE `canvas-font-px-literal`). Geometry is vp by default: ' +
1338
+ '`new CanvasRenderingContext2D(settings)` draws coordinates, `lineWidth` and `measureText` in vp, so ' +
1339
+ 'Android `dp(N)` is plain `N` — never multiply by `vp2px(1)` (GATE `canvas-coord-density-scaled`); ' +
1340
+ 'physical px only via the constructor\'s `LengthMetricsUnit.PX`. There is no `ctx.units` / `CanvasUnit`.',
1341
+ '', ...canvasText, '');
1342
+ }
1343
+ if (idxRows.length) {
1344
+ lines.push('## Mapping-reference sections for the widgets and listeners used here', '',
1345
+ 'The sections of `references/mappings/*.md` whose heading names a widget class or ' +
1346
+ "listener this group's files and captured view trees use. Read them by line range " +
1347
+ '(`offset` = start, `limit` = end - start + 1) in one batched turn instead of paging ' +
1348
+ 'through the whole reference. A widget with no row here has no dedicated section: ' +
1349
+ 'search the reference as before.', '');
1350
+ for (const [[f, a, b, , h], ws] of idxRows) { lines.push(`- \`${f}\` lines ${a}-${b} — ${h} — for ${ws.join(', ')}${mark(`${pKey(f)}#${a}`)}`); }
1351
+ lines.push('');
1352
+ }
1353
+ if (pack.styles.size) {
1354
+ lines.push('## Style definitions', '');
1355
+ for (const s of sortedBy(pack.styles)) {
1356
+ const hit = styles.get(s);
1357
+ lines.push(hit ? `- \`${s}\` → \`${hit[0]}:${hit[1]}\`${mark(`${pKey(hit[0])}#${hit[1]}`)}`
1358
+ : `- \`${s}\` → (not in project values; library/platform style)`);
1359
+ }
1360
+ lines.push('');
1361
+ }
1362
+ if (pack.arrays.size || pack.assets.size) {
1363
+ const arrays = idx.value_defs('(?:string-|integer-)?array');
1364
+ lines.push('## Arrays and assets', '');
1365
+ for (const a of sortedBy(pack.arrays)) {
1366
+ const hit = arrays.get(a);
1367
+ lines.push(hit ? `- array \`${a}\` → \`${hit[0]}:${hit[1]}\`` : `- array \`${a}\` → (not found)`);
1368
+ }
1369
+ for (const a of sortedBy(pack.assets.values(), pathStr)) {
1370
+ lines.push(`- asset \`${a}\` — ${splitlines(_read(a)).length} lines`);
1371
+ }
1372
+ lines.push('');
1373
+ }
1374
+ const refs = sortedBy([...pack.refs.values()].filter((r) => TABLE_TYPES.includes(r[0])));
1375
+ if (refs.length) {
1376
+ lines.push('## Resources referenced by these files → Harmony',
1377
+ '',
1378
+ 'From resource_mapping.md + the Harmony resource files. `exists` = present on disk ' +
1379
+ "now; `ref` goes into `$r('...')`; values shown for base / zh_CN / dark. Rows with " +
1380
+ '`exists`=NO or ref N/A need the resource-fidelity handling of conversion-procedure.md.',
1381
+ '',
1382
+ '| Android | ref | status | exists | value |',
1383
+ '|---|---|---|---|---|');
1384
+ for (const [kind, name] of refs) {
1385
+ const r = hres.row(kind, name);
1386
+ const v = r.value;
1387
+ let vs = v ? Object.entries(v).map(([q, x]) => `${q}=${[...pyStr(x)].slice(0, 60).join('')}`).join('; ') : '';
1388
+ vs = vs.replace(/\|/g, '\\|').replace(/\n/g, ' ');
1389
+ const ex = r.exists === true ? 'yes' : r.exists === false ? 'NO' : '-';
1390
+ lines.push(`| ${kind}/${name} | ${r.ref || 'N/A'} | ${r.status} | ${ex} | ${vs} |`);
1391
+ }
1392
+ lines.push('');
1393
+ }
1394
+ if (inl.lines.length) lines.push(...inl.lines);
1395
+ return lines.join('\n');
1396
+ }
1397
+
1398
+ export function _ctx(hp, android) {
1399
+ const meta = pJoin(hp, '.hometrans');
1400
+ const progress = or(_load(pJoin(meta, 'batch_progress.json'), {}), {});
1401
+ const uiInfo = pathStr(or(dget(progress, 'ui_info_root'), pJoin(meta, 'ui_info')));
1402
+ const module = or(dget(progress, 'ui_module'), 'entry');
1403
+ const plan = dget(or(_load(pJoin(uiInfo, 'conversion_set.json'), {}), {}), 'plan', {});
1404
+ return [uiInfo, dget(plan, 'groups', []), new AndroidIndex(android), new HarmonyRes(hp, module)];
1405
+ }
1406
+
1407
+ export function build(hp, android, out = null, only = null, { inline = true } = {}) {
1408
+ const [uiInfo, groups, idx, hres] = _ctx(hp, android);
1409
+ out = pathStr(or(out, pJoin(hp, '.hometrans', 'work', 'group_packs')));
1410
+ if (isFile(out)) { throw new Error(`FileExistsError: ${out}`); }
1411
+ fs.mkdirSync(out, { recursive: true });
1412
+ const report = new Map();
1413
+ for (const g of pyIter(groups)) {
1414
+ if (only && !only.has(dsub(g, 'id'))) { continue; }
1415
+ const pack = buildGroup(g, uiInfo, idx, hres, android);
1416
+ const text = render(g, pack, idx, hres, android, uiInfo, { inline });
1417
+ const gid = dsub(g, 'id');
1418
+ const file = pJoin(out, `${pyStr(gid)}.md`);
1419
+ fs.writeFileSync(file, IS_WIN ? text.replace(/\n/g, '\r\n') : text, 'utf8');
1420
+ // the same evidence as data: the parent builds REFERENCE_* and runs measure_pack from it
1421
+ fs.writeFileSync(pJoin(out, `${pyStr(gid)}.evidence.json`), JSON.stringify(referenceEvidence(g, uiInfo), null, 1), 'utf8');
1422
+ const k = typeof gid === 'string' ? gid : jsonKey(gid);
1423
+ report.set(k, new Map([['files', pack.files.size], ['resources', pack.refs.size],
1424
+ ['styles', pack.styles.size], ['mapping_sections', text.split(' — for ').length - 1]]));
1425
+ }
1426
+ return new Map([['out', out], ['groups', report]]);
1427
+ }
1428
+
1429
+ export function lookup(hp, android, names) {
1430
+ const hres = new HarmonyRes(hp, or(dget(or(_load(pJoin(hp, '.hometrans', 'batch_progress.json'), {}), {}),
1431
+ 'ui_module'), 'entry'));
1432
+ const rows = [];
1433
+ for (const n of names) {
1434
+ const s = n.replaceAll('R.', '').replaceAll('@', '').replace('.', '/');
1435
+ const i = s.indexOf('/');
1436
+ const [kind, name] = i < 0 ? [s, ''] : [s.slice(0, i), s.slice(i + 1)];
1437
+ rows.push(hres.row(kind, name));
1438
+ }
1439
+ return rows;
1440
+ }
1441
+
1442
+ // ---------------------------------------------------------------- argparse equivalent
1443
+ // Mirrors this CLI's argparse (Python 3.13) behaviour: unique long-option prefixes,
1444
+ // `--opt=value`, `--`, interleaved positionals (mode, harmony_dir, names*),
1445
+ // usage/help layout (width = terminal columns - 2), errors -> usage + exit 2.
1446
+
1447
+ function termColumns() {
1448
+ const env = Number.parseInt(process.env.COLUMNS ?? '', 10);
1449
+ if (env > 0) { return env; }
1450
+ return process.stdout.isTTY && process.stdout.columns ? process.stdout.columns : 80;
1451
+ }
1452
+
1453
+ function usage(prog) {
1454
+ const width = termColumns() - 2;
1455
+ const opt = ['[-h]', '--android ANDROID', '[--groups GROUPS]', '[--out OUT]'];
1456
+ const pos = ['{build,lookup}', 'harmony_dir', '[names ...]'];
1457
+ const full = [prog, ...opt, ...pos].join(' ');
1458
+ if ('usage: '.length + full.length <= width) { return 'usage: ' + full; }
1459
+ const getLines = (parts, indent, prefix) => {
1460
+ const lines = [];
1461
+ let line = [];
1462
+ let len = prefix !== undefined ? prefix.length - 1 : indent.length - 1;
1463
+ for (const part of parts) {
1464
+ if (len + 1 + part.length > width && line.length) {
1465
+ lines.push(indent + line.join(' '));
1466
+ line = [];
1467
+ len = indent.length - 1;
1468
+ }
1469
+ line.push(part);
1470
+ len += part.length + 1;
1471
+ }
1472
+ if (line.length) { lines.push(indent + line.join(' ')); }
1473
+ if (prefix !== undefined) { lines[0] = lines[0].slice(indent.length); }
1474
+ return lines;
1475
+ };
1476
+ let lines;
1477
+ if ('usage: '.length + prog.length <= 0.75 * width) {
1478
+ const indent = ' '.repeat('usage: '.length + prog.length + 1);
1479
+ lines = getLines([prog, ...opt], indent, prog);
1480
+ if (pos.length) { lines.push(...getLines(pos, indent)); }
1481
+ } else {
1482
+ const indent = ' '.repeat('usage: '.length);
1483
+ lines = getLines([...opt, ...pos], indent);
1484
+ if (lines.length > 1) { lines = [...getLines(opt, indent), ...getLines(pos, indent)]; }
1485
+ lines = [prog, ...lines];
1486
+ }
1487
+ return 'usage: ' + lines.join('\n');
1488
+ }
1489
+
1490
+ function helpText(prog) {
1491
+ const rows = [
1492
+ ['{build,lookup}', null], ['harmony_dir', null], ['names', 'lookup: type/name ... (e.g. string/foo R.color.bar)'],
1493
+ ];
1494
+ const opts = [['-h, --help', 'show this help message and exit'], ['--android ANDROID', 'android_project_dir'],
1495
+ ['--groups GROUPS', 'build: comma-separated ids (default: all)'],
1496
+ ['--out OUT', 'build: output dir (default .hometrans/work/group_packs)']];
1497
+ const width = termColumns() - 2;
1498
+ const maxPos = Math.min(24, Math.max(width - 20, 4));
1499
+ const longest = Math.max(...[...rows, ...opts].map(([inv]) => inv.length + 2));
1500
+ const helpPos = Math.min(longest + 2, maxPos);
1501
+ const item = ([inv, help]) => {
1502
+ if (!help) { return [' ' + inv]; }
1503
+ if (inv.length + 2 <= helpPos - 2) { return [' ' + inv.padEnd(helpPos - 4) + ' ' + help]; }
1504
+ return [' ' + inv, ' '.repeat(helpPos) + help];
1505
+ };
1506
+ return [usage(prog), '', DOC.trimEnd(), '', 'positional arguments:', ...rows.flatMap(item), '',
1507
+ 'options:', ...opts.flatMap(item)].join('\n') + '\n';
1508
+ }
1509
+
1510
+ function parseArgs(argv, prog) {
1511
+ const fail = (msg) => {
1512
+ process.stderr.write((usage(prog) + '\n' + `${prog}: error: ${msg}\n`).replace(/\n/g, EOL));
1513
+ process.exit(2);
1514
+ };
1515
+ const LONG = ['--help', '--android', '--groups', '--out'];
1516
+ // classify: 'O' option, 'A' argument; the first '--' ends options and is dropped
1517
+ const kinds = [];
1518
+ const args = [];
1519
+ let rest = false;
1520
+ for (const s of argv) {
1521
+ if (!rest && s === '--') { rest = true; continue; }
1522
+ let k = 'A';
1523
+ if (!rest && s.startsWith('-') && s !== '-') {
1524
+ if (/^-\d+$|^-\d*\.\d+$/.test(s)) { k = 'A'; }
1525
+ else if (s.includes(' ') && !LONG.includes(s.split('=')[0]) && s.split('=')[0] !== '-h') { k = 'A'; }
1526
+ else { k = 'O'; }
1527
+ }
1528
+ kinds.push(k);
1529
+ args.push(s);
1530
+ }
1531
+ const res = { mode: null, harmony_dir: null, names: null, android: null, groups: '', out: null };
1532
+ const seen = new Set();
1533
+ const extras = [];
1534
+ const posActs = ['mode', 'harmony_dir', 'names'];
1535
+ let pi = 0; // next positional action
1536
+ const take = (act, vals) => {
1537
+ if (act === 'mode') {
1538
+ if (!['build', 'lookup'].includes(vals[0])) {
1539
+ fail(`argument mode: invalid choice: ${pyRepr(vals[0])} (choose from build, lookup)`);
1540
+ }
1541
+ res.mode = vals[0];
1542
+ } else if (act === 'harmony_dir') { res.harmony_dir = vals[0]; }
1543
+ else { res.names = vals; }
1544
+ seen.add(act);
1545
+ };
1546
+ // consume a run of 'A' args with the remaining positionals (greedy, names = '*')
1547
+ const consumePos = (start, end, more) => {
1548
+ let n = end - start;
1549
+ let i = start;
1550
+ const need = posActs.slice(pi);
1551
+ // how many fixed (exactly-one) actions can be satisfied
1552
+ const fixed = need.filter((a) => a !== 'names');
1553
+ let use = Math.min(n, fixed.length);
1554
+ for (let k = 0; k < use; k++) { take(fixed[k], [args[i]]); i++; pi++; }
1555
+ if (pi === 2 && use === fixed.length) {
1556
+ const left = end - i;
1557
+ if (left > 0 || !more) { take('names', args.slice(i, end)); i = end; pi++; }
1558
+ }
1559
+ return i;
1560
+ };
1561
+ let i = 0;
1562
+ while (i < args.length) {
1563
+ if (kinds[i] === 'A') {
1564
+ let j = i;
1565
+ while (j < args.length && kinds[j] === 'A') { j++; }
1566
+ const stop = consumePos(i, j, j < args.length);
1567
+ extras.push(...args.slice(stop, j));
1568
+ i = j;
1569
+ continue;
1570
+ }
1571
+ const s = args[i];
1572
+ const eq = s.startsWith('--') ? s.indexOf('=') : -1;
1573
+ const key = eq >= 0 ? s.slice(0, eq) : s;
1574
+ let opt = null;
1575
+ let explicit = eq >= 0 ? s.slice(eq + 1) : null;
1576
+ if (key === '-h' || LONG.includes(key)) { opt = key === '-h' ? '--help' : key; }
1577
+ else if (key.startsWith('--')) {
1578
+ const hits = LONG.filter((o) => o.startsWith(key));
1579
+ if (hits.length === 1) { opt = hits[0]; }
1580
+ } else if (s.startsWith('-h') && !s.startsWith('--')) {
1581
+ opt = '--help';
1582
+ explicit = s.slice(2);
1583
+ }
1584
+ if (!opt) { extras.push(s); i++; continue; }
1585
+ if (opt === '--help') {
1586
+ if (explicit !== null && explicit !== '') {
1587
+ fail(`argument -h/--help: ignored explicit argument ${pyRepr(explicit.replace(/^=/, ''))}`);
1588
+ }
1589
+ process.stdout.write(helpText(prog).replace(/\n/g, EOL));
1590
+ process.exit(0);
1591
+ }
1592
+ const dest = opt.slice(2);
1593
+ if (explicit !== null) { res[dest] = explicit; i++; }
1594
+ else if (i + 1 < args.length && kinds[i + 1] === 'A') { res[dest] = args[i + 1]; i += 2; }
1595
+ else { fail(`argument ${opt}: expected one argument`); }
1596
+ seen.add(dest);
1597
+ }
1598
+ if (pi === 2) { take('names', []); pi++; }
1599
+ const missing = [];
1600
+ if (!seen.has('mode')) { missing.push('mode'); }
1601
+ if (!seen.has('harmony_dir')) { missing.push('harmony_dir'); }
1602
+ if (!seen.has('android')) { missing.push('--android'); }
1603
+ if (missing.length) { fail(`the following arguments are required: ${missing.join(', ')}`); }
1604
+ if (extras.length) { fail(`unrecognized arguments: ${extras.join(' ')}`); }
1605
+ if (res.names === null) { res.names = []; }
1606
+ return res;
1607
+ }
1608
+
1609
+ export function main(argv = process.argv.slice(2)) {
1610
+ const prog = path.basename(process.argv[1] || 'group_pack.mjs');
1611
+ const a = parseArgs(argv, prog);
1612
+ let res;
1613
+ if (a.mode === 'build') {
1614
+ const only = new Set(a.groups.split(',').map(pyStrip).filter((g) => g));
1615
+ // inlining is on unless GROUP_PACK_INLINE=0 (a host whose read tool truncates large files)
1616
+ res = build(a.harmony_dir, a.android, a.out, only.size ? only : null,
1617
+ { inline: process.env.GROUP_PACK_INLINE !== '0' });
1618
+ } else {
1619
+ res = lookup(a.harmony_dir, a.android, a.names);
1620
+ }
1621
+ process.stdout.write((pyJsonDumps(res, 1) + '\n').replace(/\n/g, EOL));
1622
+ return 0;
1623
+ }
1624
+
1625
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
1626
+ process.exitCode = main();
1627
+ }