@harmonyos-arkts/d2h 0.1.34 → 0.1.36

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 (61) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/android-to-hmos-00-orchestrator.md +1 -1
  3. package/agents/d2h.md +5 -4
  4. package/assets/agc-apiclient.json +10 -0
  5. package/dist/bin/install-opencode.js +6 -1
  6. package/dist/src/metrics-plugin.js +36 -1
  7. package/package.json +2 -1
  8. package/schemas/code-stats.schema.json +2 -2
  9. package/skills/d2h-code-audit/SKILL.md +17 -6
  10. package/skills/d2h-code-audit/references/code-stats-schema.md +64 -2
  11. package/skills/d2h-code-audit/scripts/code_stats.py +1 -1
  12. package/skills/d2h-code-audit/scripts/increment_delta.py +299 -0
  13. package/skills/d2h-dashboard/app/assets/{Analysis-Dj-4QEJi.js → Analysis-S3iFh2nP.js} +1 -1
  14. package/skills/d2h-dashboard/app/assets/CodeAudit-BI5iNy2f.css +1 -0
  15. package/skills/d2h-dashboard/app/assets/CodeAudit-BeZMoO_s.js +1 -0
  16. package/skills/d2h-dashboard/app/assets/{FeaturesList-C5yGUbRo.js → FeaturesList-CdKAoNw5.js} +1 -1
  17. package/skills/d2h-dashboard/app/assets/{Overview-CNkA3J9F.js → Overview-C43KVHdP.js} +1 -1
  18. package/skills/d2h-dashboard/app/assets/Overview-CzysQJHh.css +1 -0
  19. package/skills/d2h-dashboard/app/assets/{Project-BC9Tz1WY.js → Project-D5loWYjZ.js} +1 -1
  20. package/skills/d2h-dashboard/app/assets/{SpecDetail-DguVmqAE.js → SpecDetail-XCDyawZ3.js} +1 -1
  21. package/skills/d2h-dashboard/app/assets/{SpecItemDetail-7s7SaF3O.js → SpecItemDetail-BDl_Qqfx.js} +2 -2
  22. package/skills/d2h-dashboard/app/assets/datetime-DBOJn2GA.js +1 -0
  23. package/skills/d2h-dashboard/app/assets/{index-B3nfIPBm.js → index-C1bO3C02.js} +2 -2
  24. package/skills/d2h-dashboard/app/assets/{navigation-d1Uf6TR4.js → navigation-BGPexEv8.js} +1 -1
  25. package/skills/d2h-dashboard/app/index.html +1 -1
  26. package/skills/d2h-spec-generate/SKILL.md +17 -11
  27. package/skills/language/h5/d2h-h5-analyse/SKILL.md +34 -0
  28. package/skills/language/h5/d2h-h5-analyse/references/scenarios.md +36 -0
  29. package/skills/language/h5/d2h-h5-coding/SKILL.md +33 -0
  30. package/skills/language/h5/d2h-h5-coding/references/bridge-contracts.md +44 -0
  31. package/skills/language/h5/d2h-h5-coding/references/examples.md +28 -0
  32. package/skills/language/h5/d2h-h5-coding/references/scenarios.md +40 -0
  33. package/skills/language/h5/d2h-h5-coding/references/webview-implementation.md +144 -0
  34. package/skills/language/h5/d2h-webview-analyse/SKILL.md +309 -0
  35. package/skills/language/h5/d2h-webview-analyse/scripts/analyse_android_webview.py +3625 -0
  36. package/skills/language/h5/d2h-webview-jsbridge/SKILL.md +140 -0
  37. package/skills/language/h5/d2h-webview-jsbridge/references/adaptation.md +235 -0
  38. package/skills/language/h5/d2h-webview-jsbridge/references/containers-and-triage.md +30 -0
  39. package/skills/language/h5/d2h-webview-jsbridge/references/detection-rules.md +69 -0
  40. package/skills/language/h5/d2h-webview-jsbridge/references/report-system.md +69 -0
  41. package/skills/language/h5/d2h-webview-jsbridge/scripts/scan_web_jsbridge.py +2080 -0
  42. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/build.gradle +3 -0
  43. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/src/main/assets/dsbridge.js +6 -0
  44. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/src/main/java/demo/DsActivity.java +19 -0
  45. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/empty-app/app/src/main/kotlin/demo/Screen.kt +5 -0
  46. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/build.gradle +3 -0
  47. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/assets/www/WebViewJavascriptBridge.js +6 -0
  48. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/assets/www/index.html +6 -0
  49. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/java/demo/WebActivity.java +79 -0
  50. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/assets/WebViewJavascriptBridge.js +4 -0
  51. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/assets/page.html +2 -0
  52. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/kotlin/demo/Bridge.kt +23 -0
  53. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/kotlin/demo/WVJBWebView.kt +27 -0
  54. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/xml-app/app/src/main/java/demo/MainActivity.java +8 -0
  55. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/xml-app/app/src/main/res/layout/main.xml +9 -0
  56. package/skills/language/h5/d2h-webview-jsbridge/tests/run_tests.py +237 -0
  57. package/skills/preparing-migration-workspace/SKILL.md +0 -1
  58. package/skills/d2h-dashboard/app/assets/CodeAudit-Ctt3XEec.css +0 -1
  59. package/skills/d2h-dashboard/app/assets/CodeAudit-TcIcLwQL.js +0 -1
  60. package/skills/d2h-dashboard/app/assets/Overview-Cmz8yjX-.css +0 -1
  61. package/skills/d2h-dashboard/app/assets/datetime-CHrzCsjX.js +0 -1
