@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
package/CHANGELOG.md CHANGED
@@ -3,7 +3,98 @@
3
3
  All notable changes to `@ethicly/react-native` are recorded here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the
5
5
  package uses [Semantic Versioning](https://semver.org/). Every version speaks
6
- contract v1 of the Ethicly app API (`docs/APP_API_V1.md`).
6
+ contract v1 of the Ethicly app API.
7
+
8
+ ## [0.3.0] - 2026-11-21
9
+
10
+ ### Added
11
+
12
+ - `/click` now carries the impression's `viewable_token`, so the server can
13
+ bill a tap made before the view was confirmed and refuse unproven clicks.
14
+ - `frequency: { maxPerSession?, minGapSeconds? }` on `createEthicly`. The
15
+ publisher decides how often ads show: each field set in code wins over the
16
+ dashboard values from `/config` (`interstitial.max_per_session`,
17
+ `min_gap_s`); a field left out falls back to `/config`, then the defaults.
18
+ Any value 0 or above is accepted: `maxPerSession: 0` shows no ads,
19
+ `Infinity` or a large number means no session limit, `minGapSeconds: 0`
20
+ means no gap. Negative values count as 0; non-numbers are ignored with a
21
+ warning.
22
+ - `setFrequency(update)` changes the frequency at runtime (after an
23
+ entitlement check or an A/B test). A field left out keeps its value; `null`
24
+ goes back to `/config`. `getFrequency()` returns the values in effect.
25
+ - `nextAdStatus()` on the client and on `useEthiclyInterstitial`: whether an
26
+ ad may show now and, when not, the reason (`frequency_capped` with
27
+ `retryAt`, `session_cap`, `ads_disabled`, `not_ready` or a server gate) plus
28
+ `shownThisSession`, `maxPerSession` and `minGapSeconds`.
29
+ - README and INTEGRATING: "What you control and what Ethicly controls". Ads
30
+ shown beyond Ethicly's anti-abuse limits still play but are not billed.
31
+ - Example app: a status line under the buttons explains every no-ad case,
32
+ with a live countdown to the next allowed ad, and a "Demo: no frequency
33
+ limit" toggle.
34
+
35
+ ### Changed
36
+
37
+ - `canShow()` is now `nextAdStatus().allowed`; its answers are unchanged.
38
+ Without `frequency`, behaviour is identical to 0.2.x. Billing and the event
39
+ outbox are unchanged.
40
+
41
+ ## [0.2.1] - 2026-11-21
42
+
43
+ ### Fixed
44
+
45
+ - `loadInterstitial()` no longer waits for the whole creative download. When
46
+ no preloaded ad is ready it waits at most `loadTimeoutMs` (default 3000 ms),
47
+ then returns the ad with the remote URL in `media.videoUri` (the player
48
+ streams it) while the download carries on in the background for next time.
49
+ Tapping "Mark Complete" before a preload finished could hang the break for
50
+ tens of seconds.
51
+ - A slow or trickling creative download no longer holds up later downloads:
52
+ each file gets one minute, then it is cancelled (when the file cache can
53
+ cancel) or abandoned, and the creative streams.
54
+ - `setAdsEnabled(false)` now also cancels a creative download in flight and
55
+ drops the ad being downloaded.
56
+ - Still-image ads in `<EthiclyInterstitial />` count toward viewability only
57
+ after the image has loaded. An image that fails to load reports
58
+ `tracker.error()`, counts nothing, and can be closed at once.
59
+ - Only `http:` and `https:` destinations are accepted. An ad with any other
60
+ scheme (`tel:`, `intent:`, `javascript:`, an app scheme) is refused as
61
+ `invalid_response`, logged once, and the tracker never opens such a URL.
62
+ - `createExpoFileCache` no longer warns to the console in a release build
63
+ unless a logger is passed.
64
+
65
+ ### Added
66
+
67
+ - `audio` option on `createEthicly` (`'on' | 'optional' | 'none'`): the app
68
+ chooses the sound for every ad, over the server's `interstitial.audio`.
69
+ `ad.audio` is the effective value. Default unchanged: sound on.
70
+ - `audio` prop on `<EthiclyInterstitial />`, over `ad.audio` for one screen.
71
+ - `loadTimeoutMs` option on `createEthicly`, and `DEFAULT_LOAD_TIMEOUT_MS`.
72
+ - Optional `cancel()` on `FileCacheAdapter`; both `createExpoFileCache`
73
+ variants implement it.
74
+ - `<EthiclyInterstitial />` shows a small "Test ad" label on a test-mode ad.
75
+ - README: "Sound" (with what `'on'` does on an iPhone) and "App Store and
76
+ Google Play disclosures".
77
+
78
+ ### Changed
79
+
80
+ - The build runs on `prepack` instead of `prepare`, so installing the SDK
81
+ from a local folder (the example app) no longer needs TypeScript in the SDK
82
+ folder. Published tarballs are unchanged.
83
+ - The skip delay is kept within 8 to 15 seconds, for both `/config`'s
84
+ `interstitial.skip_after_ms` and the ad's `skip_after_ms` (default still
85
+ 8 s). Skip still unlocks when the video ends, after the call to action, and
86
+ after the skip delay in foreground time if playback stalls.
87
+ - `<EthiclyInterstitial />` no longer passes the deprecated
88
+ `allowsFullscreen` to `VideoView` (native controls are off, so there is no
89
+ fullscreen button either way).
90
+ - Docs: apps with a paid tier create the client with `adsEnabled: false` and
91
+ call `setAdsEnabled(true)` for free users; show nothing for `ads_disabled`
92
+ (a paid user), the house ad for every other no-fill reason;
93
+ `useEthiclyInterstitial` comes from `@ethicly/react-native` (only
94
+ `EthiclyInterstitial` is in `/interstitial`); `appVersion` from
95
+ `expo-application`; `npx expo install expo-video` adds a config plugin, so
96
+ development builds need a new native build. Release notes moved out of the
97
+ package README.
7
98
 
