-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
855 lines (736 loc) · 25.6 KB
/
background.js
File metadata and controls
855 lines (736 loc) · 25.6 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
"use strict";
const CODESYNC_GITHUB_CLIENT_ID = "Ov23likMwfQLsGH9E40I";
const GITHUB_OAUTH_SCOPE = "repo";
const GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code";
const GITHUB_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
const AUTH_ALARM_NAME = "codesync-github-auth-poll";
const DEFAULT_SETTINGS = {
githubToken: "",
repository: "",
branch: "",
authorName: "CodeSync",
authorEmail: "codesync@users.noreply.github.com",
enableDailyStreak: false,
organizeByDifficulty: false,
organizeByLanguage: false,
folderConvention: "",
baseFolder: "CodeSync",
commitTemplate: "Add {platform} solution: {title}"
};
const GITHUB_RATE_LIMIT_RETRY_MS = 60 * 1000;
const GITHUB_MAX_RETRIES = 2;
const LANGUAGE_EXTENSIONS = {
"c": "c",
"c++": "cpp",
"cpp": "cpp",
"c#": "cs",
"csharp": "cs",
"go": "go",
"golang": "go",
"java": "java",
"javascript": "js",
"js": "js",
"typescript": "ts",
"kotlin": "kt",
"php": "php",
"python": "py",
"python 2": "py",
"python 3": "py",
"ruby": "rb",
"rust": "rs",
"scala": "scala",
"swift": "swift",
"mysql": "sql",
"postgresql": "sql",
"sql": "sql",
"racket": "rkt",
"erlang": "erl",
"elixir": "ex",
"dart": "dart",
"bash": "sh",
"shell": "sh",
"plain text": "txt",
"text": "txt"
};
const NOTIFICATION_ICON =
"data:image/svg+xml;charset=UTF-8," +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><rect width="128" height="128" rx="24" fill="#111827"/><path fill="#38bdf8" d="M33 43 12 64l21 21 8-8-13-13 13-13zM95 43l-8 8 13 13-13 13 8 8 21-21z"/><path fill="#f8fafc" d="m74 26-31 78h12l31-78z"/></svg>'
);
chrome.runtime.onInstalled.addListener(async () => {
const existing = await getStorage(DEFAULT_SETTINGS);
await setStorage({ ...DEFAULT_SETTINGS, ...removeUndefined(existing) });
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === AUTH_ALARM_NAME) {
pollGitHubAuth().catch((error) => {
console.warn("CodeSync GitHub auth polling failed:", error.message);
notify("CodeSync GitHub login failed", error.message || "Login could not be completed.");
});
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "CODESYNC_AUTH_START") {
startGitHubAuth()
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => sendResponse({ ok: false, error: error.message || String(error) }));
return true;
}
if (!message || message.type !== "CODESYNC_SUBMISSION") {
return false;
}
handleSubmission(message.payload, sender)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => {
console.error("CodeSync submission failed:", error);
notify("CodeSync sync failed", error.message || "Unable to push submission to GitHub.");
sendResponse({ ok: false, error: error.message || String(error) });
});
return true;
});
async function startGitHubAuth() {
const clientId = getGitHubClientId();
const deviceData = await requestDeviceCode(clientId);
const intervalSeconds = Number(deviceData.interval || 5);
const authState = {
clientId,
deviceCode: deviceData.device_code,
userCode: deviceData.user_code,
verificationUrl: buildVerificationUrl(deviceData),
intervalSeconds,
expiresAt: Date.now() + Number(deviceData.expires_in || 900) * 1000
};
await setLocalStorage({ codesyncAuthState: authState });
scheduleAuthPoll(intervalSeconds);
const authPageUrl = chrome.runtime.getURL("auth.html");
chrome.tabs.create({ url: authPageUrl }, () => {
const error = chrome.runtime.lastError;
if (error) {
console.warn("CodeSync could not open GitHub login helper tab:", error.message);
}
});
return {
userCode: authState.userCode,
verificationUrl: authState.verificationUrl
};
}
async function requestDeviceCode(clientId) {
const response = await fetch(GITHUB_DEVICE_CODE_URL, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: clientId,
scope: GITHUB_OAUTH_SCOPE
})
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.error) {
throw new Error(data.error_description || data.message || "Could not start GitHub login.");
}
return data;
}
async function pollGitHubAuth() {
const { codesyncAuthState: authState } = await getLocalStorage({ codesyncAuthState: null });
if (!authState) {
return;
}
if (Date.now() >= authState.expiresAt) {
await clearAuthState();
notify("CodeSync GitHub login expired", "Start GitHub login again from the CodeSync popup.");
return;
}
const response = await fetch(GITHUB_ACCESS_TOKEN_URL, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: authState.clientId,
device_code: authState.deviceCode,
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
})
});
const data = await response.json().catch(() => ({}));
if (data.access_token) {
const user = await fetchGitHubUser(data.access_token);
await setStorage({
githubToken: data.access_token,
githubUser: user.login || user.name || "GitHub user"
});
await clearAuthState();
notify("CodeSync GitHub connected", `Connected as ${user.login || user.name || "GitHub user"}.`);
return;
}
if (data.error === "authorization_pending") {
scheduleAuthPoll(authState.intervalSeconds);
return;
}
if (data.error === "slow_down") {
authState.intervalSeconds = Number(authState.intervalSeconds || 5) + 5;
await setLocalStorage({ codesyncAuthState: authState });
scheduleAuthPoll(authState.intervalSeconds);
return;
}
await clearAuthState();
throw new Error(data.error_description || data.message || "GitHub login was not completed.");
}
async function fetchGitHubUser(token) {
const response = await githubFetch("https://api.github.com/user", {
headers: githubHeaders(token)
});
if (!response.ok) {
throw new Error(await githubErrorMessage(response, "Could not validate GitHub login"));
}
return response.json();
}
function scheduleAuthPoll(intervalSeconds) {
chrome.alarms.create(AUTH_ALARM_NAME, {
when: Date.now() + Math.max(Number(intervalSeconds || 5), 1) * 1000
});
}
async function clearAuthState() {
await removeLocalStorage(["codesyncAuthState"]);
chrome.alarms.clear(AUTH_ALARM_NAME);
}
function buildVerificationUrl(deviceData) {
if (deviceData.verification_uri_complete) {
return deviceData.verification_uri_complete;
}
const url = new URL(deviceData.verification_uri);
url.searchParams.set("user_code", deviceData.user_code);
return url.toString();
}
function getGitHubClientId() {
const clientId = String(CODESYNC_GITHUB_CLIENT_ID || "").trim();
if (!clientId || clientId === "YOUR_GITHUB_OAUTH_CLIENT_ID") {
throw new Error("CodeSync GitHub login is not configured. Set CODESYNC_GITHUB_CLIENT_ID in background.js.");
}
return clientId;
}
async function handleSubmission(rawSubmission, sender) {
const settings = await getSettings();
validateSettings(settings);
// Normalize content-script data before deriving paths or writing to GitHub.
const submission = normalizeSubmission(rawSubmission, sender);
const basePaths = buildSubmissionBasePaths(submission, settings);
const extension = extensionForLanguage(submission.language);
const solutionFileName = `solution.${extension}`;
const solutionHeader = getCommentHeader(submission, extension);
const readmeContent = buildReadme(submission);
const metadataContent = `${JSON.stringify(buildMetadata(submission), null, 2)}\n`;
const solutionContent = `${solutionHeader}${submission.sourceCode.trim()}\n`;
const commitMessage = renderCommitMessage(settings.commitTemplate, submission);
const writeContext = {
token: settings.githubToken,
repository: settings.repository,
branch: cleanText(settings.branch),
author: buildCommitAuthor(settings),
message: commitMessage
};
// Sync to all computed base paths
for (const basePath of basePaths) {
await putGitHubFile({
...writeContext,
path: joinPath(basePath, solutionFileName),
content: solutionContent
});
await putGitHubFile({
...writeContext,
path: joinPath(basePath, "README.md"),
content: readmeContent
});
await putGitHubFile({
...writeContext,
path: joinPath(basePath, "metadata.json"),
content: metadataContent
});
}
if (settings.enableDailyStreak) {
await putGitHubFile({
...writeContext,
path: buildDailyStreakPath(submission, settings),
content: buildDailyStreakContent(submission),
message: `Update CodeSync streak: ${new Date(submission.detectedAt).toISOString().slice(0, 10)}`
});
}
notify("CodeSync synced solution", `${submission.platform}: ${submission.title}`);
return {
solutionPath: joinPath(basePaths[0], solutionFileName),
readmePath: joinPath(basePaths[0], "README.md"),
metadataPath: joinPath(basePaths[0], "metadata.json")
};
}
function normalizeSubmission(rawSubmission, sender) {
const pageUrl = rawSubmission.problemUrl || sender?.tab?.url || "";
const title = cleanText(rawSubmission.title) || "Untitled Problem";
const language = cleanText(rawSubmission.language) || "Text";
const platform = cleanText(rawSubmission.platform) || "Unknown";
const sourceCode = String(rawSubmission.sourceCode || "").trim();
const topics = normalizeTopics(rawSubmission.topics);
const detectedAt = rawSubmission.detectedAt || new Date().toISOString();
if (!sourceCode) {
throw new Error("Accepted submission was detected, but source code could not be extracted.");
}
return {
id: rawSubmission.id || hashString(`${platform}|${title}|${language}|${sourceCode}`),
platform,
title,
problemUrl: pageUrl,
language,
topics,
runtime: cleanText(rawSubmission.runtime) || "N/A",
memory: cleanText(rawSubmission.memory) || "N/A",
difficulty: normalizeDifficulty(rawSubmission.difficulty),
sourceCode,
description: cleanText(rawSubmission.description),
detectedAt
};
}
function buildSubmissionBasePaths(submission, settings) {
const baseFolder = settings.baseFolder || DEFAULT_SETTINGS.baseFolder;
const platform = sanitizePathPart(submission.platform);
const difficulty = sanitizePathPart(submission.difficulty).toLowerCase(); // e.g. easy, medium, hard, unknown
const problemTitle = sanitizePathPart(submission.title);
if (cleanText(settings.folderConvention)) {
const values = {
baseFolder: baseFolder,
platform: submission.platform,
difficulty: submission.difficulty,
language: displayLanguage(submission.language),
problemTitle: submission.title,
title: submission.title,
primaryTag: primaryTopic(submission.topics)
};
return [renderFolderConvention(settings.folderConvention, values)];
}
const paths = [];
const topics = normalizeTopics(submission.topics);
const topicFolders = topics.map((t) => normalizeTopicFolderName(t));
// Sync to topic folders (up to 3 topics to avoid rate limits)
const syncTopics = topicFolders.slice(0, 3);
syncTopics.forEach((topicFolder) => {
paths.push(joinPath(
...sanitizePath(baseFolder),
platform,
difficulty,
topicFolder,
problemTitle
));
});
// Sync to difficulty-specific "all" folder
paths.push(joinPath(
...sanitizePath(baseFolder),
platform,
difficulty,
"all",
problemTitle
));
// Sync to platform-wide "all" folder
paths.push(joinPath(
...sanitizePath(baseFolder),
platform,
"all",
problemTitle
));
return [...new Set(paths)];
}
function normalizeTopicFolderName(topic) {
const name = cleanText(topic).toLowerCase();
if (name.includes("two pointer")) return "two-pointer";
if (name.includes("binary search")) return "binary-search";
if (name.includes("dynamic programming") || name === "dp") return "dynamic-programming";
if (name.includes("hash table") || name.includes("hash map") || name.includes("hash")) return "hash-table";
if (name.includes("union find") || name.includes("disjoint set")) return "union-find";
if (name.includes("sliding window")) return "sliding-window";
if (name.includes("bit manipulation")) return "bit-manipulation";
if (name.includes("segment tree")) return "segment-tree";
if (name.includes("binary indexed tree") || name.includes("fenwick")) return "binary-indexed-tree";
if (name.includes("topological")) return "topological-sort";
if (name.includes("shortest path")) return "shortest-path";
if (name.includes("number theory")) return "number-theory";
if (name.includes("priority queue") || name.includes("heap")) return "priority-queue";
if (name.includes("divide and conquer")) return "divide-and-conquer";
if (name.includes("backtracking")) return "backtracking";
if (name.includes("recursion")) return "recursion";
let slug = name.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
if (slug.endsWith("s") && slug.length > 3) {
slug = slug.slice(0, -1);
}
return slug || "uncategorized";
}
function renderFolderConvention(convention, values) {
const rendered = String(convention).replace(/\{(\w+)\}/g, (match, key) => {
return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : match;
});
return joinPath(...rendered.split("/").map((part) => sanitizePathPart(part)));
}
function getCommentHeader(submission, extension) {
const lines = [
`Platform: ${submission.platform}`,
`Problem: ${submission.title}`,
`URL: ${submission.problemUrl || "N/A"}`,
`Language: ${submission.language}`,
`Difficulty: ${submission.difficulty}`,
`Topics: ${submission.topics.join(", ")}`,
`Runtime: ${submission.runtime}`,
`Memory: ${submission.memory}`,
`Synced: ${submission.detectedAt}`
];
if (["py", "rb", "sh", "r", "pl"].includes(extension)) {
return lines.map((line) => `# ${line}`).join("\n") + "\n\n";
}
if (["sql"].includes(extension)) {
return lines.map((line) => `-- ${line}`).join("\n") + "\n\n";
}
return `/*\n${lines.map((line) => ` * ${line}`).join("\n")}\n */\n\n`;
}
function buildReadme(submission) {
const description = submission.description || "Problem description was not available on the page at sync time.";
return [
`# ${submission.title}`,
"",
`- Platform: ${submission.platform}`,
`- Language: ${submission.language}`,
`- Difficulty: ${submission.difficulty}`,
`- Topics: ${submission.topics.join(", ")}`,
`- Runtime: ${submission.runtime}`,
`- Memory: ${submission.memory}`,
`- Problem URL: ${submission.problemUrl || "N/A"}`,
`- Synced: ${submission.detectedAt}`,
"",
"## Problem Description",
"",
description,
"",
"## Explanation",
"",
buildGeneratedExplanation(submission),
""
].join("\n");
}
function buildMetadata(submission) {
return {
submissionTimestamp: submission.detectedAt,
runtime: submission.runtime,
memoryUsage: submission.memory,
difficulty: submission.difficulty,
tags: submission.topics,
platform: submission.platform,
language: submission.language,
problemTitle: submission.title,
problemUrl: submission.problemUrl,
submissionId: submission.id
};
}
function buildGeneratedExplanation(submission) {
const tags = submission.topics.filter((topic) => topic !== "Uncategorized");
const tagText = tags.length ? ` The detected topics are ${tags.join(", ")}.` : "";
return `This solution was accepted on ${submission.platform} using ${submission.language}.${tagText} Review the synced source file for the implementation details.`;
}
async function putGitHubFile({ token, repository, branch, author, path, content, message }) {
const encodedPath = path.split("/").map(encodeURIComponent).join("/");
const url = `https://api.github.com/repos/${repository}/contents/${encodedPath}`;
const existing = await getGitHubFile(token, url, branch);
const body = {
message,
content: utf8ToBase64(content)
};
if (branch) {
body.branch = branch;
}
if (author) {
body.author = author;
body.committer = author;
}
if (existing?.sha) {
// GitHub requires the current blob SHA when updating an existing file.
body.sha = existing.sha;
}
const response = await githubFetch(url, {
method: "PUT",
headers: githubHeaders(token),
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(await githubErrorMessage(response, `Failed to write ${path}`));
}
return response.json();
}
async function getGitHubFile(token, url, branch) {
const branchUrl = branch ? `${url}?ref=${encodeURIComponent(branch)}` : url;
const response = await githubFetch(branchUrl, {
method: "GET",
headers: githubHeaders(token)
});
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(await githubErrorMessage(response, "Failed to inspect existing GitHub file"));
}
return response.json();
}
function githubHeaders(token) {
return {
"Accept": "application/vnd.github+json",
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json",
"X-GitHub-Api-Version": "2022-11-28"
};
}
async function githubFetch(url, options = {}, attempt = 0) {
let response;
try {
response = await fetch(url, options);
} catch (error) {
throw new Error("Network request to GitHub failed. Check your internet connection and try again.");
}
if (!isRateLimited(response) || attempt >= GITHUB_MAX_RETRIES) {
return response;
}
await delay(getRateLimitDelay(response));
return githubFetch(url, options, attempt + 1);
}
function isRateLimited(response) {
return response.status === 429 || response.status === 403 && (
response.headers.get("x-ratelimit-remaining") === "0" ||
/rate limit/i.test(response.headers.get("x-ratelimit-resource") || "")
);
}
function getRateLimitDelay(response) {
const retryAfter = Number(response.headers.get("retry-after"));
if (Number.isFinite(retryAfter) && retryAfter > 0) {
return retryAfter * 1000;
}
const resetSeconds = Number(response.headers.get("x-ratelimit-reset"));
if (Number.isFinite(resetSeconds) && resetSeconds > 0) {
return Math.max(resetSeconds * 1000 - Date.now(), 1000);
}
return GITHUB_RATE_LIMIT_RETRY_MS;
}
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function githubErrorMessage(response, fallback) {
if (response.status === 401) {
return `${fallback}: GitHub authentication expired or was revoked. Login with GitHub again.`;
}
if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
return `${fallback}: GitHub API rate limit exceeded. Try again after the reset time.`;
}
if (response.status === 404) {
return `${fallback}: Repository, branch, or file path was not found. Confirm the selected repository and branch.`;
}
try {
const data = await response.json();
return `${fallback}: ${response.status} ${data.message || response.statusText}`;
} catch (error) {
return `${fallback}: ${response.status} ${response.statusText}`;
}
}
function renderCommitMessage(template, submission) {
const values = {
platform: submission.platform,
title: submission.title,
language: submission.language,
date: new Date(submission.detectedAt).toISOString().slice(0, 10)
};
return String(template || DEFAULT_SETTINGS.commitTemplate).replace(/\{(\w+)\}/g, (match, key) => {
return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : match;
});
}
function buildCommitAuthor(settings) {
const name = cleanText(settings.authorName);
const email = cleanText(settings.authorEmail);
return name && email ? { name, email } : null;
}
function buildDailyStreakPath(submission, settings) {
const date = new Date(submission.detectedAt).toISOString().slice(0, 10);
return joinPath(settings.baseFolder, "_streak", `${date}.md`);
}
function buildDailyStreakContent(submission) {
const date = new Date(submission.detectedAt).toISOString().slice(0, 10);
return [
`# CodeSync Streak - ${date}`,
"",
`- ${submission.platform}: ${submission.title}`,
`- Language: ${submission.language}`,
`- Difficulty: ${submission.difficulty}`,
`- URL: ${submission.problemUrl || "N/A"}`,
""
].join("\n");
}
function validateSettings(settings) {
if (!settings.githubToken) {
throw new Error("GitHub is not connected. Open the CodeSync popup and choose Login with GitHub.");
}
if (!/^[\w.-]+\/[\w.-]+$/.test(settings.repository || "")) {
const message = settings.repository ? "Repository must use owner/repository format." : "Missing repository. Choose or create a GitHub repository in the CodeSync popup.";
throw new Error(message);
}
}
async function getSettings() {
const settings = await getStorage(DEFAULT_SETTINGS);
return { ...DEFAULT_SETTINGS, ...removeUndefined(settings) };
}
function getStorage(defaults) {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(defaults, (result) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(result);
});
});
}
function setStorage(values) {
return new Promise((resolve, reject) => {
chrome.storage.sync.set(values, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve();
});
});
}
function getLocalStorage(defaults) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(defaults, (result) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(result);
});
});
}
function setLocalStorage(values) {
return new Promise((resolve, reject) => {
chrome.storage.local.set(values, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve();
});
});
}
function removeLocalStorage(keys) {
return new Promise((resolve, reject) => {
chrome.storage.local.remove(keys, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve();
});
});
}
function notify(title, message) {
chrome.notifications.create({
type: "basic",
iconUrl: NOTIFICATION_ICON,
title,
message
}, () => {
const error = chrome.runtime.lastError;
if (error) {
console.warn("CodeSync notification failed:", error.message);
}
});
}
function extensionForLanguage(language) {
const key = String(language || "").trim().toLowerCase();
return LANGUAGE_EXTENSIONS[key] || LANGUAGE_EXTENSIONS[key.replace(/\s+/g, " ")] || "txt";
}
function displayLanguage(language) {
const value = cleanText(language);
return value || "Unknown Language";
}
function normalizeTopics(topics) {
const normalized = []
.concat(topics || [])
.map((topic) => cleanText(topic))
.filter(Boolean)
.filter((topic, index, values) => values.findIndex((value) => value.toLowerCase() === topic.toLowerCase()) === index)
.slice(0, 8);
return normalized.length > 0 ? normalized : ["Uncategorized"];
}
function primaryTopic(topics) {
return normalizeTopics(topics)[0];
}
function normalizeDifficulty(value) {
const difficulty = cleanText(value).toLowerCase();
if (!difficulty) return "Unknown";
const rating = parseInt(difficulty.replace(/[^\d]/g, ""), 10);
if (!isNaN(rating)) {
if (rating < 1200) return "Easy";
if (rating < 1900) return "Medium";
return "Hard";
}
if (difficulty.includes("easy") || difficulty.includes("simple") || difficulty.includes("basic") || difficulty.includes("school")) return "Easy";
if (difficulty.includes("medium") || difficulty.includes("intermediate") || difficulty.includes("moderate")) return "Medium";
if (difficulty.includes("hard") || difficulty.includes("difficult") || difficulty.includes("hardcore") || difficulty.includes("challenge")) return "Hard";
return "Unknown";
}
function sanitizePathPart(value) {
const sanitized = String(value || "untitled")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[<>:"\\|?*\x00-\x1F]/g, "")
.replace(/[^\w .-]/g, "-")
.replace(/\s+/g, " ")
.trim()
.replace(/[. ]+$/g, "")
.replace(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i, "$1-file")
.slice(0, 90);
return sanitized || "untitled";
}
function sanitizePath(value) {
return String(value || "")
.replace(/\\/g, "/")
.split("/")
.map((part) => sanitizePathPart(part))
.filter(Boolean);
}
function joinPath(...parts) {
return parts
.filter(Boolean)
.join("/")
.replace(/\\/g, "/")
.replace(/\/+/g, "/")
.replace(/^\/|\/$/g, "");
}
function cleanText(value) {
return String(value || "").replace(/\s+/g, " ").trim();
}
function utf8ToBase64(value) {
// btoa only accepts binary strings, so encode UTF-8 text explicitly first.
const bytes = new TextEncoder().encode(value);
let binary = "";
bytes.forEach((byte) => {
binary += String.fromCharCode(byte);
});
return btoa(binary);
}
function hashString(value) {
let hash = 0;
for (let index = 0; index < value.length; index += 1) {
hash = ((hash << 5) - hash + value.charCodeAt(index)) | 0;
}
return Math.abs(hash).toString(36);
}
function removeUndefined(object) {
return Object.fromEntries(Object.entries(object || {}).filter(([, value]) => value !== undefined));
}