@ethicly/react-native 0.0.0-stage → 0.2.1

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/README.md +428 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +326 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +261 -0
  9. package/lib/commonjs/core/click.js +29 -0
  10. package/lib/commonjs/core/client.js +585 -0
  11. package/lib/commonjs/core/config.js +128 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +21 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +379 -0
  16. package/lib/commonjs/core/types.js +4 -0
  17. package/lib/commonjs/index.js +22 -0
  18. package/lib/commonjs/interstitial.js +7 -0
  19. package/lib/commonjs/react/EthiclyInterstitial.js +319 -0
  20. package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
  21. package/lib/commonjs/version.js +5 -0
  22. package/lib/module/core/adapters.js +315 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +257 -0
  25. package/lib/module/core/click.js +24 -0
  26. package/lib/module/core/client.js +581 -0
  27. package/lib/module/core/config.js +118 -0
  28. package/lib/module/core/http.js +105 -0
  29. package/lib/module/core/index.js +6 -0
  30. package/lib/module/core/outbox.js +186 -0
  31. package/lib/module/core/tracker.js +375 -0
  32. package/lib/module/core/types.js +3 -0
  33. package/lib/module/index.js +4 -0
  34. package/lib/module/interstitial.js +3 -0
  35. package/lib/module/react/EthiclyInterstitial.js +292 -0
  36. package/lib/module/react/useEthiclyInterstitial.js +51 -0
  37. package/lib/module/version.js +2 -0
  38. package/lib/typescript/core/adapters.d.ts +139 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +71 -0
  41. package/lib/typescript/core/click.d.ts +13 -0
  42. package/lib/typescript/core/client.d.ts +78 -0
  43. package/lib/typescript/core/config.d.ts +33 -0
  44. package/lib/typescript/core/http.d.ts +34 -0
  45. package/lib/typescript/core/index.d.ts +8 -0
  46. package/lib/typescript/core/outbox.d.ts +56 -0
  47. package/lib/typescript/core/tracker.d.ts +95 -0
  48. package/lib/typescript/core/types.d.ts +175 -0
  49. package/lib/typescript/index.d.ts +3 -0
  50. package/lib/typescript/interstitial.d.ts +2 -0
  51. package/lib/typescript/react/EthiclyInterstitial.d.ts +51 -0
  52. package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
  53. package/lib/typescript/version.d.ts +2 -0
  54. package/package.json +101 -4
  55. package/src/core/adapters.ts +365 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +261 -0
  58. package/src/core/click.ts +26 -0
  59. package/src/core/client.ts +665 -0
  60. package/src/core/config.ts +124 -0
  61. package/src/core/http.ts +115 -0
  62. package/src/core/index.ts +14 -0
  63. package/src/core/outbox.ts +193 -0
  64. package/src/core/tracker.ts +376 -0
  65. package/src/core/types.ts +185 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +432 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,665 @@
