@apmantza/greedysearch-pi 1.8.0 → 1.8.2

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.
@@ -1,230 +1,230 @@
1
- // src/search/fetch-source.mjs — HTTP and browser-based source content fetching
2
- //
3
- // Extracted from search.mjs. Uses fetchSourceHttp from src/fetcher.mjs
4
- // with browser fallback via CDP, plus GitHub content fetching.
5
-
6
- import { spawn } from "node:child_process";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
- import { fetchSourceHttp, shouldUseBrowser } from "../fetcher.mjs";
10
- import { fetchGitHubContent, parseGitHubUrl } from "../github.mjs";
11
- import { trimContentHeadTail } from "../utils/content.mjs";
12
- import { cdp } from "./chrome.mjs";
13
- import { openNewTab, closeTab, closeTabs } from "./chrome.mjs";
14
- import { SOURCE_FETCH_CONCURRENCY } from "./constants.mjs";
15
- import { trimText } from "./sources.mjs";
16
-
17
- export async function fetchSourceContent(url, maxChars = 8000) {
18
- const start = Date.now();
19
-
20
- // Check if it's a GitHub URL
21
- if (parseGitHubUrl(url)) {
22
- const parsed = parseGitHubUrl(url);
23
- if (
24
- parsed &&
25
- (parsed.type === "root" ||
26
- parsed.type === "tree" ||
27
- (parsed.type === "blob" && !parsed.path?.includes(".")))
28
- ) {
29
- const ghResult = await fetchGitHubContent(url);
30
- if (ghResult.ok) {
31
- const content = trimContentHeadTail(ghResult.content, maxChars);
32
- return {
33
- url,
34
- finalUrl: url,
35
- status: 200,
36
- contentType: "text/markdown",
37
- lastModified: "",
38
- title: ghResult.title,
39
- snippet: content.slice(0, 320),
40
- content,
41
- contentChars: content.length,
42
- source: "github-api",
43
- ...(ghResult.tree && { tree: ghResult.tree }),
44
- duration: Date.now() - start,
45
- };
46
- }
47
- process.stderr.write(
48
- `[greedysearch] GitHub API fetch failed, trying HTTP: ${ghResult.error}\n`,
49
- );
50
- }
51
- }
52
-
53
- // Try HTTP first
54
- const httpResult = await fetchSourceHttp(url, { timeoutMs: 15000 });
55
-
56
- if (httpResult.ok) {
57
- const content = trimContentHeadTail(httpResult.markdown, maxChars);
58
- return {
59
- url,
60
- finalUrl: httpResult.finalUrl,
61
- status: httpResult.status,
62
- contentType: "text/markdown",
63
- lastModified: httpResult.lastModified || "",
64
- publishedTime: httpResult.publishedTime || "",
65
- byline: httpResult.byline || "",
66
- siteName: httpResult.siteName || "",
67
- lang: httpResult.lang || "",
68
- title: httpResult.title,
69
- snippet: httpResult.excerpt,
70
- content,
71
- contentChars: content.length,
72
- source: "http",
73
- duration: Date.now() - start,
74
- };
75
- }
76
-
77
- // HTTP failed — fall back to browser
78
- process.stderr.write(
79
- `[greedysearch] HTTP failed for ${url.slice(0, 60)}, trying browser...\n`,
80
- );
81
- return await fetchSourceContentBrowser(url, maxChars);
82
- }
83
-
84
- async function fetchSourceContentBrowser(url, maxChars = 8000) {
85
- const start = Date.now();
86
- const tab = await openNewTab();
87
-
88
- try {
89
- await cdp(["nav", tab, url], 30000);
90
- await new Promise((r) => setTimeout(r, 1500));
91
-
92
- const content = await cdp([
93
- "eval",
94
- tab,
95
- `
96
- (function(){
97
- var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
98
- var text = (el || document.body).innerText;
99
- return JSON.stringify({
100
- title: document.title,
101
- content: text.replace(/\\s+/g, ' ').trim(),
102
- url: location.href
103
- });
104
- })()
105
- `,
106
- ]);
107
-
108
- const parsed = JSON.parse(content);
109
- const finalContent = trimContentHeadTail(parsed.content, maxChars);
110
-
111
- return {
112
- url,
113
- finalUrl: parsed.url || url,
114
- status: 200,
115
- contentType: "text/plain",
116
- lastModified: "",
117
- title: parsed.title,
118
- snippet: trimText(finalContent, 320),
119
- content: finalContent,
120
- contentChars: finalContent.length,
121
- source: "browser",
122
- duration: Date.now() - start,
123
- };
124
- } catch (error) {
125
- return {
126
- url,
127
- title: "",
128
- content: null,
129
- snippet: "",
130
- contentChars: 0,
131
- error: error.message,
132
- source: "browser",
133
- duration: Date.now() - start,
134
- };
135
- } finally {
136
- await closeTab(tab);
137
- }
138
- }
139
-
140
- export async function fetchMultipleSources(
141
- sources,
142
- maxSources = 5,
143
- maxChars = 8000,
144
- concurrency = SOURCE_FETCH_CONCURRENCY,
145
- ) {
146
- const toFetch = sources.slice(0, maxSources);
147
- if (toFetch.length === 0) return [];
148
-
149
- const workerCount = Math.min(
150
- toFetch.length,
151
- Math.max(1, parseInt(String(concurrency), 10) || SOURCE_FETCH_CONCURRENCY),
152
- );
153
-
154
- process.stderr.write(
155
- `[greedysearch] Fetching content from ${toFetch.length} sources via HTTP (concurrency ${workerCount})...\n`,
156
- );
157
-
158
- const fetched = new Array(toFetch.length);
159
- let nextIndex = 0;
160
- let completed = 0;
161
-
162
- async function worker() {
163
- while (true) {
164
- const index = nextIndex++;
165
- if (index >= toFetch.length) return;
166
-
167
- const s = toFetch[index];
168
- const url = s.canonicalUrl || s.url;
169
- process.stderr.write(
170
- `[greedysearch] [${index + 1}/${toFetch.length}] Fetching: ${url.slice(0, 60)}...\n`,
171
- );
172
-
173
- const result = await fetchSourceContent(url, maxChars);
174
- fetched[index] = {
175
- id: s.id,
176
- ...result,
177
- };
178
-
179
- if (result.content && result.content.length > 100) {
180
- process.stderr.write(
181
- `[greedysearch] ✓ ${result.source}: ${result.content.length} chars\n`,
182
- );
183
- } else if (result.error) {
184
- process.stderr.write(`[greedysearch] ✗ ${result.error.slice(0, 80)}\n`);
185
- }
186
-
187
- completed += 1;
188
- process.stderr.write(`PROGRESS:fetch:${completed}/${toFetch.length}\n`);
189
- }
190
- }
191
-
192
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
193
-
194
- // Log summary
195
- const successful = fetched.filter((f) => f.content && f.content.length > 100);
196
- const httpCount = fetched.filter((f) => f.source === "http").length;
197
- const browserCount = fetched.filter((f) => f.source === "browser").length;
198
-
199
- process.stderr.write(
200
- `[greedysearch] Fetched ${successful.length}/${fetched.length} sources ` +
201
- `(HTTP: ${httpCount}, Browser: ${browserCount})\n`,
202
- );
203
-
204
- return fetched;
205
- }
206
-
207
- export async function fetchTopSource(url) {
208
- const tab = await openNewTab();
209
- await cdp(["list"]); // refresh cache
210
- try {
211
- await cdp(["nav", tab, url], 30000);
212
- await new Promise((r) => setTimeout(r, 1500));
213
- const content = await cdp([
214
- "eval",
215
- tab,
216
- `
217
- (function(){
218
- var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
219
- var text = (el || document.body).innerText;
220
- return text.replace(/\\s+/g, ' ').trim();
221
- })()
222
- `,
223
- ]);
224
- return { url, content };
225
- } catch (e) {
226
- return { url, content: null, error: e.message };
227
- } finally {
228
- await closeTab(tab);
229
- }
1
+ // src/search/fetch-source.mjs — HTTP and browser-based source content fetching
2
+ //
3
+ // Extracted from search.mjs. Uses fetchSourceHttp from src/fetcher.mjs
4
+ // with browser fallback via CDP, plus GitHub content fetching.
5
+
6
+ import { spawn } from "node:child_process";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { fetchSourceHttp, shouldUseBrowser } from "../fetcher.mjs";
10
+ import { fetchGitHubContent, parseGitHubUrl } from "../github.mjs";
11
+ import { trimContentHeadTail } from "../utils/content.mjs";
12
+ import { cdp } from "./chrome.mjs";
13
+ import { openNewTab, closeTab, closeTabs } from "./chrome.mjs";
14
+ import { SOURCE_FETCH_CONCURRENCY } from "./constants.mjs";
15
+ import { trimText } from "./sources.mjs";
16
+
17
+ export async function fetchSourceContent(url, maxChars = 8000) {
18
+ const start = Date.now();
19
+
20
+ // Check if it's a GitHub URL
21
+ if (parseGitHubUrl(url)) {
22
+ const parsed = parseGitHubUrl(url);
23
+ if (
24
+ parsed &&
25
+ (parsed.type === "root" ||
26
+ parsed.type === "tree" ||
27
+ (parsed.type === "blob" && !parsed.path?.includes(".")))
28
+ ) {
29
+ const ghResult = await fetchGitHubContent(url);
30
+ if (ghResult.ok) {
31
+ const content = trimContentHeadTail(ghResult.content, maxChars);
32
+ return {
33
+ url,
34
+ finalUrl: url,
35
+ status: 200,
36
+ contentType: "text/markdown",
37
+ lastModified: "",
38
+ title: ghResult.title,
39
+ snippet: content.slice(0, 320),
40
+ content,
41
+ contentChars: content.length,
42
+ source: "github-api",
43
+ ...(ghResult.tree && { tree: ghResult.tree }),
44
+ duration: Date.now() - start,
45
+ };
46
+ }
47
+ process.stderr.write(
48
+ `[greedysearch] GitHub API fetch failed, trying HTTP: ${ghResult.error}\n`,
49
+ );
50
+ }
51
+ }
52
+
53
+ // Try HTTP first
54
+ const httpResult = await fetchSourceHttp(url, { timeoutMs: 15000 });
55
+
56
+ if (httpResult.ok) {
57
+ const content = trimContentHeadTail(httpResult.markdown, maxChars);
58
+ return {
59
+ url,
60
+ finalUrl: httpResult.finalUrl,
61
+ status: httpResult.status,
62
+ contentType: "text/markdown",
63
+ lastModified: httpResult.lastModified || "",
64
+ publishedTime: httpResult.publishedTime || "",
65
+ byline: httpResult.byline || "",
66
+ siteName: httpResult.siteName || "",
67
+ lang: httpResult.lang || "",
68
+ title: httpResult.title,
69
+ snippet: httpResult.excerpt,
70
+ content,
71
+ contentChars: content.length,
72
+ source: "http",
73
+ duration: Date.now() - start,
74
+ };
75
+ }
76
+
77
+ // HTTP failed — fall back to browser
78
+ process.stderr.write(
79
+ `[greedysearch] HTTP failed for ${url.slice(0, 60)}, trying browser...\n`,
80
+ );
81
+ return await fetchSourceContentBrowser(url, maxChars);
82
+ }
83
+
84
+ async function fetchSourceContentBrowser(url, maxChars = 8000) {
85
+ const start = Date.now();
86
+ const tab = await openNewTab();
87
+
88
+ try {
89
+ await cdp(["nav", tab, url], 30000);
90
+ await new Promise((r) => setTimeout(r, 1500));
91
+
92
+ const content = await cdp([
93
+ "eval",
94
+ tab,
95
+ `
96
+ (function(){
97
+ var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
98
+ var text = (el || document.body).innerText;
99
+ return JSON.stringify({
100
+ title: document.title,
101
+ content: text.replace(/\\s+/g, ' ').trim(),
102
+ url: location.href
103
+ });
104
+ })()
105
+ `,
106
+ ]);
107
+
108
+ const parsed = JSON.parse(content);
109
+ const finalContent = trimContentHeadTail(parsed.content, maxChars);
110
+
111
+ return {
112
+ url,
113
+ finalUrl: parsed.url || url,
114
+ status: 200,
115
+ contentType: "text/plain",
116
+ lastModified: "",
117
+ title: parsed.title,
118
+ snippet: trimText(finalContent, 320),
119
+ content: finalContent,
120
+ contentChars: finalContent.length,
121
+ source: "browser",
122
+ duration: Date.now() - start,
123
+ };
124
+ } catch (error) {
125
+ return {
126
+ url,
127
+ title: "",
128
+ content: null,
129
+ snippet: "",
130
+ contentChars: 0,
131
+ error: error.message,
132
+ source: "browser",
133
+ duration: Date.now() - start,
134
+ };
135
+ } finally {
136
+ await closeTab(tab);
137
+ }
138
+ }
139
+
140
+ export async function fetchMultipleSources(
141
+ sources,
142
+ maxSources = 5,
143
+ maxChars = 8000,
144
+ concurrency = SOURCE_FETCH_CONCURRENCY,
145
+ ) {
146
+ const toFetch = sources.slice(0, maxSources);
147
+ if (toFetch.length === 0) return [];
148
+
149
+ const workerCount = Math.min(
150
+ toFetch.length,
151
+ Math.max(1, parseInt(String(concurrency), 10) || SOURCE_FETCH_CONCURRENCY),
152
+ );
153
+
154
+ process.stderr.write(
155
+ `[greedysearch] Fetching content from ${toFetch.length} sources via HTTP (concurrency ${workerCount})...\n`,
156
+ );
157
+
158
+ const fetched = new Array(toFetch.length);
159
+ let nextIndex = 0;
160
+ let completed = 0;
161
+
162
+ async function worker() {
163
+ while (true) {
164
+ const index = nextIndex++;
165
+ if (index >= toFetch.length) return;
166
+
167
+ const s = toFetch[index];
168
+ const url = s.canonicalUrl || s.url;
169
+ process.stderr.write(
170
+ `[greedysearch] [${index + 1}/${toFetch.length}] Fetching: ${url.slice(0, 60)}...\n`,
171
+ );
172
+
173
+ const result = await fetchSourceContent(url, maxChars);
174
+ fetched[index] = {
175
+ id: s.id,
176
+ ...result,
177
+ };
178
+
179
+ if (result.content && result.content.length > 100) {
180
+ process.stderr.write(
181
+ `[greedysearch] ✓ ${result.source}: ${result.content.length} chars\n`,
182
+ );
183
+ } else if (result.error) {
184
+ process.stderr.write(`[greedysearch] ✗ ${result.error.slice(0, 80)}\n`);
185
+ }
186
+
187
+ completed += 1;
188
+ process.stderr.write(`PROGRESS:fetch:${completed}/${toFetch.length}\n`);
189
+ }
190
+ }
191
+
192
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
193
+
194
+ // Log summary
195
+ const successful = fetched.filter((f) => f.content && f.content.length > 100);
196
+ const httpCount = fetched.filter((f) => f.source === "http").length;
197
+ const browserCount = fetched.filter((f) => f.source === "browser").length;
198
+
199
+ process.stderr.write(
200
+ `[greedysearch] Fetched ${successful.length}/${fetched.length} sources ` +
201
+ `(HTTP: ${httpCount}, Browser: ${browserCount})\n`,
202
+ );
203
+
204
+ return fetched;
205
+ }
206
+
207
+ export async function fetchTopSource(url) {
208
+ const tab = await openNewTab();
209
+ await cdp(["list"]); // refresh cache
210
+ try {
211
+ await cdp(["nav", tab, url], 30000);
212
+ await new Promise((r) => setTimeout(r, 1500));
213
+ const content = await cdp([
214
+ "eval",
215
+ tab,
216
+ `
217
+ (function(){
218
+ var el = document.querySelector('article, [role="main"], main, .post-content, .article-body, #content, .content');
219
+ var text = (el || document.body).innerText;
220
+ return text.replace(/\\s+/g, ' ').trim();
221
+ })()
222
+ `,
223
+ ]);
224
+ return { url, content };
225
+ } catch (e) {
226
+ return { url, content: null, error: e.message };
227
+ } finally {
228
+ await closeTab(tab);
229
+ }
230
230
  }
@@ -1,59 +1,59 @@
1
- // src/search/output.mjs — Output serialization for search results
2
- //
3
- // Extracted from search.mjs.
4
-
5
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
- import { join } from "node:path";
7
- import { tmpdir } from "node:os";
8
-
9
- const __dir = import.meta.dirname || new URL(".", import.meta.url).pathname.replace(/^\/([A-Z]:)/, "$1");
10
-
11
- export function slugify(query) {
12
- return query
13
- .toLowerCase()
14
- .replace(/[^a-z0-9]+/g, "-")
15
- .replace(/^-|-$/g, "")
16
- .slice(0, 60);
17
- }
18
-
19
- export function resultsDir() {
20
- const dir = join(__dir, "..", "..", "results");
21
- mkdirSync(dir, { recursive: true });
22
- return dir;
23
- }
24
-
25
- export function writeOutput(
26
- data,
27
- outFile,
28
- { inline = false, synthesize = false, query = "" } = {},
29
- ) {
30
- const json = `${JSON.stringify(data, null, 2)}\n`;
31
-
32
- if (outFile) {
33
- writeFileSync(outFile, json, "utf8");
34
- process.stderr.write(`Results written to ${outFile}\n`);
35
- return;
36
- }
37
-
38
- if (inline) {
39
- process.stdout.write(json);
40
- return;
41
- }
42
-
43
- const ts = new Date()
44
- .toISOString()
45
- .replace("T", "_")
46
- .replace(/[:.]/g, "-")
47
- .slice(0, 19);
48
- const slug = slugify(query);
49
- const base = join(resultsDir(), `${ts}_${slug}`);
50
-
51
- writeFileSync(`${base}.json`, json, "utf8");
52
-
53
- if (synthesize && data._synthesis?.answer) {
54
- writeFileSync(`${base}-synthesis.md`, data._synthesis.answer, "utf8");
55
- process.stdout.write(`${base}-synthesis.md\n`);
56
- } else {
57
- process.stdout.write(`${base}.json\n`);
58
- }
1
+ // src/search/output.mjs — Output serialization for search results
2
+ //
3
+ // Extracted from search.mjs.
4
+
5
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpdir } from "node:os";
8
+
9
+ const __dir = import.meta.dirname || new URL(".", import.meta.url).pathname.replace(/^\/([A-Z]:)/, "$1");
10
+
11
+ export function slugify(query) {
12
+ return query
13
+ .toLowerCase()
14
+ .replace(/[^a-z0-9]+/g, "-")
15
+ .replace(/^-|-$/g, "")
16
+ .slice(0, 60);
17
+ }
18
+
19
+ export function resultsDir() {
20
+ const dir = join(__dir, "..", "..", "results");
21
+ mkdirSync(dir, { recursive: true });
22
+ return dir;
23
+ }
24
+
25
+ export function writeOutput(
26
+ data,
27
+ outFile,
28
+ { inline = false, synthesize = false, query = "" } = {},
29
+ ) {
30
+ const json = `${JSON.stringify(data, null, 2)}\n`;
31
+
32
+ if (outFile) {
33
+ writeFileSync(outFile, json, "utf8");
34
+ process.stderr.write(`Results written to ${outFile}\n`);
35
+ return;
36
+ }
37
+
38
+ if (inline) {
39
+ process.stdout.write(json);
40
+ return;
41
+ }
42
+
43
+ const ts = new Date()
44
+ .toISOString()
45
+ .replace("T", "_")
46
+ .replace(/[:.]/g, "-")
47
+ .slice(0, 19);
48
+ const slug = slugify(query);
49
+ const base = join(resultsDir(), `${ts}_${slug}`);
50
+
51
+ writeFileSync(`${base}.json`, json, "utf8");
52
+
53
+ if (synthesize && data._synthesis?.answer) {
54
+ writeFileSync(`${base}-synthesis.md`, data._synthesis.answer, "utf8");
55
+ process.stdout.write(`${base}-synthesis.md\n`);
56
+ } else {
57
+ process.stdout.write(`${base}.json\n`);
58
+ }
59
59
  }