-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
361 lines (311 loc) · 9.82 KB
/
Copy pathbackground.js
File metadata and controls
361 lines (311 loc) · 9.82 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// TrendScope Background Service Worker
// Orchestrates README fetching and prompt building
// Import prompt builder
importScripts('prompt-builder.js');
// Listen for messages from content script and popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'REPOS_SCRAPED') {
handleReposScraped(message.payload);
sendResponse({ success: true });
} else if (message.type === 'START_ENRICHMENT') {
startEnrichment().then(() => sendResponse({ success: true }));
return true; // Async response
} else if (message.type === 'BUILD_PROMPT') {
buildAndStorePrompt().then(() => sendResponse({ success: true }));
return true; // Async response
} else if (message.type === 'GET_STATUS') {
getStatus().then(status => sendResponse(status));
return true; // Async response
}
return false;
});
/**
* Handle scraped repos from content script
*/
async function handleReposScraped(payload) {
const { repos, period } = payload;
// Clear old prompt and stats when new repos are scraped
await chrome.storage.local.set({
repos: repos,
trendingPeriod: period,
lastRun: new Date().toISOString(),
state: 'scraped',
error: null,
prompt: null,
promptStats: null,
enrichmentProgress: null
});
}
/**
* Get settings with defaults
*/
async function getSettings() {
const data = await chrome.storage.local.get(['settings']);
return {
githubToken: '',
readmeMaxChars: 3000,
maxRepos: 25,
...data.settings
};
}
/**
* Start enrichment process - fetch READMEs and metadata for each repo
*/
async function startEnrichment() {
const data = await chrome.storage.local.get(['repos', 'trendingPeriod']);
const settings = await getSettings();
if (!data.repos || data.repos.length === 0) {
await chrome.storage.local.set({
state: 'error',
error: 'No repos to enrich. Scrape the trending page first.'
});
return;
}
// Limit repos to maxRepos setting
let repos = data.repos.slice(0, settings.maxRepos);
await chrome.storage.local.set({
state: 'enriching',
enrichmentProgress: { current: 0, total: repos.length, currentRepo: '' }
});
// Build headers for GitHub API
const headers = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'TrendScope-Chrome-Extension'
};
if (settings.githubToken) {
headers['Authorization'] = `token ${settings.githubToken}`;
}
// Enrich each repo sequentially with delay
for (let i = 0; i < repos.length; i++) {
const repo = repos[i];
// Update progress
await chrome.storage.local.set({
enrichmentProgress: {
current: i + 1,
total: repos.length,
currentRepo: repo.fullName
}
});
try {
// Fetch repo metadata
const metaResult = await fetchRepoMetadata(repo.owner, repo.name, headers);
if (metaResult.rateLimited) {
// Stop enrichment on rate limit
await chrome.storage.local.set({
repos: repos,
state: 'error',
error: `Rate limited by GitHub API. ${i} of ${repos.length} repos enriched. Wait an hour or add a GitHub token in settings.`
});
return;
}
if (metaResult.data) {
repo.forks = metaResult.data.forks_count;
repo.openIssues = metaResult.data.open_issues_count;
repo.topics = metaResult.data.topics || [];
repo.license = metaResult.data.license?.spdx_id || null;
repo.createdAt = metaResult.data.created_at;
}
// Fetch README
const readmeResult = await fetchReadme(repo.owner, repo.name, headers, settings.readmeMaxChars);
if (readmeResult.rateLimited) {
await chrome.storage.local.set({
repos: repos,
state: 'error',
error: `Rate limited by GitHub API. ${i} of ${repos.length} repos enriched. Wait an hour or add a GitHub token in settings.`
});
return;
}
repo.readme = readmeResult.content;
repo.readmeStatus = readmeResult.status;
repo.fetchedAt = new Date().toISOString();
} catch (err) {
// Log but continue - don't let one repo fail the whole process
console.error(`TrendScope: Error enriching ${repo.fullName}:`, err);
repo.readmeStatus = 'error';
repo.fetchedAt = new Date().toISOString();
}
// Update repos in storage after each one
await chrome.storage.local.set({ repos: repos });
// Delay between requests to respect rate limits (1 second)
if (i < repos.length - 1) {
await sleep(1000);
}
}
// All repos enriched - build prompt
await buildAndStorePrompt();
}
/**
* Fetch repo metadata from GitHub API
*/
async function fetchRepoMetadata(owner, name, headers) {
try {
const response = await fetch(
`https://api.github.com/repos/${owner}/${name}`,
{ headers }
);
if (response.status === 403) {
const remaining = response.headers.get('X-RateLimit-Remaining');
if (remaining === '0') {
return { rateLimited: true, data: null };
}
}
if (response.status === 404) {
return { rateLimited: false, data: null };
}
if (!response.ok) {
return { rateLimited: false, data: null };
}
const data = await response.json();
return { rateLimited: false, data };
} catch (err) {
console.error('TrendScope: Metadata fetch error:', err);
return { rateLimited: false, data: null };
}
}
/**
* Fetch README from GitHub API
*/
async function fetchReadme(owner, name, headers, maxChars) {
try {
const response = await fetch(
`https://api.github.com/repos/${owner}/${name}/readme`,
{ headers }
);
if (response.status === 403) {
const remaining = response.headers.get('X-RateLimit-Remaining');
if (remaining === '0') {
return { rateLimited: true, content: '', status: 'error' };
}
}
if (response.status === 404) {
return { rateLimited: false, content: '', status: 'unavailable' };
}
if (!response.ok) {
return { rateLimited: false, content: '', status: 'error' };
}
const data = await response.json();
// Decode base64 content
let content = '';
if (data.content && data.encoding === 'base64') {
try {
content = decodeBase64(data.content);
} catch (e) {
console.error('TrendScope: Base64 decode error:', e);
return { rateLimited: false, content: '', status: 'error' };
}
}
// Truncate if necessary
let status = 'ok';
if (content.length > maxChars) {
content = content.substring(0, maxChars) + `\n\n[README truncated at ${maxChars} characters]`;
status = 'truncated';
}
return { rateLimited: false, content, status };
} catch (err) {
console.error('TrendScope: README fetch error:', err);
return { rateLimited: false, content: '', status: 'error' };
}
}
/**
* Decode base64 string to UTF-8 text
* Handles multi-line base64 from GitHub API
*/
function decodeBase64(base64String) {
// Remove newlines that GitHub adds
const cleaned = base64String.replace(/\n/g, '');
// Decode base64 to binary string
const binaryString = atob(cleaned);
// Convert binary string to Uint8Array
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Decode UTF-8
const decoder = new TextDecoder('utf-8');
return decoder.decode(bytes);
}
/**
* Build prompt from enriched repos and store it
*/
async function buildAndStorePrompt() {
const data = await chrome.storage.local.get(['repos', 'trendingPeriod']);
const settings = await getSettings();
if (!data.repos || data.repos.length === 0) {
await chrome.storage.local.set({
state: 'error',
error: 'No repos available to build prompt.'
});
return;
}
// Use the prompt builder
const result = buildPrompt(data.repos, data.trendingPeriod || 'weekly');
// Check if prompt is too large and needs README truncation
let finalResult = result;
if (result.stats.estimatedTokens > 150000) {
// Reduce README size and rebuild
const reducedRepos = data.repos.map(repo => {
if (repo.readme && repo.readme.length > 2000) {
return {
...repo,
readme: repo.readme.substring(0, 2000) + '\n\n[README truncated at 2000 characters due to size limits]',
readmeStatus: 'truncated'
};
}
return repo;
});
finalResult = buildPrompt(reducedRepos, data.trendingPeriod || 'weekly');
// If still too large, reduce further
if (finalResult.stats.estimatedTokens > 150000) {
const furtherReducedRepos = reducedRepos.map(repo => {
if (repo.readme && repo.readme.length > 1500) {
return {
...repo,
readme: repo.readme.substring(0, 1500) + '\n\n[README truncated at 1500 characters due to size limits]',
readmeStatus: 'truncated'
};
}
return repo;
});
finalResult = buildPrompt(furtherReducedRepos, data.trendingPeriod || 'weekly');
}
}
await chrome.storage.local.set({
prompt: finalResult.prompt,
promptStats: finalResult.stats,
state: 'ready'
});
}
/**
* Get current status for popup
*/
async function getStatus() {
const data = await chrome.storage.local.get([
'state',
'repos',
'prompt',
'promptStats',
'enrichmentProgress',
'lastRun',
'error',
'trendingPeriod'
]);
return {
type: 'STATUS',
payload: {
state: data.state || 'idle',
repoCount: data.repos?.length || 0,
hasPrompt: !!data.prompt,
promptStats: data.promptStats || null,
progress: data.enrichmentProgress || null,
lastRun: data.lastRun || null,
error: data.error || null,
period: data.trendingPeriod || 'weekly'
}
};
}
/**
* Sleep helper
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}