-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMyGitHubStats.js
More file actions
2120 lines (1788 loc) · 65.4 KB
/
Copy pathMyGitHubStats.js
File metadata and controls
2120 lines (1788 loc) · 65.4 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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// icon-color: deep-blue; icon-glyph: chalkboard-teacher;
const username = "rushhiii"; // replace with your github username
const token = Keychain.get("github_token_here"); // replace this with you token
// const size = config.widgetFamily || "large";
// const size = config.widgetFamily || "medium";
const size = config.widgetFamily || "small";
const themePresets = {
auto: Device.isUsingDarkAppearance()
? { colors: ["#000244", "#000233", "#000000"], locations: [0.0, 0.5, 1.0], head: "#ffffff", text: "#909692", acc: "#3094ff" }
: { colors: ["#e6f2f1", "#bff2c2"], locations: [0, 1], head: "#000000", text: "#5a615c", acc: "#006edb" },
// auto: Device.isUsingDarkAppearance()
// ? {
// colors: [
// "#E1F5FE", // Very light sky blue
// "#B3E5FC", // Soft cyan
// "#81D4FA", // True sky blue
// "#4FC3F7", // Deeper cyan
// "#29B6F6" // iOS-like vibrant blue
// ],
// locations: [0.0, 0.25, 0.5, 0.75, 1.0],
// head: "#000000", // dark title/icon
// text: "#32555f", // bluish-gray text
// acc: "#007AFF" // standard iOS accent blue
// // colors: ["#000244", "#000233", "#000000"],
// // locations: [0, 0.5, 1],
// // head: "#ffffff", text: "#909692", acc: "#ffffff"
// }
// : {
// colors: ["#000244", "#000233", "#000000"],
// locations: [0, 0.5, 1],
// head: "#ffffff", text: "#909692", acc: "#ffffff"
// // colors: [
// // "#E1F5FE", // Very light sky blue
// // "#B3E5FC", // Soft cyan
// // "#81D4FA", // True sky blue
// // "#4FC3F7", // Deeper cyan
// // "#29B6F6" // iOS-like vibrant blue
// // ],
// // locations: [0.0, 0.25, 0.5, 0.75, 1.0],
// // head: "#000000", // dark title/icon
// // text: "#32555f", // bluish-gray text
// // acc: "#007AFF" // standard iOS accent blue
// },
blue: {
// colors: ["#0d1117", "#1E2838", "#1f6feb"],
// locations: [1.0, 0.5, 0.0],
// head: "#ffffff", text: "#c0c0c0", acc: "#58a6ff"
colors: ["#0A0C1C", "#121C3C", "#263B73"],
locations: [0, 0.5, 1],
head: "#ffffff",
text: "#c0c0c0",
acc: "#8ac7ff"
},
gray: {
colors: [
"#202631", // Cloudy navy gray
"#2D3440", // Muted slate
"#3C4454", // Blue-gray storm cloud
"#525D6F", // Electric gray blue
"#7A8699" // Lighter edge storm sky
],
locations: [0.0, 0.25, 0.5, 0.75, 1.0],
head: "#EAEAEA", // soft lightning white
text: "#C7CCD5", // light gray
acc: "#8AB4F8" // stormy blue accent
},
night: {
colors: [
"#000000", // Pure black
"#04050A", // Subtle hint of navy
"#0A0F1A", // Faint cool midnight
"#111827" // Deep twilight blue-gray
],
locations: [0.0, 0.4, 0.75, 1.0],
head: "#ffffff", // bright title/icon
text: "#B0B8C0", // soft gray text
acc: "#42A5F5"
},
day: {
colors: [
"#E1F5FE", // Very light sky blue
"#B3E5FC", // Soft cyan
"#81D4FA", // True sky blue
"#4FC3F7", // Deeper cyan
"#29B6F6" // iOS-like vibrant blue
],
locations: [0.0, 0.25, 0.5, 0.75, 1.0],
head: "#000000", // dark title/icon
text: "#32555f", // bluish-gray text
acc: "#007AFF" // standard iOS accent blue
},
gitgreen: {
colors: ["#defefa", "#bfffd1"],
locations: [0, 1],
head: "#000000", text: "#5a615c", acc: "#000000"
},
green: {
colors: ["#ebedf0", "#9be9a8", "#40c463", "#30a14e", "#216e39"],
locations: [0.0, 0.25, 0.5, 0.75, 1.0],
head: "#0a0e27", // 0a0e27
text: "#000000",
acc: "#216e39"
},
indigo: {
colors: ["#000244", "#000233", "#000000"],
locations: [0, 0.5, 1],
head: "#ffffff", text: "#909692", acc: "#ffffff"
},
dark: {
colors: ["#101411", "#101411"],
locations: [0, 1],
head: "#ffffff", text: "#909692", acc: "#3094ff"
},
light: {
colors: ["#ffffff", "#ffffff"],
locations: [0, 1],
head: "#000000", text: "#5a615c", acc: "#006edb"
}
};
// const heatmapThemes = {
// auto: Device.isUsingDarkAppearance()
// ? {
// bg: ["#0d1117", "#0d1117", "#0d1117"],
// text: "#ffffff",
// accent: "#56d364",
// box: ["#2e2f37", "#196c2e", "#196c2e", "#2ea043", "#56d364"]
// }
// : {
// bg: ["#ffffff", "#ffffff", "#ffffff"],
// text: "#000000",
// // accent: "#A0A0A0",
// accent: size === "small" ? "#A0A0A0" : "#116329",
// box: ["#eff2f5", "#aceebb", "#4ac26b", "#2da44e", "#116329"]
// },
// light: {
// bg: ["#ffffff", "#ffffff", "#ffffff"],
// text: "#000000",
// // accent: "#A0A0A0",
// accent: size === "small" ? "#A0A0A0" : "#116329",
// box: ["#eff2f5", "#aceebb", "#4ac26b", "#2da44e", "#116329"]
// },
// dark: {
// bg: ["#0d1117", "#0d1117", "#0d1117"],
// text: "#ffffff",
// accent: "#56d364",
// box: ["#2e2f37", "#196c2e", "#196c2e", "#2ea043", "#56d364"]
// },
// red: {
// bg: ["#1e1e1e", "#1e1e1e", "#1e1e1e"],
// text: "#ffffff",
// accent: "#fd4c56",
// box: ["#3a2e30", "#5f2f31", "#ad3b39", "#ae3c3c", "#fd4c56"]
// },
// green: {
// bg: ["#ebedf0", "#9be9a8", "#40c463"],
// text: "#0a0e27",
// accent: "#216e39",
// box: ["#CACACA", "#9be9a8", "#40c463", "#30a14e", "#216e39"]
// }
// };
const heatmapThemes = {
auto: Device.isUsingDarkAppearance()
? {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#ffffff",
accent: "#56d364",
box: ["#2e2f37", "#196c2e", "#196c2e", "#2ea043", "#56d364"]
}
: {
bg: ["#ffffff", "#ffffff", "#ffffff"],
text: "#000000",
accent: size === "small" ? "#A0A0A0" : "#116329",
box: ["#eff2f5", "#aceebb", "#4ac26b", "#2da44e", "#116329"]
},
light: {
bg: ["#ffffff", "#ffffff", "#ffffff"],
text: "#000000",
accent: size === "small" ? "#A0A0A0" : "#116329",
box: ["#eff2f5", "#aceebb", "#4ac26b", "#2da44e", "#116329"]
},
dark: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#ffffff",
accent: "#56d364",
box: ["#2e2f37", "#196c2e", "#196c2e", "#2ea043", "#56d364"]
},
red: {
bg: ["#1e1e1e", "#1e1e1e", "#1e1e1e"],
text: "#ffffff",
accent: "#fd4c56",
box: ["#3a2e30", "#5f2f31", "#ad3b39", "#ae3c3c", "#fd4c56"]
},
green: {
bg: ["#ebedf0", "#9be9a8", "#40c463"],
text: "#0a0e27",
accent: "#216e39",
box: ["#CACACA", "#9be9a8", "#40c463", "#30a14e", "#216e39"]
},
// New themes added below
forestCalm: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#e9f5db",
accent: "#95d5b2",
box: ["#0d1b1e", "#1b4332", "#2d6a4f", "#52b788", "#95d5b2"]
},
forestCanopy: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#f4a261",
accent: "#80ffdb",
box: ["#0d1b1e", "#1d3a3f", "#3a7d44", "#57cc99", "#80ffdb"]
},
cyberPurple: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#ffffff",
accent: "#c77dff",
box: ["#1a1a2e", "#4b0082", "#6a0dad", "#9b59b6", "#c77dff"]
},
sunsetGold: {
bg: ["#000000", "#000000", "#000000"],
text: "#ffffff",
accent: "#fcd34d",
box: ["#1a1a1a", "#a05a2c", "#e76f51", "#f4a261", "#fcd34d"]
},
nordBlueV1: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#00bfff",
accent: "#ffd700",
box: ["#1a1a2e", "#113f67", "#1c7293", "#00bfff", "#ffd700"]
},
nordBlueV2: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#c9d1d9",
accent: "#43D0FF",
box: ["#1a1a2e", "#113f67", "#1c7293", "#0086B3", "#43D0FF", "#ffd700"]
},
sunsetDusk: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#f9c74f",
accent: "#ff8e9e",
box: ["#1e1e2e", "#42275a", "#734b6d", "#b06ab3", "#ff8e9e"]
},
earthyWarm: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#7fb069",
accent: "#fae588",
box: ["#1a120b", "#3c2a21", "#9a5b13", "#d4a017", "#fae588"]
},
arcticIce: {
bg: ["#0d1117", "#0d1117", "#0d1117"],
text: "#ff6d00",
accent: "#e0e1dd",
box: ["#050505", "#1b263b", "#415a77", "#778da9", "#e0e1dd"]
}
};
const langColors = {
JavaScript: "#f1e05a",
Python: "#3572A5",
Java: "#b07219",
PHP: "#4F5D95",
HTML: "#e34c26",
CSS: "#563d7c",
TypeScript: "#2b7489",
C: "#555555",
"C++": "#f34b7d",
"C#": "#178600",
Go: "#00ADD8",
Ruby: "#701516",
Shell: "#89e051",
Swift: "#ffac45",
Kotlin: "#A97BFF",
Rust: "#dea584",
Dart: "#00B4AB"
};
// Cache configuration
const CACHE_DIR = ".cache";
const CACHE_FILE = "github_stats_cache.json";
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
// Cache management class
class CacheManager {
constructor() {
this.fm = FileManager.iCloud();
this.cacheDir = this.fm.joinPath(this.fm.documentsDirectory(), CACHE_DIR);
this.cacheFile = this.fm.joinPath(this.cacheDir, CACHE_FILE);
console.log(`Cache directory path: ${this.cacheDir}`);
console.log(`Cache file path: ${this.cacheFile}`);
this.ensureCacheDir();
}
ensureCacheDir() {
try {
if (!this.fm.fileExists(this.cacheDir)) {
console.log("Creating cache directory...");
this.fm.createDirectory(this.cacheDir, true);
console.log("Cache directory created successfully");
} else {
console.log("Cache directory already exists");
}
} catch (error) {
console.error("Failed to create cache directory:", error);
}
}
async saveCache(data) {
try {
console.log(`Attempting to save cache with data: ${Object.keys(data).join(', ')}`);
// Ensure directory exists before writing
this.ensureCacheDir();
const cacheData = {
timestamp: Date.now(),
data: data
};
const jsonString = JSON.stringify(cacheData, null, 2);
console.log(`Writing cache data, size: ${jsonString.length} characters`);
this.fm.writeString(this.cacheFile, jsonString);
// Download from iCloud to ensure it's available
if (this.fm.fileExists(this.cacheFile)) {
await this.fm.downloadFileFromiCloud(this.cacheFile);
const fileSize = this.fm.fileSize(this.cacheFile);
console.log(`Cache saved successfully! File size: ${fileSize} bytes`);
// Also log the actual file location for verification
console.log(`Cache file created at: ${this.cacheFile}`);
// List files in cache directory to verify
const cacheContents = this.fm.listContents(this.cacheDir);
console.log(`Cache directory contents: ${cacheContents.join(', ')}`);
} else {
console.error("Cache file was not created!");
}
} catch (error) {
console.error("Failed to save cache:", error);
console.error(`Error details: ${error.message}`);
}
}
async loadCache() {
try {
if (!this.fm.fileExists(this.cacheFile)) {
console.log("No cache file found");
return null;
}
// Download from iCloud first
await this.fm.downloadFileFromiCloud(this.cacheFile);
const cacheContent = this.fm.readString(this.cacheFile);
const cacheData = JSON.parse(cacheContent);
// Check if cache is still valid (within 24 hours)
const isValid = (Date.now() - cacheData.timestamp) < CACHE_DURATION;
if (!isValid) {
console.log("Cache expired");
return null;
}
console.log("Cache loaded successfully");
return cacheData.data;
} catch (error) {
console.error("Failed to load cache:", error);
return null;
}
}
isCacheValid() {
try {
if (!this.fm.fileExists(this.cacheFile)) return false;
const cacheContent = this.fm.readString(this.cacheFile);
const cacheData = JSON.parse(cacheContent);
return (Date.now() - cacheData.timestamp) < CACHE_DURATION;
} catch (error) {
return false;
}
}
}
// Initialize cache manager
const cacheManager = new CacheManager();
// Helper function to check internet connectivity
async function isOnline() {
try {
const req = new Request("https://www.google.com");
req.timeoutInterval = 5; // 5 second timeout
await req.load();
return true;
} catch (error) {
console.log("No internet connection detected");
return false;
}
}
// console.log(token);
const rawParam = args.widgetParameter || "";
// const rawParam = args.widgetParameter || "rushhiii/Scriptable-IOSWidgets,prs";
// const rawParam = args.widgetParameter || "heatmap,forestCalm";
// const parts = rawParam.toLowerCase().split(",").map(s => s.trim());
const parts = rawParam.split(",").map(s => s.trim());
// With this improved version:
let isHeatmap = parts.includes("heatmap");
let repoPath = "";
let statType = "";
let themeParam = "";
// First pass - look for stat type and repo path
for (let part of parts) {
if (part === "heatmap") continue;
if (["stars", "commits", "views", "currstreak", "contributions", "allcommits", "repos", "longstreak", "followers", "following", "issues", "prs"].includes(part)) {
statType = part;
} else if (part.includes("/")) {
repoPath = part;
}
}
// Second pass - look for theme (prioritize heatmap themes if in heatmap mode)
for (let part of parts) {
if (part === "heatmap") continue;
if (isHeatmap && heatmapThemes[part]) {
themeParam = part;
break;
} else if (!isHeatmap && themePresets[part]) {
themeParam = part;
break;
}
}
// Default theme if none specified
if (!themeParam) {
themeParam = isHeatmap ? "auto" : "auto";
}
// If heatmap and no valid theme found, default to "auto"
// if (isHeatmap && !heatmapThemes.hasOwnProperty(themeParam)) {
// themeParam = "auto";
// }
// // If not heatmap and no valid theme found, default to "auto"
// if (!isHeatmap && !themePresets.hasOwnProperty(themeParam)) {
// themeParam = "auto";
// }
// const themeParam = parts.find(p => p in themePresets) || "auto";
const UI = {
small: { font: 12, headfont: 24, lineSpacing: 4, logo: 26, pad: 10 },
medium: { font: 13, headfont: 24, lineSpacing: 5, logo: 38, pad: 14 },
large: { font: 14, headfont: 26, lineSpacing: 6, logo: 55, pad: 16 }
}[size];
const now = new Date();
const year = now.getFullYear();
const shortyearLabel = `${year.toString().slice(-2)}`;
const thisYearStart = new Date(year, 0, 1).toISOString();
const today = now.toISOString();
const selectedTheme = themePresets[themeParam];
// const selectedTheme =
// isHeatmap
// ? (themeParam in heatmapThemes ? heatmapThemes[themeParam] : heatmapThemes.auto)
// : (themeParam in themePresets ? themePresets[themeParam] : themePresets.auto);
// const selectedTheme = themePresets[themeParam.toLowerCase()] || themePresets.auto;
function getHeatmapColor(count) {
const boxes = heatmapThemes[themeParam].box;
if (count === 0) return new Color(boxes[0]);
if (count >= 20) return new Color(boxes[4]);
if (count >= 10) return new Color(boxes[3]);
if (count >= 5) return new Color(boxes[2]);
if (count >= 1) return new Color(boxes[1]);
return new Color(boxes[0]);
}
// function createGradientBackground() {
// // const colors = heatmapThemes[themeParam]?.bg || heatmapThemes.dark.bg;
// const theme = heatmapThemes[themeParam].bg;
// const gradient = new LinearGradient();
// // gradient.colors = colors.map(c => new Color(c));
// // gradient.colors = heatmapThemes.themeParam.bg.map(c => new Color(c));
// gradient.colors = theme.map(c => new Color(c));
// // gradient.locations = [1.0, 0.5, 0.0];
// gradient.locations = [0.0, 0.5, 1.0];
// return gradient;
// }
function createGradientBackground() {
const theme = heatmapThemes[themeParam];
const gradient = new LinearGradient();
gradient.colors = theme.bg.map(c => new Color(c));
gradient.locations = [0.0, 0.5, 1.0];
return gradient;
}
function makeGradient(theme) {
const g = new LinearGradient();
g.colors = theme.colors.map(c => new Color(c));
g.locations = theme.locations;
return g;
}
// Dates for yearly contributions
// const now = new Date();
// const year = new Date().getFullYear();
// const shortyearLabel = `${year.toString().slice(-2)}`; // e.g., "25'"
// const thisYearStart = new Date(now.getFullYear(), 0, 1).toISOString();
// const today = now.toISOString();
// === GRAPHQL Query ===
const graphQLQuery = `
{
user(login: "${username}") {
contributionsThisYear: contributionsCollection(from: "${thisYearStart}", to: "${today}") {
totalCommitContributions
}
contributionsAllTime: contributionsCollection {
contributionCalendar {
totalContributions
weeks {
contributionDays {
date
contributionCount
}
}
}
}
pullRequests(states: [OPEN, MERGED, CLOSED]) { totalCount }
issues(states: [OPEN, CLOSED]) { totalCount }
repositories(first: 100, isFork: false) {
nodes {
stargazerCount
defaultBranchRef {
target {
... on Commit {
history { totalCount }
}
}
}
}
}
}
}`;
async function fetchGraphQLStats() {
const online = await isOnline();
// If offline, use cache immediately
if (!online) {
console.log("Offline mode - loading GraphQL stats from cache");
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.ghStats) {
console.log("✅ Using cached GraphQL stats (offline)");
return cachedData.ghStats;
}
throw new Error("No internet connection and no valid cache available");
}
// If online, try to fetch fresh data
try {
console.log("🌐 Online mode - fetching fresh GraphQL stats");
const req = new Request("https://api.github.com/graphql");
req.method = "POST";
req.headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
};
req.body = JSON.stringify({ query: graphQLQuery });
const json = await req.loadJSON();
const user = json.data.user;
const commits2025 = user.contributionsThisYear.totalCommitContributions;
const totalContributions = user.contributionsAllTime.contributionCalendar.totalContributions;
const totalPRs = user.pullRequests.totalCount;
const totalIssues = user.issues.totalCount;
const totalCommits = user.repositories.nodes.reduce((sum, repo) =>
sum + (repo.defaultBranchRef?.target?.history?.totalCount || 0), 0);
const totalStars = user.repositories.nodes.reduce((sum, repo) =>
sum + (repo.stargazerCount || 0), 0);
const allDays = user.contributionsAllTime.contributionCalendar.weeks.flatMap(w => w.contributionDays);
const todayStr = new Date().toISOString().split("T")[0];
let currentStreak = 0;
for (let i = allDays.length - 1; i >= 0; i--) {
const d = allDays[i];
if (d.date === todayStr) continue;
if (d.contributionCount > 0) currentStreak++;
else break;
}
let longestStreak = 0, temp = 0;
for (const d of allDays) {
if (d.contributionCount > 0) {
temp++;
longestStreak = Math.max(temp, longestStreak);
} else temp = 0;
}
const result = {
commits2025,
totalCommits,
totalContributions,
totalPRs,
totalIssues,
currentStreak,
longestStreak,
totalStars
};
console.log("✅ Fresh GraphQL stats fetched successfully");
return result;
} catch (error) {
console.error("❌ Failed to fetch GraphQL stats:", error);
// Try cache as fallback
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.ghStats) {
console.log("✅ Using cached GraphQL stats as fallback");
return cachedData.ghStats;
}
throw error;
}
}
async function fetchUserInfo() {
const online = await isOnline();
// If offline, use cache immediately
if (!online) {
console.log("Offline mode - loading user info from cache");
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.userInfo) {
console.log("✅ Using cached user info (offline)");
return cachedData.userInfo;
}
throw new Error("No internet connection and no valid cache available");
}
// If online, try to fetch fresh data
try {
console.log("🌐 Online mode - fetching fresh user info");
const req = new Request(`https://api.github.com/users/${username}`);
req.headers = { Authorization: `Bearer ${token}` };
const result = await req.loadJSON();
console.log("✅ Fresh user info fetched successfully");
return result;
} catch (error) {
console.error("❌ Failed to fetch user info:", error);
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.userInfo) {
console.log("✅ Using cached user info as fallback");
return cachedData.userInfo;
}
throw error;
}
}
// async function fetchTopLanguage() {
// const req = new Request(`https://api.github.com/users/${username}/repos?per_page=100`);
// req.headers = { Authorization: `Bearer ${token}` };
// const data = await req.loadJSON();
// const langCount = {};
// for (let repo of data) {
// const lang = repo.language;
// if (lang) langCount[lang] = (langCount[lang] || 0) + 1;
// }
// return Object.entries(langCount).sort((a, b) => b[1] - a[1])[0]?.[0] || null;
// }
// fetchTopLanguagesShortform
// async function fetchTopLanguage(limit = 8) {
// const req = new Request(`https://api.github.com/users/${username}/repos?per_page=100`);
// req.headers = { Authorization: `Bearer ${token}` };
// const data = await req.loadJSON();
// const langCount = {};
// let total = 0;
// for (let repo of data) {
// const lang = repo.language;
// if (lang) {
// langCount[lang] = (langCount[lang] || 0) + 1;
// total++;
// }
// }
// // Sort and keep top N
// const topLangs = Object.entries(langCount)
// .sort((a, b) => b[1] - a[1])
// .slice(0, limit);
// // Shortform map
// const shortMap = {
// JavaScript: "JS",
// TypeScript: "TS",
// Python: "PY",
// Java: "JAVA",
// C: "C",
// "C++": "CPP",
// "C#": "CS",
// HTML: "HTML",
// CSS: "CSS",
// PHP: "PHP",
// Ruby: "RB",
// Shell: "SH",
// Go: "GO",
// Kotlin: "KT",
// Swift: "SW",
// Rust: "RS",
// };
// // Format
// return topLangs.map(([lang, count]) => {
// const short = shortMap[lang] || lang.slice(0, 3).toUpperCase();
// const percent = ((count / total) * 100).toFixed(0);
// return `${short} ${percent}%`;
// }).join(" | ");
// }
async function fetchTopLanguage(limit = 12) {
const online = await isOnline();
// If offline, use cache immediately
if (!online) {
console.log("Offline mode - loading top languages from cache");
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.topLanguages) {
console.log("✅ Using cached top languages (offline)");
return cachedData.topLanguages;
}
throw new Error("No internet connection and no valid cache available");
}
// If online, try to fetch fresh data
try {
console.log("🌐 Online mode - fetching fresh top languages");
let allRepos = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const req = new Request(`https://api.github.com/user/repos?type=all&per_page=100&page=${page}`);
req.headers = { Authorization: `Bearer ${token}` };
const data = await req.loadJSON();
if (data.length === 0) {
hasMore = false;
} else {
allRepos = allRepos.concat(data);
page++;
if (page > 10) hasMore = false;
}
}
const langCount = {};
let total = 0;
for (let repo of allRepos) {
const lang = repo.language;
if (lang) {
langCount[lang] = (langCount[lang] || 0) + 1;
total++;
}
}
const shortMap = {
JavaScript: "JS", TypeScript: "TS", Python: "PY", Java: "JAVA",
C: "C", "C++": "CPP", "C#": "CS", HTML: "HTML", CSS: "CSS",
PHP: "PHP", Ruby: "RB", Shell: "SH", Go: "GO", Kotlin: "KT",
Swift: "SW", Rust: "RS", Dart: "DART"
};
const result = Object.entries(langCount)
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([lang, count]) => {
const short = shortMap[lang] || lang.slice(0, 3).toUpperCase();
const percent = ((count / total) * 100).toFixed(2) + "%";
return [short, percent, lang]; // ← return full info
});
console.log("✅ Fresh top languages fetched successfully");
return result;
} catch (error) {
console.error("❌ Failed to fetch top languages:", error);
const cachedData = await cacheManager.loadCache();
if (cachedData && cachedData.topLanguages) {
console.log("✅ Using cached top languages as fallback");
return cachedData.topLanguages;
}
throw error;
}
}
// async function fetchRepoStat(repoPath, statType) {
// const baseUrl = `https://api.github.com/repos/${repoPath}`;
// const headers = { Authorization: `Bearer ${token}` };
// const req = new Request(baseUrl);
// req.headers = headers;
// const json = await req.loadJSON();
// const ghStats = await fetchGraphQLStats();
// const userInfo = await fetchUserInfo();
// let statValue = 0;
// let type = "";
// if (statType === "stars") {
// statValue = json.stargazers_count;
// type = stars;
// } else if (statType === "commits") {
// // const commitsReq = new Request(`${baseUrl}/commits?per_page=1`);
// // commitsReq.headers = headers;
// // const commits = await commitsReq.loadJSON();
// // const link = commitsReq.response.headers["link"];
// // const lastPage = link?.match(/&page=(\d+)>; rel="last"/)?.[1];
// // statValue = lastPage ? parseInt(lastPage) : commits.length;
// statValue = ghStats.commits2025;
// type = `${year} commits`;
// } else if (statType === "views") {
// const viewsReq = new Request(`${baseUrl}/traffic/views`);
// viewsReq.headers = headers;
// const views = await viewsReq.loadJSON();
// statValue = views.count || 0;
// type = "views";
// } else if (statType === "currstreak") {
// statValue = ghStats.currentStreak;
// type = "current streak";
// } else if (statType === "contributions") {
// statValue = ghStats.totalContributions;
// type = "contributions";
// } else if (statType === "allcommits") {
// statValue = ghStats.totalCommits;
// type = "total commits";
// } else if (statType === "repos") {
// statValue = userInfo.public_repos;
// type = "repos";
// } else if (statType === "longstreak") {
// statValue = ghStats.longestStreak;
// type = "longest streak";
// } else if (statType === "followers") {
// statValue = userInfo.followers;
// type = "Followers";
// } else if (statType === "following") {
// statValue = userInfo.following;
// type = "Following";
// } else if (statType === "prs") {
// statValue = ghStats.totalPRs;
// type = "PRs";
// } else if (statType === "issues") {
// statValue = ghStats.totalIssues;
// type = "Total Issues";
// }
// return {
// name: json.name,
// statValue,
// url: json.html_url,
// type
// };
// }
async function fetchRepoStat(repoPath, statType) {
let json = {};
let repoName = "";
let repoUrl = "";
if (repoPath) {
const req = new Request(`https://api.github.com/repos/${repoPath}`);
req.headers = { Authorization: `Bearer ${token}` };
json = await req.loadJSON();
repoName = json?.name || repoPath.split("/")[1];
repoUrl = json?.html_url || `https://github.com/${repoPath}`;
}
const ghStats = await fetchGraphQLStats();
// console.log(ghStats);
// console.log("currentStreak:", ghStats?.currentStreak);
const userInfo = await fetchUserInfo();
// fallback display name
const title = repoPath ? repoName : username;
const link = repoPath ? repoUrl : `https://github.com/${username}`;
// let value = 0;
// let label = "";
let statValue = 0;
let type = "";
if (statType === "stars") {
statValue = json.stargazers_count;
type = "stars";
} else if (statType === "commits") {
// const commitsReq = new Request(`${repoUrl}/commits?per_page=1`);
// commitsReq.headers = headers;
// const commits = await commitsReq.loadJSON();
// const link = commitsReq.response.headers["link"];
// const lastPage = link?.match(/&page=(\d+)>; rel="last"/)?.[1];
// statValue = lastPage ? parseInt(lastPage) : commits.length;
statValue = ghStats.commits2025;
type = `${year} commits`;
} else if (statType === "views") {
// const viewsReq = new Request(`${repoUrl}/traffic/views`);
// viewsReq.headers = headers;
const viewsReq = new Request(`${baseUrl}/traffic/views`);
viewsReq.headers = { Authorization: `Bearer ${token}` };
const views = await viewsReq.loadJSON();
statValue = views.count || 0;
type = "views";
} else if (statType === "currstreak") {
statValue = ghStats.currentStreak;
type = "current streak";
} else if (statType === "contributions") {
statValue = ghStats.totalContributions;
type = "contributions";
} else if (statType === "allcommits") {
statValue = ghStats.totalCommits;
type = "total commits";
} else if (statType === "repos") {
statValue = userInfo.public_repos;
type = "repos";
} else if (statType === "longstreak") {
statValue = ghStats.longestStreak;
type = "longest streak";
} else if (statType === "followers") {
statValue = userInfo.followers;
type = "Followers";
} else if (statType === "following") {
statValue = userInfo.following;
type = "Following";
} else if (statType === "prs") {
statValue = ghStats.totalPRs;
type = "PRs";
} else if (statType === "issues") {
statValue = ghStats.totalIssues;
type = "Total Issues";
}
// switch (statType) {
// case "views":
// value = json?.views?.count || 0;
// label = "Views";
// break;
// case "stars":
// value = json?.stargazers_count || 0;
// label = "Stars";
// break;
// case "commits":
// value = ghStats?.commits2025 || 0;
// label = "Commits";
// break;
// case "allcommits":
// value = ghStats?.totalCommits || 0;
// label = "Total Commits";
// break;
// case "currstreak":