8
99
  ## [0.2.0] - 2026-11-15
9
100
 
package/README.md CHANGED
@@ -1,13 +1,12 @@
1
1
  # @ethicly/react-native
2
2
 
3
- Fullscreen video ads from Ethicly for React Native and Expo apps. Version 0.2 (see `CHANGELOG.md`).
3
+ Fullscreen video ads from Ethicly for React Native and Expo apps. Version 0.2.1 (see `CHANGELOG.md`).
4
4
 
5
5
  The core is **headless**: it fetches the ad, downloads the video, and does all
6
6
  the tracking, while your app keeps its own player and its own house ads. A
7
7
  ready-made fullscreen screen is available as a separate, optional entry.
8
8
 
9
- It speaks contract v1 of the Ethicly app API (`docs/APP_API_V1.md` in the
10
- Ethicly repo). It ships no native code of its own.
9
+ It speaks contract v1 of the Ethicly app API. It ships no native code of its own.
11
10
 
12
11
  | | |
13
12
  |---|---|
@@ -31,7 +30,14 @@ Ethicly repo). It ships no native code of its own.
31
30
  `@react-native-async-storage/async-storage` and `expo-file-system` (most
32
31
  Expo apps already do). Add `expo-video` only if you want the ready-made
33
32
  screen. All three are optional peer dependencies, as is
34
- `react-native-safe-area-context`, which the screen uses when present.
33
+ `react-native-safe-area-context`, which the screen uses when present
34
+ (optional: without it the screen falls back to the status bar height).
35
+
36
+ Install Expo modules with `npx expo install` so the versions match your
37
+ Expo SDK. `npx expo install expo-video` also adds the `expo-video` config
38
+ plugin to your app config: an app that uses a development build or
39
+ `npx expo prebuild` needs a new native build after it (Expo Go already
40
+ includes expo-video).
35
41
 
36
42
  2. **Create one client at app start** and keep it for the life of the process:
37
43
 
@@ -39,12 +45,14 @@ Ethicly repo). It ships no native code of its own.
39
45
  import { Linking, Platform } from 'react-native';
40
46
  import AsyncStorage from '@react-native-async-storage/async-storage';
41
47
  import * as FileSystem from 'expo-file-system'; // any Expo SDK 50+ ('expo-file-system/legacy' works too)
48
+ import * as Application from 'expo-application'; // npx expo install expo-application
42
49
  import { createEthicly, createExpoFileCache } from '@ethicly/react-native';
43
50
 
44
51
  export const ethicly = createEthicly({
45
52
  apiKey: 'YOUR-PUBLISHER-KEY',
46
53
  platform: Platform.OS === 'android' ? 'android' : 'ios',
47
- appVersion: '4.2.0', // your app's version
54
+ appVersion: Application.nativeApplicationVersion ?? '0.0.0', // your app's version
55
+ adsEnabled: false, // apps with a paid tier: see step 3
48
56
  storage: AsyncStorage,
49
57
  fileCache: createExpoFileCache(FileSystem),
50
58
  openUrl: (url) => Linking.openURL(url),
@@ -53,9 +61,22 @@ Ethicly repo). It ships no native code of its own.
53
61
  });
