@ethicly/react-native 0.2.0 → 0.3.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 (44) hide show
  1. package/CHANGELOG.md +92 -1
  2. package/README.md +246 -53
  3. package/lib/commonjs/core/adapters.js +44 -5
  4. package/lib/commonjs/core/cache.js +60 -5
  5. package/lib/commonjs/core/click.js +10 -0
  6. package/lib/commonjs/core/client.js +237 -73
  7. package/lib/commonjs/core/config.js +17 -2
  8. package/lib/commonjs/core/index.js +2 -1
  9. package/lib/commonjs/core/tracker.js +8 -0
  10. package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
  11. package/lib/commonjs/react/useEthiclyInterstitial.js +4 -1
  12. package/lib/commonjs/version.js +1 -1
  13. package/lib/module/core/adapters.js +44 -5
  14. package/lib/module/core/cache.js +59 -4
  15. package/lib/module/core/click.js +9 -0
  16. package/lib/module/core/client.js +237 -73
  17. package/lib/module/core/config.js +15 -1
  18. package/lib/module/core/index.js +1 -1
  19. package/lib/module/core/tracker.js +9 -1
  20. package/lib/module/react/EthiclyInterstitial.js +45 -13
  21. package/lib/module/react/useEthiclyInterstitial.js +4 -1
  22. package/lib/module/version.js +1 -1
  23. package/lib/typescript/core/adapters.d.ts +2 -1
  24. package/lib/typescript/core/cache.d.ts +20 -2
  25. package/lib/typescript/core/click.d.ts +5 -0
  26. package/lib/typescript/core/client.d.ts +42 -3
  27. package/lib/typescript/core/config.d.ts +9 -0
  28. package/lib/typescript/core/index.d.ts +2 -2
  29. package/lib/typescript/core/types.d.ts +48 -0
  30. package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
  31. package/lib/typescript/react/useEthiclyInterstitial.d.ts +4 -2
  32. package/lib/typescript/version.d.ts +1 -1
  33. package/package.json +2 -2
  34. package/src/core/adapters.ts +33 -5
  35. package/src/core/cache.ts +48 -3
  36. package/src/core/click.ts +10 -0
  37. package/src/core/client.ts +278 -76
  38. package/src/core/config.ts +14 -1
  39. package/src/core/index.ts +4 -3
  40. package/src/core/tracker.ts +8 -1
  41. package/src/core/types.ts +57 -0
  42. package/src/react/EthiclyInterstitial.tsx +62 -16
  43. package/src/react/useEthiclyInterstitial.ts +8 -3
  44. package/src/version.ts +1 -1
@@ -12,7 +12,14 @@
12
12
  // - on first use every pending file, and every file in the SDK's cache
