Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1579 lines (1435 loc) · 49.6 KB
/
Copy pathcontent.js
File metadata and controls
1579 lines (1435 loc) · 49.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
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
// PrepPush - content.js (Milestone 2 + Toast)
// Re-injection guard: background may "executeScript" after extension reloads.
// `const` would throw on re-exec in same isolated world.
var PREPPUSH_FRAME = globalThis.PREPPUSH_FRAME || (window.top === window ? 'top' : 'child');
try { globalThis.PREPPUSH_FRAME = PREPPUSH_FRAME; } catch {}
console.log(
'%c[PrepPush] Content script loaded ✅ (' + PREPPUSH_FRAME + ')',
'color: #22c55e; font-weight: bold;'
);
// ─── EXTENSION CONNECTION (survives extension reload) ─────────────────────────
function getExtensionId() {
try {
return chrome.runtime?.id || null;
} catch {
return null;
}
}
function isExtensionAlive() {
return Boolean(getExtensionId());
}
function pingExtension() {
return new Promise((resolve) => {
if (!isExtensionAlive()) {
resolve(false);
return;
}
try {
chrome.runtime.sendMessage({ type: 'PING' }, (res) => {
resolve(!chrome.runtime.lastError && res?.status === 'alive');
});
} catch {
resolve(false);
}
});
}
function scheduleReconnect(reason) {
if (window.top !== window || !isExtensionAlive()) return;
if (window.__preppushReconnectTimer) return;
if (reason) console.warn('[PrepPush]', reason);
window.__preppushReconnectTimer = setTimeout(() => {
window.__preppushReconnectTimer = null;
requestExtensionReconnect();
}, 400);
}
function sendToExtension(message, onResponse) {
if (!isExtensionAlive()) {
return false;
}
try {
chrome.runtime.sendMessage(message, (response) => {
const err = chrome.runtime.lastError?.message || '';
if (err) {
if (
err.includes('Extension context invalidated') ||
err.includes('Receiving end does not exist')
) {
scheduleReconnect('Background waking up — retrying connection');
return;
}
if (err.includes('message channel closed')) {
console.warn('[PrepPush] Background is still working — check the PrepPush popup in a few seconds.');
return;
}
console.error('[PrepPush] Could not reach background:', err);
return;
}
onResponse?.(response);
});
return true;
} catch {
scheduleReconnect('Extension context reset — retrying connection');
return false;
}
}
// ─── INJECT INTERCEPTOR INTO PAGE CONTEXT (via scripting API — CSP-safe) ─────
function injectInterceptor(attempt = 0) {
if (!isExtensionAlive()) {
if (attempt < 6) {
setTimeout(() => injectInterceptor(attempt + 1), 400 + attempt * 250);
return;
}
scheduleReconnect('Extension not ready — retrying interceptor');
return;
}
try {
chrome.runtime.sendMessage({ type: 'INJECT_PAGE_INTERCEPTOR' }, (res) => {
const err = chrome.runtime.lastError?.message || '';
if (err) {
if (
attempt < 8 &&
(/Receiving end does not exist|context invalidated/i.test(err) ||
/message port closed/i.test(err))
) {
setTimeout(() => injectInterceptor(attempt + 1), 500);
return;
}
console.error('[PrepPush] Interceptor inject failed:', err);
if (/invalidated|does not exist/i.test(err)) scheduleReconnect('Retrying interceptor after disconnect');
return;
}
if (res?.ok) {
console.log('[PrepPush] Interceptor injected into page context ✅');
} else if (attempt < 6) {
setTimeout(() => injectInterceptor(attempt + 1), 500);
} else {
console.error('[PrepPush] Interceptor inject failed:', res?.error || 'unknown');
}
});
} catch {
scheduleReconnect('Retrying interceptor');
}
}
function requestExtensionReconnect() {
if (!isExtensionAlive()) return;
try {
chrome.runtime.sendMessage({ type: 'ENSURE_CONTENT_SCRIPT' }, () => {
injectInterceptor(0);
ensureInterceptorReady().catch(() => {});
});
} catch {
/* stale content script — background reinjects on popup open / tab wake */
}
}
// ─── DISMISS TOAST ───────────────────────────────────────────────────────────
// Top-level so it's accessible everywhere in this file
function dismissToast(toast) {
if (!toast || toast.classList.contains('preppush-hiding')) return;
toast.classList.add('preppush-hiding');
setTimeout(() => toast.remove(), 350);
}
// ─── TOAST NOTIFICATION ──────────────────────────────────────────────────────
function showToast(problemName) {
// Remove existing toast if any
const existing = document.getElementById('preppush-toast');
if (existing) existing.remove();
// Inject styles once
if (!document.getElementById('preppush-toast-styles')) {
const style = document.createElement('style');
style.id = 'preppush-toast-styles';
style.textContent = `
#preppush-toast {
position: fixed;
bottom: 28px;
right: 28px;
z-index: 999999;
background: #0f172a;
border: 1px solid #22c55e40;
border-left: 3px solid #22c55e;
border-radius: 10px;
padding: 12px 16px;
display: flex;
align-items: center;
gap: 10px;
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 13px;
color: #f1f5f9;
min-width: 260px;
max-width: 340px;
cursor: default;
animation: preppush-slidein 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
#preppush-toast.preppush-hiding {
animation: preppush-slideout 0.35s ease forwards;
}
@keyframes preppush-slidein {
from { opacity: 0; transform: translateY(16px) scale(0.95); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes preppush-slideout {
from { opacity: 1; transform: translateY(0) scale(1); }
to { opacity: 0; transform: translateY(10px) scale(0.95); }
}
#preppush-toast .pp-icon {
width: 28px;
height: 28px;
background: linear-gradient(135deg, #22c55e, #16a34a);
border-radius: 7px;
display: flex;
align-items: center;
justify-content: center;
font-size: 11px;
font-weight: 800;
color: #0f172a;
flex-shrink: 0;
font-family: 'Courier New', monospace;
}
#preppush-toast .pp-content {
flex: 1;
min-width: 0;
}
#preppush-toast .pp-title {
font-weight: 600;
font-size: 13px;
color: #f1f5f9;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#preppush-toast .pp-subtitle {
font-size: 11px;
color: #64748b;
margin-top: 2px;
}
#preppush-toast .pp-close {
background: none;
border: none;
color: #475569;
font-size: 14px;
cursor: pointer;
padding: 0;
line-height: 1;
flex-shrink: 0;
transition: color 0.15s;
}
#preppush-toast .pp-close:hover {
color: #94a3b8;
}
#preppush-toast .pp-progress {
position: absolute;
bottom: 0;
left: 0;
height: 2px;
background: #22c55e;
border-radius: 0 0 10px 10px;
animation: preppush-progress 4s linear forwards;
animation-play-state: running;
}
@keyframes preppush-progress {
from { width: 100%; }
to { width: 0%; }
}
`;
document.head.appendChild(style);
}
// Build toast element
const toast = document.createElement('div');
toast.id = 'preppush-toast';
toast.innerHTML = `
<div class="pp-icon">PP</div>
<div class="pp-content">
<div class="pp-title">✅ ${problemName}</div>
<div class="pp-subtitle">Saved — open PrepPush from toolbar to view</div>
</div>
<button class="pp-close" id="preppush-close">✕</button>
<div class="pp-progress"></div>
`;
document.body.appendChild(toast);
// Close button
document.getElementById('preppush-close').addEventListener('click', () => {
dismissToast(toast);
});
// ── TIMER: variable remaining time ────────────────────────────────────────
const TOTAL_DURATION = 4200; // slightly > 4s CSS animation so bar finishes first
let remaining = TOTAL_DURATION;
let startTime = Date.now();
let autoTimer = setTimeout(() => dismissToast(toast), remaining);
let leaveTimer = null;
const progressBar = toast.querySelector('.pp-progress');
toast.addEventListener('mouseenter', () => {
const elapsed = Date.now() - startTime;
remaining = Math.max(0, remaining - elapsed);
clearTimeout(autoTimer);
clearTimeout(leaveTimer);
progressBar.style.animationPlayState = 'paused';
});
toast.addEventListener('mouseleave', () => {
progressBar.style.animationPlayState = 'running';
startTime = Date.now(); // reset so next mouseenter measures from now
leaveTimer = setTimeout(() => dismissToast(toast), remaining);
});
// Click toast body — flash badge to guide user to toolbar icon
toast.addEventListener('click', (e) => {
if (e.target.id === 'preppush-close') return;
sendToExtension({ type: 'FLASH_BADGE' });
toast.style.borderLeftColor = '#86efac';
toast.style.transition = 'border-left-color 0.15s';
setTimeout(() => { toast.style.borderLeftColor = '#22c55e'; }, 200);
});
}
var SUBMISSION_FRESH_MS = globalThis.SUBMISSION_FRESH_MS || 30 * 60 * 1000;
try { globalThis.SUBMISSION_FRESH_MS = SUBMISSION_FRESH_MS; } catch {}
function isFreshSubmission(submission) {
const ts = submission?.timestamp;
if (!ts) return true;
return Date.now() - ts < SUBMISSION_FRESH_MS;
}
function isSubstantiveCode(code) {
const t = (code || '').trim();
if (t.length < 20) return false;
if (/if\s+__name__\s*==/m.test(t)) return true;
if (/\binput\s*\(/m.test(t) && /\bprint\s*\(/m.test(t)) return true;
if (/\bdef\s+\w+/m.test(t)) return t.length >= 30;
if (looksLikeSqlCode(t)) return true;
const lines = t.split('\n').filter((l) => l.trim()).length;
return lines >= 3 && t.length >= 35;
}
/** Editor scrape may miss lines; still usable for prep-kit saves. */
function isEditorCodeUsable(code) {
return isSubstantiveCode(code);
}
function shouldCaptureSubmission(submission, source) {
if (!submission) return false;
if (source === 'force' || source === 'api-fetch' || source === 'poll-watch') {
if (!submission.code?.trim()) {
console.log('[PrepPush] Skip — no code (', source, ')');
return false;
}
if (
(source === 'api-fetch' || source === 'poll-watch') &&
!isSubstantiveCode(submission.code)
) {
console.log('[PrepPush] Skip — API code incomplete (', source, ')');
return false;
}
if (source === 'force' && !isEditorCodeUsable(submission.code)) {
console.log(
'[PrepPush] Skip — editor code incomplete (',
submission.code.length,
'chars). Click Submit Code, or refresh and try Capture again.'
);
return false;
}
return true;
}
if (source === 'dom') return false;
if (!isSubstantiveCode(submission.code)) {
console.log('[PrepPush] Ignoring — solution code incomplete (need full API response)');
return false;
}
if (!isFreshSubmission(submission)) {
console.log('[PrepPush] Ignoring stale submission (opened old result, not a new submit)');
return false;
}
const id = submission.submissionId;
if (id == null || String(id).startsWith('dom-')) return false;
return true;
}
function difficultyLabelFromModel(model) {
if (!model) return null;
if (model.difficulty_name) return String(model.difficulty_name);
const score = model.difficulty ?? model.difficulty_score;
if (score == null || score === '') return null;
const n = Number(score);
if (Number.isNaN(n)) return String(score);
if (n <= 1.25) return 'Easy';
if (n <= 2.25) return 'Medium';
return 'Hard';
}
function parseChallengeModel(model) {
if (!model || typeof model !== 'object') return {};
const rawParts = [
model.body,
model.body_html,
model.problem_statement,
model.statement,
model.question_body,
model.html_body,
].filter((s) => typeof s === 'string' && s.trim());
let problemStatement = '';
if (rawParts.length) {
problemStatement = rawParts
.map((s) => (/</.test(s) ? s.replace(/<[^>]+>/g, ' ') : s))
.join('\n')
.replace(/ /gi, ' ')
.replace(/\s+/g, ' ')
.trim();
}
if (problemStatement.length < 80 && typeof model.preview === 'string') {
problemStatement = model.preview.trim();
}
return {
difficulty: difficultyLabelFromModel(model),
subdomainName:
model.track?.name ||
model.track?.track_name ||
model.primary_contest?.track?.name ||
null,
problemName: model.name || null,
problemStatement: problemStatement || null,
};
}
/** Full visible problem text from the page (fallback when REST body is thin). */
function scrapeProblemStatementFromDom() {
const selectors = [
'[data-attr2="Statement"]',
'[class*="challenge-body"]',
'[class*="ChallengeBody"]',
'.challenge-text',
'#content .challenge-body-html',
'div.challenge-body-html',
'[data-testid="challenge-body"]',
];
for (const sel of selectors) {
const el = document.querySelector(sel);
const text = el?.innerText?.trim();
if (text && text.length >= 80) return text;
}
return null;
}
function friendlySubdomainName(contestSlug, existing) {
if (existing) return existing;
if (contestSlug === 'software-engineer-prep-kit') return 'Software Engineer Prep Kit';
return null;
}
function challengeDetailsFromNextData(slug) {
const el = document.querySelector('#__NEXT_DATA__');
if (!el?.textContent) return {};
try {
const walk = (obj, depth = 0) => {
if (!obj || depth > 16) return null;
if (typeof obj === 'object' && !Array.isArray(obj)) {
if (
(obj.difficulty_name || obj.difficulty != null) &&
(obj.slug === slug || obj.challenge_slug === slug)
) {
return parseChallengeModel(obj);
}
for (const v of Object.values(obj)) {
const found = walk(v, depth + 1);
if (found?.difficulty || found?.subdomainName) return found;
}
}
if (Array.isArray(obj)) {
for (const item of obj) {
const found = walk(item, depth + 1);
if (found?.difficulty || found?.subdomainName) return found;
}
}
return null;
};
return walk(JSON.parse(el.textContent)) || {};
} catch {
return {};
}
}
async function fetchChallengeDetailsInPage(slug, contestSlug) {
if (!slug) return {};
const contests = [...new Set([contestSlug || contestSlugFromPath(), contestSlugFromPath()].filter(Boolean))];
for (const contest of contests) {
try {
const url = `https://www.hackerrank.com/rest/contests/${contest}/challenges/${slug}`;
const res = await fetch(url, {
credentials: 'include',
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
});
if (!res.ok) continue;
const parsed = parseChallengeModel((await res.json())?.model);
parsed.subdomainName = friendlySubdomainName(contest, parsed.subdomainName);
if (parsed.difficulty || parsed.subdomainName || parsed.problemStatement) return parsed;
} catch {
/* ignore */
}
}
const fallback = challengeDetailsFromNextData(slug);
fallback.subdomainName = friendlySubdomainName(contestSlugFromPath(), fallback.subdomainName);
return fallback;
}
async function handleAcceptedSubmission(submission, source) {
if (window.top !== window) return;
const id =
submission?.submissionId != null ? String(submission.submissionId) : null;
if (!id) return;
if (!window.__preppushSeenIds) window.__preppushSeenIds = new Set();
if (window.__preppushSeenIds.has(id)) return;
if (!window.__preppushCaptureInFlight) window.__preppushCaptureInFlight = new Set();
if (window.__preppushCaptureInFlight.has(id)) return;
window.__preppushCaptureInFlight.add(id);
try {
if (!looksLikeFullSubmit(submission)) {
ppLog('Skip — not a full Submit evaluation (Run/sample only)');
return;
}
if (!shouldCaptureSubmission(submission, source)) {
ppLog('Skip — shouldCaptureSubmission=false (' + source + ')');
return;
}
if (!apiIndicatesFullAcceptance(submission) && !(await awaitAllTestsPassed())) {
ppLog('Skip — API not fully accepted yet and tests-pass UI not visible');
return;
}
window.__preppushSeenIds.add(id);
clearWatching(submission.submissionId);
// Prefer full problem statement for AI notes (REST body, then page DOM).
{
const details = await fetchChallengeDetailsInPage(
submission.problemSlug,
submission.contestSlug
);
const fromDom = scrapeProblemStatementFromDom();
const statement =
(details.problemStatement && details.problemStatement.length >= 80
? details.problemStatement
: null) ||
fromDom ||
details.problemStatement ||
null;
submission = {
...submission,
difficulty: submission.difficulty || details.difficulty,
subdomainName: submission.subdomainName || details.subdomainName,
problemName: submission.problemName || details.problemName,
problemStatement: submission.problemStatement || statement,
};
}
console.log(`[PrepPush] New accepted submission (${source}):`, {
...submission,
problemStatement: submission.problemStatement
? `[${submission.problemStatement.length} chars]`
: null,
});
const displayName = submission.problemName || submission.problemSlug || 'Solution';
sendToExtension({ type: 'SUBMISSION_ACCEPTED', payload: submission }, (response) => {
const err = chrome.runtime.lastError?.message;
if (err) {
console.error('[PrepPush] Background unreachable:', err);
return;
}
if (response?.saved !== false) {
showToast(displayName);
try {
sessionStorage.setItem('preppush_captured_' + (submission.problemSlug || 'unknown'), '1');
} catch {
/* ignore */
}
console.log('[PrepPush] Background saved submission ✅', response);
window.__preppushSubmitIntent = false;
return;
}
console.error('[PrepPush] Background did not save submission:', response);
});
} finally {
window.__preppushCaptureInFlight?.delete(id);
}
}
function problemSlugFromPath() {
const m = window.location.pathname.match(/\/challenges\/([^/]+)/);
return m ? m[1] : 'unknown-problem';
}
function contestSlugFromPath() {
const m = window.location.pathname.match(/\/contests\/([^/]+)\//);
if (m) return m[1];
if (window.location.pathname.includes('software-engineer-prep-kit')) {
return 'software-engineer-prep-kit';
}
return 'master';
}
function isContestTrackPage() {
return /\/contests\/[^/]+\/challenges\//.test(window.location.pathname);
}
function testcaseCountFrom(model) {
if (!model) return 0;
if (Array.isArray(model.testcase_status)) return model.testcase_status.length;
if (typeof model.testcaseCount === 'number') return model.testcaseCount;
return 0;
}
function isRunEvaluation(model) {
const code = (model?.code ?? '').trim();
const n = testcaseCountFrom(model);
const statusStr = String(model?.status ?? '').trim();
const statusCode = model?.status_code ?? model?.statusCode;
if (/^accepted$/i.test(statusStr) && code.length > 20) return false;
if (statusCode === 1 && code.length > 20) return false;
if ((model?.solved === 1 || model?.solved === true) && code.length > 20 && n > 3) {
return false;
}
if (n > 3) return false;
if (!code && n > 0 && n <= 3) return true;
if (statusStr === '1' && statusCode !== 1 && code.length < 20) return true;
return false;
}
function isFullSubmitEvaluation(model) {
if (!model || typeof model !== 'object') return false;
if (isRunEvaluation(model)) return false;
const status = String(model.status ?? '').trim();
const statusCode = model.status_code ?? model.statusCode;
const code = (model.code ?? '').trim();
if (code.length < 20) return false;
if (/processing|compil|running|queue|pending|wrong|fail|error|timeout/i.test(status)) {
return false;
}
if (/^accepted$/i.test(status) && (model.solved === 1 || model.solved === true)) return true;
if (statusCode === 1 && (model.solved === 1 || model.solved === true)) return true;
if (statusCode === 2 && /^processed$/i.test(status) && model.solved === 1) return true;
return false;
}
function isHrSubmissionAccepted(model) {
return isFullSubmitEvaluation(model);
}
function looksLikeFullSubmit(sub) {
if (!sub) return false;
if (sub.isFullSubmit) return true;
const code = (sub.code ?? '').trim();
if (code.length < 20) return false;
const statusStr = String(sub.status ?? '').trim();
if (/^accepted$/i.test(statusStr) && (sub.solved === 1 || sub.solved === true)) return true;
if (
(sub.statusCode === 1 || sub.status_code === 1) &&
(sub.solved === 1 || sub.solved === true)
) {
return true;
}
const n = testcaseCountFrom(sub);
if (n > 3 && (sub.solved === 1 || sub.solved === true)) return true;
if (isRunEvaluation(sub)) return false;
return false;
}
function apiIndicatesFullAcceptance(sub) {
return looksLikeFullSubmit(sub);
}
function markSubmitCodeClicked() {
window.__preppushSubmitIntent = true;
window.__preppushSubmitIntentAt = Date.now();
window.__preppushTestsPassedScheduled = false;
}
function hasSubmitIntent() {
if (!window.__preppushSubmitIntent) return false;
const age = Date.now() - (window.__preppushSubmitIntentAt || 0);
if (age > 20 * 60 * 1000) {
window.__preppushSubmitIntent = false;
return false;
}
return true;
}
async function awaitAllTestsPassed(maxMs = 5000) {
if (testsPassedOnPage()) return true;
const start = Date.now();
while (Date.now() - start < maxMs) {
await new Promise((r) => setTimeout(r, 300));
if (testsPassedOnPage()) return true;
}
return false;
}
function testsPassedOnPage(bodyText) {
const t = bodyText || document.body?.innerText || '';
return (
/all (available )?test cases passed/i.test(t) ||
/all tests? passed/i.test(t) ||
(/compiler message/i.test(t) && /\bsuccess\b/i.test(t)) ||
/submission (was )?successful/i.test(t) ||
/status[:\s]*accepted/i.test(t) ||
/challenge\s+(completed|solved)/i.test(t) ||
/you\s+(have\s+)?solved\s+this/i.test(t)
);
}
function submissionFromModel(model) {
if (!model) return null;
if (!isFullSubmitEvaluation(model)) return null;
const code = model.code ?? '';
if (!code || !isSubstantiveCode(code)) return null;
return {
status: model.status || 'Accepted',
language: model.language ?? null,
problemName: model.name ?? null,
problemSlug: model.challenge_slug ?? model.slug ?? problemSlugFromPath(),
contestSlug: model.contest_slug ?? contestSlugFromPath(),
submissionId: model.id ?? null,
timestamp: model.updated_at
? new Date(model.updated_at).getTime()
: model.created_at
? new Date(model.created_at).getTime()
: Date.now(),
code,
solved: model.solved,
statusCode: model.status_code ?? model.statusCode,
testcaseCount: model.testcase_status?.length ?? 0,
isFullSubmit: true,
};
}
function rememberSubmissionPollId(id) {
if (id != null && id !== '') window.__preppushLastPollId = String(id);
}
try {
globalThis.rememberSubmissionPollId = rememberSubmissionPollId;
} catch {
/* ignore */
}
function submissionIdFromPage() {
if (window.__preppushLastPollId) return String(window.__preppushLastPollId);
try {
const entries = performance.getEntriesByType('resource');
for (let i = entries.length - 1; i >= 0; i--) {
const name = entries[i]?.name || '';
if (name.includes('/submissions/code')) continue;
const hit = name.match(/\/submissions\/(\d{8,})/);
if (hit) return hit[1];
}
} catch {
/* ignore */
}
const html = document.documentElement?.innerHTML || '';
const m = html.match(/\/submissions\/(\d{8,})/);
return m ? m[1] : null;
}
function looksLikeSqlCode(code) {
const t = String(code || '').trim();
if (!t) return false;
if (/^\s*\/\*[\s\S]*?\*\/\s*(select|insert|update|delete|with)\b/i.test(t)) return true;
return /\b(select|insert|update|delete|with)\b[\s\S]*\b(from|into|set|values)\b/i.test(t);
}
function detectLanguageFromPage(code) {
const snippet = (document.body?.innerText || '').slice(0, 8000);
if (/\bdb2\b/i.test(snippet)) return 'db2';
if (/\bmysql\b/i.test(snippet)) return 'mysql';
if (/\b(postgresql|postgres)\b/i.test(snippet)) return 'postgresql';
if (/\boracle\b/i.test(snippet)) return 'oracle';
if (/\bsql\b/i.test(snippet)) return 'sql';
if (looksLikeSqlCode(code)) return 'sql';
if (/python\s*3/i.test(snippet)) return 'python3';
if (/python/i.test(snippet)) return 'python3';
if (/java\b/i.test(snippet)) return 'java';
if (/javascript/i.test(snippet)) return 'javascript';
if (/if\s+__name__/.test(code || '')) return 'python3';
if (/\binput\s*\(/.test(code || '')) return 'python3';
if (/\bdef\s+\w+/.test(code || '')) return 'python3';
if (/\bpublic\s+class\b/.test(code || '')) return 'java';
return 'unknown';
}
function ppLog(msg, level = 'log') {
window.__preppushLastSkip = msg;
const debug = (() => {
try {
return localStorage.getItem('preppush_debug') === '1';
} catch {
return false;
}
})();
if (debug || level === 'warn' || level === 'error') {
console[level === 'error' ? 'error' : level === 'warn' ? 'warn' : 'log'](
'[PrepPush]',
msg
);
}
}
var PREPPUSH_API_MIN_GAP_MS = globalThis.PREPPUSH_API_MIN_GAP_MS || 8000;
/** Min gap between our API fetches during Submit / poll-watch (faster than background rate). */
var PREPPUSH_API_URGENT_GAP_MS = globalThis.PREPPUSH_API_URGENT_GAP_MS || 3000;
/** Spaced backup checks only if page hook misses Accepted. Fewer on contest track (avoid 429). */
var PREPPUSH_BACKUP_CHECK_MS = globalThis.PREPPUSH_BACKUP_CHECK_MS || [4000, 8000, 12000];
var PREPPUSH_BACKUP_CHECK_CONTEST_MS = globalThis.PREPPUSH_BACKUP_CHECK_CONTEST_MS || [12000];
try {
globalThis.PREPPUSH_API_MIN_GAP_MS = PREPPUSH_API_MIN_GAP_MS;
globalThis.PREPPUSH_API_URGENT_GAP_MS = PREPPUSH_API_URGENT_GAP_MS;
globalThis.PREPPUSH_BACKUP_CHECK_MS = PREPPUSH_BACKUP_CHECK_MS;
globalThis.PREPPUSH_BACKUP_CHECK_CONTEST_MS = PREPPUSH_BACKUP_CHECK_CONTEST_MS;
} catch {}
function preppushApiState() {
if (!window.__preppushApi) {
window.__preppushApi = { pausedUntil: 0, lastFetchAt: 0, inFlight: false, recentById: {} };
}
return window.__preppushApi;
}
function canFetchSubmissionNow(submissionId, minGapMs = 4500) {
if (!submissionId) return false;
const api = preppushApiState();
const id = String(submissionId);
const last = api.recentById[id] || 0;
const now = Date.now();
if (now - last < minGapMs) return false;
api.recentById[id] = now;
return true;
}
/** Throttled HackerRank API fetch — avoids 429 from aggressive polling. */
async function hrApiFetch(url, { urgent = false } = {}) {
const api = preppushApiState();
const now = Date.now();
if (now < api.pausedUntil) {
return { ok: false, status: 429, paused: true, model: null };
}
while (api.inFlight) {
await new Promise((r) => setTimeout(r, 100));
}
const minGap = urgent ? PREPPUSH_API_URGENT_GAP_MS : PREPPUSH_API_MIN_GAP_MS;
const gap = minGap - (now - api.lastFetchAt);
if (gap > 0) await new Promise((r) => setTimeout(r, gap));
api.inFlight = true;
api.lastFetchAt = Date.now();
try {
const res = await fetch(url, {
credentials: 'include',
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
});
if (res.status === 429) {
api.pausedUntil = Date.now() + 120_000;
console.warn(
'[PrepPush] HackerRank rate limit (429) — PrepPush will not call the API for 2 min. ' +
'Capture still works via HackerRank\'s own polls (no action needed).'
);
return { ok: false, status: 429, model: null };
}
if (!res.ok) return { ok: false, status: res.status, model: null };
const data = await res.json();
return { ok: true, status: res.status, model: data?.model ?? data };
} catch (e) {
return { ok: false, status: 0, error: e?.message, model: null };
} finally {
api.inFlight = false;
}
}
async function fetchSubmissionModelById(submissionId, urgent = false) {
const contest = contestSlugFromPath();
const slug = problemSlugFromPath();
const url = `https://www.hackerrank.com/rest/contests/${contest}/challenges/${slug}/submissions/${submissionId}`;
const result = await hrApiFetch(url, { urgent });
return result.ok ? result.model : null;
}
function isAlreadyCaptured(submissionId) {
if (submissionId == null) return false;
return window.__preppushSeenIds?.has(String(submissionId));
}
/** One urgent fetch when we see a submission poll URL (works without page interceptor). */
async function tryFetchAndCapture(submissionId, reason) {
if (window.top !== window || !submissionId || isAlreadyCaptured(submissionId)) return;
if (!canFetchSubmissionNow(submissionId, 5000)) return;
try {
const model = await fetchSubmissionModelById(submissionId, true);
const sub = submissionFromModel(model);
if (sub) {
ppLog('Capture via content API fetch (' + reason + ') id=' + submissionId);
await handleAcceptedSubmission(sub, 'poll-watch');
}
} catch (e) {
const msg = e?.message || String(e);
if (/invalidated|Extension context/i.test(msg)) {
scheduleReconnect('Retrying after extension reload');
}
}
}
/** Try to read accepted submission immediately (no multi-second wait). */
async function captureAsSoonAsAccepted(reason) {
if (window.top !== window) return;
if (!isExtensionAlive()) return;
try {
await ensureInterceptorReady();
} catch {
return;
}
const fromState = submissionFromPageState();
if (fromState && !isAlreadyCaptured(fromState.submissionId)) {
console.log('[PrepPush] Immediate capture from page state (' + reason + ')');
handleAcceptedSubmission(fromState, 'api-fetch');
return;
}
const pageId = submissionIdFromPage();
if (pageId && !isAlreadyCaptured(pageId)) {
if (!canFetchSubmissionNow(pageId, 5000)) {
waitForAcceptedViaHrPolls(pageId, { urgent: true });
return;
}
const model = await fetchSubmissionModelById(pageId, true);
const sub = submissionFromModel(model);
if (sub) {
console.log('[PrepPush] Immediate capture from submission API (' + reason + ')');
handleAcceptedSubmission(sub, 'poll-watch');
return;
}
waitForAcceptedViaHrPolls(pageId, { urgent: true });
return;
}
waitForSubmissionIdThenWatch();
}
function ensureInterceptorReady() {
return new Promise((resolve) => {
if (!isExtensionAlive()) {
resolve(false);
return;
}
let attempts = 0;
const tryOnce = () => {
try {
chrome.runtime.sendMessage({ type: 'INJECT_PAGE_INTERCEPTOR' }, async () => {
const err = chrome.runtime.lastError?.message || '';
if (err && /invalidated|does not exist/i.test(err)) {
resolve(false);
return;
}
try {
await new Promise((r) => setTimeout(r, 280));
const p = await probePageInterceptor();
if (p.injected && (p.xhrHook || p.fetchTrap || p.fetchPollObserver)) {
ppLog('Interceptor ready');
resolve(true);
return;
}
if (++attempts < 5) {
setTimeout(tryOnce, 400);
return;
}
resolve(false);
} catch {
resolve(false);
}
});
} catch {
resolve(false);
}
};
tryOnce();
});
}
function clearWatching(submissionId) {
window.__preppushWatching?.delete(String(submissionId));
}
/**
* Backup status checks if the page hook misses Accepted (sub-second, not 10s).
*/
function waitForAcceptedViaHrPolls(submissionId, options = {}) {
if (window.top !== window) return;