54
62
  ```
55
63
 
56
- 3. **Tell it about paid users.** `ethicly.setAdsEnabled(false)` for anyone who
57
- removed ads. It stops serve requests and downloads. You can also pass
58
- `adsEnabled: false` to `createEthicly`.
64
+ `appVersion` is your app's version string. `expo-application`'s
65
+ `Application.nativeApplicationVersion` reads it from the installed app;
66
+ `Constants.expoConfig?.version` from `expo-constants` is an alternative.
67
+ Two more options: `audio` sets the sound for every ad (see "Sound" below)
68
+ and `loadTimeoutMs` (default 3000) bounds how long `loadInterstitial()`
69
+ waits for a download (see step 4).
70
+
71
+ 3. **Tell it about paid users.** `adsEnabled` defaults to true and is not
72
+ stored: if your app has a paid, ad-free tier, create the client with
73
+ `adsEnabled: false`, check the user's entitlement as you do today, and call
74
+ `ethicly.setAdsEnabled(true)` only for free users (and
75
+ `setAdsEnabled(false)` again if they subscribe). Otherwise a subscriber's
76
+ app serves and downloads an ad on every cold start before your entitlement
77
+ check finishes. `setAdsEnabled(false)` stops serve requests, drops the
78
+ preloaded ad and cancels a creative download in flight. An app without a
79
+ paid tier can leave `adsEnabled` out.
59
80
 
60
81
  4. **Preload early, load at the break.** Call `ethicly.preload()` some time
61
82
  before the ad is needed (for example when a lesson opens). At the break
@@ -63,13 +84,20 @@ Ethicly repo). It ships no native code of its own.
63
84
 
64
85
  ```ts
65
86
  const res = await ethicly.loadInterstitial();
66
- if (!res.ad) {
67
- showHouseAd(); // res.reason says why: no fill, capped, disabled...
68
- } else {
87
+ if (res.ad) {
69
88
  showMyPlayer(res.ad, res.tracker); // your existing player
70
- }
89
+ } else if (res.reason !== 'ads_disabled') {
90
+ showHouseAd(); // no fill, capped...: your own house ad
91
+ } // ads_disabled: a paid user, show nothing
71
92
  ```
72
93
 
94
+ `loadInterstitial()` returns within about `loadTimeoutMs` (default 3 s)
95
+ plus the serve request. When `preload()` already downloaded the ad it plays
96
+ from disk at once. When the download is not finished by then, the ad comes
97
+ back with the remote URL in `ad.media.videoUri` (the player streams it,
98
+ `ad.media.cached` is false) and the download carries on in the background
99
+ for next time. A download that takes longer than a minute is cancelled.
100
+
73
101
  `loadInterstitial()` already applies the frequency caps
74
102
  (`interstitial.max_per_session`, `interstitial.min_gap_s`) and the one hour
75
103
  token lifetime. `ethicly.canShow()` answers the same question without
@@ -82,10 +110,55 @@ Ethicly repo). It ships no native code of its own.
82
110
  time of the last ad is stored through `storage`, so `min_gap_s` also holds
83
111
  across restarts.
84
112
 
113
+ **You decide how often.** The dashboard values are only the starting point.
114
+ Set them in code and they win for this client:
115
+
116
+ ```ts
117
+ const ethicly = createEthicly({
118
+ // ...
119
+ frequency: { maxPerSession: 5, minGapSeconds: 60 },
120
+ });
121
+ // Later, for example after an A/B test or an entitlement check:
122
+ ethicly.setFrequency({ minGapSeconds: 30 }); // maxPerSession stays 5
123
+ ethicly.setFrequency({ maxPerSession: null }); // back to the dashboard value
124
+ ```
125
+
126
+ Each field you set wins over `/config`; a field you leave out uses the
127
+ dashboard value, then the defaults (3 per session, 120 s). Any number 0 or
128
+ above works: `maxPerSession: 0` shows no ads, `maxPerSession: Infinity` (or
129
+ a large number such as `1_000_000`) means no session limit,
130
+ `minGapSeconds: 0` means no gap. A negative value counts as 0; anything
131
+ that is not a number is ignored with a warning. Without `frequency` the SDK
132
+ behaves exactly as 0.2.x. `ethicly.getFrequency()` returns the values in
133
+ effect.
134
+
135
+ **Tell the user when the next ad may show.** `ethicly.nextAdStatus()` (also
136
+ on the hook) says whether an ad may show now and, when not, why:
137
+
138
+ ```ts
139
+ const s = ethicly.nextAdStatus();
140
+ // { allowed: false, reason: 'frequency_capped', retryAt: 1763730000000,
141
+ // shownThisSession: 1, maxPerSession: 3, minGapSeconds: 120 }
142
+ ```
143
+
144
+ | `reason` | Meaning |
145
+ |---|---|
146
+ | `frequency_capped` | the gap between ads is running; `retryAt` (epoch ms) is when it ends |
147
+ | `session_cap` | `maxPerSession` ads were shown this session; no `retryAt` (a new session starts after 30 minutes in the background) |
148
+ | `ads_disabled` | `setAdsEnabled(false)`, a paid user |
149
+ | `not_ready` | the stored frequency state is still loading |
150
+ | `invalid_key`, `unknown_key`, `sdk_unsupported`, `app_disabled`, `interstitial_disabled` | the same gates `loadInterstitial()` reports |
151
+
152
+ `canShow()` is `nextAdStatus().allowed`. `loadInterstitial()` still
153
+ reports both caps as `frequency_capped`, as in 0.2.x.
154
+
85
155
  5. **Call the tracker from your player.** Play `ad.media.videoUri` (a local
86
- file when cached), show `ad.ctaLabel` on the button, allow skipping after
87
- `ad.skipAfterMs`, play with sound unless `ad.audio` is `none` (always
88
- muted) or `optional` (start muted), then:
156
+ file when cached, else the remote URL), show `ad.ctaLabel` on the button
157
+ with a small "Sponsored by Ethicly.ch" line under it (required, as on the
158
+ ready-made screen),
159
+ allow skipping after `ad.skipAfterMs` (always 8 to 15 seconds: the SDK
160
+ clamps the server's value), play with sound unless `ad.audio` is `none`
161
+ (always muted) or `optional` (start muted), then:
89
162
 
90
163
  | When | Call |
91
164
  |---|---|
@@ -97,7 +170,9 @@ Ethicly repo). It ships no native code of its own.
97
170
  | the user taps the button | `tracker.clicked()` (it opens the link through `openUrl`) |
98
171
  | the ad screen goes away | `tracker.closed()` |
99
172
 
100
- Every tracker method is safe to call at any time and never throws.
173
+ Every tracker method is safe to call at any time and never throws. For a
174
+ still image (`ad.media.kind === 'image'`), call `progress()` only once the
175
+ image has loaded, and `tracker.error()` if it fails to load.
101
176
 
102
177
  ### Or use the ready-made screen
103
178
 
@@ -108,7 +183,8 @@ import { EthiclyInterstitial } from '@ethicly/react-native/interstitial';
108
183
  const interstitial = useEthiclyInterstitial(ethicly);
109
184
 
110
185
  async function onMarkComplete() {
111
- if (!(await interstitial.show())) showHouseAd();
186
+ if (await interstitial.show()) return; // the screen below shows the ad
187
+ if (ethicly.lastNoFillReason !== 'ads_disabled') showHouseAd(); // nothing for paid users
112
188
  }
113
189
 
114
190
  {interstitial.ad && interstitial.tracker && (
@@ -117,6 +193,7 @@ async function onMarkComplete() {
117
193
  tracker={interstitial.tracker}
118
194
  onClose={interstitial.dismiss}
119
195
  onRemoveAds={() => { interstitial.dismiss(); navigation.navigate('Upgrade'); }}
196
+ audio="optional" // optional: overrides ad.audio for this screen
120
197
  />
121
198
  )}
122
199
  ```
