mcp-scraper 0.2.24 → 0.3.1

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 (35) hide show
  1. package/dist/bin/api-server.cjs +916 -7
  2. package/dist/bin/api-server.cjs.map +1 -1
  3. package/dist/bin/api-server.js +1 -1
  4. package/dist/bin/browser-agent-stdio-server.cjs +989 -28
  5. package/dist/bin/browser-agent-stdio-server.cjs.map +1 -1
  6. package/dist/bin/browser-agent-stdio-server.js +3 -2
  7. package/dist/bin/browser-agent-stdio-server.js.map +1 -1
  8. package/dist/bin/mcp-scraper-cli.cjs +1 -1
  9. package/dist/bin/mcp-scraper-cli.cjs.map +1 -1
  10. package/dist/bin/mcp-scraper-cli.js +1 -1
  11. package/dist/bin/mcp-scraper-combined-stdio-server.cjs +1008 -47
  12. package/dist/bin/mcp-scraper-combined-stdio-server.cjs.map +1 -1
  13. package/dist/bin/mcp-scraper-combined-stdio-server.js +4 -3
  14. package/dist/bin/mcp-scraper-combined-stdio-server.js.map +1 -1
  15. package/dist/bin/mcp-scraper-install.cjs +1 -1
  16. package/dist/bin/mcp-scraper-install.cjs.map +1 -1
  17. package/dist/bin/mcp-scraper-install.js +1 -1
  18. package/dist/bin/mcp-stdio-server.cjs +1 -1
  19. package/dist/bin/mcp-stdio-server.cjs.map +1 -1
  20. package/dist/bin/mcp-stdio-server.js +2 -2
  21. package/dist/{chunk-TTSW2MHR.js → chunk-55T4SRLJ.js} +2 -2
  22. package/dist/chunk-D4JDGKOV.js +7 -0
  23. package/dist/chunk-D4JDGKOV.js.map +1 -0
  24. package/dist/{chunk-4TNQUYP7.js → chunk-LICHCMV6.js} +131 -3
  25. package/dist/chunk-LICHCMV6.js.map +1 -0
  26. package/dist/chunk-NXRWFOEZ.js +816 -0
  27. package/dist/chunk-NXRWFOEZ.js.map +1 -0
  28. package/dist/{server-TZ5EMANS.js → server-AXPNL2RV.js} +40 -3
  29. package/dist/{server-TZ5EMANS.js.map → server-AXPNL2RV.js.map} +1 -1
  30. package/docs/mcp-tool-manifest.generated.json +39 -7
  31. package/package.json +1 -1
  32. package/dist/chunk-4TNQUYP7.js.map +0 -1
  33. package/dist/chunk-ISIITOAL.js +0 -7
  34. package/dist/chunk-ISIITOAL.js.map +0 -1
  35. /package/dist/{chunk-TTSW2MHR.js.map → chunk-55T4SRLJ.js.map} +0 -0
