Repository navigation
Expand file tree
/
Copy pathcontent_script.js
More file actions
4714 lines (4314 loc) · 253 KB
/
Copy pathcontent_script.js
File metadata and controls
4714 lines (4314 loc) · 253 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
// manifest에서 가장 먼저 동기 선언됩니다. 같은 확장의 isolated world에서만
// 공유하며, 페이지 전체를 감시하지 않고 실제 입력 이벤트의 경로만 확인합니다.
function lunaToolsIsProtectedInputEvent(event, { includeControls = false, includeActiveElement = true, allowNonEditableControls = false } = {}) {
if (String(document.designMode).toLowerCase() === 'on') return true;
const candidates = typeof event.composedPath === 'function' ? event.composedPath().slice() : [];
candidates.push(event.target);
if (includeActiveElement) candidates.push(document.activeElement);
const visited = new Set();
const inputRoles = new Set(['textbox', 'searchbox', 'combobox']);
if (!allowNonEditableControls) inputRoles.add('application');
const controlRoles = new Set([
'button', 'checkbox', 'switch', 'slider', 'spinbutton', 'grid', 'gridcell',
'listbox', 'option', 'menu', 'menubar', 'menuitem', 'menuitemcheckbox',
'menuitemradio', 'radio', 'radiogroup', 'tab', 'tablist', 'tree', 'treegrid', 'treeitem'
]);
while (candidates.length) {
const element = candidates.pop();
if (!(element instanceof Element) || visited.has(element)) continue;
visited.add(element);
const isButtonOrSlider = allowNonEditableControls && element.matches('input[type="button"], input[type="submit"], input[type="reset"], input[type="range"]');
const isProtectedInput = element.matches('input') && !isButtonOrSlider;
if (element.isContentEditable || isProtectedInput || element.matches('textarea, select, .CodeMirror, .codemirror, .monaco-editor, .ace_editor')) return true;
// Preserve focused-widget protection by default. Media shortcuts opt out while
// retaining editable-input checks, including the real focus inside Shadow DOM.
// Pointer gestures still use includeActiveElement:false for drag starting points.
if (!allowNonEditableControls && includeActiveElement && element instanceof HTMLElement && element.tabIndex >= 0 && (element === document.activeElement || element.matches(':focus'))) return true;
const editableValue = element.getAttribute('contenteditable');
if (editableValue !== null && editableValue.toLowerCase() !== 'false') return true;
const roles = String(element.getAttribute('role') || '').toLowerCase().split(/\s+/);
if (roles.some(role => inputRoles.has(role) || (includeControls && controlRoles.has(role)))) return true;
if (includeControls && element.matches('button, label, summary, video, audio, canvas, iframe, object, embed, [draggable="true"]')) return true;
candidates.push(element.parentElement || element.getRootNode?.().host);
let shadowRoot = element.shadowRoot;
if (!shadowRoot && element instanceof HTMLElement) {
try { shadowRoot = chrome.dom?.openOrClosedShadowRoot(element); } catch (_) {}
}
if (!shadowRoot) continue;
// closed Shadow DOM은 composedPath()에 내부 입력란을 노출하지 않습니다.
// 키보드는 실제 포커스, 포인터는 누른 위치를 확인합니다.
if (includeActiveElement) candidates.push(shadowRoot.activeElement);
if (Number.isFinite(event.clientX) && Number.isFinite(event.clientY)) {
try { candidates.push(shadowRoot.elementFromPoint?.(event.clientX, event.clientY)); } catch (_) {}
}
}
return false;
}
// Web Components가 미디어를 open/closed Shadow DOM 안에 숨겨도 PiP/영상 회전과
// 후속 미디어 기능이 같은 기준으로 실제 요소를 찾을 수 있게 합니다.
function lunaToolsGetAccessibleShadowRoot(element) {
if (!(element instanceof HTMLElement)) return null;
if (element.shadowRoot) return element.shadowRoot;
// Closed roots are most commonly hosted by Web Components. Avoid a costly
// extension-API bridge call for every ordinary element on very large pages.
const localName = String(element.localName || '');
if (!localName.includes('-') && !element.hasAttribute('is')) return null;
try {
return chrome.dom?.openOrClosedShadowRoot(element) || null;
} catch (_) {
return null;
}
}
function lunaToolsFindElementsAcrossShadowRoots(selector) {
const matches = [];
const roots = [document];
const visitedRoots = new WeakSet();
const visitedElements = new WeakSet();
for (let rootIndex = 0; rootIndex < roots.length; rootIndex += 1) {
const root = roots[rootIndex];
if (!root || visitedRoots.has(root)) continue;
visitedRoots.add(root);
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
let element = root.nodeType === Node.ELEMENT_NODE ? root : walker.nextNode();
while (element) {
if (!visitedElements.has(element)) {
visitedElements.add(element);
try {
if (element.matches(selector)) matches.push(element);
} catch (_) {
}
const shadowRoot = lunaToolsGetAccessibleShadowRoot(element);
if (shadowRoot && !visitedRoots.has(shadowRoot)) roots.push(shadowRoot);
}
element = walker.nextNode();
}
}
return matches;
}
// 클립보드 권한 실패가 늦게 돌아와도 사용자가 새로 선택한 입력란이나
// 복귀한 탭의 포커스를 숨은 textarea로 빼앗지 않도록 두 복사 기능이 공유합니다.
async function lunaToolsWriteTextToClipboard(text) {
const getFocusedElement = () => {
let element = document.activeElement;
const visited = new Set();
while (element && !visited.has(element)) {
visited.add(element);
let root = element.shadowRoot;
if (!root && element instanceof HTMLElement) {
try { root = chrome.dom?.openOrClosedShadowRoot(element); } catch (_) {}
}
if (!root?.activeElement) break;
element = root.activeElement;
}
return element;
};
const originalFocus = getFocusedElement();
const originalUrl = window.location.href;
let interactionChanged = false;
const cancelFallback = () => { interactionChanged = true; };
const onWindowBlur = event => { if (event.target === window) cancelFallback(); };
const pendingEvents = ['pointerdown', 'keydown', 'focusin', 'visibilitychange'];
for (const type of pendingEvents) document.addEventListener(type, cancelFallback, true);
window.addEventListener('blur', onWindowBlur);
window.addEventListener('pagehide', cancelFallback, true);
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(String(text));
return true;
}
} catch (_) {
} finally {
for (const type of pendingEvents) document.removeEventListener(type, cancelFallback, true);
window.removeEventListener('blur', onWindowBlur);
window.removeEventListener('pagehide', cancelFallback, true);
}
const isCurrentDocument = () => document.visibilityState !== 'hidden' &&
document.hasFocus() && window.location.href === originalUrl;
if (interactionChanged || !isCurrentDocument() || getFocusedElement() !== originalFocus) return false;
const selection = window.getSelection();
const ranges = [];
for (let index = 0; index < (selection?.rangeCount || 0); index += 1) {
ranges.push(selection.getRangeAt(index).cloneRange());
}
const inputSelection = Number.isInteger(originalFocus?.selectionStart)
? [originalFocus.selectionStart, originalFocus.selectionEnd, originalFocus.selectionDirection]
: null;
const textArea = document.createElement('textarea');
textArea.value = String(text);
textArea.setAttribute('readonly', '');
textArea.setAttribute('aria-hidden', 'true');
textArea.tabIndex = -1;
textArea.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;pointer-events:none!important;';
try {
document.documentElement.appendChild(textArea);
textArea.focus({ preventScroll: true });
// 모달의 포커스 트랩이 되돌린 포커스를 다시 강제로 가져오지 않습니다.
if (getFocusedElement() !== textArea) return false;
textArea.select();
return document.execCommand('copy');
} catch (_) {
return false;
} finally {
const ownsFocus = getFocusedElement() === textArea;
textArea.remove();
if (ownsFocus && isCurrentDocument() && originalFocus?.isConnected) {
try { originalFocus.focus({ preventScroll: true }); } catch (_) {}
if (getFocusedElement() === originalFocus) {
if (inputSelection) {
try { originalFocus.setSelectionRange(...inputSelection); } catch (_) {}
} else {
try {
selection?.removeAllRanges();
for (const range of ranges) {
if (range.startContainer.isConnected && range.endContainer.isConnected) selection.addRange(range);
}
} catch (_) {}
}
}
}
}
}
(async () => {
'use strict';
function normalizeHostname(value) {
return String(value || '').trim().toLowerCase().replace(/\.+$/, '');
}
function isLikelyHostRule(entry) {
let normalizedEntry = entry;
const authority = entry.split(/[/?#]/u, 1)[0];
// URL.hostname은 국제화 도메인을 ASCII로 반환합니다. 같은 URL 파서로
// 호스트 부분을 먼저 정규화하되 기존 ASCII 규칙·키워드 판별은 유지합니다.
if (/[^\x00-\x7F]/u.test(authority)) {
if (/[\s@\\]/u.test(authority)) return false;
try {
const parsed = new URL(`https://${authority}`);
if (!parsed.hostname || parsed.username || parsed.password) return false;
normalizedEntry = parsed.host + entry.slice(authority.length);
} catch (_) {
return false;
}
}
return (
/^[a-z0-9.-]+(?::\d+)?(?:[/?#].*)?$/i.test(normalizedEntry) &&
(
normalizedEntry.includes('.') ||
/^localhost(?::|[/?#]|$)/i.test(normalizedEntry) ||
/^\d{1,3}(?:\.\d{1,3}){3}(?::|[/?#]|$)/.test(normalizedEntry)
)
);
}
function getExplicitRulePort(entry, hasHttpScheme) {
const withoutScheme = hasHttpScheme ? entry.replace(/^https?:\/\//i, '') : entry;
const authority = withoutScheme.split(/[/?#]/u, 1)[0];
const portMatch = authority.match(/:(\d{1,5})$/u);
return portMatch ? String(Number(portMatch[1])) : '';
}
function getEffectiveUrlPort(url) {
if (url.port) return url.port;
if (url.protocol === 'http:') return '80';
if (url.protocol === 'https:') return '443';
return '';
}
function parseSiteRule(rawRule, { allowPath = false } = {}) {
const entry = String(rawRule || '').trim();
if (!entry) return null;
const hasHttpScheme = /^https?:\/\//i.test(entry);
if (!hasHttpScheme && !isLikelyHostRule(entry)) return null;
try {
const parsed = new URL(hasHttpScheme ? entry : `https://${entry}`);
const hostname = normalizeHostname(parsed.hostname);
if (!hostname) return null;
const pathname = allowPath && parsed.pathname && parsed.pathname !== '/'
? parsed.pathname.replace(/\/+$/, '')
: '';
return {
hostname,
protocol: hasHttpScheme ? parsed.protocol : '',
port: getExplicitRulePort(entry, hasHttpScheme),
// 차단 설정은 URL에 포함된 키워드도 허용합니다. URL 파서로
// 호스트 대소문자·국제화 도메인·기본 포트를 정규화한 문자열을
// 따로 보존해 경로·쿼리·해시의 나머지 글자도 매칭할 수 있게 합니다.
literalMatchText: hasHttpScheme ? parsed.href : parsed.href.replace(/^https:\/\//i, ''),
pathname,
search: allowPath ? parsed.search : '',
hash: allowPath && parsed.hash ? parsed.hash.replace(/\/+$/, '') : ''
};
} catch (_) {
return null;
}
}
function matchesHostnameRule(currentHostname, ruleHostname) {
const hostname = normalizeHostname(currentHostname);
const rule = normalizeHostname(ruleHostname);
return Boolean(rule) && (hostname === rule || hostname.endsWith(`.${rule}`));
}
function matchesLockedSiteRule(currentUrl, rawRule) {
const rule = parseSiteRule(rawRule);
return Boolean(
rule &&
matchesHostnameRule(currentUrl.hostname, rule.hostname) &&
(!rule.port || getEffectiveUrlPort(currentUrl) === rule.port)
);
}
function includesSearchParameters(currentSearch, expectedSearch) {
const currentParams = new URLSearchParams(currentSearch);
const expectedParams = new URLSearchParams(expectedSearch);
for (const key of new Set(expectedParams.keys())) {
const unmatchedCurrentValues = currentParams.getAll(key);
let wildcardCount = 0;
for (const expectedValue of expectedParams.getAll(key)) {
// A rule such as "?v=" is commonly used as a URL-prefix rule and
// means that the parameter must exist, regardless of its value.
// Match specific values first: consuming a wildcard immediately can
// steal the only occurrence needed by a later specific condition.
// Count wildcards separately to retain duplicate-key multiplicity.
if (expectedValue === '') {
wildcardCount += 1;
continue;
}
const matchingIndex = unmatchedCurrentValues.indexOf(expectedValue);
if (matchingIndex === -1) return false;
unmatchedCurrentValues.splice(matchingIndex, 1);
}
if (unmatchedCurrentValues.length < wildcardCount) return false;
}
return true;
}
function matchesBlockedSiteRule(currentUrl, rawRule) {
const ruleText = String(rawRule || '').trim();
if (!ruleText) return false;
const structuredRule = parseSiteRule(ruleText, { allowPath: true });
if (!structuredRule) {
// Backward compatibility: non-host entries still work as URL keywords.
return currentUrl.href.includes(ruleText);
}
if (!matchesHostnameRule(currentUrl.hostname, structuredRule.hostname)) {
return false;
}
if (structuredRule.protocol && currentUrl.protocol !== structuredRule.protocol) {
return false;
}
if (structuredRule.port && getEffectiveUrlPort(currentUrl) !== structuredRule.port) {
return false;
}
// 설정 화면의 URL 키워드가 실제 주소에 연속해서 들어 있으면
// /board-view, ?v=abcdef, #part1처럼 뒤에 글자가 더 있어도 차단합니다.
// 위의 호스트·스킴·포트 검사는 먼저 통과해야 하므로 다른 도메인을
// 단순 부분 문자열만으로 차단하지 않습니다. 그 밖의 경우 기존의
// 경로 경계·쿼리 순서 무관 매칭을 그대로 사용합니다.
if (structuredRule.literalMatchText && currentUrl.href.includes(structuredRule.literalMatchText)) {
return true;
}
if (structuredRule.pathname) {
const currentPath = (currentUrl.pathname.replace(/\/+$/, '') || '/');
const expectedPath = structuredRule.pathname;
if (currentPath !== expectedPath && !currentPath.startsWith(`${expectedPath}/`)) {
return false;
}
}
// A blocked URL rule describes a URL prefix/keyword. Extra query
// parameters (including a different order) must not bypass the rule.
if (structuredRule.search && !includesSearchParameters(currentUrl.search, structuredRule.search)) {
return false;
}
if (structuredRule.hash) {
const currentHash = currentUrl.hash.replace(/\/+$/, '');
const expectedHash = structuredRule.hash;
if (currentHash !== expectedHash && !currentHash.startsWith(`${expectedHash}/`)) {
return false;
}
}
return true;
}
const SITE_SETTINGS_RECHECK_INTERVAL_MS = 1000;
let siteSettingsUnloadHandler = null;
let siteSettingsRecheckerInitialized = false;
let lastSiteSettingsHref = '';
let siteSettingsCheckGeneration = 0;
function isCurrentSiteSettingsCheck(checkGeneration, checkedHref) {
return checkGeneration === siteSettingsCheckGeneration && window.location.href === checkedHref;
}
function setSiteLockEnabled(isEnabled) {
if (isEnabled) {
if (!siteSettingsUnloadHandler) {
siteSettingsUnloadHandler = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', siteSettingsUnloadHandler);
}
return;
}
if (siteSettingsUnloadHandler) {
window.removeEventListener('beforeunload', siteSettingsUnloadHandler);
siteSettingsUnloadHandler = null;
}
}
async function applySiteSettingsAndCheckIfBlocked() {
if (window.self !== window.top) {
return false;
}
const checkGeneration = ++siteSettingsCheckGeneration;
let currentUrl;
try {
currentUrl = new URL(window.location.href);
lastSiteSettingsHref = currentUrl.href;
} catch (_) {
if (checkGeneration === siteSettingsCheckGeneration) {
setSiteLockEnabled(false);
}
return false;
}
const checkedHref = currentUrl.href;
try {
const { lockedSites = [], blockedSites = [] } = await chrome.storage.sync.get(['lockedSites', 'blockedSites']);
// A storage read can finish after an SPA navigation or a newer settings check.
// Never apply a result that was calculated for an earlier URL/state.
if (!isCurrentSiteSettingsCheck(checkGeneration, checkedHref)) {
return false;
}
if (Array.isArray(blockedSites) && blockedSites.some(rule => matchesBlockedSiteRule(currentUrl, rule))) {
setSiteLockEnabled(false);
window.location.replace('about:blank');
return true;
}
const shouldLock = Array.isArray(lockedSites) && lockedSites.some(rule => matchesLockedSiteRule(currentUrl, rule));
setSiteLockEnabled(shouldLock);
} catch (e) {
// 설정 조회가 실패했을 때 이전 검사에서 등록한 beforeunload 잠금이 남으면
// 사용자가 잠금을 해제했는데도 페이지 이동/닫기가 계속 방해될 수 있습니다.
// 현재 URL/검사 세대가 여전히 유효할 때만 fail-safe로 해제합니다.
if (isCurrentSiteSettingsCheck(checkGeneration, checkedHref)) {
setSiteLockEnabled(false);
}
}
return false;
}
function initializeSiteSettingsRechecks() {
if (siteSettingsRecheckerInitialized || window.self !== window.top) {
return;
}
siteSettingsRecheckerInitialized = true;
lastSiteSettingsHref = window.location.href;
const recheckSiteSettings = () => {
void applySiteSettingsAndCheckIfBlocked();
};
const recheckIfUrlChanged = () => {
const currentHref = window.location.href;
if (currentHref !== lastSiteSettingsHref) {
lastSiteSettingsHref = currentHref;
recheckSiteSettings();
}
};
window.addEventListener('pageshow', recheckSiteSettings, true);
window.addEventListener('popstate', recheckSiteSettings, true);
window.addEventListener('hashchange', recheckSiteSettings, true);
document.addEventListener('visibilitychange', recheckIfUrlChanged, true);
setInterval(recheckIfUrlChanged, SITE_SETTINGS_RECHECK_INTERVAL_MS);
try {
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'sync') return;
if (changes.lockedSites || changes.blockedSites) {
recheckSiteSettings();
}
});
} catch (_) {
}
// The URL may have changed while the document-start storage read was pending,
// before the SPA listeners above existed. Revalidate the current URL once now.
recheckSiteSettings();
}
const isBlocked = await applySiteSettingsAndCheckIfBlocked();
if (isBlocked) {
return;
}
initializeSiteSettingsRechecks();
class MouseGestureHandler {
static MIN_DRAG_DISTANCE_SQ = 100;
static MIN_FINAL_DISTANCE_SQ = 625;
static MESSAGE_ACTION = 'perform-gesture';
static RIGHT_MOUSE_BUTTON = 2;
static RIGHT_MOUSE_BUTTON_MASK = 2;
constructor() {
this.isMouseDown = false;
this.startX = 0;
this.startY = 0;
this.didMove = false;
this.isTrustedSequence = false;
this.suppressNextContextMenu = false;
this.startEvent = null;
this._bindEventHandlers();
this._initializeEventListeners();
}
_bindEventHandlers() {
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleContextMenu = this.handleContextMenu.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleLifecycleReset = this.handleLifecycleReset.bind(this);
}
_initializeEventListeners() {
this.mouseMoveOptions = { capture: true, passive: true };
this.blurOptions = { capture: true, passive: true };
this.captureOptions = { capture: true };
window.addEventListener('mousedown', this.handleMouseDown, this.captureOptions);
window.addEventListener('mousemove', this.handleMouseMove, this.mouseMoveOptions);
window.addEventListener('mouseup', this.handleMouseUp, this.captureOptions);
window.addEventListener('contextmenu', this.handleContextMenu, this.captureOptions);
window.addEventListener('blur', this.handleBlur, this.blurOptions);
window.addEventListener('pagehide', this.handleLifecycleReset, this.blurOptions);
window.addEventListener('pageshow', this.handleLifecycleReset, this.blurOptions);
window.addEventListener('pointercancel', this.handleLifecycleReset, this.blurOptions);
document.addEventListener('visibilitychange', this.handleLifecycleReset, this.blurOptions);
document.addEventListener('freeze', this.handleLifecycleReset, this.blurOptions);
document.addEventListener('resume', this.handleLifecycleReset, this.blurOptions);
}
_resetPointerState() {
this.isMouseDown = false;
this.didMove = false;
this.isTrustedSequence = false;
this.startEvent = null;
}
_resetState() {
this._resetPointerState();
this.suppressNextContextMenu = false;
}
handleMouseDown(event) {
if (!event.isTrusted) return;
this._resetState();
if (event.button !== MouseGestureHandler.RIGHT_MOUSE_BUTTON ||
event.buttons !== MouseGestureHandler.RIGHT_MOUSE_BUTTON_MASK ||
event.defaultPrevented || event.ctrlKey || event.altKey || event.shiftKey || event.metaKey ||
lunaToolsIsProtectedInputEvent(event, { includeControls: true, includeActiveElement: false })) return;
this.isMouseDown = true;
this.isTrustedSequence = true;
this.startEvent = event;
this.startX = event.clientX;
this.startY = event.clientY;
this.didMove = false;
this.suppressNextContextMenu = false;
}
handleMouseMove(event) {
if (!event.isTrusted || !this.isTrustedSequence) return;
if (!this.isMouseDown) return;
if (this.startEvent?.defaultPrevented || document.visibilityState === 'hidden' || !document.hasFocus()) {
this._resetState();
return;
}
// 페이지 밖에서 오른쪽 mouseup이 유실되어도 다음 실제 이동에서
// 오래된 제스처 상태가 남지 않도록 현재 버튼 상태로 복구한다.
if ((event.buttons & MouseGestureHandler.RIGHT_MOUSE_BUTTON_MASK) === 0) {
this._resetState();
return;
}
if (this.didMove) return;
const deltaX = event.clientX - this.startX;
const deltaY = event.clientY - this.startY;
if ((deltaX ** 2 + deltaY ** 2) > MouseGestureHandler.MIN_DRAG_DISTANCE_SQ) {
this.didMove = true;
}
}
handleMouseUp(event) {
if (!event.isTrusted || !this.isTrustedSequence) return;
if (!this.isMouseDown) return;
if (this.startEvent?.defaultPrevented || document.visibilityState === 'hidden' || !document.hasFocus()) {
this._resetState();
return;
}
if (event.button !== MouseGestureHandler.RIGHT_MOUSE_BUTTON) {
this._resetState();
return;
}
const hadGestureLikeDrag = this.didMove;
const gestureDirection = this._determineGestureDirection(event.clientX, event.clientY);
if (gestureDirection) {
this.suppressNextContextMenu = true;
this._sendGestureMessage(gestureDirection);
} else if (hadGestureLikeDrag) {
this.suppressNextContextMenu = true;
}
this._resetPointerState();
}
_determineGestureDirection(endX, endY) {
const deltaX = endX - this.startX;
const deltaY = endY - this.startY;
const distanceSq = deltaX ** 2 + deltaY ** 2;
if (distanceSq < MouseGestureHandler.MIN_FINAL_DISTANCE_SQ) {
return null;
}
if (Math.abs(deltaY) > Math.abs(deltaX)) {
return deltaY < 0 ? 'U' : 'D';
}
return deltaX > 0 ? 'R' : 'L';
}
_sendGestureMessage(gesture) {
try {
chrome.runtime.sendMessage({ action: MouseGestureHandler.MESSAGE_ACTION, gesture });
} catch (error) {
}
}
handleContextMenu(event) {
if (!event.isTrusted) return;
if (this.startEvent?.defaultPrevented) {
this._resetState();
return;
}
// Some platforms dispatch contextmenu on right-button down, before any
// drag or mouseup. Keep tracking that sequence instead of discarding it;
// an ordinary early right click must still be allowed to open its menu.
if (this.isMouseDown) {
if (this.didMove || this.suppressNextContextMenu) event.preventDefault();
return;
}
if (this.didMove || this.suppressNextContextMenu) {
event.preventDefault();
}
this._resetState();
}
handleBlur(event) {
if (!event.isTrusted) return;
if (this.isMouseDown || this.suppressNextContextMenu) {
this._resetState();
}
}
handleLifecycleReset(event) {
if (event?.isTrusted === false) return;
if (this.isMouseDown || this.suppressNextContextMenu) {
this._resetState();
}
}
destroy() {
window.removeEventListener('mousedown', this.handleMouseDown, this.captureOptions);
window.removeEventListener('mousemove', this.handleMouseMove, this.mouseMoveOptions);
window.removeEventListener('mouseup', this.handleMouseUp, this.captureOptions);
window.removeEventListener('contextmenu', this.handleContextMenu, this.captureOptions);
window.removeEventListener('blur', this.handleBlur, this.blurOptions);
window.removeEventListener('pagehide', this.handleLifecycleReset, this.blurOptions);
window.removeEventListener('pageshow', this.handleLifecycleReset, this.blurOptions);
window.removeEventListener('pointercancel', this.handleLifecycleReset, this.blurOptions);
document.removeEventListener('visibilitychange', this.handleLifecycleReset, this.blurOptions);
document.removeEventListener('freeze', this.handleLifecycleReset, this.blurOptions);
document.removeEventListener('resume', this.handleLifecycleReset, this.blurOptions);
}
}
const userAgent = navigator.userAgent;
const browsersToDisableGesturesFor = [
"Edg/", "OPR/", "Whale/", "Vivaldi/"
];
const shouldDisableGestures = browsersToDisableGesturesFor.some(browserIdentifier =>
userAgent.includes(browserIdentifier)
);
if (!shouldDisableGestures) {
new MouseGestureHandler();
}
if (window.self === window.top) {
const KB_NAV_CONFIG = Object.freeze({
cache: { MAX_SIZE: 100, MAX_AGE_MS: 30 * 60 * 1000 },
navigation: {
RESET_DELAY_MS: 150,
NAVIGATION_FALLBACK_RESET_MS: 2000,
MIN_PAGE: 1,
MAX_PAGE: 9999,
DEBOUNCE_DELAY_MS: 100,
ALLOWED_PROTOCOLS: new Set(['http:', 'https:'])
},
observer: {
TARGET_SELECTORS: ['nav[aria-label="pagination"]', '.pagination', '#pagination'],
FALLBACK_TARGET_SELECTORS: ['main', '#main', '#content', 'article', 'body'],
DEBOUNCE_DELAY_MS: 100,
MAX_OBSERVE_TIME_MS: 30 * 1000,
REACTIVATION_INTERVAL_MS: 5 * 60 * 1000,
REACTIVATION_THROTTLE_MS: 1000
},
patterns: {
pageQueryKeys: ['page', 'po', 'p'],
pagePath: /(?:^|\/)page\/(\d{1,4})(?=[/?#]|$)/i,
datePath: /\/(\d{4})\/(\d{1,2})\/(\d{1,2})(\/?)(?=[?#]|$)/,
datePathPrefix: /\/\d{4}\/\d{1,2}\/\d{1,2}(?=\/|[?#]|$)/,
// Intentional: nested numeric path segments (for example, /products/42/reviews)
// are valid navigation targets for this feature. Do not restrict this to root paths.
numericPath: /\/(\d{1,4})(?:[/?#]|$)/i,
ignore: [
/\/status\/\d{10,}/i,
/\/commit\/\w{7,40}/i,
/\/\d{8,}/i
]
}
});
const KB_NAV_Utils = {
debounce(func, waitMs) {
let timeoutId;
const debounced = function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), waitMs);
};
debounced.cancel = () => clearTimeout(timeoutId);
return debounced;
},
throttle(func, waitMs) {
let throttling = false;
let lastArgs = null;
let timeoutId = null;
function throttled(...args) {
lastArgs = args;
if (!throttling) {
throttling = true;
func.apply(this, lastArgs);
lastArgs = null;
timeoutId = setTimeout(() => {
throttling = false;
if (lastArgs) throttled.apply(this, lastArgs);
}, waitMs);
}
}
throttled.cancel = () => {
clearTimeout(timeoutId);
throttling = false;
lastArgs = null;
};
return throttled;
},
normalizeNavigationUrl(candidateUrl, baseUrl = window.location.href) {
if (!candidateUrl) return null;
try {
const parsed = new URL(String(candidateUrl), baseUrl);
if (!KB_NAV_CONFIG.navigation.ALLOWED_PROTOCOLS.has(parsed.protocol) || !parsed.hostname) return null;
if (parsed.username || parsed.password) return null;
return parsed.href;
} catch (_) {
return null;
}
},
isSafeNavigableUrl(candidateUrl) {
return this.normalizeNavigationUrl(candidateUrl) !== null;
}
};
class KB_NAV_LRUCache {
constructor(maxSize, maxAgeMs) {
this.maxSize = maxSize;
this.maxAgeMs = maxAgeMs;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return undefined;
const item = this.cache.get(key);
if (Date.now() - item.timestamp > this.maxAgeMs) {
this.cache.delete(key);
return undefined;
}
this.cache.delete(key);
this.cache.set(key, item);
return item.value;
}
set(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.maxSize) {
const leastUsedKey = this.cache.keys().next().value;
this.cache.delete(leastUsedKey);
}
this.cache.set(key, { value, timestamp: Date.now() });
}
clear() { this.cache.clear(); }
removeExpired() {
const now = Date.now();
for (const [key, item] of this.cache.entries()) {
if (now - item.timestamp > this.maxAgeMs) {
this.cache.delete(key);
}
}
}
}
class KB_NAV_UrlPageFinder {
constructor() {
this.urlPatternCache = new KB_NAV_LRUCache(KB_NAV_CONFIG.cache.MAX_SIZE, KB_NAV_CONFIG.cache.MAX_AGE_MS);
this.cleanupInterval = setInterval(() => this.urlPatternCache.removeExpired(), KB_NAV_CONFIG.cache.MAX_AGE_MS / 2);
}
_createPagePatternInfo(url, pattern) {
const match = pattern.exec(url);
if (!match || !match[1]) return null;
const pageNumber = parseInt(match[1], 10);
if (isNaN(pageNumber) || pageNumber < KB_NAV_CONFIG.navigation.MIN_PAGE || pageNumber > KB_NAV_CONFIG.navigation.MAX_PAGE) {
return null;
}
return {
kind: 'page',
regex: pattern,
currentPage: pageNumber,
originalMatch: match[0],
originalPageText: match[1]
};
}
_createDatePatternInfo(url) {
const match = KB_NAV_CONFIG.patterns.datePath.exec(url);
if (!match) return undefined;
const year = parseInt(match[1], 10);
const month = parseInt(match[2], 10);
const day = parseInt(match[3], 10);
if (year < 1000 || year > 9999 || month < 1 || month > 12 || day < 1 || day > 31) {
return null;
}
const date = new Date(Date.UTC(year, month - 1, day));
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
return null;
}
return {
kind: 'date',
year,
month,
day,
monthWidth: match[2].length,
dayWidth: match[3].length,
trailingSlash: match[4],
originalMatch: match[0]
};
}
findPagePattern(url) {
const cachedResult = this.urlPatternCache.get(url);
if (cachedResult !== undefined) return cachedResult;
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch (_) {
this.urlPatternCache.set(url, null);
return null;
}
// Read only top-level query parameters. A nested URL such as
// ?redirect=https://example.com/?page=2 must not become pagination.
const queryEntries = Array.from(parsedUrl.searchParams.entries());
for (const expectedKey of KB_NAV_CONFIG.patterns.pageQueryKeys) {
const queryEntry = queryEntries.find(([key]) => key.toLowerCase() === expectedKey);
if (!queryEntry) continue;
const [queryKey, rawPageNumber] = queryEntry;
if (!/^\d{1,4}$/.test(rawPageNumber)) continue;
const currentPage = parseInt(rawPageNumber, 10);
if (currentPage < KB_NAV_CONFIG.navigation.MIN_PAGE || currentPage > KB_NAV_CONFIG.navigation.MAX_PAGE) continue;
const patternInfo = {
kind: 'query',
queryKey,
currentPage,
pageWidth: rawPageNumber.length
};
this.urlPatternCache.set(url, patternInfo);
return patternInfo;
}
const pathname = parsedUrl.pathname;
// Path patterns must only inspect the pathname. Otherwise a URL placed
// inside an unrelated query value (for example ?redirect=/page/2)
// can be mistaken for the current page's own pagination route.
const pathPagePatternInfo = this._createPagePatternInfo(pathname, KB_NAV_CONFIG.patterns.pagePath);
if (pathPagePatternInfo) {
this.urlPatternCache.set(url, pathPagePatternInfo);
return pathPagePatternInfo;
}
// 연/월/일 경로는 가장 앞의 연도를 일반 페이지 번호로 오인하지 않고
// 실제 달력 날짜로 처리합니다. 잘못된 날짜도 숫자 경로로 재해석하지 않습니다.
const datePatternInfo = this._createDatePatternInfo(pathname);
if (datePatternInfo !== undefined) {
this.urlPatternCache.set(url, datePatternInfo);
return datePatternInfo;
}
// A common article URL such as /2026/07/02/post-name contains a date
// but is not itself a day-by-day archive URL. Never reinterpret its
// leading year as a generic page number; allow rel=next/prev discovery
// to handle the page instead.
if (KB_NAV_CONFIG.patterns.datePathPrefix.test(pathname)) {
this.urlPatternCache.set(url, null);
return null;
}
const numericPatternInfo = this._createPagePatternInfo(pathname, KB_NAV_CONFIG.patterns.numericPath);
if (numericPatternInfo) {
this.urlPatternCache.set(url, numericPatternInfo);
return numericPatternInfo;
}
this.urlPatternCache.set(url, null);
return null;
}
generateNewUrl(currentUrl, patternInfo, direction) {
let parsedUrl;
try {
parsedUrl = new URL(currentUrl);
} catch (_) {
return currentUrl;
}
if (patternInfo.kind === 'date') {
const { year, month, day, monthWidth, dayWidth, trailingSlash, originalMatch } = patternInfo;
const nextDate = new Date(Date.UTC(year, month - 1, day));
nextDate.setUTCDate(nextDate.getUTCDate() + direction);
const nextYear = nextDate.getUTCFullYear();
if (nextYear < 1000 || nextYear > 9999) return currentUrl;
const nextMonth = String(nextDate.getUTCMonth() + 1).padStart(monthWidth, '0');
const nextDay = String(nextDate.getUTCDate()).padStart(dayWidth, '0');
const nextDatePath = `/${String(nextYear).padStart(4, '0')}/${nextMonth}/${nextDay}${trailingSlash}`;
parsedUrl.pathname = parsedUrl.pathname.replace(originalMatch, nextDatePath);
return parsedUrl.href;
}
if (patternInfo.kind === 'query') {
const { currentPage, queryKey, pageWidth } = patternInfo;
const newPage = Math.min(
KB_NAV_CONFIG.navigation.MAX_PAGE,
Math.max(KB_NAV_CONFIG.navigation.MIN_PAGE, currentPage + direction)
);
if (newPage === currentPage) return currentUrl;
parsedUrl.searchParams.set(queryKey, String(newPage).padStart(pageWidth, '0'));
return parsedUrl.href;
}
const { currentPage, originalMatch, originalPageText } = patternInfo;
let newPage = currentPage + direction;
newPage = Math.max(KB_NAV_CONFIG.navigation.MIN_PAGE, newPage);
newPage = Math.min(KB_NAV_CONFIG.navigation.MAX_PAGE, newPage);
if (newPage === currentPage) return currentUrl;
const newPageText = String(newPage).padStart(originalPageText.length, '0');
const newPageStringInMatch = originalMatch.replace(originalPageText, newPageText);
// A terminal path such as /192 can also occur at the start of an IP
// address. Restrict replacement to pathname so pagination cannot alter
// the host, port, query, or fragment.
parsedUrl.pathname = parsedUrl.pathname.replace(originalMatch, newPageStringInMatch);
return parsedUrl.href;
}
shouldIgnoreUrl(url) {
return KB_NAV_CONFIG.patterns.ignore.some(pattern => pattern.test(url));
}
clearCache() { this.urlPatternCache.clear(); }
destroy() {
clearInterval(this.cleanupInterval);
this.clearCache();
}
}
class KB_NAV_DomLinkFinder {
constructor() {
this.cachedLinks = null;
this.observer = null;
this.observerTarget = null;
this.isObserving = false;
this.stopLifecycleTimer = null;
this.reactivationInterval = null;
this.throttledReactivateObserver = null;