@@ -0,0 +1,2080 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Android Web 容器 & JSBridge 静态扫描器(d2h-webview-jsbridge · Phase 1,自足运行)
4
+
5
+ 只读扫描 Android 工程,识别:
6
+ 1. Web 容器:系统 WebView(android.webkit) / 腾讯 X5(TBS) / Crosswalk / GeckoView / AgentWeb / VasSonic
7
+ 2. JSBridge 机制:原生 addJavascriptInterface / WebMessagePort / URL scheme 拦截 / evaluateJavascript,
8
+ 三方 lzyzsd JsBridge / DSBridge / AgentWeb 封装
9
+ 3. 桥接方法清单:@JavascriptInterface 方法与注入命名空间、registerHandler/callHandler、
10
+ DSBridge addJavascriptObject、自定义 scheme
11
+ 4. WebSettings / 安全基线、assets 中 H5 桥脚本
12
+ 5. ohpm 鸿蒙替代库候选(内置实证映射;--search-ohpm 在线刷新)
13
+
14
+ 用法:
15
+ python3 scan_web_jsbridge.py <Android工程目录> [--output <目录>] [--stdout-json]
16
+ python3 scan_web_jsbridge.py --search-ohpm <关键词> # 在线查 ohpm 鸿蒙替代库(需网络)
17
+
18
+ 输出(默认 <Android工程同级>/<工程名>-h5-report/<工程名小写>-scan/):
19
+ web-jsbridge-report.json 机器可读(供 AI 做 ArkTS 映射,含 ohpm_candidates)
20
+ web-jsbridge-report.md 人读报告
21
+ web-jsbridge-report.html H5 报告(自包含单文件)
22
+ bridge-test.html 桥接回路自测页
23
+
24
+ 复核结论(人工/AI 复核证据后写)放 <工程名>-h5-report/ 根目录:
25
+ <工程名小写>-conclusion.json / <工程名小写>-conclusion.html(结构见 SKILL.md §2.5)
26
+
27
+ 约束:正则启发式分析,混淆代码、反射注册(无字面量命名空间)会漏报;
28
+ 每条结论均带 file:line 证据,使用前必须人工复核。
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import datetime
34
+ import html as _html
35
+ import json
36
+ import os
37
+ import re
38
+ import sys
39
+ from pathlib import Path
40
+
41
+ SKIP_DIRS = {".git", ".gradle", ".idea", ".hvigor", ".hg", ".svn", "build", "node_modules", "oh_modules"}
42
+ # Kotlin Multiplatform 非 Android 源集(desktop/ios/js/native 等):与鸿蒙迁移无关,跳过避免噪声
43
+ NON_ANDROID_SOURCE_SET = re.compile(
44
+ r"^(?:desktop\w*|ios\w*|js|wasmJs\w*|wasmWasi\w*|native\w*|macos\w*|linux\w*|mingw\w*|"
45
+ r"watchos\w*|tvos\w*|jvm)(?:Main|Test)$")
46
+ SRC_EXTS = {".java", ".kt"}
47
+ MAX_SRC_FILES = 20000
48
+ MAX_FILE_BYTES = 4 * 1024 * 1024
49
+ MAX_H5_FILES = 3000
50
+
51
+ # ---------------------------------------------------------------- 特征库
52
+
53
+ CONTAINERS = [
54
+ dict(
55
+ key="system_webview", label="系统 WebView (android.webkit)",
56
+ gradle=[], imports=["android.webkit.WebView", "android.webkit.WebSettings",
57
+ "android.webkit.WebViewClient", "android.webkit.WebChromeClient"],
58
+ symbols=[r"\bnew\s+WebView\s*\(", r"\bextends\s+WebView\b", r"\(\s*WebView\s+\w+\s*\)"],
59
+ hint="ArkUI Web({src, controller}) + webview.WebviewController;src 支持 https:// 与 $rawfile 本地页",
60
+ ),
61
+ dict(
62
+ key="androidx_webkit", label="AndroidX WebKit 兼容层(内核仍为系统 WebView)",
63
+ gradle=["androidx.webkit"], imports=["androidx.webkit"],
64
+ symbols=[], hint="内核同系统 WebView,WebMessage* 相关能力用 ArkWeb WebMessagePort 对应",
65
+ ),
66
+ dict(
67
+ key="tencent_x5", label="腾讯 X5 / TBS WebView(三方内核)",
68
+ gradle=["com.tencent.tbs", "tbssdk", "com.tencent.smtt"],
69
+ imports=["com.tencent.smtt.sdk"],
70
+ symbols=[r"\bQbSdk\b", r"X5WebView", r"com\.tencent\.smtt"],
71
+ hint="鸿蒙无 X5,直接回落 ArkWeb 内核;TBS 播放器/下载用 @ohos.multimedia.media、@ohos.request 重建,QbSdk 预加载等专有 API 逐项核对",
72
+ ),
73
+ dict(
74
+ key="crosswalk", label="Crosswalk(已停维三方内核)",
75
+ gradle=["org.xwalk"], imports=["org.xwalk.core"],
76
+ symbols=[r"XWalkView"],
77
+ hint="无鸿蒙版,功能面回落 ArkWeb;XWalk 专有接口逐项列差集",
78
+ ),
79
+ dict(
80
+ key="geckoview", label="Mozilla GeckoView(Gecko 内核)",
81
+ gradle=["geckoview"], imports=["org.mozilla.geckoview"],
82
+ symbols=[r"\bGeckoView\b", r"\bGeckoSession\b"],
83
+ hint="无鸿蒙版,功能面回落 ArkWeb",
84
+ ),
85
+ dict(
86
+ key="agentweb", label="AgentWeb 容器框架(默认系统内核,可切 X5)",
87
+ gradle=["agentweb", "io.github.justson", "com.justson"],
88
+ imports=["com.justson.agentweb", "io.github.justson.agentweb"],
89
+ symbols=[r"\bAgentWeb\b"],
90
+ hint="AgentWeb 是容器框架而非内核:按其 Builder 链路(JS 安全、文件选择、权限)在 ArkWeb 事件里重建;ohpm 无 AgentWeb 同类容器(检索 0 结果),回落 ArkWeb",
91
+ ),
92
+ dict(
93
+ key="vassonic", label="腾讯 VasSonic 首屏加速框架(非容器/非桥)",
94
+ gradle=["com.tencent.sonic", "sonic-sdk"], imports=["com.tencent.sonic"],
95
+ symbols=[r"SonicSession", r"SonicEngine"],
96
+ hint="ArkWeb 无对应框架;首屏加速可用本地缓存 + onInterceptRequest 资源应答模拟,评估是否保留",
97
+ ),
98
+ ]
99
+
100
+ BRIDGES = [
101
+ dict(
102
+ key="native_addJavascriptInterface", label="原生 addJavascriptInterface 注入(JS→Native)",
103
+ kind="native", gradle=[], imports=[],
104
+ symbols=[r"\.addJavascriptInterface\s*\(", r"@JavascriptInterface"],
105
+ hint="Web().javaScriptProxy({object, name(=注入名), methodList/syncMethodList, controller});命名空间与 Android 一致可 H5 零改动;动态注册用 controller.registerJavaScriptProxy()+refresh()",
106
+ ),
107
+ dict(
108
+ key="native_webmessage", label="原生 WebMessagePort 通道(双向端口)",
109
+ kind="native", gradle=["androidx.webkit"], imports=["androidx.webkit"],
110
+ symbols=[r"\bWebMessagePort\b", r"createWebMessageChannel", r"postWebMessage", r"WebMessageCompat", r"\bWebMessage\b"],
111
+ hint="controller.createWebMessagePorts() + postMessage 移交端口,port.postMessageEvent/onMessageEvent 双工",
112
+ ),
113
+ dict(
114
+ key="url_scheme", label="URL scheme 拦截桥(shouldOverrideUrlLoading)",
115
+ kind="native", gradle=[], imports=[],
116
+ symbols=[r"shouldOverrideUrlLoading"],
117
+ hint="用 Web().onInterceptRequest 拦截自定义 scheme 请求解析分发,结果 setResponseData 应答或 runJavaScript 回推 H5",
118
+ ),
119
+ dict(
120
+ key="native_evaluate", label="原生 evaluateJavascript(Native→JS)",
121
+ kind="native", gradle=[], imports=[],
122
+ symbols=[r"\.evaluateJavascript\s*\(", r"\.loadUrl\s*\(\s*[\"]javascript:"],
123
+ hint="controller.runJavaScript()(回调取返回值)/ runJavaScriptExt()(取错误与退出原因)",
124
+ ),
125
+ dict(
126
+ key="lzyzsd_jsbridge", label="三方 lzyzsd/JsBridge(BridgeWebView + WebViewJavascriptBridge.js)",
127
+ kind="third_party", gradle=["lzyzsd"],
128
+ imports=["com.github.lzyzsd.jsbridge"],
129
+ symbols=[r"\bBridgeWebView\b", r"\bBridgeHandler\b"],
130
+ hint="容器仍是系统 WebView。候选协议兼容库:@a_zwj/netweb(README 声明对应 lzyzsd,弱维护需实测)、"
131
+ "@yue/webview_javascript_bridge(iOS 系 WVJB 协议,Android 风格 setup 需验证);"
132
+ "不满足则 javaScriptOnDocumentStart 注入 WebViewJavascriptBridge 兼容 shim 转发到 javaScriptProxy;H5 可改时统一收敛到 javaScriptProxy",
133
+ ),
134
+ dict(
135
+ key="wendux_wvjb", label="三方 wendux/WebViewJavascriptBridge(DSBridge 前身,WVJB 风格 API)",
136
+ kind="third_party", gradle=[], imports=[],
137
+ symbols=[r"\bWVJBWebView\b", r"\bWVJBHandler\b", r"\bWVJBResponseCallback\b", r"_handleMessageFromJava"],
138
+ hint="DSBridge 前身。传输层是单个 @JavascriptInterface 方法 notice(String)(注入名 WVJBInterface)→ "
139
+ "ArkWeb 直接 javaScriptProxy({name:'WVJBInterface', methodList:['notice']}) + "
140
+ "runJavaScript('WebViewJavascriptBridge._handleMessageFromJava(...)') 回推,"
141
+ "document-start 注入原版 WebViewJavascriptBridge.js → **H5 零改动、无需重写协议**"
142
+ "(与 lzyzsd 的 iframe 队列不同);原生分发逻辑按工程内 JS 的消息契约实现",
143
+ ),
144
+ dict(
145
+ key="dsbridge", label="三方 DSBridge(wendux,DWebView + dsbridge.js)",
146
+ kind="third_party", gradle=["dsbridge", "DSBridge"],
147
+ imports=["wendu.dsbridge"],
148
+ symbols=[r"\bDWebView\b", r"\.addJavascriptObject\s*\(", r"\.hasJavascriptMethod\s*\(", r"\bdsbridge\b"],
149
+ hint="容器仍是系统 WebView。优先用协议兼容库 @hzw/ohos-dsbridge(兼容 DSBridge 2.0/3.0 JS,H5 基本零改动);"
150
+ "其次 javaScriptOnDocumentStart 注入 dsbridge 兼容 shim 转发到 javaScriptProxy;H5 可改时收敛官方桥",
151
+ ),
152
+ dict(
153
+ key="agentweb_jsinterface", label="AgentWeb JsInterface 封装(底层仍是 addJavascriptInterface)",
154
+ kind="third_party", gradle=[], imports=[],
155
+ symbols=[r"\.addJavaObject\s*\(", r"JsInterfaceHolder", r"AgentWebJsInterface"],
156
+ hint="按 addJavascriptInterface 处理:javaScriptProxy 对齐命名空间与方法清单即可",
157
+ ),
158
+ ]
159
+
160
+ # ohpm 鸿蒙替代库知识库(2026-10 实证核验:下载 .har 解包读 README;用 --search-ohpm 刷新版本/维护度)
161
+ # h5_impact: zero_change=H5 零改动 / verify=需实测协议对齐 / h5_must_change=H5 必须改
162
+ OHPM_REPLACEMENTS = {
163
+ "dsbridge": [
164
+ {"name": "@hzw/ohos-dsbridge", "h5_impact": "zero_change", "license": "Apache-2.0",
165
+ "note": "协议级兼容 DSBridge 2.0/3.0 JS 脚本;@JavaScriptInterface 装饰器、同步/异步、命名空间、"
166
+ "进度回调(一次调用多次返回);已入华为鸿蒙生态组件专区,维护活跃 → 首选"},
167
+ {"name": "@jiaxing/ohos-adaptationdsbridge", "h5_impact": "verify", "license": "Apache-2.0",
168
+ "note": "DSBridge 适配,2024 起弱维护,需实测"},
169
+ ],
170
+ "lzyzsd_jsbridge": [
171
+ {"name": "@a_zwj/netweb", "h5_impact": "verify", "license": "Apache-2.0",
172
+ "note": "README 明确标注 android 版为 github.com/lzyzsd/JsBridge,callHandler/doSend/callJSHandler "
173
+ "命名与 lzyzsd 一致;弱维护,回调链需实测。⚠️ 若工程为增强 fork"
174
+ "(persistentCallbacks/origin 校验等扩展)则不覆盖,优先自写 shim"},
175
+ {"name": "@yue/webview_javascript_bridge", "h5_impact": "verify", "license": "Apache-2.0",
176
+ "note": "实现的是 marcuswestin iOS 系 WVJB 协议;H5 若是 iOS 风格 setup(WVJBCallbacks) 基本零改动,"
177
+ "若是 lzyzsd Android 风格(等 WebViewJavascriptBridgeReady 事件 + yy://__queue_message__/) 需验证/小改"},
178
+ {"name": "@jjr/wvjb", "h5_impact": "verify", "license": "Apache-2.0",
179
+ "note": "WVJB 协议实现(@yue 同类),需验证协议细节"},
180
+ ],
181
+ "wendux_wvjb": [
182
+ {"name": "@hzw/ohos-dsbridge", "h5_impact": "verify", "license": "Apache-2.0",
183
+ "note": "DSBridge 前身与 DSBridge 同作者同族协议演进;@hzw 兼容 DSBridge 2.0/3.0 JS,"
184
+ "wendux WVJB 的 H5 协议细节需按工程内 WebViewJavascriptBridge.js 实测比对"},
185
+ {"name": "@yue/webview_javascript_bridge", "h5_impact": "verify", "license": "Apache-2.0",
186
+ "note": "H5 初始化为 WVJBCallbacks(iOS 风格),与本工程风格一致;但 wendux 传输层是 "
187
+ "WVJBInterface.notice 单方法而非 iframe scheme,需实测消息通道是否可对齐"},
188
+ ],
189
+ }
190
+ # 通用备选:非 Android 桥协议的鸿蒙自有桥框架,仅在 H5 可改造时考虑
191
+ OHPM_GENERIC_FALLBACK = [
192
+ {"name": "@ncc/jsbridge", "h5_impact": "h5_must_change", "license": "Apache-2.0",
193
+ "note": "自有协议(jsbridge.call/post),与 DSBridge/JsBridge 协议无关,2023 停更"},
194
+ {"name": "@ilye/web-bridge-adapter", "h5_impact": "h5_must_change", "license": "MIT",
195
+ "note": "自有事件分发框架(API13+,Plugin/callback/Promise),活跃但 H5 必须改;"
196
+ "H5 愿改时不如直接收敛官方 javaScriptProxy"},
197
+ ]
198
+
199
+ OHPM_SEARCH_URL = ("https://ohpm.openharmony.cn/ohpmweb/registry/oh-package/openapi/v1/search"
200
+ "?condition={kw}&pageNum=1&pageSize={size}&sortedType=popularity&isHomePage=false&publisherId=")
201
+
202
+ # 常见三方 App 外跳 scheme(非桥协议,shouldOverrideUrlLoading 内拉起外部应用)
203
+ EXTERNAL_JUMP_SCHEMES = {"weixin", "weixinurl", "alipay", "alipays", "mqq", "weibo", "snssdk",
204
+ "tmall", "tbopen", "jd", "vipshop", "kaola", "mttbrowser", "pinduoduo"}
205
+
206
+ # WebSettings:同时匹配 Java setter 风格与 Kotlin 属性赋值风格(真实工程实证:ImmichFrame 属性式全漏)
207
+ SETTINGS_FLAGS = [
208
+ ("setJavaScriptEnabled", [r"\.setJavaScriptEnabled\s*\(\s*(true|false)\s*\)", r"\.javaScriptEnabled\s*=\s*(true|false)", r"(?:^|[\s{;])javaScriptEnabled\s*=\s*(true|false)"], "value"),
209
+ ("setDomStorageEnabled", [r"\.setDomStorageEnabled\s*\(\s*(true|false)\s*\)", r"\.domStorageEnabled\s*=\s*(true|false)", r"(?:^|[\s{;])domStorageEnabled\s*=\s*(true|false)"], "value"),
210
+ ("setAllowFileAccess", [r"\.setAllowFileAccess\s*\(\s*(true|false)\s*\)", r"\.allowFileAccess\s*=\s*(true|false)", r"(?:^|[\s{;])allowFileAccess\s*=\s*(true|false)"], "value"),
211
+ ("setAllowFileAccessFromFileURLs", [r"\.setAllowFileAccessFromFileURLs\s*\(\s*(true|false)\s*\)", r"\.allowFileAccessFromFileURLs\s*=\s*(true|false)", r"(?:^|[\s{;])allowFileAccessFromFileURLs\s*=\s*(true|false)"], "value"),
212
+ ("setAllowUniversalAccessFromFileURLs", [r"\.setAllowUniversalAccessFromFileURLs\s*\(\s*(true|false)\s*\)", r"\.allowUniversalAccessFromFileURLs\s*=\s*(true|false)", r"(?:^|[\s{;])allowUniversalAccessFromFileURLs\s*=\s*(true|false)"], "value"),
213
+ ("setCacheMode", [r"\.setCacheMode\s*\(\s*([\w.]+)\s*\)", r"\.cacheMode\s*=\s*([\w.]+)", r"(?:^|[\s{;])cacheMode\s*=\s*([\w.]+)"], "value"),
214
+ ("setMixedContentMode", [r"\.setMixedContentMode\s*\(\s*([\w.]+)\s*\)", r"\.mixedContentMode\s*=\s*([\w.]+)", r"(?:^|[\s{;])mixedContentMode\s*=\s*([\w.]+)"], "value"),
215
+ ("setSavePassword", [r"\.setSavePassword\s*\(\s*(true|false)\s*\)", r"\.savePassword\s*=\s*(true|false)"], "value"),
216
+ ("setGeolocationEnabled", [r"\.setGeolocationEnabled\s*\(\s*(true|false)\s*\)", r"\.geolocationEnabled\s*=\s*(true|false)"], "value"),
217
+ ("setUserAgentString", [r"\.setUserAgentString\s*\(\s*([^\n;]{0,120})", r"\.userAgentString\s*=\s*[\"']?([^\n;\"']{0,120})", r"(?:^|[\s{;])userAgentString\s*=\s*[\"']?([^\n;\"']{0,120})"], "value"),
218
+ ("setSupportMultipleWindows", [r"\.setSupportMultipleWindows\s*\(\s*(true|false)\s*\)", r"\.supportMultipleWindows\s*=\s*(true|false)"], "value"),
219
+ ("setMediaPlaybackRequiresUserGesture", [r"\.setMediaPlaybackRequiresUserGesture\s*\(\s*(true|false)\s*\)", r"\.mediaPlaybackRequiresUserGesture\s*=\s*(true|false)"], "value"),
220
+ ("onReceivedSslError", [r"onReceivedSslError\s*\("], "ssl"),
221
+ ("setAcceptThirdPartyCookies", [r"\.setAcceptThirdPartyCookies\s*\(\s*(true|false)\s*\)",
222
+ r"\.acceptThirdPartyCookies\s*=\s*(true|false)"], "value"),
223
+ ("setAcceptCookie", [r"\.setAcceptCookie\s*\(\s*(true|false)\s*\)"], "value"),
224
+ ("自定义请求头", [r"\.loadUrl\s*\([^,\n]+,\s*(?:new\s+)?(?:[\w.]*[Hh]eaders|HashMap|ArrayMap)"], "flag"),
225
+ ]
226
+
227
+ COMMON_SCHEMES = {"http", "https", "about", "data", "blob", "javascript", "file", "intent",
228
+ "tel", "mailto", "geo", "market", "content", "ws", "wss", "ftp", "chrome"}
229
+
230
+ # 容器能力(ChromeClient / 资源拦截 / document-start / 生命周期 / Cookie / 调试)→ ArkWeb 映射提示
231
+ CHROME_FEATURES = [
232
+ ("onShowFileChooser", r"\bonShowFileChooser\s*\(",
233
+ "文件选择 → ArkWeb .onShowFileSelector()"),
234
+ ("onPermissionRequest", r"\bonPermissionRequest\s*\(",
235
+ "摄像头/麦克风权限 → ArkWeb .onPermissionRequest(),需配合应用权限申请"),
236
+ ("onGeolocationPermissionsShowPrompt", r"\bonGeolocationPermissionsShowPrompt\s*\(",
237
+ "定位 → ArkWeb .onGeolocationShow()"),
238
+ ("onCreateWindow", r"\bonCreateWindow\s*\(",
239
+ "多窗口 → .multiWindowAccess(true) + .onWindowNew()"),
240
+ ("onJsAlert", r"\bonJsAlert\s*\(",
241
+ "JS 弹窗 → .onAlert()"),
242
+ ("onJsConfirm", r"\bonJsConfirm\s*\(",
243
+ "JS 确认框 → .onConfirm()"),
244
+ ("onJsPrompt", r"\bonJsPrompt\s*\(",
245
+ "JS 输入框 → .onPrompt();⚠️ 部分桥(DSBridge 旧版)用 prompt() 做通道,需在 onPrompt 内应答桥协议"),
246
+ ("onDownloadStart", r"\bonDownloadStart\s*\(",
247
+ "下载 → @ohos.request 或 H5 直链"),
248
+ ("onShowCustomView", r"\bonShowCustomView\s*\(",
249
+ "视频全屏进入 → ArkWeb .onFullScreenEnter()(API 11+)或 video 组件/XComponent 全屏;X5 IX5WebChromeClient.CustomViewCallback 无对应"),
250
+ ("onHideCustomView", r"\bonHideCustomView\s*\(",
251
+ "视频全屏退出 → ArkWeb .onFullScreenExit()"),
252
+ ("QbSdk.initX5Environment", r"initX5Environment|initTbsSettings|getTbsVersion",
253
+ "X5 初始化/预加载/版本探测 → ArkWeb 无对应(删除);内核能力由 ArkWeb 提供,播放用 @ohos.multimedia.media(AVPlayer 支持 HLS)"),
254
+ ("CookieManager", r"CookieManager\s*\.\s*getInstance|\.setCookie\s*\(",
255
+ "Cookie → webview.WebCookieManager(configCookie/fetchCookieSync)"),
256
+ ("setWebContentsDebuggingEnabled", r"setWebContentsDebuggingEnabled\s*\(",
257
+ "调试 → webview.WebviewController.setWebDebuggingAccess(true)"),
258
+ ("shouldInterceptRequest", r"shouldInterceptRequest\s*\(",
259
+ "资源拦截(离线包/本地缓存/自定义应答)→ ArkWeb .onInterceptRequest()(异步应答:handleInterceptRequest 放行)"),
260
+ ("WebViewAssetLoader", r"WebViewAssetLoader",
261
+ "AndroidX 本地资源加载器(appassets.androidplatform.net)→ ArkWeb $rawfile 或 onInterceptRequest 资源应答"),
262
+ ("addDocumentStartJavaScript", r"addDocumentStartJavaScript",
263
+ "AndroidX document-start 注入 → ArkWeb .javaScriptOnDocumentStart()(API 12+)"),
264
+ ("WebView 生命周期", r"(?:[Ww]eb[Vv]iew\w*|mWebView\w*)\.(?:onPause|onResume|destroy)\s*\(",
265
+ "WebView onPause/onResume/destroy → ArkWeb .onInactive()/.onActive() + aboutToDisappear 释放 controller"),
266
+ ("onRenderProcessGone", r"\bonRenderProcessGone\s*\(",
267
+ "渲染进程崩溃恢复(WebViewClient.onRenderProcessGone,Android 上 return true 防应用崩溃)→ ArkWeb .onRenderExited():"
268
+ "重建 Web 控制器或重载页面恢复状态"),
269
+ ("HLS 流(m3u8/.ts)", r"https?://[^\"'\s]+\.[tT][sS]\b|https?://[^\"'\s]+\.m3u8\b",
270
+ "检测到 HLS 流地址 → 鸿蒙 Web 原生 video 或 @ohos.multimedia.media AVPlayer(原生支持 HLS/m3u8)"),
271
+ ("TbsVideo/X5VideoPlayer", r"\bTbsVideo\b|\bX5VideoPlayer\b|\bX5VideoView\b",
272
+ "X5 播放器 API → @ohos.multimedia.media(AVPlayer)+ XComponent 渲染"),
273
+ ("loadDataWithBaseURL", r"loadDataWithBaseURL\s*\(|\bloadData\s*\(",
274
+ "内联 HTML 加载(loadDataWithBaseURL/loadData)→ ArkWeb controller.loadData(data, mimeType, encoding, baseUrl, historyUrl);"
275
+ "baseUrl 影响相对资源与同源策略,需按原值对齐"),
276
+ ("WebViewRenderProcessClient", r"WebViewRenderProcessClient|setRenderProcessClient",
277
+ "androidx 渲染进程客户端(onRenderProcessResponsive/Unresponsive)→ ArkWeb .onRenderExited() + 卡顿/无响应自处理策略"),
278
+ ]
279
+
280
+ H5_NAME_HINTS = {
281
+ "webviewjavascriptbridge.js": "WebViewJavascriptBridge(WVJB 系 H5 SDK:lzyzsd / wendux,按 h5_wvjb_style 区分)",
282
+ "dsbridge.js": "dsbridge(DSBridge H5 端 SDK)",
283
+ "dsbridge.d.ts": "dsbridge(DSBridge H5 端 SDK)",
284
+ }
285
+ H5_CONTENT_HINTS = ["WebViewJavascriptBridge", "dsbridge", "window.__dsf", "callHandler("]
286
+
287
+ # H5 侧协议风格标记 → 决定 ohpm 候选库契合度
288
+ H5_STYLE_MARKERS = [
289
+ ("WVJBCallbacks", "iOS 系 WVJB setup(WVJBCallbacks 桥初始化)→ @yue/webview_javascript_bridge 契合,基本零改动"),
290
+ ("WebViewJavascriptBridgeReady", "lzyzsd Android 系 setup(等 ready 事件)→ @a_zwj/netweb 对口;@yue(iOS 协议)需适配"),
291
+ ("__queue_message__", "lzyzsd 消息队列 iframe 通道(yy://__queue_message__/)→ @yue 不直接兼容,需 shim 或改造"),
292
+ ("window._dsf", "DSBridge H5 协议(_dsf/_dsb 命名空间)→ @hzw/ohos-dsbridge 契合"),
293
+ ("_dscb", "DSBridge 异步回调挂载点(_dscb)→ @hzw/ohos-dsbridge 契合"),
294
+ ("registerPersistentCallback", "lzyzsd 增强 fork:persistentCallbacks 持久回调扩展(上游原版无)→ 现成 ohpm 库大概率不覆盖,优先自写 shim"),
295
+ ("persistentCallbacks", "lzyzsd 增强 fork:持久回调表扩展 → shim 按工程内 SDK 还原协议"),
296
+ ]
297
+
298
+ # lzyzsd 增强 fork 的 Native 侧扩展特征(同名 API 的变体,现成库不覆盖)
299
+ FORK_EXTENSION_PATTERNS = [
300
+ ("persistent_callbacks", r"registerPersistentCallback|persistentCallbacks"),
301
+ ("origin_whitelist", r"isOriginAllowed|allowedHosts"),
302
+ ("injection_debounce", r"\bmInjecting\b"),
303
+ ]
304
+
305
+ # H5 侧 handler 调用点(与 Native 注册名单做 diff,防迁移遗漏)
306
+ H5_HANDLER_RES = {
307
+ "callHandler": r"""callHandler\s*\(\s*["']([^"']+)["']""",
308
+ "registerHandler": r"""registerHandler\s*\(\s*["']([^"']+)["']""",
309
+ "dsbridge_call": r"""(?:dsbridge|dsBridge)\s*\.\s*call\s*\(\s*["']([^"']+)["']""",
310
+ "dsbridge_register": r"""(?:dsbridge|dsBridge)\s*\.\s*register\s*\(\s*["']([^"']+)["']""",
311
+ }
312
+
313
+ PKG_RE = re.compile(r"^\s*package\s+([\w.]+)", re.M)
314
+ CLASS_RE = re.compile(r"\b(?:class|interface|object)\s+([A-Za-z_]\w*)")
315
+ METHOD_RE = re.compile(r"([A-Za-z_]\w*)\s*\(([^()]*)\)")
316
+ _CTOR = r"\((?:[^()]|\([^()]*\))*\)" # 允许一层嵌套括号的构造参数
317
+ ADDJI_NEW_RE = re.compile(
318
+ r"\.?addJavascriptInterface\s*\(\s*new\s+([\w.$]+)\s*" + _CTOR + r"\s*,\s*(?:[\"']([^\"']+)[\"']|([A-Za-z_]\w*))")
319
+ ADDJI_VAR_RE = re.compile(
320
+ r"\.?addJavascriptInterface\s*\(\s*([A-Za-z_]\w*)\s*,\s*(?:[\"']([^\"']+)[\"']|([A-Za-z_]\w*))")
321
+ # 参数反序 API(封装库常见):addJavascriptInterface("name", new Cls(...)|obj)
322
+ ADDJI_REV_RE = re.compile(
323
+ r"\.?addJavascriptInterface\s*\(\s*[\"']([^\"']+)[\"']\s*,\s*(?:new\s+([\w.$]+)\s*" + _CTOR + r"|([A-Za-z_]\w*))")
324
+ # 匿名类注入:addJavascriptInterface(new Object(){ @JavascriptInterface ... }, "name"|CONST)(真实工程实证:wendux WVJB)
325
+ ADDJI_ANON_RE = re.compile(
326
+ r"\.?addJavascriptInterface\s*\(\s*(?:new\s+|object\s*:\s*)([\w.$]+)\s*" + _CTOR + r"\s*\{([\s\S]{0,4000}?)\}\s*,\s*"
327
+ r"(?:[\"']([^\"']+)[\"']|([A-Za-z_]\w*))")
328
+ ANON_METHOD_RX = re.compile(
329
+ r"@JavascriptInterface[\s\S]{0,200}?[A-Za-z_][\w<>\[\], .]*?\s+([A-Za-z_]\w*)\s*\(([^()]*)\)")
330
+
331
+ _METHOD_DEF_RX = re.compile(r"(?:void|public|protected|private|static|abstract|final)\s+[\w.$<>\[\], ]{0,40}$")
332
+
333
+
334
+ def is_method_definition(text: str, start: int) -> bool:
335
+ """排除方法定义(如 public void addJavascriptInterface(Object o, String name)),只保留真实调用。"""
336
+ return bool(_METHOD_DEF_RX.search(text[max(0, start - 70):start]))
337
+
338
+
339
+ def resolve_const_name(ident: str, text: str) -> str:
340
+ """解析常量引用的注入名(如 BRIDGE_NAME = "WVJBInterface");限制单行短字符串避免跨行误吞。"""
341
+ if not ident:
342
+ return ""
343
+ m = re.search(r"\b" + re.escape(ident) + r"\s*=\s*[\"']([^\"'\n]{1,200})[\"']", text)
344
+ return m.group(1) if m else ""
345
+
346
+
347
+ def clean_namespace(ns: str) -> str:
348
+ ns = (ns or "").strip()
349
+ if "\n" in ns or len(ns) > 100:
350
+ return ""
351
+ return ns
352
+
353
+
354
+ # 注入脚本提取(evaluateJavascript / loadUrl("javascript:...") 字面量)
355
+ INJECT_JS_PATTERNS = [
356
+ ("evaluateJavascript",
357
+ re.compile(r"""evaluateJavascript\s*\(\s*("(?:[^"\\\n]|\\.){0,400}")""")),
358
+ ("loadUrl-javascript",
359
+ re.compile(r"""loadUrl\s*\(\s*["']javascript:((?:[^"'\\\n]|\\.){0,400})["']""")),
360
+ ]
361
+
362
+
363
+ def _unquote_literal(lit: str) -> str:
364
+ body = lit[1:-1] if len(lit) >= 2 and lit[0] in "\"'" and lit[-1] == lit[0] else lit
365
+ return (body.replace('\\"', '"').replace("\\'", "'")
366
+ .replace("\\n", " ").replace("\\t", " ").strip())
367
+
368
+
369
+ def extract_injected_js(src_infos, root):
370
+ """注入脚本清单:用于 document-start / onPageEnd 迁移时机对齐。"""
371
+ out, seen = [], set()
372
+ for p, text in src_infos:
373
+ for api, rx in INJECT_JS_PATTERNS:
374
+ for m in rx.finditer(text):
375
+ line = text[:m.start()].count("\n") + 1
376
+ script = _unquote_literal(m.group(1))[:200]
377
+ key = (rel(p, root), script)
378
+ if key in seen:
379
+ continue
380
+ seen.add(key)
381
+ out.append({"file": rel(p, root), "line": line, "api": api, "script": script})
382
+ return out[:40]
383
+
384
+
385
+ # ---------------------------------------------------------------- 轻量语法辅助(零依赖)
386
+ # 不追求完整 AST:用括号/词法状态追踪解决「定义 vs 调用」「函数体边界」两类高频误判。
387
+
388
+
389
+ def line_brace_depths(text: str):
390
+ """返回每行行首的花括号深度(忽略字符串/注释内的括号)。"""
391
+ depths, depth = [], 0
392
+ i, n = 0, len(text)
393
+ line_start = True
394
+ quote = ""
395
+ line_comment = block_comment = False
396
+ while i < n:
397
+ if line_start:
398
+ depths.append(depth)
399
+ line_start = False
400
+ ch = text[i]
401
+ if line_comment:
402
+ if ch == "\n":
403
+ line_comment = False
404
+ line_start = True
405
+ i += 1
406
+ continue
407
+ if block_comment:
408
+ if text.startswith("*/", i):
409
+ block_comment = False
410
+ i += 2
411
+ continue
412
+ if ch == "\n":
413
+ line_start = True
414
+ i += 1
415
+ continue
416
+ if quote:
417
+ if ch == "\\":
418
+ i += 2
419
+ continue
420
+ if ch == quote:
421
+ quote = ""
422
+ i += 1
423
+ continue
424
+ if ch in ('"', "'"):
425
+ quote = ch
426
+ elif text.startswith("//", i):
427
+ line_comment = True
428
+ i += 2
429
+ continue
430
+ elif text.startswith("/*", i):
431
+ block_comment = True
432
+ i += 2
433
+ continue
434
+ elif ch == "{":
435
+ depth += 1
436
+ elif ch == "}":
437
+ depth = max(0, depth - 1)
438
+ if ch == "\n":
439
+ line_start = True
440
+ i += 1
441
+ return depths or [0]
442
+
443
+
444
+ def depth_at(depths, line_no: int) -> int:
445
+ if not depths:
446
+ return 0
447
+ return depths[min(max(line_no - 1, 0), len(depths) - 1)]
448
+
449
+
450
+ def method_body_after(text: str, pos: int, cap: int = 8000) -> str:
451
+ """从 pos 起定位第一个 '{' 并返回平衡括号内正文;用于函数体语义判断(替代固定行数窗口)。"""
452
+ start = text.find("{", pos)
453
+ if start < 0:
454
+ return ""
455
+ depth, i, end = 0, start, min(len(text), start + cap)
456
+ while i < end:
457
+ ch = text[i]
458
+ if ch == "{":
459
+ depth += 1
460
+ elif ch == "}":
461
+ depth -= 1
462
+ if depth == 0:
463
+ return text[start + 1:i]
464
+ i += 1
465
+ return text[start + 1:end]
466
+
467
+
468
+ def is_definition_site(text: str, start: int, depth: int) -> bool:
469
+ """判断匹配点是否为方法定义:先看词法(修饰符+返回类型),再看花括号深度(>=2 必在函数体内)。"""
470
+ if depth >= 2:
471
+ return False
472
+ return bool(_METHOD_DEF_RX.search(text[max(0, start - 70):start]))
473
+ ADDJAO_NEW_RE = re.compile(r"\.?addJavaObject\s*\(\s*new\s+([\w.$]+)\s*\([^)]*\)\s*,\s*[\"']([^\"']+)[\"']")
474
+ ADDJAO_VAR_RE = re.compile(r"\.?addJavaObject\s*\(\s*([A-Za-z_]\w*)\s*,\s*[\"']([^\"']+)[\"']")
475
+ REG_HANDLER_RE = re.compile(r"\.?registerHandler\s*\(\s*[\"']([^\"']+)[\"']")
476
+ CALL_HANDLER_RE = re.compile(r"\.?callHandler\s*\(\s*[\"']([^\"']+)[\"']")
477
+ HAS_JS_METHOD_RE = re.compile(r"\.?hasJavascriptMethod\s*\(\s*[\"']([^\"']+)[\"']")
478
+ ADD_JS_OBJECT_RE = re.compile(r"\.addJavascriptObject\s*\(\s*([^,()]+?)\s*(?:,\s*[\"']?([^,\"')]*)[\"']?\s*)?\)")
479
+ ADD_JS_OBJECT_NEW_RE = re.compile(r"\.addJavascriptObject\s*\(\s*new\s+([\w.$]+)\s*\([^)]*\)\s*(?:,\s*[\"']?([^,\"')]*)[\"']?\s*)?\)")
480
+ SCHEME_RE = re.compile(r"[\"']([a-zA-Z][a-zA-Z0-9+.\-]*)://")
481
+
482
+ # ---------------------------------------------------------------- 工具函数
483
+
484
+
485
+ def iter_files(root: Path, pred):
486
+ count = 0
487
+ for dirpath, dirnames, filenames in os.walk(root):
488
+ dirnames[:] = [d for d in dirnames
489
+ if d not in SKIP_DIRS and not NON_ANDROID_SOURCE_SET.match(d)
490
+ and not (d in ("test", "androidTest") and Path(dirpath).name == "src")]
491
+ for fn in filenames:
492
+ p = Path(dirpath) / fn
493
+ try:
494
+ if pred(p):
495
+ count += 1
496
+ if count > MAX_SRC_FILES:
497
+ return
498
+ yield p
499
+ except OSError:
500
+ pass
501
+
502
+
503
+ def read_text(p: Path):
504
+ try:
505
+ if p.stat().st_size > MAX_FILE_BYTES:
506
+ return None
507
+ return p.read_text(encoding="utf-8", errors="ignore")
508
+ except OSError:
509
+ return None
510
+
511
+
512
+ def line_is_comment(text: str, pos: int) -> bool:
513
+ start = text.rfind("\n", 0, pos) + 1
514
+ s = text[start:pos].strip()
515
+ return s.startswith(("//", "*", "/*"))
516
+
517
+
518
+ def rel(p: Path, root: Path) -> str:
519
+ try:
520
+ return str(p.relative_to(root))
521
+ except ValueError:
522
+ return str(p)
523
+
524
+
525
+ def hit_lines(text: str, pattern: str, cap: int = 6, skip_comments: bool = False):
526
+ rx = re.compile(pattern)
527
+ hits = []
528
+ for i, line in enumerate(text.splitlines(), 1):
529
+ if skip_comments:
530
+ s = line.strip()
531
+ if s.startswith(("*", "//", "/*", "*/")):
532
+ continue
533
+ if rx.search(line):
534
+ snip = line.strip()
535
+ if len(snip) > 180:
536
+ snip = snip[:177] + "..."
537
+ hits.append({"line": i, "snippet": snip})
538
+ if len(hits) >= cap:
539
+ break
540
+ return hits
541
+
542
+
543
+ # ---------------------------------------------------------------- 检测
544
+
545
+
546
+ def collect_dep_text(root: Path):
547
+ texts, files = [], []
548
+
549
+ def is_dep(p: Path):
550
+ return p.name == "pom.xml" or p.suffix in {".gradle", ".kts", ".toml"}
551
+
552
+ for p in iter_files(root, is_dep):
553
+ t = read_text(p)
554
+ if t:
555
+ texts.append(t)
556
+ files.append(rel(p, root))
557
+ return "\n".join(texts), files
558
+
559
+
560
+ def detect_kinds(kinds, dep_text, src_infos, root):
561
+ found = []
562
+ for d in kinds:
563
+ ev = {"gradle": [], "imports": [], "symbols": []}
564
+ for kw in d.get("gradle", []):
565
+ if kw in dep_text:
566
+ ev["gradle"].append(kw)
567
+ for p, text in src_infos:
568
+ for imp in d.get("imports", []):
569
+ if any(f"import {imp}" in ln for ln in text.splitlines()[:400]):
570
+ ev["imports"].append({"file": rel(p, root), "line": None, "snippet": f"import {imp}.*"})
571
+ break
572
+ for sym in d.get("symbols", []):
573
+ for h in hit_lines(text, sym, cap=3, skip_comments=True):
574
+ ev["symbols"].append({"file": rel(p, root), "line": h["line"], "snippet": h["snippet"]})
575
+ # imports/symbols 去重(同 file+line 只留一条)后截断
576
+ for kind in ("imports", "symbols"):
577
+ seen = set()
578
+ deduped = []
579
+ for e in ev[kind]:
580
+ key = (e["file"], e.get("line"), e["snippet"])
581
+ if key not in seen:
582
+ seen.add(key)
583
+ deduped.append(e)
584
+ ev[kind] = deduped[:10]
585
+ if ev["gradle"] or ev["imports"] or ev["symbols"]:
586
+ found.append({**d, "evidence": ev})
587
+ return found
588
+
589
+
590
+ def _block_span(text: str, off: int):
591
+ """从 off 之后第一个 '{' 起做平衡括号匹配,返回 (start_off, end_off);无花括号返回 None。"""
592
+ start = text.find("{", off)
593
+ if start < 0:
594
+ return None
595
+ depth, i, n = 0, start, len(text)
596
+ while i < n:
597
+ c = text[i]
598
+ if c == "{":
599
+ depth += 1
600
+ elif c == "}":
601
+ depth -= 1
602
+ if depth == 0:
603
+ return start, i
604
+ i += 1
605
+ return start, n - 1
606
+
607
+
608
+ def class_ranges(text: str):
609
+ """[(name, start_off, end_off)]:按平衡括号确定每个 class/interface/object 的体范围。"""
610
+ out = []
611
+ for m in CLASS_RE.finditer(text):
612
+ span = _block_span(text, m.end())
613
+ if span:
614
+ out.append((m.group(1), span[0], span[1]))
615
+ return out
616
+
617
+
618
+ def enclosing_class(ranges, pos: int) -> str:
619
+ """返回包含 pos 的最内层类名(解决 class 内嵌 interface 后的方法归属错乱)。"""
620
+ best = None
621
+ for name, start, end in ranges:
622
+ if start <= pos <= end:
623
+ if best is None or (end - start) < (best[2] - best[1]):
624
+ best = (name, start, end)
625
+ return best[0] if best else ""
626
+
627
+
628
+ def extract_ji_methods(src_infos, root):
629
+ out = []
630
+ for p, text in src_infos:
631
+ if "@JavascriptInterface" not in text:
632
+ continue
633
+ lines = text.splitlines()
634
+ pkg = ""
635
+ m = PKG_RE.search(text)
636
+ if m:
637
+ pkg = m.group(1)
638
+ ranges = class_ranges(text)
639
+ n = len(lines)
640
+ for i, ln in enumerate(lines, 1):
641
+ if "@JavascriptInterface" not in ln:
642
+ continue
643
+ sig = ln.split("@JavascriptInterface", 1)[1]
644
+ j = 0
645
+ while "(" not in sig and j < 3 and i + j < n:
646
+ j += 1
647
+ sig += " " + lines[i + j - 1]
648
+ last = None
649
+ for mm in METHOD_RE.finditer(sig):
650
+ last = mm
651
+ if not last:
652
+ continue
653
+ name = last.group(1)
654
+ if name in ("if", "for", "while", "switch", "catch", "super", "this", "new", "return", "fun", " synchronized"):
655
+ continue
656
+ pos = sum(len(x) + 1 for x in lines[:i - 1])
657
+ cls = enclosing_class(ranges, pos)
658
+ out.append({
659
+ "class": f"{pkg}.{cls}" if cls else rel(p, root),
660
+ "class_simple": cls or "?",
661
+ "file": rel(p, root), "line": i,
662
+ "method": name,
663
+ "params": last.group(2).strip()[:160],
664
+ })
665
+ return out
666
+
667
+
668
+ def resolve_expr_class(expr: str, text: str) -> str:
669
+ expr = re.sub(r"^this\.", "", expr.strip())
670
+ if not re.fullmatch(r"[A-Za-z_]\w*", expr):
671
+ m = re.search(r"new\s+([\w.$]+)\s*\(", expr)
672
+ return m.group(1).split(".")[-1] if m else ""
673
+ var = expr
674
+ for rx in (
675
+ r"(?:val|var)\s+" + re.escape(var) + r"\s*:\s*([\w.$]+)",
676
+ r"(?:val|var)\s+" + re.escape(var) + r"\s*=\s*([\w.$]+)\s*\(",
677
+ r"([\w.$]+)\s+" + re.escape(var) + r"\s*=\s*new\s+[\w.$]+\s*\(",
678
+ r"\b([A-Z]\w*)\s+" + re.escape(var) + r"\s*[;=)]",
679
+ ):
680
+ m = re.search(rx, text)
681
+ if m:
682
+ return m.group(1).split(".")[-1]
683
+ return ""
684
+
685
+
686
+ def extract_namespaces(src_infos, ji_methods, root):
687
+ entries = []
688
+ simple_to_methods = {}
689
+ for mm in ji_methods:
690
+ simple_to_methods.setdefault(mm["class_simple"], []).append(mm)
691
+ for p, text in src_infos:
692
+ depths = line_brace_depths(text)
693
+ for rx in (ADDJI_NEW_RE, ADDJAO_NEW_RE):
694
+ for m in rx.finditer(text):
695
+ line = text[:m.start()].count("\n") + 1
696
+ if is_definition_site(text, m.start(), depth_at(depths, line)):
697
+ continue
698
+ ns = clean_namespace(m.group(2)) or resolve_const_name(m.group(3), text)
699
+ entries.append({"namespace": ns or "(unresolved)", "class_simple": m.group(1).split(".")[-1],
700
+ "confidence": "high" if ns else "unresolved",
701
+ "file": rel(p, root), "line": line,
702
+ "api": "addJavascriptInterface" if rx is ADDJI_NEW_RE else "addJavaObject"})
703
+ for rx in (ADDJI_VAR_RE, ADDJAO_VAR_RE):
704
+ for m in rx.finditer(text):
705
+ line = text[:m.start()].count("\n") + 1
706
+ if is_definition_site(text, m.start(), depth_at(depths, line)):
707
+ continue
708
+ expr = m.group(1)
709
+ ns = clean_namespace(m.group(2)) or resolve_const_name(m.group(3), text)
710
+ if expr == "this":
711
+ # 裸 this 注入(如 addJavascriptInterface(this, "main"))→ 关联所在文件类
712
+ cls = p.stem if p.stem in simple_to_methods else (
713
+ CLASS_RE.search(text).group(1) if CLASS_RE.search(text) else "")
714
+ entries.append({"namespace": ns or "(unresolved)", "class_simple": cls,
715
+ "confidence": ("high" if ns else "unresolved") if cls and cls in simple_to_methods else "guess",
716
+ "file": rel(p, root), "line": line,
717
+ "api": "addJavascriptInterface" if rx is ADDJI_VAR_RE else "addJavaObject"})
718
+ continue
719
+ cls = resolve_expr_class(expr, text)
720
+ entries.append({"namespace": ns or "(unresolved)", "class_simple": cls,
721
+ "confidence": "high" if (cls and ns) else "unresolved",
722
+ "file": rel(p, root), "line": line,
723
+ "api": "addJavascriptInterface" if rx is ADDJI_VAR_RE else "addJavaObject"})
724
+ # 参数反序 API:addJavascriptInterface("name", new Cls(...)|obj)
725
+ for m in ADDJI_REV_RE.finditer(text):
726
+ line = text[:m.start()].count("\n") + 1
727
+ if is_definition_site(text, m.start(), depth_at(depths, line)):
728
+ continue
729
+ ns = clean_namespace(m.group(1))
730
+ cls = m.group(2).split(".")[-1] if m.group(2) else resolve_expr_class(m.group(3) or "", text)
731
+ entries.append({"namespace": ns or "(unresolved)", "class_simple": cls,
732
+ "confidence": "high" if (ns and cls) else ("high" if ns else "unresolved"),
733
+ "file": rel(p, root), "line": line, "api": "addJavascriptInterface(reversed)"})
734
+ # 匿名类注入:addJavascriptInterface(new Object(){ @JavascriptInterface ... }, "name"|CONST)
735
+ for m in ADDJI_ANON_RE.finditer(text):
736
+ line = text[:m.start()].count("\n") + 1
737
+ if is_definition_site(text, m.start(), depth_at(depths, line)):
738
+ continue
739
+ ns = clean_namespace(m.group(3)) or resolve_const_name(m.group(4), text)
740
+ body = m.group(2)
741
+ anon_methods = []
742
+ for am in ANON_METHOD_RX.finditer(body):
743
+ anon_methods.append({"method": am.group(1), "params": am.group(2).strip()[:160],
744
+ "file": rel(p, root), "line": line})
745
+ entries.append({"namespace": ns or "(unresolved)",
746
+ "class_simple": f"(anonymous {m.group(1).split('.')[-1]})",
747
+ "confidence": "high" if ns else "unresolved", "file": rel(p, root), "line": line,
748
+ "api": "addJavascriptInterface(anonymous)", "inline_methods": anon_methods})
749
+ for m in ADD_JS_OBJECT_NEW_RE.finditer(text):
750
+ line = text[:m.start()].count("\n") + 1
751
+ entries.append({"namespace": m.group(2) or "(default)", "class_simple": m.group(1).split(".")[-1],
752
+ "confidence": "high", "file": rel(p, root), "line": line,
753
+ "api": "addJavascriptObject(DSBridge)"})
754
+ for m in ADD_JS_OBJECT_RE.finditer(text):
755
+ line = text[:m.start()].count("\n") + 1
756
+ cls = resolve_expr_class(m.group(1), text)
757
+ entries.append({"namespace": m.group(2) or "(default)", "class_simple": cls,
758
+ "confidence": "high" if cls else "unresolved",
759
+ "file": rel(p, root), "line": line, "api": "addJavascriptObject(DSBridge)"})
760
+ # 兜底:只有一个 @JavascriptInterface 类且存在未解析命名空间时按 guess 关联
761
+ for e in entries:
762
+ if not e["class_simple"] and len(simple_to_methods) == 1:
763
+ e["class_simple"] = next(iter(simple_to_methods))
764
+ e["confidence"] = "guess"
765
+ anon_claimed = {(m["method"], m["file"])
766
+ for e in entries if e.get("api", "").endswith("(anonymous)")
767
+ for m in (e.get("inline_methods") or [])}
768
+ for e in entries:
769
+ if e.get("inline_methods") is not None:
770
+ inline = e.pop("inline_methods")
771
+ e["class"] = ""
772
+ e["methods"] = inline
773
+ continue
774
+ methods = simple_to_methods.get(e["class_simple"], [])
775
+ e["class"] = methods[0]["class"] if methods else ""
776
+ e["methods"] = [{"method": x["method"], "params": x["params"], "file": x["file"], "line": x["line"]}
777
+ for x in methods if (x["method"], x["file"]) not in anon_claimed]
778
+ # 合并同一 (namespace, class) 的多处注入点(多 Activity 复用同一桥对象),保留 usages 明细
779
+ merged, order = {}, []
780
+ for e in entries:
781
+ key = (e["namespace"], e["class_simple"])
782
+ if key in merged:
783
+ merged[key]["usages"].append({"file": e["file"], "line": e["line"], "api": e["api"]})
784
+ if len(e.get("methods") or []) > len(merged[key].get("methods") or []):
785
+ merged[key]["methods"] = e["methods"]
786
+ continue
787
+ e2 = dict(e)
788
+ e2["usages"] = [{"file": e["file"], "line": e["line"], "api": e["api"]}]
789
+ merged[key] = e2
790
+ order.append(key)
791
+ entries = [merged[k] for k in order]
792
+ used = {(e["namespace"], e["class_simple"]) for e in entries if e["class_simple"]}
793
+ leftovers = []
794
+ seen = set()
795
+ for cls, methods in simple_to_methods.items():
796
+ if cls == "?" or any((e["namespace"], cls) in used for e in entries):
797
+ continue
798
+ fqn = methods[0]["class"]
799
+ if fqn in seen:
800
+ continue
801
+ seen.add(fqn)
802
+ leftovers.append({"class": fqn, "class_simple": cls,
803
+ "methods": [{"method": x["method"], "params": x["params"],
804
+ "file": x["file"], "line": x["line"]} for x in methods]})
805
+ # 匿名类注入已声明的方法从「未关联类」中剔除,避免重复/误导
806
+ anon_claimed = {(m["method"], m["file"])
807
+ for e in entries if e.get("api", "").endswith("(anonymous)")
808
+ for m in e["methods"]}
809
+ if anon_claimed:
810
+ filtered = []
811
+ for x in leftovers:
812
+ kept = [m for m in x["methods"] if (m["method"], m["file"]) not in anon_claimed]
813
+ if kept:
814
+ filtered.append({**x, "methods": kept})
815
+ leftovers = filtered
816
+ return entries, leftovers
817
+
818
+
819
+ def extract_handlers(src_infos, root):
820
+ reg, call, ds_has = [], [], []
821
+ for p, text in src_infos:
822
+ lines = text.splitlines()
823
+ for m in REG_HANDLER_RE.finditer(text):
824
+ line = text[:m.start()].count("\n") + 1
825
+ reg.append({"name": m.group(1), "file": rel(p, root), "line": line,
826
+ "snippet": lines[line - 1].strip()[:180]})
827
+ for m in CALL_HANDLER_RE.finditer(text):
828
+ line = text[:m.start()].count("\n") + 1
829
+ call.append({"name": m.group(1), "file": rel(p, root), "line": line,
830
+ "snippet": lines[line - 1].strip()[:180]})
831
+ for m in HAS_JS_METHOD_RE.finditer(text):
832
+ line = text[:m.start()].count("\n") + 1
833
+ ds_has.append({"name": m.group(1), "file": rel(p, root), "line": line})
834
+ return reg[:60], call[:60], ds_has[:30]
835
+
836
+
837
+ def extract_schemes(src_infos, root):
838
+ out = []
839
+ for p, text in src_infos:
840
+ if "shouldOverrideUrlLoading" not in text:
841
+ continue
842
+ seen = set()
843
+ lines = text.splitlines()
844
+ for i, line in enumerate(lines, 1):
845
+ if "shouldOverrideUrlLoading" in line:
846
+ line_start_off = sum(len(x) + 1 for x in lines[:i - 1])
847
+ body = method_body_after(text, line_start_off) or "\n".join(lines[i:i + 25])
848
+ style = ""
849
+ has_custom_scheme = any(mm.group(1).lower() not in COMMON_SCHEMES
850
+ for mm in SCHEME_RE.finditer(body))
851
+ if has_custom_scheme:
852
+ style = "" # 自定义 scheme 桥,分类交给 url_schemes 行
853
+ elif re.search(r"\.host\b|\.authority\b|getQueryParameter|\.getPath\(", body):
854
+ style = "host/query 参数比对(疑似 OAuth 回调/深链拦截,非自定义 scheme 桥)"
855
+ elif re.search(r"ACTION_VIEW|startActivity\s*\(", body):
856
+ style = "全量外跳系统浏览器(Intent.ACTION_VIEW,非桥)"
857
+ elif re.search(r"return\s+true", body):
858
+ style = "全量拦截(return true,吞掉所有导航;ArkWeb onLoadIntercept 返回 true 等价,确认是否误伤页面内跳转)"
859
+ out.append({"file": rel(p, root), "line": i, "scheme": "(见方法体)",
860
+ "match_style": style, "snippet": line.strip()[:180]})
861
+ if not any(k in line for k in ("startsWith", "Uri.parse", "getQueryParameter",
862
+ "getHost", "equals(", "scheme")):
863
+ continue
864
+ for m in SCHEME_RE.finditer(line):
865
+ s = m.group(1)
866
+ if s.lower() in COMMON_SCHEMES or s in seen:
867
+ continue
868
+ seen.add(s)
869
+ out.append({"file": rel(p, root), "line": i, "scheme": s,
870
+ "snippet": line.strip()[:180]})
871
+ return out[:40]
872
+
873
+
874
+ def extract_settings(src_infos, root):
875
+ result = {}
876
+ risk = []
877
+ for label, rx_strs, mode in SETTINGS_FLAGS:
878
+ values = []
879
+ for p, text in src_infos:
880
+ depths = line_brace_depths(text)
881
+ for rx_str in rx_strs:
882
+ rx = re.compile(rx_str)
883
+ for m in rx.finditer(text):
884
+ line = text[:m.start()].count("\n") + 1
885
+ if is_definition_site(text, m.start(), depth_at(depths, line)):
886
+ continue
887
+ if mode == "ssl":
888
+ # 向后 15 行找 proceed(
889
+ after = "\n".join(text.splitlines()[line:line + 15])
890
+ values.append({"value": "proceed" if ".proceed(" in after else "cancel/other",
891
+ "file": rel(p, root), "line": line})
892
+ elif mode == "flag":
893
+ values.append({"value": "detected", "file": rel(p, root), "line": line})
894
+ else:
895
+ values.append({"value": m.group(1)[:120], "file": rel(p, root), "line": line})
896
+ if values:
897
+ result[label] = values[:20]
898
+ for v in result.get("onReceivedSslError", []):
899
+ if v["value"] == "proceed":
900
+ risk.append("onReceivedSslError 直接 proceed()(忽略证书校验),鸿蒙侧需评估是否保留 onSslErrorReceive 忽错")
901
+ for v in result.get("setAllowUniversalAccessFromFileURLs", []):
902
+ if v["value"] == "true":
903
+ risk.append("setAllowUniversalAccessFromFileURLs(true):file 域跨源访问,ArkWeb 需显式对齐")
904
+ for v in result.get("setAllowFileAccessFromFileURLs", []):
905
+ if v["value"] == "true":
906
+ risk.append("setAllowFileAccessFromFileURLs(true):file 域读 file,ArkWeb 需显式对齐")
907
+ for v in result.get("setMixedContentMode", []):
908
+ if "ALWAYS_ALLOW" in v["value"]:
909
+ risk.append("MIXED_CONTENT_ALWAYS_ALLOW:https 页允许 http 资源,ArkWeb mixedMode 需对齐")
910
+ elif "MIXED_CONTENT" not in v["value"]:
911
+ risk.append(f"setMixedContentMode 传入非 MixedContentMode 常量({v['value']},疑似误用或内核差异),需人工确认原意")
912
+ for v in result.get("setSavePassword", []):
913
+ if v["value"] == "true":
914
+ risk.append("setSavePassword(true):明文保存密码风险,建议迁移时关闭")
915
+ return result, risk
916
+
917
+
918
+ def scan_h5_text(text: str, fname: str):
919
+ """对单段 H5 文本提取协议风格标记 + handler 调用点(本地/远程共用)。"""
920
+ styles, handlers = [], {}
921
+ for marker, meaning in H5_STYLE_MARKERS:
922
+ if marker in text:
923
+ line = text[:text.index(marker)].count("\n") + 1
924
+ styles.append({"marker": marker, "meaning": meaning, "file": fname, "line": line})
925
+ for kind, rx_str in H5_HANDLER_RES.items():
926
+ rx = re.compile(rx_str)
927
+ for m in rx.finditer(text):
928
+ handlers.setdefault(kind, set()).add(m.group(1))
929
+ return styles, handlers
930
+
931
+
932
+ def detect_h5_sdk_versions(h5_texts):
933
+ """H5 SDK 版本识别:dsbridge v2/v3、wendux WVJB、lzyzsd(+fork)。"""
934
+ sigs = [
935
+ ("dsbridge.v3", lambda s: ("window._dsf" in s) or ("_dsb" in s) or ("_dscb" in s)),
936
+ ("dsbridge.v2", lambda s: ("dsBridge" in s) and ("window._dsf" not in s)),
937
+ ("wendux_wvjb", lambda s: ("_handleMessageFromJava" in s) and ("WVJBCallbacks" in s)),
938
+ ("lzyzsd", lambda s: ("yy://" in s) or ("__queue_message__" in s)),
939
+ ("lzyzsd_fork", lambda s: ("registerPersistentCallback" in s) or ("persistentCallbacks" in s)),
940
+ ]
941
+ found = {}
942
+ for fname, text in h5_texts:
943
+ ver = re.search(r"@version\s*([\w.\-]+)", text)
944
+ for name, pred in sigs:
945
+ if pred(text):
946
+ e = found.setdefault(name, {"sdk": name, "version": "", "files": []})
947
+ if ver and not e["version"]:
948
+ e["version"] = ver.group(1)
949
+ if fname not in e["files"]:
950
+ e["files"].append(fname)
951
+ return list(found.values())
952
+
953
+
954
+ def scan_h5_assets(root: Path):
955
+ """返回 (资产命中, 协议风格标记, handler 调用点清单, H5 文本样本)。"""
956
+ hits, styles, handlers, texts = [], [], {}, []
957
+ h5_exts = {".js", ".ts", ".html", ".htm", ".vue"}
958
+ style_seen = set()
959
+
960
+ def pred(p: Path):
961
+ if p.name.lower() in H5_NAME_HINTS:
962
+ return True
963
+ if p.suffix.lower() in {".html", ".htm"} and "raw" in p.parts and "res" in p.parts:
964
+ return True # res/raw 内嵌 HTML(loadDataWithBaseURL 常见,真实工程实证:android-youtube-player)
965
+ return p.suffix.lower() in h5_exts and any(k in p.parts for k in ("assets", "www", "hybrid"))
966
+
967
+ for p in iter_files(root, pred):
968
+ low = p.name.lower()
969
+ fpath = rel(p, root)
970
+ if low in H5_NAME_HINTS and fpath not in {h["file"] for h in hits}:
971
+ hits.append({"file": fpath, "bridge": H5_NAME_HINTS[low], "evidence": "文件名"})
972
+ elif low.endswith((".html", ".htm")) and "raw" in p.parts and "res" in p.parts:
973
+ hits.append({"file": fpath, "bridge": "res/raw 内嵌 HTML(运行时 loadData/loadDataWithBaseURL)",
974
+ "evidence": "res/raw"})
975
+ t = read_text(p)
976
+ if not t:
977
+ continue
978
+ for kw in H5_CONTENT_HINTS:
979
+ if kw in t and not any(h["file"] == fpath for h in hits):
980
+ line = t[:t.index(kw)].count("\n") + 1
981
+ hits.append({"file": fpath, "bridge": f"内容包含 {kw}", "line": line})
982
+ break
983
+ texts.append((fpath, t))
984
+ f_styles, f_handlers = scan_h5_text(t, fpath)
985
+ for s in f_styles:
986
+ if s["marker"] not in style_seen:
987
+ style_seen.add(s["marker"])
988
+ styles.append(s)
989
+ for kind, names in f_handlers.items():
990
+ handlers.setdefault(kind, set()).update(names)
991
+ if len(hits) >= MAX_H5_FILES:
992
+ break
993
+ return hits[:60], styles[:20], {k: sorted(v) for k, v in handlers.items()}, texts
994
+
995
+
996
+ # XML 布局中的 WebView 声明(ViewBinding / findViewById 常见,真实工程实证:my-tv-webview)
997
+ XML_WEBVIEW_TAGS = [
998
+ ("system_webview", re.compile(r"<WebView\b")),
999
+ ("tencent_x5", re.compile(r"<com\.tencent\.smtt\.sdk\.(?:WebView|X5WebView)\b")),
1000
+ ("crosswalk", re.compile(r"<org\.xwalk\.core\.XWalkView\b")),
1001
+ ("geckoview", re.compile(r"<org\.mozilla\.geckoview\.")),
1002
+ ]
1003
+
1004
+
1005
+ def scan_layout_webviews(root: Path):
1006
+ """扫描 res/layout 下 XML 中的 WebView 标签声明。"""
1007
+ out = []
1008
+
1009
+ def pred(p: Path):
1010
+ return p.suffix.lower() == ".xml" and "res" in p.parts
1011
+
1012
+ for p in iter_files(root, pred):
1013
+ t = read_text(p)
1014
+ if not t:
1015
+ continue
1016
+ for i, line in enumerate(t.splitlines(), 1):
1017
+ for key, rx in XML_WEBVIEW_TAGS:
1018
+ if rx.search(line):
1019
+ out.append({"kind": key, "file": rel(p, root), "line": i,
1020
+ "snippet": line.strip()[:160]})
1021
+ break
1022
+ return out[:20]
1023
+
1024
+
1025
+ SERVICE_BASE_RX = re.compile(r"(?:extends|:)\s*([\w.]*Service)\b")
1026
+ SERVICE_WEBVIEW_RX = re.compile(r"\bnew\s+WebView\s*\(|\bWebView\s*\(|addJavascriptInterface\s*\(|\.loadUrl\s*\(")
1027
+ ASSET_LOADER_PATH_RX = re.compile(r"addPathHandler\s*\(\s*[\"']([^\"']+)[\"']")
1028
+ DEEP_LINK_RX = re.compile(r"[\"'](intent://[^\"'\s)]+)[\"']")
1029
+ COOKIE_SET_RX = re.compile(r"setCookie\s*\(\s*[\"']([^\"']+)[\"']\s*,\s*[\"']([^\"'=]+)=")
1030
+
1031
+
1032
+ def detect_service_webviews(src_infos, root):
1033
+ """Service/后台组件内嵌 WebView:鸿蒙 ArkWeb 必须挂 UI 树,属结构性迁移阻塞。"""
1034
+ out = []
1035
+ for p, text in src_infos:
1036
+ for name, open_off, end_off in class_ranges(text):
1037
+ header = text[max(0, open_off - 400):open_off + 1]
1038
+ m = SERVICE_BASE_RX.search(header)
1039
+ if not m:
1040
+ continue
1041
+ if not SERVICE_WEBVIEW_RX.search(text[open_off:end_off]):
1042
+ continue
1043
+ decl = text.rfind(name, 0, open_off)
1044
+ line = text[:decl if decl >= 0 else open_off].count("\n") + 1
1045
+ out.append({"file": rel(p, root), "line": line, "klass": name,
1046
+ "service_base": m.group(1)[:60]})
1047
+ return out[:20]
1048
+
1049
+
1050
+ def extract_asset_loader_paths(src_infos, root):
1051
+ """WebViewAssetLoader.addPathHandler('/assets/', ...) 的服务路径。"""
1052
+ out, seen = [], set()
1053
+ for p, text in src_infos:
1054
+ for m in ASSET_LOADER_PATH_RX.finditer(text):
1055
+ if line_is_comment(text, m.start()):
1056
+ continue
1057
+ path = m.group(1)
1058
+ key = (rel(p, root), path)
1059
+ if key in seen:
1060
+ continue
1061
+ seen.add(key)
1062
+ out.append({"file": rel(p, root), "line": text[:m.start()].count("\n") + 1, "path": path})
1063
+ return out[:20]
1064
+
1065
+
1066
+ def extract_deep_links(src_infos, root):
1067
+ """intent:// 深链(含 scheme/host 与 Intent 参数)。"""
1068
+ out, seen = [], set()
1069
+ for p, text in src_infos:
1070
+ for m in DEEP_LINK_RX.finditer(text):
1071
+ if line_is_comment(text, m.start()):
1072
+ continue
1073
+ url = m.group(1)
1074
+ key = (rel(p, root), url)
1075
+ if key in seen:
1076
+ continue
1077
+ seen.add(key)
1078
+ out.append({"file": rel(p, root), "line": text[:m.start()].count("\n") + 1, "url": url[:240]})
1079
+ return out[:20]
1080
+
1081
+
1082
+ def extract_cookies(src_infos, root):
1083
+ """CookieManager.setCookie(url, 'key=...') 的域与 key(迁移核对 WebCookieManager 策略)。"""
1084
+ out, seen = [], set()
1085
+ for p, text in src_infos:
1086
+ for m in COOKIE_SET_RX.finditer(text):
1087
+ if line_is_comment(text, m.start()):
1088
+ continue
1089
+ key = (rel(p, root), m.group(1), m.group(2))
1090
+ if key in seen:
1091
+ continue
1092
+ seen.add(key)
1093
+ out.append({"file": rel(p, root), "line": text[:m.start()].count("\n") + 1,
1094
+ "url": m.group(1)[:200], "key": m.group(2)[:80]})
1095
+ return out[:20]
1096
+
1097
+
1098
+ def extract_chrome_features(src_infos, root):
1099
+ """容器能力(ChromeClient / 资源拦截 / document-start / 生命周期 / Cookie / 调试)→ ArkWeb 映射。"""
1100
+ out = []
1101
+ for label, rx_str, hint in CHROME_FEATURES:
1102
+ hits = []
1103
+ for p, text in src_infos:
1104
+ for h in hit_lines(text, rx_str, cap=3):
1105
+ hits.append({"file": rel(p, root), "line": h["line"], "snippet": h["snippet"]})
1106
+ if hits:
1107
+ out.append({"feature": label, "hint": hint, "hits": hits})
1108
+ return out
1109
+
1110
+
1111
+ def extract_local_entries(src_infos, root):
1112
+ """本地页入口:源码内任意 file:///android_asset/... 字符串(含变量赋值后 loadUrl,真实工程实证 ByWebView)。
1113
+ 同路径去重并记录使用次数。"""
1114
+ seen = {}
1115
+ order = []
1116
+ for p, text in src_infos:
1117
+ lines = text.splitlines()
1118
+ for m in re.finditer(r"""["'](file://[^"']+)["']""", text):
1119
+ url = m.group(1).rstrip("\\")
1120
+ line = text[:m.start()].count("\n") + 1
1121
+ ln = lines[line - 1].strip() if line - 1 < len(lines) else ""
1122
+ if ln.startswith(("//", "*", "/*")) or "\\" in url or url.rstrip().endswith((".js", ".css")):
1123
+ # 注释行 / 转义 JS 注入串 / 静态 JS·CSS 引用不算「页面入口」
1124
+ continue
1125
+ if "/android_asset/" in url:
1126
+ path = url.split("/android_asset/", 1)[1]
1127
+ if "$" in path or "{" in path:
1128
+ key = ("dynamic", url)
1129
+ entry = {
1130
+ "url": url, "kind": "dynamic_asset",
1131
+ "harmony_src": "(运行时拼接的 assets 路径)",
1132
+ "note": "路径为运行时变量/插值:迁移时改为沙箱或 rawfile 常量路径,或按运行时逻辑生成",
1133
+ }
1134
+ if key in seen:
1135
+ seen[key]["usages"] += 1
1136
+ continue
1137
+ entry.update({"file": rel(p, root), "line": line, "usages": 1})
1138
+ seen[key] = entry
1139
+ order.append(key)
1140
+ continue
1141
+ key = ("android_asset", path)
1142
+ entry = {
1143
+ "url": url, "kind": "android_asset",
1144
+ "harmony_src": f"$rawfile('{path}')",
1145
+ "note": "assets 整目录迁 resources/rawfile(结构不变),页内引用 resource://rawfile/...",
1146
+ }
1147
+ else:
1148
+ key = ("file_other", url)
1149
+ entry = {
1150
+ "url": url, "kind": "file_other",
1151
+ "harmony_src": "(本地文件路径)",
1152
+ "note": "本地文件页:迁沙箱后 src 指向沙箱路径,或改放 rawfile",
1153
+ }
1154
+ if key in seen:
1155
+ seen[key]["usages"] += 1
1156
+ continue
1157
+ entry.update({"file": rel(p, root), "line": line, "usages": 1})
1158
+ seen[key] = entry
1159
+ order.append(key)
1160
+ return [seen[k] for k in order][:40]
1161
+
1162
+
1163
+ def extract_fork_extensions(src_infos, root):
1164
+ """lzyzsd 增强 fork 的 Native 侧私有扩展检测(现成 ohpm 库不覆盖这些)。"""
1165
+ out = []
1166
+ for key, rx_str in FORK_EXTENSION_PATTERNS:
1167
+ hits = []
1168
+ for p, text in src_infos:
1169
+ for h in hit_lines(text, rx_str, cap=2, skip_comments=True):
1170
+ hits.append({"file": rel(p, root), "line": h["line"], "snippet": h["snippet"]})
1171
+ if hits:
1172
+ out.append({"key": key, "hits": hits})
1173
+ return out
1174
+
1175
+
1176
+ # ---------------------------------------------------------------- ohpm 在线检索
1177
+
1178
+
1179
+ def search_ohpm(keyword: str, size: int = 20):
1180
+ """在线检索 ohpm 中心仓(官方 openapi,2026-10 实证)。仅查询,不读写工程。"""
1181
+ import time as _time
1182
+ import urllib.parse
1183
+ import urllib.request
1184
+
1185
+ url = OHPM_SEARCH_URL.format(kw=urllib.parse.quote(keyword), size=size)
1186
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
1187
+ with urllib.request.urlopen(req, timeout=20) as r:
1188
+ d = json.load(r)
1189
+ body = d.get("body") or {}
1190
+ rows = body.get("rows") or []
1191
+ print(f"ohpm 检索 “{keyword}”:共 {body.get('total', 0)} 条")
1192
+ for p in rows:
1193
+ ts = p.get("latestPublishTime")
1194
+ date = _time.strftime("%Y-%m-%d", _time.localtime(ts / 1000)) if isinstance(ts, (int, float)) else "?"
1195
+ desc = (p.get("description") or "").replace("\n", " ")[:60]
1196
+ print(f"- {p['name']} v{p.get('latestVersion', '')} | {desc} | likes={p.get('likes', 0)} "
1197
+ f"| {p.get('license', '')} | 发布 {date}")
1198
+ if not rows:
1199
+ print("(无结果)")
1200
+ print("\n核验方式:下载 .har 解包读 README(url 形如 "
1201
+ "https://ohpm.openharmony.cn/ohpm/<name>/-/<短名>-<版本>.har),"
1202
+ "重点比对 H5 全局对象名 / ready 事件 / 回调 ID 约定 / 同步返回语义。")
1203
+
1204
+
1205
+ def build_ohpm_candidates(bridge_keys):
1206
+ """把检测到的桥 key 映射到实证过的 ohpm 候选库(离线知识库)。"""
1207
+ out = []
1208
+ for k in bridge_keys:
1209
+ for c in OHPM_REPLACEMENTS.get(k, []):
1210
+ out.append({"detected": k, "source": "protocol_compat", **c})
1211
+ if bridge_keys:
1212
+ for c in OHPM_GENERIC_FALLBACK:
1213
+ out.append({"detected": "(通用备选)", "source": "generic_h5_changeable", **c})
1214
+ return out
1215
+
1216
+
1217
+ # ---------------------------------------------------------------- 远程 H5 抓取(--fetch-url)
1218
+
1219
+
1220
+ def fetch_remote_h5(url: str, max_scripts: int = 5):
1221
+ """抓取远程页面 + 同源 <script src>(最多 5 个),返回 [(名称, 文本)]。"""
1222
+ import urllib.parse
1223
+ import urllib.request
1224
+ from urllib.parse import urljoin, urlparse
1225
+
1226
+ headers = {"User-Agent": "Mozilla/5.0 (HarmonyOS migration analyzer)"}
1227
+
1228
+ def _get(u: str) -> str:
1229
+ req = urllib.request.Request(u, headers=headers)
1230
+ with urllib.request.urlopen(req, timeout=20) as r:
1231
+ return r.read(2 * 1024 * 1024).decode("utf-8", errors="ignore")
1232
+
1233
+ page = _get(url)
1234
+ texts = [(url, page)]
1235
+ base = urlparse(url)
1236
+ for src in re.findall(r"""<script[^>]+src=["']([^"']+)["']""", page)[:max_scripts]:
1237
+ absu = urljoin(url, src)
1238
+ if urlparse(absu).netloc != base.netloc:
1239
+ continue
1240
+ try:
1241
+ texts.append((absu, _get(absu)))
1242
+ except Exception:
1243
+ continue
1244
+ return texts
1245
+
1246
+
1247
+ def merge_remote_h5(rep, url: str):
1248
+ """抓取远程 H5 并把信号并入报告(styles/handler_calls/sdk_versions + 重算 handler_diff)。"""
1249
+ texts = fetch_remote_h5(url)
1250
+ styles, handlers = [], {}
1251
+ for fname, text in texts:
1252
+ st, hd = scan_h5_text(text, fname)
1253
+ styles.extend(st)
1254
+ for k, names in hd.items():
1255
+ handlers.setdefault(k, set()).update(names)
1256
+ remote_handlers = {k: sorted(v) for k, v in handlers.items()}
1257
+ rep["remote_h5"] = {"url": url, "files": [f for f, _ in texts],
1258
+ "styles": styles, "handler_calls": remote_handlers,
1259
+ "sdk_versions": detect_h5_sdk_versions(texts)}
1260
+ seen = {(s["marker"], s["file"]) for s in rep["h5_bridge_styles"]}
1261
+ for s in styles:
1262
+ if (s["marker"], s["file"]) not in seen:
1263
+ rep["h5_bridge_styles"].append(s)
1264
+ for k, names in remote_handlers.items():
1265
+ cur = set(rep["h5_handler_calls"].get(k, []))
1266
+ rep["h5_handler_calls"][k] = sorted(cur | set(names))
1267
+ # sdk versions 合并
1268
+ merged_sdk = {v["sdk"]: v for v in rep.get("h5_sdk_versions", [])}
1269
+ for v in rep["remote_h5"]["sdk_versions"]:
1270
+ merged_sdk.setdefault(v["sdk"], v)
1271
+ rep["h5_sdk_versions"] = list(merged_sdk.values())
1272
+ # 重算 handler_diff(加入远程调用点)
1273
+ native_reg = {h["name"] for h in rep["bridge_methods"]["register_handlers"]}
1274
+ calls_all = set(rep["h5_handler_calls"].get("callHandler", []))
1275
+ sdk_internal = sorted(n for n in calls_all if n.startswith("_"))
1276
+ calls = calls_all - set(sdk_internal)
1277
+ native_ds = ({m["method"] for e in rep["bridge_methods"]["javascript_interfaces"] for m in e["methods"]}
1278
+ | {m["method"] for x in rep["bridge_methods"]["ji_classes_without_namespace"]
1279
+ for m in x["methods"]})
1280
+ ds_missing = [n for n in rep["h5_handler_calls"].get("dsbridge_call", [])
1281
+ if not n.startswith("_") and n.rsplit(".", 1)[-1] not in native_ds and n not in native_ds]
1282
+ rep["bridge_methods"]["handler_diff"] = {
1283
+ "h5_call_no_native_register": sorted(calls - native_reg),
1284
+ "h5_dsbridge_call_no_native_method": ds_missing,
1285
+ "native_registered_h5_never_calls": sorted(native_reg - calls),
1286
+ "sdk_internal_h5_calls": sdk_internal,
1287
+ }
1288
+ for n in rep["bridge_methods"]["handler_diff"]["h5_call_no_native_register"]:
1289
+ msg = f"远程 H5 callHandler 调用但 Native 未注册:{n}(需人工确认)"
1290
+ if msg not in rep["summary"]["risk_flags"]:
1291
+ rep["summary"]["risk_flags"].append(msg)
1292
+
1293
+
1294
+ # ---------------------------------------------------------------- 桥接回路自测页
1295
+
1296
+ TEST_PAGE_TEMPLATE = r"""<!DOCTYPE html>
1297
+ <html>
1298
+ <head>
1299
+ <meta charset="utf-8">
1300
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1301
+ <title>桥接回路自测页</title>
1302
+ <style>
1303
+ body{font-family:monospace;font-size:13px;padding:8px}
1304
+ #log{white-space:pre-wrap;word-break:break-all}
1305
+ button{margin:4px 0;padding:6px 12px}
1306
+ </style>
1307
+ </head>
1308
+ <body>
1309
+ <h4>桥接回路自测页(scan_web_jsbridge.py 生成,供鸿蒙迁移验收)</h4>
1310
+ <div>UA: <span id="ua"></span></div>
1311
+ <button onclick="location.reload()">重新执行</button>
1312
+ <pre id="log"></pre>
1313
+ <script>
1314
+ var CASES = __PAYLOAD__;
1315
+ var pass = 0, fail = 0;
1316
+ var elLog = document.getElementById('log');
1317
+ function log(msg, ok) {
1318
+ if (ok === true) pass++;
1319
+ else if (ok === false) fail++;
1320
+ elLog.textContent += (ok === true ? '[PASS] ' : ok === false ? '[FAIL] ' : '[INFO] ') + msg + '\n';
1321
+ }
1322
+ window.onerror = function (m) { log('window.onerror: ' + m, false); return false; };
1323
+ document.getElementById('ua').textContent = navigator.userAgent;
1324
+
1325
+ function runNs() {
1326
+ log('\n==== 原生命名空间(addJavascriptInterface → javaScriptProxy)====');
1327
+ CASES.ns_calls.forEach(function (c) {
1328
+ try {
1329
+ var obj = window[c.ns];
1330
+ if (!obj) { log(c.ns + ' 命名空间不存在(javaScriptProxy name 未对齐或未注入)', false); return; }
1331
+ if (typeof obj[c.method] !== 'function') { log(c.ns + '.' + c.method + ' 不在 methodList 白名单', false); return; }
1332
+ var r = obj[c.method]('{"__test":true}');
1333
+ log(c.ns + '.' + c.method + ' -> ' + r, true);
1334
+ } catch (e) { log(c.ns + '.' + c.method + ' 异常: ' + e, false); }
1335
+ });
1336
+ }
1337
+
1338
+ function runWjb() {
1339
+ log('\n==== WebViewJavascriptBridge(lzyzsd 协议)====');
1340
+ CASES.wjb_names.forEach(function (n) {
1341
+ try {
1342
+ window.WebViewJavascriptBridge.callHandler(n, { __test: true }, function (r) {
1343
+ log('callHandler(' + n + ') 回调 -> ' + JSON.stringify(r), true);
1344
+ });
1345
+ } catch (e) { log('callHandler(' + n + ') 异常: ' + e, false); }
1346
+ });
1347
+ }
1348
+
1349
+ function runDs() {
1350
+ log('\n==== DSBridge 协议 ====');
1351
+ CASES.ds_names.forEach(function (n) {
1352
+ try {
1353
+ var ds = window.dsbridge || window.dsBridge;
1354
+ if (!ds) { log('dsbridge/dsBridge 全局对象不存在', false); return; }
1355
+ var r = ds.call(n, { __test: true });
1356
+ log('ds.call(' + n + ') -> ' + r, true);
1357
+ } catch (e) { log('ds.call(' + n + ') 异常: ' + e, false); }
1358
+ });
1359
+ }
1360
+
1361
+ setTimeout(function () {
1362
+ runNs();
1363
+ if (CASES.wjb_names.length) {
1364
+ if (window.WebViewJavascriptBridge) runWjb();
1365
+ else {
1366
+ log('WebViewJavascriptBridge 未就绪,等待 WebViewJavascriptBridgeReady 事件…');
1367
+ var done = false;
1368
+ document.addEventListener('WebViewJavascriptBridgeReady', function () {
1369
+ if (!done) { done = true; runWjb(); }
1370
+ }, false);
1371
+ setTimeout(function () {
1372
+ if (!done) { done = true; log('WebViewJavascriptBridgeReady 超时未触发(协议层缺失,走决策树)', false); }
1373
+ }, 3000);
1374
+ }
1375
+ }
1376
+ if (CASES.ds_names.length) runDs();
1377
+ log('\n==== 汇总 ====');
1378
+ log('PASS=' + pass + ' FAIL=' + fail + '(FAIL>0 时对照报告与分诊表逐项排查)');
1379
+ }, 300);
1380
+ </script>
1381
+ </body>
1382
+ </html>
1383
+ """
1384
+
1385
+
1386
+ def gen_bridge_test_page(rep) -> str:
1387
+ """按报告清单生成桥接回路自测页(命名空间方法 / lzyzsd handler / DSBridge 方法)。"""
1388
+ bm = rep["bridge_methods"]
1389
+ ns_calls = [{"ns": e["namespace"], "method": m["method"]}
1390
+ for e in bm["javascript_interfaces"] for m in e["methods"]]
1391
+ wjb_names = {h["name"] for h in bm["register_handlers"]}
1392
+ wjb_names |= set(rep.get("h5_handler_calls", {}).get("callHandler", []))
1393
+ ds_names = ({h["name"] for h in bm.get("dsbridge_has_methods", [])} |
1394
+ set(rep.get("h5_handler_calls", {}).get("dsbridge_call", [])))
1395
+ payload = json.dumps({"ns_calls": ns_calls, "wjb_names": sorted(wjb_names),
1396
+ "ds_names": sorted(ds_names)}, ensure_ascii=False)
1397
+ return TEST_PAGE_TEMPLATE.replace("__PAYLOAD__", payload)
1398
+
1399
+
1400
+ # ---------------------------------------------------------------- 汇总
1401
+
1402
+
1403
+ def build_report(root: Path):
1404
+ dep_text, dep_files = collect_dep_text(root)
1405
+ src_infos = []
1406
+ for p in iter_files(root, lambda x: x.suffix in SRC_EXTS):
1407
+ t = read_text(p)
1408
+ if t is not None:
1409
+ src_infos.append((p, t))
1410
+
1411
+ containers = detect_kinds(CONTAINERS, dep_text, src_infos, root)
1412
+ for hit in scan_layout_webviews(root):
1413
+ existing = next((c for c in containers if c["key"] == hit["kind"]), None)
1414
+ ev = {"file": hit["file"], "line": hit["line"], "snippet": hit["snippet"]}
1415
+ if existing is None:
1416
+ spec = next((d for d in CONTAINERS if d["key"] == hit["kind"]), None)
1417
+ if spec:
1418
+ containers.append({**spec,
1419
+ "evidence": {"gradle": [], "imports": [], "symbols": [], "xml": [ev]}})
1420
+ else:
1421
+ existing["evidence"].setdefault("xml", []).append(ev)
1422
+ bridges = detect_kinds(BRIDGES, dep_text, src_infos, root)
1423
+ ji_methods = extract_ji_methods(src_infos, root)
1424
+ namespaces, leftovers = extract_namespaces(src_infos, ji_methods, root)
1425
+ reg_handlers, call_handlers, ds_has = extract_handlers(src_infos, root)
1426
+ schemes = extract_schemes(src_infos, root)
1427
+ settings, risk = extract_settings(src_infos, root)
1428
+ chrome_features = extract_chrome_features(src_infos, root)
1429
+ local_entries = extract_local_entries(src_infos, root)
1430
+ injected_js = extract_injected_js(src_infos, root)
1431
+ service_webviews = detect_service_webviews(src_infos, root)
1432
+ asset_loader_paths = extract_asset_loader_paths(src_infos, root)
1433
+ deep_links = extract_deep_links(src_infos, root)
1434
+ cookies = extract_cookies(src_infos, root)
1435
+ h5_assets, h5_styles, h5_handlers, h5_texts = scan_h5_assets(root)
1436
+ h5_sdk_versions = detect_h5_sdk_versions(h5_texts)
1437
+ fork_extensions = extract_fork_extensions(src_infos, root) if any(
1438
+ b["key"] == "lzyzsd_jsbridge" for b in bridges) else []
1439
+
1440
+ # WVJB 家族风格消歧:lzyzsd 的 H5 SDK 内含 WVJBCallbacks(iOS 兼容回退,js 第 222 行),
1441
+ # 必须以 ready 事件 / iframe 队列通道为准,否则会把 lzyzsd 工程误推给 iOS 协议库
1442
+ markers = {s["marker"] for s in h5_styles}
1443
+ wvjb_style = None
1444
+ if "WebViewJavascriptBridgeReady" in markers or "__queue_message__" in markers:
1445
+ wvjb_style = {"style": "lzyzsd_android",
1446
+ "meaning": "lzyzsd Android 系(WebViewJavascriptBridgeReady 事件 + iframe 队列通道)确定;"
1447
+ "WVJBCallbacks 仅为 SDK 内 iOS 兼容回退,不代表 iOS 风格 setup → "
1448
+ "优先 @a_zwj/netweb 或自写 shim;@yue/@jjr 需适配"}
1449
+ elif "WVJBCallbacks" in markers:
1450
+ wvjb_style = {"style": "ios",
1451
+ "meaning": "iOS 系 WVJB setup(WVJBCallbacks 桥初始化,无 ready 事件依赖)→ "
1452
+ "@yue/webview_javascript_bridge / @jjr/wvjb 契合,基本零改动"}
1453
+
1454
+ # Native/H5 handler 名单 diff(防迁移遗漏;动态拼接名会误报,需人工复核)
1455
+ # `_` 前缀为桥 SDK 内部协议方法(_closePage/_hasNativeMethod/_disableJavascriptAlertBoxSafetyTimeout 等),
1456
+ # 不参与遗漏判定(真实工程实证:wendux WVJB)
1457
+ native_reg = {h["name"] for h in reg_handlers}
1458
+ h5_calls_all = set(h5_handlers.get("callHandler", []))
1459
+ sdk_internal_calls = sorted(n for n in h5_calls_all if n.startswith("_"))
1460
+ h5_calls = h5_calls_all - set(sdk_internal_calls)
1461
+ native_ds_methods = {m["method"] for e in namespaces for m in e["methods"]} | {
1462
+ m["method"] for x in leftovers for m in x["methods"]}
1463
+ ds_missing = [n for n in h5_handlers.get("dsbridge_call", [])
1464
+ if not n.startswith("_") and n.rsplit(".", 1)[-1] not in native_ds_methods
1465
+ and n not in native_ds_methods]
1466
+ handler_diff = {
1467
+ "h5_call_no_native_register": sorted(h5_calls - native_reg),
1468
+ "h5_dsbridge_call_no_native_method": ds_missing,
1469
+ "native_registered_h5_never_calls": sorted(native_reg - h5_calls),
1470
+ "sdk_internal_h5_calls": sdk_internal_calls,
1471
+ }
1472
+ if handler_diff["h5_call_no_native_register"]:
1473
+ risk.append("H5 callHandler 调用但 Native 未 registerHandler:"
1474
+ + ", ".join(handler_diff["h5_call_no_native_register"][:10])
1475
+ + "(可能是动态注册/字符串拼接名,需人工确认)")
1476
+ if ds_missing:
1477
+ risk.append("H5 dsbridge.call 调用但 Native 无对应 @JavascriptInterface 方法:"
1478
+ + ", ".join(ds_missing[:10]))
1479
+
1480
+ # AgentWeb 底层内核判断
1481
+ for c in containers:
1482
+ if c["key"] == "agentweb":
1483
+ c["hint"] += "(本工程同时检测到 X5,内核可能为 X5)" if any(
1484
+ x["key"] == "tencent_x5" for x in containers) else "(未检测到 X5,内核为系统 WebView)"
1485
+
1486
+ hints = []
1487
+ for c in containers:
1488
+ hints.append({"target": f"容器:{c['key']}", "hint": c["hint"]})
1489
+ for b in bridges:
1490
+ hints.append({"target": f"桥:{b['key']}", "hint": b["hint"]})
1491
+
1492
+ bridge_keys = [b["key"] for b in bridges]
1493
+ ohpm_candidates = build_ohpm_candidates(bridge_keys)
1494
+ for cand in ohpm_candidates:
1495
+ if cand["source"] == "protocol_compat":
1496
+ hints.append({"target": f"桥:{cand['detected']}",
1497
+ "hint": f"优先评估 ohpm 协议兼容库 {cand['name']}({cand['h5_impact']}):{cand['note']}"})
1498
+ for f in chrome_features:
1499
+ hints.append({"target": f"能力:{f['feature']}", "hint": f["hint"]})
1500
+ style_hint_skip = {"WVJBCallbacks", "WebViewJavascriptBridgeReady"} if wvjb_style else set()
1501
+ if injected_js:
1502
+ hints.append({"target": f"注入JS:{len(injected_js)}处",
1503
+ "hint": "document-start/onPageEnd 注入清单见 injected_js;ArkWeb 用 .javaScriptOnDocumentStart()"
1504
+ "(API 12+)或 javaScriptProxy 常驻 + onPageEnd runJavaScript 补注入,保持注入顺序"})
1505
+ for v in h5_sdk_versions:
1506
+ hints.append({"target": f"H5SDK:{v['sdk']}" + (f"@{v['version']}" if v["version"] else ""),
1507
+ "hint": f"识别到 {v['sdk']}({', '.join(v['files'][:3])})→ 候选库契合度按此版本核对"})
1508
+ for s in h5_styles:
1509
+ if s["marker"] in style_hint_skip:
1510
+ continue
1511
+ hints.append({"target": f"H5协议:{s['marker']}", "hint": s["meaning"]})
1512
+ if wvjb_style:
1513
+ hints.append({"target": f"WVJB风格:{wvjb_style['style']}", "hint": wvjb_style["meaning"]})
1514
+ if any(b["key"] == "wendux_wvjb" for b in bridges) and any(b["key"] == "dsbridge" for b in bridges):
1515
+ hints.append({"target": "同族双检出:wendux_wvjb+dsbridge",
1516
+ "hint": "wendux WVJB 自带 hasJavascriptMethod(DSBridge 前身 API 演进)→ 双检出属同族;"
1517
+ "以 wendux 单方法 notice 通道处置为准,若另有 DWebView/addJavascriptObject 才按 DSBridge 处置"})
1518
+ if fork_extensions:
1519
+ keys = ", ".join(x["key"] for x in fork_extensions)
1520
+ hints.append({"target": f"lzyzsd增强fork:{keys}",
1521
+ "hint": "检测到同源 fork 私有扩展(persistentCallbacks/origin 白名单/注入防抖)→ "
1522
+ "@a_zwj/netweb 等现成库大概率不覆盖,优先自写 shim(§4.3 选项②),"
1523
+ "协议以工程内 WebViewJavascriptBridge.js 为准"})
1524
+ ext_jumps = {s["scheme"].lower() for s in schemes if s.get("scheme") in EXTERNAL_JUMP_SCHEMES}
1525
+ if ext_jumps:
1526
+ hints.append({"target": f"外跳scheme:{','.join(sorted(ext_jumps))}",
1527
+ "hint": "三方 App 外跳(非桥协议)→ 鸿蒙用 context.openLink()/startAbility(Want URI) 拉起,"
1528
+ "可用 canOpenLink 预判;勿误当桥应答处理"})
1529
+ for s in service_webviews:
1530
+ risk.append(f"Service 内嵌 WebView({s['klass']} @ {s['file']}:{s['line']}):"
1531
+ "鸿蒙 ArkWeb 必须挂 UI 组件树,后台 Service 无法渲染 → 重构为窗口化页面/卡片或前台任务")
1532
+ hints.append({"target": f"Service内WebView:{s['klass']}",
1533
+ "hint": "结构性迁移阻塞:WebView 渲染依赖 UI 树;Service 场景改为独立页面/窗口、沉浸式卡片或前台任务 + 页面承载"})
1534
+ for a in asset_loader_paths:
1535
+ hints.append({"target": f"AssetLoader:{a['path']}",
1536
+ "hint": f"路径 '{a['path']}' 经 appassets.androidplatform.net 提供 → 迁移映射 rawfile 目录或 onInterceptRequest 应答"})
1537
+ for d in deep_links:
1538
+ hints.append({"target": "intent深链", "hint": f"{d['url'][:80]} → ArkWeb onLoadIntercept 转 Want(uri/action/参数),canOpenLink 预判"})
1539
+ for ck in cookies:
1540
+ hints.append({"target": f"Cookie:{ck['key']}",
1541
+ "hint": f"setCookie({ck['url'][:60]}, {ck['key']}=...) → webview.WebCookieManager.configCookie 对齐域与键"})
1542
+ if any(s.get("match_style") for s in schemes):
1543
+ hints.append({"target": "scheme拦截:非桥模式",
1544
+ "hint": "shouldOverrideUrlLoading 为非桥拦截(host/query 参数比对=OAuth 回调/深链;"
1545
+ "Intent.ACTION_VIEW=全量外跳系统浏览器)→ ArkWeb 用 onLoadIntercept/onInterceptRequest "
1546
+ "按 host 匹配后放行、转 Want 或 context.openLink() 拉起浏览器,勿当桥应答处理"})
1547
+ if local_entries:
1548
+ hints.append({"target": f"本地H5入口:{len(local_entries)}处",
1549
+ "hint": "入口页与 assets 整目录迁 resources/rawfile(结构不变),src 用 $rawfile('...'),"
1550
+ "页内静态资源引用改 resource://rawfile/..."})
1551
+
1552
+ method_count = sum(len(e["methods"]) for e in namespaces) + sum(
1553
+ len(x["methods"]) for x in leftovers) + len(reg_handlers)
1554
+ risk = list(dict.fromkeys(risk)) # 同一风险多处命中只保留一条
1555
+
1556
+ return {
1557
+ "schema_version": 1,
1558
+ "project": root.name,
1559
+ "project_path": str(root),
1560
+ "scanned": {"sources": len(src_infos), "dep_files": dep_files},
1561
+ "summary": {
1562
+ "containers": [c["key"] for c in containers],
1563
+ "jsbridge": [b["key"] for b in bridges],
1564
+ "bridge_method_count": method_count,
1565
+ "risk_flags": risk,
1566
+ },
1567
+ "containers": [{"key": c["key"], "label": c["label"], "evidence": c["evidence"]}
1568
+ for c in containers],
1569
+ "jsbridge": [{"key": b["key"], "label": b["label"], "kind": b["kind"],
1570
+ "evidence": b["evidence"]} for b in bridges],
1571
+ "bridge_methods": {
1572
+ "javascript_interfaces": namespaces,
1573
+ "ji_classes_without_namespace": leftovers,
1574
+ "register_handlers": reg_handlers,
1575
+ "native_call_handlers": call_handlers,
1576
+ "dsbridge_has_methods": ds_has,
1577
+ "handler_diff": handler_diff,
1578
+ },
1579
+ "url_schemes": schemes,
1580
+ "web_settings": settings,
1581
+ "chrome_capabilities": chrome_features,
1582
+ "local_h5_entries": local_entries,
1583
+ "h5_assets": h5_assets,
1584
+ "h5_sdk_versions": h5_sdk_versions,
1585
+ "injected_js": injected_js,
1586
+ "background_webviews": service_webviews,
1587
+ "asset_loader_paths": asset_loader_paths,
1588
+ "deep_links": deep_links,
1589
+ "cookies": cookies,
1590
+ "h5_bridge_styles": h5_styles,
1591
+ "h5_wvjb_style": wvjb_style,
1592
+ "h5_handler_calls": h5_handlers,
1593
+ "lzyzsd_fork_extensions": fork_extensions,
1594
+ "ohpm_candidates": ohpm_candidates,
1595
+ "harmonyos_adaptation_hints": hints,
1596
+ }
1597
+
1598
+
1599
+ def render_md(rep) -> str:
1600
+ L = []
1601
+ L.append(f"# Web 容器 & JSBridge 识别报告 —— {rep['project']}")
1602
+ L.append("")
1603
+ L.append(f"- 扫描源码文件:{rep['scanned']['sources']},依赖清单:{len(rep['scanned']['dep_files'])} 个")
1604
+ L.append(f"- 容器结论:{', '.join(rep['summary']['containers']) or '未检出'}")
1605
+ L.append(f"- JSBridge 结论:{', '.join(rep['summary']['jsbridge']) or '未检出'}")
1606
+ L.append(f"- 桥接方法(含 handler)总数:{rep['summary']['bridge_method_count']}")
1607
+ L.append("")
1608
+ if rep["summary"]["risk_flags"]:
1609
+ L.append("## 0. 风险基线")
1610
+ for r in rep["summary"]["risk_flags"]:
1611
+ L.append(f"- ⚠️ {r}")
1612
+ L.append("")
1613
+ L.append("## 1. Web 容器(系统 or 三方)")
1614
+ for c in rep["containers"]:
1615
+ L.append(f"### {c['label']} (`{c['key']}`)")
1616
+ for kind in ("gradle", "imports", "symbols", "xml"):
1617
+ for e in c["evidence"].get(kind, []):
1618
+ if isinstance(e, dict):
1619
+ L.append(f"- [{kind}] {e['file']}:{e.get('line') or '-'} `{e['snippet']}`")
1620
+ else:
1621
+ L.append(f"- [{kind}] {e}")
1622
+ L.append("")
1623
+ L.append("## 2. JSBridge 机制(原生 or 三方)")
1624
+ for b in rep["jsbridge"]:
1625
+ L.append(f"### {b['label']}({'三方' if b['kind'] == 'third_party' else '原生'})")
1626
+ for kind in ("gradle", "imports", "symbols"):
1627
+ for e in b["evidence"][kind]:
1628
+ if isinstance(e, dict):
1629
+ L.append(f"- [{kind}] {e['file']}:{e.get('line') or '-'} `{e['snippet']}`")
1630
+ else:
1631
+ L.append(f"- [{kind}] {e}")
1632
+ L.append("")
1633
+ if rep.get("lzyzsd_fork_extensions"):
1634
+ L.append("### ⚠️ lzyzsd 增强 fork 私有扩展(现成 ohpm 库不覆盖)")
1635
+ for x in rep["lzyzsd_fork_extensions"]:
1636
+ h0 = x["hits"][0]
1637
+ L.append(f"- **{x['key']}**({len(x['hits'])} 处,首处 {h0['file']}:{h0['line']})`{h0['snippet']}`")
1638
+ L.append("")
1639
+ L.append("## 3. 桥接方法清单")
1640
+ bm = rep["bridge_methods"]
1641
+ if bm["javascript_interfaces"]:
1642
+ L.append("### 注入命名空间 → @JavascriptInterface 方法")
1643
+ for e in bm["javascript_interfaces"]:
1644
+ conf = {"high": "✅", "guess": "❓按唯一类推断", "unresolved": "❗未解析"}.get(e["confidence"], "")
1645
+ usages = e.get("usages") or []
1646
+ use_note = f"({len(usages)} 处使用)" if len(usages) > 1 else ""
1647
+ L.append(f"- `{e['namespace']}` ← {e['class'] or e['class_simple'] or '?'} "
1648
+ f"({e['api']} @ {e['file']}:{e['line']}){conf}{use_note}")
1649
+ for m in e["methods"]:
1650
+ L.append(f" - `{m['method']}({m['params']})` {m['file']}:{m['line']}")
1651
+ if bm["ji_classes_without_namespace"]:
1652
+ L.append("### 含 @JavascriptInterface 但未关联到注入点的类(人工确认是否反射注册)")
1653
+ for e in bm["ji_classes_without_namespace"]:
1654
+ L.append(f"- {e['class']}:{', '.join(m['method'] for m in e['methods'])}")
1655
+ if bm["register_handlers"]:
1656
+ L.append("### registerHandler(H5→Native handler 名,lzyzsd 等)")
1657
+ for h in bm["register_handlers"]:
1658
+ L.append(f"- `{h['name']}` {h['file']}:{h['line']}")
1659
+ if bm["native_call_handlers"]:
1660
+ L.append("### callHandler(Native→JS handler 名)")
1661
+ for h in bm["native_call_handlers"]:
1662
+ L.append(f"- `{h['name']}` {h['file']}:{h['line']}")
1663
+ if bm["dsbridge_has_methods"]:
1664
+ L.append("### DSBridge hasJavascriptMethod 探测的方法")
1665
+ for h in bm["dsbridge_has_methods"]:
1666
+ L.append(f"- `{h['name']}` {h['file']}:{h['line']}")
1667
+ L.append("")
1668
+ if rep["url_schemes"]:
1669
+ L.append("## 4. URL scheme 拦截")
1670
+ for s in rep["url_schemes"]:
1671
+ extra = f"({s['match_style']})" if s.get("match_style") else ""
1672
+ L.append(f"- {s['file']}:{s['line']} scheme=`{s['scheme']}`{extra} `{s['snippet']}`")
1673
+ L.append("")
1674
+ L.append("## 5. WebSettings / 安全基线")
1675
+ if rep["web_settings"]:
1676
+ for k, v in rep["web_settings"].items():
1677
+ vals = {x["value"] for x in v}
1678
+ L.append(f"- `{k}`: {', '.join(sorted(vals))}({len(v)} 处,首处 {v[0]['file']}:{v[0]['line']})")
1679
+ else:
1680
+ L.append("- 未检测到显式 WebSettings 调用")
1681
+ L.append("")
1682
+ if rep.get("chrome_capabilities"):
1683
+ L.append("## 6. 容器能力(ChromeClient / 资源拦截 / document-start / 生命周期 / Cookie / 调试)")
1684
+ for f in rep["chrome_capabilities"]:
1685
+ first = f["hits"][0]
1686
+ L.append(f"- **{f['feature']}**({len(f['hits'])} 处,首处 {first['file']}:{first['line']}):{f['hint']}")
1687
+ L.append("")
1688
+ if rep.get("background_webviews") or rep.get("asset_loader_paths") or rep.get("deep_links") or rep.get("cookies"):
1689
+ L.append("## 6b. 专项信号(Service / AssetLoader / 深链 / Cookie)")
1690
+ for s in rep.get("background_webviews", []):
1691
+ L.append(f"- ⚠️ **Service 内嵌 WebView** `{s['klass']}` {s['file']}:{s['line']}({s['service_base']})")
1692
+ for a in rep.get("asset_loader_paths", []):
1693
+ L.append(f"- AssetLoader 路径 `{a['path']}` {a['file']}:{a['line']}")
1694
+ for d in rep.get("deep_links", []):
1695
+ L.append(f"- intent 深链 `{d['url'][:120]}` {d['file']}:{d['line']}")
1696
+ for ck in rep.get("cookies", []):
1697
+ L.append(f"- Cookie `{ck['key']}` @ `{ck['url'][:80]}` {ck['file']}:{ck['line']}")
1698
+ L.append("")
1699
+ if rep.get("local_h5_entries"):
1700
+ L.append("## 7. 本地 H5 入口(rawfile 迁移清单)")
1701
+ for e in rep["local_h5_entries"]:
1702
+ L.append(f"- `{e['url']}` {e['file']}:{e['line']} → `Web({{ src: {e['harmony_src']} }})`;{e['note']}")
1703
+ L.append("")
1704
+ if rep.get("injected_js"):
1705
+ L.append("## 8. 注入脚本清单(document-start / onPageEnd 迁移)")
1706
+ for j in rep["injected_js"]:
1707
+ L.append(f"- {j['file']}:{j['line']} [{j['api']}] `{j['script'][:140]}`")
1708
+ L.append("")
1709
+ if rep["h5_assets"] or rep.get("h5_bridge_styles") or rep.get("h5_handler_calls"):
1710
+ L.append("## 9. H5 侧桥资产与协议风格")
1711
+ for h in rep["h5_assets"]:
1712
+ L.append(f"- {h['file']} — {h['bridge']}")
1713
+ if rep.get("h5_bridge_styles"):
1714
+ L.append("")
1715
+ L.append("### 协议风格标记(决定 ohpm 候选库契合度)")
1716
+ for s in rep["h5_bridge_styles"]:
1717
+ L.append(f"- `{s['marker']}` {s['file']}:{s['line']} — {s['meaning']}")
1718
+ if rep.get("h5_wvjb_style"):
1719
+ L.append(f"- **消歧结论:`{rep['h5_wvjb_style']['style']}`** — {rep['h5_wvjb_style']['meaning']}")
1720
+ if rep.get("h5_sdk_versions"):
1721
+ L.append("")
1722
+ L.append("### H5 SDK 版本")
1723
+ for v in rep["h5_sdk_versions"]:
1724
+ ver = f" @{v['version']}" if v.get("version") else ""
1725
+ L.append(f"- **{v['sdk']}{ver}**({', '.join(v['files'][:3])})")
1726
+ h5h = rep.get("h5_handler_calls") or {}
1727
+ if any(h5h.values()):
1728
+ L.append("")
1729
+ L.append("### H5 侧 handler 调用点")
1730
+ for kind, names in h5h.items():
1731
+ if names:
1732
+ L.append(f"- {kind}: {', '.join(names)}")
1733
+ if rep.get("remote_h5"):
1734
+ r = rep["remote_h5"]
1735
+ L.append("")
1736
+ L.append(f"### 远程 H5(--fetch-url)")
1737
+ L.append(f"- url: {r['url']}")
1738
+ L.append(f"- files: {', '.join(r['files'])}")
1739
+ diff = (rep["bridge_methods"] or {}).get("handler_diff") or {}
1740
+ if diff.get("h5_call_no_native_register") or diff.get("h5_dsbridge_call_no_native_method"):
1741
+ L.append("")
1742
+ L.append("### ⚠️ Native/H5 名单 diff(疑似遗漏,需人工确认是否动态注册/拼接)")
1743
+ if diff.get("h5_call_no_native_register"):
1744
+ L.append(f"- H5 callHandler 调用但 Native 未注册:{', '.join(diff['h5_call_no_native_register'])}")
1745
+ if diff.get("h5_dsbridge_call_no_native_method"):
1746
+ L.append(f"- H5 dsbridge.call 调用但 Native 无对应方法:{', '.join(diff['h5_dsbridge_call_no_native_method'])}")
1747
+ L.append("")
1748
+ L.append("## 10. 鸿蒙适配提示(Phase 2 输入)")
1749
+ for h in rep["harmonyos_adaptation_hints"]:
1750
+ L.append(f"- **{h['target']}**:{h['hint']}")
1751
+ L.append("")
1752
+ if rep.get("ohpm_candidates"):
1753
+ L.append("## 11. ohpm 鸿蒙替代库候选(实证映射,2026-10 核验)")
1754
+ L.append("")
1755
+ L.append("决策优先级:**协议兼容库(H5 零改动)→ 自写兼容 shim(H5 零改动)→ H5 改造收敛官方 javaScriptProxy(最稳)**")
1756
+ L.append("")
1757
+ impact_label = {"zero_change": "✅ H5 零改动", "verify": "⚠️ 需实测协议对齐",
1758
+ "h5_must_change": "❌ H5 必须改"}
1759
+ for c in rep["ohpm_candidates"]:
1760
+ tag = "(通用备选,H5 可改造时)" if c["detected"] == "(通用备选)" else f"(针对 桥:{c['detected']})"
1761
+ L.append(f"- **{c['name']}** {tag} — {impact_label.get(c['h5_impact'], c['h5_impact'])},{c['license']}")
1762
+ L.append(f" - {c['note']}")
1763
+ L.append("")
1764
+ L.append("> 版本与维护度请用 `python3 scan_web_jsbridge.py --search-ohpm <关键词>` 在线刷新;"
1765
+ "采库前下载 .har 解包读 README 核对协议细节。")
1766
+ L.append("")
1767
+ L.append("> 本报告为正则启发式结论,每条均带 file:line 证据,使用前请逐条复核。")
1768
+ return "\n".join(L)
1769
+
1770
+
1771
+ def render_html(rep) -> str:
1772
+ """自包含 HTML 报告(零外部依赖、零 JS,可直接浏览器打开或随报告归档)。"""
1773
+ e = _html.escape
1774
+
1775
+ def badge(text, cls):
1776
+ return f'<span class="bdg bdg-{cls}">{e(text)}</span>'
1777
+
1778
+ CONF = {"high": ("✅ high", "ok"), "guess": ("❓ guess", "warn"), "unresolved": ("❗ unresolved", "bad")}
1779
+ IMPACT = {"zero_change": ("✅ H5 零改动", "ok"), "verify": ("⚠️ 需实测", "warn"),
1780
+ "h5_must_change": ("❌ H5 必须改", "bad")}
1781
+ now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1782
+
1783
+ L = []
1784
+ L.append('<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">')
1785
+ L.append('<meta name="viewport" content="width=device-width,initial-scale=1">')
1786
+ L.append(f"<title>Web 容器 &amp; JSBridge 识别报告 — {e(rep['project'])}</title>")
1787
+ L.append("""<style>
1788
+ :root{--ink:#1c2333;--sub:#5b6478;--line:#e3e7ef;--bg:#f5f7fb;--card:#fff;
1789
+ --ok:#0a7d33;--okbg:#e6f6ec;--warn:#9a6200;--warnbg:#fdf3e0;--bad:#b3261e;--badbg:#fcebea;
1790
+ --blue:#1a56b0;--bluebg:#e8f0fd;--purple:#6b3fa0;--purplebg:#f1eafa}
1791
+ *{box-sizing:border-box}
1792
+ body{margin:0;font:14px/1.65 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--ink);background:var(--bg)}
1793
+ header{background:linear-gradient(135deg,#20305e,#3a5aa8);color:#fff;padding:22px 28px}
1794
+ header h1{margin:0 0 6px;font-size:20px}
1795
+ header .meta{opacity:.85;font-size:12.5px}
1796
+ main{max-width:1080px;margin:0 auto;padding:20px 24px 40px}
1797
+ .cardrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:-30px 0 18px}
1798
+ .card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px 16px;box-shadow:0 1px 4px rgba(16,24,40,.06)}
1799
+ .card .num{font-size:24px;font-weight:700}
1800
+ .card .lbl{color:var(--sub);font-size:12.5px}
1801
+ section{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px 20px;margin:14px 0}
1802
+ section>h2{margin:0 0 10px;font-size:16px;border-left:4px solid #3a5aa8;padding-left:9px}
1803
+ .risk{background:var(--badbg);border-color:#f0c8c5}
1804
+ .risk>h2{border-color:var(--bad)}
1805
+ .risk li{margin:3px 0}
1806
+ table{width:100%;border-collapse:collapse;font-size:13px;margin:6px 0}
1807
+ th,td{border:1px solid var(--line);padding:6px 9px;text-align:left;vertical-align:top}
1808
+ th{background:#f0f3f9;font-weight:600}
1809
+ code{background:#f0f3f9;border-radius:4px;padding:1px 5px;font-size:12.5px;word-break:break-all}
1810
+ .bdg{display:inline-block;border-radius:20px;padding:1px 9px;font-size:12px;font-weight:600;white-space:nowrap}
1811
+ .bdg-ok{color:var(--ok);background:var(--okbg)}
1812
+ .bdg-warn{color:var(--warn);background:var(--warnbg)}
1813
+ .bdg-bad{color:var(--bad);background:var(--badbg)}
1814
+ .bdg-info{color:var(--blue);background:var(--bluebg)}
1815
+ .bdg-tp{color:var(--purple);background:var(--purplebg)}
1816
+ details{margin:6px 0}
1817
+ details>summary{cursor:pointer;color:var(--blue);font-size:13px}
1818
+ .muted{color:var(--sub);font-size:12.5px}
1819
+ .ev td{font-size:12.5px}
1820
+ footer{max-width:1080px;margin:0 auto;padding:0 24px 30px;color:var(--sub);font-size:12px}
1821
+ </style></head><body>""")
1822
+
1823
+ L.append(f"<header><h1>Web 容器 &amp; JSBridge 识别报告 — {e(rep['project'])}</h1>"
1824
+ f"<div class='meta'>schema v{rep['schema_version']} · 源码 {rep['scanned']['sources']} 文件 · "
1825
+ f"依赖清单 {len(rep['scanned']['dep_files'])} 个 · 路径 <code>{e(rep['project_path'])}</code> · 生成于 {now}</div></header>")
1826
+
1827
+ s = rep["summary"]
1828
+ L.append("<main>")
1829
+ L.append("<div class='cardrow'>")
1830
+ L.append(f"<div class='card'><div class='num'>{len(s['containers'])}</div><div class='lbl'>Web 容器({e('、'.join(s['containers']) or '未检出')})</div></div>")
1831
+ L.append(f"<div class='card'><div class='num'>{len(s['jsbridge'])}</div><div class='lbl'>JSBridge 机制({e('、'.join(s['jsbridge']) or '未检出')})</div></div>")
1832
+ L.append(f"<div class='card'><div class='num'>{s['bridge_method_count']}</div><div class='lbl'>桥接方法(含 handler)</div></div>")
1833
+ L.append(f"<div class='card'><div class='num'>{len(s['risk_flags'])}</div><div class='lbl'>风险项</div></div>")
1834
+ L.append("</div>")
1835
+
1836
+ if s["risk_flags"]:
1837
+ L.append("<section class='risk'><h2>⚠️ 风险基线</h2><ul>")
1838
+ for r in s["risk_flags"]:
1839
+ L.append(f"<li>{e(r)}</li>")
1840
+ L.append("</ul></section>")
1841
+
1842
+ def ev_table(ev):
1843
+ rows = [("gradle", "-", e(g)) for g in ev.get("gradle", [])]
1844
+ rows += [("import", e(x.get("file", "-")), e(x.get("snippet", ""))) for x in ev.get("imports", [])]
1845
+ rows += [("symbol", e(f"{x.get('file')}:{x.get('line') or '-'}"), e(x.get("snippet", ""))) for x in ev.get("symbols", [])]
1846
+ rows += [("xml", e(f"{x.get('file')}:{x.get('line') or '-'}"), e(x.get("snippet", ""))) for x in ev.get("xml", [])]
1847
+ if not rows:
1848
+ return "<p class='muted'>无证据</p>"
1849
+ t = ["<table class='ev'><tr><th>类型</th><th>位置</th><th>内容</th></tr>"]
1850
+ for kind, loc, snip in rows:
1851
+ t.append(f"<tr><td>{kind}</td><td><code>{loc}</code></td><td><code>{snip}</code></td></tr>")
1852
+ t.append("</table>")
1853
+ return "".join(t)
1854
+
1855
+ L.append("<section><h2>1. Web 容器</h2>")
1856
+ for c in rep["containers"]:
1857
+ L.append(f"<details open><summary>{e(c['label'])} <code>{e(c['key'])}</code></summary>{ev_table(c['evidence'])}</details>")
1858
+ if not rep["containers"]:
1859
+ L.append("<p class='muted'>未检出</p>")
1860
+ L.append("</section>")
1861
+
1862
+ L.append("<section><h2>2. JSBridge 机制</h2>")
1863
+ for b in rep["jsbridge"]:
1864
+ kind_badge = badge("三方", "tp") if b["kind"] == "third_party" else badge("原生", "info")
1865
+ L.append(f"<details open><summary>{e(b['label'])} {kind_badge} <code>{e(b['key'])}</code></summary>{ev_table(b['evidence'])}</details>")
1866
+ if rep.get("lzyzsd_fork_extensions"):
1867
+ L.append("<div class='risk' style='border-radius:8px;padding:10px 14px'><b>⚠️ lzyzsd 增强 fork 私有扩展(现成 ohpm 库不覆盖,优先自写 shim)</b><ul>")
1868
+ for x in rep["lzyzsd_fork_extensions"]:
1869
+ h0 = x["hits"][0]
1870
+ L.append(f"<li><code>{e(x['key'])}</code>({len(x['hits'])} 处,首处 <code>{e(h0['file'])}:{h0['line']}</code>)</li>")
1871
+ L.append("</ul></div>")
1872
+ if not rep["jsbridge"]:
1873
+ L.append("<p class='muted'>未检出</p>")
1874
+ L.append("</section>")
1875
+
1876
+ bm = rep["bridge_methods"]
1877
+ L.append("<section><h2>3. 桥接方法清单</h2>")
1878
+ if bm["javascript_interfaces"]:
1879
+ L.append("<table><tr><th>命名空间</th><th>类</th><th>置信度</th><th>方法</th></tr>")
1880
+ for x in bm["javascript_interfaces"]:
1881
+ conf = CONF.get(x["confidence"], (x["confidence"], "info"))
1882
+ methods = "<br>".join(
1883
+ f"<code>{e(m['method'] + '(' + m['params'] + ')')}</code> <span class='muted'>{e(m['file'])}:{m['line']}</span>"
1884
+ for m in x["methods"]) or "<span class='muted'>(未解析到方法)</span>"
1885
+ usages = x.get("usages") or []
1886
+ use_note = f"<div class='muted'>{len(usages)} 处使用</div>" if len(usages) > 1 else ""
1887
+ L.append(f"<tr><td><b>{e(x['namespace'])}</b></td><td><code>{e(x['class'] or x['class_simple'] or '?')}</code>"
1888
+ f"<div class='muted'>{e(x['api'])} @ {e(x['file'])}:{x['line']}</div>{use_note}</td>"
1889
+ f"<td>{badge(*conf)}</td><td>{methods}</td></tr>")
1890
+ L.append("</table>")
1891
+ if bm["ji_classes_without_namespace"]:
1892
+ L.append("<details><summary>含 @JavascriptInterface 但未关联注入点的类(人工确认是否反射注册)</summary><ul>")
1893
+ for x in bm["ji_classes_without_namespace"]:
1894
+ L.append(f"<li><code>{e(x['class'])}</code>:{e('、'.join(m['method'] for m in x['methods']))}</li>")
1895
+ L.append("</ul></details>")
1896
+ for title, key in (("registerHandler(H5→Native)", "register_handlers"),
1897
+ ("callHandler(Native→JS)", "native_call_handlers"),
1898
+ ("DSBridge hasJavascriptMethod 探测", "dsbridge_has_methods")):
1899
+ if bm[key]:
1900
+ names = "、".join(f"<code>{e(h['name'])}</code> <span class='muted'>{e(h['file'])}:{h['line']}</span>" for h in bm[key])
1901
+ L.append(f"<p><b>{title}</b>:{names}</p>")
1902
+ diff = bm.get("handler_diff") or {}
1903
+ if diff.get("h5_call_no_native_register") or diff.get("h5_dsbridge_call_no_native_method"):
1904
+ L.append("<div class='risk' style='border-radius:8px;padding:10px 14px'><b>⚠️ Native/H5 名单 diff(疑似遗漏)</b><ul>")
1905
+ if diff.get("h5_call_no_native_register"):
1906
+ L.append(f"<li>H5 callHandler 调用但 Native 未注册:{'、'.join(f'<code>{e(n)}</code>' for n in diff['h5_call_no_native_register'])}</li>")
1907
+ if diff.get("h5_dsbridge_call_no_native_method"):
1908
+ L.append(f"<li>H5 dsbridge.call 调用但 Native 无对应方法:{'、'.join(f'<code>{e(n)}</code>' for n in diff['h5_dsbridge_call_no_native_method'])}</li>")
1909
+ L.append("</ul><span class='muted'>可能是动态注册/字符串拼接名,需人工确认</span></div>")
1910
+ if not (bm["javascript_interfaces"] or bm["register_handlers"] or bm.get("dsbridge_has_methods")):
1911
+ L.append("<p class='muted'>未检出桥接方法</p>")
1912
+ L.append("</section>")
1913
+
1914
+ if rep["url_schemes"]:
1915
+ L.append("<section><h2>4. URL scheme 拦截</h2><table><tr><th>位置</th><th>scheme / 模式</th><th>代码</th></tr>")
1916
+ for x in rep["url_schemes"]:
1917
+ style = badge(x["match_style"], "warn") if x.get("match_style") else e(x["scheme"])
1918
+ L.append(f"<tr><td><code>{e(x['file'])}:{x['line']}</code></td><td>{style}</td><td><code>{e(x['snippet'])}</code></td></tr>")
1919
+ L.append("</table></section>")
1920
+
1921
+ L.append("<section><h2>5. WebSettings / 安全基线</h2>")
1922
+ if rep["web_settings"]:
1923
+ L.append("<table><tr><th>配置</th><th>值</th><th>位置(首处)</th></tr>")
1924
+ for k, v in rep["web_settings"].items():
1925
+ vals = "、".join(sorted({str(x["value"]) for x in v}))
1926
+ L.append(f"<tr><td><code>{e(k)}</code></td><td><code>{e(vals)}</code></td>"
1927
+ f"<td><code>{e(v[0]['file'])}:{v[0]['line']}</code>({len(v)} 处)</td></tr>")
1928
+ L.append("</table>")
1929
+ else:
1930
+ L.append("<p class='muted'>未检测到显式 WebSettings 调用</p>")
1931
+ if rep.get("chrome_capabilities"):
1932
+ L.append("<h2 style='font-size:15px;margin-top:14px'>容器能力(ChromeClient / 资源拦截 / document-start / 生命周期)→ ArkWeb</h2><table><tr><th>能力</th><th>映射提示</th><th>首处</th></tr>")
1933
+ for f in rep["chrome_capabilities"]:
1934
+ h0 = f["hits"][0]
1935
+ L.append(f"<tr><td><code>{e(f['feature'])}</code>({len(f['hits'])} 处)</td><td>{e(f['hint'])}</td>"
1936
+ f"<td><code>{e(h0['file'])}:{h0['line']}</code></td></tr>")
1937
+ L.append("</table>")
1938
+ if rep.get("background_webviews") or rep.get("asset_loader_paths") or rep.get("deep_links") or rep.get("cookies"):
1939
+ L.append("<h2 style='font-size:15px;margin-top:14px'>专项信号(Service / AssetLoader / 深链 / Cookie)</h2><ul>")
1940
+ for sw in rep.get("background_webviews", []):
1941
+ L.append(f"<li>⚠️ <b>Service 内嵌 WebView</b> <code>{e(sw['klass'])}</code> "
1942
+ f"<code>{e(sw['file'])}:{sw['line']}</code>({e(sw['service_base'])})</li>")
1943
+ for a in rep.get("asset_loader_paths", []):
1944
+ L.append(f"<li>AssetLoader 路径 <code>{e(a['path'])}</code> <code>{e(a['file'])}:{a['line']}</code></li>")
1945
+ for d in rep.get("deep_links", []):
1946
+ L.append(f"<li>intent 深链 <code>{e(d['url'][:120])}</code> <code>{e(d['file'])}:{d['line']}</code></li>")
1947
+ for ck in rep.get("cookies", []):
1948
+ L.append(f"<li>Cookie <code>{e(ck['key'])}</code> @ <code>{e(ck['url'][:80])}</code> "
1949
+ f"<code>{e(ck['file'])}:{ck['line']}</code></li>")
1950
+ L.append("</ul>")
1951
+ L.append("</section>")
1952
+
1953
+ if rep.get("local_h5_entries"):
1954
+ L.append("<section><h2>6. 本地 H5 入口(rawfile 迁移清单)</h2><table><tr><th>Android 入口</th><th>鸿蒙 src</th><th>说明</th></tr>")
1955
+ for x in rep["local_h5_entries"]:
1956
+ L.append(f"<tr><td><code>{e(x['url'])}</code><div class='muted'>{e(x['file'])}:{x['line']}</div></td>"
1957
+ f"<td><code>{e(x['harmony_src'])}</code></td><td>{e(x['note'])}</td></tr>")
1958
+ L.append("</table></section>")
1959
+
1960
+ if rep["h5_assets"] or rep.get("h5_bridge_styles") or rep.get("h5_wvjb_style"):
1961
+ L.append("<section><h2>7. H5 侧桥资产与协议风格</h2><ul>")
1962
+ for h in rep["h5_assets"]:
1963
+ L.append(f"<li><code>{e(h['file'])}</code> — {e(h['bridge'])}</li>")
1964
+ L.append("</ul>")
1965
+ if rep.get("injected_js"):
1966
+ L.append("<h2 style='font-size:15px;margin-top:14px'>注入脚本清单(document-start / onPageEnd 迁移)</h2><table><tr><th>位置</th><th>API</th><th>脚本</th></tr>")
1967
+ for j in rep["injected_js"]:
1968
+ L.append(f"<tr><td><code>{e(j['file'])}:{j['line']}</code></td><td>{e(j['api'])}</td>"
1969
+ f"<td><code>{e(j['script'][:140])}</code></td></tr>")
1970
+ L.append("</table>")
1971
+ if rep.get("h5_sdk_versions"):
1972
+ L.append("<p><b>H5 SDK 版本:</b>" + "、".join(
1973
+ f"<code>{e(v['sdk'])}{('@' + e(v['version'])) if v.get('version') else ''}</code>"
1974
+ for v in rep["h5_sdk_versions"]) + "</p>")
1975
+ if rep.get("remote_h5"):
1976
+ L.append(f"<p><b>远程 H5(--fetch-url):</b><code>{e(rep['remote_h5']['url'])}</code>"
1977
+ f"({len(rep['remote_h5']['files'])} 个文件)</p>")
1978
+ if rep.get("h5_bridge_styles"):
1979
+ L.append("<table><tr><th>标记</th><th>含义</th><th>位置</th></tr>")
1980
+ for st in rep["h5_bridge_styles"]:
1981
+ L.append(f"<tr><td><code>{e(st['marker'])}</code></td><td>{e(st['meaning'])}</td>"
1982
+ f"<td><code>{e(st['file'])}:{st['line']}</code></td></tr>")
1983
+ L.append("</table>")
1984
+ if rep.get("h5_wvjb_style"):
1985
+ w = rep["h5_wvjb_style"]
1986
+ L.append(f"<p><b>消歧结论:</b>{badge(w['style'], 'info')} {e(w['meaning'])}</p>")
1987
+ h5h = rep.get("h5_handler_calls") or {}
1988
+ if any(h5h.values()):
1989
+ for kind, names in h5h.items():
1990
+ if names:
1991
+ L.append(f"<p><b>H5 {e(kind)}</b>:{'、'.join('<code>' + e(n) + '</code>' for n in names)}</p>")
1992
+ L.append("</section>")
1993
+
1994
+ if rep.get("ohpm_candidates"):
1995
+ L.append("<section><h2>8. ohpm 鸿蒙替代库候选(实证映射 2026-10)</h2>")
1996
+ L.append("<p class='muted'>决策优先级:<b>协议兼容库(H5 零改动)→ 自写兼容 shim → H5 改造收敛官方 javaScriptProxy</b></p>")
1997
+ L.append("<table><tr><th>ohpm 库</th><th>针对</th><th>H5 影响</th><th>说明</th></tr>")
1998
+ for c in rep["ohpm_candidates"]:
1999
+ imp = IMPACT.get(c["h5_impact"], (c["h5_impact"], "info"))
2000
+ L.append(f"<tr><td><b><code>{e(c['name'])}</code></b><div class='muted'>{e(c['license'])}</div></td>"
2001
+ f"<td>{e(c['detected'])}</td><td>{badge(*imp)}</td><td>{e(c['note'])}</td></tr>")
2002
+ L.append("</table></section>")
2003
+
2004
+ L.append("<section><h2>9. 鸿蒙适配提示(Phase 2 输入)</h2><table><tr><th>对象</th><th>提示</th></tr>")
2005
+ for h in rep["harmonyos_adaptation_hints"]:
2006
+ L.append(f"<tr><td><b>{e(h['target'])}</b></td><td>{e(h['hint'])}</td></tr>")
2007
+ L.append("</table></section>")
2008
+
2009
+ raw = json.dumps(rep, ensure_ascii=False, indent=2)
2010
+ L.append("<section><details><summary>📎 原始 JSON(供 AI 消费,schema_version="
2011
+ f"{rep['schema_version']})</summary><pre style='overflow:auto;max-height:420px;font-size:12px'>"
2012
+ f"{e(raw)}</pre></details></section>")
2013
+
2014
+ L.append("</main>")
2015
+ L.append(f"<footer>由 scan_web_jsbridge.py 生成 · 正则启发式结论,每条带 file:line 证据,使用前请逐条人工复核 · {now}</footer>")
2016
+ L.append("</body></html>")
2017
+ return "\n".join(L)
2018
+
2019
+
2020
+ def main():
2021
+ ap = argparse.ArgumentParser(description="Android Web 容器 & JSBridge 静态扫描器")
2022
+ ap.add_argument("project", nargs="?", default=None, help="Android 工程根目录")
2023
+ ap.add_argument("--output", help="报告输出目录(默认 <工程同级>/<工程名>-h5-report/<工程名小写>-scan/)")
2024
+ ap.add_argument("--stdout-json", action="store_true", help="仅打印 JSON 到 stdout")
2025
+ ap.add_argument("--search-ohpm", metavar="KEYWORD",
2026
+ help="在线检索 ohpm 鸿蒙替代库(需网络,不扫描工程)")
2027
+ ap.add_argument("--fetch-url", action="append", metavar="URL", default=[],
2028
+ help="抓取远程 H5 页面(含同源 script)并并入报告信号,可重复(需网络)")
2029
+ args = ap.parse_args()
2030
+
2031
+ if args.search_ohpm:
2032
+ try:
2033
+ search_ohpm(args.search_ohpm)
2034
+ except Exception as e: # 网络异常不阻断离线扫描流程
2035
+ print(f"ohpm 检索失败:{e}", file=sys.stderr)
2036
+ sys.exit(1)
2037
+ return
2038
+
2039
+ if not args.project:
2040
+ ap.error("缺少 <Android工程目录>(或使用 --search-ohpm <关键词>)")
2041
+ root = Path(args.project).resolve()
2042
+ if not root.is_dir():
2043
+ print(f"not a directory: {root}", file=sys.stderr)
2044
+ sys.exit(2)
2045
+
2046
+ rep = build_report(root)
2047
+ for url in args.fetch_url:
2048
+ try:
2049
+ merge_remote_h5(rep, url)
2050
+ print(f"fetched remote h5: {url}", file=sys.stderr)
2051
+ except Exception as e:
2052
+ print(f"远程 H5 抓取失败(忽略):{url} — {e}", file=sys.stderr)
2053
+ if args.stdout_json:
2054
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
2055
+ return
2056
+
2057
+ out = Path(args.output).resolve() if args.output else (
2058
+ root.parent / f"{root.name}-h5-report" / f"{root.name.lower()}-scan")
2059
+ out.mkdir(parents=True, exist_ok=True)
2060
+ (out / "web-jsbridge-report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=2),
2061
+ encoding="utf-8")
2062
+ (out / "web-jsbridge-report.md").write_text(render_md(rep), encoding="utf-8")
2063
+ (out / "web-jsbridge-report.html").write_text(render_html(rep), encoding="utf-8")
2064
+ bm = rep["bridge_methods"]
2065
+ has_bridge = (bm["javascript_interfaces"] or bm["register_handlers"]
2066
+ or bm.get("dsbridge_has_methods") or rep.get("h5_handler_calls"))
2067
+ test_page = out / "bridge-test.html"
2068
+ if has_bridge:
2069
+ test_page.write_text(gen_bridge_test_page(rep), encoding="utf-8")
2070
+ print(f"sources scanned : {rep['scanned']['sources']}")
2071
+ print(f"containers : {', '.join(rep['summary']['containers']) or 'none'}")
2072
+ print(f"jsbridge : {', '.join(rep['summary']['jsbridge']) or 'none'}")
2073
+ print(f"bridge methods : {rep['summary']['bridge_method_count']}")
2074
+ print(f"report -> {out / 'web-jsbridge-report.md'}")
2075
+ print(f"html -> {out / 'web-jsbridge-report.html'}")
2076
+ print(f"test page -> {test_page if has_bridge else '(无桥接方法,未生成)'}")
2077
+
2078
+
2079
+ if __name__ == "__main__":
2080
+ main()