dsh-browser-verify 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # dsh-browser-verify
2
+
3
+ Read-only browser verification tools for the DeepSeek Harness web GUI — verify a page (H5/desktop) in **≤4 tool calls** with mock interception, DOM assertions, and screenshots that auto-project into the model context. If your verification fits the four tools below, this plugin beats ad-hoc toolchain setup (browser install, cache probing, script authoring, image inspection) roughly 4 calls to ~20 steps.
4
+
5
+ - **Registry**: `browser_open` / `browser_mock` / `browser_assert` / `browser_screenshot`
6
+ - **Scope**: read-only verification only (no click/input/scroll). Runs headless Chromium via `playwright-core` (no browser download on the plugin side).
7
+ - **License**: Apache-2.0
8
+
9
+ ## Install
10
+
11
+ > The plugin runs inside the harness process; install it into the harness profile. `dsh plugin` is invoked from the harness checkout.
12
+
13
+ ### From a packed tarball (recommended for local/private use)
14
+
15
+ ```bash
16
+ pnpm install && pnpm build && pnpm pack # → dsh-browser-verify-<version>.tgz
17
+ dsh plugin --profile web add ./dsh-browser-verify-<version>.tgz
18
+ ```
19
+
20
+ ### From a directory link (development)
21
+
22
+ ```bash
23
+ pnpm build # lib/ is gitignored — build first
24
+ dsh plugin --profile web add /path/to/dsh-browser-verify
25
+ ```
26
+
27
+ ### From a git URL (git+https)
28
+
29
+ pnpm installs a git dependency by cloning the repo and running its `prepare` script, so the remote repo must define `prepare` (build `lib/`), and the target profile must allow that build script via `allowBuilds` in its `pnpm-workspace.yaml`. The verified install paths for this repo are the packed tarball and the directory link above.
30
+
31
+ After install, restart the harness GUI, open a new session, and the four tools appear in the tool catalog.
32
+
33
+ ## Quick start
34
+
35
+ ```text
36
+ browser_open url="http://localhost:5173/hweb/#/pages/lyp/livingPayment" waitSelector=".header"
37
+ Opens the page in a fresh scenario (headless Chromium, default viewport 390×844 @2x) and
38
+ returns title/status/visible-text/console-errors. Pass `mocks` here to intercept APIs before
39
+ the first navigation, for pages that boot against mocked data.
40
+ ```
41
+
42
+ ```text
43
+ browser_mock urlPattern="**/api/*.do*" json={status:0,result:{list:[],data:{}}} status=200
44
+ Registers a playwright-glob route interception and auto-reloads the page to show the mocked
45
+ state. Duplicate patterns error: browser_open a fresh scenario or use a different pattern.
46
+ ```
47
+
48
+ ```text
49
+ browser_assert selector=".empty-wrap" count=1 text="暂无可用缴费服务"
50
+ Waits for the selector (default 5s) and returns {pass, count, actualText, elapsedMs} —
51
+ a miss is a normal `pass:false`, never a thrown error. This is the cheapest verification
52
+ step; use it before ever taking a screenshot.
53
+ ```
54
+
55
+ ```text
56
+ browser_screenshot name="livingPayment-empty" fullPage=false
57
+ Captures the current page and auto-projects the image block into the model context;
58
+ returns size/hash plus `identicalToPrevious:true` when the shot is byte-identical to the
59
+ previous one (page probably not refreshed — re-open with browser_open).
60
+ ```
61
+
62
+ ## Environment variables
63
+
64
+ | Variable | Default | Meaning |
65
+ |---|---|---|
66
+ | `DSH_BROWSER_VERIFY_CHROMIUM` | *(unset)* | Full path to a Chromium binary; wins over cache probing. Checked for existence — startup fails with a hint if the path is wrong. |
67
+ | `DSH_BROWSER_VERIFY_TIMEOUT` | `10000` | Timeout (ms) for page load / wait-selector / mock reload; wraps `browser_open`'s page-load path only (the other tools are FIFO-serialized without a wall-clock timeout). |
68
+ | `DSH_BROWSER_VERIFY_IDLE_MS` | `600000` | Idle window (ms) before the browser instance auto-closes; plugin dispose force-cleans in any case. |
69
+
70
+ ## Garbage cleanup
71
+
72
+ This plugin writes only to the system temp dir (its own `dsh-browser-verify-*` prefix), the harness attachment store, and `--persist` paths you choose explicitly. A startup sweep removes leftover dirs (>1 h old, own prefix) and kills stray Chromium; still, after a host crash the manual commands are:
73
+
74
+ ```bash
75
+ # Temp dirs + profile dirs left by crashes (macOS tmpdir, not /tmp)
76
+ rm -rf "$(node -p 'require("os").tmpdir()')/dsh-browser-verify-*"
77
+ ```
78
+
79
+ - **Attachment store**: screenshots persist to the harness-wide store at `~/.dsh/attachments` (content-addressed, identical bytes deduplicated). Their lifecycle is the harness attachment store's, not this plugin's — they are not deleted by tool exit.
80
+ - **Playwright cache**: first-run install (`npx playwright install chromium`, needs `playwright-core@1.62.0`) writes the machine cache (`~/Library/Caches/ms-playwright`). The whole directory can be deleted and reinstalled; the plugin also probes it for a usable binary instead of downloading anything itself.
81
+ - **Packed artifacts**: `*.tgz` from `pnpm pack` is gitignored; delete freely.
82
+
83
+ ## Development
84
+
85
+ ```bash
86
+ pnpm install
87
+ pnpm build # tsc -b && tsdown → lib/
88
+ pnpm test # vitest run
89
+ pnpm vitest run --coverage # per-file ≥90% statements gate on discover/cleanup/attachments
90
+ pnpm typecheck
91
+ node lib/cli.js --url 'http://localhost:5173/hweb/#/pages/lyp/livingPayment' \
92
+ --mock tests/fixtures/mock-empty.json --wait-selector '.header' \
93
+ --assert '.empty-wrap' --screenshot
94
+ scripts/smoke.sh # two-state end-to-end; REQUIRES the hhhweb dev server on :5173
95
+ ```
96
+
97
+ CLI options: `--url <u>` (required), `--mock <file.json>`, `--wait-selector <sel>`, `--assert <sel>`, `--screenshot`, `--persist <dir>` (keep the PNG), `--viewport <WxH>`.
98
+
99
+ ## Moving to another machine
100
+
101
+ 1. Copy/clone this repo and run `pnpm install && pnpm build && pnpm pack`.
102
+ 2. `dsh plugin --profile web add ./dsh-browser-verify-<version>.tgz` on the target machine.
103
+ 3. The browser cache is **not** shipped with the repo: install once with `npx playwright install chromium` (or set `DSH_BROWSER_VERIFY_CHROMIUM` to an existing binary).
104
+
105
+ ## Notes
106
+
107
+ - **Single-machine assumption**: the startup sweep assumes one harness instance per machine — it only removes `dsh-browser-verify-*` pid dirs older than 1 h (plus stray Chromium for those pids), so concurrent harnesses on one host keep their fresh dirs.
108
+ - **Platform**: verified on macOS arm64. On other platforms point `DSH_BROWSER_VERIFY_CHROMIUM` at a browser binary.
109
+
110
+ ## Notes for real apps
111
+
112
+ - uni-app H5 pages use hash routes (`/hweb/#/pages/...`) and an API envelope of `{status, result}` — both confirmed against the reference app (hhhweb).
113
+ - Pages that re-route or bounce when real APIs answer “session invalid” need mocks registered **before** navigation: pass `mocks` to `browser_open` (or `--mock` to the CLI).
package/README.zh.md ADDED
@@ -0,0 +1,110 @@
1
+ # dsh-browser-verify
2
+
3
+ 面向 DeepSeek Harness Web GUI 的只读浏览器验证工具——**≤4 次工具调用**即可验证一个页面(H5/桌面),覆盖 mock 拦截、DOM 断言、截图自动投影进模型上下文。如果你的验证场景能被以下四件套覆盖,本插件相比临时搭建验证工具链(装浏览器、探测缓存、写场景脚本、人工读图)大约 4 次调用对 ~20 个步骤。
4
+
5
+ - **工具面**:`browser_open` / `browser_mock` / `browser_assert` / `browser_screenshot`
6
+ - **范围**:仅只读验证(无点击/输入/滚动)。通过 `playwright-core` 驱动无头 Chromium(插件侧不下载浏览器)。
7
+ - **许可证**:Apache-2.0
8
+
9
+ ## 安装
10
+
11
+ > 插件在 harness 进程内运行,安装目标是 harness profile;`dsh plugin` 命令在 harness checkout 下执行。
12
+
13
+ ### 从打包 tgz 安装(本地/私有使用推荐)
14
+
15
+ ```bash
16
+ pnpm install && pnpm build && pnpm pack # → dsh-browser-verify-<版本号>.tgz
17
+ dsh plugin --profile web add ./dsh-browser-verify-<版本号>.tgz
18
+ ```
19
+
20
+ ### 从目录 link 安装(开发调试)
21
+
22
+ ```bash
23
+ pnpm build # lib/ 被 gitignore——先构建
24
+ dsh plugin --profile web add /路径/dsh-browser-verify
25
+ ```
26
+
27
+ ### 从 git URL 安装(git+https)
28
+
29
+ pnpm 安装 git 依赖时先克隆仓库再执行其 `prepare` 脚本:因此远端仓库必须定义 `prepare`(构建 `lib/`),且目标 profile 必须在 `pnpm-workspace.yaml` 的 `allowBuilds` 中放行该构建脚本。本仓库已验证的安装路径为上述 tgz 与目录 link 两种。
30
+
31
+ 安装后重启 harness GUI、新开会话,四个工具即出现在工具目录中。
32
+
33
+ ## 快速上手
34
+
35
+ ```text
36
+ browser_open url="http://localhost:5173/hweb/#/pages/lyp/livingPayment" waitSelector=".header"
37
+ 在新场景中打开页面(无头 Chromium,默认视口 390×844 @2x),返回标题/状态码/可见文本/
38
+ console 错误。对于启动即依赖接口数据的页面,可在此传 mocks 在首次导航前完成拦截。
39
+ ```
40
+
41
+ ```text
42
+ browser_mock urlPattern="**/api/*.do*" json={status:0,result:{list:[],data:{}}} status=200
43
+ 注册 playwright glob 路由拦截并自动 reload 当前页,展示 mock 后的状态。pattern 重复会
44
+ 报错:请 browser_open 重开场景,或换一个 urlPattern。
45
+ ```
46
+
47
+ ```text
48
+ browser_assert selector=".empty-wrap" count=1 text="暂无可用缴费服务"
49
+ 等待选择器出现(默认 5s),返回 {pass, count, actualText, elapsedMs}——不满足时是正常的
50
+ pass:false,绝不抛错。这是最省 token 的验证手段;先断言,确有必要再截图。
51
+ ```
52
+
53
+ ```text
54
+ browser_screenshot name="livingPayment-empty" fullPage=false
55
+ 截取当前页并将图片块自动投影进模型上下文;返回尺寸/哈希,若与上一张字节完全一致则
56
+ 附 identicalToPrevious:true(疑似页面未刷新——请 browser_open 重开)。
57
+ ```
58
+
59
+ ## 环境变量
60
+
61
+ | 变量 | 默认值 | 含义 |
62
+ |---|---|---|
63
+ | `DSH_BROWSER_VERIFY_CHROMIUM` | (未设置) | Chromium 二进制完整路径,优先级高于缓存探测;启动时校验存在性,路径有误会给出提示。 |
64
+ | `DSH_BROWSER_VERIFY_TIMEOUT` | `10000` | 超时(ms):页面加载 / 等待选择器 / mock reload;仅包裹 `browser_open` 的页面加载路径(其余三个工具仅 FIFO 串行,无墙钟超时)。 |
65
+ | `DSH_BROWSER_VERIFY_IDLE_MS` | `600000` | 空闲回收窗口(ms),到时自动关闭浏览器实例;插件 dispose 时无论如何会强制清理。 |
66
+
67
+ ## 垃圾清理
68
+
69
+ 本插件只会在系统临时目录(自己的 `dsh-browser-verify-*` 前缀)、harness 附件库、以及你显式指定的 `--persist` 路径落东西。启动时会清扫过期残留目录(>1h、仅限自己的前缀)并兜底杀死孤儿 Chromium;但宿主崩溃后仍建议手动执行:
70
+
71
+ ```bash
72
+ # 崩溃残留的临时目录/profile 目录(注意 macOS tmpdir 不是 /tmp)
73
+ rm -rf "$(node -p 'require("os").tmpdir()')/dsh-browser-verify-*"
74
+ ```
75
+
76
+ - **附件库**:截图持久化到 harness 全局附件库 `~/.dsh/attachments`(内容寻址,相同字节自动去重)。其生命周期由 harness 附件库管理,不随工具退出删除。
77
+ - **Playwright 缓存**:首次安装(`npx playwright install chromium`,需 `playwright-core@1.62.0`)写入机器级缓存(`~/Library/Caches/ms-playwright`)。整个目录可整删后重装;插件本身只会探测该缓存中的可用二进制,不会自行下载。
78
+ - **打包产物**:`pnpm pack` 产生的 `*.tgz` 已被 gitignore,可随意删除。
79
+
80
+ ## 开发
81
+
82
+ ```bash
83
+ pnpm install
84
+ pnpm build # tsc -b && tsdown → lib/
85
+ pnpm test # vitest run
86
+ pnpm vitest run --coverage # discover/cleanup/attachments 逐文件语句覆盖 ≥90% 门槛
87
+ pnpm typecheck
88
+ node lib/cli.js --url 'http://localhost:5173/hweb/#/pages/lyp/livingPayment' \
89
+ --mock tests/fixtures/mock-empty.json --wait-selector '.header' \
90
+ --assert '.empty-wrap' --screenshot
91
+ scripts/smoke.sh # 两态端到端冒烟;需要 hhhweb dev server 在 :5173 运行
92
+ ```
93
+
94
+ CLI 选项:`--url <u>`(必填)、`--mock <file.json>`、`--wait-selector <sel>`、`--assert <sel>`、`--screenshot`、`--persist <dir>`(保留 PNG)、`--viewport <WxH>`。
95
+
96
+ ## 多机迁移
97
+
98
+ 1. 复制/克隆本仓库并执行 `pnpm install && pnpm build && pnpm pack`。
99
+ 2. 在目标机器 `dsh plugin --profile web add ./dsh-browser-verify-<版本号>.tgz`。
100
+ 3. 浏览器缓存**不随仓库**:先 `npx playwright install chromium` 安装一次(或将 `DSH_BROWSER_VERIFY_CHROMIUM` 指向已有二进制)。
101
+
102
+ ## 注意事项
103
+
104
+ - **单机假设**:启动清扫按“每台机器一个 harness 实例”设计——只清理超过 1h 的 `dsh-browser-verify-*` pid 目录(及对应孤儿进程),同机多实例的新鲜目录不受影响。
105
+ - **平台**:已在 macOS arm64 实测验证;其他平台请用 `DSH_BROWSER_VERIFY_CHROMIUM` 指向浏览器二进制。
106
+
107
+ ## 真实应用注意事项
108
+
109
+ - uni-app H5 页面使用 hash 路由(`/hweb/#/pages/...`),API 响应信封为 `{status, result}`——均已在参考应用(hhhweb)实测确认。
110
+ - 真实 API 返回“session invalid”时会跳转/回退的路由:mock 必须在导航前注册——请通过 `browser_open` 的 `mocks` 传入(CLI 则用 `--mock`)。
@@ -0,0 +1,17 @@
1
+ # dsh-browser-verify bundle patch: inserts the four browser verification
2
+ # tools into the web profile roster. Applied as a profile bundle layer (the
3
+ # dsh.bundle.patch manifest field).
4
+ #
5
+ # Install (from a source checkout; tarball name follows the current version):
6
+ # pnpm install && pnpm build && pnpm pack
7
+ # dsh plugin --profile web add ./dsh-browser-verify-<version>.tgz
8
+ # # or, during development, add the checkout directory directly (pnpm link):
9
+ # dsh plugin --profile web add <path-to-this-directory>
10
+ #
11
+ # Host half only: the node half (exports ".") registers browser_open /
12
+ # browser_mock / browser_assert / browser_screenshot. No client half, no
13
+ # settings card. Configuration is env-var only (DSH_BROWSER_VERIFY_*); do NOT
14
+ # add a `config:` block here.
15
+ - insert:
16
+ - id: browser-verify
17
+ name: 'dsh-browser-verify'
package/lib/cli.js ADDED
@@ -0,0 +1,104 @@
1
+ import { t as BrowserDriver } from "./driver-DxMldTYf.js";
2
+ import { readFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ //#region src/cli.ts
6
+ /**
7
+ * Debug CLI for dsh-browser-verify: exercises the same core the tools use,
8
+ * without the harness. Prints structured JSON results.
9
+ * @module dsh-browser-verify/cli
10
+ */
11
+ function parseCliArgs(argv) {
12
+ const opts = {
13
+ url: "",
14
+ viewport: {
15
+ width: 390,
16
+ height: 844
17
+ }
18
+ };
19
+ for (let i = 0; i < argv.length; i++) {
20
+ const arg = argv[i];
21
+ const next = () => {
22
+ const v = argv[++i];
23
+ if (v === void 0) throw new Error(`browser-verify: 参数 ${arg} 缺少值。请按 --url <url> 的用法补充。`);
24
+ return v;
25
+ };
26
+ if (arg === "--url") opts.url = next();
27
+ else if (arg === "--mock") opts.mockFile = next();
28
+ else if (arg === "--wait-selector") opts.waitSelector = next();
29
+ else if (arg === "--assert") opts.assertSelector = next();
30
+ else if (arg === "--screenshot") opts.screenshot = true;
31
+ else if (arg === "--persist") opts.persistDir = next();
32
+ else if (arg === "--viewport") {
33
+ const [w, h] = next().split("x").map(Number);
34
+ opts.viewport = {
35
+ width: w,
36
+ height: h
37
+ };
38
+ } else throw new Error(`browser-verify: 未知参数 ${arg}。请检查命令行用法(--url/--mock/--assert/--screenshot/--persist/--viewport/--wait-selector)。`);
39
+ }
40
+ if (opts.url === "") throw new Error("browser-verify: 缺少 --url。请提供页面地址,如 --url http://localhost:5173/hweb/#/pages/lyp/livingPayment。");
41
+ return opts;
42
+ }
43
+ async function main() {
44
+ const opts = parseCliArgs(process.argv.slice(2));
45
+ let rule = null;
46
+ if (opts.mockFile !== void 0) try {
47
+ rule = JSON.parse(await readFile(opts.mockFile, "utf8"));
48
+ } catch (error) {
49
+ const raw = error instanceof Error ? error.message : String(error);
50
+ throw new Error(`browser-verify: 读取 --mock 文件失败: ${raw}。请检查文件路径与 JSON 格式。`);
51
+ }
52
+ const driver = new BrowserDriver({ viewport: opts.viewport });
53
+ try {
54
+ const opened = await driver.startScenario({
55
+ url: opts.url,
56
+ timeoutMs: 15e3,
57
+ waitSelector: opts.waitSelector,
58
+ mocks: rule === null ? void 0 : [{
59
+ urlPattern: rule.urlPattern,
60
+ json: rule.json,
61
+ status: rule.status
62
+ }]
63
+ });
64
+ console.log(JSON.stringify({
65
+ step: "open",
66
+ ...opened
67
+ }));
68
+ if (rule !== null) console.log(JSON.stringify({
69
+ step: "mock",
70
+ patterns: [rule.urlPattern]
71
+ }));
72
+ if (opts.assertSelector !== void 0) {
73
+ const assertSelector = opts.assertSelector;
74
+ const result = await driver.withScenario((s) => s.assert({
75
+ selector: assertSelector,
76
+ timeoutMs: 5e3
77
+ }));
78
+ console.log(JSON.stringify({
79
+ step: "assert",
80
+ ...result
81
+ }));
82
+ }
83
+ if (opts.screenshot === true) {
84
+ const shot = await driver.withScenario((s) => s.screenshot({ fullPage: false }));
85
+ const path = opts.persistDir === void 0 ? join(tmpdir(), `dsh-browser-verify-${process.pid}`, "cli-last.png") : join(resolve(opts.persistDir), `browser-verify-${Date.now()}.png`);
86
+ await import("node:fs/promises").then((fs) => fs.writeFile(path, shot.data));
87
+ console.log(JSON.stringify({
88
+ step: "screenshot",
89
+ path,
90
+ keep: opts.persistDir !== void 0,
91
+ sha256: shot.sha256,
92
+ identicalToPrevious: shot.identicalToPrevious
93
+ }));
94
+ }
95
+ } finally {
96
+ await driver.dispose();
97
+ }
98
+ }
99
+ if (process.argv[1] !== void 0 && /(^|[\\/])cli\.(js|ts)$/.test(process.argv[1])) main().catch((error) => {
100
+ console.error(String(error));
101
+ process.exitCode = 1;
102
+ });
103
+ //#endregion
104
+ export { parseCliArgs };