-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
657 lines (582 loc) · 18.3 KB
/
Copy pathscript.js
File metadata and controls
657 lines (582 loc) · 18.3 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
/**
* MainRoute Ads Engine v1.0.0
* Lightweight, zero-dependency, self-hosted client-side ad server.
* https://MainRoute-Core.github.io/ads/
*/
(function () {
"use strict";
// Prevent double-injection collision while allowing shared singletons
const GLOBAL_NAMESPACE = "__MR_ADS_ENGINE__";
window[GLOBAL_NAMESPACE] = window[GLOBAL_NAMESPACE] || {
dbPromise: null,
instances: new Set(),
debug: false
};
const runtime = window[GLOBAL_NAMESPACE];
/**
* Safe Logger
*/
const log = {
info: (...args) => runtime.debug && console.info("[MainRoute Ads]", ...args),
warn: (...args) => console.warn("[MainRoute Ads]", ...args),
error: (...args) => console.error("[MainRoute Ads]", ...args)
};
/**
* Security & Utility Helpers
*/
const Security = {
ALLOWED_PROTOCOLS: ["https:", "http:"],
sanitizeUrl(rawUrl) {
if (!rawUrl || typeof rawUrl !== "string") return null;
try {
const parsed = new URL(rawUrl, window.location.href);
if (this.ALLOWED_PROTOCOLS.includes(parsed.protocol)) {
return parsed.href;
}
} catch (_) {
// Fallback for invalid absolute/relative URLs
}
return null;
},
resolveAssetUrl(path, dbBaseUrl) {
if (!path || typeof path !== "string") return "";
if (path.startsWith("http://") || path.startsWith("https://")) {
return this.sanitizeUrl(path) || "";
}
try {
const resolved = new URL(path, dbBaseUrl);
return this.sanitizeUrl(resolved.href) || "";
} catch (_) {
return "";
}
}
};
/**
* Client-side Frequency & Impression Storage (Rolling 24-Hour window)
*/
const FrequencyManager = {
STORAGE_KEY: "mr_ads_impressions",
ROLLING_WINDOW_MS: 24 * 60 * 60 * 1000,
getStore() {
try {
const data = localStorage.getItem(this.STORAGE_KEY);
return data ? JSON.parse(data) : {};
} catch (err) {
log.warn("LocalStorage inaccessible for frequency tracking.", err);
return {};
}
},
saveStore(store) {
try {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(store));
} catch (err) {
log.warn("Failed to write to LocalStorage.", err);
}
},
isAllowed(adId, maxTimes) {
if (!maxTimes || maxTimes <= 0) return true;
const store = this.getStore();
const now = Date.now();
const timestamps = store[adId]?.timestamps || [];
const validTimestamps = timestamps.filter(ts => (now - ts) < this.ROLLING_WINDOW_MS);
return validTimestamps.length < maxTimes;
},
record(adId) {
if (!adId) return;
const store = this.getStore();
const now = Date.now();
const current = store[adId]?.timestamps || [];
const validTimestamps = current.filter(ts => (now - ts) < this.ROLLING_WINDOW_MS);
validTimestamps.push(now);
store[adId] = { timestamps: validTimestamps };
this.saveStore(store);
}
};
/**
* Database Loader with Single-Flight Promise Sharing
*/
function fetchDatabase(dbUrl) {
if (!runtime.dbPromise) {
const fetchUrl = new URL(dbUrl);
fetchUrl.searchParams.set("v", Date.now().toString());
runtime.dbPromise = fetch(fetchUrl.href, { cache: "no-store" })
.then((res) => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then((json) => {
if (!json || typeof json !== "object" || !json.settings) {
throw new Error("Invalid adsdb.json structure");
}
return json;
})
.catch((err) => {
log.error("Unable to load ad database:", err.message);
runtime.dbPromise = null; // Allow retry on subsequent execution if needed
return null;
});
}
return runtime.dbPromise;
}
/**
* Inject Essential Namespaced CSS Once
*/
function injectStyles() {
const STYLE_ID = "mr-ads-core-styles";
if (document.getElementById(STYLE_ID)) return;
const css = `
.mr-ads-slot {
display: block;
width: 100%;
box-sizing: border-box;
margin: 10px 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.4;
}
.mr-ads-container {
display: flex;
overflow: hidden;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 8px;
color: #1a202c;
text-decoration: none;
box-sizing: border-box;
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
}
.mr-ads-container:hover {
border-color: #cbd5e1;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
transform: translateY(-1px);
}
.mr-ads-container:focus-visible {
outline: 2px solid #2563eb;
outline-offset: 2px;
}
/* Format: Default */
.mr-ads-default {
padding: 12px 14px;
align-items: center;
gap: 12px;
}
.mr-ads-default .mr-ads-logo {
width: 44px;
height: 44px;
border-radius: 6px;
object-fit: cover;
flex-shrink: 0;
background: #f1f5f9;
}
.mr-ads-default .mr-ads-content {
flex: 1 1 auto;
min-width: 0;
}
.mr-ads-default .mr-ads-name {
font-size: 14px;
font-weight: 600;
color: #0f172a;
margin: 0 0 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mr-ads-default .mr-ads-desc {
font-size: 12px;
color: #64748b;
margin: 0;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.mr-ads-default .mr-ads-cta {
font-size: 12px;
font-weight: 600;
color: #2563eb;
white-space: nowrap;
padding-left: 8px;
}
/* Format: Banner (6:1 Aspect Ratio) */
.mr-ads-banner {
position: relative;
width: 100%;
aspect-ratio: 6 / 1;
background: #0f172a;
align-items: center;
justify-content: center;
}
.mr-ads-banner img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
/* Format: Card */
.mr-ads-card {
flex-direction: column;
width: 100%;
max-width: 340px;
}
.mr-ads-card .mr-ads-banner-wrap {
width: 100%;
aspect-ratio: 6 / 1;
background: #f1f5f9;
overflow: hidden;
}
.mr-ads-card .mr-ads-banner-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
}
.mr-ads-card .mr-ads-card-body {
padding: 14px;
display: flex;
gap: 12px;
align-items: flex-start;
}
.mr-ads-card .mr-ads-logo {
width: 40px;
height: 40px;
border-radius: 6px;
object-fit: cover;
flex-shrink: 0;
}
.mr-ads-card .mr-ads-content {
flex: 1 1 auto;
}
.mr-ads-card .mr-ads-name {
font-size: 15px;
font-weight: 600;
color: #0f172a;
margin: 0 0 4px;
}
.mr-ads-card .mr-ads-desc {
font-size: 13px;
color: #64748b;
margin: 0;
}
/* Format: Compact (Sidebars / Toolbars) */
.mr-ads-compact {
padding: 6px 10px;
align-items: center;
gap: 8px;
}
.mr-ads-compact .mr-ads-logo {
width: 24px;
height: 24px;
border-radius: 4px;
object-fit: cover;
flex-shrink: 0;
}
.mr-ads-compact .mr-ads-name {
font-size: 12px;
font-weight: 600;
color: #0f172a;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Format: Both (Banner on top, standard info below) */
.mr-ads-both {
flex-direction: column;
}
.mr-ads-both .mr-ads-banner-wrap {
width: 100%;
aspect-ratio: 6 / 1;
overflow: hidden;
}
.mr-ads-both .mr-ads-banner-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
}
.mr-ads-both .mr-ads-bottom {
padding: 10px 14px;
display: flex;
align-items: center;
gap: 10px;
}
/* Native Ad Badge */
.mr-ads-badge {
position: absolute;
top: 4px;
right: 4px;
background: rgba(15, 23, 42, 0.7);
color: #ffffff;
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
padding: 2px 4px;
border-radius: 3px;
pointer-events: none;
letter-spacing: 0.5px;
}
`;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = css;
document.head.appendChild(style);
}
/**
* Ad Unit Instance Class
*/
class MainRouteAdUnit {
constructor(scriptEl) {
this.scriptEl = scriptEl;
this.app = scriptEl.getAttribute("data-app");
this.format = scriptEl.getAttribute("data-format") || "default";
this.placement = scriptEl.getAttribute("data-placement") || null;
this.slotEl = null;
this.timerId = null;
this.currentAdId = null;
this.dbBaseUrl = "";
}
init() {
if (!this.app) {
log.error("Initialization rejected: Required attribute 'data-app' is missing on script tag.", this.scriptEl);
return;
}
// Compute base URL from script src
const scriptSrc = this.scriptEl.src;
this.dbBaseUrl = new URL(scriptSrc, window.location.href).href.replace(/script\.js(?:\?.*)?$/, "");
const dbUrl = new URL("adsdb.json", this.dbBaseUrl).href;
// Create placeholder slot right before the script tag
this.slotEl = document.createElement("div");
this.slotEl.className = "mr-ads-slot";
this.slotEl.setAttribute("data-mr-app", this.app);
if (this.placement) this.slotEl.setAttribute("data-mr-placement", this.placement);
this.scriptEl.parentNode.insertBefore(this.slotEl, this.scriptEl);
injectStyles();
// Begin loading DB
fetchDatabase(dbUrl).then((db) => {
if (!db) return;
this.runLoop(db);
});
}
runLoop(db) {
if (this.timerId) clearTimeout(this.timerId);
const ad = this.resolveAd(db);
if (!ad) {
this.slotEl.innerHTML = "";
this.slotEl.style.display = "none";
return;
}
this.renderAd(ad, db);
FrequencyManager.record(ad.id);
const duration = (ad.duration || db.settings?.defaultDuration || 10) * 1000;
this.timerId = setTimeout(() => {
this.runLoop(db);
}, duration);
}
resolveAd(db) {
if (!db.settings?.enabled) return null;
const appConfig = db.apps?.[this.app];
if (!appConfig || appConfig.enabled === false) return null;
let candidates = [];
// Priority 1: Exact App + Placement
if (this.placement && appConfig.placements?.[this.placement]) {
candidates = candidates.concat(appConfig.placements[this.placement]);
}
// Priority 2: App-wide Fallback
if (candidates.length === 0 && Array.isArray(appConfig.ads)) {
candidates = candidates.concat(appConfig.ads);
}
// Priority 3: Global Fallback
if (candidates.length === 0 && Array.isArray(db.global)) {
candidates = candidates.concat(db.global);
}
// Deduplicate by ID
const uniqueMap = new Map();
candidates.forEach((ad) => {
if (ad && ad.id && !uniqueMap.has(ad.id)) {
uniqueMap.set(ad.id, ad);
}
});
const uniqueCandidates = Array.from(uniqueMap.values());
// Filter
const defaultTimes = db.settings?.defaultTimes || 6;
const eligible = uniqueCandidates.filter((ad) => this.filterAd(ad, defaultTimes));
if (eligible.length === 0) return null;
// Select Ad (Fair randomized rotation, avoid immediate repetition if > 1 eligible)
if (eligible.length === 1) return eligible[0];
const pool = eligible.filter((ad) => ad.id !== this.currentAdId);
const selected = pool.length > 0
? pool[Math.floor(Math.random() * pool.length)]
: eligible[Math.floor(Math.random() * eligible.length)];
this.currentAdId = selected.id;
return selected;
}
filterAd(ad, defaultTimes) {
if (!ad || typeof ad !== "object") return false;
if (!ad.id || !ad.name || !ad.link) return false;
// Status check
if (ad.status === "in") return false;
// Expiry check for temporary ads
if (ad.status === "tem") {
if (!ad.expire) return false;
const expiryDate = new Date(ad.expire);
if (isNaN(expiryDate.getTime()) || Date.now() >= expiryDate.getTime()) {
return false;
}
}
// Frequency limit
const maxImpressions = ad.times !== undefined ? ad.times : defaultTimes;
if (!FrequencyManager.isAllowed(ad.id, maxImpressions)) {
return false;
}
// Sanitized destination verification
if (!Security.sanitizeUrl(ad.link)) return false;
// Format-specific asset verification
if (this.format === "banner" && !ad.banner) return false;
return true;
}
renderAd(ad, db) {
const destination = Security.sanitizeUrl(ad.link);
const logoUrl = Security.resolveAssetUrl(ad.logo, this.dbBaseUrl);
const bannerUrl = Security.resolveAssetUrl(ad.banner, this.dbBaseUrl);
// Clean container
this.slotEl.innerHTML = "";
this.slotEl.style.display = "block";
const anchor = document.createElement("a");
anchor.className = `mr-ads-container mr-ads-${this.format}`;
anchor.href = destination;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.setAttribute("aria-label", `Advertisement: ${ad.name}`);
switch (this.format) {
case "banner":
this.renderBanner(anchor, bannerUrl, ad.name);
break;
case "card":
this.renderCard(anchor, bannerUrl, logoUrl, ad);
break;
case "compact":
this.renderCompact(anchor, logoUrl, ad);
break;
case "both":
this.renderBoth(anchor, bannerUrl, logoUrl, ad);
break;
case "default":
default:
this.renderDefault(anchor, logoUrl, ad);
break;
}
this.slotEl.appendChild(anchor);
}
renderDefault(container, logoUrl, ad) {
if (logoUrl) {
const img = document.createElement("img");
img.className = "mr-ads-logo";
img.src = logoUrl;
img.alt = "";
img.loading = "lazy";
container.appendChild(img);
}
const content = document.createElement("div");
content.className = "mr-ads-content";
const name = document.createElement("div");
name.className = "mr-ads-name";
name.textContent = ad.name;
content.appendChild(name);
if (ad.desc) {
const desc = document.createElement("p");
desc.className = "mr-ads-desc";
desc.textContent = ad.desc;
content.appendChild(desc);
}
container.appendChild(content);
const cta = document.createElement("span");
cta.className = "mr-ads-cta";
cta.textContent = "Learn More →";
cta.setAttribute("aria-hidden", "true");
container.appendChild(cta);
}
renderBanner(container, bannerUrl, adName) {
const img = document.createElement("img");
img.src = bannerUrl;
img.alt = adName;
img.loading = "lazy";
container.appendChild(img);
const badge = document.createElement("span");
badge.className = "mr-ads-badge";
badge.textContent = "Ad";
container.appendChild(badge);
}
renderCard(container, bannerUrl, logoUrl, ad) {
if (bannerUrl) {
const wrap = document.createElement("div");
wrap.className = "mr-ads-banner-wrap";
const img = document.createElement("img");
img.src = bannerUrl;
img.alt = "";
wrap.appendChild(img);
container.appendChild(wrap);
}
const body = document.createElement("div");
body.className = "mr-ads-card-body";
if (logoUrl) {
const logo = document.createElement("img");
logo.className = "mr-ads-logo";
logo.src = logoUrl;
logo.alt = "";
body.appendChild(logo);
}
const content = document.createElement("div");
content.className = "mr-ads-content";
const name = document.createElement("div");
name.className = "mr-ads-name";
name.textContent = ad.name;
content.appendChild(name);
if (ad.desc) {
const desc = document.createElement("p");
desc.className = "mr-ads-desc";
desc.textContent = ad.desc;
content.appendChild(desc);
}
body.appendChild(content);
container.appendChild(body);
}
renderCompact(container, logoUrl, ad) {
if (logoUrl) {
const img = document.createElement("img");
img.className = "mr-ads-logo";
img.src = logoUrl;
img.alt = "";
container.appendChild(img);
}
const name = document.createElement("span");
name.className = "mr-ads-name";
name.textContent = ad.name;
container.appendChild(name);
}
renderBoth(container, bannerUrl, logoUrl, ad) {
if (bannerUrl) {
const wrap = document.createElement("div");
wrap.className = "mr-ads-banner-wrap";
const img = document.createElement("img");
img.src = bannerUrl;
img.alt = "";
wrap.appendChild(img);
container.appendChild(wrap);
}
const bottom = document.createElement("div");
bottom.className = "mr-ads-bottom";
this.renderDefault(bottom, logoUrl, ad);
container.appendChild(bottom);
}
destroy() {
if (this.timerId) clearTimeout(this.timerId);
if (this.slotEl && this.slotEl.parentNode) {
this.slotEl.parentNode.removeChild(this.slotEl);
}
}
}
// Bind to current executing script tag immediately
const activeScript = document.currentScript;
if (activeScript && !activeScript.dataset.mrLoaded) {
activeScript.dataset.mrLoaded = "true";
const unit = new MainRouteAdUnit(activeScript);
runtime.instances.add(unit);
unit.init();
}
})();