@@ -0,0 +1,816 @@
1
+ // src/services/fanout/cdp-capture.ts
2
+ var ANSWER_RE = /\/backend-api\/(f\/)?conversation$|\/chat_conversations\/[^/]+\/(completion|retry_completion)$|\/completion$/i;
3
+ var FanoutCdpCapture = class {
4
+ client = null;
5
+ reqUrl = /* @__PURE__ */ new Map();
6
+ ctById = /* @__PURE__ */ new Map();
7
+ answerIds = /* @__PURE__ */ new Set();
8
+ bodies = [];
9
+ pending = [];
10
+ answerStreams = 0;
11
+ async attach(page) {
12
+ if (this.client) return;
13
+ const client = await page.context().newCDPSession(page);
14
+ this.client = client;
15
+ await client.send("Network.enable", { maxTotalBufferSize: 2e8, maxResourceBufferSize: 2e8 });
16
+ client.on("Network.requestWillBeSent", (e) => {
17
+ const id = e.requestId;
18
+ const req = e.request;
19
+ if (id) this.reqUrl.set(id, req?.url || "");
20
+ });
21
+ client.on("Network.responseReceived", (e) => {
22
+ const id = e.requestId;
23
+ const res = e.response;
24
+ const url = res?.url || this.reqUrl.get(id) || "";
25
+ const headers = res?.headers || {};
26
+ const ct = String(headers["content-type"] || headers["Content-Type"] || "");
27
+ if (id) this.ctById.set(id, ct);
28
+ if (id && (this.isAnswerUrl(url) || /event-stream/i.test(ct))) this.answerIds.add(id);
29
+ });
30
+ client.on("Network.loadingFinished", (e) => this.grab(e.requestId));
31
+ }
32
+ reset() {
33
+ this.bodies = [];
34
+ this.answerStreams = 0;
35
+ this.answerIds.clear();
36
+ this.pending = [];
37
+ }
38
+ answerStreamCount() {
39
+ return this.answerStreams;
40
+ }
41
+ async drain() {
42
+ await Promise.all(this.pending);
43
+ }
44
+ bestAnswerText() {
45
+ const eventStreams = this.bodies.filter((b) => /event-stream/i.test(b.ct));
46
+ const answerStreams = eventStreams.filter((b) => this.isAnswerUrl(b.url)).sort((a, b) => b.text.length - a.text.length);
47
+ if (answerStreams.length) return answerStreams.map((b) => b.text).join("\n");
48
+ const answerJson = this.bodies.filter((b) => this.isAnswerUrl(b.url)).sort((a, b) => b.text.length - a.text.length);
49
+ if (answerJson.length) return answerJson[0].text;
50
+ if (eventStreams.length) return eventStreams.sort((a, b) => b.text.length - a.text.length)[0].text;
51
+ return "";
52
+ }
53
+ async detach() {
54
+ try {
55
+ await this.client?.detach();
56
+ } catch {
57
+ this.client = null;
58
+ }
59
+ this.client = null;
60
+ }
61
+ isAnswerUrl(url) {
62
+ let path = "";
63
+ try {
64
+ path = new URL(url).pathname;
65
+ } catch {
66
+ path = String(url || "").split("?")[0];
67
+ }
68
+ return ANSWER_RE.test(path);
69
+ }
70
+ grab(requestId) {
71
+ if (!requestId || !this.client || !this.answerIds.has(requestId)) return;
72
+ const url = this.reqUrl.get(requestId) || "";
73
+ const ct = this.ctById.get(requestId) || "";
74
+ const client = this.client;
75
+ const p = client.send("Network.getResponseBody", { requestId }).then((r) => {
76
+ const text = r.base64Encoded ? Buffer.from(String(r.body), "base64").toString("utf8") : String(r.body || "");
77
+ if (text) {
78
+ this.bodies.push({ url, ct, text });
79
+ if (this.isAnswerUrl(url)) this.answerStreams++;
80
+ }
81
+ }).catch(() => void 0);
82
+ this.pending.push(p);
83
+ }
84
+ };
85
+
86
+ // src/services/fanout/parse-helpers.ts
87
+ var INTERNAL = /chatgpt\.com|openai\.com|oaiusercontent|oaistatic|claude\.ai|anthropic\.com/i;
88
+ var TRACK = /^(utm_|oai|fbclid|gclid|ref$|ref_|sa$|usg$|ved$|sca_esv$|sources$)/i;
89
+ function domainOf(u) {
90
+ try {
91
+ return new URL(u).hostname.replace(/^www\./, "");
92
+ } catch {
93
+ return "";
94
+ }
95
+ }
96
+ function normUrl(u) {
97
+ try {
98
+ const x = new URL(u);
99
+ x.hash = "";
100
+ for (const k of [...x.searchParams.keys()]) {
101
+ if (TRACK.test(k)) x.searchParams.delete(k);
102
+ }
103
+ return x.toString().replace(/\/$/, "").toLowerCase();
104
+ } catch {
105
+ return String(u || "").toLowerCase();
106
+ }
107
+ }
108
+ function isExternal(u) {
109
+ const h = domainOf(u);
110
+ return Boolean(h) && !INTERNAL.test(h);
111
+ }
112
+ function unesc(s) {
113
+ try {
114
+ return JSON.parse('"' + s + '"');
115
+ } catch {
116
+ return String(s).replace(/\\(.)/g, "$1");
117
+ }
118
+ }
119
+ function stripCitationMarkers(s) {
120
+ return String(s || "").replace(/[-]/g, "").replace(/cite(?:turn\d+\w+?\d+)+/g, "").replace(/\s+/g, " ").trim();
121
+ }
122
+ function sliceBalanced(text, openIdx) {
123
+ const open = text[openIdx];
124
+ const close = open === "[" ? "]" : "}";
125
+ let depth = 0;
126
+ let inStr = false;
127
+ let esc2 = false;
128
+ for (let i = openIdx; i < text.length; i++) {
129
+ const ch = text[i];
130
+ if (inStr) {
131
+ if (esc2) esc2 = false;
132
+ else if (ch === "\\") esc2 = true;
133
+ else if (ch === '"') inStr = false;
134
+ continue;
135
+ }
136
+ if (ch === '"') {
137
+ inStr = true;
138
+ continue;
139
+ }
140
+ if (ch === open) depth++;
141
+ else if (ch === close) {
142
+ depth--;
143
+ if (depth === 0) return text.slice(openIdx, i + 1);
144
+ }
145
+ }
146
+ return null;
147
+ }
148
+ function findJsonValues(text, field) {
149
+ const out = [];
150
+ const re = new RegExp('"' + field + '"\\s*:\\s*(\\[|\\{)', "g");
151
+ let m;
152
+ while (m = re.exec(text)) {
153
+ const openIdx = m.index + m[0].length - 1;
154
+ const slice = sliceBalanced(text, openIdx);
155
+ if (slice) {
156
+ try {
157
+ out.push(JSON.parse(slice));
158
+ } catch {
159
+ continue;
160
+ }
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+ function stringsInArrayBody(arrBody) {
166
+ const out = [];
167
+ const re = /"((?:[^"\\]|\\.){2,300}?)"/g;
168
+ let m;
169
+ while (m = re.exec(arrBody)) out.push(unesc(m[1]));
170
+ return out;
171
+ }
172
+ function cleanQuery(q) {
173
+ const t = (q || "").trim();
174
+ if (t.length < 2 || t.length > 300) return null;
175
+ return t;
176
+ }
177
+
178
+ // src/services/fanout/adapters/chatgpt.ts
179
+ function roundOf(refId) {
180
+ const m = /^turn(\d+)/.exec(refId || "");
181
+ return m ? Number(m[1]) : null;
182
+ }
183
+ function normRef(r) {
184
+ if (typeof r === "string") {
185
+ const m = /turn(\d+)(search|news|ref|video|image|product)(\d+)/.exec(r);
186
+ return m ? `turn${m[1]}${m[2]}${m[3]}` : null;
187
+ }
188
+ if (r && typeof r === "object") {
189
+ const o = r;
190
+ if (o.turn_index != null) {
191
+ return `turn${o.turn_index}${o.ref_type || "search"}${o.ref_index != null ? o.ref_index : ""}`;
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+ function refsInText(s) {
197
+ return (String(s || "").match(/turn\d+(?:search|news|ref|video|image|product)\d+/g) || []).map(normRef).filter((x) => Boolean(x));
198
+ }
199
+ function collectInto(arr, v) {
200
+ if (Array.isArray(v)) arr.push(...v);
201
+ else if (v && typeof v === "object") arr.push(v);
202
+ }
203
+ function reconstructFromSsePatches(raw) {
204
+ const contentReferences = [];
205
+ const searchResultGroups = [];
206
+ const citations = [];
207
+ const citedUrls = /* @__PURE__ */ new Set();
208
+ const state = { found: false };
209
+ const handleOp = (op) => {
210
+ if (!op || typeof op !== "object") return;
211
+ const o = op;
212
+ const v = o.v;
213
+ if (o.o === "patch" && Array.isArray(v)) {
214
+ state.found = true;
215
+ v.forEach(handleOp);
216
+ return;
217
+ }
218
+ const path = typeof o.p === "string" ? o.p : "";
219
+ if ((path === "" || path === "/message") && v && typeof v === "object") {
220
+ const root = v;
221
+ const msg = root.message || root;
222
+ const md = msg && msg.metadata;
223
+ if (md) {
224
+ collectInto(contentReferences, md.content_references);
225
+ collectInto(searchResultGroups, md.search_result_groups);
226
+ collectInto(citations, md.citations);
227
+ state.found = true;
228
+ }
229
+ }
230
+ if (!path) return;
231
+ if (/\/safe_urls$/.test(path) && Array.isArray(v)) {
232
+ for (const u of v) if (typeof u === "string") citedUrls.add(u);
233
+ state.found = true;
234
+ } else if (path.includes("content_references")) {
235
+ collectInto(contentReferences, v);
236
+ state.found = true;
237
+ } else if (path.includes("search_result_groups")) {
238
+ collectInto(searchResultGroups, v);
239
+ state.found = true;
240
+ } else if (path.includes("citations")) {
241
+ collectInto(citations, v);
242
+ state.found = true;
243
+ }
244
+ };
245
+ for (const line of raw.split("\n")) {
246
+ const s = (line.startsWith("data:") ? line.slice(5) : line).trim();
247
+ if (!s || s === "[DONE]" || s[0] !== "{" && s[0] !== "[") continue;
248
+ let parsed;
249
+ try {
250
+ parsed = JSON.parse(s);
251
+ } catch {
252
+ continue;
253
+ }
254
+ const ops = Array.isArray(parsed) ? parsed : [parsed];
255
+ ops.forEach(handleOp);
256
+ }
257
+ if (!state.found) return raw;
258
+ const citedRefs = [...citedUrls].map((url) => ({ type: "grouped_webpages", items: [{ url }] }));
259
+ const synthetic = JSON.stringify({
260
+ content_references: [...contentReferences, ...citedRefs],
261
+ search_result_groups: searchResultGroups,
262
+ citations
263
+ });
264
+ return raw + "\n" + synthetic;
265
+ }
266
+ var chatgptAdapter = {
267
+ platform: "ChatGPT",
268
+ matchesHost(hostname) {
269
+ return /(^|\.)chatgpt\.com$|(^|\.)openai\.com$/i.test(hostname);
270
+ },
271
+ parse(rawInput, prompt) {
272
+ const raw = reconstructFromSsePatches(rawInput);
273
+ const sources = /* @__PURE__ */ new Map();
274
+ const snippets = /* @__PURE__ */ new Map();
275
+ const queries = /* @__PURE__ */ new Set();
276
+ const unmapped = /* @__PURE__ */ new Set();
277
+ const meta = { model: "", finishType: "", title: "", rounds: 0 };
278
+ const ensure = (url) => {
279
+ if (!isExternal(url)) return null;
280
+ const k = normUrl(url);
281
+ let s = sources.get(k);
282
+ if (!s) {
283
+ s = { url, domain: domainOf(url), title: "", cited: false, timesCited: 0, firstOrder: Infinity, snippet: "", round: null };
284
+ sources.set(k, s);
285
+ }
286
+ return s;
287
+ };
288
+ const addSnippet = (url, title, text) => {
289
+ const clean = stripCitationMarkers(text);
290
+ if (!isExternal(url) || clean.length < 2) return;
291
+ snippets.set(normUrl(url), { url, domain: domainOf(url), title: title || domainOf(url), text: clean.slice(0, 400) });
292
+ };
293
+ for (const m of raw.matchAll(/"([a-z_]*(?:quer|search)[a-z_]*)"\s*:/gi)) unmapped.add(m[1]);
294
+ for (const m of raw.matchAll(/"search_model_queries"\s*:\s*\[([^\]]*)\]/g)) {
295
+ for (const q of stringsInArrayBody(m[1])) {
296
+ const c = cleanQuery(q);
297
+ if (c) queries.add(c);
298
+ }
299
+ }
300
+ for (const m of raw.matchAll(/"(?:search_queries|queries|search_query)"\s*:\s*\[([^\]]*)\]/g)) {
301
+ for (const q of stringsInArrayBody(m[1])) {
302
+ const c = cleanQuery(q);
303
+ if (c) queries.add(c);
304
+ }
305
+ }
306
+ for (const v of findJsonValues(raw, "search_result_groups")) {
307
+ if (!Array.isArray(v)) continue;
308
+ for (const g of v) {
309
+ const entries = g && typeof g === "object" && Array.isArray(g.entries) ? g.entries : [];
310
+ for (const e of entries) {
311
+ const url = typeof e.url === "string" ? e.url : "";
312
+ const s = ensure(url);
313
+ if (!s) continue;
314
+ if (!s.title && typeof e.title === "string") s.title = e.title.slice(0, 200);
315
+ const ref = normRef(e.ref_id);
316
+ if (ref && s.round == null) s.round = roundOf(ref);
317
+ if (typeof e.snippet === "string" && e.snippet) addSnippet(url, s.title, e.snippet);
318
+ }
319
+ }
320
+ }
321
+ for (const m of raw.matchAll(/"url"\s*:\s*"(https?:\/\/[^"\\]+)"(?:[\s\S]{0,120}?"(?:title|name)"\s*:\s*"((?:[^"\\]|\\.){0,200})")?/g)) {
322
+ const s = ensure(m[1]);
323
+ if (s && !s.title && m[2]) s.title = unesc(m[2]).slice(0, 200);
324
+ }
325
+ let spanTotal = 0;
326
+ for (const cr of findJsonValues(raw, "content_references")) {
327
+ if (!Array.isArray(cr)) continue;
328
+ for (const ref of cr) {
329
+ const type = typeof ref.type === "string" ? ref.type : "";
330
+ const isBundle = /sources_footnote|nav_list|alt_text/.test(type);
331
+ const refs = refsInText(typeof ref.matched_text === "string" ? ref.matched_text : "");
332
+ if (!isBundle) spanTotal++;
333
+ const ord = typeof ref.start_idx === "number" ? ref.start_idx : isBundle ? Infinity : spanTotal;
334
+ const items = Array.isArray(ref.items) ? ref.items : [];
335
+ items.forEach((it, idx) => {
336
+ const refForItem = refs.length === items.length ? refs[idx] : refs[0];
337
+ const urls = [it.url].concat((Array.isArray(it.supporting_websites) ? it.supporting_websites : []).map((s) => s?.url)).filter((u) => typeof u === "string");
338
+ for (const u of urls) {
339
+ const s = ensure(u);
340
+ if (!s) continue;
341
+ if (!isBundle) {
342
+ s.cited = true;
343
+ s.timesCited++;
344
+ if (ord < s.firstOrder) s.firstOrder = ord;
345
+ } else if (!s.cited) {
346
+ s.cited = true;
347
+ }
348
+ if (refForItem && s.round == null) s.round = roundOf(refForItem);
349
+ }
350
+ if (typeof it.url === "string" && typeof it.snippet === "string") addSnippet(it.url, typeof it.title === "string" ? it.title : "", it.snippet);
351
+ });
352
+ }
353
+ }
354
+ for (const v of findJsonValues(raw, "citations")) {
355
+ if (!Array.isArray(v)) continue;
356
+ v.forEach((c, i) => {
357
+ const md = c && typeof c === "object" ? c.metadata : null;
358
+ if (!md || typeof md.url !== "string") return;
359
+ const s = ensure(md.url);
360
+ if (!s) return;
361
+ s.cited = true;
362
+ s.timesCited++;
363
+ const ord = typeof c.start_ix === "number" ? c.start_ix : i;
364
+ if (ord < s.firstOrder) s.firstOrder = ord;
365
+ if (typeof md.text === "string") addSnippet(md.url, typeof md.title === "string" ? md.title : "", md.text);
366
+ });
367
+ }
368
+ for (const m of raw.matchAll(/"content_type"\s*:\s*"tether_quote"([\s\S]{0,4000}?)"text"\s*:\s*"((?:[^"\\]|\\.)*)"/g)) {
369
+ const url = (m[1].match(/"url"\s*:\s*"([^"]+)"/) || [])[1];
370
+ const title = (m[1].match(/"title"\s*:\s*"((?:[^"\\]|\\.)*)"/) || [])[1];
371
+ if (url) {
372
+ ensure(url);
373
+ addSnippet(url, title ? unesc(title) : "", unesc(m[2]));
374
+ }
375
+ }
376
+ const modelMatches = [...raw.matchAll(/"resolved_model_slug"\s*:\s*"([^"]+)"/g)];
377
+ const slugMatches = modelMatches.length ? modelMatches : [...raw.matchAll(/"model_slug"\s*:\s*"([^"]+)"/g)];
378
+ if (slugMatches.length) meta.model = slugMatches[slugMatches.length - 1][1];
379
+ const finish = raw.match(/"finish_details"\s*:\s*\{[^}]*"type"\s*:\s*"([^"]+)"/);
380
+ if (finish) meta.finishType = finish[1];
381
+ const searchRounds = (raw.match(/"recipient"\s*:\s*"(?:web|browser)"[\s\S]{0,400}?"content_type"\s*:\s*"code"[\s\S]{0,200}?search\(/g) || []).length;
382
+ const sourceRounds = /* @__PURE__ */ new Set();
383
+ for (const s of sources.values()) if (s.round != null) sourceRounds.add(s.round);
384
+ meta.rounds = Math.max(searchRounds, sourceRounds.size);
385
+ const ordered = [...sources.values()].sort((a, b) => a.cited === b.cited ? b.timesCited - a.timesCited || a.firstOrder - b.firstOrder : a.cited ? -1 : 1).map((s) => ({
386
+ url: s.url,
387
+ domain: s.domain,
388
+ title: s.title || s.domain,
389
+ cited: s.cited,
390
+ timesCited: s.timesCited,
391
+ snippet: snippets.get(normUrl(s.url))?.text || "",
392
+ round: s.round
393
+ }));
394
+ return {
395
+ subQueries: [...queries],
396
+ sources: ordered,
397
+ snippets: [...snippets.values()],
398
+ meta,
399
+ unmappedKeys: [...unmapped].slice(0, 50)
400
+ };
401
+ }
402
+ };
403
+
404
+ // src/services/fanout/adapters/claude.ts
405
+ function isFavicon(u) {
406
+ return /\/s2\/favicons/i.test(u) || /favicon/i.test(u);
407
+ }
408
+ var claudeAdapter = {
409
+ platform: "Claude",
410
+ matchesHost(hostname) {
411
+ return /(^|\.)claude\.ai$/i.test(hostname);
412
+ },
413
+ parse(raw, prompt) {
414
+ const sources = /* @__PURE__ */ new Map();
415
+ const snippets = /* @__PURE__ */ new Map();
416
+ const queries = /* @__PURE__ */ new Set();
417
+ const unmapped = /* @__PURE__ */ new Set();
418
+ const meta = { model: "", finishType: "", title: "", rounds: 0 };
419
+ const ensure = (url) => {
420
+ if (!url || !isExternal(url) || isFavicon(url)) return null;
421
+ const k = normUrl(url);
422
+ let s = sources.get(k);
423
+ if (!s) {
424
+ s = { url, domain: domainOf(url), title: "", cited: false, timesCited: 0, snippet: "", round: null };
425
+ sources.set(k, s);
426
+ }
427
+ return s;
428
+ };
429
+ const toolInputs = /* @__PURE__ */ new Map();
430
+ const searchBlocks = /* @__PURE__ */ new Set();
431
+ const finalizeTool = (index) => {
432
+ const t = toolInputs.get(index);
433
+ if (!t || !/web_search|web_fetch|search|browse/i.test(t.name)) return;
434
+ try {
435
+ const input = JSON.parse(t.buf);
436
+ if (typeof input.query === "string") {
437
+ const q = cleanQuery(input.query);
438
+ if (q) queries.add(q);
439
+ }
440
+ } catch {
441
+ const m = t.buf.match(/"query"\s*:\s*"((?:[^"\\]|\\.)*)"/);
442
+ if (m) {
443
+ const q = cleanQuery(unesc(m[1]));
444
+ if (q) queries.add(q);
445
+ }
446
+ }
447
+ };
448
+ for (const line of raw.split("\n")) {
449
+ const s = (line.startsWith("data:") ? line.slice(5) : line).trim();
450
+ if (!s || s[0] !== "{" && s[0] !== "[") continue;
451
+ let ev;
452
+ try {
453
+ ev = JSON.parse(s);
454
+ } catch {
455
+ continue;
456
+ }
457
+ const type = ev.type;
458
+ if (type === "content_block_start") {
459
+ const cb = ev.content_block || {};
460
+ const index = typeof ev.index === "number" ? ev.index : -1;
461
+ if (cb.type === "tool_use" && index >= 0) {
462
+ const name = typeof cb.name === "string" ? cb.name : "";
463
+ toolInputs.set(index, { name, buf: "" });
464
+ if (/web_search|web_fetch|search|browse/i.test(name)) searchBlocks.add(index);
465
+ }
466
+ } else if (type === "content_block_delta") {
467
+ const d = ev.delta || {};
468
+ const index = typeof ev.index === "number" ? ev.index : -1;
469
+ if (d.type === "input_json_delta" && typeof d.partial_json === "string") {
470
+ const t = toolInputs.get(index);
471
+ if (t) t.buf += d.partial_json;
472
+ } else if (d.type === "citation_start_delta") {
473
+ const c = d.citation || {};
474
+ if (typeof c.url === "string") {
475
+ const src = ensure(c.url);
476
+ if (src) {
477
+ src.cited = true;
478
+ src.timesCited++;
479
+ if (!src.title && typeof c.title === "string") src.title = c.title.slice(0, 200);
480
+ if (typeof c.cited_text === "string" && c.cited_text) {
481
+ snippets.set(normUrl(c.url), { url: c.url, domain: domainOf(c.url), title: src.title, text: String(c.cited_text).slice(0, 400) });
482
+ }
483
+ }
484
+ }
485
+ }
486
+ } else if (type === "content_block_stop") {
487
+ const index = typeof ev.index === "number" ? ev.index : -1;
488
+ if (index >= 0) finalizeTool(index);
489
+ } else if (type === "message_delta" || type === "message_stop" || type === "message_start") {
490
+ const d = ev.delta || ev.message || {};
491
+ if (typeof d.stop_reason === "string" && !meta.finishType) meta.finishType = d.stop_reason;
492
+ if (typeof d.model === "string" && !meta.model) meta.model = d.model;
493
+ }
494
+ }
495
+ for (const index of searchBlocks) finalizeTool(index);
496
+ for (const m of raw.matchAll(/"title"\s*:\s*"((?:[^"\\]|\\.){1,200})"\s*,\s*"url"\s*:\s*"(https?:\/\/[^"\\]+)"/g)) {
497
+ const src = ensure(m[2]);
498
+ if (src && !src.title) src.title = unesc(m[1]).slice(0, 200);
499
+ }
500
+ for (const m of raw.matchAll(/"url"\s*:\s*"(https?:\/\/[^"\\]+)"/g)) ensure(m[1]);
501
+ for (const m of raw.matchAll(/\\"title\\"\s*:\s*\\"((?:[^"\\]|\\.){1,160}?)\\"[\s\S]{0,160}?\\"url\\"\s*:\s*\\"(https?:[^"\\]+)\\"/g)) {
502
+ const src = ensure(m[2]);
503
+ if (src && !src.title) src.title = unesc(unesc(m[1])).slice(0, 200);
504
+ }
505
+ for (const m of raw.matchAll(/\\"url\\"\s*:\s*\\"(https?:[^"\\]+)\\"/g)) ensure(m[1]);
506
+ if (!meta.model) {
507
+ const mm = raw.match(/"model"\s*:\s*"(claude[^"]+)"/);
508
+ if (mm) meta.model = mm[1];
509
+ }
510
+ meta.rounds = queries.size > 0 ? searchBlocks.size : 0;
511
+ for (const m of raw.matchAll(/"([a-z_]*(?:quer|search)[a-z_]*)"\s*:/gi)) unmapped.add(m[1]);
512
+ const ordered = [...sources.values()].sort((a, b) => a.cited === b.cited ? b.timesCited - a.timesCited : a.cited ? -1 : 1).map((s) => ({
513
+ url: s.url,
514
+ domain: s.domain,
515
+ title: s.title || s.domain,
516
+ cited: s.cited,
517
+ timesCited: s.timesCited,
518
+ snippet: snippets.get(normUrl(s.url))?.text || "",
519
+ round: s.round
520
+ }));
521
+ return {
522
+ subQueries: [...queries],
523
+ sources: ordered,
524
+ snippets: [...snippets.values()],
525
+ meta,
526
+ unmappedKeys: [...unmapped].slice(0, 50)
527
+ };
528
+ }
529
+ };
530
+
531
+ // src/services/fanout/adapters/index.ts
532
+ var FANOUT_ADAPTERS = [chatgptAdapter, claudeAdapter];
533
+ function adapterForHost(hostname) {
534
+ return FANOUT_ADAPTERS.find((a) => a.matchesHost(hostname)) ?? null;
535
+ }
536
+
537
+ // src/services/fanout/build.ts
538
+ function buildFanoutResult(ctx) {
539
+ const { platform, parsed, ready, rawBytes } = ctx;
540
+ const browsedUrls = parsed.sources;
541
+ const citedUrls = browsedUrls.filter((s) => s.cited);
542
+ const browsedOnly = browsedUrls.filter((s) => !s.cited);
543
+ const prompt = ctx.prompt || parsed.meta.title || "";
544
+ const result = {
545
+ platform,
546
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
547
+ prompt,
548
+ meta: parsed.meta,
549
+ subQueries: parsed.subQueries,
550
+ browsedUrls,
551
+ citedUrls,
552
+ browsedOnly,
553
+ snippets: parsed.snippets,
554
+ counts: {
555
+ subQueries: parsed.subQueries.length,
556
+ browsed: browsedUrls.length,
557
+ cited: citedUrls.length,
558
+ browsedOnly: browsedOnly.length
559
+ }
560
+ };
561
+ if (parsed.subQueries.length === 0 && browsedUrls.length === 0) {
562
+ result.debug = {
563
+ interceptorReady: ready,
564
+ rawBytes,
565
+ unmappedKeys: parsed.unmappedKeys,
566
+ note: ready ? "Capture hook is live but no fan-out was seen yet. Run a NEW prompt that triggers web search in this session, then call browser_capture_fanout again. Fan-out is only captured as it streams; past answers from before the session opened cannot be recovered." : "Capture hook not detected on this page. The session must be opened with MCP_SCRAPER_BROWSER_MODE=local and navigated to chatgpt.com or claude.ai after opening, so the hook installs before the site scripts run."
567
+ };
568
+ }
569
+ return result;
570
+ }
571
+
572
+ // src/services/fanout/classify.ts
573
+ var SOCIAL = /(^|\.)(youtube\.com|youtu\.be|instagram\.com|tiktok\.com|facebook\.com|fb\.com|x\.com|twitter\.com|linkedin\.com|pinterest\.com|threads\.net|vimeo\.com)$/i;
574
+ var ENCYCLOPEDIA = /(^|\.)(wikipedia\.org|wikimedia\.org|britannica\.com|merriam-webster\.com|dictionary\.com|fandom\.com|investopedia\.com)$/i;
575
+ var REVIEW = /(^|\.)(yelp\.com|trustpilot\.com|g2\.com|capterra\.com|angi\.com|angieslist\.com|bbb\.org|consumeraffairs\.com|bestcompany\.com|sitejabber\.com|clutch\.co|bestpickreports\.com|homeguide\.com|porch\.com|ontoplist\.com|thumbtack\.com)$/i;
576
+ var NEWS = /(^|\.)(reuters\.com|apnews\.com|nytimes\.com|wsj\.com|washingtonpost\.com|bloomberg\.com|cnbc\.com|forbes\.com|bbc\.com|theguardian\.com|cnn\.com|npr\.org|usatoday\.com|expressnews\.com|mysanantonio\.com|beaumontenterprise\.com)$/i;
577
+ function classifyDomain(domain, firstPartyDomain) {
578
+ const d = domain.toLowerCase().replace(/^www\./, "");
579
+ if (firstPartyDomain) {
580
+ const fp = firstPartyDomain.toLowerCase().replace(/^www\./, "");
581
+ if (fp && (d === fp || d.endsWith("." + fp))) return "First-party/vendor";
582
+ }
583
+ if (/(^|\.)reddit\.com$/i.test(d)) return "Reddit";
584
+ if (SOCIAL.test(d)) return "Social/video";
585
+ if (ENCYCLOPEDIA.test(d)) return "Encyclopedia";
586
+ if (REVIEW.test(d)) return "Review site";
587
+ if (NEWS.test(d) || /(^|\.)news\./i.test(d)) return "News/media";
588
+ if (/^docs?\.|^developer\.|^developers\.|readthedocs|\.dev$/i.test(d)) return "Docs";
589
+ return "Blog";
590
+ }
591
+ function emptyCategoryCounts() {
592
+ return { "First-party/vendor": 0, "News/media": 0, Reddit: 0, "Social/video": 0, Encyclopedia: 0, "Review site": 0, Docs: 0, Blog: 0 };
593
+ }
594
+ function enrichFanout(result, opts = {}) {
595
+ const addSiteType = (s) => ({ ...s, siteType: classifyDomain(s.domain, opts.firstPartyDomain) });
596
+ const browsedUrls = result.browsedUrls.map(addSiteType);
597
+ const citedUrls = result.citedUrls.map(addSiteType);
598
+ const browsedOnly = result.browsedOnly.map(addSiteType);
599
+ const byCategory = emptyCategoryCounts();
600
+ const domainAgg = /* @__PURE__ */ new Map();
601
+ for (const s of browsedUrls) {
602
+ byCategory[s.siteType]++;
603
+ const cur = domainAgg.get(s.domain);
604
+ if (!cur) domainAgg.set(s.domain, { domain: s.domain, count: 1, cited: s.cited, timesCited: s.timesCited, siteType: s.siteType });
605
+ else {
606
+ cur.count++;
607
+ cur.cited = cur.cited || s.cited;
608
+ cur.timesCited += s.timesCited;
609
+ }
610
+ }
611
+ const topSites = [...domainAgg.values()].sort((a, b) => b.count - a.count || b.timesCited - a.timesCited);
612
+ const citationOrder = citedUrls.slice().sort((a, b) => b.timesCited - a.timesCited).map((s, i) => ({ rank: i + 1, domain: s.domain, url: s.url, timesCited: s.timesCited }));
613
+ return {
614
+ platform: result.platform,
615
+ capturedAt: result.capturedAt,
616
+ prompt: result.prompt,
617
+ meta: result.meta,
618
+ queries: result.subQueries,
619
+ browsedUrls,
620
+ citedUrls,
621
+ browsedOnly,
622
+ snippets: result.snippets,
623
+ counts: result.counts,
624
+ aggregates: { topSites, citationOrder, byCategory },
625
+ firstPartyDomain: opts.firstPartyDomain ? opts.firstPartyDomain.toLowerCase().replace(/^www\./, "") : null,
626
+ ...result.debug ? { debug: result.debug } : {}
627
+ };
628
+ }
629
+
630
+ // src/services/fanout/export.ts
631
+ import { mkdirSync, writeFileSync } from "fs";
632
+ import { homedir } from "os";
633
+ import { join } from "path";
634
+ import Papa from "papaparse";
635
+ function outputBaseDir() {
636
+ return process.env.MCP_SCRAPER_OUTPUT_DIR?.trim() || join(homedir(), "Downloads", "mcp-scraper");
637
+ }
638
+ function safe(value) {
639
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "capture";
640
+ }
641
+ function writeTable(path, rows, delimiter) {
642
+ writeFileSync(path, Papa.unparse(rows.length ? rows : [{}], { delimiter }));
643
+ }
644
+ function exportFanout(enriched) {
645
+ const stamp = safe(enriched.capturedAt.replace(/[:.]/g, "-"));
646
+ const dir = join(outputBaseDir(), "fanout", `${stamp}-${safe(enriched.platform)}`);
647
+ mkdirSync(dir, { recursive: true });
648
+ const queryRows = enriched.queries.map((q, i) => ({ index: i + 1, query: q }));
649
+ const citationRows = enriched.aggregates.citationOrder.map((c) => {
650
+ const src = enriched.citedUrls.find((s) => s.url === c.url);
651
+ return { rank: c.rank, domain: c.domain, url: c.url, timesCited: c.timesCited, siteType: src?.siteType ?? "", title: src?.title ?? "" };
652
+ });
653
+ const sourceRows = enriched.browsedUrls.map((s) => ({ domain: s.domain, url: s.url, cited: s.cited, timesCited: s.timesCited, siteType: s.siteType, title: s.title, round: s.round ?? "" }));
654
+ const domainRows = enriched.aggregates.topSites.map((d) => ({ domain: d.domain, count: d.count, cited: d.cited, timesCited: d.timesCited, siteType: d.siteType }));
655
+ const paths = {
656
+ dir,
657
+ json: join(dir, "fanout.json"),
658
+ queriesCsv: join(dir, "queries.csv"),
659
+ queriesTsv: join(dir, "queries.tsv"),
660
+ citationsCsv: join(dir, "citations.csv"),
661
+ sourcesCsv: join(dir, "sources.csv"),
662
+ domainsCsv: join(dir, "domains.csv"),
663
+ report: join(dir, "report.html")
664
+ };
665
+ writeFileSync(paths.json, JSON.stringify(enriched, null, 2));
666
+ writeTable(paths.queriesCsv, queryRows, ",");
667
+ writeTable(paths.queriesTsv, queryRows, " ");
668
+ writeTable(paths.citationsCsv, citationRows, ",");
669
+ writeTable(paths.sourcesCsv, sourceRows, ",");
670
+ writeTable(paths.domainsCsv, domainRows, ",");
671
+ writeFileSync(paths.report, renderReportHtml(enriched));
672
+ return paths;
673
+ }
674
+ function esc(s) {
675
+ return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
676
+ }
677
+ function renderReportHtml(enriched) {
678
+ const data = JSON.stringify(enriched).replace(/</g, "\\u003c");
679
+ return `<!doctype html>
680
+ <html lang="en">
681
+ <head>
682
+ <meta charset="utf-8" />
683
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
684
+ <title>AI Search Fan-Out \u2014 ${esc(enriched.platform)}</title>
685
+ <style>
686
+ :root{--bg:#0b0d12;--panel:#151922;--line:#252b38;--ink:#e8ecf3;--mut:#8b95a7;--acc:#5b9dff;--cite:#39d98a;--browse:#5a6677}
687
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}
688
+ .wrap{max-width:980px;margin:0 auto;padding:28px 20px 80px}
689
+ h1{font-size:20px;margin:0 0 2px}.sub{color:var(--mut);margin:0 0 20px;font-size:13px}
690
+ .stat{font-size:30px;font-weight:700}.stat small{font-size:13px;font-weight:400;color:var(--mut)}
691
+ .cards{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:18px 0}
692
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 14px}
693
+ .card b{font-size:22px;display:block}.card span{color:var(--mut);font-size:12px}
694
+ .bars{margin:8px 0 22px}.bar{display:flex;align-items:center;gap:8px;margin:4px 0}
695
+ .bar .lab{width:150px;color:var(--mut);font-size:12px;text-align:right}.bar .track{flex:1;background:#10141c;border-radius:5px;overflow:hidden}
696
+ .bar .fill{background:var(--acc);height:16px}.bar .n{width:34px;font-size:12px;color:var(--mut)}
697
+ .tabs{display:flex;gap:8px;margin:22px 0 12px}.tab{background:var(--panel);border:1px solid var(--line);color:var(--ink);padding:7px 14px;border-radius:8px;cursor:pointer}
698
+ .tab.on{background:var(--acc);border-color:var(--acc);color:#04101f;font-weight:600}
699
+ .chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}
700
+ .chip{background:var(--panel);border:1px solid var(--line);color:var(--mut);padding:4px 10px;border-radius:20px;cursor:pointer;font-size:12px}
701
+ .chip.on{border-color:var(--acc);color:var(--ink)}.chip b{color:var(--ink)}
702
+ .row{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 12px;margin:6px 0;display:flex;gap:10px;align-items:flex-start}
703
+ .row .idx{color:var(--mut);min-width:22px}.row .main{flex:1}
704
+ .tag{font-size:11px;padding:2px 7px;border-radius:6px;border:1px solid var(--line);color:var(--mut);margin-right:5px}
705
+ .dom{font-weight:600}.url{color:var(--mut);font-size:12px;word-break:break-all}
706
+ .pill{font-size:11px;padding:2px 7px;border-radius:6px}.pill.cite{background:rgba(57,217,138,.15);color:var(--cite)}.pill.brow{background:rgba(90,102,119,.2);color:#aeb8c8}
707
+ .copy{background:none;border:1px solid var(--line);color:var(--mut);border-radius:6px;cursor:pointer;font-size:11px;padding:2px 8px}
708
+ .hide{display:none}
709
+ </style>
710
+ </head>
711
+ <body><div class="wrap">
712
+ <h1>AI Search Fan-Out</h1>
713
+ <p class="sub" id="sub"></p>
714
+ <div class="stat" id="stat"></div>
715
+ <div class="cards" id="cards"></div>
716
+ <div id="charts"></div>
717
+ <div class="tabs"><button class="tab on" data-tab="q">Queries</button><button class="tab" data-tab="u">URLs</button></div>
718
+ <div class="chips" id="chips"></div>
719
+ <div id="list"></div>
720
+ </div>
721
+ <script>
722
+ const D=${data};
723
+ const el=(t,c,h)=>{const e=document.createElement(t);if(c)e.className=c;if(h!=null)e.innerHTML=h;return e};
724
+ document.getElementById('sub').textContent=D.platform+' \xB7 '+(D.meta.model||'model n/a')+' \xB7 '+D.meta.rounds+' search round(s) \xB7 prompt: '+(D.prompt||'');
725
+ document.getElementById('stat').innerHTML='Total Fan-Out: '+D.counts.subQueries+' <small>sub-queries \xB7 '+D.counts.browsed+' URLs researched \xB7 '+D.counts.cited+' cited</small>';
726
+ const cards=[['Sub-queries',D.counts.subQueries],['Researched',D.counts.browsed],['Cited',D.counts.cited],['Browsed-only',D.counts.browsedOnly]];
727
+ const cc=document.getElementById('cards');cards.forEach(([k,v])=>{const c=el('div','card');c.appendChild(el('b',null,v));c.appendChild(el('span',null,k));cc.appendChild(c)});
728
+ function barChart(title,obj){const max=Math.max(1,...Object.values(obj));const box=el('div','bars');box.appendChild(el('div',null,'<b>'+title+'</b>'));Object.entries(obj).forEach(([k,v])=>{const r=el('div','bar');r.appendChild(el('div','lab',k));const t=el('div','track');const f=el('div','fill');f.style.width=(v/max*100)+'%';t.appendChild(f);r.appendChild(t);r.appendChild(el('div','n',v));box.appendChild(r)});return box}
729
+ const charts=document.getElementById('charts');
730
+ charts.appendChild(barChart('URL Categories',D.aggregates.byCategory));
731
+ let tab='q',filter=null;
732
+ const chips=document.getElementById('chips'),list=document.getElementById('list');
733
+ function render(){
734
+ chips.innerHTML='';list.innerHTML='';
735
+ if(tab==='q'){
736
+ D.queries.forEach((q,i)=>{const r=el('div','row');r.appendChild(el('div','idx',i+1));const m=el('div','main');m.appendChild(el('div',null,esc(q)));r.appendChild(m);const b=el('button','copy','copy');b.onclick=()=>navigator.clipboard.writeText(q);r.appendChild(b);list.appendChild(r)});
737
+ } else {
738
+ const counts={};D.browsedUrls.forEach(s=>{counts[s.siteType]=(counts[s.siteType]||0)+1});
739
+ Object.entries(counts).forEach(([k,v])=>{const c=el('button','chip'+(filter===k?' on':''),k+' <b>'+v+'</b>');c.onclick=()=>{filter=filter===k?null:k;render()};chips.appendChild(c)});
740
+ D.browsedUrls.forEach(s=>{if(filter&&s.siteType!==filter)return;const r=el('div','row');const m=el('div','main');m.appendChild(el('div',null,'<span class="dom">'+esc(s.domain)+'</span> <span class="pill '+(s.cited?'cite':'brow')+'">'+(s.cited?'cited '+s.timesCited+'\xD7':'browsed')+'</span> <span class="tag">'+s.siteType+'</span>'));m.appendChild(el('div','url',esc(s.url)));r.appendChild(m);list.appendChild(r)});
741
+ }
742
+ }
743
+ function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')}
744
+ document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>{document.querySelectorAll('.tab').forEach(x=>x.classList.remove('on'));t.classList.add('on');tab=t.dataset.tab;filter=null;render()});
745
+ render();
746
+ </script>
747
+ </body></html>`;
748
+ }
749
+
750
+ // src/services/fanout/run-capture.ts
751
+ var COMPOSER_SELECTORS = [
752
+ "#prompt-textarea",
753
+ "div#prompt-textarea",
754
+ 'textarea[data-testid="prompt-textarea"]',
755
+ 'div.ProseMirror[contenteditable="true"]',
756
+ 'div[contenteditable="true"]',
757
+ "textarea"
758
+ ];
759
+ async function sendPrompt(page, text) {
760
+ for (const selector of COMPOSER_SELECTORS) {
761
+ const locator = page.locator(selector).first();
762
+ try {
763
+ await locator.waitFor({ state: "visible", timeout: 12e3 });
764
+ } catch {
765
+ continue;
766
+ }
767
+ await locator.click({ timeout: 4e3 }).catch(() => void 0);
768
+ await locator.focus().catch(() => void 0);
769
+ await page.keyboard.type(text, { delay: 12 });
770
+ await page.waitForTimeout(300).catch(() => void 0);
771
+ await page.keyboard.press("Enter");
772
+ return true;
773
+ }
774
+ return false;
775
+ }
776
+ async function waitForAnswer(page, cap, baseline, waitMs) {
777
+ const start = Date.now();
778
+ while (Date.now() - start < waitMs && cap.answerStreamCount() <= baseline) {
779
+ await page.waitForTimeout(400).catch(() => void 0);
780
+ }
781
+ await page.waitForTimeout(1e3).catch(() => void 0);
782
+ }
783
+ async function runFanoutCapture(page, input) {
784
+ const cap = new FanoutCdpCapture();
785
+ await cap.attach(page);
786
+ try {
787
+ const baseline = cap.answerStreamCount();
788
+ if (input.prompt) await sendPrompt(page, input.prompt).catch(() => false);
789
+ const waitMs = input.wait_ms ?? (input.prompt ? 9e4 : 8e3);
790
+ await waitForAnswer(page, cap, baseline, waitMs);
791
+ await cap.drain();
792
+ let hostname = "";
793
+ try {
794
+ hostname = new URL(page.url()).hostname;
795
+ } catch {
796
+ hostname = "";
797
+ }
798
+ const adapter = adapterForHost(hostname);
799
+ if (!adapter) {
800
+ throw new Error(`browser_capture_fanout supports chatgpt.com and claude.ai only; the session is on ${hostname || "an unknown page"}. Navigate there first with browser_goto.`);
801
+ }
802
+ const text = cap.bestAnswerText();
803
+ const parsed = adapter.parse(text, input.prompt || "");
804
+ const result = buildFanoutResult({ platform: adapter.platform, parsed, prompt: input.prompt || "", ready: true, rawBytes: text.length });
805
+ const enriched = enrichFanout(result, { firstPartyDomain: input.first_party_domain });
806
+ const exports = input.export ? exportFanout(enriched) : null;
807
+ return { result: enriched, exports };
808
+ } finally {
809
+ await cap.detach().catch(() => void 0);
810
+ }
811
+ }
812
+
813
+ export {
814
+ runFanoutCapture
815
+ };
816
+ //# sourceMappingURL=chunk-NXRWFOEZ.js.map