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