@@ -133,19 +210,47 @@ The screen is a fullscreen modal: the video fills it, a small "Ad" label sits
133
210
  top left, a white button shows `ctaLabel` ("Learn more" when the advertiser
134
211
  set none), and either `onRemoveAds` (a "Remove ads" link) or
135
212
  `renderBelowButton` fills the space under the button, above a small
136
- "Sponsored by Ethicly.ch" line. Audio follows
137
- `interstitial.audio`: `on` (the default) starts with sound and offers a mute
138
- toggle (expo-video plays through the iPhone silent switch and pauses other
139
- audio while the ad has sound), `optional` starts muted with a sound toggle, `none` is always muted.
213
+ "Sponsored by Ethicly.ch" line. A test-mode ad (`ad.test`) also shows a small
214
+ "Test ad" label. Sound follows `ad.audio`, or the screen's `audio` prop when
215
+ you pass one (see "Sound" below).
216
+
217
+ A still-image ad counts toward viewability only once the image has loaded. If
218
+ it fails to load the screen reports `tracker.error()`, counts nothing, and
219
+ lets the user close it at once.
140
220
 
141
221
  The skip control is a solid black pill that reads "Skip in N", then
142
- "Skip Ad" with a skip-to-end icon (restyle it with the `skipStyle` and `skipTextStyle` props). The
222
+ "Skip Ad" with a skip-to-end icon (restyle it with the `skipStyle` and `skipTextStyle` props).
223
+ Skip appears after `ad.skipAfterMs`: at least 8 seconds, at most 15. The
143
224
  countdown follows playback, with foreground time on screen as a fallback, so a
144
- stalled video never traps the user. After the user opens the link and comes
225
+ stalled video never traps the user. A video shorter than that can be closed
226
+ when it ends. After the user opens the link and comes
145
227
  back, Skip is available at once. Android back closes the ad only once Skip is
146
228
  available. If the ad expired before it reached the screen, the screen closes
147
229
  itself through `onClose` without recording an impression.
