@ethicly/react-native 0.0.0-stage → 0.2.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/LICENSE +21 -0
  3. package/README.md +313 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +287 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +206 -0
  9. package/lib/commonjs/core/click.js +19 -0
  10. package/lib/commonjs/core/client.js +489 -0
  11. package/lib/commonjs/core/config.js +113 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +20 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +374 -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 +286 -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 +276 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +202 -0
  25. package/lib/module/core/click.js +15 -0
  26. package/lib/module/core/client.js +485 -0
  27. package/lib/module/core/config.js +104 -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 +370 -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 +260 -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 +138 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +53 -0
  41. package/lib/typescript/core/click.d.ts +8 -0
  42. package/lib/typescript/core/client.d.ts +58 -0
  43. package/lib/typescript/core/config.d.ts +24 -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 +170 -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 +39 -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 +337 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +216 -0
  58. package/src/core/click.ts +16 -0
  59. package/src/core/client.ts +547 -0
  60. package/src/core/config.ts +111 -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 +371 -0
  65. package/src/core/types.ts +180 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +386 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,547 @@
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 } from './cache';
9
+ import { BUNDLED_BASE_URL, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
10
+ import { httpRequest, RouteGate } from './http';
11
+ import { outboxFor, replayRecord, type Outbox } from './outbox';
12
+ import { InterstitialTracker } from './tracker';
13
+ import { SDK_VERSION } from '../version';
14
+ import type {
15
+ EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
16
+ Logger, NoFillReason, Platform, WireServe,
17
+ } from './types';
18
+
19
+ export interface EthiclyOptions {
20
+ /** Publisher API key (UUID). */
21
+ apiKey: string;
22
+ /** The OS the app runs on. Never "rn": the server ignores unknown platforms. */
23
+ platform: Platform;
24
+ /** The host app's version, sent as app_version. */
25
+ appVersion: string;
26
+ /** The bundled URL /config is fetched from. Default https://ads.ethicly.ch/functions/v1/get-ad-with-geo */
27
+ baseUrl?: string;
28
+ /**
29
+ * Adds test=1 to serve. Ignored in a React Native release build
30
+ * (`__DEV__` false), where the SDK serves and bills normally and logs an error.
31
+ */
32
+ testMode?: boolean;
33
+ /** Initial state of the ads switch, default true. */
34
+ adsEnabled?: boolean;
35
+ storage?: KeyValueStorage;
36
+ fileCache?: FileCacheAdapter;
37
+ openUrl?: (url: string) => unknown;
38
+ fetch?: FetchLike;
39
+ now?: () => number;
40
+ logger?: Logger;
41
+ /**
42
+ * App foreground and background changes, for sessions. Defaults to React
43
+ * Native's AppState; null turns sessions off (one session per process).
44
+ */
45
+ appState?: AppStateLike | null;
46
+ }
47
+
48
+ export interface Ethicly {
49
+ /** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
50
+ readonly ready: Promise<void>;
51
+ /** Serve and download an interstitial ahead of time. Does not consume it. */
52
+ preload(): Promise<InterstitialResult>;
53
+ /** The ad to show now: the preloaded one if still valid, else a fresh serve. Consumes it. */
54
+ loadInterstitial(): Promise<InterstitialResult>;
55
+ /**
56
+ * Frequency caps, the ads switch and the kill switch, checked client-side.
57
+ * false until the stored frequency state has loaded (see `ready`).
58
+ */
59
+ canShow(): boolean;
60
+ /** false for paid users: stops serves and downloads. */
61
+ setAdsEnabled(enabled: boolean): void;
62
+ isAdsEnabled(): boolean;
63
+ getConfig(): EthiclyConfig;
64
+ /** Refetch /config now (subject to Retry-After). */
65
+ refreshConfig(): Promise<void>;
66
+ /** Why the last load returned no ad. */
67
+ readonly lastNoFillReason: NoFillReason | null;
68
+ readonly sdkVersion: string;
69
+ }
70
+
71
+ const CONFIG_TIMEOUT_MS = 5000;
72
+ const SERVE_TIMEOUT_MS = 8000;
73
+ const SIZE_PROBE_TIMEOUT_MS = 3000;
74
+ const CONFIG_RETRY_AFTER_FAILURE_MS = 30000;
75
+ const DEFAULT_TTL_S = 3600;
76
+ /**
77
+ * A new session (interstitial.max_per_session counts from zero again) starts
78
+ * when the app comes back after at least this long in the background.
79
+ */
80
+ export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
81
+
82
+ let releaseTestModeLogged = false;
83
+
84
+ interface StoredConfig { config: EthiclyConfig; fetchedAt: number; maxAgeS: number }
85
+ interface StoredFrequency { lastShownAt: number }
86
+
87
+ interface Preloaded { result: { ad: EthiclyAd; tracker: InterstitialTracker } }
88
+
89
+ export function createEthicly(options: EthiclyOptions): Ethicly {
90
+ return new EthiclyClient(options);
91
+ }
92
+
93
+ class EthiclyClient implements Ethicly {
94
+ readonly ready: Promise<void>;
95
+ readonly sdkVersion = SDK_VERSION;
96
+ lastNoFillReason: NoFillReason | null = null;
97
+
98
+ private bundled: string;
99
+ private fetchFn: FetchLike;
100
+ private now: () => number;
101
+ private log: Required<Logger>;
102
+ private storage: KeyValueStorage;
103
+ private cache: CreativeCache;
104
+ private gate: RouteGate;
105
+
106
+ private config: EthiclyConfig;
107
+ private configSource: 'default' | 'stored' | 'network' = 'default';
108
+ private configFetchedAt = 0;
109
+ private configMaxAgeS = 300;
110
+ private configRetryAt = 0;
111
+ private configInflight: Promise<void> | null = null;
112
+ /** 404 unknown_key with no stored config. */
113
+ private unknownKey = false;
114
+ /** 400 or 403 on a key: integration bug, stop for this process. */
115
+ private invalidKey = false;
116
+ /** app_disabled from serve: until a later /config says enabled. */
117
+ private appDisabled = false;
118
+ /** sdk_unsupported: for the rest of the process lifetime. */
119
+ private sdkUnsupported = false;
120
+
121
+ private adsOn: boolean;
122
+ private testMode: boolean;
123
+ private shownCount = 0;
124
+ private lastShownAt: number | null = null;
125
+ private frequencyLoaded = false;
126
+ /** When the app left the foreground, null while it is in it. */
127
+ private backgroundSince: number | null = null;
128
+ private outbox: Outbox;
129
+ private preloaded: Preloaded | null = null;
130
+ private serveInflight: Promise<InterstitialResult> | null = null;
131
+
132
+ constructor(private o: EthiclyOptions) {
133
+ this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
134
+ const f = o.fetch || (globalThis as { fetch?: FetchLike }).fetch;
135
+ if (!f) throw new Error('[ethicly] no fetch available: pass options.fetch');
136
+ this.fetchFn = f;
137
+ this.now = o.now || Date.now;
138
+ this.log = safeLogger(o.logger);
139
+ this.storage = o.storage || createMemoryStorage();
140
+ this.gate = new RouteGate(this.now);
141
+ // The size probe only matters when files really land on disk.
142
+ this.cache = new CreativeCache(
143
+ o.fileCache || createMemoryFileCache(), this.storage, 'ethicly:v1:cache', this.now, this.log,
144
+ o.fileCache ? (url) => this.contentLength(url) : undefined,
145
+ );
146
+ this.config = defaultConfig(this.bundled);
147
+ this.adsOn = o.adsEnabled !== false;
148
+ this.testMode = !!o.testMode && !isReleaseBuild();
149
+ if (o.testMode && !this.testMode) this.reportReleaseTestMode();
150
+ if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
151
+ this.outbox = outboxFor(this.storage, o.apiKey, this.log);
152
+ this.watchAppState(o.appState === undefined ? defaultAppState() : o.appState);
153
+ this.ready = this.init().catch((e) => this.log.error('init failed', e));
154
+ }
155
+
156
+ /** testMode in a release build would earn the publisher nothing: ignore it, loudly, once. */
157
+ private reportReleaseTestMode(): void {
158
+ const msg = 'testMode is set in a release build: ignored, ads are served and billed normally. Set testMode: __DEV__.';
159
+ this.log.error(msg);
160
+ if (releaseTestModeLogged) return;
161
+ releaseTestModeLogged = true;
162
+ try { (globalThis as { console?: { error?: (m: string) => void } }).console?.error?.(`[ethicly] ${msg}`); } catch { /* never throw */ }
163
+ }
164
+
165
+ /** Sessions: back in the foreground after SESSION_TIMEOUT_MS or more starts a new one. */
166
+ private watchAppState(appState: AppStateLike | null): void {
167
+ if (!appState) return;
168
+ const onChange = (state: string) => {
169
+ if (state === 'active') {
170
+ if (this.backgroundSince !== null && this.now() - this.backgroundSince >= SESSION_TIMEOUT_MS) {
171
+ this.shownCount = 0;
172
+ this.log.debug('new session after time in the background');
173
+ }
174
+ this.backgroundSince = null;
175
+ } else if (this.backgroundSince === null) {
176
+ this.backgroundSince = this.now();
177
+ }
178
+ };
179
+ try {
180
+ if (appState.currentState && appState.currentState !== 'active') onChange(appState.currentState);
181
+ // Kept for the life of the client, which is the life of the process.
182
+ appState.addEventListener('change', (s) => { try { onChange(s); } catch { /* never throw */ } });
183
+ } catch (e) {
184
+ this.log.warn('could not watch AppState: one session per process', e);
185
+ }
186
+ }
187
+
188
+ /** Content-Length from a HEAD request, so an oversized creative is never written. */
189
+ private async contentLength(url: string): Promise<number | null> {
190
+ let timer: ReturnType<typeof setTimeout> | undefined;
191
+ try {
192
+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), SIZE_PROBE_TIMEOUT_MS); });
193
+ const res = await Promise.race([this.fetchFn(url, { method: 'HEAD' }), timeout]);
194
+ if (!res) return null;
195
+ const n = Number(res.headers.get('content-length'));
196
+ return res.status >= 200 && res.status < 300 && Number.isFinite(n) && n > 0 ? n : null;
197
+ } catch {
198
+ return null;
199
+ } finally {
200
+ if (timer) clearTimeout(timer);
201
+ }
202
+ }
203
+
204
+ // ------------------------------------------------------------- headers
205
+
206
+ private headers(): Record<string, string> {
207
+ return { 'X-Ethicly-SDK': `${this.o.platform}/${SDK_VERSION}` };
208
+ }
209
+
210
+ private serveBase(): string {
211
+ return this.configSource === 'default' ? this.bundled : this.config.endpoints.serve;
212
+ }
213
+
214
+ private beaconCtx(): BeaconContext {
215
+ return {
216
+ fetch: this.fetchFn,
217
+ serveBase: () => this.serveBase(),
218
+ headers: () => this.headers(),
219
+ gate: this.gate,
220
+ now: this.now,
221
+ log: this.log,
222
+ };
223
+ }
224
+
225
+ // ------------------------------------------------------------- config
226
+
227
+ private get storageKey(): string {
228
+ return `ethicly:v1:config:${this.o.apiKey}`;
229
+ }
230
+
231
+ private get frequencyKey(): string {
232
+ return `ethicly:v1:frequency:${this.o.apiKey}`;
233
+ }
234
+
235
+ /** The last shown time survives restarts, so min_gap_s does too. Never rejects. */
236
+ private async loadFrequency(): Promise<void> {
237
+ try {
238
+ const raw = await this.storage.getItem(this.frequencyKey);
239
+ const t = raw ? (JSON.parse(raw) as StoredFrequency).lastShownAt : null;
240
+ // A time in the future (the clock moved back) is ignored.
241
+ if (typeof t === 'number' && Number.isFinite(t) && t <= this.now()) {
242
+ this.lastShownAt = Math.max(this.lastShownAt ?? 0, t);
243
+ }
244
+ } catch (e) {
245
+ this.log.warn('stored frequency state unreadable', e);
246
+ } finally {
247
+ this.frequencyLoaded = true;
248
+ }
249
+ }
250
+
251
+ private async init(): Promise<void> {
252
+ await Promise.all([this.loadFrequency(), this.outbox.load()]);
253
+ try {
254
+ const raw = await this.storage.getItem(this.storageKey);
255
+ if (raw) {
256
+ const s = JSON.parse(raw) as StoredConfig;
257
+ const parsed = parseConfig(s.config, this.bundled);
258
+ if (parsed) {
259
+ this.config = parsed;
260
+ this.configSource = 'stored';
261
+ this.configFetchedAt = s.fetchedAt;
262
+ this.configMaxAgeS = s.maxAgeS;
263
+ }
264
+ }
265
+ } catch (e) {
266
+ this.log.warn('stored config unreadable', e);
267
+ }
268
+ this.applyConfigGates();
269
+ if (this.configStale()) await this.refreshConfig();
270
+ void this.replayOutbox();
271
+ }
272
+
273
+ /**
274
+ * Send what a previous run left unsent, one ad at a time. Not while a kill
275
+ * switch is on (app_disabled, sdk_unsupported) or the key is refused: the
276
+ * records then stay stored and expire one hour after their ad was shown.
277
+ * Never rejects.
278
+ */
279
+ private async replayOutbox(): Promise<void> {
280
+ const blocked = this.blockedReason();
281
+ if (blocked && blocked !== 'interstitial_disabled') {
282
+ this.log.info(`unsent beacons from the last run held back: ${blocked}`);
283
+ return;
284
+ }
285
+ const orphans = this.outbox.claimOrphans(this.now());
286
+ if (orphans.length) this.log.info(`sending ${orphans.length} unsent beacon set(s) from the last run`);
287
+ for (const rec of orphans) await replayRecord(this.beaconCtx(), this.outbox, rec);
288
+ }
289
+
290
+ private configStale(): boolean {
291
+ return this.configSource !== 'network' && this.configSource !== 'stored'
292
+ ? true
293
+ : this.now() - this.configFetchedAt >= this.configMaxAgeS * 1000;
294
+ }
295
+
296
+ private applyConfigGates(): void {
297
+ if (this.configSource === 'default') return;
298
+ if (this.config.enabled) this.appDisabled = false;
299
+ const min = this.o.platform === 'ios' ? this.config.min_sdk.ios : this.config.min_sdk.android;
300
+ if (isBelowMinSdk(SDK_VERSION, min)) {
301
+ if (!this.sdkUnsupported) this.log.error(`SDK ${SDK_VERSION} is below min_sdk ${min}: no ads until the app updates`);
302
+ this.sdkUnsupported = true;
303
+ }
304
+ }
305
+
306
+ getConfig(): EthiclyConfig {
307
+ return this.config;
308
+ }
309
+
310
+ refreshConfig(): Promise<void> {
311
+ if (this.invalidKey || this.now() < this.configRetryAt) return Promise.resolve();
312
+ if (!this.configInflight) {
313
+ this.configInflight = this.fetchConfig().catch((e) => this.log.error('config fetch failed', e))
314
+ .finally(() => { this.configInflight = null; });
315
+ }
316
+ return this.configInflight;
317
+ }
318
+
319
+ private async fetchConfig(): Promise<void> {
320
+ const url = `${this.bundled}/config?key=${encodeURIComponent(this.o.apiKey)}&platform=${this.o.platform}`;
321
+ const res = await httpRequest(this.fetchFn, url, { headers: this.headers(), timeoutMs: CONFIG_TIMEOUT_MS });
322
+ if (res.status === 200) {
323
+ const parsed = parseConfig(res.body, this.bundled);
324
+ if (parsed) {
325
+ this.config = parsed;
326
+ this.configSource = 'network';
327
+ this.configFetchedAt = this.now();
328
+ this.configMaxAgeS = maxAgeSeconds(res.cacheControl);
329
+ this.unknownKey = false;
330
+ this.applyConfigGates();
331
+ const stored: StoredConfig = { config: parsed, fetchedAt: this.configFetchedAt, maxAgeS: this.configMaxAgeS };
332
+ await this.storage.setItem(this.storageKey, JSON.stringify(stored)).catch(() => undefined);
333
+ return;
334
+ }
335
+ this.log.warn('config body unreadable, keeping the last known config');
336
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
337
+ return;
338
+ }
339
+ if (res.status === 429) {
340
+ this.configRetryAt = this.now() + Math.max(1, res.retryAfterS ?? 1) * 1000;
341
+ this.log.warn('config rate limited, keeping the last known config');
342
+ return;
343
+ }
344
+ if (res.status === 404) {
345
+ // Kept for this session; with nothing stored there is no ad.
346
+ if (this.configSource === 'default') this.unknownKey = true;
347
+ this.configRetryAt = this.now() + this.configMaxAgeS * 1000;
348
+ this.log.warn('config 404 unknown_key (unknown or not approved site)');
349
+ return;
350
+ }
351
+ if (res.status === 400) {
352
+ this.invalidKey = true;
353
+ this.log.error('config 400: the API key is missing or not a UUID. Not retried.');
354
+ return;
355
+ }
356
+ // 5xx, timeout, network error: keep the last known config, retry later.
357
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
358
+ this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
359
+ }
360
+
361
+ // ------------------------------------------------------------- frequency
362
+
363
+ canShow(): boolean {
364
+ const it = this.config.interstitial;
365
+ if (!this.adsOn || !this.frequencyLoaded || this.blockedReason()) return false;
366
+ if (this.shownCount >= it.max_per_session) return false;
367
+ if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000) return false;
368
+ return true;
369
+ }
370
+
371
+ private onShown(): void {
372
+ this.shownCount += 1;
373
+ this.lastShownAt = this.now();
374
+ const stored: StoredFrequency = { lastShownAt: this.lastShownAt };
375
+ try {
376
+ this.storage.setItem(this.frequencyKey, JSON.stringify(stored)).catch(() => undefined);
377
+ } catch { /* a storage that throws synchronously must not reach the host */ }
378
+ }
379
+
380
+ setAdsEnabled(enabled: boolean): void {
381
+ this.adsOn = !!enabled;
382
+ if (!this.adsOn) this.preloaded = null;
383
+ }
384
+
385
+ isAdsEnabled(): boolean {
386
+ return this.adsOn;
387
+ }
388
+
389
+ // ------------------------------------------------------------- serve
390
+
391
+ private blockedReason(): NoFillReason | null {
392
+ if (this.invalidKey) return 'invalid_key';
393
+ if (this.unknownKey) return 'unknown_key';
394
+ if (this.sdkUnsupported) return 'sdk_unsupported';
395
+ if (this.appDisabled || (this.configSource !== 'default' && !this.config.enabled)) return 'app_disabled';
396
+ if (this.configSource !== 'default' && this.config.formats.indexOf('interstitial') === -1) return 'interstitial_disabled';
397
+ return null;
398
+ }
399
+
400
+ private noFill(reason: NoFillReason): InterstitialResult {
401
+ this.lastNoFillReason = reason;
402
+ this.log.info(`no ad: ${reason}`);
403
+ return { ad: null, tracker: null, reason };
404
+ }
405
+
406
+ async preload(): Promise<InterstitialResult> {
407
+ try {
408
+ if (!this.adsOn) return this.noFill('ads_disabled');
409
+ if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
410
+ this.preloaded = null;
411
+ if (this.shownCount >= this.config.interstitial.max_per_session) return this.noFill('frequency_capped');
412
+ if (!this.serveInflight) {
413
+ this.serveInflight = this.serve().finally(() => { this.serveInflight = null; });
414
+ }
415
+ const r = await this.serveInflight;
416
+ if (r.ad && this.adsOn) this.preloaded = { result: r as Preloaded['result'] };
417
+ return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
418
+ } catch (e) {
419
+ this.log.error('preload failed', e);
420
+ return this.noFill('network_error');
421
+ }
422
+ }
423
+
424
+ async loadInterstitial(): Promise<InterstitialResult> {
425
+ try {
426
+ await this.ready;
427
+ if (!this.adsOn) return this.noFill('ads_disabled');
428
+ if (this.configStale()) await this.refreshConfig();
429
+ const blocked = this.blockedReason();
430
+ if (blocked) return this.noFill(blocked);
431
+ if (!this.canShow()) return this.noFill('frequency_capped');
432
+ const r = await this.preload();
433
+ this.preloaded = null;
434
+ return r;
435
+ } catch (e) {
436
+ this.log.error('loadInterstitial failed', e);
437
+ return this.noFill('network_error');
438
+ }
439
+ }
440
+
441
+ private async serve(): Promise<InterstitialResult> {
442
+ await this.ready;
443
+ if (this.configStale()) await this.refreshConfig();
444
+ const blocked = this.blockedReason();
445
+ if (blocked) return this.noFill(blocked);
446
+ if (this.gate.waitMs('serve') > 0) return this.noFill('rate_limited');
447
+
448
+ const q = [
449
+ `key=${encodeURIComponent(this.o.apiKey)}`,
450
+ 'format=interstitial',
451
+ `platform=${this.o.platform}`,
452
+ `sdk_version=${encodeURIComponent(SDK_VERSION)}`,
453
+ `app_version=${encodeURIComponent(this.o.appVersion)}`,
454
+ ];
455
+ if (this.testMode) q.push('test=1');
456
+ const res = await httpRequest(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
457
+ headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
458
+ });
459
+ const servedAt = this.now();
460
+ if (res.status === 429) {
461
+ this.gate.block('serve', res.retryAfterS);
462
+ return this.noFill('rate_limited');
463
+ }
464
+ if (res.status === 400 || res.status === 403) {
465
+ this.invalidKey = true;
466
+ this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
467
+ return this.noFill('invalid_key');
468
+ }
469
+ if (res.status === 0) return this.noFill('network_error');
470
+ if (res.status !== 200 || !res.body || typeof res.body !== 'object') return this.noFill('server_error');
471
+
472
+ const body = res.body as WireServe;
473
+ if (!body.ad) {
474
+ const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
475
+ if (reason === 'app_disabled') this.appDisabled = true;
476
+ if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
477
+ return this.noFill(reason);
478
+ }
479
+ const ad = body.ad;
480
+ const m = ad.media;
481
+ if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
482
+ this.log.warn('serve answered an ad without media or destination', body.request_id);
483
+ return this.noFill('invalid_response');
484
+ }
485
+ if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
486
+ if (!this.adsOn) return this.noFill('ads_disabled');
487
+
488
+ const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
489
+ const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
490
+ const pf = this.config.prefetch;
491
+ const cached = await this.cache.ensure(
492
+ ad.id,
493
+ poster ? [m.url, poster] : [m.url],
494
+ { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
495
+ () => this.adsOn,
496
+ ).catch(() => ({ uris: {} as Record<string, string> }));
497
+ if (!this.adsOn) return this.noFill('ads_disabled');
498
+
499
+ const uri = cached.uris[m.url] || m.url;
500
+ const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
501
+ const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
502
+ const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
503
+ const result: EthiclyAd = {
504
+ id: ad.id,
505
+ ctaLabel: label || 'Learn more',
506
+ destinationUrl: ad.destination_url,
507
+ skipAfterMs: typeof ad.skip_after_ms === 'number' && ad.skip_after_ms >= 0
508
+ ? ad.skip_after_ms
509
+ : this.config.interstitial.skip_after_ms,
510
+ media: {
511
+ kind,
512
+ uri,
513
+ videoUri: kind === 'video' ? uri : null,
514
+ posterUri: poster ? cached.uris[poster] || poster : null,
515
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
516
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
517
+ width: posInt(m.width, 720),
518
+ height: posInt(m.height, 1280),
519
+ cached: uri !== m.url,
520
+ },
521
+ audio: this.config.interstitial.audio,
522
+ title: typeof ad.title === 'string' ? ad.title : null,
523
+ test: body.test === true,
524
+ servedAt,
525
+ expiresAt: servedAt + ttlS * 1000,
526
+ };
527
+ const tracker = new InterstitialTracker({
528
+ ctx: this.beaconCtx(),
529
+ ad: result,
530
+ serve: {
531
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
532
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
533
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
534
+ },
535
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
536
+ flushIntervalS: this.config.beacon.flush_interval_s,
537
+ platform: this.o.platform,
538
+ sdkVersion: SDK_VERSION,
539
+ appVersion: this.o.appVersion,
540
+ openUrl: this.o.openUrl,
541
+ onShown: () => this.onShown(),
542
+ outbox: this.outbox,
543
+ });
544
+ this.lastNoFillReason = null;
545
+ return { ad: result, tracker };
546
+ }
547
+ }
@@ -0,0 +1,111 @@
1
+ // /config parsing, defaults and version comparison (doc "GET /config",
2
+ // "Versioning").
3
+
4
+ import type { AudioPolicy, EthiclyConfig } from './types';
5
+
6
+ export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
7
+ export const DEFAULT_MAX_AGE_S = 300;
8
+
9
+ /** The defaults shown in the doc. Used when no config was ever fetched. */
10
+ export function defaultConfig(serveBase: string): EthiclyConfig {
11
+ return {
12
+ enabled: true,
13
+ min_sdk: { ios: '0.0.0', android: '0.0.0' },
14
+ formats: ['interstitial', '300x250'],
15
+ interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
16
+ prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
17
+ beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
18
+ endpoints: { serve: serveBase },
19
+ };
20
+ }
21
+
22
+ function obj(v: unknown): Record<string, unknown> {
23
+ return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
24
+ }
25
+
26
+ function num(v: unknown, fallback: number, min: number, max: number): number {
27
+ return typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
28
+ }
29
+
30
+ function str(v: unknown, fallback: string): string {
31
+ return typeof v === 'string' && v.trim() ? v.trim() : fallback;
32
+ }
33
+
34
+ /** An https URL, without a trailing slash, or null. */
35
+ export function cleanServeBase(v: unknown): string | null {
36
+ if (typeof v !== 'string') return null;
37
+ const s = v.trim().replace(/\/+$/, '');
38
+ return /^https:\/\/[^/\s]+\/\S*$/.test(s) ? s : null;
39
+ }
40
+
41
+ /**
42
+ * Read a /config body leniently: every field is validated and falls back to
43
+ * the default, unknown fields are ignored. Returns null when the body is not a
44
+ * config at all.
45
+ */
46
+ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig | null {
47
+ const b = obj(body);
48
+ if (typeof b.enabled !== 'boolean') return null;
49
+ const d = defaultConfig(bundledBase);
50
+ const ms = obj(b.min_sdk);
51
+ const it = obj(b.interstitial);
52
+ const pf = obj(b.prefetch);
53
+ const bc = obj(b.beacon);
54
+ // Sound on is the default; 'none' (always muted) and 'optional' (start muted)
55
+ // are the publisher's explicit choices.
56
+ const audio = it.audio === 'none' || it.audio === 'optional' ? (it.audio as AudioPolicy) : 'on';
57
+ return {
58
+ enabled: b.enabled,
59
+ min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
60
+ formats: Array.isArray(b.formats) ? b.formats.filter((f): f is string => typeof f === 'string') : d.formats,
61
+ interstitial: {
62
+ skip_after_ms: num(it.skip_after_ms, d.interstitial.skip_after_ms, 0, 15000),
63
+ max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
64
+ min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
65
+ audio,
66
+ },
67
+ prefetch: {
68
+ max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
69
+ max_cache_mb: num(pf.max_cache_mb, d.prefetch.max_cache_mb, 0, 10000),
70
+ },
71
+ beacon: {
72
+ viewable_after_ms: num(bc.viewable_after_ms, d.beacon.viewable_after_ms, 0, 60000),
73
+ flush_interval_s: num(bc.flush_interval_s, d.beacon.flush_interval_s, 1, 3600),
74
+ },
75
+ endpoints: { serve: cleanServeBase(obj(b.endpoints).serve) || bundledBase },
76
+ };
77
+ }
78
+
79
+ /** max-age from Cache-Control, default 300 s. */
80
+ export function maxAgeSeconds(cacheControl: string | null): number {
81
+ const m = cacheControl ? /max-age=(\d+)/i.exec(cacheControl) : null;
82
+ return m ? Number(m[1]) : DEFAULT_MAX_AGE_S;
83
+ }
84
+
85
+ /**
86
+ * Doc "Versioning > Comparison": leading dot-separated numeric components,
87
+ * everything from the first other character ignored. -1, 0, 1, or null when
88
+ * either side has no leading number. Mirrors compareVersions in the server's
89
+ * appConfig.ts.
90
+ */
91
+ export function compareVersions(a: unknown, b: unknown): number | null {
92
+ const parse = (v: unknown): number[] | null => {
93
+ if (typeof v !== 'string') return null;
94
+ const m = /^\d+(\.\d+)*/.exec(v.trim());
95
+ return m ? m[0].split('.').map(Number) : null;
96
+ };
97
+ const pa = parse(a);
98
+ const pb = parse(b);
99
+ if (!pa || !pb) return null;
100
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
101
+ const d = (pa[i] || 0) - (pb[i] || 0);
102
+ if (d !== 0) return d < 0 ? -1 : 1;
103
+ }
104
+ return 0;
105
+ }
106
+
107
+ /** True only when `sdk` parses and is below `min`. */
108
+ export function isBelowMinSdk(sdk: string, min: string): boolean {
109
+ const c = compareVersions(sdk, min);
110
+ return c !== null && c < 0;
111
+ }