@zhanfu/zhanfu-cli 0.0.0-stage → 1.0.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.
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { loadPlaywright } from './dependencies.mjs';
5
+ import { createSelectionState } from './page_state.mjs';
6
+ import { takeSnapshot, resolveRef } from './page_snapshot.mjs';
7
+
8
+ const actions = new Set(['list', 'select', 'visit', 'content', 'query', 'extract', 'click', 'input', 'move', 'scroll', 'exec', 'snapshot', 'screenshot', 'upload', 'captcha', 'wait-element', 'wait-nav']);
9
+ const flags = new Set(['new-tab', 'submit', 'full-page', 'stdin', 'wait-nav']);
10
+ const values = new Set(['port', 'target-id', 'url', 'wait-until', 'selector', 'ref', 'text', 'script', 'base64', 'path', 'timeout', 'frame-url', 'max-chars', 'format', 'state', 'ms', 'state-dir', 'x', 'y', 'selectors', 'selectors-file', 'limit', 'max-items', 'file']);
11
+ const mutations = new Set(['visit', 'click', 'input', 'move', 'scroll', 'upload', 'exec']);
12
+ const handles = [];
13
+ let browser;
14
+ let action;
15
+ let targetId;
16
+ let actionMayHaveOccurred = false;
17
+
18
+ function fail(status, message) {
19
+ throw Object.assign(new Error(message), { status });
20
+ }
21
+ function integer(value, name, fallback, max = 300000) {
22
+ if (value === undefined) return fallback;
23
+ const n = Number(value);
24
+ if (!Number.isInteger(n) || n < 1 || n > max) fail('invalid_args', `Invalid --${name}`);
25
+ return n;
26
+ }
27
+ function required(opts, name) {
28
+ if (opts[name] === undefined || opts[name] === '') fail('invalid_args', `Missing --${name}`);
29
+ return opts[name];
30
+ }
31
+ function coordinate(value, name, fallback = 0) {
32
+ if (value === undefined) return fallback;
33
+ const n = Number(value);
34
+ if (!Number.isFinite(n)) fail('invalid_args', `Invalid --${name}`);
35
+ return n;
36
+ }
37
+ function parse(argv) {
38
+ const opts = {};
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const equals = argv[i].indexOf('=');
41
+ const key = argv[i].startsWith('--') ? argv[i].slice(2, equals < 0 ? undefined : equals) : '';
42
+ if (!flags.has(key) && !values.has(key)) fail('invalid_args', `Unknown argument: ${argv[i]}`);
43
+ if (Object.hasOwn(opts, key) && key !== 'file') fail('invalid_args', `Repeated --${key}`);
44
+ if (flags.has(key)) {
45
+ if (equals >= 0) fail('invalid_args', `Flag --${key} does not accept a value`);
46
+ opts[key] = true;
47
+ }
48
+ else {
49
+ if (equals < 0 && (i + 1 >= argv.length || argv[i + 1].startsWith('--'))) fail('invalid_args', `Missing value for --${key}`);
50
+ const value = equals < 0 ? argv[++i] : argv[i].slice(equals + 1);
51
+ if (key === 'file') (opts.file ??= []).push(value); else opts[key] = value;
52
+ }
53
+ }
54
+ return opts;
55
+ }
56
+ function emit(value) {
57
+ console.log('RESULT_JSON=' + JSON.stringify(value, (_key, v) => typeof v === 'bigint' ? { valueType: 'bigint', value: v.toString() } : v));
58
+ }
59
+ async function pageInfo(context, page) {
60
+ const session = await context.newCDPSession(page);
61
+ try {
62
+ const { targetInfo } = await session.send('Target.getTargetInfo');
63
+ const url = page.url();
64
+ return { page, targetId: targetInfo.targetId, url, title: await page.title(), operable: /^(https?:|about:blank|data:)/.test(url) };
65
+ } finally {
66
+ await session.detach();
67
+ }
68
+ }
69
+ async function unique(frame, selector) {
70
+ const locator = frame.locator(selector);
71
+ const count = await locator.count();
72
+ if (count !== 1) fail('selector_not_unique', `Selector matched ${count} elements: ${selector}`);
73
+ return locator;
74
+ }
75
+ async function resolveControl(frame, opts) {
76
+ if (opts.ref) {
77
+ const element = await resolveRef(frame, opts.ref);
78
+ handles.push(element);
79
+ return element;
80
+ }
81
+ return unique(frame, required(opts, 'selector'));
82
+ }
83
+ async function run() {
84
+ const argv = process.argv.slice(2);
85
+ if (argv.length === 0 || argv.includes('--help')) {
86
+ emit({ ok: true, status: 'help', actions: [...actions], aliases: { wait: 'legacy element wait/delay' }, captcha: 'Known challenge detection and human handoff; no automated solver', usage: 'node page.mjs <action> --port <port> [--target-id <id>] [options]', reference: '../references/commands.md' });
87
+ return;
88
+ }
89
+ action = argv.shift();
90
+ if (!actions.has(action) && action !== 'wait') fail('unsupported_action', `Unknown action: ${action}; AI may use task-specific Playwright for unsupported ordinary page actions`);
91
+ const opts = parse(argv);
92
+ const port = integer(required(opts, 'port'), 'port', undefined, 65535);
93
+ const timeout = integer(opts.timeout, 'timeout', 30000);
94
+ // Validate arguments before any browser mutation.
95
+ if (opts.ref && opts.selector) fail('invalid_args', '--selector and --ref are mutually exclusive');
96
+ if (['click', 'input', 'upload'].includes(action) && !opts.ref) required(opts, 'selector');
97
+ if (action === 'query') required(opts, 'selector');
98
+ if (action === 'select') required(opts, 'target-id');
99
+ if (action === 'input' && opts.text === undefined) fail('invalid_args', 'Missing --text');
100
+ if (action === 'screenshot') required(opts, 'path');
101
+ if (opts['new-tab'] && action !== 'visit') fail('invalid_args', '--new-tab requires visit');
102
+ if (opts['new-tab'] && opts['target-id']) fail('invalid_args', '--new-tab and --target-id are mutually exclusive');
103
+ if (opts['new-tab'] && opts['frame-url'] !== undefined) fail('invalid_args', '--new-tab and --frame-url are mutually exclusive');
104
+ if (opts['wait-until'] !== undefined && !['domcontentloaded', 'load', 'networkidle', 'commit'].includes(opts['wait-until'])) fail('invalid_args', 'Invalid --wait-until');
105
+ if (action === 'visit') {
106
+ let url;
107
+ const input = required(opts, 'url');
108
+ try { url = new URL(input); }
109
+ catch { fail('invalid_args', 'Invalid --url'); }
110
+ if (!['http:', 'https:', 'about:'].includes(url.protocol) || (url.protocol === 'about:' && url.href !== 'about:blank')) fail('invalid_args', 'Use http(s) URL or about:blank');
111
+ if (!['domcontentloaded', 'load', 'networkidle', 'commit'].includes(opts['wait-until'] ?? 'domcontentloaded')) fail('invalid_args', 'Invalid --wait-until');
112
+ }
113
+ if (action === 'content' && !['text', 'html', 'structured'].includes(opts.format ?? 'text')) fail('invalid_args', 'Invalid --format');
114
+ const maxChars = integer(opts['max-chars'], 'max-chars', 12000, 1000000);
115
+ const limit = integer(opts.limit, 'limit', 100, 1000);
116
+ let script;
117
+ if (action === 'exec') {
118
+ if (['script', 'stdin', 'base64'].filter(k => opts[k] !== undefined).length !== 1) fail('invalid_args', 'Use exactly one of --script/--stdin/--base64');
119
+ if (opts.stdin) {
120
+ const chunks = [];
121
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
122
+ script = Buffer.concat(chunks).toString('utf8');
123
+ } else if (opts.base64 !== undefined) {
124
+ const encoded = opts.base64.replace(/\s/g, '');
125
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) || encoded.length % 4 === 1 || (encoded.includes('=') && encoded.length % 4 !== 0)) fail('invalid_args', 'Invalid --base64');
126
+ const decoded = Buffer.from(encoded, 'base64');
127
+ if (decoded.toString('base64').replace(/=+$/, '') !== encoded.replace(/=+$/, '')) fail('invalid_args', 'Invalid --base64');
128
+ try { script = new TextDecoder('utf-8', { fatal: true }).decode(decoded); }
129
+ catch { fail('invalid_args', '--base64 must contain UTF-8 JavaScript'); }
130
+ } else script = opts.script;
131
+ if (!script?.trim()) fail('invalid_args', 'Empty script');
132
+ }
133
+ if (action === 'wait' || action === 'wait-element') {
134
+ if (action === 'wait-element') required(opts, 'selector');
135
+ else if ((opts.selector !== undefined) === (opts.ms !== undefined)) fail('invalid_args', 'Use exactly one of --selector/--ms');
136
+ if (opts.ms !== undefined) integer(opts.ms, 'ms');
137
+ if (!['visible', 'attached', 'hidden', 'detached'].includes(opts.state ?? 'visible')) fail('invalid_args', 'Invalid --state');
138
+ }
139
+ if (action === 'move') {
140
+ const control = !!(opts.selector || opts.ref);
141
+ const point = opts.x !== undefined || opts.y !== undefined;
142
+ if (control === point) fail('invalid_args', 'Use a selector/ref or both --x/--y');
143
+ if (point && (opts.x === undefined || opts.y === undefined || coordinate(opts.x, 'x') < 0 || coordinate(opts.y, 'y') < 0)) fail('invalid_args', 'Viewport coordinates require nonnegative x and y');
144
+ }
145
+ let extraction;
146
+ if (action === 'extract') {
147
+ if ((opts.selectors !== undefined) === (opts['selectors-file'] !== undefined)) fail('invalid_args', 'Use exactly one of --selectors/--selectors-file');
148
+ let source;
149
+ try { source = opts.selectors ?? await readFile(opts['selectors-file'], 'utf8'); }
150
+ catch (error) { fail('invalid_args', `Cannot read --selectors-file: ${error.message}`); }
151
+ try { extraction = JSON.parse(source.replace(/^\uFEFF/, '')); }
152
+ catch { fail('invalid_args', 'Selectors must contain valid JSON'); }
153
+ if (!extraction || typeof extraction !== 'object' || Array.isArray(extraction)) fail('invalid_args', 'Selectors must be a field-to-selector object');
154
+ for (const field of Object.values(extraction)) {
155
+ if (!(typeof field === 'string' && field) && !(field && typeof field.selector === 'string' && field.selector)) fail('invalid_args', 'Each field needs a CSS selector');
156
+ if (typeof field === 'object') {
157
+ for (const key of ['all', 'html', 'required']) if (field[key] !== undefined && typeof field[key] !== 'boolean') fail('invalid_args', `Extraction ${key} must be a boolean`);
158
+ if (field.attribute !== undefined && (typeof field.attribute !== 'string' || !field.attribute.trim())) fail('invalid_args', 'Extraction attribute must be a nonempty string');
159
+ }
160
+ }
161
+ }
162
+ let files;
163
+ if (action === 'upload') {
164
+ if (!opts.file?.length) fail('invalid_args', 'Provide at least one --file');
165
+ files = opts.file.map(file => path.resolve(file));
166
+ for (const file of files) {
167
+ let info;
168
+ try { info = await stat(file); }
169
+ catch (error) { fail('invalid_args', `Cannot read upload file: ${error.message}`); }
170
+ if (!info.isFile()) fail('invalid_args', `Not a regular file: ${file}`);
171
+ }
172
+ }
173
+ const { chromium } = await loadPlaywright();
174
+ const selection = await createSelectionState(port, Math.min(timeout, 15000), opts['state-dir']);
175
+ // Connect only; never launch a replacement browser.
176
+ browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: Math.min(timeout, 15000) });
177
+ const contexts = browser.contexts();
178
+ const infos = [];
179
+ for (const context of contexts) for (const page of context.pages()) infos.push(await pageInfo(context, page));
180
+ const selectedId = await selection.read();
181
+ const validSelected = infos.find(info => info.targetId === selectedId && info.operable);
182
+ if (action === 'list') {
183
+ emit({ ok: true, status: 'listed', action, port, data: infos.map(({ page, ...info }) => ({ ...info, selected: info.targetId === validSelected?.targetId })) });
184
+ return;
185
+ }
186
+ let page;
187
+ if (opts['new-tab']) {
188
+ if (contexts.length !== 1) fail('ambiguous_page', 'Expected one store browser context');
189
+ actionMayHaveOccurred = true;
190
+ page = await contexts[0].newPage();
191
+ targetId = (await pageInfo(contexts[0], page)).targetId;
192
+ } else {
193
+ const candidates = opts['target-id'] ? infos.filter(p => p.targetId === opts['target-id']) : validSelected ? [validSelected] : infos.filter(p => p.operable);
194
+ if (candidates.length === 0) fail('target_not_found', 'No matching page; run list and specify --target-id');
195
+ if (candidates.length !== 1) fail('ambiguous_page', 'Multiple pages; run list and specify --target-id');
196
+ ({ page, targetId } = candidates[0]);
197
+ if (action === 'select' && !candidates[0].operable) fail('invalid_target', 'Select an ordinary business page rather than a browser-internal page');
198
+ }
199
+ await selection.select(targetId);
200
+ if (action === 'select') {
201
+ emit({ ok: true, status: 'selected', action, port, targetId, url: page.url(), title: await page.title(), data: { selected: true, activated: false } });
202
+ return;
203
+ }
204
+ const frames = opts['frame-url'] !== undefined ? page.frames().filter(f => f.url() === opts['frame-url']) : [page.mainFrame()];
205
+ if (frames.length !== 1) fail('ambiguous_frame', 'Frame URL must match exactly one frame');
206
+ const frame = frames[0];
207
+ let data;
208
+ if (action === 'visit') {
209
+ actionMayHaveOccurred = true;
210
+ const response = await frame.goto(opts.url, { waitUntil: opts['wait-until'] ?? 'domcontentloaded', timeout });
211
+ await page.bringToFront();
212
+ data = { httpStatus: response?.status() ?? null, frameUrl: frame.url() };
213
+ } else if (action === 'content') {
214
+ const root = opts.selector ? await unique(frame, opts.selector) : frame.locator('body');
215
+ const raw = opts.format === 'html' ? await root.innerHTML({ timeout }) : await root.innerText({ timeout });
216
+ data = { format: opts.format ?? 'text', content: raw.slice(0, maxChars), totalChars: raw.length, truncated: raw.length > maxChars };
217
+ if (opts.format !== 'html') data.elements = await root.locator('a,input,button,select,textarea,[role="button"]').evaluateAll(elements => elements.slice(0, 80).map(e => ({ tag: e.localName, text: (e.innerText || e.getAttribute('aria-label') || '').slice(0, 160), id: e.id, name: e.getAttribute('name'), type: e.getAttribute('type'), href: e.getAttribute('href') })));
218
+ } else if (action === 'query') {
219
+ const locator = frame.locator(opts.selector);
220
+ const count = await locator.count();
221
+ const candidates = [];
222
+ for (let i = 0; i < Math.min(count, limit); i++) {
223
+ const item = locator.nth(i);
224
+ candidates.push({ ...await item.evaluate(e => ({ tag: e.localName, text: (e.innerText || e.textContent || '').slice(0, 200), id: e.id, name: e.getAttribute('name'), ariaLabel: e.getAttribute('aria-label') }), undefined, { timeout }), visible: await item.isVisible() });
225
+ }
226
+ data = { count, candidates, truncated: count > limit };
227
+ } else if (action === 'click' || action === 'input') {
228
+ const locator = await resolveControl(frame, opts);
229
+ actionMayHaveOccurred = true;
230
+ if (action === 'click') {
231
+ if (opts['wait-nav']) await Promise.all([frame.waitForNavigation({ waitUntil: opts['wait-until'] ?? 'domcontentloaded', timeout }), locator.click({ timeout })]);
232
+ else await locator.click({ timeout });
233
+ }
234
+ else {
235
+ await locator.fill(opts.text, { timeout });
236
+ if (opts.submit) await locator.press('Enter', { timeout });
237
+ }
238
+ data = { dispatched: true, submitted: action === 'input' && !!opts.submit };
239
+ } else if (action === 'exec') {
240
+ actionMayHaveOccurred = true;
241
+ // A CDP evaluation may outlive a caller timeout; never automatically replay it.
242
+ let timer;
243
+ try {
244
+ const result = await Promise.race([frame.evaluate(script), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('Script evaluation timed out; execution may continue in browser')), timeout); })]);
245
+ data = { result: result === undefined ? null : result, valueType: typeof result };
246
+ } finally { clearTimeout(timer); }
247
+ } else if (action === 'screenshot') {
248
+ const output = path.resolve(opts.path);
249
+ await mkdir(path.dirname(output), { recursive: true });
250
+ // Some store kernels do not render inactive targets for captureScreenshot.
251
+ await page.bringToFront();
252
+ const shot = opts.selector || opts.ref ? await resolveControl(frame, opts) : page;
253
+ await shot.screenshot({ path: output, type: 'png', timeout, ...(opts.selector || opts.ref ? {} : { fullPage: !!opts['full-page'] }) });
254
+ data = { path: output };
255
+ } else if (action === 'wait' || action === 'wait-element') {
256
+ if (opts.selector) await frame.locator(opts.selector).waitFor({ state: opts.state ?? 'visible', timeout });
257
+ else await new Promise(resolve => setTimeout(resolve, integer(opts.ms, 'ms')));
258
+ data = { completed: true };
259
+ } else if (action === 'extract') {
260
+ const fields = {};
261
+ for (const [name, raw] of Object.entries(extraction)) {
262
+ const spec = typeof raw === 'string' ? { selector: raw } : raw;
263
+ const locator = frame.locator(spec.selector);
264
+ const count = await locator.count();
265
+ if (!count && spec.required) fail('extraction_missing', `Required field not found: ${name}`);
266
+ const results = [];
267
+ for (let i = 0; i < Math.min(count, spec.all ? limit : 1); i++) {
268
+ const item = locator.nth(i);
269
+ results.push(spec.attribute ? await item.getAttribute(spec.attribute, { timeout }) : spec.html ? await item.innerHTML({ timeout }) : await item.innerText({ timeout }));
270
+ }
271
+ Object.defineProperty(fields, name, { value: spec.all ? results : results[0] ?? null, enumerable: true });
272
+ }
273
+ data = { fields };
274
+ } else if (action === 'snapshot') {
275
+ data = await takeSnapshot(frame, integer(opts['max-items'], 'max-items', 200, 2000));
276
+ } else if (action === 'move') {
277
+ const control = opts.selector || opts.ref ? await resolveControl(frame, opts) : null;
278
+ actionMayHaveOccurred = true;
279
+ if (control) await control.hover({ timeout });
280
+ else await page.mouse.move(coordinate(opts.x, 'x'), coordinate(opts.y, 'y'));
281
+ data = { dispatched: true };
282
+ } else if (action === 'scroll') {
283
+ const x = coordinate(opts.x, 'x'), y = coordinate(opts.y, 'y');
284
+ if (!x && !y) fail('invalid_args', 'Provide a nonzero --x or --y scroll delta');
285
+ actionMayHaveOccurred = true;
286
+ if (opts.selector || opts.ref) await (await resolveControl(frame, opts)).hover({ timeout });
287
+ else {
288
+ const viewport = await page.evaluate(() => ({ width: innerWidth, height: innerHeight }));
289
+ await page.mouse.move(viewport.width / 2, viewport.height / 2);
290
+ }
291
+ await page.mouse.wheel(x, y);
292
+ data = { dispatched: true, deltaX: x, deltaY: y };
293
+ } else if (action === 'upload') {
294
+ const control = await resolveControl(frame, opts);
295
+ actionMayHaveOccurred = true;
296
+ await control.setInputFiles(files, { timeout });
297
+ data = { attached: true, submitted: false, fileNames: files.map(file => path.basename(file)) };
298
+ } else if (action === 'wait-nav') {
299
+ const state = opts['wait-until'] === 'commit' ? 'domcontentloaded' : opts['wait-until'] ?? 'domcontentloaded';
300
+ if (!['domcontentloaded', 'load', 'networkidle'].includes(state)) fail('invalid_args', 'Invalid --wait-until');
301
+ if (opts.url) await frame.waitForURL(opts.url, { waitUntil: state, timeout });
302
+ else await frame.waitForLoadState(state, { timeout });
303
+ data = { completed: true, frameUrl: frame.url() };
304
+ } else if (action === 'captcha') {
305
+ const selectors = ['iframe[src*="recaptcha"]', 'iframe[src*="hcaptcha"]', 'iframe[src*="challenges.cloudflare.com"]', '.g-recaptcha', '.h-captcha', '#captcha', '[data-captcha]', '[id*="captcha-verify"]'];
306
+ const visibleSelectors = [];
307
+ for (const selector of selectors) {
308
+ const locator = frame.locator(selector);
309
+ for (let i = 0; i < Math.min(await locator.count(), 10); i++) if (await locator.nth(i).isVisible()) { visibleSelectors.push(selector); break; }
310
+ }
311
+ const found = visibleSelectors.length > 0;
312
+ emit({ ok: !found, status: found ? 'needs_human' : 'not_found', action, port, targetId, url: page.url(), title: await page.title(), actionMayHaveOccurred: false, data: { challengeDetected: found, solved: false, requiresHuman: found ? true : null, visibleSelectors, reason: found ? 'No automated CAPTCHA solver is configured; preserve this page for the user.' : 'No known visible CAPTCHA selector found; this does not prove the page is verification-free.' } });
313
+ if (found) process.exitCode = 2;
314
+ return;
315
+ }
316
+ emit({ ok: true, status: 'completed', action, port, targetId, url: page.url(), title: await page.title(), data });
317
+ }
318
+
319
+ try {
320
+ await run();
321
+ } catch (error) {
322
+ emit({ ok: false, status: error.status ?? 'operation_failed', action, targetId, actionMayHaveOccurred: mutations.has(action) && actionMayHaveOccurred, message: error.message, dependency: error.dependency, install: error.install });
323
+ process.exitCode = 1;
324
+ } finally {
325
+ for (const handle of handles) await handle.dispose().catch(() => {});
326
+ // For a CDP-connected browser this disconnects Playwright and keeps the store running.
327
+ if (browser) await browser.close().catch(() => {});
328
+ }
@@ -0,0 +1,62 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ export async function takeSnapshot(frame, maxItems) {
4
+ return frame.evaluate(({ id, maxItems }) => {
5
+ const key = Symbol.for('zhanfu.page.snapshot.runtime');
6
+ let runtime = globalThis[key];
7
+ if (!runtime) {
8
+ runtime = { generation: 0, snapshots: new Map() };
9
+ runtime.observer = new MutationObserver(() => { runtime.generation++; });
10
+ runtime.observer.observe(document, { childList: true, subtree: true, attributes: true, characterData: true });
11
+ globalThis[key] = runtime;
12
+ }
13
+ if (runtime.observer.takeRecords().length) runtime.generation++;
14
+ const candidates = [];
15
+ const selector = 'a[href],button,input:not([type="hidden"]),textarea,select,[role],h1,h2,h3,[contenteditable="true"]';
16
+ const scan = root => {
17
+ for (const element of root.querySelectorAll(selector)) {
18
+ const rect = element.getBoundingClientRect();
19
+ const style = getComputedStyle(element);
20
+ if (rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none') candidates.push(element);
21
+ }
22
+ for (const element of root.querySelectorAll('*')) if (element.shadowRoot) {
23
+ runtime.observer.observe(element.shadowRoot, { childList: true, subtree: true, attributes: true, characterData: true });
24
+ scan(element.shadowRoot);
25
+ }
26
+ };
27
+ scan(document);
28
+ const nodes = candidates.slice(0, maxItems);
29
+ const items = nodes.map((element, index) => ({
30
+ ref: `zf:${id}:${index}`,
31
+ tag: element.localName,
32
+ role: element.getAttribute('role') || null,
33
+ name: (element.getAttribute('aria-label') || element.labels?.[0]?.innerText || element.innerText || element.getAttribute('placeholder') || element.getAttribute('name') || '').trim().slice(0, 200),
34
+ type: element.getAttribute('type'),
35
+ disabled: element.matches(':disabled') || element.getAttribute('aria-disabled') === 'true',
36
+ href: element.getAttribute('href'),
37
+ }));
38
+ runtime.snapshots.set(id, { generation: runtime.generation, createdAt: Date.now(), nodes });
39
+ while (runtime.snapshots.size > 5) runtime.snapshots.delete(runtime.snapshots.keys().next().value);
40
+ return { snapshotId: id, generation: runtime.generation, items, total: candidates.length, truncated: candidates.length > maxItems, expiresInMs: 120000 };
41
+ }, { id: randomUUID(), maxItems });
42
+ }
43
+
44
+ export async function resolveRef(frame, ref) {
45
+ const match = /^zf:([0-9a-f-]{36}):(\d+)$/.exec(ref);
46
+ if (!match) throw Object.assign(new Error('Invalid snapshot ref'), { status: 'invalid_args' });
47
+ const [_, id, index] = match;
48
+ const handle = await frame.evaluateHandle(({ id, index }) => {
49
+ const runtime = globalThis[Symbol.for('zhanfu.page.snapshot.runtime')];
50
+ if (runtime?.observer.takeRecords().length) runtime.generation++;
51
+ const snapshot = runtime?.snapshots.get(id);
52
+ if (!snapshot || Date.now() - snapshot.createdAt > 120000 || snapshot.generation !== runtime.generation) return null;
53
+ const element = snapshot.nodes[Number(index)];
54
+ return element?.isConnected ? element : null;
55
+ }, { id, index });
56
+ const element = handle.asElement();
57
+ if (!element) {
58
+ await handle.dispose();
59
+ throw Object.assign(new Error('Snapshot ref expired or page changed; take a new snapshot'), { status: 'stale_ref' });
60
+ }
61
+ return element;
62
+ }
@@ -0,0 +1,43 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ async function stateIo(operation) {
7
+ for (let attempt = 0; ; attempt++) {
8
+ try { return await operation(); }
9
+ catch (error) {
10
+ // Windows can briefly lock a file while another process replaces it.
11
+ // Preserve atomic replacement; never delete the live state to force a write.
12
+ if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) || attempt >= 8) throw error;
13
+ await new Promise(resolve => setTimeout(resolve, Math.min(10 * 2 ** attempt, 100)));
14
+ }
15
+ }
16
+ }
17
+
18
+ export async function createSelectionState(port, timeout, directory) {
19
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeout) });
20
+ if (!response.ok) throw new Error(`CDP discovery HTTP ${response.status}`);
21
+ const version = await response.json();
22
+ if (!version.webSocketDebuggerUrl) throw new Error('CDP discovery did not return a browser WebSocket URL');
23
+ const identity = createHash('sha256').update(`${port}:${version.webSocketDebuggerUrl}`).digest('hex');
24
+ const root = path.resolve(directory || process.env.ZHANFU_PAGE_STATE_DIR || path.join(
25
+ process.platform === 'win32' ? (process.env.APPDATA || os.homedir()) : path.join(os.homedir(), '.local', 'state'),
26
+ 'ZhanFu', 'page',
27
+ ));
28
+ const file = path.join(root, `${identity}.json`);
29
+ return {
30
+ async read() {
31
+ try { return JSON.parse(await stateIo(() => readFile(file, 'utf8'))).targetId || null; }
32
+ catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return null; throw error; }
33
+ },
34
+ async select(targetId) {
35
+ await mkdir(root, { recursive: true });
36
+ const temporary = `${file}.${randomUUID()}.tmp`;
37
+ try {
38
+ await writeFile(temporary, JSON.stringify({ targetId, updatedAt: new Date().toISOString() }), { mode: 0o600 });
39
+ await stateIo(() => rename(temporary, file));
40
+ } finally { await stateIo(() => unlink(temporary)).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
41
+ },
42
+ };
43
+ }