@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,115 @@
1
+ // One HTTP request with a timeout, JSON that keeps 64-bit impression ids exact,
2
+ // and the per-route 429 gate (doc "Rules that hold for every route").
3
+
4
+ import type { FetchLike, ImpressionId } from './types';
5
+
6
+ export interface HttpResult {
7
+ /** 0 for a network error or timeout. */
8
+ status: number;
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ body: any;
11
+ /** Seconds from Retry-After, null when absent or unparseable. */
12
+ retryAfterS: number | null;
13
+ cacheControl: string | null;
14
+ timedOut: boolean;
15
+ }
16
+
17
+ /**
18
+ * impression_id is a 64-bit integer. JSON.parse would round anything above
19
+ * 2^53, so long ids are read as strings and written back as bare numbers.
20
+ */
21
+ export function parseJson(text: string): unknown {
22
+ return JSON.parse(text.replace(/("impression_id"\s*:\s*)(\d{16,})/g, '$1"$2"'));
23
+ }
24
+
25
+ export function stringifyJson(value: unknown): string {
26
+ return JSON.stringify(value).replace(/("impression_id":)"(\d+)"/g, '$1$2');
27
+ }
28
+
29
+ export function asImpressionId(v: unknown): ImpressionId | null {
30
+ if (typeof v === 'number' && Number.isInteger(v) && v > 0) return v;
31
+ if (typeof v === 'string' && /^\d+$/.test(v) && !/^0+$/.test(v)) {
32
+ const n = Number(v);
33
+ return Number.isSafeInteger(n) ? n : v;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ export function parseRetryAfter(v: string | null): number | null {
39
+ if (!v) return null;
40
+ const n = Number(v.trim());
41
+ if (Number.isFinite(n) && n >= 0) return n;
42
+ const date = Date.parse(v);
43
+ return Number.isFinite(date) ? Math.max(0, Math.ceil((date - Date.now()) / 1000)) : null;
44
+ }
45
+
46
+ export async function httpRequest(
47
+ fetchFn: FetchLike,
48
+ url: string,
49
+ opts: { method?: string; headers: Record<string, string>; body?: unknown; timeoutMs: number },
50
+ ): Promise<HttpResult> {
51
+ const Ctrl = (globalThis as { AbortController?: typeof AbortController }).AbortController;
52
+ const ctrl = Ctrl ? new Ctrl() : null;
53
+ let timer: ReturnType<typeof setTimeout> | undefined;
54
+ let timedOut = false;
55
+ const timeout = new Promise<null>((resolve) => {
56
+ timer = setTimeout(() => {
57
+ timedOut = true;
58
+ try { ctrl?.abort(); } catch { /* ignore */ }
59
+ resolve(null);
60
+ }, opts.timeoutMs);
61
+ });
62
+ const headers = { ...opts.headers };
63
+ let body: string | undefined;
64
+ if (opts.body !== undefined) {
65
+ headers['Content-Type'] = 'application/json';
66
+ body = stringifyJson(opts.body);
67
+ }
68
+ const fail: HttpResult = { status: 0, body: null, retryAfterS: null, cacheControl: null, timedOut: false };
69
+ try {
70
+ const work = (async (): Promise<HttpResult> => {
71
+ const res = await fetchFn(url, { method: opts.method || 'GET', headers, body, signal: ctrl?.signal });
72
+ const text = await res.text();
73
+ let parsed: unknown = null;
74
+ try { parsed = text ? parseJson(text) : null; } catch { parsed = null; }
75
+ return {
76
+ status: res.status,
77
+ body: parsed,
78
+ retryAfterS: parseRetryAfter(res.headers.get('retry-after')),
79
+ cacheControl: res.headers.get('cache-control'),
80
+ timedOut: false,
81
+ };
82
+ })();
83
+ const out = await Promise.race([work, timeout]);
84
+ if (out === null) {
85
+ work.catch(() => undefined);
86
+ return { ...fail, timedOut: true };
87
+ }
88
+ return out;
89
+ } catch {
90
+ return { ...fail, timedOut };
91
+ } finally {
92
+ if (timer !== undefined) clearTimeout(timer);
93
+ }
94
+ }
95
+
96
+ /** On a 429 the route is closed until Retry-After has passed. */
97
+ export class RouteGate {
98
+ private until = new Map<string, number>();
99
+ constructor(private now: () => number) {}
100
+
101
+ block(route: string, retryAfterS: number | null): void {
102
+ const ms = Math.max(1, retryAfterS ?? 1) * 1000;
103
+ this.until.set(route, Math.max(this.until.get(route) || 0, this.now() + ms));
104
+ }
105
+
106
+ /** Milliseconds until the route opens, 0 when open. */
107
+ waitMs(route: string): number {
108
+ const t = this.until.get(route);
109
+ return t ? Math.max(0, t - this.now()) : 0;
110
+ }
111
+ }
112
+
113
+ export function sleep(ms: number): Promise<void> {
114
+ return new Promise((resolve) => setTimeout(resolve, ms));
115
+ }
@@ -0,0 +1,14 @@
1
+ // Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
2
+ export { createEthicly, SESSION_TIMEOUT_MS } from './client';
3
+ export type { Ethicly, EthiclyOptions } from './client';
4
+ export {
5
+ createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4,
6
+ } from './adapters';
7
+ export type { AppStateLike, ExpoFileSystemLike, ExpoFileSystemModernLike } from './adapters';
8
+ export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
9
+ export { compareVersions, BUNDLED_BASE_URL } from './config';
10
+ export { SDK_VERSION } from '../version';
11
+ export type {
12
+ AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter,
13
+ InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform, Tracker,
14
+ } from './types';
@@ -0,0 +1,193 @@
1
+ // The beacon outbox: what a rendered ad still owes the server, kept in
2
+ // `storage` so it survives the app being killed, and sent on the next start.
3
+ //
4
+ // Only beacons the server treats as idempotent are kept, so a replay can never
5
+ // count anything twice (docs/APP_API_V1.md):
6
+ // - /impression with its client_impression_id: a retry of a row that did land
7
+ // is answered `duplicate: true`, nothing new is recorded (rule 7);
8
+ // - /viewable: billing happens at most once per impression;
9
+ // - /video-event: applied monotonically, repeats change nothing.
10
+ // /click is never kept: it is never retried (doc "Click handling", step 5).
11
+ // Everything expires one hour after the ad was shown (rule 4), and the outbox
12
+ // holds at most MAX_OUTBOX_RECORDS ads.
13
+
14
+ import { ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
15
+ import { asImpressionId } from './http';
16
+ import type { ImpressionId, KeyValueStorage, Logger } from './types';
17
+
18
+ export const MAX_OUTBOX_RECORDS = 20;
19
+
20
+ const VIDEO_EVENTS = ['start', 'q1', 'q2', 'q3', 'complete', 'skip', 'error'];
21
+
22
+ export interface OutboxEvent { event: string; ms: number | null }
23
+
24
+ /** One rendered ad's unsent beacons. */
25
+ export interface OutboxRecord {
26
+ /** client_impression_id. */
27
+ cid: string;
28
+ /** Epoch ms the ad was shown. Every beacon below is dropped one hour later. */
29
+ shownAt: number;
30
+ /** The /impression body while it has no answer. */
31
+ impression?: Record<string, unknown>;
32
+ /** Known once /impression answered. */
33
+ impressionId?: ImpressionId;
34
+ viewableToken?: string | null;
35
+ /** viewable_ms of a /viewable still to send. */
36
+ viewableMs?: number;
37
+ events: OutboxEvent[];
38
+ }
39
+
40
+ function validRecord(r: unknown): r is OutboxRecord {
41
+ const o = r as Partial<OutboxRecord> | null;
42
+ if (!o || typeof o.cid !== 'string' || !o.cid || typeof o.shownAt !== 'number' || !Array.isArray(o.events)) return false;
43
+ if (!o.impression && asImpressionId(o.impressionId) === null) return false;
44
+ return o.events.every((e) => e && VIDEO_EVENTS.indexOf(e.event) >= 0);
45
+ }
46
+
47
+ /**
48
+ * One outbox per storage and API key in this JS runtime, shared by every
49
+ * client created on them, so two clients never replay the same record.
50
+ */
51
+ const registry = new WeakMap<object, Map<string, Outbox>>();
52
+
53
+ export function outboxFor(storage: KeyValueStorage, apiKey: string, log: Required<Logger>): Outbox {
54
+ let byKey = registry.get(storage);
55
+ if (!byKey) {
56
+ byKey = new Map();
57
+ registry.set(storage, byKey);
58
+ }
59
+ let ob = byKey.get(apiKey);
60
+ if (!ob) {
61
+ ob = new Outbox(storage, `ethicly:v1:outbox:${apiKey}`, log);
62
+ byKey.set(apiKey, ob);
63
+ }
64
+ return ob;
65
+ }
66
+
67
+ export class Outbox {
68
+ private records = new Map<string, OutboxRecord>();
69
+ /** Records a tracker or a replay in this runtime is already sending. */
70
+ private owned = new Set<string>();
71
+ private loaded: Promise<void> | null = null;
72
+ private dirty = false;
73
+ private writing: Promise<void> | null = null;
74
+
75
+ constructor(private storage: KeyValueStorage, private key: string, private log: Required<Logger>) {}
76
+
77
+ /** Read what a previous run left. Never rejects. */
78
+ load(): Promise<void> {
79
+ if (!this.loaded) {
80
+ this.loaded = (async () => {
81
+ try {
82
+ const raw = await this.storage.getItem(this.key);
83
+ const list = raw ? JSON.parse(raw) : [];
84
+ if (Array.isArray(list)) {
85
+ const valid = list.filter(validRecord).sort((a, b) => b.shownAt - a.shownAt).slice(0, MAX_OUTBOX_RECORDS);
86
+ for (const r of valid) if (!this.records.has(r.cid)) this.records.set(r.cid, r);
87
+ }
88
+ } catch (e) {
89
+ this.log.warn('stored beacon outbox unreadable, starting empty', e);
90
+ }
91
+ })();
92
+ }
93
+ return this.loaded;
94
+ }
95
+
96
+ /** Save or replace a record owned by this runtime. */
97
+ put(rec: OutboxRecord): void {
98
+ this.owned.add(rec.cid);
99
+ this.records.set(rec.cid, rec);
100
+ this.save();
101
+ }
102
+
103
+ remove(cid: string): void {
104
+ if (this.records.delete(cid)) this.save();
105
+ }
106
+
107
+ /**
108
+ * Unexpired records nobody in this runtime is sending, now owned by the
109
+ * caller. Expired ones are dropped.
110
+ */
111
+ claimOrphans(now: number): OutboxRecord[] {
112
+ const out: OutboxRecord[] = [];
113
+ let changed = false;
114
+ for (const r of Array.from(this.records.values())) {
115
+ if (this.owned.has(r.cid)) continue;
116
+ // A time in the future (clock moved back) cannot be trusted either.
117
+ if (now > r.shownAt + ONE_HOUR_MS || r.shownAt > now + 60000) {
118
+ this.records.delete(r.cid);
119
+ changed = true;
120
+ continue;
121
+ }
122
+ this.owned.add(r.cid);
123
+ out.push(r);
124
+ }
125
+ if (changed) this.save();
126
+ return out;
127
+ }
128
+
129
+ /** Coalesced write of the whole outbox, after the stored one was read. Never rejects. */
130
+ private save(): void {
131
+ this.dirty = true;
132
+ if (this.writing) return;
133
+ this.writing = (async () => {
134
+ await this.load();
135
+ while (this.dirty) {
136
+ this.dirty = false;
137
+ // Newest first, so the bound drops the oldest.
138
+ const list = Array.from(this.records.values()).sort((a, b) => b.shownAt - a.shownAt);
139
+ for (const r of list.slice(MAX_OUTBOX_RECORDS)) this.records.delete(r.cid);
140
+ try {
141
+ await this.storage.setItem(this.key, JSON.stringify(list.slice(0, MAX_OUTBOX_RECORDS)));
142
+ } catch (e) {
143
+ this.log.warn('could not save the beacon outbox', e);
144
+ }
145
+ }
146
+ })().finally(() => { this.writing = null; });
147
+ }
148
+
149
+ /** Resolves when nothing is waiting to be written. For tests. */
150
+ async flushed(): Promise<void> {
151
+ while (this.writing) await this.writing;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Send what a previous run left for one ad, with the live tracker's rules:
157
+ * /impression first (same client_impression_id), then /viewable, then the
158
+ * video events. Anything the server refuses, or that is past one hour, is
159
+ * dropped. Never throws.
160
+ */
161
+ export async function replayRecord(ctx: BeaconContext, outbox: Outbox, rec: OutboxRecord): Promise<void> {
162
+ const deadline = rec.shownAt + ONE_HOUR_MS;
163
+ try {
164
+ let id = asImpressionId(rec.impressionId);
165
+ let token = typeof rec.viewableToken === 'string' ? rec.viewableToken : null;
166
+ if (id === null && rec.impression) {
167
+ const res = await sendWithRetry(ctx, 'impression', rec.impression, { deadline });
168
+ id = res && res.status === 200 ? asImpressionId(res.body?.impression_id) : null;
169
+ if (id === null) return;
170
+ token = typeof res!.body?.viewable_token === 'string' ? res!.body.viewable_token : null;
171
+ // Rule 5: a token-enforced serve with no viewable_token cannot bill.
172
+ if (rec.impression.impression_token && !token) return;
173
+ outbox.put({ ...rec, impression: undefined, impressionId: id, viewableToken: token });
174
+ }
175
+ if (id === null) return;
176
+ if (typeof rec.viewableMs === 'number') {
177
+ const body: Record<string, unknown> = { impression_id: id, viewable_ms: Math.round(rec.viewableMs) };
178
+ if (token) body.viewable_token = token;
179
+ if (ctx.now() <= deadline) await sendWithRetry(ctx, 'viewable', body, { deadline });
180
+ }
181
+ for (const e of rec.events) {
182
+ if (ctx.now() > deadline) break;
183
+ const body: Record<string, unknown> = { impression_id: id, event: e.event };
184
+ if (e.ms !== null && e.ms !== undefined) body.ms = e.ms;
185
+ if (token) body.viewable_token = token;
186
+ await sendWithRetry(ctx, 'video-event', body, { deadline });
187
+ }
188
+ } catch (e) {
189
+ ctx.log.error('beacon replay failed', e);
190
+ } finally {
191
+ outbox.remove(rec.cid);
192
+ }
193
+ }
@@ -0,0 +1,371 @@
1
+ // The tracker a host player drives for one rendered ad. Implements doc
2
+ // "Lifecycle and timing" steps 4 to 8 and "Click handling". Every public
3
+ // method swallows its errors and reports them through the logger.
4
+
5
+ import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
6
+ import { appendClickToken, CLICK_TIMEOUT_MS } from './click';
7
+ import { asImpressionId, httpRequest } from './http';
8
+ import type { Outbox } from './outbox';
9
+ import { uuidv4 } from './adapters';
10
+ import type { EthiclyAd, ImpressionId, Tracker } from './types';
11
+
12
+ export interface ServeContext {
13
+ publisherSiteId: number | null;
14
+ countryCode: string | null;
15
+ impressionToken: string | null;
16
+ }
17
+
18
+ export interface TrackerDeps {
19
+ ctx: BeaconContext;
20
+ ad: EthiclyAd;
21
+ serve: ServeContext;
22
+ viewableAfterMs: number;
23
+ flushIntervalS: number;
24
+ platform: string;
25
+ sdkVersion: string;
26
+ appVersion: string;
27
+ openUrl?: (url: string) => unknown;
28
+ /** Called once when the ad is shown, for the frequency caps. */
29
+ onShown(): void;
30
+ /** Keeps unsent beacons in storage so they survive the app being killed. */
31
+ outbox?: Outbox;
32
+ }
33
+
34
+ /** Doc "Still-image interstitials": /viewable after 1000 ms on screen. */
35
+ export const STILL_VIEWABLE_MS = 1000;
36
+
37
+ /**
38
+ * A wall-clock gap between two progress() calls longer than this breaks
39
+ * "continuous" playback: a host player that stops ticking while the app is in
40
+ * the background must not count the time it was away.
41
+ */
42
+ export const MAX_TICK_GAP_MS = 1500;
43
+
44
+ type VideoEvent = 'start' | 'q1' | 'q2' | 'q3' | 'complete' | 'skip' | 'error';
45
+ interface Queued { event: VideoEvent; ms: number | null }
46
+
47
+ interface Impression { id: ImpressionId; viewableToken: string | null; at: number }
48
+
49
+ export class InterstitialTracker implements Tracker {
50
+ /** Exposed for tests and debug logs. */
51
+ clientImpressionId: string | null = null;
52
+ impression: Impression | null = null;
53
+ /** True when the impression can never bill (doc lifecycle rule 5, or a refused beacon). */
54
+ unbillable = false;
55
+
56
+ private impressionDone: Promise<Impression | null> | null = null;
57
+ private viewableSent = false;
58
+ private continuousMs = 0;
59
+ /** viewable_ms as measured when the threshold was crossed. */
60
+ private viewableMs = 0;
61
+ private last: { pos: number; wall: number; visible: boolean } | null = null;
62
+ private sentOnce = new Set<VideoEvent>();
63
+ private queue: Queued[] = [];
64
+ private timer: ReturnType<typeof setTimeout> | null = null;
65
+ private isClosed = false;
66
+ private clickUrl: Promise<string> | null = null;
67
+ private pending = new Set<Promise<unknown>>();
68
+ private flushChain: Promise<void> = Promise.resolve();
69
+ private shownAt = 0;
70
+ /** The /impression body until it has an answer. */
71
+ private impressionBody: Record<string, unknown> | null = null;
72
+ /** viewable_ms of a /viewable not yet answered. */
73
+ private viewablePending: number | null = null;
74
+ /** Video events queued or in flight. */
75
+ private unsent: Queued[] = [];
76
+
77
+ constructor(private d: TrackerDeps) {}
78
+
79
+ private get isVideo(): boolean {
80
+ return this.d.ad.media.kind === 'video';
81
+ }
82
+
83
+ private track<T>(p: Promise<T>): Promise<T> {
84
+ this.pending.add(p);
85
+ p.finally(() => this.pending.delete(p)).catch(() => undefined);
86
+ return p;
87
+ }
88
+
89
+ /** Resolves when every beacon in flight has settled. For tests and shutdown. */
90
+ async settle(): Promise<void> {
91
+ while (this.pending.size) await Promise.all(Array.from(this.pending)).catch(() => undefined);
92
+ }
93
+
94
+ isExpired(): boolean {
95
+ return this.d.ctx.now() >= this.d.ad.expiresAt;
96
+ }
97
+
98
+ shown(size?: { width?: number; height?: number }): Promise<void> {
99
+ if (this.impressionDone) return this.impressionDone.then(() => undefined);
100
+ if (this.isExpired()) {
101
+ // Rule 4: an ad served more than token_ttl_s ago must not be shown.
102
+ this.d.ctx.log.error(`ad ${this.d.ad.id} expired before it was shown; load a new one`);
103
+ this.unbillable = true;
104
+ this.impressionDone = Promise.resolve(null);
105
+ return Promise.resolve();
106
+ }
107
+ try { this.d.onShown(); } catch { /* never throw */ }
108
+ // Rule 6: one client_impression_id per rendered ad, reused only for retries.
109
+ this.clientImpressionId = uuidv4();
110
+ this.shownAt = this.d.ctx.now();
111
+ this.impressionDone = this.track(this.sendImpression(size).catch((e) => {
112
+ this.d.ctx.log.error('impression failed', e);
113
+ this.unbillable = true;
114
+ this.persist();
115
+ return null;
116
+ }));
117
+ return this.impressionDone.then(() => undefined);
118
+ }
119
+
120
+ /**
121
+ * Mirror what this ad still owes the server into the outbox, or drop it
122
+ * there once nothing is owed. Never throws.
123
+ */
124
+ private persist(): void {
125
+ const ob = this.d.outbox;
126
+ const cid = this.clientImpressionId;
127
+ if (!ob || !cid) return;
128
+ try {
129
+ const imp = this.impression;
130
+ const owed = this.impressionBody !== null
131
+ || (imp !== null && (this.viewablePending !== null || this.unsent.length > 0));
132
+ if (this.unbillable || !owed) {
133
+ ob.remove(cid);
134
+ return;
135
+ }
136
+ ob.put({
137
+ cid,
138
+ shownAt: this.shownAt,
139
+ impression: this.impressionBody ?? undefined,
140
+ impressionId: imp?.id,
141
+ viewableToken: imp?.viewableToken,
142
+ viewableMs: this.viewablePending ?? undefined,
143
+ events: this.unsent.map((q) => ({ event: q.event, ms: q.ms })),
144
+ });
145
+ } catch (e) {
146
+ this.d.ctx.log.warn('could not record unsent beacons', e);
147
+ }
148
+ }
149
+
150
+ private async sendImpression(size?: { width?: number; height?: number }): Promise<Impression | null> {
151
+ const { ad, serve, ctx } = this.d;
152
+ const body: Record<string, unknown> = {
153
+ ad_id: ad.id,
154
+ client_impression_id: this.clientImpressionId,
155
+ platform: this.d.platform,
156
+ sdk_version: this.d.sdkVersion,
157
+ app_version: this.d.appVersion,
158
+ format_width: Math.round(size?.width ?? ad.media.width),
159
+ format_height: Math.round(size?.height ?? ad.media.height),
160
+ };
161
+ if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
162
+ if (serve.countryCode) body.country_code = serve.countryCode;
163
+ if (serve.impressionToken) body.impression_token = serve.impressionToken;
164
+ this.impressionBody = body;
165
+ this.persist();
166
+
167
+ // Rule 1: sent now, never queued. Rule 7: retry timeouts, 5xx and 429 with
168
+ // the same client_impression_id, give up after one hour.
169
+ const res = await sendWithRetry(ctx, 'impression', body, { deadline: this.shownAt + ONE_HOUR_MS });
170
+ this.impressionBody = null;
171
+ if (!res || res.status !== 200) {
172
+ this.unbillable = true;
173
+ if (res?.status === 422) ctx.log.error('impression rejected (422), not retried: integration bug', res.body);
174
+ else ctx.log.warn(`impression not recorded (${res ? res.status : 'deadline passed'})`);
175
+ this.queue = [];
176
+ this.unsent = [];
177
+ this.persist();
178
+ return null;
179
+ }
180
+ const id = asImpressionId(res.body?.impression_id);
181
+ if (!id) {
182
+ this.unbillable = true;
183
+ ctx.log.warn('impression answer had no impression_id', res.body);
184
+ this.persist();
185
+ return null;
186
+ }
187
+ const viewableToken = typeof res.body?.viewable_token === 'string' ? res.body.viewable_token : null;
188
+ if (res.body?.test === true) ctx.log.info(`test impression ${id}: nothing is stored or billed`);
189
+ if (res.body?.token_expired === true) ctx.log.warn('test token expired: in production this impression would not bill');
190
+ if (serve.impressionToken && !viewableToken) {
191
+ // Rule 5: token-enforced site, no viewable_token: cannot bill, do not retry.
192
+ this.unbillable = true;
193
+ ctx.log.warn('impression stored without viewable_token: it cannot bill');
194
+ }
195
+ this.impression = { id, viewableToken, at: ctx.now() };
196
+ this.persist();
197
+ if (this.viewableSent) this.track(this.sendViewable(this.viewableMs));
198
+ if (this.queue.length) void this.flush();
199
+ return this.impression;
200
+ }
201
+
202
+ progress(positionMs: number, opts: { visible: boolean; durationMs?: number }): void {
203
+ try {
204
+ if (!this.impressionDone || this.isClosed || !Number.isFinite(positionMs)) return;
205
+ const wall = this.d.ctx.now();
206
+ const visible = !!opts.visible;
207
+ const gap = this.last ? wall - this.last.wall : 0;
208
+ if (!visible || gap > MAX_TICK_GAP_MS) {
209
+ // Not on screen, or the player stopped reporting for a while (app in
210
+ // the background): the continuous count starts again.
211
+ this.continuousMs = 0;
212
+ } else if (this.last && this.last.visible) {
213
+ const delta = positionMs - this.last.pos;
214
+ // Count real playback only: a seek forward cannot count for more than
215
+ // the wall-clock time that passed.
216
+ if (delta > 0) this.continuousMs += Math.min(delta, gap);
217
+ }
218
+ this.last = { pos: positionMs, wall, visible };
219
+
220
+ const threshold = this.isVideo ? this.d.viewableAfterMs : STILL_VIEWABLE_MS;
221
+ if (visible && !this.viewableSent && this.continuousMs >= threshold) {
222
+ // Rule 2: sent as soon as the threshold is met.
223
+ this.viewableSent = true;
224
+ this.viewableMs = this.continuousMs;
225
+ this.viewablePending = this.viewableMs;
226
+ this.persist();
227
+ if (this.impression) this.track(this.sendViewable(this.viewableMs));
228
+ }
229
+
230
+ if (!this.isVideo) return;
231
+ if (visible) this.enqueueOnce('start', Math.max(0, Math.round(positionMs)));
232
+ const duration = this.d.ad.media.durationMs ?? (opts.durationMs && opts.durationMs > 0 ? opts.durationMs : null);
233
+ if (duration) {
234
+ (['q1', 'q2', 'q3'] as const).forEach((q, i) => {
235
+ if (positionMs >= (duration * (i + 1)) / 4) this.enqueueOnce(q, Math.round(positionMs));
236
+ });
237
+ }
238
+ } catch (e) {
239
+ this.d.ctx.log.error('progress failed', e);
240
+ }
241
+ }
242
+
243
+ private async sendViewable(viewableMs: number): Promise<void> {
244
+ const imp = this.impression;
245
+ if (!imp || this.unbillable) return;
246
+ const deadline = imp.at + ONE_HOUR_MS;
247
+ try {
248
+ if (this.d.ctx.now() > deadline) return; // rule 4: drop, do not send
249
+ const body: Record<string, unknown> = { impression_id: imp.id, viewable_ms: Math.round(viewableMs) };
250
+ if (imp.viewableToken) body.viewable_token = imp.viewableToken;
251
+ await sendWithRetry(this.d.ctx, 'viewable', body, { deadline });
252
+ } finally {
253
+ this.viewablePending = null;
254
+ this.persist();
255
+ }
256
+ }
257
+
258
+ private enqueueOnce(event: VideoEvent, ms: number | null): void {
259
+ if (this.sentOnce.has(event)) return;
260
+ this.sentOnce.add(event);
261
+ const q = { event, ms };
262
+ this.queue.push(q);
263
+ this.unsent.push(q);
264
+ this.persist();
265
+ // Rule 3: reporting may wait up to flush_interval_s. The timer only runs
266
+ // while something is queued.
267
+ if (!this.timer && !this.isClosed) {
268
+ this.timer = setTimeout(() => { this.timer = null; void this.flush(); }, this.d.flushIntervalS * 1000);
269
+ }
270
+ }
271
+
272
+ complete(): void {
273
+ if (!this.isVideo || this.isClosed) return;
274
+ this.enqueueOnce('complete', this.d.ad.media.durationMs);
275
+ void this.flush();
276
+ }
277
+
278
+ skipped(positionMs: number): void {
279
+ if (!this.isVideo || this.isClosed) return;
280
+ this.enqueueOnce('skip', Number.isFinite(positionMs) ? Math.max(0, Math.round(positionMs)) : null);
281
+ void this.flush();
282
+ }
283
+
284
+ error(): void {
285
+ if (!this.isVideo || this.isClosed) return;
286
+ this.enqueueOnce('error', null);
287
+ void this.flush();
288
+ }
289
+
290
+ /** Send every queued video event, one request each (there is no batch route). */
291
+ flush(): Promise<void> {
292
+ if (this.timer) clearTimeout(this.timer);
293
+ this.timer = null;
294
+ const imp = this.impression;
295
+ if (!imp) return Promise.resolve(); // sent when /impression resolves
296
+ if (this.unbillable || this.d.ctx.now() > imp.at + ONE_HOUR_MS) {
297
+ this.queue = []; // ignored by the server, and rule 4 says drop
298
+ this.unsent = [];
299
+ this.persist();
300
+ return Promise.resolve();
301
+ }
302
+ const batch = this.queue.splice(0);
303
+ const deadline = imp.at + ONE_HOUR_MS;
304
+ // The server accepts any order, but sending in order keeps reports and
305
+ // logs readable, so flushes run one after another.
306
+ this.flushChain = this.flushChain.then(async () => {
307
+ for (const q of batch) {
308
+ const body: Record<string, unknown> = { impression_id: imp.id, event: q.event };
309
+ if (q.ms !== null && q.ms !== undefined) body.ms = q.ms;
310
+ if (imp.viewableToken) body.viewable_token = imp.viewableToken;
311
+ await sendWithRetry(this.d.ctx, 'video-event', body, { deadline });
312
+ this.unsent = this.unsent.filter((u) => u !== q);
313
+ this.persist();
314
+ }
315
+ }).catch((e) => this.d.ctx.log.error('video event flush failed', e));
316
+ return this.track(this.flushChain);
317
+ }
318
+
319
+ clicked(): Promise<string> {
320
+ if (!this.clickUrl) this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
321
+ return this.clickUrl.then(async (url) => {
322
+ try {
323
+ if (this.d.openUrl) await this.d.openUrl(url);
324
+ else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
325
+ } catch (e) {
326
+ this.d.ctx.log.error('openUrl failed', e);
327
+ }
328
+ return url;
329
+ });
330
+ }
331
+
332
+ private async resolveClickUrl(): Promise<string> {
333
+ const { ad, serve, ctx } = this.d;
334
+ const dest = ad.destinationUrl;
335
+ const deadline = ctx.now() + CLICK_TIMEOUT_MS;
336
+ // The impression_id is required. If /impression is still in flight, wait
337
+ // for it inside the same 500 ms budget.
338
+ const imp = this.impression ?? (this.impressionDone
339
+ ? await Promise.race([this.impressionDone, new Promise<null>((r) => setTimeout(() => r(null), CLICK_TIMEOUT_MS))])
340
+ : null);
341
+ if (!imp) {
342
+ ctx.log.warn('click before an impression_id was known: opening without a click beacon');
343
+ return dest;
344
+ }
345
+ if (this.unbillable) return dest;
346
+ if (ctx.gate.waitMs('click') > 0) return dest;
347
+ const remaining = Math.max(1, Math.min(CLICK_TIMEOUT_MS, deadline - ctx.now()));
348
+ const body: Record<string, unknown> = { ad_id: ad.id, impression_id: imp.id };
349
+ if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
350
+ if (serve.countryCode) body.country_code = serve.countryCode;
351
+ // Never retried: one request, whatever happens.
352
+ const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
353
+ method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
354
+ });
355
+ if (res.status === 429) ctx.gate.block('click', res.retryAfterS);
356
+ const token = res.status === 200 && typeof res.body?.click_token === 'string' ? res.body.click_token : null;
357
+ return appendClickToken(dest, token);
358
+ }
359
+
360
+ async closed(): Promise<void> {
361
+ if (this.isClosed) return;
362
+ this.isClosed = true;
363
+ try {
364
+ // Step 8: send any video event still queued (after /impression resolves).
365
+ if (this.impressionDone) await this.impressionDone;
366
+ await this.flush();
367
+ } catch (e) {
368
+ this.d.ctx.log.error('close flush failed', e);
369
+ }
370
+ }
371
+ }