zero-vision 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.
Files changed (49) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +163 -0
  4. package/dist/cdp/attach.js +121 -0
  5. package/dist/cdp/attach.js.map +1 -0
  6. package/dist/cdp/client.js +53 -0
  7. package/dist/cdp/client.js.map +1 -0
  8. package/dist/cdp/extract.js +197 -0
  9. package/dist/cdp/extract.js.map +1 -0
  10. package/dist/cli.js +223 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/engines/apple-fm.js +103 -0
  13. package/dist/engines/apple-fm.js.map +1 -0
  14. package/dist/engines/apple-vision.js +89 -0
  15. package/dist/engines/apple-vision.js.map +1 -0
  16. package/dist/engines/cloud/index.js +41 -0
  17. package/dist/engines/cloud/index.js.map +1 -0
  18. package/dist/engines/index.js +71 -0
  19. package/dist/engines/index.js.map +1 -0
  20. package/dist/engines/local-vlm.js +46 -0
  21. package/dist/engines/local-vlm.js.map +1 -0
  22. package/dist/engines/tesseract.js +221 -0
  23. package/dist/engines/tesseract.js.map +1 -0
  24. package/dist/mcp.js +225 -0
  25. package/dist/mcp.js.map +1 -0
  26. package/dist/native.js +66 -0
  27. package/dist/native.js.map +1 -0
  28. package/dist/snap.js +30 -0
  29. package/dist/snap.js.map +1 -0
  30. package/dist/test/argv.test.js +22 -0
  31. package/dist/test/argv.test.js.map +1 -0
  32. package/dist/test/ax.test.js +28 -0
  33. package/dist/test/ax.test.js.map +1 -0
  34. package/dist/test/engines.test.js +81 -0
  35. package/dist/test/engines.test.js.map +1 -0
  36. package/dist/test/fetch.test.js +46 -0
  37. package/dist/test/fetch.test.js.map +1 -0
  38. package/dist/test/ocr.test.js +34 -0
  39. package/dist/test/ocr.test.js.map +1 -0
  40. package/dist/test/parity.test.js +33 -0
  41. package/dist/test/parity.test.js.map +1 -0
  42. package/dist/test/port.test.js +55 -0
  43. package/dist/test/port.test.js.map +1 -0
  44. package/dist/test/snap.test.js +13 -0
  45. package/dist/test/snap.test.js.map +1 -0
  46. package/dist/test/tesseract.test.js +17 -0
  47. package/dist/test/tesseract.test.js.map +1 -0
  48. package/docs/spec.md +549 -0
  49. package/package.json +40 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ zero-vision