13
13
  // directory that the index does not list, is deleted.
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.CreativeCache = void 0;
15
+ exports.CreativeCache = exports.DOWNLOAD_TIMEOUT_MS = void 0;
16
+ /**
17
+ * The longest one creative file may take to download. A slower (trickling)
18
+ * download is cancelled when the adapter supports it, else abandoned: the
19
+ * creative streams and later downloads are not held up behind it. A file it
20
+ * still writes afterwards is not indexed, so the next launch's sweep deletes it.
21
+ */
22
+ exports.DOWNLOAD_TIMEOUT_MS = 60000;
16
23
  function hash(s) {
17
24
  let h = 5381;
18
25
  for (let i = 0; i < s.length; i++)
@@ -27,18 +34,59 @@ function baseName(uri) {
27
34
  return uri.replace(/[?#].*$/, '').split('/').pop() || uri;
28
35
  }
29
36
  class CreativeCache {
30
- constructor(files, storage, storageKey, now, log, probeSize = async () => null) {
37
+ constructor(files, storage, storageKey, now, log, probeSize = async () => null, downloadTimeoutMs = exports.DOWNLOAD_TIMEOUT_MS) {
31
38
  this.files = files;
32
39
  this.storage = storage;
33
40
  this.storageKey = storageKey;
34
41
  this.now = now;
35
42
  this.log = log;
36
43
  this.probeSize = probeSize;
44
+ this.downloadTimeoutMs = downloadTimeoutMs;
37
45
  this.entries = [];
38
46
  /** File names whose download has started but not landed. */
39
47
  this.pending = [];
40
48
  this.loaded = null;
41
49
  this.chain = Promise.resolve();
50
+ /** Bumped by cancel(): a download started before it no longer counts. */
51
+ this.generation = 0;
52
+ }
53
+ /**
54
+ * Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
55
+ * and skip the files not started yet. For setAdsEnabled(false).
56
+ */
57
+ cancel() {
58
+ var _a, _b;
59
+ this.generation += 1;
60
+ try {
61
+ (_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
62
+ }
63
+ catch (e) {
64
+ this.log.warn('could not cancel the creative download', e);
65
+ }
66
+ }
67
+ /** The adapter's download, given up on after downloadTimeoutMs. */
68
+ async downloadWithin(url, name, maxBytes) {
69
+ let timer;
70
+ const timeout = new Promise((_, reject) => {
71
+ timer = setTimeout(() => {
72
+ var _a, _b;
73
+ try {
74
+ (_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
75
+ }
76
+ catch { /* best effort */ }
77
+ reject(new Error(`download took longer than ${this.downloadTimeoutMs} ms`));
78
+ }, this.downloadTimeoutMs);
79
+ });
80
+ const dl = this.files.download(url, name, { maxBytes });
81
+ // A late rejection of an abandoned download must not go unhandled.
82
+ dl.catch(() => undefined);
83
+ try {
84
+ return await Promise.race([dl, timeout]);
85
+ }
86
+ finally {
87
+ if (timer)
88
+ clearTimeout(timer);
89
+ }
42
90
  }
43
91
  load() {
44
92
  if (!this.loaded)
@@ -111,7 +159,8 @@ class CreativeCache {
111
159
  * Make sure the files of one creative are on disk. Never throws: a file that
112
160
  * cannot be cached is simply left out of the result and streamed instead.
113
161
  * `allowed()` is checked before every download so setAdsEnabled(false)
114
- * stops a download that has not started yet.
162
+ * stops a download that has not started yet; cancel() also stops the one in
163
+ * flight when the adapter supports it.
115
164
  */
116
165
  ensure(adId, urls, limits, allowed) {
117
166
  const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
@@ -133,10 +182,12 @@ class CreativeCache {
133
182
  this.entries.push(entry);
134
183
  }
135
184
  entry.lastUsed = this.now();
185
+ const generation = this.generation;
186
+ const go = () => allowed() && generation === this.generation;
136
187
  for (const url of urls) {
137
188
  if (entry.files.some((f) => f.url === url))
138
189
  continue;
139
- if (!allowed())
190
+ if (!go())
140
191
  break;
141
192
  // One creative may use the whole budget (older ones are evicted), never more.
142
193
  const budget = limits.maxBytes - this.size(entry);
@@ -152,12 +203,16 @@ class CreativeCache {
152
203
  this.pending = [name];
153
204
  await this.persist();
154
205
  try {
155
- const res = await this.files.download(url, name, { maxBytes: budget });
206
+ const res = await this.downloadWithin(url, name, budget);
156
207
  const bytes = typeof res.bytes === 'number' && res.bytes > 0 ? res.bytes : await this.files.size(res.uri).catch(() => 0);
157
208
  if (bytes > budget) {
158
209
  await this.files.delete(res.uri).catch(() => undefined);
159
210
  this.log.info(`${url} is over the cache budget: it will stream`);
160
211
  }
212
+ else if (!go()) {
213
+ // Cancelled while it was landing: keep nothing for a paid user.
214
+ await this.files.delete(res.uri).catch(() => undefined);
215
+ }
161
216
  else {
162
217
  entry.files.push({ url, uri: res.uri, bytes });
163
218
  }
@@ -4,6 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.CLICK_TIMEOUT_MS = void 0;
6
6
  exports.appendClickToken = appendClickToken;
7
+ exports.isWebUrl = isWebUrl;
7
8
  /**
8
9
  * Append ethicly_click=<token> to the destination. The separator is "&" when
9
10
  * the URL already contains a "?" anywhere, otherwise "?". The token is
@@ -17,3 +18,12 @@ function appendClickToken(destinationUrl, clickToken) {
17
18
  }
18
19
  /** The /click budget: the website snippet aborts at exactly 500 ms. */
19
20
  exports.CLICK_TIMEOUT_MS = 500;
21
+ /**
22
+ * True for an absolute http: or https: URL with a host. Anything else (tel:,
23
+ * intent:, javascript:, a custom app scheme, a relative path) is never opened.
24
+ */
25
+ function isWebUrl(url) {
26
+ return typeof url === 'string'
27
+ && /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
28
+ && !/[\s\u0000-\u001f\u007f]/.test(url);
29
+ }
@@ -2,15 +2,18 @@
2
2
  // createEthicly: config, serve, prefetch, frequency caps and the ads switch.
3
3
  // Pure TypeScript; every native capability comes in through an adapter.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.SESSION_TIMEOUT_MS = void 0;
5
+ exports.SESSION_TIMEOUT_MS = exports.DEFAULT_LOAD_TIMEOUT_MS = void 0;
6
6
  exports.createEthicly = createEthicly;
7
7
  const adapters_1 = require("./adapters");
8
8
  const cache_1 = require("./cache");
9
+ const click_1 = require("./click");
9
10
  const config_1 = require("./config");
10
11
  const http_1 = require("./http");
11
12
  const outbox_1 = require("./outbox");
12
13
  const tracker_1 = require("./tracker");
13
14
  const version_1 = require("../version");
15
+ /** How long loadInterstitial() waits for a creative download by default. */
16
+ exports.DEFAULT_LOAD_TIMEOUT_MS = 3000;
14
17
  const CONFIG_TIMEOUT_MS = 5000;
15
18
  const SERVE_TIMEOUT_MS = 8000;
16
19
  const SIZE_PROBE_TIMEOUT_MS = 3000;
@@ -22,6 +25,26 @@ const DEFAULT_TTL_S = 3600;
22
25
  */
23
26
  exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
24
27
  let releaseTestModeLogged = false;
28
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
29
+ const MAX_MIN_GAP_S = 86400;
30
+ /**
31
+ * A frequency value from code: undefined when not a usable number, else >= 0.
32
+ * Infinity only where `allowInfinity`.
33
+ */
34
+ function frequencyValue(v, name, allowInfinity, log) {
35
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
36
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
37
+ return undefined;
38
+ }
39
+ if (v < 0) {
40
+ log.warn(`frequency.${name} below 0: using 0`);
41
+ return 0;
42
+ }
43
+ return v;
44
+ }
45
+ function audioPolicy(v) {
46
+ return v === 'on' || v === 'optional' || v === 'none' ? v : null;
47
+ }
25
48
  function createEthicly(options) {
26
49
  return new EthiclyClient(options);
27
50
  }
@@ -46,10 +69,16 @@ class EthiclyClient {
46
69
  this.shownCount = 0;
47
70
  this.lastShownAt = null;
48
71
  this.frequencyLoaded = false;
72
+ /** Frequency set in code, null where /config decides. */
73
+ this.maxPerSessionOverride = null;
74
+ this.minGapSOverride = null;
49
75
  /** When the app left the foreground, null while it is in it. */
50
76
  this.backgroundSince = null;
51
77
  this.preloaded = null;
52
78
  this.serveInflight = null;
79
+ /** Served, creative still downloading, not yet taken. */
80
+ this.pendingServed = null;
81
+ this.badDestinationLogged = false;
53
82
  this.bundled = (0, config_1.cleanServeBase)(o.baseUrl) || config_1.BUNDLED_BASE_URL;
54
83
  const f = o.fetch || globalThis.fetch;
55
84
  if (!f)
@@ -63,6 +92,14 @@ class EthiclyClient {
63
92
  this.cache = new cache_1.CreativeCache(o.fileCache || (0, adapters_1.createMemoryFileCache)(), this.storage, 'ethicly:v1:cache', this.now, this.log, o.fileCache ? (url) => this.contentLength(url) : undefined);
64
93
  this.config = (0, config_1.defaultConfig)(this.bundled);
65
94
  this.adsOn = o.adsEnabled !== false;
95
+ this.audio = audioPolicy(o.audio);
96
+ if (o.audio !== undefined && !this.audio)
97
+ this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
98
+ this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
99
+ ? o.loadTimeoutMs
100
+ : exports.DEFAULT_LOAD_TIMEOUT_MS;
101
+ if (o.frequency)
102
+ this.setFrequency(o.frequency);
66
103
  this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
67
104
  if (o.testMode && !this.testMode)
68
105
  this.reportReleaseTestMode();
@@ -289,15 +326,61 @@ class EthiclyClient {
289
326
  this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
290
327
  }
291
328
  // ------------------------------------------------------------- frequency
292
- canShow() {
329
+ getFrequency() {
330
+ var _a, _b;
293
331
  const it = this.config.interstitial;
294
- if (!this.adsOn || !this.frequencyLoaded || this.blockedReason())
295
- return false;
296
- if (this.shownCount >= it.max_per_session)
297
- return false;
298
- if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000)
299
- return false;
300
- return true;
332
+ return {
333
+ maxPerSession: (_a = this.maxPerSessionOverride) !== null && _a !== void 0 ? _a : it.max_per_session,
334
+ minGapSeconds: (_b = this.minGapSOverride) !== null && _b !== void 0 ? _b : it.min_gap_s,
335
+ };
336
+ }
337
+ setFrequency(update) {
338
+ if (!update || typeof update !== 'object')
339
+ return;
340
+ if (update.maxPerSession === null)
341
+ this.maxPerSessionOverride = null;
342
+ else if (update.maxPerSession !== undefined) {
343
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
344
+ if (v !== undefined) {
345
+ const whole = Math.floor(v);
346
+ if (whole !== v)
347
+ this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
348
+ this.maxPerSessionOverride = whole;
349
+ }
350
+ }
351
+ if (update.minGapSeconds === null)
352
+ this.minGapSOverride = null;
353
+ else if (update.minGapSeconds !== undefined) {
354
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
355
+ if (v !== undefined) {
356
+ if (v > MAX_MIN_GAP_S)
357
+ this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
358
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
359
+ }
360
+ }
361
+ }
362
+ nextAdStatus() {
363
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
364
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
365
+ const no = (reason, retryAt) => (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
366
+ if (!this.adsOn)
367
+ return no('ads_disabled');
368
+ if (!this.frequencyLoaded)
369
+ return no('not_ready');
370
+ const blocked = this.blockedReason();
371
+ if (blocked)
372
+ return no(blocked);
373
+ if (this.shownCount >= maxPerSession)
374
+ return no('session_cap');
375
+ if (this.lastShownAt !== null) {
376
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
377
+ if (this.now() < retryAt)
378
+ return no('frequency_capped', retryAt);
379
+ }
380
+ return { ...base, allowed: true };
381
+ }
382
+ canShow() {
383
+ return this.nextAdStatus().allowed;
301
384
  }
302
385
  onShown() {
303
386
  this.shownCount += 1;
@@ -310,8 +393,12 @@ class EthiclyClient {
310
393
  }
311
394
  setAdsEnabled(enabled) {
312
395
  this.adsOn = !!enabled;
313
- if (!this.adsOn)
314
- this.preloaded = null;
396
+ if (this.adsOn)
397
+ return;
398
+ this.preloaded = null;
399
+ this.pendingServed = null;
400
+ // A paid user downloads nothing: stop the creative download in flight.
401
+ this.cache.cancel();
315
402
  }
316
403
  isAdsEnabled() {
317
404
  return this.adsOn;
@@ -335,6 +422,29 @@ class EthiclyClient {
335
422
  this.log.info(`no ad: ${reason}`);
336
423
  return { ad: null, tracker: null, reason };
337
424
  }
425
+ /** The served ad waiting for its download, or a new serve. One serve at a time. */
426
+ serveOnce() {
427
+ const p = this.pendingServed;
428
+ if (p && !p.consumed && this.now() < p.expiresAt)
429
+ return Promise.resolve({ served: p });
430
+ this.pendingServed = null;
431
+ if (!this.serveInflight) {
432
+ this.serveInflight = this.serve()
433
+ .then((out) => {
434
+ if (out.served)
435
+ this.pendingServed = out.served;
436
+ return out;
437
+ })
438
+ .finally(() => { this.serveInflight = null; });
439
+ }
440
+ return this.serveInflight;
441
+ }
442
+ /** The ad and tracker of a served ad, built once, by whoever asks first. */
443
+ claim(s, uris) {
444
+ if (!s.result)
445
+ s.result = s.build(uris);
446
+ return s.result;
447
+ }
338
448
  async preload() {
339
449
  try {
340
450
  if (!this.adsOn)
@@ -342,15 +452,23 @@ class EthiclyClient {
342
452
  if (this.preloaded && !this.preloaded.result.tracker.isExpired())
343
453
  return this.preloaded.result;
344
454
  this.preloaded = null;
345
- if (this.shownCount >= this.config.interstitial.max_per_session)
455
+ if (this.shownCount >= this.getFrequency().maxPerSession)
346
456
  return this.noFill('frequency_capped');
347
- if (!this.serveInflight) {
348
- this.serveInflight = this.serve().finally(() => { this.serveInflight = null; });
349
- }
350
- const r = await this.serveInflight;
351
- if (r.ad && this.adsOn)
457
+ const out = await this.serveOnce();
458
+ if (!out.served)
459
+ return out.noFill;
460
+ const s = out.served;
461
+ // In the background: wait for the whole download, so the ad plays from disk.
462
+ const cached = await s.download;
463
+ if (!this.adsOn)
464
+ return this.noFill('ads_disabled');
465
+ const r = this.claim(s, cached.uris);
466
+ if (!s.consumed) {
352
467
  this.preloaded = { result: r };
353
- return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
468
+ if (this.pendingServed === s)
469
+ this.pendingServed = null;
470
+ }
471
+ return r;
354
472
  }
355
473
  catch (e) {
356
474
  this.log.error('preload failed', e);
@@ -358,6 +476,7 @@ class EthiclyClient {
358
476
  }
359
477
  }
360
478
  async loadInterstitial() {
479
+ var _a;
361
480
  try {
362
481
  await this.ready;
363
482
  if (!this.adsOn)
@@ -369,8 +488,28 @@ class EthiclyClient {
369
488
  return this.noFill(blocked);
370
489
  if (!this.canShow())
371
490
  return this.noFill('frequency_capped');
372
- const r = await this.preload();
491
+ const pre = this.preloaded;
373
492
  this.preloaded = null;
493
+ if (pre && !pre.result.tracker.isExpired())
494
+ return pre.result;
495
+ const out = await this.serveOnce();
496
+ if (!out.served)
497
+ return out.noFill;
498
+ const s = out.served;
499
+ // The user is waiting: give the download a short budget, then stream the
500
+ // remote file. The download carries on in the background for next time.
501
+ const cached = await this.within(s.download, this.loadTimeoutMs);
502
+ if (!this.adsOn)
503
+ return this.noFill('ads_disabled');
504
+ if (!cached)
505
+ this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
506
+ const r = this.claim(s, cached ? cached.uris : {});
507
+ s.consumed = true;
508
+ if (this.pendingServed === s)
509
+ this.pendingServed = null;
510
+ // A preload that finished meanwhile may have stored this same ad.
511
+ if (((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result) === r)
512
+ this.preloaded = null;
374
513
  return r;
375
514
  }
376
515
  catch (e) {
@@ -378,15 +517,24 @@ class EthiclyClient {
378
517
  return this.noFill('network_error');
379
518
  }
380
519
  }
520
+ /** `p`, or null once `ms` have passed first. */
521
+ within(p, ms) {
522
+ let timer;
523
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
524
+ return Promise.race([p, timeout]).finally(() => { if (timer)
525
+ clearTimeout(timer); });
526
+ }
381
527
  async serve() {
528
+ var _a, _b;
529
+ const noFill = (reason) => ({ noFill: this.noFill(reason) });
382
530
  await this.ready;
383
531
  if (this.configStale())
384
532
  await this.refreshConfig();
385
533
  const blocked = this.blockedReason();
386
534
  if (blocked)
387
- return this.noFill(blocked);
535
+ return noFill(blocked);
388
536
  if (this.gate.waitMs('serve') > 0)
389
- return this.noFill('rate_limited');
537
+ return noFill('rate_limited');
390
538
  const q = [
391
539
  `key=${encodeURIComponent(this.o.apiKey)}`,
392
540
  'format=interstitial',
@@ -402,17 +550,17 @@ class EthiclyClient {
402
550
  const servedAt = this.now();
403
551
  if (res.status === 429) {
404
552
  this.gate.block('serve', res.retryAfterS);
405
- return this.noFill('rate_limited');
553
+ return noFill('rate_limited');
406
554
  }
407
555
  if (res.status === 400 || res.status === 403) {
408
556
  this.invalidKey = true;
409
557
  this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
410
- return this.noFill('invalid_key');
558
+ return noFill('invalid_key');
411
559
  }
412
560
  if (res.status === 0)
413
- return this.noFill('network_error');
561
+ return noFill('network_error');
414
562
  if (res.status !== 200 || !res.body || typeof res.body !== 'object')
415
- return this.noFill('server_error');
563
+ return noFill('server_error');
416
564
  const body = res.body;
417
565
  if (!body.ad) {
418
566
  const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
@@ -420,70 +568,86 @@ class EthiclyClient {
420
568
  this.appDisabled = true;
421
569
  if (reason === 'sdk_unsupported')
422
570
  this.sdkUnsupported = true;
423
- return this.noFill(reason);
571
+ return noFill(reason);
424
572
  }
425
573
  const ad = body.ad;
426
574
  const m = ad.media;
427
575
  if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
428
576
  this.log.warn('serve answered an ad without media or destination', body.request_id);
429
- return this.noFill('invalid_response');
577
+ return noFill('invalid_response');
578
+ }
579
+ if (!(0, click_1.isWebUrl)(ad.destination_url)) {
580
+ // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
581
+ if (!this.badDestinationLogged) {
582
+ this.badDestinationLogged = true;
583
+ this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
584
+ }
585
+ return noFill('invalid_response');
430
586
  }
431
587
  if (body.test === true)
432
588
  this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
433
589
  if (!this.adsOn)
434
- return this.noFill('ads_disabled');
590
+ return noFill('ads_disabled');
435
591
  const kind = m.kind === 'video' ? 'video' : 'image';
436
592
  const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
437
593
  const pf = this.config.prefetch;
438
- const cached = await this.cache.ensure(ad.id, poster ? [m.url, poster] : [m.url], { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 }, () => this.adsOn).catch(() => ({ uris: {} }));
439
- if (!this.adsOn)
440
- return this.noFill('ads_disabled');
441
- const uri = cached.uris[m.url] || m.url;
594
+ // Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
595
+ const download = this.cache.ensure(ad.id, poster ? [m.url, poster] : [m.url], { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 }, () => this.adsOn).catch(() => ({ uris: {} }));
442
596
  const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
597
+ const expiresAt = servedAt + ttlS * 1000;
598
+ const adId = ad.id;
599
+ const mediaUrl = m.url;
600
+ const destinationUrl = ad.destination_url;
443
601
  const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
444
602
  const posInt = (v, d) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
445
- const result = {
446
- id: ad.id,
447
- ctaLabel: label || 'Learn more',
448
- destinationUrl: ad.destination_url,
449
- skipAfterMs: typeof ad.skip_after_ms === 'number' && ad.skip_after_ms >= 0
450
- ? ad.skip_after_ms
451
- : this.config.interstitial.skip_after_ms,
452
- media: {
453
- kind,
454
- uri,
455
- videoUri: kind === 'video' ? uri : null,
456
- posterUri: poster ? cached.uris[poster] || poster : null,
457
- durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
458
- mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
459
- width: posInt(m.width, 720),
460
- height: posInt(m.height, 1280),
461
- cached: uri !== m.url,
462
- },
463
- audio: this.config.interstitial.audio,
464
- title: typeof ad.title === 'string' ? ad.title : null,
465
- test: body.test === true,
466
- servedAt,
467
- expiresAt: servedAt + ttlS * 1000,
603
+ // The ad's value wins over /config, kept within the same 8 to 15 s range.
604
+ const skipAfterMs = (_a = (0, config_1.clampSkipAfterMs)(ad.skip_after_ms)) !== null && _a !== void 0 ? _a : this.config.interstitial.skip_after_ms;
605
+ // The app's choice (options.audio) wins over the server's interstitial.audio.
606
+ const audio = (_b = this.audio) !== null && _b !== void 0 ? _b : this.config.interstitial.audio;
607
+ const build = (uris) => {
608
+ const uri = uris[mediaUrl] || mediaUrl;
609
+ const result = {
610
+ id: adId,
611
+ ctaLabel: label || 'Learn more',
612
+ destinationUrl,
613
+ skipAfterMs,
614
+ media: {
615
+ kind,
616
+ uri,
617
+ videoUri: kind === 'video' ? uri : null,
618
+ posterUri: poster ? uris[poster] || poster : null,
619
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
620
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
621
+ width: posInt(m.width, 720),
622
+ height: posInt(m.height, 1280),
623
+ cached: uri !== mediaUrl,
624
+ },
625
+ audio,
626
+ title: typeof ad.title === 'string' ? ad.title : null,
627
+ test: body.test === true,
628
+ servedAt,
629
+ expiresAt,
630
+ };
631
+ const tracker = new tracker_1.InterstitialTracker({
632
+ ctx: this.beaconCtx(),
633
+ ad: result,
634
+ serve: {
635
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
636
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
637
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
638
+ },
639
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
640
+ flushIntervalS: this.config.beacon.flush_interval_s,
641
+ platform: this.o.platform,
642
+ sdkVersion: version_1.SDK_VERSION,
643
+ appVersion: this.o.appVersion,
644
+ openUrl: this.o.openUrl,
645
+ onShown: () => this.onShown(),
646
+ outbox: this.outbox,
647
+ });
648
+ return { ad: result, tracker };
468
649
  };
469
- const tracker = new tracker_1.InterstitialTracker({
470
- ctx: this.beaconCtx(),
471
- ad: result,
472
- serve: {
473
- publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
474
- countryCode: typeof body.country_code === 'string' ? body.country_code : null,
475
- impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
476
- },
477
- viewableAfterMs: this.config.beacon.viewable_after_ms,
478
- flushIntervalS: this.config.beacon.flush_interval_s,
479
- platform: this.o.platform,
480
- sdkVersion: version_1.SDK_VERSION,
481
- appVersion: this.o.appVersion,
482
- openUrl: this.o.openUrl,
483
- onShown: () => this.onShown(),
484
- outbox: this.outbox,
485
- });
486
650
  this.lastNoFillReason = null;
487
- return { ad: result, tracker };
651
+ return { served: { build, download, expiresAt, consumed: false, result: null } };
488
652
  }
489
653
  }
@@ -2,7 +2,8 @@
2
2
  // /config parsing, defaults and version comparison (doc "GET /config",
3
3
  // "Versioning").
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.DEFAULT_MAX_AGE_S = exports.BUNDLED_BASE_URL = void 0;
5
+ exports.MAX_SKIP_AFTER_MS = exports.MIN_SKIP_AFTER_MS = exports.DEFAULT_MAX_AGE_S = exports.BUNDLED_BASE_URL = void 0;
6
+ exports.clampSkipAfterMs = clampSkipAfterMs;
6
7
  exports.defaultConfig = defaultConfig;
7
8
  exports.cleanServeBase = cleanServeBase;
8
9
  exports.parseConfig = parseConfig;
@@ -11,6 +12,19 @@ exports.compareVersions = compareVersions;
11
12
  exports.isBelowMinSdk = isBelowMinSdk;
12
13
  exports.BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
13
14
  exports.DEFAULT_MAX_AGE_S = 300;
15
+ /**
16
+ * The skip delay is kept within these bounds, from /config and from the ad:
17
+ * the video is watched for at least 8 s before Skip appears (it still
18
+ * unlocks earlier when the video ends or after the call to action).
19
+ */
20
+ exports.MIN_SKIP_AFTER_MS = 8000;
21
+ exports.MAX_SKIP_AFTER_MS = 15000;
22
+ /** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
23
+ function clampSkipAfterMs(v) {
24
+ if (typeof v !== 'number' || !Number.isFinite(v))
25
+ return null;
26
+ return Math.min(exports.MAX_SKIP_AFTER_MS, Math.max(exports.MIN_SKIP_AFTER_MS, Math.round(v)));
27
+ }
14
28
  /** The defaults shown in the doc. Used when no config was ever fetched. */
15
29
  function defaultConfig(serveBase) {
16
30
  return {
@@ -45,6 +59,7 @@ function cleanServeBase(v) {
45
59
  * config at all.
46
60
  */
47
61
  function parseConfig(body, bundledBase) {
62
+ var _a;
48
63
  const b = obj(body);
49
64
  if (typeof b.enabled !== 'boolean')
50
65
  return null;
@@ -61,7 +76,7 @@ function parseConfig(body, bundledBase) {
61
76
  min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
62
77
  formats: Array.isArray(b.formats) ? b.formats.filter((f) => typeof f === 'string') : d.formats,
63
78
  interstitial: {
64
- skip_after_ms: num(it.skip_after_ms, d.interstitial.skip_after_ms, 0, 15000),
79
+ skip_after_ms: (_a = clampSkipAfterMs(it.skip_after_ms)) !== null && _a !== void 0 ? _a : d.interstitial.skip_after_ms,
65
80
  max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
66
81
  min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
67
82
  audio,
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SDK_VERSION = exports.BUNDLED_BASE_URL = exports.compareVersions = exports.CLICK_TIMEOUT_MS = exports.appendClickToken = exports.uuidv4 = exports.createExpoFileCache = exports.createMemoryFileCache = exports.createMemoryStorage = exports.SESSION_TIMEOUT_MS = exports.createEthicly = void 0;
3
+ exports.SDK_VERSION = exports.BUNDLED_BASE_URL = exports.compareVersions = exports.CLICK_TIMEOUT_MS = exports.appendClickToken = exports.uuidv4 = exports.createExpoFileCache = exports.createMemoryFileCache = exports.createMemoryStorage = exports.SESSION_TIMEOUT_MS = exports.DEFAULT_LOAD_TIMEOUT_MS = exports.createEthicly = void 0;
4
4
  // Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
5
5
  var client_1 = require("./client");
6
6
  Object.defineProperty(exports, "createEthicly", { enumerable: true, get: function () { return client_1.createEthicly; } });
7
+ Object.defineProperty(exports, "DEFAULT_LOAD_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.DEFAULT_LOAD_TIMEOUT_MS; } });
7
8
  Object.defineProperty(exports, "SESSION_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.SESSION_TIMEOUT_MS; } });
8
9
  var adapters_1 = require("./adapters");
9
10
  Object.defineProperty(exports, "createMemoryStorage", { enumerable: true, get: function () { return adapters_1.createMemoryStorage; } });
@@ -311,6 +311,11 @@ class InterstitialTracker {
311
311
  if (!this.clickUrl)
312
312
  this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
313
313
  return this.clickUrl.then(async (url) => {
314
+ // The client already refuses such an ad; this guards a hand-built EthiclyAd.
315
+ if (!(0, click_1.isWebUrl)(url)) {
316
+ this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
317
+ return url;
318
+ }
314
319
  try {
315
320
  if (this.d.openUrl)
316
321
  await this.d.openUrl(url);
@@ -347,6 +352,9 @@ class InterstitialTracker {
347
352
  body.publisher_site_id = serve.publisherSiteId;
348
353
  if (serve.countryCode)
349
354
  body.country_code = serve.countryCode;
355
+ // Proof the view was served: lets the server bill a tap made before /viewable.
356
+ if (imp.viewableToken)
357
+ body.viewable_token = imp.viewableToken;
350
358
  // Never retried: one request, whatever happens.
351
359
  const res = await (0, http_1.httpRequest)(ctx.fetch, `${ctx.serveBase()}/click`, {
352
360
  method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, beacons_1.BEACON_TIMEOUT_MS),