148
230
 
231
+ ### Sound
232
+
233
+ Ads play with sound by default. You choose, in code:
234
+
235
+ - `createEthicly({ ..., audio })` sets it for every ad, over the publisher
236
+ setting from the server. `ad.audio` is the effective value.
237
+ - `<EthiclyInterstitial audio="optional" ... />` sets it for one screen, over
238
+ `ad.audio`.
239
+
240
+ Precedence: the screen's `audio` prop, then the client's `audio` option, then
241
+ the server's `interstitial.audio`, then `'on'`.
242
+
243
+ | Value | Behaviour |
244
+ |---|---|
245
+ | `'on'` (default) | starts with sound, with a mute toggle |
246
+ | `'optional'` | starts muted, with a "Sound on" toggle |
247
+ | `'none'` | always muted, no toggle |
248
+
249
+ Know what `'on'` does on an iPhone: expo-video plays the ad's sound even when
250
+ the silent switch is on, and it pauses the user's own audio (music, a
251
+ podcast) while the ad plays. If your users often listen to something while
252
+ using the app, `'optional'` is the gentler choice.
253
+
149
254
  ### The creative cache
150
255
 
151
256
  `createExpoFileCache(FileSystem)` takes the `expo-file-system` module as your
@@ -153,7 +258,8 @@ app imports it, on any Expo SDK from 50. On SDK 54 and later
153
258
  `import * as FileSystem from 'expo-file-system'` is the object API (`File`,
154
259
  `Directory`, `Paths`) and the adapter uses it; before SDK 54, or from
155
260
  `expo-file-system/legacy`, it uses the legacy functions. You never need to
156
- tell it which. Given anything else it streams creatives and logs one warning.
261
+ tell it which. Given anything else it streams creatives and logs one warning
262
+ (through the `logger` argument; to the console only in development).
157
263
 
158
264
  It keeps creatives in `<cache directory>/ethicly-ads/`
