@xbrowser/cli 1.28.0 → 1.30.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 (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
@@ -9,9 +9,81 @@ import {
9
9
  } from "./chunk-KFQGP6VL.js";
10
10
 
11
11
  // src/recorder/session-recorder.ts
12
- import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "fs";
13
- import { join } from "path";
14
- import { homedir } from "os";
12
+ init_site_knowledge();
13
+ import { existsSync, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync2, rmSync } from "fs";
14
+ import { join as join3 } from "path";
15
+ import { homedir as homedir2 } from "os";
16
+
17
+ // src/recorder/network-capture.ts
18
+ function createNetworkCaptureState() {
19
+ return { entries: [], counter: { value: 0 }, lastRequestKey: "", lastRequestTs: 0 };
20
+ }
21
+ function handleNetworkRequest(request, state) {
22
+ const resourceType = request.resourceType();
23
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
24
+ const url = request.url();
25
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
26
+ const dedupKey = request.method() + " " + url;
27
+ const now = Date.now();
28
+ if (state.lastRequestKey === dedupKey && now - state.lastRequestTs < 100) return;
29
+ state.lastRequestKey = dedupKey;
30
+ state.lastRequestTs = now;
31
+ state.counter.value++;
32
+ const entry = {
33
+ id: state.counter.value,
34
+ timestamp: Date.now(),
35
+ method: request.method(),
36
+ url,
37
+ path: new URL(url).pathname,
38
+ status: 0,
39
+ resourceType,
40
+ contentType: "",
41
+ responseSize: 0
42
+ };
43
+ if (["POST", "PATCH", "PUT"].includes(request.method())) {
44
+ try {
45
+ const postData = request.postData();
46
+ if (postData) {
47
+ try {
48
+ entry.requestBody = JSON.parse(postData);
49
+ } catch {
50
+ entry.requestBody = postData.substring(0, 500);
51
+ }
52
+ }
53
+ } catch {
54
+ }
55
+ }
56
+ state.entries.push(entry);
57
+ }
58
+ async function handleNetworkResponse(response, state) {
59
+ const url = response.url();
60
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
61
+ const entry = [...state.entries].reverse().find((e) => e.url === url && e.status === 0);
62
+ if (!entry) return;
63
+ entry.status = response.status();
64
+ entry.contentType = response.headers()["content-type"] || "";
65
+ const resourceType = response.request().resourceType();
66
+ const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
67
+ if (isApi) {
68
+ try {
69
+ const text = await response.text();
70
+ entry.responseSize = text.length;
71
+ if (text.length <= 20480) {
72
+ try {
73
+ entry.responseBody = JSON.parse(text);
74
+ } catch {
75
+ entry.responseBody = text.substring(0, 500);
76
+ }
77
+ }
78
+ } catch {
79
+ }
80
+ } else {
81
+ try {
82
+ entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
83
+ } catch {
84
+ }
85
+ }
86
+ }
15
87
 
16
88
  // src/recorder/selector-utils.ts
17
89
  function getSelectorGeneratorScript() {
@@ -275,8 +347,7 @@ function getSelectorGeneratorScript() {
275
347
  `;
276
348
  }
277
349
 
278
- // src/recorder/session-recorder.ts
279
- init_site_knowledge();
350
+ // src/recorder/injection-scripts.ts
280
351
  var ACTION_SIGNAL_SCRIPT = `
281
352
  (function() {
282
353
  if (window.__xb_action_signal) return;
@@ -2064,166 +2135,934 @@ var CHECKPOINT_OVERLAY_SCRIPT = `
2064
2135
  }, true);
2065
2136
  })();
2066
2137
  `;
2067
- var SessionRecorder = class _SessionRecorder {
2068
- context;
2069
- page;
2070
- sessionName;
2071
- startUrl = "";
2072
- startedAt = 0;
2073
- actions = [];
2074
- network = [];
2075
- contextChanges = [];
2076
- checkpoints = [];
2077
- /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2078
- * containerSelector so re-scans after navigation replace rather than dup. */
2079
- discoveredFilters = /* @__PURE__ */ new Map();
2080
- actionCounter = 0;
2081
- networkCounter = 0;
2082
- contextCounter = 0;
2083
- checkpointCounter = 0;
2084
- pollTimer = null;
2085
- flushTimer = null;
2086
- lastActionTs = 0;
2087
- activePages = /* @__PURE__ */ new Set();
2088
- lastKnownUrl = "";
2089
- // Track URL to detect real navigation changes
2090
- /** Dedup map: key = normalizedType|tag|value → expiration timestamp.
2091
- * Replaces old single-entry cdpActionDedup for bidirectional dedup. */
2092
- dedupMap = /* @__PURE__ */ new Map();
2093
- dedupActionCount = 0;
2094
- // counter for periodic cleanup
2095
- /** Network dedup: last request key for short-window dedup */
2096
- _lastRequestKey = "";
2097
- _lastRequestTs = 0;
2098
- _isRecording = false;
2099
- streamMode = "clean";
2100
- /** Snapshot throttle: prevents too many screenshots during rapid inputs.
2101
- * Keyed by 'type|elementSelector', value = last snapshot timestamp. */
2102
- snapshotThrottle = /* @__PURE__ */ new Map();
2103
- /** Ambient action types: filtered out in clean mode */
2104
- static AMBIENT_TYPES = /* @__PURE__ */ new Set([
2105
- "hover",
2106
- "focus",
2107
- "scroll",
2108
- "visibility",
2109
- "resize",
2110
- "clipboard",
2111
- "touch",
2112
- "contextmenu"
2113
- ]);
2114
- constructor(context, page, sessionName) {
2115
- this.context = context;
2116
- this.page = page;
2117
- this.sessionName = sessionName;
2118
- }
2119
- get isRecording() {
2120
- return this._isRecording;
2121
- }
2122
- get actionCount() {
2123
- return this.actions.length;
2124
- }
2125
- /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
2126
- async recordCommandAction(action) {
2127
- const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
2128
- if (dedupFromAction) {
2129
- const entry = this.dedupMap.get(dedupFromAction);
2130
- if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2131
- return;
2132
- }
2133
- }
2134
- this.actionCounter++;
2135
- const ts = Date.now();
2136
- const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
2137
- const actionToPush = {
2138
- id: this.actionCounter,
2139
- type: action.type,
2140
- timestamp: ts,
2141
- url: actionUrl,
2142
- pageTitle: "",
2143
- element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
2144
- value: action.value
2145
- };
2146
- this.actions.push(actionToPush);
2147
- actionToPush.elementScreenshot = await Promise.race([
2148
- this.captureElementScreenshot(this.page, {
2149
- type: action.type,
2150
- element: actionToPush.element
2151
- }).catch(() => void 0),
2152
- new Promise((r) => setTimeout(r, 3e3))
2153
- ]);
2154
- await Promise.race([
2155
- this.captureAutoSnapshot(this.page, actionToPush, "after").catch(() => {
2156
- }),
2157
- new Promise((r) => setTimeout(r, 6e3))
2158
- ]);
2159
- this.lastActionTs = ts;
2160
- this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2161
- this.dedupActionCount++;
2162
- if (this.dedupActionCount % 200 === 0) {
2163
- const now = Date.now();
2164
- for (const [k, v] of this.dedupMap) {
2165
- if (now >= v.expires) this.dedupMap.delete(k);
2138
+
2139
+ // src/recorder/script-injector.ts
2140
+ async function injectActionScript(page) {
2141
+ let success = false;
2142
+ const maxAttempts = 3;
2143
+ let lastError = "";
2144
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2145
+ try {
2146
+ await page.evaluate(getSelectorGeneratorScript());
2147
+ await page.evaluate(ACTION_SIGNAL_SCRIPT);
2148
+ await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2149
+ const injected = await page.evaluate(`(function() {
2150
+ try { return !!window.__xb_action_signal; } catch(e) { return false; }
2151
+ })()`).catch(() => false);
2152
+ if (injected) {
2153
+ success = true;
2154
+ break;
2166
2155
  }
2156
+ lastError = "verification failed (script did not set __xb_action_signal flag)";
2157
+ console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2158
+ } catch (e) {
2159
+ const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2160
+ lastError = err.message;
2161
+ console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2167
2162
  }
2168
- if (action.url && action.url !== "about:blank") {
2169
- this.lastKnownUrl = action.url;
2170
- } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
2171
- this.lastKnownUrl = action.value;
2163
+ if (attempt < maxAttempts) {
2164
+ await new Promise((r) => setTimeout(r, 1e3));
2172
2165
  }
2173
2166
  }
2174
- /** Generate dedup key for an action (normalized type + selector/tag + value). */
2175
- dedupKey(type, selector, tag, value) {
2176
- const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
2177
- const selOrTag = selector || tag || "";
2178
- return `${normType}|${selOrTag}|${value || ""}`;
2167
+ if (!success) {
2168
+ console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2179
2169
  }
2180
- get networkCount() {
2181
- return this.network.length;
2170
+ try {
2171
+ await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2172
+ } catch (e) {
2173
+ const msg = e instanceof Error ? e.message : String(e);
2174
+ console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2182
2175
  }
2183
- getLiveData() {
2184
- return this.buildData();
2176
+ if (success) {
2177
+ try {
2178
+ await page.evaluate(`(function() {
2179
+ if (typeof window.__xb_scanFilters === 'function') {
2180
+ setTimeout(window.__xb_scanFilters, 100);
2181
+ }
2182
+ })()`);
2183
+ } catch {
2184
+ }
2185
2185
  }
2186
- addManualCheckpoint(type, hint, selector) {
2187
- this.checkpointCounter++;
2188
- const cp = {
2189
- id: this.checkpointCounter,
2190
- type,
2191
- timestamp: Date.now(),
2192
- url: this.page.url(),
2193
- pageTitle: "",
2194
- hint,
2195
- selector,
2196
- source: "manual"
2197
- };
2198
- this.checkpoints.push(cp);
2199
- return cp;
2186
+ try {
2187
+ await page.evaluate(`
2188
+ (function() {
2189
+ var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2190
+ function injectIframe(iframe) {
2191
+ try {
2192
+ var w = iframe.contentWindow;
2193
+ if (!w) return;
2194
+ // Force re-injection: clear old flag
2195
+ try { delete w.__xb_action_signal; } catch(e) {}
2196
+ w.eval(_scriptSrc);
2197
+ // Tag iframe so flushIframes knows it's injected
2198
+ iframe.__xb_injected = true;
2199
+ } catch(e) {}
2200
+ }
2201
+ function watchIframe(iframe) {
2202
+ if (iframe.__xb_watched) return;
2203
+ iframe.__xb_watched = true;
2204
+ injectIframe(iframe);
2205
+ iframe.addEventListener('load', function() { injectIframe(iframe); });
2206
+ }
2207
+ // Inject into existing iframes
2208
+ try {
2209
+ var iframes = document.querySelectorAll('iframe');
2210
+ for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2211
+ } catch(e) {}
2212
+ // Watch for dynamically inserted iframes
2213
+ if (!window.__xb_iframe_observer) {
2214
+ window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2215
+ for (var m = 0; m < mutations.length; m++) {
2216
+ for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2217
+ var node = mutations[m].addedNodes[n];
2218
+ if (node.tagName === 'IFRAME') {
2219
+ watchIframe(node);
2220
+ } else if (node.querySelectorAll) {
2221
+ var sub = node.querySelectorAll('iframe');
2222
+ for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2223
+ }
2224
+ }
2225
+ }
2226
+ });
2227
+ window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2228
+ }
2229
+ // Periodic re-injection for iframes that load late or navigate internally
2230
+ if (!window.__xb_iframe_timer) {
2231
+ window.__xb_iframe_timer = setInterval(function() {
2232
+ try {
2233
+ var iframes = document.querySelectorAll('iframe');
2234
+ for (var i = 0; i < iframes.length; i++) {
2235
+ if (!iframes[i].__xb_injected) {
2236
+ watchIframe(iframes[i]);
2237
+ }
2238
+ }
2239
+ } catch(e) {}
2240
+ }, 3000);
2241
+ }
2242
+ })();
2243
+ `);
2244
+ } catch {
2200
2245
  }
2201
- /** Directory for this session's recordings. */
2202
- get recordingsDir() {
2203
- return _SessionRecorder.getRecordingsDir(this.sessionName);
2246
+ return success;
2247
+ }
2248
+
2249
+ // src/recorder/summary-builder.ts
2250
+ var POST_WINDOW = 5e3;
2251
+ var MERGE_WINDOW = 2e3;
2252
+ var COMPACT_MAX_FLOW_ITEMS = 100;
2253
+ var COMPACT_MAX_API_ITEMS = 20;
2254
+ function buildCompactSummary(data, startedAt) {
2255
+ const flow = [];
2256
+ let lastInputKey = "";
2257
+ const events = [
2258
+ ...data.actions.map((action) => ({ timestamp: action.timestamp, action })),
2259
+ ...data.contextChanges.map((contextChange) => ({ timestamp: contextChange.timestamp, contextChange }))
2260
+ ].sort((a, b) => a.timestamp - b.timestamp);
2261
+ for (const event of events) {
2262
+ if (flow.length >= COMPACT_MAX_FLOW_ITEMS) break;
2263
+ if (event.contextChange) {
2264
+ if (event.contextChange.type !== "navigate" || !event.contextChange.url) continue;
2265
+ lastInputKey = "";
2266
+ flow.push({
2267
+ step: flow.length + 1,
2268
+ action: `navigate ${event.contextChange.url}`
2269
+ });
2270
+ continue;
2271
+ }
2272
+ const action = event.action;
2273
+ if (!action) continue;
2274
+ const selector = action.element?.selector || action.element?.ariaLabel || action.element?.placeholder || action.element?.tag || "";
2275
+ const text = (action.element?.text || "").trim();
2276
+ const target = selector || text || action.url || "unknown";
2277
+ let description = "";
2278
+ if (action.type === "input" || action.type === "cdp-fill") {
2279
+ const inputKey = `${action.type}|${target}`;
2280
+ if (inputKey === lastInputKey) continue;
2281
+ lastInputKey = inputKey;
2282
+ description = `fill ${target} value=${truncate(action.value || "", 60)}`;
2283
+ } else if (action.type === "click" || action.type === "cdp-click") {
2284
+ lastInputKey = "";
2285
+ description = `click ${target}${text ? ` text=${truncate(text, 60)}` : ""}`;
2286
+ } else if (action.type === "change") {
2287
+ lastInputKey = "";
2288
+ description = `change ${target} value=${truncate(action.value || "", 60)}`;
2289
+ } else if (action.type === "submit") {
2290
+ lastInputKey = "";
2291
+ description = `submit ${target}`;
2292
+ } else if (action.type === "hover") {
2293
+ lastInputKey = "";
2294
+ description = `hover ${target}`;
2295
+ } else if (action.type === "drag") {
2296
+ lastInputKey = "";
2297
+ description = `drag from (${action.drag?.fromX ?? 0},${action.drag?.fromY ?? 0}) to (${action.drag?.toX ?? 0},${action.drag?.toY ?? 0})`;
2298
+ } else if (action.type === "drop") {
2299
+ lastInputKey = "";
2300
+ description = `drop ${action.files?.count ?? 1} file(s) on ${target}`;
2301
+ } else {
2302
+ continue;
2303
+ }
2304
+ flow.push({ step: flow.length + 1, action: description });
2305
+ }
2306
+ const keyApis = data.network.filter((entry) => (entry.resourceType === "fetch" || entry.resourceType === "xhr") && entry.contentType.toLowerCase().includes("json")).sort((a, b) => b.responseSize - a.responseSize).slice(0, COMPACT_MAX_API_ITEMS).map((entry) => ({
2307
+ method: entry.method,
2308
+ url: entry.url,
2309
+ path: entry.path,
2310
+ status: entry.status,
2311
+ contentType: entry.contentType,
2312
+ responseSize: entry.responseSize,
2313
+ ...entry.requestBody === void 0 ? {} : { requestBody: entry.requestBody }
2314
+ }));
2315
+ return {
2316
+ startUrl: data.startUrl,
2317
+ recordedAt: new Date(startedAt).toISOString(),
2318
+ durationMs: Math.max(0, Date.now() - startedAt),
2319
+ totalActions: data.actions.length,
2320
+ totalNetworkRequests: data.network.length,
2321
+ flow,
2322
+ keyApis
2323
+ };
2324
+ }
2325
+ function truncate(value, maxLength) {
2326
+ return value.length > maxLength ? `${value.slice(0, Math.max(0, maxLength - 3))}...` : value;
2327
+ }
2328
+ function buildSummary(data, startedAt) {
2329
+ const steps = [];
2330
+ const selectorToRef = /* @__PURE__ */ new Map();
2331
+ const elements = {};
2332
+ let refCounter = 0;
2333
+ function getRef(action) {
2334
+ const sel = action.element?.selector || action.element?.tag || "_none";
2335
+ if (selectorToRef.has(sel)) return selectorToRef.get(sel);
2336
+ refCounter++;
2337
+ const ref = "e" + refCounter;
2338
+ selectorToRef.set(sel, ref);
2339
+ if (action.element) {
2340
+ elements[ref] = {
2341
+ selector: action.element.selector || action.element.tag,
2342
+ tag: action.element.tag,
2343
+ text: action.element.text,
2344
+ role: action.element.role,
2345
+ type: action.element.type,
2346
+ placeholder: action.element.placeholder,
2347
+ ariaLabel: action.element.ariaLabel,
2348
+ href: action.element.href
2349
+ };
2350
+ } else {
2351
+ elements[ref] = { selector: "_none", tag: "_", text: "" };
2352
+ }
2353
+ return ref;
2354
+ }
2355
+ const isNoiseNetwork = (n) => {
2356
+ const url = n.url || "";
2357
+ const path = n.path || "";
2358
+ const rt = n.resourceType || "";
2359
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
2360
+ if (n.status === 0) return true;
2361
+ if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
2362
+ if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
2363
+ return false;
2364
+ };
2365
+ const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
2366
+ const filtered = data.actions;
2367
+ const groups = [];
2368
+ let current = null;
2369
+ for (const action of filtered) {
2370
+ const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
2371
+ const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
2372
+ if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
2373
+ current.actions.push(action);
2374
+ if (action.type === "input") current.primary = action;
2375
+ } else {
2376
+ current = { actions: [action], primary: action };
2377
+ groups.push(current);
2378
+ }
2204
2379
  }
2205
- /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
2206
- get snapshotsDir() {
2207
- return join(this.recordingsDir, ".tmp", "snapshots");
2380
+ for (const group of groups) {
2381
+ const primary = group.primary;
2382
+ const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
2383
+ const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
2384
+ const inputAction = group.actions.find((a) => a.type === "input");
2385
+ const nearbyNetwork = meaningfulNetwork.filter(
2386
+ (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
2387
+ );
2388
+ const nearbyContext = data.contextChanges.filter(
2389
+ (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
2390
+ );
2391
+ const matchedInputs = inputAction ? matchActionToNetwork(inputAction, nearbyNetwork) : [];
2392
+ const clickMatches = primary.type === "click" && primary.element?.text ? matchActionToNetwork(primary, nearbyNetwork) : [];
2393
+ const signals = primary.__signals || [];
2394
+ steps.push({
2395
+ step: steps.length + 1,
2396
+ ref: getRef(primary),
2397
+ action: primary,
2398
+ network: nearbyNetwork.map((n) => ({
2399
+ ...n,
2400
+ responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
2401
+ })),
2402
+ contextChanges: nearbyContext,
2403
+ matchedInputs: [...matchedInputs, ...clickMatches],
2404
+ signals
2405
+ });
2208
2406
  }
2209
- static getRecordingsDir(sessionName) {
2210
- return join(homedir(), ".xbrowser", "sessions", sessionName, "recordings");
2407
+ return {
2408
+ startUrl: data.startUrl,
2409
+ recordedAt: new Date(startedAt).toISOString(),
2410
+ durationMs: Date.now() - startedAt,
2411
+ totalActions: data.actions.length,
2412
+ totalNetworkRequests: meaningfulNetwork.length,
2413
+ steps,
2414
+ elements,
2415
+ checkpoints: data.checkpoints
2416
+ };
2417
+ }
2418
+ function matchActionToNetwork(action, nearbyNetwork) {
2419
+ const matches = [];
2420
+ const searchValue = (action.value || action.element?.text || "").trim();
2421
+ if (!searchValue || searchValue.length < 2) return matches;
2422
+ for (const netEntry of nearbyNetwork) {
2423
+ if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
2424
+ matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
2425
+ }
2426
+ if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
2427
+ searchObjectForValue(
2428
+ netEntry.requestBody,
2429
+ searchValue,
2430
+ netEntry.id,
2431
+ "",
2432
+ matches
2433
+ );
2434
+ }
2211
2435
  }
2212
- /** Path to the control file (used by record stop to signal this process). */
2213
- get controlFilePath() {
2214
- return join(this.recordingsDir, ".control.json");
2436
+ return matches;
2437
+ }
2438
+ function searchObjectForValue(obj, targetValue, networkId, prefix, results) {
2439
+ for (const [key, value] of Object.entries(obj)) {
2440
+ const fullKey = prefix ? `${prefix}.${key}` : key;
2441
+ if (typeof value === "string" && value.includes(targetValue)) {
2442
+ results.push({ inputValue: targetValue, networkId, paramName: fullKey });
2443
+ } else if (typeof value === "object" && value !== null) {
2444
+ searchObjectForValue(value, targetValue, networkId, fullKey, results);
2445
+ }
2215
2446
  }
2216
- /** Path to the stop signal file (written by `record stop`). */
2217
- get stopSignalPath() {
2218
- return join(this.recordingsDir, ".stop");
2447
+ }
2448
+
2449
+ // src/recorder/markdown-summary.ts
2450
+ import { readFileSync } from "fs";
2451
+ import { join } from "path";
2452
+ import { homedir } from "os";
2453
+ function buildMarkdownSummary(_data, summary) {
2454
+ const lines = [];
2455
+ const durSec = Math.round(summary.durationMs / 1e3);
2456
+ lines.push("# Recording Summary");
2457
+ lines.push("");
2458
+ lines.push(`- **URL**: ${summary.startUrl}`);
2459
+ lines.push(`- **Recorded**: ${summary.recordedAt}`);
2460
+ lines.push(`- **Duration**: ${durSec}s`);
2461
+ lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
2462
+ if (summary.checkpoints.length > 0) {
2463
+ const cpTypes = summary.checkpoints.map((c) => c.type);
2464
+ lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
2465
+ } else {
2466
+ lines.push("- **Checkpoints**: 0");
2467
+ }
2468
+ const checkpointSteps = /* @__PURE__ */ new Map();
2469
+ for (const cp of summary.checkpoints) {
2470
+ if (cp.relatedActionId != null) {
2471
+ for (const step of summary.steps) {
2472
+ if (step.action.id === cp.relatedActionId) {
2473
+ checkpointSteps.set(step.step, cp);
2474
+ break;
2475
+ }
2476
+ }
2477
+ }
2219
2478
  }
2220
- // ─── Start ──────────────────────────────────────────────────────
2221
- async start(url, options) {
2222
- if (this._isRecording) throw new Error("Already recording");
2223
- this._isRecording = true;
2224
- this.startedAt = Date.now();
2479
+ lines.push("");
2480
+ lines.push("## Steps");
2481
+ lines.push("");
2482
+ for (const step of summary.steps) {
2483
+ const a = step.action;
2484
+ const el = a.element;
2485
+ const cp = checkpointSteps.get(step.step);
2486
+ if (cp) {
2487
+ lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
2488
+ lines.push(`- **Type**: ${cp.type} (${cp.source})`);
2489
+ lines.push(`- **Hint**: ${cp.hint}`);
2490
+ if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
2491
+ lines.push(`- **Action needed**: Human intervention required before continuing`);
2492
+ } else {
2493
+ const title = describeActionTitle(a);
2494
+ lines.push(`### Step ${step.step}: ${title}`);
2495
+ }
2496
+ if (el) {
2497
+ const parts = [`\`${el.selector || el.tag}\``];
2498
+ if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
2499
+ parts.push(`(${el.tag})`);
2500
+ if (el.type) parts.push(`type=${el.type}`);
2501
+ lines.push(`- **Element**: ${parts.join(" ")}`);
2502
+ }
2503
+ if (a.value != null && a.type === "input") {
2504
+ lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
2505
+ }
2506
+ if (step.network.length > 0) {
2507
+ const netDescs = step.network.map((n) => {
2508
+ let desc = `${n.method} ${n.path}`;
2509
+ if (n.status) desc += ` \u2192 ${n.status}`;
2510
+ if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
2511
+ return desc;
2512
+ });
2513
+ lines.push(`- **Network**: ${netDescs.join(", ")}`);
2514
+ for (const n of step.network) {
2515
+ if (n.requestBody && typeof n.requestBody === "object") {
2516
+ const bodyStr = JSON.stringify(n.requestBody);
2517
+ if (bodyStr.length <= 300) {
2518
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
2519
+ } else {
2520
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
2521
+ }
2522
+ }
2523
+ }
2524
+ } else {
2525
+ lines.push("- **Network**: none");
2526
+ }
2527
+ if (step.matchedInputs.length > 0) {
2528
+ for (const m of step.matchedInputs) {
2529
+ lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
2530
+ }
2531
+ }
2532
+ for (const ctx of step.contextChanges) {
2533
+ if (ctx.type === "navigate") {
2534
+ lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
2535
+ } else if (ctx.type === "new_tab") {
2536
+ lines.push(`- **New tab**: ${ctx.url}`);
2537
+ }
2538
+ }
2539
+ if (a.clickContext) {
2540
+ if (a.clickContext.appeared?.length > 0) {
2541
+ for (const popup of a.clickContext.appeared) {
2542
+ const roleStr = popup.role ? ` [${popup.role}]` : "";
2543
+ lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
2544
+ if (popup.items?.length > 0) {
2545
+ const itemStrs = popup.items.slice(0, 8).map((i) => {
2546
+ const dis = i.disabled ? " [disabled]" : "";
2547
+ return `"${i.text}"${dis}`;
2548
+ });
2549
+ let itemLine = ` - Items: ${itemStrs.join(", ")}`;
2550
+ if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
2551
+ lines.push(itemLine);
2552
+ }
2553
+ }
2554
+ }
2555
+ if (a.clickContext.stateChanges?.length > 0) {
2556
+ for (const sc of a.clickContext.stateChanges) {
2557
+ const parts = [];
2558
+ if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
2559
+ if (sc.disabled) parts.push("disabled");
2560
+ if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
2561
+ if (sc.dataState) parts.push(`state=${sc.dataState}`);
2562
+ if (parts.length > 0) {
2563
+ lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
2564
+ }
2565
+ }
2566
+ }
2567
+ }
2568
+ lines.push("");
2569
+ }
2570
+ const allNetwork = summary.steps.flatMap((s) => s.network);
2571
+ if (allNetwork.length > 0) {
2572
+ lines.push("## Network Timeline");
2573
+ lines.push("");
2574
+ allNetwork.forEach((n, i) => {
2575
+ let line = `${i + 1}. ${n.method} ${n.path}`;
2576
+ if (n.status) line += ` \u2192 ${n.status}`;
2577
+ if (n.requestBody && typeof n.requestBody === "object") {
2578
+ const bodyStr = JSON.stringify(n.requestBody);
2579
+ if (bodyStr.length <= 150) {
2580
+ line += ` ${bodyStr}`;
2581
+ }
2582
+ }
2583
+ if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
2584
+ lines.push(line);
2585
+ });
2586
+ lines.push("");
2587
+ }
2588
+ const orphanCheckpoints = summary.checkpoints.filter(
2589
+ (cp) => cp.relatedActionId == null || !checkpointSteps.has(
2590
+ summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
2591
+ )
2592
+ );
2593
+ if (orphanCheckpoints.length > 0) {
2594
+ lines.push("## Unresolved Checkpoints");
2595
+ lines.push("");
2596
+ for (const cp of orphanCheckpoints) {
2597
+ const src = cp.source === "auto" ? "[auto]" : "[manual]";
2598
+ lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
2599
+ if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
2600
+ }
2601
+ lines.push("");
2602
+ }
2603
+ return lines.join("\n");
2604
+ }
2605
+ function readMarkdownSummary(sessionName) {
2606
+ const mdPath = join(homedir(), ".xbrowser", "recordings", sessionName, "summary.md");
2607
+ try {
2608
+ return readFileSync(mdPath, "utf8");
2609
+ } catch {
2610
+ return null;
2611
+ }
2612
+ }
2613
+ function describeActionTitle(a) {
2614
+ const el = a.element;
2615
+ const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
2616
+ const elTag = el?.tag ? `<${el.tag}>` : "";
2617
+ switch (a.type) {
2618
+ case "click":
2619
+ return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
2620
+ case "input":
2621
+ return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
2622
+ case "change":
2623
+ return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
2624
+ case "keydown":
2625
+ return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
2626
+ case "submit":
2627
+ return `Submit ${elText || elTag || "form"}`;
2628
+ default:
2629
+ return `${a.type} ${elText || elTag}`.trim() || a.type;
2630
+ }
2631
+ }
2632
+ function formatBytes(bytes) {
2633
+ if (bytes < 1024) return `${bytes}B`;
2634
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
2635
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
2636
+ }
2637
+
2638
+ // src/recorder/observation-insights.ts
2639
+ async function detectCheckpoints(page, allocateCheckpointId) {
2640
+ const CHECKPOINT_RULES = [
2641
+ { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
2642
+ { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
2643
+ { type: "login", selectors: ['input[type="password"]'] },
2644
+ { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
2645
+ ];
2646
+ try {
2647
+ const found = await page.evaluate((rules) => {
2648
+ const results = [];
2649
+ for (const rule of rules) {
2650
+ for (const sel of rule.selectors) {
2651
+ try {
2652
+ const el = document.querySelector(sel);
2653
+ if (el) {
2654
+ const rect = el.getBoundingClientRect();
2655
+ if (rect.width > 0 && rect.height > 0) {
2656
+ results.push({
2657
+ type: rule.type,
2658
+ selector: sel,
2659
+ text: (el.textContent || "").substring(0, 60)
2660
+ });
2661
+ }
2662
+ }
2663
+ } catch {
2664
+ }
2665
+ }
2666
+ }
2667
+ return results;
2668
+ }, CHECKPOINT_RULES);
2669
+ const entries = [];
2670
+ for (const item of found) {
2671
+ const id = allocateCheckpointId();
2672
+ ;
2673
+ const hints = {
2674
+ captcha: "Captcha verification detected",
2675
+ slider: "Slider verification detected",
2676
+ login: "Login form detected (password field)",
2677
+ iframe: "Verification iframe detected"
2678
+ };
2679
+ entries.push({
2680
+ id,
2681
+ type: item.type,
2682
+ timestamp: Date.now(),
2683
+ url: page.url(),
2684
+ pageTitle: await page.title().catch(() => ""),
2685
+ hint: hints[item.type] || item.type,
2686
+ selector: item.selector,
2687
+ source: "auto",
2688
+ context: { matchedSelector: item.selector, elementText: item.text }
2689
+ });
2690
+ }
2691
+ return entries;
2692
+ } catch {
2693
+ return [];
2694
+ }
2695
+ }
2696
+ async function verifyAction(page, action, network, checkpoints) {
2697
+ const signals = [];
2698
+ try {
2699
+ const currentUrl = page.url();
2700
+ if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
2701
+ signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
2702
+ }
2703
+ } catch {
2704
+ }
2705
+ try {
2706
+ const recentNetwork = network.filter(
2707
+ (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
2708
+ );
2709
+ for (const net of recentNetwork.slice(0, 3)) {
2710
+ signals.push({
2711
+ type: "network_success",
2712
+ value: `${net.status}`,
2713
+ label: `${net.method} ${net.path} \u2192 ${net.status}`
2714
+ });
2715
+ }
2716
+ } catch {
2717
+ }
2718
+ try {
2719
+ const recentDialog = [...checkpoints].reverse().find(
2720
+ (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
2721
+ );
2722
+ if (recentDialog) {
2723
+ signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
2724
+ }
2725
+ } catch {
2726
+ }
2727
+ return signals;
2728
+ }
2729
+
2730
+ // src/recorder/page-context.ts
2731
+ import { mkdirSync, writeFileSync } from "fs";
2732
+ import { join as join2 } from "path";
2733
+ var SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
2734
+ "click",
2735
+ "dblclick",
2736
+ "navigation",
2737
+ "goto",
2738
+ "submit",
2739
+ "cdp-click",
2740
+ "cdp-fill",
2741
+ "input",
2742
+ "change",
2743
+ "filechooser",
2744
+ "popup_appear"
2745
+ ]);
2746
+ async function captureElementScreenshot(page, action) {
2747
+ const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
2748
+ if (!keyTypes.includes(action.type)) return;
2749
+ if (!action.element?.selector) return;
2750
+ const selector = action.element.selector;
2751
+ try {
2752
+ const buffer = await page.locator(selector).first().screenshot({
2753
+ type: "png",
2754
+ timeout: 3e3
2755
+ });
2756
+ return buffer.toString("base64");
2757
+ } catch {
2758
+ }
2759
+ try {
2760
+ await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
2761
+ const buffer = await page.locator(selector).first().screenshot({
2762
+ type: "png",
2763
+ timeout: 3e3
2764
+ });
2765
+ return buffer.toString("base64");
2766
+ } catch {
2767
+ }
2768
+ try {
2769
+ const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
2770
+ return buffer.toString("base64");
2771
+ } catch {
2772
+ return;
2773
+ }
2774
+ }
2775
+ function isSnapshotThrottled(type, selector, snapshotThrottle) {
2776
+ if (type === "input" || type === "change" || type === "cdp-fill") {
2777
+ const key = `${type}|${selector || ""}`;
2778
+ const last = snapshotThrottle.get(key);
2779
+ const now = Date.now();
2780
+ if (last && now - last < 2e3) return true;
2781
+ snapshotThrottle.set(key, now);
2782
+ }
2783
+ return false;
2784
+ }
2785
+ async function captureAutoSnapshot(page, action, suffix = "after", snapshotsDir, snapshotThrottle) {
2786
+ if (!SNAPSHOT_TYPES.has(action.type)) return;
2787
+ if (isSnapshotThrottled(action.type, action.element?.selector, snapshotThrottle)) return;
2788
+ const snapDir = snapshotsDir;
2789
+ mkdirSync(snapDir, { recursive: true });
2790
+ const stepId = String(action.id).padStart(3, "0");
2791
+ const snapshot = {};
2792
+ try {
2793
+ const pngPath = join2(snapDir, `step-${stepId}-${suffix}.png`);
2794
+ const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
2795
+ writeFileSync(pngPath, buffer);
2796
+ snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
2797
+ } catch {
2798
+ }
2799
+ try {
2800
+ snapshot.aria = await page.evaluate(`
2801
+ (function() {
2802
+ try {
2803
+ var parts = [];
2804
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
2805
+ var node;
2806
+ while (node = walker.nextNode()) {
2807
+ var tag = node.tagName.toLowerCase();
2808
+ var role = node.getAttribute('role') || '';
2809
+ var text = (node.textContent || '').trim().substring(0, 60);
2810
+ var ariaLabel = node.getAttribute('aria-label') || '';
2811
+ if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
2812
+ parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
2813
+ }
2814
+ }
2815
+ return parts.slice(0, 100).join(' | ');
2816
+ } catch(e) { return ''; }
2817
+ })()
2818
+ `);
2819
+ } catch {
2820
+ }
2821
+ if (snapshot.png || snapshot.aria) {
2822
+ action.snapshots = snapshot;
2823
+ }
2824
+ }
2825
+ async function captureClickContext(page, cx, cy) {
2826
+ await new Promise((r) => setTimeout(r, 300));
2827
+ try {
2828
+ const ctx = await page.evaluate(`
2829
+ (function() {
2830
+ var cx = ${cx}, cy = ${cy};
2831
+ var POPOVER_SELECTORS = [
2832
+ '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
2833
+ '[role="combobox"]','[role="tree"]','[role="grid"]',
2834
+ '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
2835
+ '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
2836
+ '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
2837
+ '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
2838
+ '.semi-dropdown','.semi-popover','.semi-modal',
2839
+ '.ant-dropdown','.ant-popover','.ant-modal',
2840
+ '.el-dropdown','.el-popover','.el-dialog',
2841
+ '.t-dropdown','.t-popup','.t-dialog'
2842
+ ];
2843
+
2844
+ function isNear(el, x, y, range) {
2845
+ try {
2846
+ var r = el.getBoundingClientRect();
2847
+ if (!r || r.width === 0 || r.height === 0) return false;
2848
+ return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
2849
+ } catch(e) { return false; }
2850
+ }
2851
+
2852
+ var result = { appeared: [], disappeared: [], stateChanges: [] };
2853
+ var seenElements = new Set();
2854
+
2855
+ for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
2856
+ try {
2857
+ var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
2858
+ for (var j = 0; j < els.length; j++) {
2859
+ var el = els[j];
2860
+ if (seenElements.has(el)) continue;
2861
+ if (!isNear(el, cx, cy, 300)) continue;
2862
+ var rect = el.getBoundingClientRect();
2863
+ if (rect.width === 0 || rect.height === 0) continue;
2864
+ seenElements.add(el);
2865
+
2866
+ var items = [];
2867
+ var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
2868
+ var seenItemTexts = new Set();
2869
+ for (var k = 0; k < Math.min(children.length, 30); k++) {
2870
+ var child = children[k];
2871
+ var childText = (child.textContent || '').trim().substring(0, 60);
2872
+ if (!childText || seenItemTexts.has(childText)) continue;
2873
+ seenItemTexts.add(childText);
2874
+ var ci = { text: childText };
2875
+ try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
2876
+ try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
2877
+ try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
2878
+ items.push(ci);
2879
+ }
2880
+
2881
+ result.appeared.push({
2882
+ tag: el.tagName.toLowerCase(),
2883
+ selector: el.id ? '#' + el.id : undefined,
2884
+ role: el.getAttribute('role'),
2885
+ text: (el.textContent || '').trim().substring(0, 100),
2886
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
2887
+ items: items
2888
+ });
2889
+ }
2890
+ } catch(e) { /* skip invalid selectors */ }
2891
+ }
2892
+
2893
+ var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
2894
+ for (var i = 0; i < allInteractive.length; i++) {
2895
+ var el2 = allInteractive[i];
2896
+ if (!isNear(el2, cx, cy, 200)) continue;
2897
+ var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
2898
+ try { if (el2.id) info.id = el2.id; } catch(e) {}
2899
+ try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
2900
+ try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
2901
+ try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
2902
+ try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
2903
+ result.stateChanges.push(info);
2904
+ }
2905
+
2906
+ return result;
2907
+ })()
2908
+ `);
2909
+ if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
2910
+ return ctx;
2911
+ }
2912
+ } catch {
2913
+ }
2914
+ return void 0;
2915
+ }
2916
+
2917
+ // src/recorder/session-recorder.ts
2918
+ var SessionRecorder = class _SessionRecorder {
2919
+ context;
2920
+ page;
2921
+ sessionName;
2922
+ startUrl = "";
2923
+ startedAt = 0;
2924
+ actions = [];
2925
+ networkCapture = createNetworkCaptureState();
2926
+ contextChanges = [];
2927
+ checkpoints = [];
2928
+ /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2929
+ * containerSelector so re-scans after navigation replace rather than dup. */
2930
+ discoveredFilters = /* @__PURE__ */ new Map();
2931
+ actionCounter = 0;
2932
+ contextCounter = 0;
2933
+ checkpointCounter = 0;
2934
+ pollTimer = null;
2935
+ flushTimer = null;
2936
+ lastActionTs = 0;
2937
+ activePages = /* @__PURE__ */ new Set();
2938
+ lastKnownUrl = "";
2939
+ dedupMap = /* @__PURE__ */ new Map();
2940
+ dedupActionCount = 0;
2941
+ _isRecording = false;
2942
+ streamMode = "clean";
2943
+ snapshotThrottle = /* @__PURE__ */ new Map();
2944
+ static AMBIENT_TYPES = /* @__PURE__ */ new Set([
2945
+ "hover",
2946
+ "focus",
2947
+ "scroll",
2948
+ "visibility",
2949
+ "resize",
2950
+ "clipboard",
2951
+ "touch",
2952
+ "contextmenu"
2953
+ ]);
2954
+ constructor(context, page, sessionName) {
2955
+ this.context = context;
2956
+ this.page = page;
2957
+ this.sessionName = sessionName;
2958
+ }
2959
+ get isRecording() {
2960
+ return this._isRecording;
2961
+ }
2962
+ get actionCount() {
2963
+ return this.actions.length;
2964
+ }
2965
+ /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
2966
+ async recordCommandAction(action) {
2967
+ const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
2968
+ if (dedupFromAction) {
2969
+ const entry = this.dedupMap.get(dedupFromAction);
2970
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2971
+ return;
2972
+ }
2973
+ }
2974
+ this.actionCounter++;
2975
+ const ts = Date.now();
2976
+ const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
2977
+ const actionToPush = {
2978
+ id: this.actionCounter,
2979
+ type: action.type,
2980
+ timestamp: ts,
2981
+ url: actionUrl,
2982
+ pageTitle: "",
2983
+ element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
2984
+ value: action.value
2985
+ };
2986
+ this.actions.push(actionToPush);
2987
+ actionToPush.elementScreenshot = await Promise.race([
2988
+ captureElementScreenshot(this.page, {
2989
+ type: action.type,
2990
+ element: actionToPush.element
2991
+ }).catch(() => void 0),
2992
+ new Promise((r) => setTimeout(r, 3e3))
2993
+ ]);
2994
+ await Promise.race([
2995
+ captureAutoSnapshot(this.page, actionToPush, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2996
+ }),
2997
+ new Promise((r) => setTimeout(r, 6e3))
2998
+ ]);
2999
+ this.lastActionTs = ts;
3000
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
3001
+ this.dedupActionCount++;
3002
+ if (this.dedupActionCount % 200 === 0) {
3003
+ const now = Date.now();
3004
+ for (const [k, v] of this.dedupMap) {
3005
+ if (now >= v.expires) this.dedupMap.delete(k);
3006
+ }
3007
+ }
3008
+ if (action.url && action.url !== "about:blank") {
3009
+ this.lastKnownUrl = action.url;
3010
+ } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
3011
+ this.lastKnownUrl = action.value;
3012
+ }
3013
+ }
3014
+ /** Generate dedup key for an action (normalized type + selector/tag + value). */
3015
+ dedupKey(type, selector, tag, value) {
3016
+ const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
3017
+ const selOrTag = selector || tag || "";
3018
+ return `${normType}|${selOrTag}|${value || ""}`;
3019
+ }
3020
+ get networkCount() {
3021
+ return this.networkCapture.entries.length;
3022
+ }
3023
+ getLiveData() {
3024
+ return this.buildData();
3025
+ }
3026
+ addManualCheckpoint(type, hint, selector) {
3027
+ this.checkpointCounter++;
3028
+ const cp = {
3029
+ id: this.checkpointCounter,
3030
+ type,
3031
+ timestamp: Date.now(),
3032
+ url: this.page.url(),
3033
+ pageTitle: "",
3034
+ hint,
3035
+ selector,
3036
+ source: "manual"
3037
+ };
3038
+ this.checkpoints.push(cp);
3039
+ return cp;
3040
+ }
3041
+ /** Directory for this session's recordings. */
3042
+ get recordingsDir() {
3043
+ return _SessionRecorder.getRecordingsDir(this.sessionName);
3044
+ }
3045
+ /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
3046
+ get snapshotsDir() {
3047
+ return join3(this.recordingsDir, ".tmp", "snapshots");
3048
+ }
3049
+ static getRecordingsDir(sessionName) {
3050
+ return join3(homedir2(), ".xbrowser", "sessions", sessionName, "recordings");
3051
+ }
3052
+ /** Path to the control file (used by record stop to signal this process). */
3053
+ get controlFilePath() {
3054
+ return join3(this.recordingsDir, ".control.json");
3055
+ }
3056
+ /** Path to the stop signal file (written by `record stop`). */
3057
+ get stopSignalPath() {
3058
+ return join3(this.recordingsDir, ".stop");
3059
+ }
3060
+ // ─── Start ──────────────────────────────────────────────────────
3061
+ async start(url, options) {
3062
+ if (this._isRecording) throw new Error("Already recording");
3063
+ this._isRecording = true;
3064
+ this.startedAt = Date.now();
2225
3065
  this.actions = [];
2226
- this.network = [];
2227
3066
  this.contextChanges = [];
2228
3067
  this.checkpoints = [];
2229
3068
  this.checkpointCounter = 0;
@@ -2248,14 +3087,14 @@ var SessionRecorder = class _SessionRecorder {
2248
3087
  } else {
2249
3088
  this.startUrl = this.page.url();
2250
3089
  }
2251
- mkdirSync(this.recordingsDir, { recursive: true });
3090
+ mkdirSync2(this.recordingsDir, { recursive: true });
2252
3091
  const control = {
2253
3092
  pid: process.pid,
2254
3093
  startedAt: new Date(this.startedAt).toISOString(),
2255
3094
  startUrl: this.startUrl,
2256
3095
  sessionName: this.sessionName
2257
3096
  };
2258
- writeFileSync(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
3097
+ writeFileSync2(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
2259
3098
  await this.injectActionScript(this.page);
2260
3099
  this.context.on("page", this.handleNewPage);
2261
3100
  this.pollTimer = setInterval(() => void this.pollActions(), 200);
@@ -2290,21 +3129,21 @@ var SessionRecorder = class _SessionRecorder {
2290
3129
  });
2291
3130
  }
2292
3131
  const data = this.buildData();
2293
- const summary = this.buildSummary(data);
3132
+ const summary = buildSummary(data, this.startedAt);
2294
3133
  this.writeFinalOutput(data, summary);
2295
3134
  try {
2296
3135
  const knowledge = updateSiteKnowledge(data);
2297
- const knowledgeDir = join(this.recordingsDir, "site-knowledge.md");
2298
- const knowledgeJson = join(this.recordingsDir, "site-knowledge.json");
3136
+ const knowledgeDir = join3(this.recordingsDir, "site-knowledge.md");
3137
+ const knowledgeJson = join3(this.recordingsDir, "site-knowledge.json");
2299
3138
  const { readFileSync: rf } = __require("fs");
2300
3139
  const { getKnowledgePath } = (init_site_knowledge(), __toCommonJS(site_knowledge_exports));
2301
3140
  const mdPath = getKnowledgePath(knowledge.domain, "md");
2302
3141
  try {
2303
3142
  const md = rf(mdPath, "utf-8");
2304
- writeFileSync(knowledgeDir, md, "utf-8");
3143
+ writeFileSync2(knowledgeDir, md, "utf-8");
2305
3144
  } catch {
2306
3145
  }
2307
- writeFileSync(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
3146
+ writeFileSync2(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
2308
3147
  } catch {
2309
3148
  }
2310
3149
  try {
@@ -2317,268 +3156,103 @@ var SessionRecorder = class _SessionRecorder {
2317
3156
  }
2318
3157
  return { data, summary };
2319
3158
  }
2320
- // ─── Cleanup (called on session close) ──────────────────────────
2321
- static cleanup(sessionName) {
2322
- const dir = _SessionRecorder.getRecordingsDir(sessionName);
2323
- if (existsSync(dir)) {
2324
- rmSync(dir, { recursive: true, force: true });
2325
- }
2326
- }
2327
- // ─── Wait for stop signal (blocks the process) ──────────────────
2328
- waitForStopSignal() {
2329
- return new Promise((resolve) => {
2330
- const check = () => {
2331
- if (existsSync(this.stopSignalPath)) {
2332
- resolve();
2333
- } else {
2334
- setTimeout(check, 300);
2335
- }
2336
- };
2337
- check();
2338
- });
2339
- }
2340
- // ─── Static: send stop signal to a running recorder ─────────────
2341
- static async sendStopSignal(sessionName) {
2342
- const dir = _SessionRecorder.getRecordingsDir(sessionName);
2343
- const controlPath = join(dir, ".control.json");
2344
- const stopPath = join(dir, ".stop");
2345
- if (!existsSync(controlPath)) return null;
2346
- const control = JSON.parse(readFileSync(controlPath, "utf-8"));
2347
- let alive = false;
2348
- try {
2349
- process.kill(control.pid, 0);
2350
- alive = true;
2351
- } catch {
2352
- alive = false;
2353
- }
2354
- if (!alive) {
2355
- try {
2356
- rmSync(controlPath);
2357
- } catch {
2358
- }
2359
- return control;
2360
- }
2361
- mkdirSync(dir, { recursive: true });
2362
- writeFileSync(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
2363
- for (let i = 0; i < 50; i++) {
2364
- await new Promise((r) => setTimeout(r, 200));
2365
- if (!existsSync(controlPath)) return control;
2366
- try {
2367
- process.kill(control.pid, 0);
2368
- } catch {
2369
- try {
2370
- rmSync(controlPath);
2371
- } catch {
2372
- }
2373
- return control;
2374
- }
2375
- }
2376
- try {
2377
- rmSync(controlPath);
2378
- } catch {
2379
- }
2380
- return control;
2381
- }
2382
- // ─── Static: read recording from disk ───────────────────────────
2383
- static readSummary(sessionName) {
2384
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
2385
- try {
2386
- return JSON.parse(readFileSync(path, "utf-8"));
2387
- } catch {
2388
- return null;
2389
- }
2390
- }
2391
- static readData(sessionName) {
2392
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
2393
- try {
2394
- return JSON.parse(readFileSync(path, "utf-8"));
2395
- } catch {
2396
- return null;
2397
- }
2398
- }
2399
- // ==================== Private ====================
2400
- /** Whether the initial action-signal script injection succeeded. Check this
2401
- * after start() returns — if false, user actions will NOT be recorded and
2402
- * the caller should surface a clear error to the user instead of silently
2403
- * pretending recording is working. */
2404
- _injectionFailed = false;
2405
- get injectionFailed() {
2406
- return this._injectionFailed;
2407
- }
2408
- async injectActionScript(page) {
2409
- let success = false;
2410
- const maxAttempts = 3;
2411
- let lastError = "";
2412
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2413
- try {
2414
- await page.evaluate(getSelectorGeneratorScript());
2415
- await page.evaluate(ACTION_SIGNAL_SCRIPT);
2416
- await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2417
- const injected = await page.evaluate(`(function() {
2418
- try { return !!window.__xb_action_signal; } catch(e) { return false; }
2419
- })()`).catch(() => false);
2420
- if (injected) {
2421
- success = true;
2422
- break;
2423
- }
2424
- lastError = "verification failed (script did not set __xb_action_signal flag)";
2425
- console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2426
- } catch (e) {
2427
- const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2428
- lastError = err.message;
2429
- console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2430
- }
2431
- if (attempt < maxAttempts) {
2432
- await new Promise((r) => setTimeout(r, 1e3));
2433
- }
2434
- }
2435
- if (!success) {
2436
- this._injectionFailed = true;
2437
- console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2438
- }
2439
- try {
2440
- await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2441
- } catch (e) {
2442
- const msg = e instanceof Error ? e.message : String(e);
2443
- console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2444
- }
2445
- if (success) {
2446
- try {
2447
- await page.evaluate(`(function() {
2448
- if (typeof window.__xb_scanFilters === 'function') {
2449
- setTimeout(window.__xb_scanFilters, 100);
2450
- }
2451
- })()`);
2452
- } catch {
2453
- }
2454
- }
2455
- try {
2456
- await page.evaluate(`
2457
- (function() {
2458
- var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2459
- function injectIframe(iframe) {
2460
- try {
2461
- var w = iframe.contentWindow;
2462
- if (!w) return;
2463
- // Force re-injection: clear old flag
2464
- try { delete w.__xb_action_signal; } catch(e) {}
2465
- w.eval(_scriptSrc);
2466
- // Tag iframe so flushIframes knows it's injected
2467
- iframe.__xb_injected = true;
2468
- } catch(e) {}
2469
- }
2470
- function watchIframe(iframe) {
2471
- if (iframe.__xb_watched) return;
2472
- iframe.__xb_watched = true;
2473
- injectIframe(iframe);
2474
- iframe.addEventListener('load', function() { injectIframe(iframe); });
2475
- }
2476
- // Inject into existing iframes
2477
- try {
2478
- var iframes = document.querySelectorAll('iframe');
2479
- for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2480
- } catch(e) {}
2481
- // Watch for dynamically inserted iframes
2482
- if (!window.__xb_iframe_observer) {
2483
- window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2484
- for (var m = 0; m < mutations.length; m++) {
2485
- for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2486
- var node = mutations[m].addedNodes[n];
2487
- if (node.tagName === 'IFRAME') {
2488
- watchIframe(node);
2489
- } else if (node.querySelectorAll) {
2490
- var sub = node.querySelectorAll('iframe');
2491
- for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2492
- }
2493
- }
2494
- }
2495
- });
2496
- window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2497
- }
2498
- // Periodic re-injection for iframes that load late or navigate internally
2499
- if (!window.__xb_iframe_timer) {
2500
- window.__xb_iframe_timer = setInterval(function() {
2501
- try {
2502
- var iframes = document.querySelectorAll('iframe');
2503
- for (var i = 0; i < iframes.length; i++) {
2504
- if (!iframes[i].__xb_injected) {
2505
- watchIframe(iframes[i]);
2506
- }
2507
- }
2508
- } catch(e) {}
2509
- }, 3000);
2510
- }
2511
- })();
2512
- `);
2513
- } catch {
3159
+ // ─── Cleanup (called on session close) ──────────────────────────
3160
+ static cleanup(sessionName) {
3161
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3162
+ if (existsSync(dir)) {
3163
+ rmSync(dir, { recursive: true, force: true });
2514
3164
  }
2515
3165
  }
2516
- // ─── Network capture ────────────────────────────────────────────
2517
- handleRequest = (request) => {
2518
- const resourceType = request.resourceType();
2519
- if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
2520
- const url = request.url();
2521
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2522
- const dedupKey = request.method() + " " + url;
2523
- const now = Date.now();
2524
- if (this._lastRequestKey === dedupKey && now - this._lastRequestTs < 100) return;
2525
- this._lastRequestKey = dedupKey;
2526
- this._lastRequestTs = now;
2527
- this.networkCounter++;
2528
- const entry = {
2529
- id: this.networkCounter,
2530
- timestamp: Date.now(),
2531
- method: request.method(),
2532
- url,
2533
- path: new URL(url).pathname,
2534
- status: 0,
2535
- resourceType,
2536
- contentType: "",
2537
- responseSize: 0
2538
- };
2539
- if (["POST", "PATCH", "PUT"].includes(request.method())) {
2540
- try {
2541
- const postData = request.postData();
2542
- if (postData) {
2543
- try {
2544
- entry.requestBody = JSON.parse(postData);
2545
- } catch {
2546
- entry.requestBody = postData.substring(0, 500);
2547
- }
3166
+ // ─── Wait for stop signal (blocks the process) ──────────────────
3167
+ waitForStopSignal() {
3168
+ return new Promise((resolve) => {
3169
+ const check = () => {
3170
+ if (existsSync(this.stopSignalPath)) {
3171
+ resolve();
3172
+ } else {
3173
+ setTimeout(check, 300);
2548
3174
  }
2549
- } catch {
2550
- }
3175
+ };
3176
+ check();
3177
+ });
3178
+ }
3179
+ // ─── Static: send stop signal to a running recorder ─────────────
3180
+ static async sendStopSignal(sessionName) {
3181
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3182
+ const controlPath = join3(dir, ".control.json");
3183
+ const stopPath = join3(dir, ".stop");
3184
+ if (!existsSync(controlPath)) return null;
3185
+ const control = JSON.parse(readFileSync2(controlPath, "utf-8"));
3186
+ let alive = false;
3187
+ try {
3188
+ process.kill(control.pid, 0);
3189
+ alive = true;
3190
+ } catch {
3191
+ alive = false;
2551
3192
  }
2552
- this.network.push(entry);
2553
- };
2554
- handleResponse = async (response) => {
2555
- const url = response.url();
2556
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2557
- const entry = [...this.network].reverse().find((e) => e.url === url && e.status === 0);
2558
- if (!entry) return;
2559
- entry.status = response.status();
2560
- entry.contentType = response.headers()["content-type"] || "";
2561
- const resourceType = response.request().resourceType();
2562
- const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
2563
- if (isApi) {
3193
+ if (!alive) {
2564
3194
  try {
2565
- const text = await response.text();
2566
- entry.responseSize = text.length;
2567
- if (text.length <= 20480) {
2568
- try {
2569
- entry.responseBody = JSON.parse(text);
2570
- } catch {
2571
- entry.responseBody = text.substring(0, 500);
2572
- }
2573
- }
3195
+ rmSync(controlPath);
2574
3196
  } catch {
2575
3197
  }
2576
- } else {
3198
+ return control;
3199
+ }
3200
+ mkdirSync2(dir, { recursive: true });
3201
+ writeFileSync2(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
3202
+ for (let i = 0; i < 50; i++) {
3203
+ await new Promise((r) => setTimeout(r, 200));
3204
+ if (!existsSync(controlPath)) return control;
2577
3205
  try {
2578
- entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
3206
+ process.kill(control.pid, 0);
2579
3207
  } catch {
3208
+ try {
3209
+ rmSync(controlPath);
3210
+ } catch {
3211
+ }
3212
+ return control;
2580
3213
  }
2581
3214
  }
3215
+ try {
3216
+ rmSync(controlPath);
3217
+ } catch {
3218
+ }
3219
+ return control;
3220
+ }
3221
+ // ─── Static: read recording from disk ───────────────────────────
3222
+ static readSummary(sessionName) {
3223
+ const path = join3(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
3224
+ try {
3225
+ return JSON.parse(readFileSync2(path, "utf-8"));
3226
+ } catch {
3227
+ return null;
3228
+ }
3229
+ }
3230
+ static readData(sessionName) {
3231
+ const path = join3(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
3232
+ try {
3233
+ return JSON.parse(readFileSync2(path, "utf-8"));
3234
+ } catch {
3235
+ return null;
3236
+ }
3237
+ }
3238
+ // ==================== Private ====================
3239
+ /** Whether the initial action-signal script injection succeeded. Check this
3240
+ * after start() returns — if false, user actions will NOT be recorded and
3241
+ * the caller should surface a clear error to the user instead of silently
3242
+ * pretending recording is working. */
3243
+ _injectionFailed = false;
3244
+ get injectionFailed() {
3245
+ return this._injectionFailed;
3246
+ }
3247
+ async injectActionScript(page) {
3248
+ this._injectionFailed = !await injectActionScript(page);
3249
+ }
3250
+ // ─── Network capture ────────────────────────────────────────────
3251
+ handleRequest = (request) => {
3252
+ handleNetworkRequest(request, this.networkCapture);
3253
+ };
3254
+ handleResponse = async (response) => {
3255
+ await handleNetworkResponse(response, this.networkCapture);
2582
3256
  };
2583
3257
  // ─── Page tracking ──────────────────────────────────────────────
2584
3258
  handleNewPage = async (page) => {
@@ -2868,7 +3542,7 @@ var SessionRecorder = class _SessionRecorder {
2868
3542
  popupAppear: raw.popupAppear
2869
3543
  };
2870
3544
  this.actions.push(pushed2);
2871
- await this.captureAutoSnapshot(page, pushed2, "after").catch(() => {
3545
+ await captureAutoSnapshot(page, pushed2, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2872
3546
  });
2873
3547
  this.lastActionTs = raw.ts;
2874
3548
  continue;
@@ -2898,7 +3572,7 @@ var SessionRecorder = class _SessionRecorder {
2898
3572
  this.actionCounter++;
2899
3573
  let clickContext;
2900
3574
  if (raw.type === "click" && raw.x !== void 0 && raw.y !== void 0) {
2901
- clickContext = await this.captureClickContext(page, raw.x, raw.y);
3575
+ clickContext = await captureClickContext(page, raw.x, raw.y);
2902
3576
  }
2903
3577
  this.actions.push({
2904
3578
  id: this.actionCounter,
@@ -2925,8 +3599,8 @@ var SessionRecorder = class _SessionRecorder {
2925
3599
  drag: raw.drag
2926
3600
  });
2927
3601
  const pushed = this.actions[this.actions.length - 1];
2928
- pushed.elementScreenshot = await this.captureElementScreenshot(page, raw);
2929
- await this.captureAutoSnapshot(page, pushed, "after").catch(() => {
3602
+ pushed.elementScreenshot = await captureElementScreenshot(page, raw);
3603
+ await captureAutoSnapshot(page, pushed, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2930
3604
  });
2931
3605
  this.lastActionTs = raw.ts;
2932
3606
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
@@ -2936,13 +3610,13 @@ var SessionRecorder = class _SessionRecorder {
2936
3610
  }
2937
3611
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
2938
3612
  if (verifyTypes.has(raw.type)) {
2939
- const signals = await this.verifyAction(page, pushed).catch(() => []);
3613
+ const signals = await verifyAction(page, pushed, this.networkCapture.entries, this.checkpoints).catch(() => []);
2940
3614
  if (signals.length > 0) {
2941
3615
  pushed.__signals = signals;
2942
3616
  }
2943
3617
  }
2944
3618
  if (raw.type === "click" || raw.type === "navigate" || raw.type === "submit") {
2945
- const detected = await this.detectCheckpoints(page);
3619
+ const detected = await detectCheckpoints(page, () => ++this.checkpointCounter);
2946
3620
  for (const cp of detected) {
2947
3621
  cp.relatedActionId = this.actionCounter;
2948
3622
  this.checkpoints.push(cp);
@@ -2950,339 +3624,31 @@ var SessionRecorder = class _SessionRecorder {
2950
3624
  }
2951
3625
  }
2952
3626
  }
2953
- /**
2954
- * Capture a screenshot of the target element for key action types.
2955
- * Returns a base64-encoded PNG string, or undefined if the element has no
2956
- * selector or the screenshot fails (non-critical — never blocks recording).
2957
- *
2958
- * Only captures for: click, input, change, dblclick, and their CDP counterparts.
2959
- *
2960
- * Retry strategy (3 attempts, 3s each):
2961
- * 1. element screenshot via locator
2962
- * 2. retry element screenshot (element may have been animating/detached)
2963
- * 3. fallback to viewport screenshot (so we always get *something*)
2964
- */
2965
- async captureElementScreenshot(page, action) {
2966
- const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
2967
- if (!keyTypes.includes(action.type)) return;
2968
- if (!action.element?.selector) return;
2969
- const selector = action.element.selector;
2970
- try {
2971
- const buffer = await page.locator(selector).first().screenshot({
2972
- type: "png",
2973
- timeout: 3e3
2974
- });
2975
- return buffer.toString("base64");
2976
- } catch {
2977
- }
2978
- try {
2979
- await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
2980
- const buffer = await page.locator(selector).first().screenshot({
2981
- type: "png",
2982
- timeout: 3e3
2983
- });
2984
- return buffer.toString("base64");
2985
- } catch {
2986
- }
2987
- try {
2988
- const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
2989
- return buffer.toString("base64");
2990
- } catch {
2991
- return;
2992
- }
2993
- }
2994
- /**
2995
- * Action types that trigger auto-snapshot capture.
2996
- * Hover is excluded — it's too noisy and rarely changes the page visually.
2997
- * Popup_appear captures the popup state (after only).
2998
- */
2999
- static SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
3000
- "click",
3001
- "dblclick",
3002
- "navigation",
3003
- "goto",
3004
- "submit",
3005
- "cdp-click",
3006
- "cdp-fill",
3007
- "input",
3008
- "change",
3009
- "filechooser",
3010
- "popup_appear"
3011
- ]);
3012
- /**
3013
- * Throttle key for snapshot capture to avoid too many during rapid inputs.
3014
- * Returns true if this action should be throttled (skip snapshot).
3015
- */
3016
- isSnapshotThrottled(type, selector) {
3017
- if (type === "input" || type === "change" || type === "cdp-fill") {
3018
- const key = `${type}|${selector || ""}`;
3019
- const last = this.snapshotThrottle.get(key);
3020
- const now = Date.now();
3021
- if (last && now - last < 2e3) return true;
3022
- this.snapshotThrottle.set(key, now);
3023
- }
3024
- return false;
3025
- }
3026
- /**
3027
- * Capture a viewport screenshot + compact accessibility tree for a key action.
3028
- * - PNG stored in .tmp/snapshots/ (temporary, easy to clean up)
3029
- * - aria tree stored inline as compact text on the action (searchable via grep)
3030
- *
3031
- * Non-blocking (errors silently caught). Throttled for rapid inputs.
3032
- */
3033
- async captureAutoSnapshot(page, action, suffix = "after") {
3034
- if (!_SessionRecorder.SNAPSHOT_TYPES.has(action.type)) return;
3035
- if (this.isSnapshotThrottled(action.type, action.element?.selector)) return;
3036
- const snapDir = this.snapshotsDir;
3037
- mkdirSync(snapDir, { recursive: true });
3038
- const stepId = String(action.id).padStart(3, "0");
3039
- const snapshot = {};
3040
- try {
3041
- const pngPath = join(snapDir, `step-${stepId}-${suffix}.png`);
3042
- const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
3043
- writeFileSync(pngPath, buffer);
3044
- snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
3045
- } catch {
3046
- }
3047
- try {
3048
- snapshot.aria = await page.evaluate(`
3049
- (function() {
3050
- try {
3051
- var parts = [];
3052
- var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
3053
- var node;
3054
- while (node = walker.nextNode()) {
3055
- var tag = node.tagName.toLowerCase();
3056
- var role = node.getAttribute('role') || '';
3057
- var text = (node.textContent || '').trim().substring(0, 60);
3058
- var ariaLabel = node.getAttribute('aria-label') || '';
3059
- if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
3060
- parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
3061
- }
3062
- }
3063
- return parts.slice(0, 100).join(' | ');
3064
- } catch(e) { return ''; }
3065
- })()
3066
- `);
3067
- } catch {
3068
- }
3069
- if (snapshot.png || snapshot.aria) {
3070
- action.snapshots = snapshot;
3071
- }
3072
- }
3073
- /**
3074
- * After a click, wait 300ms then scan for popover/dropdown/menu elements
3075
- * near the click position. This runs server-side to avoid race conditions
3076
- * with the client-side poll interval.
3077
- */
3078
- async captureClickContext(page, cx, cy) {
3079
- await new Promise((r) => setTimeout(r, 300));
3080
- try {
3081
- const ctx = await page.evaluate(`
3082
- (function() {
3083
- var cx = ${cx}, cy = ${cy};
3084
- var POPOVER_SELECTORS = [
3085
- '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
3086
- '[role="combobox"]','[role="tree"]','[role="grid"]',
3087
- '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
3088
- '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
3089
- '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
3090
- '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
3091
- '.semi-dropdown','.semi-popover','.semi-modal',
3092
- '.ant-dropdown','.ant-popover','.ant-modal',
3093
- '.el-dropdown','.el-popover','.el-dialog',
3094
- '.t-dropdown','.t-popup','.t-dialog'
3095
- ];
3096
-
3097
- function isNear(el, x, y, range) {
3098
- try {
3099
- var r = el.getBoundingClientRect();
3100
- if (!r || r.width === 0 || r.height === 0) return false;
3101
- return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
3102
- } catch(e) { return false; }
3103
- }
3104
-
3105
- var result = { appeared: [], disappeared: [], stateChanges: [] };
3106
- var seenElements = new Set();
3107
-
3108
- for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
3109
- try {
3110
- var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
3111
- for (var j = 0; j < els.length; j++) {
3112
- var el = els[j];
3113
- if (seenElements.has(el)) continue;
3114
- if (!isNear(el, cx, cy, 300)) continue;
3115
- var rect = el.getBoundingClientRect();
3116
- if (rect.width === 0 || rect.height === 0) continue;
3117
- seenElements.add(el);
3118
-
3119
- var items = [];
3120
- var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
3121
- var seenItemTexts = new Set();
3122
- for (var k = 0; k < Math.min(children.length, 30); k++) {
3123
- var child = children[k];
3124
- var childText = (child.textContent || '').trim().substring(0, 60);
3125
- if (!childText || seenItemTexts.has(childText)) continue;
3126
- seenItemTexts.add(childText);
3127
- var ci = { text: childText };
3128
- try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
3129
- try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
3130
- try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
3131
- items.push(ci);
3132
- }
3133
-
3134
- result.appeared.push({
3135
- tag: el.tagName.toLowerCase(),
3136
- selector: el.id ? '#' + el.id : undefined,
3137
- role: el.getAttribute('role'),
3138
- text: (el.textContent || '').trim().substring(0, 100),
3139
- rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
3140
- items: items
3141
- });
3142
- }
3143
- } catch(e) { /* skip invalid selectors */ }
3144
- }
3145
-
3146
- var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
3147
- for (var i = 0; i < allInteractive.length; i++) {
3148
- var el2 = allInteractive[i];
3149
- if (!isNear(el2, cx, cy, 200)) continue;
3150
- var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
3151
- try { if (el2.id) info.id = el2.id; } catch(e) {}
3152
- try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
3153
- try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
3154
- try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
3155
- try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
3156
- result.stateChanges.push(info);
3157
- }
3158
-
3159
- return result;
3160
- })()
3161
- `);
3162
- if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
3163
- return ctx;
3164
- }
3165
- } catch {
3166
- }
3167
- return void 0;
3168
- }
3169
- async detectCheckpoints(page) {
3170
- const CHECKPOINT_RULES = [
3171
- { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
3172
- { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
3173
- { type: "login", selectors: ['input[type="password"]'] },
3174
- { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
3175
- ];
3176
- try {
3177
- const found = await page.evaluate((rules) => {
3178
- const results = [];
3179
- for (const rule of rules) {
3180
- for (const sel of rule.selectors) {
3181
- try {
3182
- const el = document.querySelector(sel);
3183
- if (el) {
3184
- const rect = el.getBoundingClientRect();
3185
- if (rect.width > 0 && rect.height > 0) {
3186
- results.push({
3187
- type: rule.type,
3188
- selector: sel,
3189
- text: (el.textContent || "").substring(0, 60)
3190
- });
3191
- }
3192
- }
3193
- } catch {
3194
- }
3195
- }
3196
- }
3197
- return results;
3198
- }, CHECKPOINT_RULES);
3199
- const entries = [];
3200
- for (const item of found) {
3201
- this.checkpointCounter++;
3202
- const hints = {
3203
- captcha: "Captcha verification detected",
3204
- slider: "Slider verification detected",
3205
- login: "Login form detected (password field)",
3206
- iframe: "Verification iframe detected"
3207
- };
3208
- entries.push({
3209
- id: this.checkpointCounter,
3210
- type: item.type,
3211
- timestamp: Date.now(),
3212
- url: page.url(),
3213
- pageTitle: await page.title().catch(() => ""),
3214
- hint: hints[item.type] || item.type,
3215
- selector: item.selector,
3216
- source: "auto",
3217
- context: { matchedSelector: item.selector, elementText: item.text }
3218
- });
3219
- }
3220
- return entries;
3221
- } catch {
3222
- return [];
3223
- }
3224
- }
3225
- // ─── Verification: collect success signals after key actions ──────
3226
- /**
3227
- * After a key action (click/submit/input), check for success signals:
3228
- * URL changes, recent successful network responses, dialog appearances.
3229
- */
3230
- async verifyAction(page, action) {
3231
- const signals = [];
3232
- try {
3233
- const currentUrl = page.url();
3234
- if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
3235
- signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
3236
- }
3237
- } catch {
3238
- }
3239
- try {
3240
- const recentNetwork = this.network.filter(
3241
- (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
3242
- );
3243
- for (const net of recentNetwork.slice(0, 3)) {
3244
- signals.push({
3245
- type: "network_success",
3246
- value: `${net.status}`,
3247
- label: `${net.method} ${net.path} \u2192 ${net.status}`
3248
- });
3249
- }
3250
- } catch {
3251
- }
3252
- try {
3253
- const recentDialog = [...this.checkpoints].reverse().find(
3254
- (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
3255
- );
3256
- if (recentDialog) {
3257
- signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
3258
- }
3259
- } catch {
3260
- }
3261
- return signals;
3262
- }
3263
3627
  // ─── Periodic disk flush ────────────────────────────────────────
3264
3628
  flushToDisk() {
3265
3629
  const data = this.buildData();
3266
3630
  try {
3267
- writeFileSync(
3268
- join(this.recordingsDir, "recording.json"),
3631
+ writeFileSync2(
3632
+ join3(this.recordingsDir, "recording.json"),
3269
3633
  JSON.stringify(data, null, 2),
3270
3634
  "utf-8"
3271
3635
  );
3272
- const jsonlPath = join(this.recordingsDir, "recording.jsonl");
3636
+ const jsonlPath = join3(this.recordingsDir, "recording.jsonl");
3273
3637
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3274
- writeFileSync(jsonlPath, lines, "utf-8");
3638
+ writeFileSync2(jsonlPath, lines, "utf-8");
3275
3639
  } catch {
3276
3640
  }
3277
3641
  }
3278
3642
  writeFinalOutput(data, summary) {
3279
- mkdirSync(this.recordingsDir, { recursive: true });
3280
- writeFileSync(join(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3281
- const jsonlPath = join(this.recordingsDir, "recording.jsonl");
3643
+ mkdirSync2(this.recordingsDir, { recursive: true });
3644
+ writeFileSync2(join3(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3645
+ const jsonlPath = join3(this.recordingsDir, "recording.jsonl");
3282
3646
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3283
- writeFileSync(jsonlPath, lines, "utf-8");
3284
- writeFileSync(join(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3285
- writeFileSync(join(this.recordingsDir, "summary.md"), this.buildMarkdownSummary(data, summary), "utf-8");
3647
+ writeFileSync2(jsonlPath, lines, "utf-8");
3648
+ writeFileSync2(join3(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3649
+ const compactSummary = buildCompactSummary(data, this.startedAt);
3650
+ writeFileSync2(join3(this.recordingsDir, "summary-compact.json"), JSON.stringify(compactSummary, null, 2), "utf-8");
3651
+ writeFileSync2(join3(this.recordingsDir, "summary.md"), buildMarkdownSummary(data, summary), "utf-8");
3286
3652
  }
3287
3653
  buildData() {
3288
3654
  return {
@@ -3290,321 +3656,15 @@ var SessionRecorder = class _SessionRecorder {
3290
3656
  sessionName: this.sessionName,
3291
3657
  startedAt: new Date(this.startedAt).toISOString(),
3292
3658
  actions: [...this.actions],
3293
- network: [...this.network],
3659
+ network: [...this.networkCapture.entries],
3294
3660
  contextChanges: [...this.contextChanges],
3295
3661
  checkpoints: [...this.checkpoints],
3296
3662
  discoveredFilters: [...this.discoveredFilters.values()]
3297
3663
  };
3298
3664
  }
3299
- // ─── Summary builder with ref compression + input→network matching ──
3300
- buildSummary(data) {
3301
- const POST_WINDOW = 5e3;
3302
- const MERGE_WINDOW = 2e3;
3303
- const steps = [];
3304
- const selectorToRef = /* @__PURE__ */ new Map();
3305
- const elements = {};
3306
- let refCounter = 0;
3307
- function getRef(action) {
3308
- const sel = action.element?.selector || action.element?.tag || "_none";
3309
- if (selectorToRef.has(sel)) return selectorToRef.get(sel);
3310
- refCounter++;
3311
- const ref = "e" + refCounter;
3312
- selectorToRef.set(sel, ref);
3313
- if (action.element) {
3314
- elements[ref] = {
3315
- selector: action.element.selector || action.element.tag,
3316
- tag: action.element.tag,
3317
- text: action.element.text,
3318
- role: action.element.role,
3319
- type: action.element.type,
3320
- placeholder: action.element.placeholder,
3321
- ariaLabel: action.element.ariaLabel,
3322
- href: action.element.href
3323
- };
3324
- } else {
3325
- elements[ref] = { selector: "_none", tag: "_", text: "" };
3326
- }
3327
- return ref;
3328
- }
3329
- const isNoiseNetwork = (n) => {
3330
- const url = n.url || "";
3331
- const path = n.path || "";
3332
- const rt = n.resourceType || "";
3333
- if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
3334
- if (n.status === 0) return true;
3335
- if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
3336
- if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
3337
- return false;
3338
- };
3339
- const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
3340
- const filtered = data.actions;
3341
- const groups = [];
3342
- let current = null;
3343
- for (const action of filtered) {
3344
- const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
3345
- const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
3346
- if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
3347
- current.actions.push(action);
3348
- if (action.type === "input") current.primary = action;
3349
- } else {
3350
- current = { actions: [action], primary: action };
3351
- groups.push(current);
3352
- }
3353
- }
3354
- for (const group of groups) {
3355
- const primary = group.primary;
3356
- const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
3357
- const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
3358
- const inputAction = group.actions.find((a) => a.type === "input");
3359
- const nearbyNetwork = meaningfulNetwork.filter(
3360
- (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
3361
- );
3362
- const nearbyContext = data.contextChanges.filter(
3363
- (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
3364
- );
3365
- const matchedInputs = inputAction ? this.matchActionToNetwork(inputAction, nearbyNetwork) : [];
3366
- const clickMatches = primary.type === "click" && primary.element?.text ? this.matchActionToNetwork(primary, nearbyNetwork) : [];
3367
- const signals = primary.__signals || [];
3368
- steps.push({
3369
- step: steps.length + 1,
3370
- ref: getRef(primary),
3371
- action: primary,
3372
- network: nearbyNetwork.map((n) => ({
3373
- ...n,
3374
- responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
3375
- })),
3376
- contextChanges: nearbyContext,
3377
- matchedInputs: [...matchedInputs, ...clickMatches],
3378
- signals
3379
- });
3380
- }
3381
- return {
3382
- startUrl: data.startUrl,
3383
- recordedAt: new Date(this.startedAt).toISOString(),
3384
- durationMs: Date.now() - this.startedAt,
3385
- totalActions: data.actions.length,
3386
- totalNetworkRequests: meaningfulNetwork.length,
3387
- steps,
3388
- elements,
3389
- checkpoints: data.checkpoints
3390
- };
3391
- }
3392
- matchActionToNetwork(action, nearbyNetwork) {
3393
- const matches = [];
3394
- const searchValue = (action.value || action.element?.text || "").trim();
3395
- if (!searchValue || searchValue.length < 2) return matches;
3396
- for (const netEntry of nearbyNetwork) {
3397
- if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
3398
- matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
3399
- }
3400
- if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
3401
- this.searchObjectForValue(
3402
- netEntry.requestBody,
3403
- searchValue,
3404
- netEntry.id,
3405
- "",
3406
- matches
3407
- );
3408
- }
3409
- }
3410
- return matches;
3411
- }
3412
- searchObjectForValue(obj, targetValue, networkId, prefix, results) {
3413
- for (const [key, value] of Object.entries(obj)) {
3414
- const fullKey = prefix ? `${prefix}.${key}` : key;
3415
- if (typeof value === "string" && value.includes(targetValue)) {
3416
- results.push({ inputValue: targetValue, networkId, paramName: fullKey });
3417
- } else if (typeof value === "object" && value !== null) {
3418
- this.searchObjectForValue(value, targetValue, networkId, fullKey, results);
3419
- }
3420
- }
3421
- }
3422
- buildMarkdownSummary(_data, summary) {
3423
- const lines = [];
3424
- const durSec = Math.round(summary.durationMs / 1e3);
3425
- lines.push("# Recording Summary");
3426
- lines.push("");
3427
- lines.push(`- **URL**: ${summary.startUrl}`);
3428
- lines.push(`- **Recorded**: ${summary.recordedAt}`);
3429
- lines.push(`- **Duration**: ${durSec}s`);
3430
- lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
3431
- if (summary.checkpoints.length > 0) {
3432
- const cpTypes = summary.checkpoints.map((c) => c.type);
3433
- lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
3434
- } else {
3435
- lines.push("- **Checkpoints**: 0");
3436
- }
3437
- const checkpointSteps = /* @__PURE__ */ new Map();
3438
- for (const cp of summary.checkpoints) {
3439
- if (cp.relatedActionId != null) {
3440
- for (const step of summary.steps) {
3441
- if (step.action.id === cp.relatedActionId) {
3442
- checkpointSteps.set(step.step, cp);
3443
- break;
3444
- }
3445
- }
3446
- }
3447
- }
3448
- lines.push("");
3449
- lines.push("## Steps");
3450
- lines.push("");
3451
- for (const step of summary.steps) {
3452
- const a = step.action;
3453
- const el = a.element;
3454
- const cp = checkpointSteps.get(step.step);
3455
- if (cp) {
3456
- lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
3457
- lines.push(`- **Type**: ${cp.type} (${cp.source})`);
3458
- lines.push(`- **Hint**: ${cp.hint}`);
3459
- if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
3460
- lines.push(`- **Action needed**: Human intervention required before continuing`);
3461
- } else {
3462
- const title = describeActionTitle(a);
3463
- lines.push(`### Step ${step.step}: ${title}`);
3464
- }
3465
- if (el) {
3466
- const parts = [`\`${el.selector || el.tag}\``];
3467
- if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
3468
- parts.push(`(${el.tag})`);
3469
- if (el.type) parts.push(`type=${el.type}`);
3470
- lines.push(`- **Element**: ${parts.join(" ")}`);
3471
- }
3472
- if (a.value != null && a.type === "input") {
3473
- lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
3474
- }
3475
- if (step.network.length > 0) {
3476
- const netDescs = step.network.map((n) => {
3477
- let desc = `${n.method} ${n.path}`;
3478
- if (n.status) desc += ` \u2192 ${n.status}`;
3479
- if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
3480
- return desc;
3481
- });
3482
- lines.push(`- **Network**: ${netDescs.join(", ")}`);
3483
- for (const n of step.network) {
3484
- if (n.requestBody && typeof n.requestBody === "object") {
3485
- const bodyStr = JSON.stringify(n.requestBody);
3486
- if (bodyStr.length <= 300) {
3487
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
3488
- } else {
3489
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
3490
- }
3491
- }
3492
- }
3493
- } else {
3494
- lines.push("- **Network**: none");
3495
- }
3496
- if (step.matchedInputs.length > 0) {
3497
- for (const m of step.matchedInputs) {
3498
- lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
3499
- }
3500
- }
3501
- for (const ctx of step.contextChanges) {
3502
- if (ctx.type === "navigate") {
3503
- lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
3504
- } else if (ctx.type === "new_tab") {
3505
- lines.push(`- **New tab**: ${ctx.url}`);
3506
- }
3507
- }
3508
- if (a.clickContext) {
3509
- if (a.clickContext.appeared?.length > 0) {
3510
- for (const popup of a.clickContext.appeared) {
3511
- const roleStr = popup.role ? ` [${popup.role}]` : "";
3512
- lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
3513
- if (popup.items?.length > 0) {
3514
- const itemStrs = popup.items.slice(0, 8).map((i) => {
3515
- const dis = i.disabled ? " [disabled]" : "";
3516
- return `"${i.text}"${dis}`;
3517
- });
3518
- let itemLine = ` - Items: ${itemStrs.join(", ")}`;
3519
- if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
3520
- lines.push(itemLine);
3521
- }
3522
- }
3523
- }
3524
- if (a.clickContext.stateChanges?.length > 0) {
3525
- for (const sc of a.clickContext.stateChanges) {
3526
- const parts = [];
3527
- if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
3528
- if (sc.disabled) parts.push("disabled");
3529
- if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
3530
- if (sc.dataState) parts.push(`state=${sc.dataState}`);
3531
- if (parts.length > 0) {
3532
- lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
3533
- }
3534
- }
3535
- }
3536
- }
3537
- lines.push("");
3538
- }
3539
- const allNetwork = summary.steps.flatMap((s) => s.network);
3540
- if (allNetwork.length > 0) {
3541
- lines.push("## Network Timeline");
3542
- lines.push("");
3543
- allNetwork.forEach((n, i) => {
3544
- let line = `${i + 1}. ${n.method} ${n.path}`;
3545
- if (n.status) line += ` \u2192 ${n.status}`;
3546
- if (n.requestBody && typeof n.requestBody === "object") {
3547
- const bodyStr = JSON.stringify(n.requestBody);
3548
- if (bodyStr.length <= 150) {
3549
- line += ` ${bodyStr}`;
3550
- }
3551
- }
3552
- if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
3553
- lines.push(line);
3554
- });
3555
- lines.push("");
3556
- }
3557
- const orphanCheckpoints = summary.checkpoints.filter(
3558
- (cp) => cp.relatedActionId == null || !checkpointSteps.has(
3559
- summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
3560
- )
3561
- );
3562
- if (orphanCheckpoints.length > 0) {
3563
- lines.push("## Unresolved Checkpoints");
3564
- lines.push("");
3565
- for (const cp of orphanCheckpoints) {
3566
- const src = cp.source === "auto" ? "[auto]" : "[manual]";
3567
- lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
3568
- if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
3569
- }
3570
- lines.push("");
3571
- }
3572
- return lines.join("\n");
3573
- }
3574
- static readMarkdownSummary(sessionName) {
3575
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "summary.md");
3576
- try {
3577
- return readFileSync(path, "utf-8");
3578
- } catch {
3579
- return null;
3580
- }
3581
- }
3582
3665
  };
3583
- function describeActionTitle(a) {
3584
- const el = a.element;
3585
- const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
3586
- const elTag = el?.tag ? `<${el.tag}>` : "";
3587
- switch (a.type) {
3588
- case "click":
3589
- return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
3590
- case "input":
3591
- return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
3592
- case "change":
3593
- return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
3594
- case "keydown":
3595
- return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
3596
- case "submit":
3597
- return `Submit ${elText || elTag || "form"}`;
3598
- default:
3599
- return `${a.type} ${elText || elTag}`.trim() || a.type;
3600
- }
3601
- }
3602
- function formatBytes(bytes) {
3603
- if (bytes < 1024) return `${bytes}B`;
3604
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
3605
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
3606
- }
3607
3666
 
3608
3667
  export {
3668
+ readMarkdownSummary,
3609
3669
  SessionRecorder
3610
3670
  };