2
+ Copyright 2026 Unfoundbox Crew
3
+
4
+ This product includes software developed at Unfoundbox Crew
5
+ (https://github.com/unfoundbox-crew).
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # zero-vision
2
+
3
+ **Read a page, a screenshot, or a video as text. Default path never sends pixels off the machine.**
4
+
5
+ Public. Apache-2.0. Crew: [unfoundbox-crew](https://github.com/unfoundbox-crew).
6
+
7
+ | Surface | Name |
8
+ | --- | --- |
9
+ | GitHub | `unfoundbox-crew/zero-vision` |
10
+ | npm package | `zero-vision` |
11
+ | CLI / bin | `zrv` |
12
+
13
+ `zrv` as an unscoped npm name is taken. Install `zero-vision`; that puts `zrv` on `PATH`. Use `npx zero-vision`, never `npx zrv`.
14
+
15
+ ## Perception rank
16
+
17
+ Cheap and local first. Frontier only when you name it.
18
+
19
+ 1. Chrome AX / cleaned text (attach-only CDP — no click)
20
+ 2. Apple Vision OCR (`apple-vision`, default for files)
21
+ 3. On-device Foundation Model (`apple-fm`)
22
+ 4. Local VLM (`local-vlm`) — weights must already be on disk
23
+ 5. Cloud VLM (`cloud-vlm`) — opt-in, never a fallback
24
+
25
+ Not a browser driver. Chrome DevTools MCP and Playwright MCP already click.
26
+
27
+ ## Install
28
+
29
+ macOS, Node 22+, Apple silicon for pixel engines.
30
+
31
+ ```bash
32
+ npm install -g zero-vision
33
+ # or from a checkout:
34
+ npm install && npm run build && npm run native
35
+ ```
36
+
37
+ `npm run native` builds `zrv-native` (Vision OCR). Without it, CDP still works; `zrv ocr` exits 3.
38
+
39
+ ## Design
40
+
41
+ ```
42
+ ┌──────────────┐ ┌───────────────┐
43
+ │ CLI (zrv) │ │ MCP (zrv mcp) │
44
+ │ page · ocr │ │ peek_* · ocr_*│
45
+ │ tabs · snap │ │ 5 tools │
46
+ └──────┬───────┘ └───────┬───────┘
47
+ │ │
48
+ ▼ ▼
49
+ ┌──────────────────────────────────────────┐
50
+ │ perceive() │
51
+ │ task: transcribe | describe │
52
+ └───────┬──────────────────────┬───────────┘
53
+ │ │
54
+ ┌────────────▼────────┐ ┌──────────▼──────────────┐
55
+ │ CDP (attach-only) │ │ pixel engines (ranked, │
56
+ │ text · md · AX │ │ fail-closed) │
57
+ │ never launch │ │ │
58
+ │ never 9222 │ │ 1 apple-vision (OCR) │
59
+ │ opaque ≥30% ──► OCR│ │ 2 apple-fm (judge) │
60
+ └─────────────────────┘ │ 3 local-vlm (weights │
61
+ │ must be on disk) │
62
+ │ 4 cloud-vlm (named │
63
+ │ opt-in only) │
64
+ └──────────┬──────────────┘
65
+
66
+ ┌────────────▼────────────┐
67
+ │ zrv-native (Swift) │
68
+ │ Vision · AVFoundation │
69
+ │ video keyframes │
70
+ └─────────────────────────┘
71
+
72
+ Invariants: no silent cloud fallback · contact sheet = one image,
73
+ never split · snap stays CLI-only · not a browser driver.
74
+ ```
75
+
76
+ ## How it compares
77
+
78
+ ```
79
+ ┌───────────────────┬──────────┬────────┬────────┬────────┬────────────────────────────┐
80
+ │ Tool │ No-pixel │ Local │ Video │ Drives │ Catch │
81
+ │ │ text │ OCR │ text │ browser│ │
82
+ ├───────────────────┼──────────┼────────┼────────┼────────┼────────────────────────────┤
83
+ │ zero-vision (own) │ yes │ yes │ yes │ no │ macOS + Apple silicon │
84
+ │ Playwright MCP │ AX tree │ no │ no │ yes │ pays vision for pixels │
85
+ │ Chrome DevTools │ AX tree │ no │ no │ yes │ same; traces cost extra │
86
+ │ Stagehand │ AX + LLM │ no │ no │ yes │ LLM call per extract │
87
+ │ Crawl4AI │ HTML │ no │ no │ crawl │ rendered HTML, no OCR │
88
+ │ Browser-Use │ hybrid │ no │ no │ yes │ still pays vision often │
89
+ │ ocrtool-mcp │ n/a │ yes │ no │ no │ images only, no tab read │
90
+ │ Frontier VLM shot │ no │ no │ frames │ no │ $$$ per image, off-machine │
91
+ │ agy Flash │ n/a │ no │ no │ no │ cheap but cloud + ~20s lag │
92
+ └───────────────────┴──────────┴────────┴────────┴────────┴────────────────────────────┘
93
+ ```
94
+
95
+ zero-vision is free per call, private by default, and deterministic —
96
+ but pixels need macOS + Apple silicon (see Linux below), it never clicks
97
+ by design, and it is 0.1.0, unproven at scale.
98
+
99
+ ## Linux
100
+
101
+ CDP text works anywhere Node 22 runs. The pixel side swaps backends:
102
+
103
+ | Need | macOS | Linux |
104
+ | ----------------- | ------------------- | -------------------------------------- |
105
+ | OCR | Apple Vision | `tesseract` engine (tesseract.js, pure npm) |
106
+ | OCR speed path | ANE | system `tesseract` binary when present |
107
+ | Describe / judge | apple-fm | `local-vlm` at Ollama / llama.cpp |
108
+ | Video keyframes | AVFoundation | ffmpeg (optional, fail-closed) |
109
+ | `snap` capture | `screencapture` | grim (Wayland) / scrot (X11) |
110
+ | Clipboard | pbcopy | xclip / wl-copy |
111
+
112
+ Same `perceive()` interface, same rank order, same fail-closed rules.
113
+
114
+ ## Commands
115
+
116
+ ```text
117
+ zrv text of the chosen debug-Chrome tab
118
+ zrv --md markdown
119
+ zrv --a11y interesting AX tree
120
+ zrv --tabs
121
+ zrv --url <url> [--navigate|--fetch]
122
+ zrv ocr <file.png|jpg|heic|pdf|mp4|mov> [--task transcribe|describe] [--lang en-US] [--level fast|accurate]
123
+ zrv ocr <clip.mp4> [--mode scene|interval|all-idr] [--interval 2] [--max-frames 60]
124
+ zrv ocr --clipboard
125
+ zrv ocr --task describe --engine apple-fm
126
+ zrv snap interactive capture → clipboard
127
+ zrv snap --ocr capture, OCR, print text, pbcopy
128
+ zrv mcp stdio MCP server
129
+ ```
130
+
131
+ Default debug ports: `1948`, then `9223`. Never `9222` unless `--port 9222` or `ZEROVISION_ALLOW_USER_CHROME=1`.
132
+
133
+ ## MCP tools
134
+
135
+ `peek_tabs` `peek_page` `peek_a11y` `ocr_image` `ocr_video`
136
+
137
+ Prefer these over a screenshot when the goal is to read text. Use `apple-vision` unless the user asked to describe.
138
+
139
+ Agent skill: `npx skills add unfoundbox-crew/zero-vision -g`
140
+
141
+ ## Who consumes this
142
+
143
+ Standalone repo. Other crew products call it; they do not own it.
144
+
145
+ | Project | Job |
146
+ | --- | --- |
147
+ | MotionVector / `mvec` | Contact sheets, title cards, "what does this frame say" after `mvec frame` |
148
+ | AgentWorth | The 92% of visual sessions that are transcription, not taste |
149
+ | SpacePilot | Optional `--engine local-vlm` when weights are already on disk |
150
+
151
+ Photos of a room → classical CV → SDF block-out is MotionVector. This tool stops at text (and, if named, a local/cloud VLM).
152
+
153
+ ## v1 limits
154
+
155
+ `local-vlm` and `cloud-vlm` are fail-closed: they check weights/key and refuse to spawn or POST. Contact sheets are one image, not a split grid. Video OCR needs the native binary.
156
+
157
+ ## Spec
158
+
159
+ [`docs/spec.md`](docs/spec.md)
160
+
161
+ ## License
162
+
163
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,121 @@
1
+ import { CdpClient } from "./client.js";
2
+ const INTERNAL = /^(chrome|devtools|chrome-extension|edge):\/\//;
3
+ function host() {
4
+ return process.env.ZEROVISION_HOST ?? "127.0.0.1";
5
+ }
6
+ export function probePorts(explicit) {
7
+ if (explicit)
8
+ return [explicit];
9
+ const env = process.env.ZEROVISION_PORT;
10
+ if (env)
11
+ return [Number(env)];
12
+ const list = [];
13
+ if (process.env.AGENT_CHROME_PORT)
14
+ list.push(Number(process.env.AGENT_CHROME_PORT));
15
+ list.push(1948, 9223);
16
+ if (process.env.ZEROVISION_ALLOW_USER_CHROME === "1")
17
+ list.push(9222);
18
+ return list;
19
+ }
20
+ export async function findOpenPort(explicit) {
21
+ const h = host();
22
+ if (h !== "127.0.0.1" && h !== "localhost" && !process.env.ZEROVISION_HOST) {
23
+ throw new Error("refusing non-loopback host");
24
+ }
25
+ const ports = probePorts(explicit);
26
+ const tried = [];
27
+ for (const port of ports) {
28
+ tried.push(port);
29
+ try {
30
+ const ac = new AbortController();
31
+ const t = setTimeout(() => ac.abort(), 150);
32
+ const res = await fetch(`http://${h}:${port}/json/version`, { signal: ac.signal });
33
+ clearTimeout(t);
34
+ if (!res.ok)
35
+ continue;
36
+ const version = (await res.json());
37
+ return { port, version };
38
+ }
39
+ catch {
40
+ continue;
41
+ }
42
+ }
43
+ throw Object.assign(new Error(`no debug port (tried ${tried.join(", ")}). Start Chrome with --remote-debugging-port=<n>`), {
44
+ code: 2,
45
+ });
46
+ }
47
+ export async function listTabs(port) {
48
+ const res = await fetch(`http://${host()}:${port}/json/list`);
49
+ if (!res.ok)
50
+ throw new Error(`json/list ${res.status}`);
51
+ const raw = (await res.json());
52
+ return raw.filter((t) => (t.type === "page" || t.type === "tab") && !INTERNAL.test(t.url ?? ""));
53
+ }
54
+ export function pickTab(tabs, opts) {
55
+ let matches = tabs;
56
+ if (opts.tab) {
57
+ const q = opts.tab.toLowerCase();
58
+ matches = tabs.filter((t) => t.id === opts.tab || t.title.toLowerCase().includes(q) || t.url.toLowerCase().includes(q));
59
+ }
60
+ else if (opts.url) {
61
+ matches = tabs.filter((t) => t.url === opts.url || t.url.startsWith(opts.url));
62
+ }
63
+ if (matches.length === 0) {
64
+ throw Object.assign(new Error("no matching tab"), { code: 1, tabs });
65
+ }
66
+ if ((opts.tab || opts.url) && matches.length > 1) {
67
+ const list = matches.map((t) => `${t.id}\t${t.title}\t${t.url}`).join("\n");
68
+ throw Object.assign(new Error(`multiple matches:\n${list}`), { code: 1, tabs: matches });
69
+ }
70
+ return matches[0];
71
+ }
72
+ export async function attach(opts) {
73
+ const { port, version } = await findOpenPort(opts.port);
74
+ const client = new CdpClient();
75
+ await client.connect(version.webSocketDebuggerUrl);
76
+ await client.send("Target.setDiscoverTargets", { discover: true });
77
+ const { targetInfos } = (await client.send("Target.getTargets"));
78
+ let pages = targetInfos.filter((t) => (t.type === "page" || t.type === "tab") && !INTERNAL.test(t.url));
79
+ let chosen = pages[0];
80
+ if (opts.url && opts.navigate) {
81
+ const existing = pages.filter((t) => t.url === opts.url || t.url.startsWith(opts.url));
82
+ if (existing.length === 1)
83
+ chosen = existing[0];
84
+ else if (existing.length === 0) {
85
+ const { targetId } = (await client.send("Target.createTarget", { url: opts.url }));
86
+ const { targetInfos: again } = (await client.send("Target.getTargets"));
87
+ chosen = again.find((t) => t.targetId === targetId) ?? { targetId, type: "page", title: "", url: opts.url };
88
+ }
89
+ else {
90
+ client.close();
91
+ throw Object.assign(new Error(`multiple matches:\n${existing.map((t) => `${t.targetId}\t${t.title}\t${t.url}`).join("\n")}`), { code: 1 });
92
+ }
93
+ }
94
+ else {
95
+ const tabs = pages.map((t) => ({
96
+ id: t.targetId,
97
+ title: t.title,
98
+ url: t.url,
99
+ type: t.type,
100
+ }));
101
+ const tab = pickTab(tabs, { tab: opts.tab, url: opts.url });
102
+ chosen = pages.find((p) => p.targetId === tab.id) ?? pages[0];
103
+ }
104
+ if (!chosen) {
105
+ client.close();
106
+ throw Object.assign(new Error("no attachable page target"), { code: 2 });
107
+ }
108
+ const { sessionId } = (await client.send("Target.attachToTarget", {
109
+ targetId: chosen.targetId,
110
+ flatten: true,
111
+ }));
112
+ return {
113
+ client,
114
+ sessionId,
115
+ targetId: chosen.targetId,
116
+ title: chosen.title,
117
+ url: chosen.url,
118
+ port,
119
+ };
120
+ }
121
+ //# sourceMappingURL=attach.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach.js","sourceRoot":"","sources":["../../src/cdp/attach.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,QAAQ,GAAG,+CAA+C,CAAC;AAmBjE,SAAS,IAAI;IACX,OAAO,OAAO,CAAC,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AO,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAC5D,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,EAAE,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;IAChE,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,MAAM,EAAE,SAAS,EAAE,GAAG,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,uBAAuB,EAAE;QAChE,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,OAAO,EAAE,IAAI;KACd,CAAC,CAA0B,CAAC;IAE7B,OAAO;QACL,MAAM;QACN,SAAS;QACT,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,IAAI;KACL,CAAC;AACJ,CAAC"}
@@ -0,0 +1,53 @@
1
+ import { EventEmitter } from "node:events";
2
+ export class CdpClient extends EventEmitter {
3
+ ws = null;
4
+ nextId = 1;
5
+ pending = new Map();
6
+ async connect(wsUrl) {
7
+ this.ws = new WebSocket(wsUrl);
8
+ await new Promise((resolve, reject) => {
9
+ this.ws.addEventListener("open", () => resolve());
10
+ this.ws.addEventListener("error", () => reject(new Error("cdp websocket error")));
11
+ });
12
+ this.ws.addEventListener("message", (ev) => {
13
+ const msg = JSON.parse(String(ev.data));
14
+ if (msg.method) {
15
+ this.emit(msg.method, msg.params, msg.sessionId);
16
+ return;
17
+ }
18
+ if (typeof msg.id === "number") {
19
+ const p = this.pending.get(msg.id);
20
+ if (!p)
21
+ return;
22
+ this.pending.delete(msg.id);
23
+ if (msg.error)
24
+ p.reject(new Error(msg.error.message));
25
+ else
26
+ p.resolve(msg.result);
27
+ }
28
+ });
29
+ }
30
+ send(method, params, sessionId) {
31
+ if (!this.ws)
32
+ return Promise.reject(new Error("cdp not connected"));
33
+ const id = this.nextId++;
34
+ const payload = { id, method, params };
35
+ if (sessionId)
36
+ payload.sessionId = sessionId;
37
+ this.ws.send(JSON.stringify(payload));
38
+ return new Promise((resolve, reject) => {
39
+ this.pending.set(id, { resolve, reject });
40
+ setTimeout(() => {
41
+ if (this.pending.has(id)) {
42
+ this.pending.delete(id);
43
+ reject(new Error(`cdp timeout: ${method}`));
44
+ }
45
+ }, 15_000);
46
+ });
47
+ }
48
+ close() {
49
+ this.ws?.close();
50
+ this.ws = null;
51
+ }
52
+ }
53
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/cdp/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,MAAM,OAAO,SAAU,SAAQ,YAAY;IACjC,EAAE,GAAqB,IAAI,CAAC;IAC5B,MAAM,GAAG,CAAC,CAAC;IACX,OAAO,GAAG,IAAI,GAAG,EAAyE,CAAC;IAEnG,KAAK,CAAC,OAAO,CAAC,KAAa;QACzB,IAAI,CAAC,EAAE,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;QAC/B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC1C,IAAI,CAAC,EAAG,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;YACnD,IAAI,CAAC,EAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC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