-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBonusVarsler.user.js
More file actions
3252 lines (3114 loc) · 157 KB
/
BonusVarsler.user.js
File metadata and controls
3252 lines (3114 loc) · 157 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
// ==UserScript==
// @name BonusVarsler (for Trumf, SAS, OBOS, NAF, LOfavør, DNB, re:member++)
// @namespace http://tampermonkey.net/
// @version 9.0
// @description Varsler om bonuser, EuroBonus-poeng og cashback fra Trumf, SAS, OBOS, NAF, LOfavør, re:member, DNB og andre når du besøker nettsider som tilbyr dette. Norsk utvidelse.
// @author kristofferR
// @match *://*/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_xmlhttpRequest
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.xmlHttpRequest
// @grant GM_setClipboard
// @connect raw.githubusercontent.com
// @run-at document-start
// @downloadURL https://github.com/kristofferR/BonusVarsler/raw/main/BonusVarsler.user.js
// @updateURL https://github.com/kristofferR/BonusVarsler/raw/main/BonusVarsler.user.js
// @homepageURL https://github.com/kristofferR/BonusVarsler
// ==/UserScript==
(() => {
// src/storage/local-session-storage.ts
var LocalSessionStorage = class {
get(key) {
try {
return sessionStorage.getItem(key);
} catch {
return null;
}
}
set(key, value) {
try {
sessionStorage.setItem(key, value);
} catch {
}
}
};
var localSessionStorageInstance = null;
function getLocalSessionStorage() {
if (!localSessionStorageInstance) {
localSessionStorageInstance = new LocalSessionStorage();
}
return localSessionStorageInstance;
}
// src/storage/gm-storage.ts
var GMStorage = class {
async get(key, defaultValue) {
try {
if (typeof GM !== "undefined" && GM.getValue) {
const value = await GM.getValue(key, defaultValue);
return value;
} else if (typeof GM_getValue === "function") {
return GM_getValue(key, defaultValue);
}
return defaultValue;
} catch {
return defaultValue;
}
}
async set(key, value) {
try {
if (typeof GM !== "undefined" && GM.setValue) {
await GM.setValue(key, value);
} else if (typeof GM_setValue === "function") {
GM_setValue(key, value);
}
} catch {
}
}
async remove(keys) {
try {
if (typeof GM !== "undefined" && GM.deleteValue) {
await Promise.all(keys.map((key) => GM.deleteValue(key)));
} else if (typeof GM_deleteValue === "function") {
for (const key of keys) {
GM_deleteValue(key);
}
}
} catch {
}
}
};
var gmStorageInstance = null;
function getGMStorage() {
if (!gmStorageInstance) {
gmStorageInstance = new GMStorage();
}
return gmStorageInstance;
}
function getSessionStorage() {
return getLocalSessionStorage();
}
var getGMSessionStorage = getSessionStorage;
// src/network/gm-fetch.ts
function gmFetch(url, timeout = 1e4) {
return new Promise((resolve, reject) => {
const details = {
method: "GET",
url,
timeout,
onload: (response) => {
resolve({
ok: response.status >= 200 && response.status < 300,
status: response.status,
data: response.responseText
});
},
onerror: () => reject(new Error("Network error")),
ontimeout: () => reject(new Error("Timeout"))
};
if (typeof GM !== "undefined" && GM.xmlHttpRequest) {
GM.xmlHttpRequest(details);
} else if (typeof GM_xmlhttpRequest === "function") {
GM_xmlhttpRequest(details);
} else {
reject(new Error("GM.xmlHttpRequest not available"));
}
});
}
var GMFetch = class {
async fetchJSON(url) {
try {
const response = await gmFetch(url);
if (!response.ok) {
return null;
}
return JSON.parse(response.data);
} catch {
return null;
}
}
async fetchFeed(primaryUrl, fallbackUrl) {
const primary = await this.fetchJSON(primaryUrl);
if (primary) {
return primary;
}
if (fallbackUrl) {
const fallback = await this.fetchJSON(fallbackUrl);
if (fallback) {
return fallback;
}
}
await new Promise((resolve) => setTimeout(resolve, 1500));
return this.fetchJSON(primaryUrl);
}
async checkUrlBlocked(url) {
try {
await fetch(url, { mode: "no-cors" });
return false;
} catch {
return true;
}
}
};
var instance = null;
function getGMFetch() {
if (!instance) {
instance = new GMFetch();
}
return instance;
}
// src/i18n/static-i18n.ts
var NORWEGIAN_MESSAGES = {
// Notification
cashbackAt: { message: "bonus hos $STORE$", placeholders: { store: { content: "$1" } } },
serviceBonusAt: {
message: "$SERVICE$-bonus hos $STORE$",
placeholders: {
service: { content: "$1" },
store: { content: "$2" }
}
},
clickToGetBonus: { message: "F\xE5 $SERVICE$ bonus", placeholders: { service: { content: "$1" } } },
getServiceBonus: { message: "F\xE5 $SERVICE$-bonus", placeholders: { service: { content: "$1" } } },
thisStore: { message: "denne butikken" },
rememberTo: { message: "Husk \xE5:" },
disableAdblockers: { message: "Deaktivere uBlock/AdGuard Home/Pi-Hole" },
acceptAllCookies: { message: "Akseptere alle cookies" },
emptyCart: { message: "T\xF8mme handlevognen" },
rememberToUse: { message: "Husk \xE5 bruke lenken under f\xF8r du handler!" },
dontShowOnThisSite: { message: "Ikke vis p\xE5 denne siden" },
hideOnThisSite: { message: "Skjul p\xE5 denne siden" },
aboutExtension: { message: "Om denne utvidelsen" },
purchaseRegistered: { message: "Hvis alt ble gjort riktig, skal kj\xF8pet ha blitt registrert." },
adblockerDetected: { message: "Adblocker funnet!" },
checkingAdblock: { message: "Sjekker..." },
checkAdblockAgain: { message: "Sjekk p\xE5 nytt" },
trackingUnavailable: { message: "Sporing utilgjengelig" },
adblockWarning: { message: "Adblock oppdaget!" },
adblockNote: { message: "Du m\xE5 skru av adblock for at sporingen skal fungere." },
// DNB code-based
dnbCodeLabel: { message: "Rabattkode:" },
dnbInstruction1: { message: "Kopier rabattkoden over" },
dnbInstruction2: { message: "G\xE5 til handlekurven og skriv inn koden" },
dnbInstruction3: { message: "Handelen registreres automatisk" },
codeCopied: { message: "Kopiert!" },
copyCode: { message: "Kopier kode" },
copyFailed: { message: "Kopiering feilet" },
openLink: { message: "\xC5pne lenke" },
// Reminder
importantReminder: { message: "Viktig p\xE5minnelse!" },
reminderMessage: { message: "Husk \xE5 deaktivere adblock f\xF8r du handler. Sporingen kan blokkeres hvis adblock er aktivert." },
reminderAdblockWarning: { message: "Hvis handelen ikke registreres kan det skyldes adblock." },
reminderTip: { message: "Tips: Test at lenken fungerer ved \xE5 klikke og se at du blir sendt videre." },
// Settings
settings: { message: "Innstillinger" },
appearance: { message: "Utseende" },
theme: { message: "Tema" },
themeLight: { message: "Lys" },
themeDark: { message: "M\xF8rk" },
themeSystem: { message: "Auto" },
position: { message: "Posisjon" },
defaultPosition: { message: "Posisjon" },
startMinimized: { message: "Start minimert" },
hiddenSites: { message: "Skjulte sider" },
noHiddenSites: { message: "Ingen skjulte sider" },
hiddenSitesCount: { message: "$COUNT$ skjulte sider", placeholders: { count: { content: "$1" } } },
hiddenSitesCountPlural: {
message: "$COUNT$ sider skjult",
placeholders: { count: { content: "$1" } }
},
reset: { message: "Nullstill" },
resetHiddenSites: { message: "Tilbakestill" },
back: { message: "\u2190 Tilbake" },
services: { message: "Tjenester" },
selectServices: { message: "Velg bonustjenester" },
saveServices: { message: "Lagre" },
comingSoon: { message: "(kommer snart)" },
// Aria labels
ariaNotificationLabel: { message: "Bonusvarsel" },
ariaReminderLabel: { message: "P\xE5minnelse" },
ariaClose: { message: "Lukk" },
ariaMinimize: { message: "Minimer" },
// Info-type reminder
infoReminderTitle: { message: "P\xE5minnelse" },
infoReminderMessage: {
message: "Logg inn p\xE5 $SERVICE$ for \xE5 se rabattkoden din.",
placeholders: {
service: { content: "$1" }
}
},
// Info-type (OBOS etc.)
serviceDiscountAt: {
message: "$SERVICE$-rabatt hos $STORE$",
placeholders: {
service: { content: "$1" },
store: { content: "$2" }
}
},
readMoreAboutDiscount: { message: "Les mer om rabatten" },
infoInstruction1: { message: "Vis at du er medlem" },
infoInstruction2: { message: "Sjekk vilk\xE5rene for rabatten" },
// Confirmation
siteHidden: { message: "Varsler skjult for $SITE$", placeholders: { site: { content: "$1" } } }
};
var StaticI18n = class {
messages = NORWEGIAN_MESSAGES;
async loadMessages(_lang) {
}
getMessage(key, substitutions) {
const entry = this.messages[key];
if (!entry || !entry.message) {
return key;
}
let msg = entry.message;
if (substitutions !== void 0) {
const subs = Array.isArray(substitutions) ? substitutions : [substitutions];
subs.forEach((sub, index) => {
const placeholder = `$${index + 1}`;
msg = msg.replace(placeholder, sub);
if (entry.placeholders) {
for (const [name, config] of Object.entries(entry.placeholders)) {
if (config.content === placeholder) {
msg = msg.replace(new RegExp(`\\$${name.toUpperCase()}\\$`, "g"), sub);
}
}
}
});
}
return msg;
}
};
var instance2 = null;
function getStaticI18n() {
if (!instance2) {
instance2 = new StaticI18n();
}
return instance2;
}
// src/config/constants.ts
var CONFIG = {
feedUrl: "https://raw.githubusercontent.com/kristofferR/BonusVarsler/main/sitelist.json",
cacheDuration: 48 * 60 * 60 * 1e3,
// 48 hours
messageDuration: 10 * 60 * 1e3,
// 10 minutes
pageVisitsBeforeCooldown: 3,
// Start cooldown after this many page visits per site
maxRetries: 5,
retryDelays: [100, 500, 1e3, 2e3, 4e3],
// Exponential backoff
adblockTimeout: 3e3
// 3 seconds timeout for adblock checks
};
var STORAGE_KEYS = {
feedData: "BonusVarsler_FeedData_v1",
feedTime: "BonusVarsler_FeedTime_v1",
hostIndex: "BonusVarsler_HostIndex_v1",
hiddenSites: "BonusVarsler_HiddenSites",
blacklistedSites: "BonusVarsler_BlacklistedSites",
theme: "BonusVarsler_Theme",
startMinimized: "BonusVarsler_StartMinimized",
position: "BonusVarsler_Position",
sitePositions: "BonusVarsler_SitePositions",
reminderShown: "BonusVarsler_ReminderShown",
language: "BonusVarsler_Language",
enabledServices: "BonusVarsler_EnabledServices",
setupComplete: "BonusVarsler_SetupComplete",
setupShowCount: "BonusVarsler_SetupShowCount",
version: "BonusVarsler_Version"
};
var LEGACY_KEYS = {
feedData_v3: "BonusVarsler_FeedData_v3",
feedTime_v3: "BonusVarsler_FeedTime_v3",
hostIndex_v3: "BonusVarsler_HostIndex_v3",
feedData_v4: "BonusVarsler_FeedData_v4",
feedTime_v4: "BonusVarsler_FeedTime_v4",
hostIndex_v4: "BonusVarsler_HostIndex_v4"
};
var CURRENT_VERSION = "9.0";
var MESSAGE_SHOWN_KEY_PREFIX = "BonusVarsler_MessageShown_";
var PAGE_VISIT_COUNT_PREFIX = "BonusVarsler_PageVisits_";
function getMessageShownKey(currentHost, currentPathname = "/") {
return `${MESSAGE_SHOWN_KEY_PREFIX}${currentHost}|${currentPathname || "/"}`;
}
var DEFAULT_POSITION = "bottom-right";
var DEFAULT_THEME = "light";
var AD_TEST_URLS = [
"https://widgets.outbrain.com/outbrain.js",
"https://adligature.com/",
"https://secure.quantserve.com/quant.js",
"https://srvtrck.com/assets/css/LineIcons.css"
];
var AD_BANNER_IDS = [
"AdHeader",
"AdContainer",
"AD_Top",
"homead",
"ad-lead"
];
var CSP_RESTRICTED_SITES = /* @__PURE__ */ new Set([
"bikbok.com",
"cdon.com",
"cdon.no",
"dressmann.com",
"elite.se",
"extraoptical.no",
"fabel.no",
"godtlevert.no",
"hoie.no",
"hunkemoller.no",
"junkyard.com",
"loopia.no",
"lux-case.no",
"no.match.com",
"nordvpn.com",
"sportsmagasinet.no",
"stockx.com",
"talkmore.no",
"vetzoo.no",
"www.autodude.no",
"www.beautycos.no",
"www.bookbeat.no",
"www.bravofly.com",
"www.circlek.no",
"www.clickandboat.com",
"www.dbs.no",
"www.directferries.no",
"www.ekstralys.no",
"www.elite.se",
"www.elon.no",
"www.eurodel.no",
"www.extraoptical.se",
"www.getyourguide.com",
"www.ginatricot.com",
"www.londonpass.com",
"www.lufthansa.com",
"www.lusini.com",
"www.myprotein.no",
"www.skyshowtime.com",
"www.sportmann.no",
"www.strikkia.no",
"www.vivara.no"
]);
// src/config/domain-aliases.ts
var DOMAIN_ALIASES = {
"nordicfeel.com": "nordicfeel.no",
"www.nordicfeel.com": "www.nordicfeel.no",
"lekmer.com": "lekmer.no",
"www.lekmer.com": "lekmer.no",
"lyko.com": "lyko.no",
"www.lyko.com": "www.lyko.no",
"storytel.com": "storytel.no",
"www.storytel.com": "www.storytel.no",
"beckmann-norway.com": "beckmann.no",
"www.beckmann-norway.com": "beckmann.no",
"nordicnest.no": "id.nordicnest.no",
"www.nordicnest.no": "id.nordicnest.no",
"dbjourney.com": "dbjourney.no",
"www.dbjourney.com": "dbjourney.no",
"bookbeat.com": "bookbeat.no",
"www.bookbeat.com": "www.bookbeat.no",
"outnorth.com": "outnorth.no",
"www.outnorth.com": "outnorth.no",
"no-pin.loccitane.com": "no.loccitane.com",
"bilglass.no": "booking.bilglass.no",
"www.bilglass.no": "booking.bilglass.no",
"booking.fyriresort.com": "fyriresort.com",
"www.oakley.com": "no.oakley.com",
"www.viator.com": "www.viatorcom.no",
"www.scandichotels.com": "www.scandichotels.no",
"www.omio.com": "www.omio.no",
"trip.com": "www.trip.com",
"no.trip.com": "www.trip.com",
"comfort.no": "www.bademiljo.no",
"www.comfort.no": "www.bademiljo.no",
"blivakker.no": "www.blivakker.no",
"addresshotels.com": "www.addresshotels.com",
"bravofly.com": "www.bravofly.com",
"computersalg.no": "csmegastore.no",
"www.computersalg.no": "csmegastore.no",
"www.csmegastore.no": "csmegastore.no",
"www.houdinisportswear.com": "houdinisportswear.com",
"ralphlauren.global": "www.ralphlauren.global"
};
// src/config/services.ts
var SERVICES_FALLBACK = {
trumf: {
id: "trumf",
name: "Trumf",
clickthroughUrl: "https://trumfnetthandel.no/cashback/{urlName}",
reminderDomain: "trumfnetthandel.no",
color: "#4D4DFF",
defaultEnabled: true
},
sas: {
id: "sas",
name: "SAS EuroBonus",
clickthroughUrl: "https://onlineshopping.flysas.com/nb-NO/butikker/{urlName}",
reminderDomain: "onlineshopping.flysas.com",
cashbackPathPatterns: ["/nb-NO/butikker"],
color: "#0F1E82",
defaultEnabled: false
},
remember: {
id: "remember",
name: "re:member",
clickthroughUrl: "https://www.remember.no/reward/rabatt/{urlName}",
reminderDomain: "remember.no",
color: "#f28d00",
defaultEnabled: false
},
dnb: {
id: "dnb",
name: "DNB",
clickthroughUrl: "https://www.dnb.no/kundeprogram/fordeler/faste-rabatter",
color: "#007272",
defaultEnabled: false,
type: "code"
},
obos: {
id: "obos",
name: "OBOS",
clickthroughUrl: "https://www.obos.no/medlem/medlemsfordeler/{urlName}",
color: "#0047ba",
defaultEnabled: false,
type: "info"
},
naf: {
id: "naf",
name: "NAF",
clickthroughUrl: "https://www.naf.no/medlemskap/medlemsfordeler/{urlName}",
reminderDomain: "naf.no",
cashbackPathPatterns: ["/medlemskap/medlemsfordeler"],
color: "#c9a000",
defaultEnabled: false,
type: "info"
},
lofavor: {
id: "lofavor",
name: "LOfav\xF8r",
clickthroughUrl: "https://www.lofavor.no/{urlName}",
color: "#66083c",
defaultEnabled: false,
type: "info"
},
logbuy: {
id: "logbuy",
name: "Visma LogBuy",
// CustomerId=101274 is the public browser-extension LogBuy account identifier
// from the official extension, not a per-user secret.
clickthroughUrl: "https://www.mylogbuy.com/WebPages/ShowDeal/Default.aspx?SupplierInfoId={urlName}&ContentSet=B2C&CustomerId=101274",
reminderDomain: "mylogbuy.com",
cashbackPathPatterns: ["/WebPages/ShowDeal/"],
color: "#ee2e24",
defaultEnabled: false
}
};
var SERVICE_ORDER = ["trumf", "sas", "remember", "dnb", "obos", "naf", "lofavor", "logbuy"];
function getDefaultEnabledServices(services = SERVICES_FALLBACK) {
return Object.values(services).filter((s) => s.defaultEnabled).map((s) => s.id);
}
function isValidService(service) {
return typeof service.name === "string" && service.name.length > 0 && typeof service.color === "string" && service.color.length > 0;
}
function mergeServices(feedServices, fallback = SERVICES_FALLBACK) {
if (!feedServices) {
return { ...fallback };
}
const merged = { ...fallback };
for (const [id, service] of Object.entries(feedServices)) {
const existing = merged[id] || {};
const candidate = { ...existing, ...service, id };
if (isValidService(candidate)) {
merged[id] = candidate;
} else {
console.warn(`BonusVarsler: Skipping invalid service "${id}" - missing required fields`);
}
}
return merged;
}
// src/core/settings.ts
var MAX_SITE_POSITIONS = 100;
function createDefaultSettings() {
return {
hiddenSites: /* @__PURE__ */ new Set(),
blacklistedSites: /* @__PURE__ */ new Set(),
theme: DEFAULT_THEME,
startMinimized: false,
position: DEFAULT_POSITION,
sitePositions: {},
enabledServices: null,
setupComplete: false,
setupShowCount: 0
};
}
var Settings = class {
cache;
storage;
currentHost;
constructor(storage, currentHost) {
this.cache = createDefaultSettings();
this.storage = storage;
this.currentHost = currentHost;
}
/**
* Run version-based migrations
*/
async runMigrations() {
try {
const storedVersion = await this.storage.get(STORAGE_KEYS.version, null);
if (storedVersion !== CURRENT_VERSION) {
const existingEnabledServices = await this.storage.get(
STORAGE_KEYS.enabledServices,
null
);
const legacyFeedData = await this.storage.get(LEGACY_KEYS.feedData_v3, null);
const legacyFeedTime = await this.storage.get(LEGACY_KEYS.feedTime_v3, null);
const legacyFeedDataV4 = await this.storage.get(LEGACY_KEYS.feedData_v4, null);
const legacyFeedTimeV4 = await this.storage.get(LEGACY_KEYS.feedTime_v4, null);
const isLegacyUser = existingEnabledServices === null && (legacyFeedData !== null || legacyFeedTime !== null || legacyFeedDataV4 !== null || legacyFeedTimeV4 !== null);
const isExistingUser = storedVersion !== null || existingEnabledServices !== null || isLegacyUser;
const keysToRemove = [
STORAGE_KEYS.feedData,
STORAGE_KEYS.feedTime,
STORAGE_KEYS.hostIndex,
LEGACY_KEYS.feedData_v3,
LEGACY_KEYS.feedTime_v3,
LEGACY_KEYS.hostIndex_v3,
LEGACY_KEYS.feedData_v4,
LEGACY_KEYS.feedTime_v4,
LEGACY_KEYS.hostIndex_v4,
STORAGE_KEYS.reminderShown
];
await this.storage.remove(keysToRemove);
if (isLegacyUser) {
await this.storage.set(STORAGE_KEYS.enabledServices, ["trumf"]);
}
if (isExistingUser) {
await this.storage.set(STORAGE_KEYS.setupComplete, true);
}
await this.storage.set(STORAGE_KEYS.version, CURRENT_VERSION);
console.log("[BonusVarsler] Migrated to version", CURRENT_VERSION);
}
} catch (err) {
console.error("[BonusVarsler] Settings migration failed:", err);
}
}
/**
* Load all settings from storage
*/
async load() {
await this.runMigrations();
const hiddenSitesArray = await this.storage.get(STORAGE_KEYS.hiddenSites, []);
this.cache.hiddenSites = new Set(hiddenSitesArray);
const blacklistedSitesArray = await this.storage.get(STORAGE_KEYS.blacklistedSites, []);
this.cache.blacklistedSites = new Set(blacklistedSitesArray);
this.cache.theme = await this.storage.get(STORAGE_KEYS.theme, DEFAULT_THEME);
this.cache.startMinimized = await this.storage.get(STORAGE_KEYS.startMinimized, false);
this.cache.position = await this.storage.get(STORAGE_KEYS.position, DEFAULT_POSITION);
this.cache.sitePositions = await this.storage.get(
STORAGE_KEYS.sitePositions,
{}
);
const storedServices = await this.storage.get(
STORAGE_KEYS.enabledServices,
null
);
this.cache.enabledServices = storedServices;
this.cache.setupComplete = await this.storage.get(STORAGE_KEYS.setupComplete, false);
this.cache.setupShowCount = await this.storage.get(STORAGE_KEYS.setupShowCount, 0);
}
// ==================
// Hidden Sites
// ==================
getHiddenSites() {
return this.cache.hiddenSites;
}
isSiteHidden(host) {
const normalized = this.normalizeHost(host);
return this.cache.hiddenSites.has(normalized);
}
async hideSite(host) {
const normalized = this.normalizeHost(host);
if (!this.cache.hiddenSites.has(normalized)) {
this.cache.hiddenSites.add(normalized);
await this.storage.set(STORAGE_KEYS.hiddenSites, [...this.cache.hiddenSites]);
}
}
async resetHiddenSites() {
this.cache.hiddenSites = /* @__PURE__ */ new Set();
await this.storage.set(STORAGE_KEYS.hiddenSites, []);
}
// ==================
// Blacklisted Sites
// ==================
normalizeHost(host) {
let h = host.trim().toLowerCase();
if (h.startsWith("www.")) {
h = h.slice(4);
}
h = h.replace(/^\.+|\.+$/g, "");
return h;
}
getBlacklistedSites() {
return this.cache.blacklistedSites;
}
isSiteBlacklisted(host) {
return this.cache.blacklistedSites.has(this.normalizeHost(host));
}
async blacklistSite(host) {
const normalized = this.normalizeHost(host);
if (!this.cache.blacklistedSites.has(normalized)) {
this.cache.blacklistedSites.add(normalized);
await this.storage.set(STORAGE_KEYS.blacklistedSites, [...this.cache.blacklistedSites]);
}
}
async unblacklistSite(host) {
const normalized = this.normalizeHost(host);
if (this.cache.blacklistedSites.has(normalized)) {
this.cache.blacklistedSites.delete(normalized);
await this.storage.set(STORAGE_KEYS.blacklistedSites, [...this.cache.blacklistedSites]);
}
}
async resetBlacklistedSites() {
this.cache.blacklistedSites = /* @__PURE__ */ new Set();
await this.storage.set(STORAGE_KEYS.blacklistedSites, []);
}
// ==================
// Theme
// ==================
getTheme() {
return this.cache.theme;
}
async setTheme(theme) {
this.cache.theme = theme;
await this.storage.set(STORAGE_KEYS.theme, theme);
}
// ==================
// Start Minimized
// ==================
getStartMinimized() {
return this.cache.startMinimized;
}
async setStartMinimized(value) {
this.cache.startMinimized = value;
await this.storage.set(STORAGE_KEYS.startMinimized, value);
}
// ==================
// Position
// ==================
getPosition() {
return this.cache.sitePositions[this.currentHost] || this.cache.position;
}
getDefaultPosition() {
return this.cache.position;
}
async setDefaultPosition(position) {
this.cache.position = position;
await this.storage.set(STORAGE_KEYS.position, position);
}
async setPositionForSite(position) {
this.cache.sitePositions[this.currentHost] = position;
const hosts = Object.keys(this.cache.sitePositions);
if (hosts.length > MAX_SITE_POSITIONS) {
const toRemove = hosts.slice(0, hosts.length - MAX_SITE_POSITIONS);
for (const host of toRemove) {
delete this.cache.sitePositions[host];
}
}
await this.storage.set(STORAGE_KEYS.sitePositions, this.cache.sitePositions);
}
// ==================
// Enabled Services
// ==================
getEnabledServices() {
return this.cache.enabledServices || getDefaultEnabledServices();
}
isServiceEnabled(serviceId) {
return this.getEnabledServices().includes(serviceId);
}
async setServiceEnabled(serviceId, enabled) {
const current = this.getEnabledServices();
let updated;
if (enabled && !current.includes(serviceId)) {
updated = [...current, serviceId];
} else if (!enabled && current.includes(serviceId)) {
updated = current.filter((s) => s !== serviceId);
} else {
return;
}
this.cache.enabledServices = updated;
await this.storage.set(STORAGE_KEYS.enabledServices, updated);
}
async setEnabledServices(services) {
this.cache.enabledServices = services;
await this.storage.set(STORAGE_KEYS.enabledServices, services);
}
// ==================
// Setup Complete
// ==================
isSetupComplete() {
return this.cache.setupComplete;
}
getSetupShowCount() {
return this.cache.setupShowCount;
}
async setSetupComplete(complete) {
this.cache.setupComplete = complete;
await this.storage.set(STORAGE_KEYS.setupComplete, complete);
}
/**
* Verify that first-run setup state was actually persisted to storage.
* Used to detect silent GM storage failures in userscript environments.
*/
async verifySetupSelection(expectedServices) {
try {
const persistedSetupComplete = await this.storage.get(
STORAGE_KEYS.setupComplete,
false
);
const persistedServices = await this.storage.get(
STORAGE_KEYS.enabledServices,
null
);
if (!persistedSetupComplete || !persistedServices) {
return false;
}
const normalizeServices = (services) => [...new Set(services)].sort((a, b) => a.localeCompare(b));
const actual = normalizeServices(persistedServices);
const expected = normalizeServices(expectedServices);
return actual.length === expected.length && actual.every((serviceId, index) => serviceId === expected[index]);
} catch {
return false;
}
}
async incrementSetupShowCount() {
this.cache.setupShowCount++;
await this.storage.set(STORAGE_KEYS.setupShowCount, this.cache.setupShowCount);
}
};
// src/core/feed.ts
function isValidFeed(feed) {
return feed !== null && typeof feed === "object" && "merchants" in feed && typeof feed.merchants === "object" && feed.merchants !== null;
}
function isUnifiedFeedFormat(feed) {
return feed.services !== void 0 && typeof feed.services === "object";
}
var FeedManager = class {
storage;
fetcher;
cachedFeed = null;
services = { ...SERVICES_FALLBACK };
constructor(storage, fetcher) {
this.storage = storage;
this.fetcher = fetcher;
}
/**
* Get the service registry (merged from feed and fallback)
*/
getServices() {
return this.services;
}
/**
* Get cached feed from storage
*/
async getCachedFeed() {
const storedTime = await this.storage.get(STORAGE_KEYS.feedTime, null);
if (!storedTime) {
return null;
}
const elapsed = Date.now() - storedTime;
if (elapsed >= CONFIG.cacheDuration) {
return null;
}
const storedData = await this.storage.get(STORAGE_KEYS.feedData, null);
if (isValidFeed(storedData)) {
this.updateServicesFromFeed(storedData);
return storedData;
}
return null;
}
/**
* Cache feed data to storage
*/
async cacheFeed(data) {
try {
await this.storage.set(STORAGE_KEYS.feedData, data);
await this.storage.set(STORAGE_KEYS.feedTime, Date.now());
if (data.merchants) {
await this.storage.set(STORAGE_KEYS.hostIndex, Object.keys(data.merchants));
}
this.updateServicesFromFeed(data);
} catch {
}
}
/**
* Update service registry from feed data
*/
updateServicesFromFeed(feed) {
if (feed.services) {
this.services = mergeServices(feed.services, SERVICES_FALLBACK);
}
}
/**
* Get feed (from cache or fetch)
*/
async getFeed() {
if (this.cachedFeed) {
return this.cachedFeed;
}
const cached = await this.getCachedFeed();
if (cached) {
this.cachedFeed = cached;
return cached;
}
const feed = await this.fetcher.fetchFeed(CONFIG.feedUrl);
if (feed && isValidFeed(feed)) {
await this.cacheFeed(feed);
this.cachedFeed = feed;
return feed;
}
return null;
}
/**
* Check if a host is in the cached host index (fast lookup)
*/
async isKnownMerchantHost(currentHost, domainAliases) {
const hostIndex = await this.storage.get(STORAGE_KEYS.hostIndex, null);
if (!hostIndex) {
return null;
}
const hostSet = new Set(hostIndex);
const noWww = currentHost.replace(/^www\./, "");
if (hostSet.has(currentHost) || hostSet.has(noWww) || hostSet.has("www." + noWww)) {
return true;
}
const aliasedHost = domainAliases[currentHost];
if (aliasedHost && hostSet.has(aliasedHost)) {
return true;
}
const aliasedNoWww = domainAliases[noWww];
if (aliasedNoWww && hostSet.has(aliasedNoWww)) {
return true;
}
return false;
}
};
// src/core/merchant-matching.ts
function parseCashbackRate(description) {
if (!description) return { value: 0, type: "percent", isVariable: false };
const normalized = description.toLowerCase().trim();
const isVariable = normalized.startsWith("opptil") || normalized.startsWith("opp til") || normalized.startsWith("up to") || /\d+\s*[-\u2013]\s*\d+/.test(normalized);
const cleanDesc = description.replace(/^(opptil|opp til|up to)\s*/i, "").trim();
const rangePercentMatch = cleanDesc.match(/(\d+[,.]?\d*)\s*[-\u2013]\s*(\d+[,.]?\d*)\s*%/);
if (rangePercentMatch?.[2]) {
const value = parseFloat(rangePercentMatch[2].replace(",", "."));
return { value, type: "percent", isVariable };
}
const percentMatch = cleanDesc.match(/(\d+[,.]?\d*)\s*%/);
if (percentMatch?.[1]) {
const value = parseFloat(percentMatch[1].replace(",", "."));
return { value, type: "percent", isVariable };
}
const fixedMatch = cleanDesc.match(/(\d+[,.]?\d*)\s*kr/i);
if (fixedMatch?.[1]) {
const value = parseFloat(fixedMatch[1].replace(",", "."));
return { value, type: "fixed", isVariable };
}
return { value: 0, type: "percent", isVariable: false };
}
function compareCashbackRates(a, b, avgPurchaseAmount = 500) {
if (a.type !== b.type) {
const monetaryA = a.type === "percent" ? a.value / 100 * avgPurchaseAmount : a.value;
const monetaryB = b.type === "percent" ? b.value / 100 * avgPurchaseAmount : b.value;
if (monetaryA > monetaryB) return -1;
if (monetaryA < monetaryB) return 1;
if (a.type === "percent") return -1;
return 1;
}
if (a.value > b.value) return -1;
if (a.value < b.value) return 1;
if (!a.isVariable && b.isVariable) return -1;
if (a.isVariable && !b.isVariable) return 1;
return 0;
}
function tryHost(merchants, host) {
if (merchants[host]) {
return merchants[host];
}
const noWww = host.replace(/^www\./, "");
if (noWww !== host && merchants[noWww]) {
return merchants[noWww];
}
if (!host.startsWith("www.")) {
const withWww = "www." + host;
if (merchants[withWww]) {
return merchants[withWww];
}
}
return null;
}
function normalizePathPrefix(pathname, caseSensitive = false) {
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
const withoutTrailingSlash = normalized.replace(/\/+$/, "") || "/";
return caseSensitive ? withoutTrailingSlash : withoutTrailingSlash.toLowerCase();
}
function offerMatchesPath(offer, currentPathname) {
if (!offer.matchPathPrefix) {
return true;
}
const caseSensitive = Boolean(offer.matchPathCaseSensitive);
const currentPath = normalizePathPrefix(currentPathname, caseSensitive);
const offerPath = normalizePathPrefix(offer.matchPathPrefix, caseSensitive);
if (offerPath === "/") {
return currentPath === "/";
}
return currentPath === offerPath || currentPath.startsWith(`${offerPath}/`);
}
function getOfferPathSpecificity(offer) {
if (!offer.matchPathPrefix) {
return -1;
}
return normalizePathPrefix(
offer.matchPathPrefix,
Boolean(offer.matchPathCaseSensitive)
).length;
}
function findBestOffer(feed, currentHost, enabledServices, services = SERVICES_FALLBACK, currentPathname = "/") {
if (!feed?.merchants) {
return null;
}
const { merchants } = feed;
const isUnified = isUnifiedFeedFormat(feed);
let merchant = tryHost(merchants, currentHost);
if (!merchant) {
const aliasedHost = DOMAIN_ALIASES[currentHost];
if (aliasedHost) {