159
265
  within `prefetch.max_cache_mb` and `prefetch.max_cached_creatives` (from
@@ -168,7 +274,35 @@ default in-memory `storage` the index is lost when the app exits, so the
168
274
  directory is emptied at the next start: disk use stays bounded either way, but
169
275
  pass `AsyncStorage` to keep creatives across launches. A custom
170
276
  `FileCacheAdapter` should implement `list()` (and ideally `uriFor()`) for the
171
- same guarantee.
277
+ same guarantee, and `cancel()` so `setAdsEnabled(false)` and the one-minute
278
+ limit can stop a download in flight.
279
+
280
+ ## What you control and what Ethicly controls
281
+
282
+ You, the publisher, decide how ads fit your app:
283
+
284
+ - **How often:** the `frequency` option or `setFrequency()` in code, or the
285
+ dashboard values when you set nothing.
286
+ - **When:** which moments in your app call `show()` or `loadInterstitial()`.
287
+ - **Paid users:** `setAdsEnabled(false)` means no serves and no downloads.
288
+ - **Sound:** the `audio` option or prop.
289
+ - **Fallback:** what to show when no Ethicly ad is available (your house ad).
290
+ - **Player:** the ready-made screen or your own player with the tracker.
291
+
292
+ Ethicly decides:
293
+
294
+ - **Which ad** is served.
295
+ - **The skip window:** Skip appears after 8 to 15 seconds.
296
+ - **The ad labels:** the "Ad" label and the "Sponsored by Ethicly.ch" line
297
+ under the button stay visible, also in your own player.
298
+ - **What counts** as a billable view or a billable click.
299
+ - **Billing** and payouts.
300
+ - **Anti-abuse limits**, such as a minimum time between billable views from
301
+ the same app.
302
+ - **The kill switch** and the **minimum SDK version**.
303
+
304
+ Ads you show beyond Ethicly's anti-abuse limits still play, but they are not
305
+ billed. Showing ads more often than those limits allow does not earn more.
172
306
 
173
307
  ## Test mode
174
308
 
@@ -180,9 +314,8 @@ earnings. The `/impression` answer is logged as a test impression.
180
314
  (`__DEV__` false) the SDK ignores `testMode: true`: it serves and bills
181
315
  normally and logs an error through `logger` and once through `console.error`,
182
316
  so a forgotten flag cannot cost the publisher its earnings. Still tie it to
183
- `__DEV__`. Where `__DEV__` is not defined at all (a Node script such as
184
- `npm run test:live`, or tests) the code is not a shipped app, and test mode
185
- works as asked.
317
+ `__DEV__`. Where `__DEV__` is not defined at all (a Node script, or tests)
318
+ the code is not a shipped app, and test mode works as asked.
186
319
 
187
320
  ## Reliability
188
321
 
@@ -213,9 +346,12 @@ createEthicly(options: {
213
346
  appVersion: string;
214
347
  baseUrl?: string; // default https://ads.ethicly.ch/functions/v1/get-ad-with-geo
215
348
  testMode?: boolean; // ignored in a release build
216
- adsEnabled?: boolean; // default true
349
+ adsEnabled?: boolean; // default true; pass false until entitlement is known (paid tier)
350
+ audio?: 'on' | 'optional' | 'none'; // overrides the server's interstitial.audio for every ad
351
+ loadTimeoutMs?: number; // default 3000: longest loadInterstitial() waits for a download
352
+ frequency?: { maxPerSession?: number; minGapSeconds?: number }; // wins over /config; unset: /config
217
353
  storage?: KeyValueStorage; // AsyncStorage shape; default in memory
218
- fileCache?: FileCacheAdapter; // download/exists/delete/size/list; default streams
354
+ fileCache?: FileCacheAdapter; // download/exists/delete/size/list/cancel; default streams
219
355
  openUrl?: (url: string) => unknown;
220
356
  fetch?: FetchLike; // default global fetch
221
357
  now?: () => number;
@@ -230,6 +366,9 @@ interface Ethicly {
230
366
  preload(): Promise<InterstitialResult>;
231
367
  loadInterstitial(): Promise<InterstitialResult>;
232
368
  canShow(): boolean; // false until the stored frequency state loaded
369
+ nextAdStatus(): NextAdStatus; // allowed, reason, retryAt, shownThisSession, maxPerSession, minGapSeconds
370
+ setFrequency(update: { maxPerSession?: number | null; minGapSeconds?: number | null }): void; // null: back to /config
371
+ getFrequency(): { maxPerSession: number; minGapSeconds: number };
233
372
  setAdsEnabled(enabled: boolean): void;
234
373
  isAdsEnabled(): boolean;
235
374
  getConfig(): EthiclyConfig;
@@ -265,12 +404,17 @@ interface Tracker {
265
404
  `NoFillReason` is a server reason (`no_matching_ad`, `no_approved_ads`,
266
405
  `app_disabled`, `sdk_unsupported`, `interstitial_disabled`, ...) or one of the
267
406
  SDK's own: `ads_disabled`, `frequency_capped`, `unknown_key`, `invalid_key`,
268
- `rate_limited`, `network_error`, `server_error`, `invalid_response`. Treat
269
- every one of them as "show the house ad".
407
+ `rate_limited`, `network_error`, `server_error`, `invalid_response`. Show
408
+ your house ad for every reason except `ads_disabled`: that one means a paid
409
+ user (you called `setAdsEnabled(false)`), so show nothing.
410
+
411
+ An ad whose destination is not an `http:` or `https:` URL (for example
412
+ `tel:`, `intent:`, `javascript:` or an app scheme) is refused as
413
+ `invalid_response`, and the tracker never opens such a URL.
270
414
 
271
415
  Also exported: `useEthiclyInterstitial`, `createMemoryStorage`,
272
416
  `createMemoryFileCache`, `createExpoFileCache`, `appendClickToken`,
273
- `compareVersions`, `SDK_VERSION`, `SESSION_TIMEOUT_MS`. The core alone is at
417
+ `compareVersions`, `SDK_VERSION`, `SESSION_TIMEOUT_MS`, `DEFAULT_LOAD_TIMEOUT_MS`. The core alone is at
274
418
  `@ethicly/react-native/core` (no React import).
275
419
 
276
420
  ## What it sends, and what it never sends
@@ -282,7 +426,75 @@ from `crypto.randomUUID` or `crypto.getRandomValues` and falls back to
282
426
  without a polyfill such as `react-native-get-random-values`), the ad
283
427
  and impression ids, and the country code the server returned. It sends no
284
428
  advertising identifier, no device or vendor id, no user id and no location.
285
- The server's full inventory is in "Data collected" in `docs/APP_API_V1.md`.
429
+ With each impression it also sends the rendered ad size, how long the ad was
430
+ visible, video progress (quartiles, complete, skip and its position, playback
431
+ error) and whether the button was tapped.
432
+
433
+ ## App Store and Google Play disclosures
434
+
435
+ This is a factual list of what the SDK and Ethicly's server handle, so you can
436
+ fill in Apple's App Privacy answers and Google Play's Data safety form. It is
437
+ not legal advice; you are responsible for your app's declarations.
438
+
439
+ **What Ethicly's server stores**, per ad shown:
440
+
441
+ - the ad id and your publisher site id, `platform`, the SDK version and your
442
+ `appVersion`;
443
+ - a random id the SDK generates for that one rendered ad (not tied to the
444
+ user or the device; a new one for every ad);
445
+ - the rendered size of the ad, whether and how long it was visible, video
446
+ progress (highest quartile, completed, skipped and the skip position,
447
+ playback error);
448
+ - whether the ad was clicked, with a random click token for conversion
449
+ reporting;
450
+ - a two-letter country code. The server derives it from the device's IP
451
+ address with its own database (no third party). The IP address itself is
452
+ used in transit (country lookup, rate limiting) and is not written to
453
+ Ethicly's database or to the ad server's own logs, except as two salted
454
+ hashes used against fraud: one combined with the ad id, used to cap clicks
455
+ per IP and deleted after two days; and one combined with your site and the
456
+ day, used to cap billable views per network and deleted after about two
457
+ hours. Neither identifies a device or links data across apps. Request logs
458
+ kept by Ethicly's hosting platform are outside this
459
+ list.
460
+
461
+ Serve and `/config` requests store nothing per request. The User-Agent header
462
+ is read in transit and not stored.
463
+
464
+ **Never collected:** no advertising identifier (IDFA or GAID), no vendor or
465
+ device identifier, no install or user id, no precise location, no contacts,
466
+ no cookies. Nothing links the data to a user or to data from other apps.
467
+
468
+ **The creative host.** The SDK downloads the ad's video, image and poster
469
+ from the URLs in the ad. Like any download, that host sees the device's IP
470
+ address and User-Agent.
471
+
472
+ **Apple (App Privacy, App Store Connect):**
473
+
474
+ - Usage Data, Product Interaction (ad views, taps, video progress), and
475
+ Usage Data, Advertising Data (which ads were shown): collected, used for
476
+ Third-Party Advertising (and Analytics, for the publisher's reports), **not
477
+ linked to the user**, **not used for tracking**.
478
+ - Country derived from the IP address: if you treat it as location, declare
479
+ Location, Coarse Location: not linked to the user, not used for tracking.
480
+ - No App Tracking Transparency prompt is needed for Ethicly: the SDK does not
481
+ read the IDFA and does not track users across apps or websites.
482
+
483
+ **Google Play (Data safety):**
484
+
485
+ - Location, Approximate location: derived from the IP address on Ethicly's
486
+ server (country only). Collected, for Advertising or marketing and
487
+ Analytics.
488
+ - App activity, App interactions (ad views, clicks, video progress):
489
+ collected, for Advertising or marketing and Analytics.
490
+ - Not used for tracking: no advertising or device identifier is read, and
491
+ the data is not linked to a user. Answer the sharing, encryption and
492
+ deletion questions for your app as a whole; ask Ethicly if you need a
493
+ statement for them.
494
+
495
+ **Children.** Ethicly is not a Google Play Families self-certified ads SDK.
496
+ Do not use it in apps primarily directed at children, or in the parts of an
497
+ app aimed at children.
286
498
 
287
499
  ## Development
288
500
 
@@ -290,25 +502,6 @@ The server's full inventory is in "Data collected" in `docs/APP_API_V1.md`.
290
502
  npm install
291
503
  npm run typecheck
292
504
  npm test # jest in Node, against recorded fixtures
293
- npm run test:live # one test-mode run against production (stores nothing)
294
505
  npm run build # lib/commonjs, lib/module, lib/typescript (also run by `prepare`)
295
506
  npm pack # installable tarball
296
507
  ```
297
-
298
- ### Releasing
299
-
300
- Bump `version` in `package.json` and `package-lock.json`, add the
301
- `CHANGELOG.md` section in a normal PR and merge it. Then tag the merge commit:
302
-
303
- ```
304
- git tag sdk-v0.2.0 <merge commit on main> && git push origin sdk-v0.2.0
305
- ```
306
-
307
- `.github/workflows/sdk-release.yml` re-runs the checks, refuses a tag that
308
- does not match `package.json` or is not on main, publishes to npm (secret
309
- `NPM_TOKEN` in the `npm-publish` environment, whose reviewers approve each run) and creates a GitHub release with the tarball and that version's
310
- changelog. Running the workflow by hand is a dry run.
311
-
312
- `example/` is a minimal Expo app with both the headless flow and the
313
- ready-made screen, in test mode. It reads the publisher key from
314
- `EXPO_PUBLIC_ETHICLY_KEY` (for example `EXPO_PUBLIC_ETHICLY_KEY=... npx expo start`).
@@ -73,7 +73,8 @@ function isLegacyFs(fs) {
73
73
  * A file cache over either expo-file-system API: the object API of SDK 54+
74
74
  * (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
75
75
  * `downloadAsync`, ...). Anything else gets the streaming cache, which writes
76
- * nothing to disk, and one warning through `logger` (default `console`).
76
+ * nothing to disk, and one warning through `logger` (default `console` in
77
+ * development, nothing in a release build).
77
78
  */
78
79
  function createExpoFileCache(fs, subdirectory = exports.DEFAULT_CACHE_SUBDIRECTORY, logger) {
79
80
  const sub = safeCacheSubdirectory(subdirectory);
@@ -81,7 +82,8 @@ function createExpoFileCache(fs, subdirectory = exports.DEFAULT_CACHE_SUBDIRECTO
81
82
  return modernFileCache(fs, sub);
82
83
  if (isLegacyFs(fs))
83
84
  return legacyFileCache(fs, sub);
84
- safeLogger(logger || consoleLogger()).warn('createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream');
85
+ // console only in development: a release build stays quiet unless the app passes a logger.
86
+ safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn('createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream');
85
87
  return createMemoryFileCache();
86
88
  }
87
89
  function consoleLogger() {
@@ -91,6 +93,8 @@ function consoleLogger() {
91
93
  function legacyFileCache(fs, sub) {
92
94
  const dir = `${fs.cacheDirectory}${sub}`;
93
95
  let made = null;
96
+ /** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
97
+ const inflight = new Set();
94
98
  const sizeOf = async (uri) => {
95
99
  const info = await fs.getInfoAsync(uri, { size: true });
96
100
  return info.exists && typeof info.size === 'number' ? info.size : 0;
@@ -106,15 +110,22 @@ function legacyFileCache(fs, sub) {
106
110
  let tooBig = false;
107
111
  if (max !== undefined && fs.createDownloadResumable) {
108
112
  // Stop as soon as the server announces, or we have written, more than the budget.
113
+ const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
109
114
  const dl = fs.createDownloadResumable(url, target, {}, (p) => {
110
115
  if (tooBig)
111
116
  return;
112
117
  if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
113
118
  tooBig = true;
114
- void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined);
119
+ stop();
115
120
  }
116
121
  });
117
- res = await dl.downloadAsync().catch(() => undefined);
122
+ inflight.add(stop);
123
+ try {
124
+ res = await dl.downloadAsync().catch(() => undefined);
125
+ }
126
+ finally {
127
+ inflight.delete(stop);
128
+ }
118
129
  }
119
130
  else {
120
131
  res = await fs.downloadAsync(url, target);
@@ -129,6 +140,12 @@ function legacyFileCache(fs, sub) {
129
140
  async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
130
141
  size: sizeOf,
131
142
  uriFor: (fileName) => dir + fileName,
143
+ cancel() {
144
+ inflight.forEach((stop) => { try {
145
+ stop();
146
+ }
147
+ catch { /* already settled */ } });
148
+ },
132
149
  async list() {
133
150
  if (!fs.readDirectoryAsync)
134
151
  return [];
@@ -163,6 +180,7 @@ function modernFileCache(fs, sub) {
163
180
  return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
164
181
  };
165
182
  let made = false;
183
+ const inflight = new Set();
166
184
  return {
167
185
  async download(url, fileName, opts) {
168
186
  if (!made) {
@@ -174,6 +192,7 @@ function modernFileCache(fs, sub) {
174
192
  const target = dir() + fileName;
175
193
  const max = opts === null || opts === void 0 ? void 0 : opts.maxBytes;
176
194
  let tooBig = false;
195
+ let cancelled = false;
177
196
  try {
178
197
  remove(target);
179
198
  const createTask = fs.File.createDownloadTask;
@@ -190,7 +209,14 @@ function modernFileCache(fs, sub) {
190
209
  catch { /* already settled */ }
191
210
  },
192
211
  });
193
- await task.downloadAsync();
212
+ const handle = { cancel: () => { cancelled = true; task.cancel(); } };
213
+ inflight.add(handle);
214
+ try {
215
+ await task.downloadAsync();
216
+ }
217
+ finally {
218
+ inflight.delete(handle);
219
+ }
194
220
  }
195
221
  else {
196
222
  await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
@@ -206,6 +232,13 @@ function modernFileCache(fs, sub) {
206
232
  // Without a progress callback the whole file lands first: check it now
207
233
  // and delete it if it is over the budget.
208
234
  const bytes = await sizeOf(target);
235
+ if (cancelled) {
236
+ try {
237
+ remove(target);
238
+ }
239
+ catch { /* ignore */ }
240
+ throw new Error('download cancelled');
241
+ }
209
242
  if (tooBig || (max !== undefined && bytes > max)) {
210
243
  try {
211
244
  remove(target);
@@ -219,6 +252,12 @@ function modernFileCache(fs, sub) {
219
252
  async delete(uri) { remove(uri); },
220
253
  size: sizeOf,
221
254
  uriFor: (fileName) => dir() + fileName,
255
+ cancel() {
256
+ inflight.forEach((t) => { try {
257
+ t.cancel();
258
+ }
259
+ catch { /* already settled */ } });
260
+ },
222
261
  async list() {
223
262
  const d = new fs.Directory(dir());
224
263
  if (!d.exists)