@web-auto/camo 0.1.2 → 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 +7 -3
- 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 +190 -78
- package/src/commands/autoscript.mjs +1100 -0
- package/src/commands/browser.mjs +20 -4
- package/src/commands/container.mjs +401 -0
- 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 +311 -0
- package/src/container/element-filter.mjs +143 -0
- package/src/container/index.mjs +3 -0
- 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 +200 -0
- 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 +28 -0
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
|
}
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
// Change Notifier - Subscribe to DOM changes and element events
|
|
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
|
+
|
|
85
|
+
export class ChangeNotifier {
|
|
86
|
+
constructor() {
|
|
87
|
+
this.subscriptions = new Map(); // topic -> Set<callback>
|
|
88
|
+
this.elementWatchers = new Map(); // selector -> { lastState, callbacks }
|
|
89
|
+
this.lastSnapshot = null;
|
|
90
|
+
}
|
|
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
|
+
|
|
114
|
+
// Subscribe to a topic
|
|
115
|
+
subscribe(topic, callback) {
|
|
116
|
+
if (!this.subscriptions.has(topic)) {
|
|
117
|
+
this.subscriptions.set(topic, new Set());
|
|
118
|
+
}
|
|
119
|
+
this.subscriptions.get(topic).add(callback);
|
|
120
|
+
return () => {
|
|
121
|
+
this.subscriptions.get(topic)?.delete(callback);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Watch specific elements by selector
|
|
126
|
+
watch(selector, options = {}) {
|
|
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);
|
|
131
|
+
|
|
132
|
+
if (!this.elementWatchers.has(key)) {
|
|
133
|
+
this.elementWatchers.set(key, {
|
|
134
|
+
selector: resolvedSelector,
|
|
135
|
+
lastState: null,
|
|
136
|
+
lastNotifyTime: 0,
|
|
137
|
+
throttle: resolvedThrottle,
|
|
138
|
+
callbacks: { onAppear, onDisappear, onChange },
|
|
139
|
+
});
|
|
140
|
+
} else {
|
|
141
|
+
const watcher = this.elementWatchers.get(key);
|
|
142
|
+
if (onAppear) watcher.callbacks.onAppear = onAppear;
|
|
143
|
+
if (onDisappear) watcher.callbacks.onDisappear = onDisappear;
|
|
144
|
+
if (onChange) watcher.callbacks.onChange = onChange;
|
|
145
|
+
watcher.throttle = resolvedThrottle;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return () => {
|
|
149
|
+
this.elementWatchers.delete(key);
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Notify all subscribers of a topic
|
|
154
|
+
notify(topic, data) {
|
|
155
|
+
const callbacks = this.subscriptions.get(topic);
|
|
156
|
+
if (!callbacks) return;
|
|
157
|
+
for (const callback of callbacks) {
|
|
158
|
+
try {
|
|
159
|
+
callback(data);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
console.error(`[ChangeNotifier] callback error for ${topic}:`, err);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Process new DOM snapshot and trigger notifications
|
|
167
|
+
processSnapshot(snapshot) {
|
|
168
|
+
const now = Date.now();
|
|
169
|
+
const prevSnapshot = this.lastSnapshot;
|
|
170
|
+
this.lastSnapshot = snapshot;
|
|
171
|
+
|
|
172
|
+
// Notify general DOM change
|
|
173
|
+
this.notify('dom:changed', { snapshot, prevSnapshot });
|
|
174
|
+
|
|
175
|
+
// Process element watchers
|
|
176
|
+
for (const [, watcher] of this.elementWatchers) {
|
|
177
|
+
const { lastState, callbacks, lastNotifyTime, throttle } = watcher;
|
|
178
|
+
|
|
179
|
+
// Throttle notifications
|
|
180
|
+
if (now - lastNotifyTime < throttle) continue;
|
|
181
|
+
|
|
182
|
+
const currentElements = this.findElements(snapshot, watcher.selector);
|
|
183
|
+
const currentState = currentElements.map(e => e.path).sort().join(',');
|
|
184
|
+
|
|
185
|
+
if (lastState !== null && currentState !== lastState) {
|
|
186
|
+
// Something changed
|
|
187
|
+
const prevElements = watcher.prevElements || [];
|
|
188
|
+
const appeared = currentElements.filter(e => !prevElements.find(p => p.path === e.path));
|
|
189
|
+
const disappeared = prevElements.filter(e => !currentElements.find(c => c.path === e.path));
|
|
190
|
+
|
|
191
|
+
if (appeared.length > 0 && callbacks.onAppear) {
|
|
192
|
+
callbacks.onAppear(appeared);
|
|
193
|
+
watcher.lastNotifyTime = now;
|
|
194
|
+
}
|
|
195
|
+
if (disappeared.length > 0 && callbacks.onDisappear) {
|
|
196
|
+
callbacks.onDisappear(disappeared);
|
|
197
|
+
watcher.lastNotifyTime = now;
|
|
198
|
+
}
|
|
199
|
+
if (callbacks.onChange) {
|
|
200
|
+
callbacks.onChange({ current: currentElements, previous: prevElements, appeared, disappeared });
|
|
201
|
+
watcher.lastNotifyTime = now;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
watcher.lastState = currentState;
|
|
206
|
+
watcher.prevElements = currentElements;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Find elements matching selector in DOM tree
|
|
211
|
+
findElements(node, selector, path = 'root', context = null) {
|
|
212
|
+
const results = [];
|
|
213
|
+
if (!node) return results;
|
|
214
|
+
const normalized = normalizeSelector(selector);
|
|
215
|
+
const runtimeContext = context || {
|
|
216
|
+
viewport: node?.__viewport || null,
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// Check if current node matches
|
|
220
|
+
if (this.nodeMatchesSelector(node, normalized) && this.nodePassesVisibility(node, normalized, runtimeContext.viewport)) {
|
|
221
|
+
results.push({ ...node, path });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Recurse into children
|
|
225
|
+
if (node.children) {
|
|
226
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
227
|
+
const childResults = this.findElements(node.children[i], normalized, `${path}/${i}`, runtimeContext);
|
|
228
|
+
results.push(...childResults);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return results;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Check if node matches selector
|
|
236
|
+
nodeMatchesSelector(node, selector) {
|
|
237
|
+
if (!node) return false;
|
|
238
|
+
const normalized = normalizeSelector(selector);
|
|
239
|
+
if (!normalized || typeof normalized !== 'object') return false;
|
|
240
|
+
|
|
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;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
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
|
+
: [];
|
|
277
|
+
|
|
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;
|
|
284
|
+
}
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Cleanup
|
|
289
|
+
destroy() {
|
|
290
|
+
this.subscriptions.clear();
|
|
291
|
+
this.elementWatchers.clear();
|
|
292
|
+
this.lastSnapshot = null;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Global instance
|
|
297
|
+
let globalNotifier = null;
|
|
298
|
+
|
|
299
|
+
export function getChangeNotifier() {
|
|
300
|
+
if (!globalNotifier) {
|
|
301
|
+
globalNotifier = new ChangeNotifier();
|
|
302
|
+
}
|
|
303
|
+
return globalNotifier;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function destroyChangeNotifier() {
|
|
307
|
+
if (globalNotifier) {
|
|
308
|
+
globalNotifier.destroy();
|
|
309
|
+
globalNotifier = null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Container Element Filter - Filter DOM elements by visibility, container definitions
|
|
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
|
+
|
|
22
|
+
export class ElementFilter {
|
|
23
|
+
constructor(options = {}) {
|
|
24
|
+
this.viewportMargin = options.viewportMargin || 0;
|
|
25
|
+
this.minVisibleRatio = options.minVisibleRatio || 0.5;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Check if element is in viewport
|
|
29
|
+
isInViewport(rect, viewport) {
|
|
30
|
+
return (
|
|
31
|
+
rect.left < viewport.width + this.viewportMargin &&
|
|
32
|
+
rect.right > -this.viewportMargin &&
|
|
33
|
+
rect.top < viewport.height + this.viewportMargin &&
|
|
34
|
+
rect.bottom > -this.viewportMargin
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Calculate visibility ratio
|
|
39
|
+
getVisibilityRatio(rect, viewport) {
|
|
40
|
+
const visibleLeft = Math.max(0, rect.left);
|
|
41
|
+
const visibleTop = Math.max(0, rect.top);
|
|
42
|
+
const visibleRight = Math.min(viewport.width, rect.right);
|
|
43
|
+
const visibleBottom = Math.min(viewport.height, rect.bottom);
|
|
44
|
+
|
|
45
|
+
const visibleArea = Math.max(0, visibleRight - visibleLeft) * Math.max(0, visibleBottom - visibleTop);
|
|
46
|
+
const totalArea = rect.width * rect.height;
|
|
47
|
+
|
|
48
|
+
return totalArea > 0 ? visibleArea / totalArea : 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Filter elements by container definition
|
|
52
|
+
filterByContainer(elements, containerDef) {
|
|
53
|
+
const selectors = containerDef.selectors || [];
|
|
54
|
+
const results = [];
|
|
55
|
+
|
|
56
|
+
for (const element of elements) {
|
|
57
|
+
for (const selector of selectors) {
|
|
58
|
+
if (this.matchesSelector(element, selector)) {
|
|
59
|
+
results.push({
|
|
60
|
+
element,
|
|
61
|
+
container: containerDef,
|
|
62
|
+
matchedSelector: selector,
|
|
63
|
+
});
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return results;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Check if element matches selector definition
|
|
73
|
+
matchesSelector(element, selector) {
|
|
74
|
+
if (!element || !selector) return false;
|
|
75
|
+
if (selector.css && element.selector === selector.css) return true;
|
|
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;
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Main filter method
|
|
111
|
+
filter(elements, options = {}) {
|
|
112
|
+
const {
|
|
113
|
+
container,
|
|
114
|
+
viewport,
|
|
115
|
+
requireVisible = true,
|
|
116
|
+
minVisibleRatio = this.minVisibleRatio,
|
|
117
|
+
} = options;
|
|
118
|
+
|
|
119
|
+
let results = [...elements];
|
|
120
|
+
|
|
121
|
+
// Filter by container definition
|
|
122
|
+
if (container) {
|
|
123
|
+
results = this.filterByContainer(results, container);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Filter by viewport visibility
|
|
127
|
+
if (requireVisible && viewport) {
|
|
128
|
+
results = results.filter(item => {
|
|
129
|
+
const rect = item.element?.rect || item.rect;
|
|
130
|
+
if (!rect) return false;
|
|
131
|
+
const ratio = this.getVisibilityRatio(rect, viewport);
|
|
132
|
+
item.visibilityRatio = ratio;
|
|
133
|
+
return ratio >= minVisibleRatio;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return results;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function createElementFilter(options) {
|
|
142
|
+
return new ElementFilter(options);
|
|
143
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { callAPI, getDomSnapshotByProfile } from '../../utils/browser-service.mjs';
|
|
2
|
+
import {
|
|
3
|
+
asErrorPayload,
|
|
4
|
+
buildSelectorCheck,
|
|
5
|
+
ensureActiveSession,
|
|
6
|
+
getCurrentUrl,
|
|
7
|
+
isCheckpointRiskUrl,
|
|
8
|
+
maybeSelector,
|
|
9
|
+
normalizeArray,
|
|
10
|
+
} from './utils.mjs';
|
|
11
|
+
|
|
12
|
+
export const XHS_CHECKPOINTS = {
|
|
13
|
+
search_ready: [
|
|
14
|
+
'#search-input',
|
|
15
|
+
'input.search-input',
|
|
16
|
+
'.search-result-list',
|
|
17
|
+
],
|
|
18
|
+
home_ready: [
|
|
19
|
+
'.feeds-page',
|
|
20
|
+
'.note-item',
|
|
21
|
+
],
|
|
22
|
+
detail_ready: [
|
|
23
|
+
'.note-scroller',
|
|
24
|
+
'.note-content',
|
|
25
|
+
'.interaction-container',
|
|
26
|
+
],
|
|
27
|
+
comments_ready: [
|
|
28
|
+
'.comments-container',
|
|
29
|
+
'.comment-item',
|
|
30
|
+
],
|
|
31
|
+
login_guard: [
|
|
32
|
+
'.login-container',
|
|
33
|
+
'.login-dialog',
|
|
34
|
+
'#login-container',
|
|
35
|
+
],
|
|
36
|
+
risk_control: [
|
|
37
|
+
'.qrcode-box',
|
|
38
|
+
'.captcha-container',
|
|
39
|
+
'[class*="captcha"]',
|
|
40
|
+
],
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export async function detectCheckpoint({ profileId, platform = 'xiaohongshu' }) {
|
|
44
|
+
if (platform !== 'xiaohongshu') {
|
|
45
|
+
return asErrorPayload('UNSUPPORTED_PLATFORM', `Unsupported platform: ${platform}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const session = await ensureActiveSession(profileId);
|
|
50
|
+
const resolvedProfile = session.profileId || profileId;
|
|
51
|
+
const [url, snapshot] = await Promise.all([
|
|
52
|
+
getCurrentUrl(resolvedProfile),
|
|
53
|
+
getDomSnapshotByProfile(resolvedProfile),
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
const signals = [];
|
|
57
|
+
const counter = {};
|
|
58
|
+
const addCount = (label, selectors) => {
|
|
59
|
+
for (const css of selectors) {
|
|
60
|
+
const count = buildSelectorCheck(snapshot, css).length;
|
|
61
|
+
if (count > 0) {
|
|
62
|
+
counter[css] = count;
|
|
63
|
+
signals.push(`${label}:${css}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
addCount('search_ready', XHS_CHECKPOINTS.search_ready);
|
|
69
|
+
addCount('home_ready', XHS_CHECKPOINTS.home_ready);
|
|
70
|
+
addCount('detail_ready', XHS_CHECKPOINTS.detail_ready);
|
|
71
|
+
addCount('comments_ready', XHS_CHECKPOINTS.comments_ready);
|
|
72
|
+
addCount('login_guard', XHS_CHECKPOINTS.login_guard);
|
|
73
|
+
addCount('risk_control', XHS_CHECKPOINTS.risk_control);
|
|
74
|
+
|
|
75
|
+
let checkpoint = 'unknown';
|
|
76
|
+
if (!url || !url.includes('xiaohongshu.com')) checkpoint = 'offsite';
|
|
77
|
+
else if (isCheckpointRiskUrl(url)) checkpoint = 'risk_control';
|
|
78
|
+
else if (signals.some((item) => item.startsWith('login_guard:'))) checkpoint = 'login_guard';
|
|
79
|
+
else if (signals.some((item) => item.startsWith('comments_ready:'))) checkpoint = 'comments_ready';
|
|
80
|
+
else if (signals.some((item) => item.startsWith('detail_ready:'))) checkpoint = 'detail_ready';
|
|
81
|
+
else if (signals.some((item) => item.startsWith('search_ready:'))) checkpoint = 'search_ready';
|
|
82
|
+
else if (signals.some((item) => item.startsWith('home_ready:'))) checkpoint = 'home_ready';
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
ok: true,
|
|
86
|
+
code: 'CHECKPOINT_DETECTED',
|
|
87
|
+
message: 'Checkpoint detected',
|
|
88
|
+
data: {
|
|
89
|
+
profileId: resolvedProfile,
|
|
90
|
+
platform,
|
|
91
|
+
checkpoint,
|
|
92
|
+
url,
|
|
93
|
+
signals,
|
|
94
|
+
selectorHits: counter,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
} catch (err) {
|
|
98
|
+
return asErrorPayload('CHECKPOINT_DETECT_FAILED', err?.message || String(err));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function captureCheckpoint({
|
|
103
|
+
profileId,
|
|
104
|
+
containerId = null,
|
|
105
|
+
selector = null,
|
|
106
|
+
platform = 'xiaohongshu',
|
|
107
|
+
}) {
|
|
108
|
+
try {
|
|
109
|
+
const session = await ensureActiveSession(profileId);
|
|
110
|
+
const resolvedProfile = session.profileId || profileId;
|
|
111
|
+
const checkpointRes = await detectCheckpoint({ profileId: resolvedProfile, platform });
|
|
112
|
+
const effectiveSelector = maybeSelector({ profileId: resolvedProfile, containerId, selector });
|
|
113
|
+
const snapshot = await getDomSnapshotByProfile(resolvedProfile);
|
|
114
|
+
const matched = effectiveSelector ? buildSelectorCheck(snapshot, effectiveSelector) : [];
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
ok: true,
|
|
118
|
+
code: 'CHECKPOINT_CAPTURED',
|
|
119
|
+
message: 'Checkpoint captured',
|
|
120
|
+
data: {
|
|
121
|
+
profileId: resolvedProfile,
|
|
122
|
+
checkpoint: checkpointRes?.data?.checkpoint || 'unknown',
|
|
123
|
+
checkpointUrl: checkpointRes?.data?.url || '',
|
|
124
|
+
containerId,
|
|
125
|
+
selector: effectiveSelector,
|
|
126
|
+
selectorCount: matched.length,
|
|
127
|
+
capturedAt: new Date().toISOString(),
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
} catch (err) {
|
|
131
|
+
return asErrorPayload('CHECKPOINT_CAPTURE_FAILED', err?.message || String(err));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function restoreCheckpoint({
|
|
136
|
+
profileId,
|
|
137
|
+
checkpoint = null,
|
|
138
|
+
action,
|
|
139
|
+
containerId = null,
|
|
140
|
+
selector = null,
|
|
141
|
+
targetCheckpoint = null,
|
|
142
|
+
platform = 'xiaohongshu',
|
|
143
|
+
}) {
|
|
144
|
+
try {
|
|
145
|
+
const session = await ensureActiveSession(profileId);
|
|
146
|
+
const resolvedProfile = session.profileId || profileId;
|
|
147
|
+
const effectiveSelector = maybeSelector({ profileId: resolvedProfile, containerId, selector });
|
|
148
|
+
let actionResult = null;
|
|
149
|
+
|
|
150
|
+
if (action === 'requery_container') {
|
|
151
|
+
if (!effectiveSelector) return asErrorPayload('CONTAINER_NOT_FOUND', 'Selector is required for requery_container');
|
|
152
|
+
const snapshot = await getDomSnapshotByProfile(resolvedProfile);
|
|
153
|
+
const matches = buildSelectorCheck(snapshot, effectiveSelector);
|
|
154
|
+
if (matches.length === 0) return asErrorPayload('CONTAINER_NOT_FOUND', `Container selector not found: ${effectiveSelector}`);
|
|
155
|
+
actionResult = { selector: effectiveSelector, count: matches.length };
|
|
156
|
+
} else if (action === 'scroll_into_view') {
|
|
157
|
+
if (!effectiveSelector) return asErrorPayload('CONTAINER_NOT_FOUND', 'Selector is required for scroll_into_view');
|
|
158
|
+
actionResult = await callAPI('evaluate', {
|
|
159
|
+
profileId: resolvedProfile,
|
|
160
|
+
script: `(async () => {
|
|
161
|
+
const el = document.querySelector(${JSON.stringify(effectiveSelector)});
|
|
162
|
+
if (!el) throw new Error('Element not found');
|
|
163
|
+
el.scrollIntoView({ behavior: 'auto', block: 'center', inline: 'nearest' });
|
|
164
|
+
return { ok: true, selector: ${JSON.stringify(effectiveSelector)} };
|
|
165
|
+
})()`,
|
|
166
|
+
});
|
|
167
|
+
} else if (action === 'page_back') {
|
|
168
|
+
actionResult = await callAPI('page:back', { profileId: resolvedProfile });
|
|
169
|
+
} else if (action === 'goto_checkpoint_url') {
|
|
170
|
+
const url = checkpoint?.checkpointUrl || checkpoint?.url || '';
|
|
171
|
+
if (!url) return asErrorPayload('CHECKPOINT_RESTORE_FAILED', 'checkpointUrl is required for goto_checkpoint_url');
|
|
172
|
+
actionResult = await callAPI('goto', { profileId: resolvedProfile, url });
|
|
173
|
+
} else {
|
|
174
|
+
return asErrorPayload('UNSUPPORTED_RECOVERY_ACTION', `Unsupported recovery action: ${action}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const checkpointAfter = await detectCheckpoint({ profileId: resolvedProfile, platform });
|
|
178
|
+
const reached = checkpointAfter?.data?.checkpoint || 'unknown';
|
|
179
|
+
const targetMatched = targetCheckpoint ? reached === targetCheckpoint : true;
|
|
180
|
+
return {
|
|
181
|
+
ok: true,
|
|
182
|
+
code: targetMatched ? 'CHECKPOINT_RESTORED' : 'CHECKPOINT_RESTORE_PARTIAL',
|
|
183
|
+
message: targetMatched ? 'Checkpoint restored' : 'Recovery action completed but target checkpoint not reached',
|
|
184
|
+
data: {
|
|
185
|
+
profileId: resolvedProfile,
|
|
186
|
+
action,
|
|
187
|
+
actionResult,
|
|
188
|
+
reachedCheckpoint: reached,
|
|
189
|
+
targetCheckpoint,
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
} catch (err) {
|
|
193
|
+
return asErrorPayload('CHECKPOINT_RESTORE_FAILED', err?.message || String(err));
|
|
194
|
+
}
|
|
195
|
+
}
|