@web-auto/camo 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -0
- package/package.json +2 -1
- package/scripts/check-file-size.mjs +80 -0
- package/scripts/file-size-policy.json +8 -0
- package/src/autoscript/action-providers/index.mjs +9 -0
- package/src/autoscript/action-providers/xhs/comments.mjs +412 -0
- package/src/autoscript/action-providers/xhs/common.mjs +77 -0
- package/src/autoscript/action-providers/xhs/detail.mjs +181 -0
- package/src/autoscript/action-providers/xhs/interaction.mjs +466 -0
- package/src/autoscript/action-providers/xhs/like-rules.mjs +57 -0
- package/src/autoscript/action-providers/xhs/persistence.mjs +167 -0
- package/src/autoscript/action-providers/xhs/search.mjs +174 -0
- package/src/autoscript/action-providers/xhs.mjs +133 -0
- package/src/autoscript/impact-engine.mjs +78 -0
- package/src/autoscript/runtime.mjs +1015 -0
- package/src/autoscript/schema.mjs +370 -0
- package/src/autoscript/xhs-unified-template.mjs +931 -0
- package/src/cli.mjs +185 -79
- package/src/commands/autoscript.mjs +1100 -0
- package/src/commands/browser.mjs +20 -4
- package/src/commands/container.mjs +298 -75
- package/src/commands/events.mjs +152 -0
- package/src/commands/lifecycle.mjs +17 -3
- package/src/commands/window.mjs +32 -1
- package/src/container/change-notifier.mjs +165 -24
- package/src/container/element-filter.mjs +51 -5
- package/src/container/runtime-core/checkpoint.mjs +195 -0
- package/src/container/runtime-core/index.mjs +21 -0
- package/src/container/runtime-core/operations/index.mjs +351 -0
- package/src/container/runtime-core/operations/selector-scripts.mjs +68 -0
- package/src/container/runtime-core/operations/tab-pool.mjs +544 -0
- package/src/container/runtime-core/operations/viewport.mjs +143 -0
- package/src/container/runtime-core/subscription.mjs +87 -0
- package/src/container/runtime-core/utils.mjs +94 -0
- package/src/container/runtime-core/validation.mjs +127 -0
- package/src/container/runtime-core.mjs +1 -0
- package/src/container/subscription-registry.mjs +459 -0
- package/src/core/actions.mjs +573 -0
- package/src/core/browser.mjs +270 -0
- package/src/core/index.mjs +53 -0
- package/src/core/utils.mjs +87 -0
- package/src/events/daemon-entry.mjs +33 -0
- package/src/events/daemon.mjs +80 -0
- package/src/events/progress-log.mjs +109 -0
- package/src/events/ws-server.mjs +239 -0
- package/src/lib/client.mjs +8 -5
- package/src/lifecycle/session-registry.mjs +8 -4
- package/src/lifecycle/session-watchdog.mjs +220 -0
- package/src/utils/browser-service.mjs +232 -9
- package/src/utils/help.mjs +26 -3
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { createProgressWsServer } from '../events/ws-server.mjs';
|
|
2
|
+
import { getProgressEventsFile, readRecentProgressEvents, safeAppendProgressEvent } from '../events/progress-log.mjs';
|
|
3
|
+
import { ensureProgressEventDaemon } from '../events/daemon.mjs';
|
|
4
|
+
|
|
5
|
+
function readFlagValue(args, names) {
|
|
6
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
7
|
+
if (!names.includes(args[i])) continue;
|
|
8
|
+
const value = args[i + 1];
|
|
9
|
+
if (!value || String(value).startsWith('-')) return null;
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function hasFlag(args, name) {
|
|
16
|
+
return args.includes(name);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function buildQuery(args) {
|
|
20
|
+
const profileId = readFlagValue(args, ['--profile', '-p']);
|
|
21
|
+
const runId = readFlagValue(args, ['--run-id']);
|
|
22
|
+
const mode = readFlagValue(args, ['--mode']);
|
|
23
|
+
const events = readFlagValue(args, ['--events']);
|
|
24
|
+
const replay = Math.max(0, Number(readFlagValue(args, ['--replay']) ?? 50) || 50);
|
|
25
|
+
const qs = new URLSearchParams();
|
|
26
|
+
if (profileId) qs.set('profileId', profileId);
|
|
27
|
+
if (runId) qs.set('runId', runId);
|
|
28
|
+
if (mode) qs.set('mode', mode);
|
|
29
|
+
if (events) qs.set('events', events);
|
|
30
|
+
qs.set('replay', String(replay));
|
|
31
|
+
return qs;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function handleEventsServe(args) {
|
|
35
|
+
const host = readFlagValue(args, ['--host']) || '127.0.0.1';
|
|
36
|
+
const port = Math.max(1, Number(readFlagValue(args, ['--port']) || 7788) || 7788);
|
|
37
|
+
const pollMs = Math.max(80, Number(readFlagValue(args, ['--poll-ms']) || 220) || 220);
|
|
38
|
+
const fromStart = hasFlag(args, '--from-start');
|
|
39
|
+
|
|
40
|
+
const server = createProgressWsServer({ host, port, pollMs, fromStart });
|
|
41
|
+
const info = await server.start();
|
|
42
|
+
console.log(JSON.stringify({
|
|
43
|
+
ok: true,
|
|
44
|
+
command: 'events.serve',
|
|
45
|
+
...info,
|
|
46
|
+
message: 'Progress WS server started. Press Ctrl+C to stop.',
|
|
47
|
+
}, null, 2));
|
|
48
|
+
|
|
49
|
+
const stop = async (reason = 'signal_interrupt') => {
|
|
50
|
+
await server.stop();
|
|
51
|
+
console.log(JSON.stringify({ ok: true, event: 'events.serve.stop', reason }));
|
|
52
|
+
process.exit(0);
|
|
53
|
+
};
|
|
54
|
+
process.once('SIGINT', () => {
|
|
55
|
+
stop('SIGINT');
|
|
56
|
+
});
|
|
57
|
+
process.once('SIGTERM', () => {
|
|
58
|
+
stop('SIGTERM');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
await new Promise(() => {});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function handleEventsTail(args) {
|
|
65
|
+
const host = readFlagValue(args, ['--host']) || '127.0.0.1';
|
|
66
|
+
const port = Math.max(1, Number(readFlagValue(args, ['--port']) || 7788) || 7788);
|
|
67
|
+
await ensureProgressEventDaemon({ host, port });
|
|
68
|
+
const qs = buildQuery(args);
|
|
69
|
+
const wsUrl = `ws://${host}:${port}/events?${qs.toString()}`;
|
|
70
|
+
if (typeof WebSocket !== 'function') {
|
|
71
|
+
throw new Error('Global WebSocket is unavailable in this Node runtime');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const socket = new WebSocket(wsUrl);
|
|
75
|
+
socket.addEventListener('open', () => {
|
|
76
|
+
console.log(JSON.stringify({ ok: true, command: 'events.tail', wsUrl }));
|
|
77
|
+
});
|
|
78
|
+
socket.addEventListener('message', (event) => {
|
|
79
|
+
const text = typeof event.data === 'string' ? event.data : String(event.data);
|
|
80
|
+
console.log(text);
|
|
81
|
+
});
|
|
82
|
+
socket.addEventListener('close', () => {
|
|
83
|
+
process.exit(0);
|
|
84
|
+
});
|
|
85
|
+
socket.addEventListener('error', (err) => {
|
|
86
|
+
console.error(JSON.stringify({ ok: false, command: 'events.tail', wsUrl, error: err?.message || String(err) }));
|
|
87
|
+
process.exit(1);
|
|
88
|
+
});
|
|
89
|
+
process.once('SIGINT', () => {
|
|
90
|
+
socket.close();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
await new Promise(() => {});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function handleEventsRecent(args) {
|
|
97
|
+
const limit = Math.max(1, Number(readFlagValue(args, ['--limit', '-n']) || 50) || 50);
|
|
98
|
+
const rows = readRecentProgressEvents(limit);
|
|
99
|
+
console.log(JSON.stringify({
|
|
100
|
+
ok: true,
|
|
101
|
+
command: 'events.recent',
|
|
102
|
+
file: getProgressEventsFile(),
|
|
103
|
+
count: rows.length,
|
|
104
|
+
events: rows,
|
|
105
|
+
}, null, 2));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function handleEventsEmit(args) {
|
|
109
|
+
const eventName = readFlagValue(args, ['--event']) || 'manual.emit';
|
|
110
|
+
const mode = readFlagValue(args, ['--mode']) || 'normal';
|
|
111
|
+
const profileId = readFlagValue(args, ['--profile', '-p']) || null;
|
|
112
|
+
const runId = readFlagValue(args, ['--run-id']) || null;
|
|
113
|
+
const payloadRaw = readFlagValue(args, ['--payload']) || '{}';
|
|
114
|
+
let payload = null;
|
|
115
|
+
try {
|
|
116
|
+
payload = JSON.parse(payloadRaw);
|
|
117
|
+
} catch {
|
|
118
|
+
payload = { raw: payloadRaw };
|
|
119
|
+
}
|
|
120
|
+
const appended = safeAppendProgressEvent({
|
|
121
|
+
source: 'events.emit',
|
|
122
|
+
mode,
|
|
123
|
+
profileId,
|
|
124
|
+
runId,
|
|
125
|
+
event: eventName,
|
|
126
|
+
payload,
|
|
127
|
+
});
|
|
128
|
+
console.log(JSON.stringify({ ok: Boolean(appended), command: 'events.emit', event: appended }, null, 2));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function handleEventsCommand(args) {
|
|
132
|
+
const sub = args[1];
|
|
133
|
+
switch (sub) {
|
|
134
|
+
case 'serve':
|
|
135
|
+
return handleEventsServe(args);
|
|
136
|
+
case 'tail':
|
|
137
|
+
return handleEventsTail(args);
|
|
138
|
+
case 'recent':
|
|
139
|
+
return handleEventsRecent(args);
|
|
140
|
+
case 'emit':
|
|
141
|
+
return handleEventsEmit(args);
|
|
142
|
+
default:
|
|
143
|
+
console.log(`Usage: camo events <serve|tail|recent|emit> [options]
|
|
144
|
+
|
|
145
|
+
Commands:
|
|
146
|
+
serve [--host 127.0.0.1] [--port 7788] [--poll-ms 220] [--from-start]
|
|
147
|
+
tail [--host 127.0.0.1] [--port 7788] [--profile <id>] [--run-id <id>] [--mode <normal|autoscript>] [--events e1,e2] [--replay 50]
|
|
148
|
+
recent [--limit 50]
|
|
149
|
+
emit --event <name> [--mode <normal|autoscript>] [--profile <id>] [--run-id <id>] [--payload '{"k":"v"}']
|
|
150
|
+
`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
getSessionInfo, unregisterSession, markSessionClosed, cleanupStaleSessions,
|
|
11
11
|
listRegisteredSessions, registerSession, updateSession
|
|
12
12
|
} from '../lifecycle/session-registry.mjs';
|
|
13
|
+
import { stopAllSessionWatchdogs, stopSessionWatchdog } from '../lifecycle/session-watchdog.mjs';
|
|
13
14
|
|
|
14
15
|
export async function handleCleanupCommand(args) {
|
|
15
16
|
const sub = args[1];
|
|
@@ -36,14 +37,21 @@ export async function handleCleanupCommand(args) {
|
|
|
36
37
|
const sessions = Array.isArray(status?.sessions) ? status.sessions : [];
|
|
37
38
|
|
|
38
39
|
for (const session of sessions) {
|
|
40
|
+
let stopError = null;
|
|
39
41
|
try {
|
|
40
42
|
await callAPI('stop', { profileId: session.profileId });
|
|
43
|
+
} catch (err) {
|
|
44
|
+
stopError = err;
|
|
45
|
+
} finally {
|
|
46
|
+
stopSessionWatchdog(session.profileId);
|
|
41
47
|
releaseLock(session.profileId);
|
|
42
48
|
markSessionClosed(session.profileId);
|
|
43
|
-
results.push({ profileId: session.profileId, ok: true });
|
|
44
|
-
} catch (err) {
|
|
45
|
-
results.push({ profileId: session.profileId, ok: false, error: err.message });
|
|
46
49
|
}
|
|
50
|
+
results.push(
|
|
51
|
+
stopError
|
|
52
|
+
? { profileId: session.profileId, ok: false, error: stopError.message }
|
|
53
|
+
: { profileId: session.profileId, ok: true },
|
|
54
|
+
);
|
|
47
55
|
}
|
|
48
56
|
} catch {}
|
|
49
57
|
}
|
|
@@ -51,6 +59,7 @@ export async function handleCleanupCommand(args) {
|
|
|
51
59
|
// Cleanup stale locks and sessions
|
|
52
60
|
const cleanedLocks = cleanupStaleLocks();
|
|
53
61
|
const cleanedSessions = cleanupStaleSessions();
|
|
62
|
+
stopAllSessionWatchdogs();
|
|
54
63
|
|
|
55
64
|
console.log(JSON.stringify({
|
|
56
65
|
ok: true,
|
|
@@ -74,6 +83,7 @@ export async function handleCleanupCommand(args) {
|
|
|
74
83
|
} catch {}
|
|
75
84
|
}
|
|
76
85
|
|
|
86
|
+
stopSessionWatchdog(profileId);
|
|
77
87
|
releaseLock(profileId);
|
|
78
88
|
markSessionClosed(profileId);
|
|
79
89
|
console.log(JSON.stringify({ ok: true, profileId }, null, 2));
|
|
@@ -86,11 +96,13 @@ export async function handleForceStopCommand(args) {
|
|
|
86
96
|
|
|
87
97
|
try {
|
|
88
98
|
const result = await callAPI('stop', { profileId, force: true });
|
|
99
|
+
stopSessionWatchdog(profileId);
|
|
89
100
|
releaseLock(profileId);
|
|
90
101
|
markSessionClosed(profileId);
|
|
91
102
|
console.log(JSON.stringify({ ok: true, profileId, ...result }, null, 2));
|
|
92
103
|
} catch (err) {
|
|
93
104
|
// Even if stop fails, cleanup local state
|
|
105
|
+
stopSessionWatchdog(profileId);
|
|
94
106
|
releaseLock(profileId);
|
|
95
107
|
markSessionClosed(profileId);
|
|
96
108
|
console.log(JSON.stringify({ ok: true, profileId, warning: 'Session stopped locally but remote stop failed: ' + err.message }, null, 2));
|
|
@@ -204,6 +216,7 @@ export async function handleRecoverCommand(args) {
|
|
|
204
216
|
|
|
205
217
|
if (!serviceUp) {
|
|
206
218
|
// Service is down - session cannot be recovered, clean up
|
|
219
|
+
stopSessionWatchdog(profileId);
|
|
207
220
|
unregisterSession(profileId);
|
|
208
221
|
releaseLock(profileId);
|
|
209
222
|
console.log(JSON.stringify({
|
|
@@ -240,6 +253,7 @@ export async function handleRecoverCommand(args) {
|
|
|
240
253
|
}, null, 2));
|
|
241
254
|
} else {
|
|
242
255
|
// Session not in browser service - clean up
|
|
256
|
+
stopSessionWatchdog(profileId);
|
|
243
257
|
unregisterSession(profileId);
|
|
244
258
|
releaseLock(profileId);
|
|
245
259
|
console.log(JSON.stringify({
|
package/src/commands/window.mjs
CHANGED
|
@@ -24,7 +24,38 @@ export async function handleWindowCommand(args) {
|
|
|
24
24
|
const width = parseInt(args[widthIdx + 1]);
|
|
25
25
|
const height = parseInt(args[heightIdx + 1]);
|
|
26
26
|
const result = await callAPI('window:resize', { profileId, width, height });
|
|
27
|
-
|
|
27
|
+
const measured = await callAPI('evaluate', {
|
|
28
|
+
profileId,
|
|
29
|
+
script: '({ innerWidth: window.innerWidth, innerHeight: window.innerHeight, outerWidth: window.outerWidth, outerHeight: window.outerHeight })',
|
|
30
|
+
});
|
|
31
|
+
const innerWidth = Math.max(320, Number(measured?.result?.innerWidth || 0) || 0);
|
|
32
|
+
const innerHeight = Math.max(240, Number(measured?.result?.innerHeight || 0) || 0);
|
|
33
|
+
const outerWidth = Math.max(320, Number(measured?.result?.outerWidth || 0) || innerWidth);
|
|
34
|
+
const outerHeight = Math.max(240, Number(measured?.result?.outerHeight || 0) || innerHeight);
|
|
35
|
+
const rawDeltaW = Math.max(0, outerWidth - innerWidth);
|
|
36
|
+
const rawDeltaH = Math.max(0, outerHeight - innerHeight);
|
|
37
|
+
const frameW = rawDeltaW > 400 ? 16 : Math.min(rawDeltaW, 120);
|
|
38
|
+
const frameH = rawDeltaH > 400 ? 88 : Math.min(rawDeltaH, 180);
|
|
39
|
+
const targetViewportWidth = Math.max(320, outerWidth - frameW);
|
|
40
|
+
const targetViewportHeight = Math.max(240, outerHeight - frameH);
|
|
41
|
+
const viewport = await callAPI('page:setViewport', {
|
|
42
|
+
profileId,
|
|
43
|
+
width: targetViewportWidth,
|
|
44
|
+
height: targetViewportHeight,
|
|
45
|
+
});
|
|
46
|
+
console.log(JSON.stringify({
|
|
47
|
+
ok: true,
|
|
48
|
+
profileId,
|
|
49
|
+
window: result,
|
|
50
|
+
measured: measured?.result || null,
|
|
51
|
+
targetViewport: {
|
|
52
|
+
width: targetViewportWidth,
|
|
53
|
+
height: targetViewportHeight,
|
|
54
|
+
frameW,
|
|
55
|
+
frameH,
|
|
56
|
+
},
|
|
57
|
+
viewport,
|
|
58
|
+
}, null, 2));
|
|
28
59
|
} else {
|
|
29
60
|
throw new Error('Usage: camo window <move|resize> [profileId] --x <x> --y <y> / --width <w> --height <h>');
|
|
30
61
|
}
|
|
@@ -1,5 +1,87 @@
|
|
|
1
1
|
// Change Notifier - Subscribe to DOM changes and element events
|
|
2
2
|
|
|
3
|
+
function normalizeSelector(selector) {
|
|
4
|
+
if (!selector) return { visible: true };
|
|
5
|
+
if (typeof selector === 'string') return { css: selector, visible: true };
|
|
6
|
+
if (typeof selector !== 'object') return { visible: true };
|
|
7
|
+
return {
|
|
8
|
+
...selector,
|
|
9
|
+
visible: selector.visible !== false,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function selectorKey(selector) {
|
|
14
|
+
const normalized = normalizeSelector(selector);
|
|
15
|
+
const stable = {
|
|
16
|
+
css: normalized.css || null,
|
|
17
|
+
tag: normalized.tag || null,
|
|
18
|
+
id: normalized.id || null,
|
|
19
|
+
classes: Array.isArray(normalized.classes) ? [...normalized.classes].sort() : [],
|
|
20
|
+
visible: normalized.visible !== false,
|
|
21
|
+
};
|
|
22
|
+
return JSON.stringify(stable);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseCssSelector(css) {
|
|
26
|
+
const raw = typeof css === 'string' ? css.trim() : '';
|
|
27
|
+
if (!raw) return [];
|
|
28
|
+
const attrRegex = /\[\s*([^\s~|^$*=\]]+)\s*(\*=|\^=|\$=|=)?\s*(?:"([^"]*)"|'([^']*)'|([^\]\s]+))?\s*\]/g;
|
|
29
|
+
return raw
|
|
30
|
+
.split(',')
|
|
31
|
+
.map((item) => item.trim())
|
|
32
|
+
.filter(Boolean)
|
|
33
|
+
.map((item) => {
|
|
34
|
+
const tagMatch = item.match(/^[a-zA-Z][\w-]*/);
|
|
35
|
+
const idMatch = item.match(/#([\w-]+)/);
|
|
36
|
+
const classMatches = item.match(/\.([\w-]+)/g) || [];
|
|
37
|
+
const attrs = [];
|
|
38
|
+
let attrMatch = attrRegex.exec(item);
|
|
39
|
+
while (attrMatch) {
|
|
40
|
+
attrs.push({
|
|
41
|
+
name: String(attrMatch[1] || '').toLowerCase(),
|
|
42
|
+
op: attrMatch[2] || 'exists',
|
|
43
|
+
value: attrMatch[3] ?? attrMatch[4] ?? attrMatch[5] ?? '',
|
|
44
|
+
});
|
|
45
|
+
attrMatch = attrRegex.exec(item);
|
|
46
|
+
}
|
|
47
|
+
attrRegex.lastIndex = 0;
|
|
48
|
+
return {
|
|
49
|
+
tag: tagMatch ? tagMatch[0].toLowerCase() : null,
|
|
50
|
+
id: idMatch ? idMatch[1] : null,
|
|
51
|
+
classes: classMatches.map((token) => token.slice(1)),
|
|
52
|
+
attrs,
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function nodeAttribute(node, name, nodeId, nodeClasses) {
|
|
58
|
+
const key = String(name || '').toLowerCase();
|
|
59
|
+
if (!key) return null;
|
|
60
|
+
if (key === 'id') return nodeId || null;
|
|
61
|
+
if (key === 'class') return Array.from(nodeClasses).join(' ');
|
|
62
|
+
|
|
63
|
+
const attrs = node?.attrs && typeof node.attrs === 'object' ? node.attrs : null;
|
|
64
|
+
if (attrs && attrs[key] !== undefined && attrs[key] !== null) return String(attrs[key]);
|
|
65
|
+
|
|
66
|
+
const direct = node?.[key];
|
|
67
|
+
if (typeof direct === 'string' || typeof direct === 'number' || typeof direct === 'boolean') {
|
|
68
|
+
return String(direct);
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function matchAttribute(node, attrSpec, nodeId, nodeClasses) {
|
|
74
|
+
const value = nodeAttribute(node, attrSpec.name, nodeId, nodeClasses);
|
|
75
|
+
if (attrSpec.op === 'exists') return value !== null && value !== '';
|
|
76
|
+
if (value === null) return false;
|
|
77
|
+
const expected = String(attrSpec.value || '');
|
|
78
|
+
if (attrSpec.op === '=') return value === expected;
|
|
79
|
+
if (attrSpec.op === '*=') return value.includes(expected);
|
|
80
|
+
if (attrSpec.op === '^=') return value.startsWith(expected);
|
|
81
|
+
if (attrSpec.op === '$=') return value.endsWith(expected);
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
3
85
|
export class ChangeNotifier {
|
|
4
86
|
constructor() {
|
|
5
87
|
this.subscriptions = new Map(); // topic -> Set<callback>
|
|
@@ -7,6 +89,28 @@ export class ChangeNotifier {
|
|
|
7
89
|
this.lastSnapshot = null;
|
|
8
90
|
}
|
|
9
91
|
|
|
92
|
+
nodePassesVisibility(node, selector, viewport) {
|
|
93
|
+
const normalized = normalizeSelector(selector);
|
|
94
|
+
if (normalized.visible === false) return true;
|
|
95
|
+
if (!node || typeof node !== 'object') return false;
|
|
96
|
+
if (typeof node.visible === 'boolean') return node.visible;
|
|
97
|
+
|
|
98
|
+
const rect = node.rect || null;
|
|
99
|
+
if (!rect) return true;
|
|
100
|
+
const width = Number(rect.width || 0);
|
|
101
|
+
const height = Number(rect.height || 0);
|
|
102
|
+
if (width <= 0 || height <= 0) return false;
|
|
103
|
+
|
|
104
|
+
const vw = Number(viewport?.width || 0);
|
|
105
|
+
const vh = Number(viewport?.height || 0);
|
|
106
|
+
if (vw <= 0 || vh <= 0) return true;
|
|
107
|
+
const left = Number(rect.left ?? rect.x ?? 0);
|
|
108
|
+
const top = Number(rect.top ?? rect.y ?? 0);
|
|
109
|
+
const right = Number(rect.right ?? (left + width));
|
|
110
|
+
const bottom = Number(rect.bottom ?? (top + height));
|
|
111
|
+
return right > 0 && bottom > 0 && left < vw && top < vh;
|
|
112
|
+
}
|
|
113
|
+
|
|
10
114
|
// Subscribe to a topic
|
|
11
115
|
subscribe(topic, callback) {
|
|
12
116
|
if (!this.subscriptions.has(topic)) {
|
|
@@ -21,22 +125,28 @@ export class ChangeNotifier {
|
|
|
21
125
|
// Watch specific elements by selector
|
|
22
126
|
watch(selector, options = {}) {
|
|
23
127
|
const { onAppear, onDisappear, onChange, throttle = 200 } = options;
|
|
128
|
+
const resolvedSelector = normalizeSelector(selector);
|
|
129
|
+
const key = selectorKey(resolvedSelector);
|
|
130
|
+
const resolvedThrottle = Math.max(50, Number(throttle) || 200);
|
|
24
131
|
|
|
25
|
-
if (!this.elementWatchers.has(
|
|
26
|
-
this.elementWatchers.set(
|
|
132
|
+
if (!this.elementWatchers.has(key)) {
|
|
133
|
+
this.elementWatchers.set(key, {
|
|
134
|
+
selector: resolvedSelector,
|
|
27
135
|
lastState: null,
|
|
28
136
|
lastNotifyTime: 0,
|
|
137
|
+
throttle: resolvedThrottle,
|
|
29
138
|
callbacks: { onAppear, onDisappear, onChange },
|
|
30
139
|
});
|
|
31
140
|
} else {
|
|
32
|
-
const watcher = this.elementWatchers.get(
|
|
141
|
+
const watcher = this.elementWatchers.get(key);
|
|
33
142
|
if (onAppear) watcher.callbacks.onAppear = onAppear;
|
|
34
143
|
if (onDisappear) watcher.callbacks.onDisappear = onDisappear;
|
|
35
144
|
if (onChange) watcher.callbacks.onChange = onChange;
|
|
145
|
+
watcher.throttle = resolvedThrottle;
|
|
36
146
|
}
|
|
37
147
|
|
|
38
148
|
return () => {
|
|
39
|
-
this.elementWatchers.delete(
|
|
149
|
+
this.elementWatchers.delete(key);
|
|
40
150
|
};
|
|
41
151
|
}
|
|
42
152
|
|
|
@@ -63,13 +173,13 @@ export class ChangeNotifier {
|
|
|
63
173
|
this.notify('dom:changed', { snapshot, prevSnapshot });
|
|
64
174
|
|
|
65
175
|
// Process element watchers
|
|
66
|
-
for (const [
|
|
176
|
+
for (const [, watcher] of this.elementWatchers) {
|
|
67
177
|
const { lastState, callbacks, lastNotifyTime, throttle } = watcher;
|
|
68
178
|
|
|
69
179
|
// Throttle notifications
|
|
70
180
|
if (now - lastNotifyTime < throttle) continue;
|
|
71
181
|
|
|
72
|
-
const currentElements = this.findElements(snapshot, selector);
|
|
182
|
+
const currentElements = this.findElements(snapshot, watcher.selector);
|
|
73
183
|
const currentState = currentElements.map(e => e.path).sort().join(',');
|
|
74
184
|
|
|
75
185
|
if (lastState !== null && currentState !== lastState) {
|
|
@@ -98,19 +208,23 @@ export class ChangeNotifier {
|
|
|
98
208
|
}
|
|
99
209
|
|
|
100
210
|
// Find elements matching selector in DOM tree
|
|
101
|
-
findElements(node, selector, path = 'root') {
|
|
211
|
+
findElements(node, selector, path = 'root', context = null) {
|
|
102
212
|
const results = [];
|
|
103
213
|
if (!node) return results;
|
|
214
|
+
const normalized = normalizeSelector(selector);
|
|
215
|
+
const runtimeContext = context || {
|
|
216
|
+
viewport: node?.__viewport || null,
|
|
217
|
+
};
|
|
104
218
|
|
|
105
219
|
// Check if current node matches
|
|
106
|
-
if (this.nodeMatchesSelector(node,
|
|
220
|
+
if (this.nodeMatchesSelector(node, normalized) && this.nodePassesVisibility(node, normalized, runtimeContext.viewport)) {
|
|
107
221
|
results.push({ ...node, path });
|
|
108
222
|
}
|
|
109
223
|
|
|
110
224
|
// Recurse into children
|
|
111
225
|
if (node.children) {
|
|
112
226
|
for (let i = 0; i < node.children.length; i++) {
|
|
113
|
-
const childResults = this.findElements(node.children[i],
|
|
227
|
+
const childResults = this.findElements(node.children[i], normalized, `${path}/${i}`, runtimeContext);
|
|
114
228
|
results.push(...childResults);
|
|
115
229
|
}
|
|
116
230
|
}
|
|
@@ -121,27 +235,54 @@ export class ChangeNotifier {
|
|
|
121
235
|
// Check if node matches selector
|
|
122
236
|
nodeMatchesSelector(node, selector) {
|
|
123
237
|
if (!node) return false;
|
|
238
|
+
const normalized = normalizeSelector(selector);
|
|
239
|
+
if (!normalized || typeof normalized !== 'object') return false;
|
|
124
240
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
241
|
+
const nodeTag = typeof node.tag === 'string' ? node.tag.toLowerCase() : null;
|
|
242
|
+
const nodeId = typeof node.id === 'string' ? node.id : null;
|
|
243
|
+
const nodeClasses = new Set(Array.isArray(node.classes) ? node.classes : []);
|
|
244
|
+
|
|
245
|
+
// Exact selector string (fast path).
|
|
246
|
+
if (normalized.css && node.selector === normalized.css) return true;
|
|
247
|
+
|
|
248
|
+
const cssVariants = parseCssSelector(normalized.css);
|
|
249
|
+
if (cssVariants.length > 0) {
|
|
250
|
+
for (const cssVariant of cssVariants) {
|
|
251
|
+
const hasConstraints = Boolean(
|
|
252
|
+
cssVariant.tag
|
|
253
|
+
|| cssVariant.id
|
|
254
|
+
|| (cssVariant.classes && cssVariant.classes.length > 0)
|
|
255
|
+
|| (cssVariant.attrs && cssVariant.attrs.length > 0),
|
|
256
|
+
);
|
|
257
|
+
if (!hasConstraints) continue;
|
|
258
|
+
|
|
259
|
+
let matched = true;
|
|
260
|
+
if (cssVariant.tag && nodeTag !== cssVariant.tag) matched = false;
|
|
261
|
+
if (cssVariant.id && nodeId !== cssVariant.id) matched = false;
|
|
262
|
+
if (matched && cssVariant.classes.length > 0) {
|
|
263
|
+
matched = cssVariant.classes.every((className) => nodeClasses.has(className));
|
|
264
|
+
}
|
|
265
|
+
if (matched && cssVariant.attrs.length > 0) {
|
|
266
|
+
matched = cssVariant.attrs.every((attrSpec) => matchAttribute(node, attrSpec, nodeId, nodeClasses));
|
|
267
|
+
}
|
|
268
|
+
if (matched) return true;
|
|
132
269
|
}
|
|
133
270
|
}
|
|
134
271
|
|
|
135
|
-
|
|
136
|
-
|
|
272
|
+
const requiredTag = normalized.tag ? String(normalized.tag).toLowerCase() : null;
|
|
273
|
+
const requiredId = normalized.id ? String(normalized.id) : null;
|
|
274
|
+
const requiredClasses = Array.isArray(normalized.classes)
|
|
275
|
+
? normalized.classes.filter(Boolean).map((className) => String(className))
|
|
276
|
+
: [];
|
|
137
277
|
|
|
138
|
-
|
|
139
|
-
if (
|
|
140
|
-
|
|
141
|
-
|
|
278
|
+
const hasStructuredSelector = Boolean(requiredTag || requiredId || requiredClasses.length > 0);
|
|
279
|
+
if (!hasStructuredSelector) return false;
|
|
280
|
+
if (requiredTag && nodeTag !== requiredTag) return false;
|
|
281
|
+
if (requiredId && nodeId !== requiredId) return false;
|
|
282
|
+
if (requiredClasses.length > 0 && !requiredClasses.every((className) => nodeClasses.has(className))) {
|
|
283
|
+
return false;
|
|
142
284
|
}
|
|
143
|
-
|
|
144
|
-
return false;
|
|
285
|
+
return true;
|
|
145
286
|
}
|
|
146
287
|
|
|
147
288
|
// Cleanup
|
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
// Container Element Filter - Filter DOM elements by visibility, container definitions
|
|
2
2
|
|
|
3
|
+
function parseCssSelector(css) {
|
|
4
|
+
const raw = typeof css === 'string' ? css.trim() : '';
|
|
5
|
+
if (!raw) return [];
|
|
6
|
+
return raw
|
|
7
|
+
.split(',')
|
|
8
|
+
.map((item) => item.trim())
|
|
9
|
+
.filter(Boolean)
|
|
10
|
+
.map((item) => {
|
|
11
|
+
const tagMatch = item.match(/^[a-zA-Z][\w-]*/);
|
|
12
|
+
const idMatch = item.match(/#([\w-]+)/);
|
|
13
|
+
const classMatches = item.match(/\.([\w-]+)/g) || [];
|
|
14
|
+
return {
|
|
15
|
+
tag: tagMatch ? tagMatch[0].toLowerCase() : null,
|
|
16
|
+
id: idMatch ? idMatch[1] : null,
|
|
17
|
+
classes: classMatches.map((token) => token.slice(1)),
|
|
18
|
+
};
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
3
22
|
export class ElementFilter {
|
|
4
23
|
constructor(options = {}) {
|
|
5
24
|
this.viewportMargin = options.viewportMargin || 0;
|
|
@@ -52,13 +71,40 @@ export class ElementFilter {
|
|
|
52
71
|
|
|
53
72
|
// Check if element matches selector definition
|
|
54
73
|
matchesSelector(element, selector) {
|
|
74
|
+
if (!element || !selector) return false;
|
|
55
75
|
if (selector.css && element.selector === selector.css) return true;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
76
|
+
|
|
77
|
+
const elementTag = typeof element.tag === 'string' ? element.tag.toLowerCase() : null;
|
|
78
|
+
const elementId = typeof element.id === 'string' ? element.id : null;
|
|
79
|
+
const elementClasses = new Set(Array.isArray(element.classes) ? element.classes : []);
|
|
80
|
+
|
|
81
|
+
const cssVariants = parseCssSelector(selector.css);
|
|
82
|
+
if (cssVariants.length > 0) {
|
|
83
|
+
for (const cssVariant of cssVariants) {
|
|
84
|
+
let matched = true;
|
|
85
|
+
if (cssVariant.tag && elementTag !== cssVariant.tag) matched = false;
|
|
86
|
+
if (cssVariant.id && elementId !== cssVariant.id) matched = false;
|
|
87
|
+
if (matched && cssVariant.classes.length > 0) {
|
|
88
|
+
matched = cssVariant.classes.every((className) => elementClasses.has(className));
|
|
89
|
+
}
|
|
90
|
+
if (matched) return true;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const requiredTag = selector.tag ? String(selector.tag).toLowerCase() : null;
|
|
95
|
+
const requiredId = selector.id ? String(selector.id) : null;
|
|
96
|
+
const requiredClasses = Array.isArray(selector.classes)
|
|
97
|
+
? selector.classes.filter(Boolean).map((className) => String(className))
|
|
98
|
+
: [];
|
|
99
|
+
|
|
100
|
+
const hasStructuredSelector = Boolean(requiredTag || requiredId || requiredClasses.length > 0);
|
|
101
|
+
if (!hasStructuredSelector) return false;
|
|
102
|
+
if (requiredTag && elementTag !== requiredTag) return false;
|
|
103
|
+
if (requiredId && elementId !== requiredId) return false;
|
|
104
|
+
if (requiredClasses.length > 0 && !requiredClasses.every((className) => elementClasses.has(className))) {
|
|
105
|
+
return false;
|
|
60
106
|
}
|
|
61
|
-
return
|
|
107
|
+
return true;
|
|
62
108
|
}
|
|
63
109
|
|
|
64
110
|
// Main filter method
|