@ethicly/react-native 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/README.md +112 -13
- package/lib/commonjs/core/cache.js +2 -0
- package/lib/commonjs/core/client.js +168 -53
- package/lib/commonjs/core/config.js +4 -1
- package/lib/commonjs/core/houseTracker.js +92 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +23 -4
- package/lib/commonjs/react/useEthiclyInterstitial.js +22 -6
- package/lib/commonjs/version.js +1 -1
- package/lib/module/core/cache.js +2 -0
- package/lib/module/core/client.js +168 -53
- package/lib/module/core/config.js +4 -1
- package/lib/module/core/houseTracker.js +88 -0
- package/lib/module/react/EthiclyInterstitial.js +23 -4
- package/lib/module/react/useEthiclyInterstitial.js +22 -6
- package/lib/module/version.js +1 -1
- package/lib/typescript/core/cache.d.ts +3 -1
- package/lib/typescript/core/client.d.ts +24 -4
- package/lib/typescript/core/houseTracker.d.ts +53 -0
- package/lib/typescript/core/index.d.ts +1 -1
- package/lib/typescript/core/types.d.ts +44 -2
- package/lib/typescript/react/EthiclyInterstitial.d.ts +7 -0
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +16 -2
- package/lib/typescript/version.d.ts +1 -1
- package/package.json +1 -1
- package/src/core/cache.ts +4 -2
- package/src/core/client.ts +186 -55
- package/src/core/config.ts +4 -1
- package/src/core/houseTracker.ts +108 -0
- package/src/core/index.ts +1 -1
- package/src/core/types.ts +44 -2
- package/src/react/EthiclyInterstitial.tsx +26 -4
- package/src/react/useEthiclyInterstitial.ts +38 -8
- package/src/version.ts +1 -1
package/src/core/client.ts
CHANGED
|
@@ -10,11 +10,13 @@ import { isWebUrl } from './click';
|
|
|
10
10
|
import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
|
|
11
11
|
import { httpRequest, RouteGate } from './http';
|
|
12
12
|
import { outboxFor, replayRecord, type Outbox } from './outbox';
|
|
13
|
+
import { HouseTracker } from './houseTracker';
|
|
13
14
|
import { InterstitialTracker } from './tracker';
|
|
14
15
|
import { SDK_VERSION } from '../version';
|
|
15
16
|
import type {
|
|
16
17
|
AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate,
|
|
17
|
-
InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform,
|
|
18
|
+
InterstitialResult, KeyValueStorage, LoadOptions, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform,
|
|
19
|
+
Tracker, WireAd, WireServe,
|
|
18
20
|
} from './types';
|
|
19
21
|
|
|
20
22
|
export interface EthiclyOptions {
|
|
@@ -58,6 +60,20 @@ export interface EthiclyOptions {
|
|
|
58
60
|
* behaviour. Change it later with setFrequency().
|
|
59
61
|
*/
|
|
60
62
|
frequency?: FrequencyOptions;
|
|
63
|
+
/**
|
|
64
|
+
* Show the publisher's house ad (uploaded in the dashboard) when no paid ad
|
|
65
|
+
* fills. Default true: the upload is the opt-in, so a publisher without one
|
|
66
|
+
* sees no change. false never asks for one, so the app can show its own.
|
|
67
|
+
* Change it later with setHouseAds(), or per call with { houseAds }.
|
|
68
|
+
*/
|
|
69
|
+
houseAds?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Where EthiclyInterstitial sends a tap on a house ad's button instead of
|
|
72
|
+
* opening its link, for example the app's premium screen. The tap is still
|
|
73
|
+
* counted and the ad closes first. useEthiclyInterstitial's and the
|
|
74
|
+
* screen's own onHouseAdPress win over this. Never used for paid ads.
|
|
75
|
+
*/
|
|
76
|
+
onHouseAdPress?: (ad: EthiclyAd) => void;
|
|
61
77
|
storage?: KeyValueStorage;
|
|
62
78
|
fileCache?: FileCacheAdapter;
|
|
63
79
|
openUrl?: (url: string) => unknown;
|
|
@@ -75,9 +91,15 @@ export interface Ethicly {
|
|
|
75
91
|
/** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
|
|
76
92
|
readonly ready: Promise<void>;
|
|
77
93
|
/** Serve and download an interstitial ahead of time. Does not consume it. */
|
|
78
|
-
preload(): Promise<InterstitialResult>;
|
|
79
|
-
/**
|
|
80
|
-
|
|
94
|
+
preload(opts?: LoadOptions): Promise<InterstitialResult>;
|
|
95
|
+
/**
|
|
96
|
+
* The ad to show now: the preloaded one if still valid, else a fresh serve.
|
|
97
|
+
* Consumes it. A preloaded house ad never stands in for a paid ad: a fresh
|
|
98
|
+
* serve is tried first, within loadTimeoutMs. Check `ad.house`.
|
|
99
|
+
*/
|
|
100
|
+
loadInterstitial(opts?: LoadOptions): Promise<InterstitialResult>;
|
|
101
|
+
/** Turn house ads on or off for this client (options.houseAds). Off drops a preloaded house ad. */
|
|
102
|
+
setHouseAds(enabled: boolean): void;
|
|
81
103
|
/**
|
|
82
104
|
* Frequency caps, the ads switch and the kill switch, checked client-side.
|
|
83
105
|
* false until the stored frequency state has loaded (see `ready`).
|
|
@@ -124,7 +146,7 @@ let releaseTestModeLogged = false;
|
|
|
124
146
|
interface StoredConfig { config: EthiclyConfig; fetchedAt: number; maxAgeS: number }
|
|
125
147
|
interface StoredFrequency { lastShownAt: number }
|
|
126
148
|
|
|
127
|
-
interface Preloaded { result: { ad: EthiclyAd; tracker:
|
|
149
|
+
interface Preloaded { result: { ad: EthiclyAd; tracker: Tracker } }
|
|
128
150
|
|
|
129
151
|
/** A served ad whose creative is downloading. Built into an ad once, by preload() or loadInterstitial(). */
|
|
130
152
|
interface Served {
|
|
@@ -134,6 +156,10 @@ interface Served {
|
|
|
134
156
|
/** Taken by loadInterstitial(): never stored as the preloaded ad. */
|
|
135
157
|
consumed: boolean;
|
|
136
158
|
result: Preloaded['result'] | null;
|
|
159
|
+
/** A house ad, shown only when no paid ad fills. */
|
|
160
|
+
house: boolean;
|
|
161
|
+
/** For a house ad: why no paid ad filled. */
|
|
162
|
+
noFillReason?: NoFillReason;
|
|
137
163
|
}
|
|
138
164
|
|
|
139
165
|
type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
|
|
@@ -194,6 +220,7 @@ class EthiclyClient implements Ethicly {
|
|
|
194
220
|
private sdkUnsupported = false;
|
|
195
221
|
|
|
196
222
|
private adsOn: boolean;
|
|
223
|
+
private houseAdsOn: boolean;
|
|
197
224
|
private testMode: boolean;
|
|
198
225
|
private shownCount = 0;
|
|
199
226
|
private lastShownAt: number | null = null;
|
|
@@ -228,6 +255,7 @@ class EthiclyClient implements Ethicly {
|
|
|
228
255
|
);
|
|
229
256
|
this.config = defaultConfig(this.bundled);
|
|
230
257
|
this.adsOn = o.adsEnabled !== false;
|
|
258
|
+
this.houseAdsOn = o.houseAds !== false;
|
|
231
259
|
this.audio = audioPolicy(o.audio);
|
|
232
260
|
if (o.audio !== undefined && !this.audio) this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
|
|
233
261
|
this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
|
|
@@ -521,6 +549,22 @@ class EthiclyClient implements Ethicly {
|
|
|
521
549
|
return this.adsOn;
|
|
522
550
|
}
|
|
523
551
|
|
|
552
|
+
setHouseAds(enabled: boolean): void {
|
|
553
|
+
this.houseAdsOn = !!enabled;
|
|
554
|
+
if (this.houseAdsOn) return;
|
|
555
|
+
if (this.preloaded?.result.ad.house) this.preloaded = null;
|
|
556
|
+
if (this.pendingServed?.house) this.pendingServed = null;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Whether this call takes a house ad: the call's option, else the client's,
|
|
561
|
+
* and never while the dashboard switch (/config interstitial.house_ads) is off.
|
|
562
|
+
*/
|
|
563
|
+
private wantHouse(opts?: LoadOptions): boolean {
|
|
564
|
+
if (!this.config.interstitial.house_ads) return false;
|
|
565
|
+
return typeof opts?.houseAds === 'boolean' ? opts.houseAds : this.houseAdsOn;
|
|
566
|
+
}
|
|
567
|
+
|
|
524
568
|
// ------------------------------------------------------------- serve
|
|
525
569
|
|
|
526
570
|
private blockedReason(): Exclude<NextAdReason, 'frequency_capped' | 'session_cap' | 'ads_disabled' | 'not_ready'> | null {
|
|
@@ -538,13 +582,22 @@ class EthiclyClient implements Ethicly {
|
|
|
538
582
|
return { ad: null, tracker: null, reason };
|
|
539
583
|
}
|
|
540
584
|
|
|
541
|
-
/**
|
|
542
|
-
|
|
585
|
+
/**
|
|
586
|
+
* The served ad waiting for its download, or a new serve. One serve at a
|
|
587
|
+
* time. A house ad is a no fill for a caller that does not take one.
|
|
588
|
+
*/
|
|
589
|
+
private async serveFor(houseAds: boolean): Promise<ServeOutcome> {
|
|
590
|
+
const out = await this.serveOnce(houseAds);
|
|
591
|
+
if (out.served && out.served.house && !houseAds) return { noFill: this.noFill(out.served.noFillReason || 'no_matching_ad') };
|
|
592
|
+
return out;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
private serveOnce(houseAds: boolean): Promise<ServeOutcome> {
|
|
543
596
|
const p = this.pendingServed;
|
|
544
597
|
if (p && !p.consumed && this.now() < p.expiresAt) return Promise.resolve({ served: p });
|
|
545
598
|
this.pendingServed = null;
|
|
546
599
|
if (!this.serveInflight) {
|
|
547
|
-
this.serveInflight = this.serve()
|
|
600
|
+
this.serveInflight = this.serve(houseAds)
|
|
548
601
|
.then((out) => {
|
|
549
602
|
if (out.served) this.pendingServed = out.served;
|
|
550
603
|
return out;
|
|
@@ -560,13 +613,19 @@ class EthiclyClient implements Ethicly {
|
|
|
560
613
|
return s.result;
|
|
561
614
|
}
|
|
562
615
|
|
|
563
|
-
async preload(): Promise<InterstitialResult> {
|
|
616
|
+
async preload(opts?: LoadOptions): Promise<InterstitialResult> {
|
|
564
617
|
try {
|
|
565
618
|
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
566
|
-
|
|
567
|
-
this.preloaded
|
|
619
|
+
const house = this.wantHouse(opts);
|
|
620
|
+
const p = this.preloaded;
|
|
621
|
+
if (p && !p.result.tracker.isExpired()) {
|
|
622
|
+
if (house || !p.result.ad.house) return p.result;
|
|
623
|
+
// A preloaded house ad this call does not take: kept, and a paid ad may replace it.
|
|
624
|
+
} else {
|
|
625
|
+
this.preloaded = null;
|
|
626
|
+
}
|
|
568
627
|
if (this.shownCount >= this.getFrequency().maxPerSession) return this.noFill('frequency_capped');
|
|
569
|
-
const out = await this.
|
|
628
|
+
const out = await this.serveFor(house);
|
|
570
629
|
if (!out.served) return out.noFill;
|
|
571
630
|
const s = out.served;
|
|
572
631
|
// In the background: wait for the whole download, so the ad plays from disk.
|
|
@@ -584,7 +643,7 @@ class EthiclyClient implements Ethicly {
|
|
|
584
643
|
}
|
|
585
644
|
}
|
|
586
645
|
|
|
587
|
-
async loadInterstitial(): Promise<InterstitialResult> {
|
|
646
|
+
async loadInterstitial(opts?: LoadOptions): Promise<InterstitialResult> {
|
|
588
647
|
try {
|
|
589
648
|
await this.ready;
|
|
590
649
|
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
@@ -592,16 +651,40 @@ class EthiclyClient implements Ethicly {
|
|
|
592
651
|
const blocked = this.blockedReason();
|
|
593
652
|
if (blocked) return this.noFill(blocked);
|
|
594
653
|
if (!this.canShow()) return this.noFill('frequency_capped');
|
|
654
|
+
const house = this.wantHouse(opts);
|
|
595
655
|
const pre = this.preloaded;
|
|
596
656
|
this.preloaded = null;
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
if (!
|
|
657
|
+
const valid = pre && !pre.result.tracker.isExpired() ? pre : null;
|
|
658
|
+
if (valid && !valid.result.ad.house) return valid.result;
|
|
659
|
+
// A preloaded house ad this call does not take stays for a later one.
|
|
660
|
+
if (valid && !house) this.preloaded = valid;
|
|
661
|
+
const fallback = valid && house ? valid : null;
|
|
662
|
+
const started = this.now();
|
|
663
|
+
|
|
664
|
+
let out: ServeOutcome | null;
|
|
665
|
+
if (fallback) {
|
|
666
|
+
// A preloaded house ad never blocks a paid one: ask for a paid ad
|
|
667
|
+
// first, within the load budget, and show the house ad only without one.
|
|
668
|
+
out = await this.within(this.serveFor(false), this.loadTimeoutMs);
|
|
669
|
+
if (!out || !out.served) {
|
|
670
|
+
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
671
|
+
// The paid-first serve may have hit the kill switch or the minimum SDK
|
|
672
|
+
// version: the server said stop, so the preloaded house ad must not show.
|
|
673
|
+
const nowBlocked = this.blockedReason();
|
|
674
|
+
if (nowBlocked) return this.noFill(nowBlocked);
|
|
675
|
+
// The serve may still answer: it then waits as pendingServed for next time.
|
|
676
|
+
this.lastNoFillReason = null;
|
|
677
|
+
return fallback.result;
|
|
678
|
+
}
|
|
679
|
+
} else {
|
|
680
|
+
out = await this.serveFor(house);
|
|
681
|
+
if (!out.served) return out.noFill;
|
|
682
|
+
}
|
|
601
683
|
const s = out.served;
|
|
602
684
|
// The user is waiting: give the download a short budget, then stream the
|
|
603
685
|
// remote file. The download carries on in the background for next time.
|
|
604
|
-
const
|
|
686
|
+
const budget = Math.max(0, this.loadTimeoutMs - (this.now() - started));
|
|
687
|
+
const cached = await this.within(s.download, budget);
|
|
605
688
|
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
606
689
|
if (!cached) this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
|
|
607
690
|
const r = this.claim(s, cached ? cached.uris : {});
|
|
@@ -609,6 +692,8 @@ class EthiclyClient implements Ethicly {
|
|
|
609
692
|
if (this.pendingServed === s) this.pendingServed = null;
|
|
610
693
|
// A preload that finished meanwhile may have stored this same ad.
|
|
611
694
|
if ((this.preloaded as Preloaded | null)?.result === r) this.preloaded = null;
|
|
695
|
+
// The house ad that was not needed stays preloaded for next time.
|
|
696
|
+
if (fallback && !this.preloaded) this.preloaded = fallback;
|
|
612
697
|
return r;
|
|
613
698
|
} catch (e) {
|
|
614
699
|
this.log.error('loadInterstitial failed', e);
|
|
@@ -623,13 +708,15 @@ class EthiclyClient implements Ethicly {
|
|
|
623
708
|
return Promise.race([p, timeout]).finally(() => { if (timer) clearTimeout(timer); });
|
|
624
709
|
}
|
|
625
710
|
|
|
626
|
-
private async serve(): Promise<ServeOutcome> {
|
|
711
|
+
private async serve(houseAds: boolean): Promise<ServeOutcome> {
|
|
627
712
|
const noFill = (reason: NoFillReason): ServeOutcome => ({ noFill: this.noFill(reason) });
|
|
628
713
|
await this.ready;
|
|
629
714
|
if (this.configStale()) await this.refreshConfig();
|
|
630
715
|
const blocked = this.blockedReason();
|
|
631
716
|
if (blocked) return noFill(blocked);
|
|
632
717
|
if (this.gate.waitMs('serve') > 0) return noFill('rate_limited');
|
|
718
|
+
// The dashboard switch, read from the config just refreshed.
|
|
719
|
+
const askHouse = houseAds && this.config.interstitial.house_ads;
|
|
633
720
|
|
|
634
721
|
const q = [
|
|
635
722
|
`key=${encodeURIComponent(this.o.apiKey)}`,
|
|
@@ -639,6 +726,8 @@ class EthiclyClient implements Ethicly {
|
|
|
639
726
|
`app_version=${encodeURIComponent(this.o.appVersion)}`,
|
|
640
727
|
];
|
|
641
728
|
if (this.testMode) q.push('test=1');
|
|
729
|
+
// The SDK counts a house ad itself, on show (/fallback-impression): the server must not count it at pick time.
|
|
730
|
+
if (askHouse) q.push('house_ads=1', 'client_fallback_tracking=1');
|
|
642
731
|
const res = await httpRequest(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
|
|
643
732
|
headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
|
|
644
733
|
});
|
|
@@ -656,54 +745,109 @@ class EthiclyClient implements Ethicly {
|
|
|
656
745
|
if (res.status !== 200 || !res.body || typeof res.body !== 'object') return noFill('server_error');
|
|
657
746
|
|
|
658
747
|
const body = res.body as WireServe;
|
|
748
|
+
const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
|
|
659
749
|
if (!body.ad) {
|
|
660
750
|
const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
|
|
661
751
|
if (reason === 'app_disabled') this.appDisabled = true;
|
|
662
752
|
if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
|
|
753
|
+
const h = body.house_ad;
|
|
754
|
+
// A house ad only when asked for, and never past a kill switch.
|
|
755
|
+
if (askHouse && h && typeof h === 'object' && reason !== 'app_disabled' && reason !== 'sdk_unsupported') {
|
|
756
|
+
if (!this.validAd(h, 'house ad', body.request_id)) return noFill(reason);
|
|
757
|
+
if (!this.adsOn) return noFill('ads_disabled');
|
|
758
|
+
const fallbackId = h.id;
|
|
759
|
+
const test = this.testMode || h.test === true || body.test === true;
|
|
760
|
+
this.log.info(`no paid ad (${reason}): house ad ${fallbackId}`);
|
|
761
|
+
return {
|
|
762
|
+
served: this.makeServed({
|
|
763
|
+
wire: h, cacheKey: `house-${fallbackId}`, servedAt, ttlS, test, house: true, noFillReason: reason,
|
|
764
|
+
tracker: (ad) => new HouseTracker({
|
|
765
|
+
ctx: this.beaconCtx(), ad, fallbackId, test, openUrl: this.o.openUrl, onShown: () => this.onShown(),
|
|
766
|
+
onPress: this.o.onHouseAdPress,
|
|
767
|
+
}),
|
|
768
|
+
}),
|
|
769
|
+
};
|
|
770
|
+
}
|
|
663
771
|
return noFill(reason);
|
|
664
772
|
}
|
|
665
773
|
const ad = body.ad;
|
|
774
|
+
if (!this.validAd(ad, 'ad', body.request_id)) return noFill('invalid_response');
|
|
775
|
+
if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
|
|
776
|
+
if (!this.adsOn) return noFill('ads_disabled');
|
|
777
|
+
return {
|
|
778
|
+
served: this.makeServed({
|
|
779
|
+
wire: ad, cacheKey: ad.id, servedAt, ttlS, test: body.test === true, house: false,
|
|
780
|
+
tracker: (result) => new InterstitialTracker({
|
|
781
|
+
ctx: this.beaconCtx(),
|
|
782
|
+
ad: result,
|
|
783
|
+
serve: {
|
|
784
|
+
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
785
|
+
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
786
|
+
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
787
|
+
},
|
|
788
|
+
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
789
|
+
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
790
|
+
platform: this.o.platform,
|
|
791
|
+
sdkVersion: SDK_VERSION,
|
|
792
|
+
appVersion: this.o.appVersion,
|
|
793
|
+
openUrl: this.o.openUrl,
|
|
794
|
+
onShown: () => this.onShown(),
|
|
795
|
+
outbox: this.outbox,
|
|
796
|
+
}),
|
|
797
|
+
}),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** A paid or house ad has a numeric id, media and an http(s) destination. */
|
|
802
|
+
private validAd(ad: WireAd, what: string, requestId?: string): boolean {
|
|
666
803
|
const m = ad.media;
|
|
667
804
|
if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
|
|
668
|
-
this.log.warn(
|
|
669
|
-
return
|
|
805
|
+
this.log.warn(`serve answered a ${what} without media or destination`, requestId);
|
|
806
|
+
return false;
|
|
670
807
|
}
|
|
671
808
|
if (!isWebUrl(ad.destination_url)) {
|
|
672
809
|
// Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
|
|
673
810
|
if (!this.badDestinationLogged) {
|
|
674
811
|
this.badDestinationLogged = true;
|
|
675
|
-
this.log.error(
|
|
812
|
+
this.log.error(`${what} ${ad.id}: destination is not an http(s) URL, ad skipped`, requestId);
|
|
676
813
|
}
|
|
677
|
-
return
|
|
814
|
+
return false;
|
|
678
815
|
}
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** Start the creative download; the ad and tracker are built later by preload() or loadInterstitial(). */
|
|
820
|
+
private makeServed(a: {
|
|
821
|
+
wire: WireAd; cacheKey: string | number; servedAt: number; ttlS: number; test: boolean;
|
|
822
|
+
house: boolean; noFillReason?: NoFillReason; tracker(ad: EthiclyAd): Tracker;
|
|
823
|
+
}): Served {
|
|
824
|
+
const ad = a.wire;
|
|
825
|
+
// validAd() checked these.
|
|
826
|
+
const m = ad.media as NonNullable<WireAd['media']>;
|
|
827
|
+
const mediaUrl = m.url as string;
|
|
828
|
+
const destinationUrl = ad.destination_url as string;
|
|
682
829
|
const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
|
|
683
830
|
const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
|
|
684
831
|
const pf = this.config.prefetch;
|
|
685
832
|
// Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
|
|
686
833
|
const download = this.cache.ensure(
|
|
687
|
-
|
|
688
|
-
poster ? [
|
|
834
|
+
a.cacheKey,
|
|
835
|
+
poster ? [mediaUrl, poster] : [mediaUrl],
|
|
689
836
|
{ maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
|
|
690
837
|
() => this.adsOn,
|
|
691
838
|
).catch(() => ({ uris: {} as Record<string, string> }));
|
|
692
|
-
const
|
|
693
|
-
const expiresAt = servedAt + ttlS * 1000;
|
|
694
|
-
const adId = ad.id;
|
|
695
|
-
const mediaUrl = m.url;
|
|
696
|
-
const destinationUrl = ad.destination_url;
|
|
839
|
+
const expiresAt = a.servedAt + a.ttlS * 1000;
|
|
697
840
|
const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
|
|
698
841
|
const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
|
|
699
842
|
// The ad's value wins over /config, kept within the same 8 to 15 s range.
|
|
700
843
|
const skipAfterMs = clampSkipAfterMs(ad.skip_after_ms) ?? this.config.interstitial.skip_after_ms;
|
|
701
844
|
// The app's choice (options.audio) wins over the server's interstitial.audio.
|
|
702
845
|
const audio: AudioPolicy = this.audio ?? this.config.interstitial.audio;
|
|
846
|
+
const showSponsorLabel = !a.house && this.config.interstitial.sponsor_label;
|
|
703
847
|
const build = (uris: Record<string, string>): Preloaded['result'] => {
|
|
704
848
|
const uri = uris[mediaUrl] || mediaUrl;
|
|
705
849
|
const result: EthiclyAd = {
|
|
706
|
-
id:
|
|
850
|
+
id: ad.id,
|
|
707
851
|
ctaLabel: label || 'Learn more',
|
|
708
852
|
destinationUrl,
|
|
709
853
|
skipAfterMs,
|
|
@@ -720,30 +864,17 @@ class EthiclyClient implements Ethicly {
|
|
|
720
864
|
},
|
|
721
865
|
audio,
|
|
722
866
|
title: typeof ad.title === 'string' ? ad.title : null,
|
|
723
|
-
test:
|
|
724
|
-
servedAt,
|
|
867
|
+
test: a.test,
|
|
868
|
+
servedAt: a.servedAt,
|
|
725
869
|
expiresAt,
|
|
870
|
+
house: a.house,
|
|
871
|
+
showSponsorLabel,
|
|
726
872
|
};
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
ad: result,
|
|
730
|
-
serve: {
|
|
731
|
-
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
732
|
-
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
733
|
-
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
734
|
-
},
|
|
735
|
-
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
736
|
-
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
737
|
-
platform: this.o.platform,
|
|
738
|
-
sdkVersion: SDK_VERSION,
|
|
739
|
-
appVersion: this.o.appVersion,
|
|
740
|
-
openUrl: this.o.openUrl,
|
|
741
|
-
onShown: () => this.onShown(),
|
|
742
|
-
outbox: this.outbox,
|
|
743
|
-
});
|
|
744
|
-
return { ad: result, tracker };
|
|
873
|
+
if (a.house) result.noFillReason = a.noFillReason;
|
|
874
|
+
return { ad: result, tracker: a.tracker(result) };
|
|
745
875
|
};
|
|
876
|
+
// An ad will show, so there is no fill reason, even for a house ad (see ad.noFillReason).
|
|
746
877
|
this.lastNoFillReason = null;
|
|
747
|
-
return {
|
|
878
|
+
return { build, download, expiresAt, consumed: false, result: null, house: a.house, noFillReason: a.noFillReason };
|
|
748
879
|
}
|
|
749
880
|
}
|
package/src/core/config.ts
CHANGED
|
@@ -25,7 +25,7 @@ export function defaultConfig(serveBase: string): EthiclyConfig {
|
|
|
25
25
|
enabled: true,
|
|
26
26
|
min_sdk: { ios: '0.0.0', android: '0.0.0' },
|
|
27
27
|
formats: ['interstitial', '300x250'],
|
|
28
|
-
interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
|
|
28
|
+
interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on', sponsor_label: true, house_ads: true },
|
|
29
29
|
prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
|
|
30
30
|
beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
|
|
31
31
|
endpoints: { serve: serveBase },
|
|
@@ -76,6 +76,9 @@ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig |
|
|
|
76
76
|
max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
|
|
77
77
|
min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
|
|
78
78
|
audio,
|
|
79
|
+
// Only an explicit false hides the line.
|
|
80
|
+
sponsor_label: it.sponsor_label !== false,
|
|
81
|
+
house_ads: it.house_ads !== false,
|
|
79
82
|
},
|
|
80
83
|
prefetch: {
|
|
81
84
|
max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The tracker for a house ad: the publisher's own creative, shown when no paid
|
|
2
|
+
// ad fills. Nothing is billed, so there is no /impression, /viewable, video
|
|
3
|
+
// event or click token: only the unbilled /fallback-impression and
|
|
4
|
+
// /fallback-click counters, fire-and-forget, and none of them in test mode.
|
|
5
|
+
|
|
6
|
+
import { BEACON_TIMEOUT_MS, type BeaconContext } from './beacons';
|
|
7
|
+
import { isWebUrl } from './click';
|
|
8
|
+
import { httpRequest } from './http';
|
|
9
|
+
import type { EthiclyAd, Tracker } from './types';
|
|
10
|
+
|
|
11
|
+
export interface HouseTrackerDeps {
|
|
12
|
+
ctx: BeaconContext;
|
|
13
|
+
ad: EthiclyAd;
|
|
14
|
+
/** The house ad id the server sent (fallback_id on the wire). */
|
|
15
|
+
fallbackId: number;
|
|
16
|
+
/** Test mode: the counters are never sent. */
|
|
17
|
+
test: boolean;
|
|
18
|
+
openUrl?: (url: string) => unknown;
|
|
19
|
+
/** Called once when the ad is shown: a house ad counts toward the frequency caps. */
|
|
20
|
+
onShown(): void;
|
|
21
|
+
/** createEthicly's onHouseAdPress, if any. */
|
|
22
|
+
onPress?: (ad: EthiclyAd) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class HouseTracker implements Tracker {
|
|
26
|
+
/**
|
|
27
|
+
* Where the ready-made screen sends a tap instead of opening the link:
|
|
28
|
+
* createEthicly's onHouseAdPress, replaced by useEthiclyInterstitial's.
|
|
29
|
+
* EthiclyInterstitial's own prop wins over both.
|
|
30
|
+
*/
|
|
31
|
+
/** @internal Set by the SDK; apps pass onHouseAdPress instead. */
|
|
32
|
+
houseAdPress: ((ad: EthiclyAd) => void) | undefined;
|
|
33
|
+
private shownOnce = false;
|
|
34
|
+
private clickedOnce = false;
|
|
35
|
+
private pending = new Set<Promise<unknown>>();
|
|
36
|
+
|
|
37
|
+
constructor(private d: HouseTrackerDeps) {
|
|
38
|
+
this.houseAdPress = d.onPress;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Resolves when every counter in flight has settled. For tests. */
|
|
42
|
+
async settle(): Promise<void> {
|
|
43
|
+
while (this.pending.size) await Promise.all(Array.from(this.pending)).catch(() => undefined);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
isExpired(): boolean {
|
|
47
|
+
return this.d.ctx.now() >= this.d.ad.expiresAt;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* One POST to a house-ad counter, never retried, never awaited by the
|
|
52
|
+
* caller. The answer (200, 400 or 429) changes nothing. Never rejects.
|
|
53
|
+
*/
|
|
54
|
+
private send(route: 'fallback-impression' | 'fallback-click'): void {
|
|
55
|
+
const { ctx } = this.d;
|
|
56
|
+
if (this.d.test) return;
|
|
57
|
+
const p = httpRequest(ctx.fetch, `${ctx.serveBase()}/${route}`, {
|
|
58
|
+
method: 'POST', headers: ctx.headers(), body: { fallback_id: this.d.fallbackId }, timeoutMs: BEACON_TIMEOUT_MS,
|
|
59
|
+
}).then((res) => {
|
|
60
|
+
if (res.status !== 200) ctx.log.debug(`/${route} answered ${res.status || 'nothing'}`);
|
|
61
|
+
}).catch((e) => ctx.log.debug(`/${route} failed`, e));
|
|
62
|
+
this.pending.add(p);
|
|
63
|
+
p.finally(() => this.pending.delete(p)).catch(() => undefined);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
shown(): Promise<void> {
|
|
67
|
+
if (this.shownOnce) return Promise.resolve();
|
|
68
|
+
this.shownOnce = true;
|
|
69
|
+
if (this.isExpired()) {
|
|
70
|
+
this.d.ctx.log.error(`house ad ${this.d.fallbackId} expired before it was shown; load a new one`);
|
|
71
|
+
return Promise.resolve();
|
|
72
|
+
}
|
|
73
|
+
try { this.d.onShown(); } catch { /* never throw */ }
|
|
74
|
+
this.send('fallback-impression');
|
|
75
|
+
return Promise.resolve();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
progress(_positionMs: number, _opts: { visible: boolean; durationMs?: number }): void { /* house ads report no playback */ }
|
|
79
|
+
complete(): void { /* no video events for house ads */ }
|
|
80
|
+
skipped(_positionMs: number): void { /* no video events for house ads */ }
|
|
81
|
+
error(): void { /* no video events for house ads */ }
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Counts the tap once (fire-and-forget) and opens the destination right
|
|
85
|
+
* away. `{ open: false }` only counts it: the app shows its own screen.
|
|
86
|
+
*/
|
|
87
|
+
async clicked(opts?: { open?: boolean }): Promise<string> {
|
|
88
|
+
const url = this.d.ad.destinationUrl;
|
|
89
|
+
if (!this.clickedOnce) {
|
|
90
|
+
this.clickedOnce = true;
|
|
91
|
+
this.send('fallback-click');
|
|
92
|
+
}
|
|
93
|
+
if (opts?.open === false) return url;
|
|
94
|
+
if (!isWebUrl(url)) {
|
|
95
|
+
this.d.ctx.log.error(`house ad ${this.d.fallbackId}: destination is not an http(s) URL, not opened`);
|
|
96
|
+
return url;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
if (this.d.openUrl) await this.d.openUrl(url);
|
|
100
|
+
else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
|
|
101
|
+
} catch (e) {
|
|
102
|
+
this.d.ctx.log.error('openUrl failed', e);
|
|
103
|
+
}
|
|
104
|
+
return url;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async closed(): Promise<void> { /* nothing is queued for a house ad */ }
|
|
108
|
+
}
|
package/src/core/index.ts
CHANGED
|
@@ -10,6 +10,6 @@ export { compareVersions, BUNDLED_BASE_URL } from './config';
|
|
|
10
10
|
export { SDK_VERSION } from '../version';
|
|
11
11
|
export type {
|
|
12
12
|
AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions,
|
|
13
|
-
FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason,
|
|
13
|
+
FrequencyUpdate, InterstitialResult, KeyValueStorage, LoadOptions, Logger, NextAdReason, NextAdStatus, NoFillReason,
|
|
14
14
|
Platform, Tracker,
|
|
15
15
|
} from './types';
|
package/src/core/types.ts
CHANGED
|
@@ -14,6 +14,16 @@ export interface EthiclyConfig {
|
|
|
14
14
|
max_per_session: number;
|
|
15
15
|
min_gap_s: number;
|
|
16
16
|
audio: AudioPolicy;
|
|
17
|
+
/**
|
|
18
|
+
* Whether the paid-ad screen shows "Sponsored by Ethicly.ch", set in the
|
|
19
|
+
* publisher's dashboard. Absent from the server: true.
|
|
20
|
+
*/
|
|
21
|
+
sponsor_label: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* The publisher's dashboard master switch for house ads. false: the SDK
|
|
24
|
+
* never asks for one. Absent from the server: true.
|
|
25
|
+
*/
|
|
26
|
+
house_ads: boolean;
|
|
17
27
|
};
|
|
18
28
|
prefetch: { max_cached_creatives: number; max_cache_mb: number };
|
|
19
29
|
beacon: { viewable_after_ms: number; flush_interval_s: number };
|
|
@@ -133,6 +143,18 @@ export interface EthiclyAd {
|
|
|
133
143
|
servedAt: number;
|
|
134
144
|
/** Epoch ms after which the ad must not be shown (served + token_ttl_s). */
|
|
135
145
|
expiresAt: number;
|
|
146
|
+
/**
|
|
147
|
+
* True for the publisher's own house ad, uploaded in the dashboard and shown
|
|
148
|
+
* when no paid ad fills. Unbilled, but it counts toward the frequency caps.
|
|
149
|
+
*/
|
|
150
|
+
house: boolean;
|
|
151
|
+
/** For a house ad: why no paid ad filled (the server's reason). Unset for a paid ad. */
|
|
152
|
+
noFillReason?: NoFillReason;
|
|
153
|
+
/**
|
|
154
|
+
* Show "Sponsored by Ethicly.ch" with this ad. false for house ads, else the
|
|
155
|
+
* dashboard setting (/config interstitial.sponsor_label, default true).
|
|
156
|
+
*/
|
|
157
|
+
showSponsorLabel: boolean;
|
|
136
158
|
}
|
|
137
159
|
|
|
138
160
|
export interface Tracker {
|
|
@@ -143,14 +165,28 @@ export interface Tracker {
|
|
|
143
165
|
complete(): void;
|
|
144
166
|
skipped(positionMs: number): void;
|
|
145
167
|
error(): void;
|
|
146
|
-
/**
|
|
147
|
-
|
|
168
|
+
/**
|
|
169
|
+
* POST /click (500 ms budget), then open the destination. Resolves with the URL opened.
|
|
170
|
+
* House ads only: `{ open: false }` counts the tap without opening anything,
|
|
171
|
+
* for an app that sends it to its own screen. A paid ad always opens the
|
|
172
|
+
* advertiser's page.
|
|
173
|
+
*/
|
|
174
|
+
clicked(opts?: { open?: boolean }): Promise<string>;
|
|
148
175
|
/** Call when the ad screen goes away. Sends queued video events. */
|
|
149
176
|
closed(): Promise<void>;
|
|
150
177
|
/** True once the ad is older than token_ttl_s: it must not be shown. */
|
|
151
178
|
isExpired(): boolean;
|
|
152
179
|
}
|
|
153
180
|
|
|
181
|
+
/** Per-call options for preload() and loadInterstitial(). */
|
|
182
|
+
export interface LoadOptions {
|
|
183
|
+
/**
|
|
184
|
+
* false treats a house ad as no fill for this call, so the app can show its
|
|
185
|
+
* own fallback. Default: the client's setting (options.houseAds, default true).
|
|
186
|
+
*/
|
|
187
|
+
houseAds?: boolean;
|
|
188
|
+
}
|
|
189
|
+
|
|
154
190
|
export type InterstitialResult =
|
|
155
191
|
| { ad: EthiclyAd; tracker: Tracker; reason?: undefined }
|
|
156
192
|
| { ad: null; tracker: null; reason: NoFillReason };
|
|
@@ -173,9 +209,15 @@ export interface WireAd {
|
|
|
173
209
|
} | null;
|
|
174
210
|
}
|
|
175
211
|
|
|
212
|
+
/** Raw house ad, sent next to `ad: null` on an interstitial no-fill when the serve asked with house_ads=1. */
|
|
213
|
+
export interface WireHouseAd extends WireAd {
|
|
214
|
+
test?: boolean;
|
|
215
|
+
}
|
|
216
|
+
|
|
176
217
|
export interface WireServe {
|
|
177
218
|
ad: WireAd | null;
|
|
178
219
|
reason?: string;
|
|
220
|
+
house_ad?: WireHouseAd | null;
|
|
179
221
|
publisher_site_id?: number;
|
|
180
222
|
country_code?: string;
|
|
181
223
|
impression_token?: string;
|