1
+ // createEthicly: config, serve, prefetch, frequency caps and the ads switch.
2
+ // Pure TypeScript; every native capability comes in through an adapter.
3
+
4
+ import {
5
+ createMemoryFileCache, createMemoryStorage, defaultAppState, isReleaseBuild, safeLogger, type AppStateLike,
6
+ } from './adapters';
7
+ import type { BeaconContext } from './beacons';
8
+ import { CreativeCache, type CachedMedia } from './cache';
9
+ import { isWebUrl } from './click';
10
+ import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
11
+ import { httpRequest, RouteGate } from './http';
12
+ import { outboxFor, replayRecord, type Outbox } from './outbox';
13
+ import { InterstitialTracker } from './tracker';
14
+ import { SDK_VERSION } from '../version';
15
+ import type {
16
+ AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
17
+ Logger, NoFillReason, Platform, WireServe,
18
+ } from './types';
19
+
20
+ export interface EthiclyOptions {
21
+ /** Publisher API key (UUID). */
22
+ apiKey: string;
23
+ /** The OS the app runs on. Never "rn": the server ignores unknown platforms. */
24
+ platform: Platform;
25
+ /** The host app's version, sent as app_version. */
26
+ appVersion: string;
27
+ /** The bundled URL /config is fetched from. Default https://ads.ethicly.ch/functions/v1/get-ad-with-geo */
28
+ baseUrl?: string;
29
+ /**
30
+ * Adds test=1 to serve. Ignored in a React Native release build
31
+ * (`__DEV__` false), where the SDK serves and bills normally and logs an error.
32
+ */
33
+ testMode?: boolean;
34
+ /**
35
+ * Initial state of the ads switch, default true. Apps with a paid tier: pass
36
+ * false until you know the user's entitlement, then setAdsEnabled(true) for
37
+ * free users, so a subscriber never serves or downloads an ad.
38
+ */
39
+ adsEnabled?: boolean;
40
+ /**
41
+ * Sound for every ad, over the server's interstitial.audio: 'on' plays with
42
+ * sound, 'optional' starts muted with a sound toggle, 'none' plays muted with
43
+ * no toggle. Unset: the server's value, which defaults to 'on'. `ad.audio`
44
+ * is the effective value. EthiclyInterstitial's `audio` prop overrides it per screen.
45
+ */
46
+ audio?: AudioPolicy;
47
+ /**
48
+ * The longest loadInterstitial() waits for the creative download when no
49
+ * preloaded ad is ready, in ms. Default 3000 (DEFAULT_LOAD_TIMEOUT_MS). After
50
+ * it the ad comes back with the remote URL, so the player streams, and the
51
+ * download carries on in the background for next time.
52
+ */
53
+ loadTimeoutMs?: number;
54
+ storage?: KeyValueStorage;
55
+ fileCache?: FileCacheAdapter;
56
+ openUrl?: (url: string) => unknown;
57
+ fetch?: FetchLike;
58
+ now?: () => number;
59
+ logger?: Logger;
60
+ /**
61
+ * App foreground and background changes, for sessions. Defaults to React
62
+ * Native's AppState; null turns sessions off (one session per process).
63
+ */
64
+ appState?: AppStateLike | null;
65
+ }
66
+
67
+ export interface Ethicly {
68
+ /** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
69
+ readonly ready: Promise<void>;
70
+ /** Serve and download an interstitial ahead of time. Does not consume it. */
71
+ preload(): Promise<InterstitialResult>;
72
+ /** The ad to show now: the preloaded one if still valid, else a fresh serve. Consumes it. */
73
+ loadInterstitial(): Promise<InterstitialResult>;
74
+ /**
75
+ * Frequency caps, the ads switch and the kill switch, checked client-side.
76
+ * false until the stored frequency state has loaded (see `ready`).
77
+ */
78
+ canShow(): boolean;
79
+ /** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
80
+ setAdsEnabled(enabled: boolean): void;
81
+ isAdsEnabled(): boolean;
82
+ getConfig(): EthiclyConfig;
83
+ /** Refetch /config now (subject to Retry-After). */
84
+ refreshConfig(): Promise<void>;
85
+ /** Why the last load returned no ad. */
86
+ readonly lastNoFillReason: NoFillReason | null;
87
+ readonly sdkVersion: string;
88
+ }
89
+
90
+ /** How long loadInterstitial() waits for a creative download by default. */
91
+ export const DEFAULT_LOAD_TIMEOUT_MS = 3000;
92
+ const CONFIG_TIMEOUT_MS = 5000;
93
+ const SERVE_TIMEOUT_MS = 8000;
94
+ const SIZE_PROBE_TIMEOUT_MS = 3000;
95
+ const CONFIG_RETRY_AFTER_FAILURE_MS = 30000;
96
+ const DEFAULT_TTL_S = 3600;
97
+ /**
98
+ * A new session (interstitial.max_per_session counts from zero again) starts
99
+ * when the app comes back after at least this long in the background.
100
+ */
101
+ export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
102
+
103
+ let releaseTestModeLogged = false;
104
+
105
+ interface StoredConfig { config: EthiclyConfig; fetchedAt: number; maxAgeS: number }
106
+ interface StoredFrequency { lastShownAt: number }
107
+
108
+ interface Preloaded { result: { ad: EthiclyAd; tracker: InterstitialTracker } }
109
+
110
+ /** A served ad whose creative is downloading. Built into an ad once, by preload() or loadInterstitial(). */
111
+ interface Served {
112
+ download: Promise<CachedMedia>;
113
+ build(uris: Record<string, string>): Preloaded['result'];
114
+ expiresAt: number;
115
+ /** Taken by loadInterstitial(): never stored as the preloaded ad. */
116
+ consumed: boolean;
117
+ result: Preloaded['result'] | null;
118
+ }
119
+
120
+ type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
121
+
122
+ function audioPolicy(v: unknown): AudioPolicy | null {
123
+ return v === 'on' || v === 'optional' || v === 'none' ? v : null;
124
+ }
125
+
126
+ export function createEthicly(options: EthiclyOptions): Ethicly {
127
+ return new EthiclyClient(options);
128
+ }
129
+
130
+ class EthiclyClient implements Ethicly {
131
+ readonly ready: Promise<void>;
132
+ readonly sdkVersion = SDK_VERSION;
133
+ lastNoFillReason: NoFillReason | null = null;
134
+
135
+ private bundled: string;
136
+ private fetchFn: FetchLike;
137
+ private now: () => number;
138
+ private log: Required<Logger>;
139
+ private storage: KeyValueStorage;
140
+ private cache: CreativeCache;
141
+ private gate: RouteGate;
142
+
143
+ private config: EthiclyConfig;
144
+ private configSource: 'default' | 'stored' | 'network' = 'default';
145
+ private configFetchedAt = 0;
146
+ private configMaxAgeS = 300;
147
+ private configRetryAt = 0;
148
+ private configInflight: Promise<void> | null = null;
149
+ /** 404 unknown_key with no stored config. */
150
+ private unknownKey = false;
151
+ /** 400 or 403 on a key: integration bug, stop for this process. */
152
+ private invalidKey = false;
153
+ /** app_disabled from serve: until a later /config says enabled. */
154
+ private appDisabled = false;
155
+ /** sdk_unsupported: for the rest of the process lifetime. */
156
+ private sdkUnsupported = false;
157
+
158
+ private adsOn: boolean;
159
+ private testMode: boolean;
160
+ private shownCount = 0;
161
+ private lastShownAt: number | null = null;
162
+ private frequencyLoaded = false;
163
+ /** When the app left the foreground, null while it is in it. */
164
+ private backgroundSince: number | null = null;
165
+ private outbox: Outbox;
166
+ private preloaded: Preloaded | null = null;
167
+ private serveInflight: Promise<ServeOutcome> | null = null;
168
+ /** Served, creative still downloading, not yet taken. */
169
+ private pendingServed: Served | null = null;
170
+ private loadTimeoutMs: number;
171
+ private audio: AudioPolicy | null;
172
+ private badDestinationLogged = false;
173
+
174
+ constructor(private o: EthiclyOptions) {
175
+ this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
176
+ const f = o.fetch || (globalThis as { fetch?: FetchLike }).fetch;
177
+ if (!f) throw new Error('[ethicly] no fetch available: pass options.fetch');
178
+ this.fetchFn = f;
179
+ this.now = o.now || Date.now;
180
+ this.log = safeLogger(o.logger);
181
+ this.storage = o.storage || createMemoryStorage();
182
+ this.gate = new RouteGate(this.now);
183
+ // The size probe only matters when files really land on disk.
184
+ this.cache = new CreativeCache(
185
+ o.fileCache || createMemoryFileCache(), this.storage, 'ethicly:v1:cache', this.now, this.log,
186
+ o.fileCache ? (url) => this.contentLength(url) : undefined,
187
+ );
188
+ this.config = defaultConfig(this.bundled);
189
+ this.adsOn = o.adsEnabled !== false;
190
+ this.audio = audioPolicy(o.audio);
191
+ if (o.audio !== undefined && !this.audio) this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
192
+ this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
193
+ ? o.loadTimeoutMs
194
+ : DEFAULT_LOAD_TIMEOUT_MS;
195
+ this.testMode = !!o.testMode && !isReleaseBuild();
196
+ if (o.testMode && !this.testMode) this.reportReleaseTestMode();
197
+ if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
198
+ this.outbox = outboxFor(this.storage, o.apiKey, this.log);
199
+ this.watchAppState(o.appState === undefined ? defaultAppState() : o.appState);
200
+ this.ready = this.init().catch((e) => this.log.error('init failed', e));
201
+ }
202
+
203
+ /** testMode in a release build would earn the publisher nothing: ignore it, loudly, once. */
204
+ private reportReleaseTestMode(): void {
205
+ const msg = 'testMode is set in a release build: ignored, ads are served and billed normally. Set testMode: __DEV__.';
206
+ this.log.error(msg);
207
+ if (releaseTestModeLogged) return;
208
+ releaseTestModeLogged = true;
209
+ try { (globalThis as { console?: { error?: (m: string) => void } }).console?.error?.(`[ethicly] ${msg}`); } catch { /* never throw */ }
210
+ }
211
+
212
+ /** Sessions: back in the foreground after SESSION_TIMEOUT_MS or more starts a new one. */
213
+ private watchAppState(appState: AppStateLike | null): void {
214
+ if (!appState) return;
215
+ const onChange = (state: string) => {
216
+ if (state === 'active') {
217
+ if (this.backgroundSince !== null && this.now() - this.backgroundSince >= SESSION_TIMEOUT_MS) {
218
+ this.shownCount = 0;
219
+ this.log.debug('new session after time in the background');
220
+ }
221
+ this.backgroundSince = null;
222
+ } else if (this.backgroundSince === null) {
223
+ this.backgroundSince = this.now();
224
+ }
225
+ };
226
+ try {
227
+ if (appState.currentState && appState.currentState !== 'active') onChange(appState.currentState);
228
+ // Kept for the life of the client, which is the life of the process.
229
+ appState.addEventListener('change', (s) => { try { onChange(s); } catch { /* never throw */ } });
230
+ } catch (e) {
231
+ this.log.warn('could not watch AppState: one session per process', e);
232
+ }
233
+ }
234
+
235
+ /** Content-Length from a HEAD request, so an oversized creative is never written. */
236
+ private async contentLength(url: string): Promise<number | null> {
237
+ let timer: ReturnType<typeof setTimeout> | undefined;
238
+ try {
239
+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), SIZE_PROBE_TIMEOUT_MS); });
240
+ const res = await Promise.race([this.fetchFn(url, { method: 'HEAD' }), timeout]);
241
+ if (!res) return null;
242
+ const n = Number(res.headers.get('content-length'));
243
+ return res.status >= 200 && res.status < 300 && Number.isFinite(n) && n > 0 ? n : null;
244
+ } catch {
245
+ return null;
246
+ } finally {
247
+ if (timer) clearTimeout(timer);
248
+ }
249
+ }
250
+
251
+ // ------------------------------------------------------------- headers
252
+
253
+ private headers(): Record<string, string> {
254
+ return { 'X-Ethicly-SDK': `${this.o.platform}/${SDK_VERSION}` };
255
+ }
256
+
257
+ private serveBase(): string {
258
+ return this.configSource === 'default' ? this.bundled : this.config.endpoints.serve;
259
+ }
260
+
261
+ private beaconCtx(): BeaconContext {
262
+ return {
263
+ fetch: this.fetchFn,
264
+ serveBase: () => this.serveBase(),
265
+ headers: () => this.headers(),
266
+ gate: this.gate,
267
+ now: this.now,
268
+ log: this.log,
269
+ };
270
+ }
271
+
272
+ // ------------------------------------------------------------- config
273
+
274
+ private get storageKey(): string {
275
+ return `ethicly:v1:config:${this.o.apiKey}`;
276
+ }
277
+
278
+ private get frequencyKey(): string {
279
+ return `ethicly:v1:frequency:${this.o.apiKey}`;
280
+ }
281
+
282
+ /** The last shown time survives restarts, so min_gap_s does too. Never rejects. */
283
+ private async loadFrequency(): Promise<void> {
284
+ try {
285
+ const raw = await this.storage.getItem(this.frequencyKey);
286
+ const t = raw ? (JSON.parse(raw) as StoredFrequency).lastShownAt : null;
287
+ // A time in the future (the clock moved back) is ignored.
288
+ if (typeof t === 'number' && Number.isFinite(t) && t <= this.now()) {
289
+ this.lastShownAt = Math.max(this.lastShownAt ?? 0, t);
290
+ }
291
+ } catch (e) {
292
+ this.log.warn('stored frequency state unreadable', e);
293
+ } finally {
294
+ this.frequencyLoaded = true;
295
+ }
296
+ }
297
+
298
+ private async init(): Promise<void> {
299
+ await Promise.all([this.loadFrequency(), this.outbox.load()]);
300
+ try {
301
+ const raw = await this.storage.getItem(this.storageKey);
302
+ if (raw) {
303
+ const s = JSON.parse(raw) as StoredConfig;
304
+ const parsed = parseConfig(s.config, this.bundled);
305
+ if (parsed) {
306
+ this.config = parsed;
307
+ this.configSource = 'stored';
308
+ this.configFetchedAt = s.fetchedAt;
309
+ this.configMaxAgeS = s.maxAgeS;
310
+ }
311
+ }
312
+ } catch (e) {
313
+ this.log.warn('stored config unreadable', e);
314
+ }
315
+ this.applyConfigGates();
316
+ if (this.configStale()) await this.refreshConfig();
317
+ void this.replayOutbox();
318
+ }
319
+
320
+ /**
321
+ * Send what a previous run left unsent, one ad at a time. Not while a kill
322
+ * switch is on (app_disabled, sdk_unsupported) or the key is refused: the
323
+ * records then stay stored and expire one hour after their ad was shown.
324
+ * Never rejects.
325
+ */
326
+ private async replayOutbox(): Promise<void> {
327
+ const blocked = this.blockedReason();
328
+ if (blocked && blocked !== 'interstitial_disabled') {
329
+ this.log.info(`unsent beacons from the last run held back: ${blocked}`);
330
+ return;
331
+ }
332
+ const orphans = this.outbox.claimOrphans(this.now());
333
+ if (orphans.length) this.log.info(`sending ${orphans.length} unsent beacon set(s) from the last run`);
334
+ for (const rec of orphans) await replayRecord(this.beaconCtx(), this.outbox, rec);
335
+ }
336
+
337
+ private configStale(): boolean {
338
+ return this.configSource !== 'network' && this.configSource !== 'stored'
339
+ ? true
340
+ : this.now() - this.configFetchedAt >= this.configMaxAgeS * 1000;
341
+ }
342
+
343
+ private applyConfigGates(): void {
344
+ if (this.configSource === 'default') return;
345
+ if (this.config.enabled) this.appDisabled = false;
346
+ const min = this.o.platform === 'ios' ? this.config.min_sdk.ios : this.config.min_sdk.android;
347
+ if (isBelowMinSdk(SDK_VERSION, min)) {
348
+ if (!this.sdkUnsupported) this.log.error(`SDK ${SDK_VERSION} is below min_sdk ${min}: no ads until the app updates`);
349
+ this.sdkUnsupported = true;
350
+ }
351
+ }
352
+
353
+ getConfig(): EthiclyConfig {
354
+ return this.config;
355
+ }
356
+
357
+ refreshConfig(): Promise<void> {
358
+ if (this.invalidKey || this.now() < this.configRetryAt) return Promise.resolve();
359
+ if (!this.configInflight) {
360
+ this.configInflight = this.fetchConfig().catch((e) => this.log.error('config fetch failed', e))
361
+ .finally(() => { this.configInflight = null; });
362
+ }
363
+ return this.configInflight;
364
+ }
365
+
366
+ private async fetchConfig(): Promise<void> {
367
+ const url = `${this.bundled}/config?key=${encodeURIComponent(this.o.apiKey)}&platform=${this.o.platform}`;
368
+ const res = await httpRequest(this.fetchFn, url, { headers: this.headers(), timeoutMs: CONFIG_TIMEOUT_MS });
369
+ if (res.status === 200) {
370
+ const parsed = parseConfig(res.body, this.bundled);
371
+ if (parsed) {
372
+ this.config = parsed;
373
+ this.configSource = 'network';
374
+ this.configFetchedAt = this.now();
375
+ this.configMaxAgeS = maxAgeSeconds(res.cacheControl);
376
+ this.unknownKey = false;
377
+ this.applyConfigGates();
378
+ const stored: StoredConfig = { config: parsed, fetchedAt: this.configFetchedAt, maxAgeS: this.configMaxAgeS };
379
+ await this.storage.setItem(this.storageKey, JSON.stringify(stored)).catch(() => undefined);
380
+ return;
381
+ }
382
+ this.log.warn('config body unreadable, keeping the last known config');
383
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
384
+ return;
385
+ }
386
+ if (res.status === 429) {
387
+ this.configRetryAt = this.now() + Math.max(1, res.retryAfterS ?? 1) * 1000;
388
+ this.log.warn('config rate limited, keeping the last known config');
389
+ return;
390
+ }
391
+ if (res.status === 404) {
392
+ // Kept for this session; with nothing stored there is no ad.
393
+ if (this.configSource === 'default') this.unknownKey = true;
394
+ this.configRetryAt = this.now() + this.configMaxAgeS * 1000;
395
+ this.log.warn('config 404 unknown_key (unknown or not approved site)');
396
+ return;
397
+ }
398
+ if (res.status === 400) {
399
+ this.invalidKey = true;
400
+ this.log.error('config 400: the API key is missing or not a UUID. Not retried.');
401
+ return;
402
+ }
403
+ // 5xx, timeout, network error: keep the last known config, retry later.
404
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
405
+ this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
406
+ }
407
+
408
+ // ------------------------------------------------------------- frequency
409
+
410
+ canShow(): boolean {
411
+ const it = this.config.interstitial;
412
+ if (!this.adsOn || !this.frequencyLoaded || this.blockedReason()) return false;
413
+ if (this.shownCount >= it.max_per_session) return false;
414
+ if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000) return false;
415
+ return true;
416
+ }
417
+
418
+ private onShown(): void {
419
+ this.shownCount += 1;
420
+ this.lastShownAt = this.now();
421
+ const stored: StoredFrequency = { lastShownAt: this.lastShownAt };
422
+ try {
423
+ this.storage.setItem(this.frequencyKey, JSON.stringify(stored)).catch(() => undefined);
424
+ } catch { /* a storage that throws synchronously must not reach the host */ }
425
+ }
426
+
427
+ setAdsEnabled(enabled: boolean): void {
428
+ this.adsOn = !!enabled;
429
+ if (this.adsOn) return;
430
+ this.preloaded = null;
431
+ this.pendingServed = null;
432
+ // A paid user downloads nothing: stop the creative download in flight.
433
+ this.cache.cancel();
434
+ }
435
+
436
+ isAdsEnabled(): boolean {
437
+ return this.adsOn;
438
+ }
439
+
440
+ // ------------------------------------------------------------- serve
441
+
442
+ private blockedReason(): NoFillReason | null {
443
+ if (this.invalidKey) return 'invalid_key';
444
+ if (this.unknownKey) return 'unknown_key';
445
+ if (this.sdkUnsupported) return 'sdk_unsupported';
446
+ if (this.appDisabled || (this.configSource !== 'default' && !this.config.enabled)) return 'app_disabled';
447
+ if (this.configSource !== 'default' && this.config.formats.indexOf('interstitial') === -1) return 'interstitial_disabled';
448
+ return null;
449
+ }
450
+
451
+ private noFill(reason: NoFillReason): InterstitialResult {
452
+ this.lastNoFillReason = reason;
453
+ this.log.info(`no ad: ${reason}`);
454
+ return { ad: null, tracker: null, reason };
455
+ }
456
+
457
+ /** The served ad waiting for its download, or a new serve. One serve at a time. */
458
+ private serveOnce(): Promise<ServeOutcome> {
459
+ const p = this.pendingServed;
460
+ if (p && !p.consumed && this.now() < p.expiresAt) return Promise.resolve({ served: p });
461
+ this.pendingServed = null;
462
+ if (!this.serveInflight) {
463
+ this.serveInflight = this.serve()
464
+ .then((out) => {
465
+ if (out.served) this.pendingServed = out.served;
466
+ return out;
467
+ })
468
+ .finally(() => { this.serveInflight = null; });
469
+ }
470
+ return this.serveInflight;
471
+ }
472
+
473
+ /** The ad and tracker of a served ad, built once, by whoever asks first. */
474
+ private claim(s: Served, uris: Record<string, string>): Preloaded['result'] {
475
+ if (!s.result) s.result = s.build(uris);
476
+ return s.result;
477
+ }
478
+
479
+ async preload(): Promise<InterstitialResult> {
480
+ try {
481
+ if (!this.adsOn) return this.noFill('ads_disabled');
482
+ if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
483
+ this.preloaded = null;
484
+ if (this.shownCount >= this.config.interstitial.max_per_session) return this.noFill('frequency_capped');
485
+ const out = await this.serveOnce();
486
+ if (!out.served) return out.noFill;
487
+ const s = out.served;
488
+ // In the background: wait for the whole download, so the ad plays from disk.
489
+ const cached = await s.download;
490
+ if (!this.adsOn) return this.noFill('ads_disabled');
491
+ const r = this.claim(s, cached.uris);
492
+ if (!s.consumed) {
493
+ this.preloaded = { result: r };
494
+ if (this.pendingServed === s) this.pendingServed = null;
495
+ }
496
+ return r;
497
+ } catch (e) {
498
+ this.log.error('preload failed', e);
499
+ return this.noFill('network_error');
500
+ }
501
+ }
502
+
503
+ async loadInterstitial(): Promise<InterstitialResult> {
504
+ try {
505
+ await this.ready;
506
+ if (!this.adsOn) return this.noFill('ads_disabled');
507
+ if (this.configStale()) await this.refreshConfig();
508
+ const blocked = this.blockedReason();
509
+ if (blocked) return this.noFill(blocked);
510
+ if (!this.canShow()) return this.noFill('frequency_capped');
511
+ const pre = this.preloaded;
512
+ this.preloaded = null;
513
+ if (pre && !pre.result.tracker.isExpired()) return pre.result;
514
+
515
+ const out = await this.serveOnce();
516
+ if (!out.served) return out.noFill;
517
+ const s = out.served;
518
+ // The user is waiting: give the download a short budget, then stream the
519
+ // remote file. The download carries on in the background for next time.
520
+ const cached = await this.within(s.download, this.loadTimeoutMs);
521
+ if (!this.adsOn) return this.noFill('ads_disabled');
522
+ if (!cached) this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
523
+ const r = this.claim(s, cached ? cached.uris : {});
524
+ s.consumed = true;
525
+ if (this.pendingServed === s) this.pendingServed = null;
526
+ // A preload that finished meanwhile may have stored this same ad.
527
+ if ((this.preloaded as Preloaded | null)?.result === r) this.preloaded = null;
528
+ return r;
529
+ } catch (e) {
530
+ this.log.error('loadInterstitial failed', e);
531
+ return this.noFill('network_error');
532
+ }
533
+ }
534
+
535
+ /** `p`, or null once `ms` have passed first. */
536
+ private within<T>(p: Promise<T>, ms: number): Promise<T | null> {
537
+ let timer: ReturnType<typeof setTimeout> | undefined;
538
+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), ms); });
539
+ return Promise.race([p, timeout]).finally(() => { if (timer) clearTimeout(timer); });
540
+ }
541
+
542
+ private async serve(): Promise<ServeOutcome> {
543
+ const noFill = (reason: NoFillReason): ServeOutcome => ({ noFill: this.noFill(reason) });
544
+ await this.ready;
545
+ if (this.configStale()) await this.refreshConfig();
546
+ const blocked = this.blockedReason();
547
+ if (blocked) return noFill(blocked);
548
+ if (this.gate.waitMs('serve') > 0) return noFill('rate_limited');
549
+
550
+ const q = [
551
+ `key=${encodeURIComponent(this.o.apiKey)}`,
552
+ 'format=interstitial',
553
+ `platform=${this.o.platform}`,
554
+ `sdk_version=${encodeURIComponent(SDK_VERSION)}`,
555
+ `app_version=${encodeURIComponent(this.o.appVersion)}`,
556
+ ];
557
+ if (this.testMode) q.push('test=1');
558
+ const res = await httpRequest(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
559
+ headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
560
+ });
561
+ const servedAt = this.now();
562
+ if (res.status === 429) {
563
+ this.gate.block('serve', res.retryAfterS);
564
+ return noFill('rate_limited');
565
+ }
566
+ if (res.status === 400 || res.status === 403) {
567
+ this.invalidKey = true;
568
+ this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
569
+ return noFill('invalid_key');
570
+ }
571
+ if (res.status === 0) return noFill('network_error');
572
+ if (res.status !== 200 || !res.body || typeof res.body !== 'object') return noFill('server_error');
573
+
574
+ const body = res.body as WireServe;
575
+ if (!body.ad) {
576
+ const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
577
+ if (reason === 'app_disabled') this.appDisabled = true;
578
+ if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
579
+ return noFill(reason);
580
+ }
581
+ const ad = body.ad;
582
+ const m = ad.media;
583
+ if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
584
+ this.log.warn('serve answered an ad without media or destination', body.request_id);
585
+ return noFill('invalid_response');
586
+ }
587
+ if (!isWebUrl(ad.destination_url)) {
588
+ // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
589
+ if (!this.badDestinationLogged) {
590
+ this.badDestinationLogged = true;
591
+ this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
592
+ }
593
+ return noFill('invalid_response');
594
+ }
595
+ if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
596
+ if (!this.adsOn) return noFill('ads_disabled');
597
+
598
+ const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
599
+ const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
600
+ const pf = this.config.prefetch;
601
+ // Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
602
+ const download = this.cache.ensure(
603
+ ad.id,
604
+ poster ? [m.url, poster] : [m.url],
605
+ { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
606
+ () => this.adsOn,
607
+ ).catch(() => ({ uris: {} as Record<string, string> }));
608
+ const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
609
+ const expiresAt = servedAt + ttlS * 1000;
610
+ const adId = ad.id;
611
+ const mediaUrl = m.url;
612
+ const destinationUrl = ad.destination_url;
613
+ const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
614
+ const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
615
+ // The ad's value wins over /config, kept within the same 8 to 15 s range.
616
+ const skipAfterMs = clampSkipAfterMs(ad.skip_after_ms) ?? this.config.interstitial.skip_after_ms;
617
+ // The app's choice (options.audio) wins over the server's interstitial.audio.
618
+ const audio: AudioPolicy = this.audio ?? this.config.interstitial.audio;
619
+ const build = (uris: Record<string, string>): Preloaded['result'] => {
620
+ const uri = uris[mediaUrl] || mediaUrl;
621
+ const result: EthiclyAd = {
622
+ id: adId,
623
+ ctaLabel: label || 'Learn more',
624
+ destinationUrl,
625
+ skipAfterMs,
626
+ media: {
627
+ kind,
628
+ uri,
629
+ videoUri: kind === 'video' ? uri : null,
630
+ posterUri: poster ? uris[poster] || poster : null,
631
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
632
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
633
+ width: posInt(m.width, 720),
634
+ height: posInt(m.height, 1280),
635
+ cached: uri !== mediaUrl,
636
+ },
637
+ audio,
638
+ title: typeof ad.title === 'string' ? ad.title : null,
639
+ test: body.test === true,
640
+ servedAt,
641
+ expiresAt,
642
+ };
643
+ const tracker = new InterstitialTracker({
644
+ ctx: this.beaconCtx(),
645
+ ad: result,
646
+ serve: {
647
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
648
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
649
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
650
+ },
651
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
652
+ flushIntervalS: this.config.beacon.flush_interval_s,
653
+ platform: this.o.platform,
654
+ sdkVersion: SDK_VERSION,
655
+ appVersion: this.o.appVersion,
656
+ openUrl: this.o.openUrl,
657
+ onShown: () => this.onShown(),
658
+ outbox: this.outbox,
659
+ });
660
+ return { ad: result, tracker };
661
+ };
662
+ this.lastNoFillReason = null;
663
+ return { served: { build, download, expiresAt, consumed: false, result: null } };
664
+ }
665
+ }