File size: 8,136 Bytes
3330bff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
(function () {
  function compactText(text) {
    return String(text || "").replace(/\s+/g, " ").trim();
  }

  function clipText(text, maxLength = 180) {
    const clean = String(text || "");
    return clean.length > maxLength ? `${clean.slice(0, maxLength - 3).trim()}...` : clean;
  }

  function metadataValue(line, key) {
    const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    return line.match(new RegExp(`\\b${escaped}=([^;\\n]+)`, "i"))?.[1]?.trim() || "";
  }

  function safeUrl(value) {
    let raw = String(value || "").trim();
    if (!raw) return "";
    if (raw.startsWith("//")) raw = `https:${raw}`;

    try {
      return new URL(raw).toString();
    } catch {
      if (!/^[\w.-]+\.[a-z]{2,}(?::\d+)?(?:[/?#]|$)/i.test(raw)) return "";

      try {
        return new URL(`https://${raw}`).toString();
      } catch {
        return "";
      }
    }
  }

  function domainFromUrl(value) {
    const url = safeUrl(value);
    if (!url) return "";

    try {
      return new URL(url).hostname;
    } catch {
      return "";
    }
  }

  function displaySourceName(value) {
    const clean = compactText(value);
    if (!clean) return "";

    const domain = domainFromUrl(clean);
    if (domain) return domain;

    if (/[/\\]/.test(clean)) {
      const basename = clean.split(/[/\\]/).filter(Boolean).pop() || clean;
      return basename.replace(/[_-]+/g, " ");
    }

    return clean;
  }

  function sourceInitial(label) {
    const clean = compactText(label).replace(/^www\./i, "");
    return (clean[0] || "?").toUpperCase();
  }

  function sourceLogoUrl(source) {
    const url = source?.url || (source?.domain ? `https://${source.domain}` : "");
    if (!url) return "";
    return `https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(url)}&sz=64`;
  }

  function parseMetadataLine(line) {
    const raw = String(line || "").trim();
    if (!/^\[\d+\]\s+/.test(raw)) return null;

    const metadataText = raw.replace(/^\[\d+\]\s+/, "");
    const data = {};

    metadataText.split(";").forEach((part) => {
      const index = part.indexOf("=");
      if (index < 0) return;
      const key = part.slice(0, index).trim().toLowerCase();
      const value = part.slice(index + 1).trim();
      if (key) data[key] = value;
    });

    return Object.keys(data).length ? data : null;
  }

  function textCandidateFromJson(value) {
    if (typeof value === "string") return value;

    if (Array.isArray(value)) {
      return value.map(textCandidateFromJson).filter(Boolean).join("\n\n");
    }

    if (!value || typeof value !== "object") return "";

    for (const key of ["text", "raw_text", "content", "page_content", "body", "snippet", "summary"]) {
      const candidate = textCandidateFromJson(value[key]);
      if (candidate) return candidate;
    }

    if (value.document && typeof value.document === "object") {
      return textCandidateFromJson(value.document);
    }

    return "";
  }

  function stripProtocolTags(text) {
    return String(text || "")
      .replace(/\[Runtime instruction:\s*[\s\S]*?\]/gi, "")
      .replace(/<\/?(think|query|result|answer|hand_motor_1|wait)>/gi, "")
      .trim();
  }

  function stripResultHeader(text) {
    return String(text || "").replace(/^Query:\s*[\s\S]*?Retrieved Result:\s*/i, "");
  }

  function cleanResultText(text) {
    const stripped = stripResultHeader(stripProtocolTags(text));
    const lines = stripped.split(/\r?\n/);
    const cleanLines = [];

    for (const line of lines) {
      const trimmed = line.trim();

      if (!trimmed) {
        if (cleanLines.length && cleanLines[cleanLines.length - 1] !== "") cleanLines.push("");
        continue;
      }

      if (/^\[\d+\]\s+/.test(trimmed) && /\b(title|url|source|domain|path|id|chunk|score|rank|crawled|search_)/i.test(trimmed)) {
        continue;
      }

      if (/^(title|url|domain|source|section|path|id|chunk|crawled|crawl_success|fit_markdown|scores):?\s*=/i.test(trimmed)) {
        continue;
      }

      if (/^scores:\s+/i.test(trimmed)) {
        continue;
      }

      if (/^(Retrieval chunk length|Retrieval policy|Retrieval count|Exposure reason|Document exposed|Documents exposed|Continuation chunk offset):/i.test(trimmed)) {
        continue;
      }

      if (/^(If this document is sufficient|If this continuation is sufficient|No more documents remain)/i.test(trimmed)) {
        continue;
      }

      cleanLines.push(line);
    }

    let clean = cleanLines.join("\n").trim();
    const jsonLike = clean.match(/^[\[{]/);

    if (jsonLike) {
      try {
        const parsed = JSON.parse(clean);
        const candidate = textCandidateFromJson(parsed);
        if (candidate) clean = candidate;
      } catch {
        // Keep the cleaned text when the payload only looks like JSON.
      }
    }

    return clean.replace(/\n{3,}/g, "\n\n").trim();
  }

  function cleanPreviewText(text, maxLength = 520) {
    return clipText(compactText(cleanResultText(text)), maxLength);
  }

  function sourceFromMetadata(metadata, rawText) {
    const url = safeUrl(metadata.url || metadata.search_url || metadata.href);
    const sourceName = metadata.domain || metadata.source || metadata.source_name || "";
    const sourceUrl = url || safeUrl(sourceName);
    const domain = domainFromUrl(sourceUrl) || displaySourceName(sourceName);
    const title = metadata.title || metadata.search_title || domain || "Retrieved source";

    return {
      title: compactText(title),
      url: sourceUrl,
      domain: compactText(domain),
      rawText: rawText || "",
      previewText: cleanResultText(rawText || ""),
      key: sourceUrl || `${compactText(domain)}:${compactText(title)}`,
    };
  }

  function sourcesFromResultContent(text) {
    const rawText = String(text || "");
    const sources = [];
    let currentMetadata = null;

    function flushCurrent() {
      if (!currentMetadata) return;
      const source = sourceFromMetadata(currentMetadata, rawText);
      if (source.title || source.domain || source.url) sources.push(source);
      currentMetadata = null;
    }

    rawText.split(/\r?\n/).forEach((line) => {
      const metadata = parseMetadataLine(line);
      if (metadata) {
        flushCurrent();
        currentMetadata = metadata;
        return;
      }

      const trimmed = line.trim();
      const continuation = trimmed.match(/^(title|url|domain|source|source_name|search_title|search_url|href|path|section)=([\s\S]+)$/i);

      if (currentMetadata && continuation) {
        currentMetadata[continuation[1].toLowerCase()] = continuation[2].trim();
        return;
      }

      if (currentMetadata && trimmed && !/^[-*]/.test(trimmed)) {
        flushCurrent();
      }
    });

    flushCurrent();

    if (!sources.length) {
      const url = rawText.match(/https?:\/\/[^\s;)"']+/i)?.[0] || "";
      if (url) {
        sources.push(sourceFromMetadata({ url, title: domainFromUrl(url) }, rawText));
      }
    }

    return sources;
  }

  function sourcesFromSections(sections = []) {
    const seen = new Set();
    const sources = [];

    sections
      .filter((section) => section.kind === "result")
      .flatMap((section) => sourcesFromResultContent(section.content))
      .forEach((source) => {
        const key = source.key || source.url || `${source.domain}:${source.title}`;
        if (seen.has(key)) return;
        seen.add(key);
        sources.push(source);
      });

    return sources.slice(0, 8);
  }

  function sourceLabelFromResult(text) {
    const source = sourcesFromResultContent(text)[0];
    if (!source) return "Retrieved document";
    if (source.title && source.domain && source.title !== source.domain) {
      return `${source.title} · ${source.domain}`;
    }
    return source.title || source.domain || "Retrieved document";
  }

  window.SourceUtils = {
    compactText,
    clipText,
    metadataValue,
    safeUrl,
    domainFromUrl,
    displaySourceName,
    sourceInitial,
    sourceLogoUrl,
    cleanResultText,
    cleanPreviewText,
    sourcesFromResultContent,
    sourcesFromSections,
    sourceLabelFromResult,
  };
})();