@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.
- package/CHANGELOG.md +92 -1
- package/README.md +246 -53
- package/lib/commonjs/core/adapters.js +44 -5
- package/lib/commonjs/core/cache.js +60 -5
- package/lib/commonjs/core/click.js +10 -0
- package/lib/commonjs/core/client.js +237 -73
- package/lib/commonjs/core/config.js +17 -2
- package/lib/commonjs/core/index.js +2 -1
- package/lib/commonjs/core/tracker.js +8 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
- package/lib/commonjs/react/useEthiclyInterstitial.js +4 -1
- package/lib/commonjs/version.js +1 -1
- package/lib/module/core/adapters.js +44 -5
- package/lib/module/core/cache.js +59 -4
- package/lib/module/core/click.js +9 -0
- package/lib/module/core/client.js +237 -73
- package/lib/module/core/config.js +15 -1
- package/lib/module/core/index.js +1 -1
- package/lib/module/core/tracker.js +9 -1
- package/lib/module/react/EthiclyInterstitial.js +45 -13
- package/lib/module/react/useEthiclyInterstitial.js +4 -1
- package/lib/module/version.js +1 -1
- package/lib/typescript/core/adapters.d.ts +2 -1
- package/lib/typescript/core/cache.d.ts +20 -2
- package/lib/typescript/core/click.d.ts +5 -0
- package/lib/typescript/core/client.d.ts +42 -3
- package/lib/typescript/core/config.d.ts +9 -0
- package/lib/typescript/core/index.d.ts +2 -2
- package/lib/typescript/core/types.d.ts +48 -0
- package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +4 -2
- package/lib/typescript/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/core/adapters.ts +33 -5
- package/src/core/cache.ts +48 -3
- package/src/core/click.ts +10 -0
- package/src/core/client.ts +278 -76
- package/src/core/config.ts +14 -1
- package/src/core/index.ts +4 -3
- package/src/core/tracker.ts +8 -1
- package/src/core/types.ts +57 -0
- package/src/react/EthiclyInterstitial.tsx +62 -16
- package/src/react/useEthiclyInterstitial.ts +8 -3
- package/src/version.ts +1 -1
|
@@ -47,5 +47,8 @@ export function useEthiclyInterstitial(ethicly, options = {}) {
|
|
|
47
47
|
void ethicly.preload();
|
|
48
48
|
}, [ethicly, preload]);
|
|
49
49
|
const canShow = useCallback(() => ethicly.canShow(), [ethicly]);
|
|
50
|
-
|
|
50
|
+
const nextAdStatus = useCallback(() => ethicly.nextAdStatus(), [ethicly]);
|
|
51
|
+
return {
|
|
52
|
+
ad: (_a = current === null || current === void 0 ? void 0 : current.ad) !== null && _a !== void 0 ? _a : null, tracker: (_b = current === null || current === void 0 ? void 0 : current.tracker) !== null && _b !== void 0 ? _b : null, reason, loading, show, dismiss, canShow, nextAdStatus,
|
|
53
|
+
};
|
|
51
54
|
}
|
package/lib/module/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
|
|
2
|
-
export const SDK_VERSION = '0.
|
|
2
|
+
export const SDK_VERSION = '0.3.0';
|
|
@@ -108,7 +108,8 @@ export declare function safeCacheSubdirectory(subdirectory: unknown): string;
|
|
|
108
108
|
* A file cache over either expo-file-system API: the object API of SDK 54+
|
|
109
109
|
* (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
|
|
110
110
|
* `downloadAsync`, ...). Anything else gets the streaming cache, which writes
|
|
111
|
-
* nothing to disk, and one warning through `logger` (default `console`
|
|
111
|
+
* nothing to disk, and one warning through `logger` (default `console` in
|
|
112
|
+
* development, nothing in a release build).
|
|
112
113
|
*/
|
|
113
114
|
export declare function createExpoFileCache(fs: ExpoFileSystemLike | ExpoFileSystemModernLike, subdirectory?: string, logger?: Logger): FileCacheAdapter;
|
|
114
115
|
/**
|
|
@@ -7,6 +7,13 @@ export interface CachedMedia {
|
|
|
7
7
|
/** remote URL -> local uri, for the files that are cached. */
|
|
8
8
|
uris: Record<string, string>;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* The longest one creative file may take to download. A slower (trickling)
|
|
12
|
+
* download is cancelled when the adapter supports it, else abandoned: the
|
|
13
|
+
* creative streams and later downloads are not held up behind it. A file it
|
|
14
|
+
* still writes afterwards is not indexed, so the next launch's sweep deletes it.
|
|
15
|
+
*/
|
|
16
|
+
export declare const DOWNLOAD_TIMEOUT_MS = 60000;
|
|
10
17
|
/** Content-Length of a URL, or null when unknown. */
|
|
11
18
|
export type SizeProbe = (url: string) => Promise<number | null>;
|
|
12
19
|
export declare class CreativeCache {
|
|
@@ -16,12 +23,22 @@ export declare class CreativeCache {
|
|
|
16
23
|
private now;
|
|
17
24
|
private log;
|
|
18
25
|
private probeSize;
|
|
26
|
+
private downloadTimeoutMs;
|
|
19
27
|
private entries;
|
|
20
28
|
/** File names whose download has started but not landed. */
|
|
21
29
|
private pending;
|
|
22
30
|
private loaded;
|
|
23
31
|
private chain;
|
|
24
|
-
|
|
32
|
+
/** Bumped by cancel(): a download started before it no longer counts. */
|
|
33
|
+
private generation;
|
|
34
|
+
constructor(files: FileCacheAdapter, storage: KeyValueStorage, storageKey: string, now: () => number, log: Required<Logger>, probeSize?: SizeProbe, downloadTimeoutMs?: number);
|
|
35
|
+
/**
|
|
36
|
+
* Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
|
|
37
|
+
* and skip the files not started yet. For setAdsEnabled(false).
|
|
38
|
+
*/
|
|
39
|
+
cancel(): void;
|
|
40
|
+
/** The adapter's download, given up on after downloadTimeoutMs. */
|
|
41
|
+
private downloadWithin;
|
|
25
42
|
private load;
|
|
26
43
|
private loadNow;
|
|
27
44
|
/**
|
|
@@ -40,7 +57,8 @@ export declare class CreativeCache {
|
|
|
40
57
|
* Make sure the files of one creative are on disk. Never throws: a file that
|
|
41
58
|
* cannot be cached is simply left out of the result and streamed instead.
|
|
42
59
|
* `allowed()` is checked before every download so setAdsEnabled(false)
|
|
43
|
-
* stops a download that has not started yet
|
|
60
|
+
* stops a download that has not started yet; cancel() also stops the one in
|
|
61
|
+
* flight when the adapter supports it.
|
|
44
62
|
*/
|
|
45
63
|
ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
|
|
46
64
|
private ensureNow;
|
|
@@ -6,3 +6,8 @@
|
|
|
6
6
|
export declare function appendClickToken(destinationUrl: string, clickToken: string | null | undefined): string;
|
|
7
7
|
/** The /click budget: the website snippet aborts at exactly 500 ms. */
|
|
8
8
|
export declare const CLICK_TIMEOUT_MS = 500;
|
|
9
|
+
/**
|
|
10
|
+
* True for an absolute http: or https: URL with a host. Anything else (tel:,
|
|
11
|
+
* intent:, javascript:, a custom app scheme, a relative path) is never opened.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isWebUrl(url: unknown): url is string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AppStateLike } from './adapters';
|
|
2
|
-
import type { EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform } from './types';
|
|
2
|
+
import type { AudioPolicy, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdStatus, NoFillReason, Platform } from './types';
|
|
3
3
|
export interface EthiclyOptions {
|
|
4
4
|
/** Publisher API key (UUID). */
|
|
5
5
|
apiKey: string;
|
|
@@ -14,8 +14,33 @@ export interface EthiclyOptions {
|
|
|
14
14
|
* (`__DEV__` false), where the SDK serves and bills normally and logs an error.
|
|
15
15
|
*/
|
|
16
16
|
testMode?: boolean;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Initial state of the ads switch, default true. Apps with a paid tier: pass
|
|
19
|
+
* false until you know the user's entitlement, then setAdsEnabled(true) for
|
|
20
|
+
* free users, so a subscriber never serves or downloads an ad.
|
|
21
|
+
*/
|
|
18
22
|
adsEnabled?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Sound for every ad, over the server's interstitial.audio: 'on' plays with
|
|
25
|
+
* sound, 'optional' starts muted with a sound toggle, 'none' plays muted with
|
|
26
|
+
* no toggle. Unset: the server's value, which defaults to 'on'. `ad.audio`
|
|
27
|
+
* is the effective value. EthiclyInterstitial's `audio` prop overrides it per screen.
|
|
28
|
+
*/
|
|
29
|
+
audio?: AudioPolicy;
|
|
30
|
+
/**
|
|
31
|
+
* The longest loadInterstitial() waits for the creative download when no
|
|
32
|
+
* preloaded ad is ready, in ms. Default 3000 (DEFAULT_LOAD_TIMEOUT_MS). After
|
|
33
|
+
* it the ad comes back with the remote URL, so the player streams, and the
|
|
34
|
+
* download carries on in the background for next time.
|
|
35
|
+
*/
|
|
36
|
+
loadTimeoutMs?: number;
|
|
37
|
+
/**
|
|
38
|
+
* How often ads may show, decided in code. A field set here overrides the
|
|
39
|
+
* dashboard value (/config interstitial.max_per_session, min_gap_s) for this
|
|
40
|
+
* client; an unset field uses /config, then the defaults. Unset: 0.2.x
|
|
41
|
+
* behaviour. Change it later with setFrequency().
|
|
42
|
+
*/
|
|
43
|
+
frequency?: FrequencyOptions;
|
|
19
44
|
storage?: KeyValueStorage;
|
|
20
45
|
fileCache?: FileCacheAdapter;
|
|
21
46
|
openUrl?: (url: string) => unknown;
|
|
@@ -40,7 +65,19 @@ export interface Ethicly {
|
|
|
40
65
|
* false until the stored frequency state has loaded (see `ready`).
|
|
41
66
|
*/
|
|
42
67
|
canShow(): boolean;
|
|
43
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* Whether an ad may show now and, when not, why and when it may: retryAt is
|
|
70
|
+
* set while the gap between ads runs. canShow() is nextAdStatus().allowed.
|
|
71
|
+
*/
|
|
72
|
+
nextAdStatus(): NextAdStatus;
|
|
73
|
+
/**
|
|
74
|
+
* Change the frequency set in code, for example after an entitlement check
|
|
75
|
+
* or an A/B test. A field left out keeps its value; null goes back to /config.
|
|
76
|
+
*/
|
|
77
|
+
setFrequency(update: FrequencyUpdate): void;
|
|
78
|
+
/** The effective frequency: code, else /config, else the defaults. */
|
|
79
|
+
getFrequency(): Required<FrequencyOptions>;
|
|
80
|
+
/** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
|
|
44
81
|
setAdsEnabled(enabled: boolean): void;
|
|
45
82
|
isAdsEnabled(): boolean;
|
|
46
83
|
getConfig(): EthiclyConfig;
|
|
@@ -50,6 +87,8 @@ export interface Ethicly {
|
|
|
50
87
|
readonly lastNoFillReason: NoFillReason | null;
|
|
51
88
|
readonly sdkVersion: string;
|
|
52
89
|
}
|
|
90
|
+
/** How long loadInterstitial() waits for a creative download by default. */
|
|
91
|
+
export declare const DEFAULT_LOAD_TIMEOUT_MS = 3000;
|
|
53
92
|
/**
|
|
54
93
|
* A new session (interstitial.max_per_session counts from zero again) starts
|
|
55
94
|
* when the app comes back after at least this long in the background.
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { EthiclyConfig } from './types';
|
|
2
2
|
export declare const BUNDLED_BASE_URL = "https://ads.ethicly.ch/functions/v1/get-ad-with-geo";
|
|
3
3
|
export declare const DEFAULT_MAX_AGE_S = 300;
|
|
4
|
+
/**
|
|
5
|
+
* The skip delay is kept within these bounds, from /config and from the ad:
|
|
6
|
+
* the video is watched for at least 8 s before Skip appears (it still
|
|
7
|
+
* unlocks earlier when the video ends or after the call to action).
|
|
8
|
+
*/
|
|
9
|
+
export declare const MIN_SKIP_AFTER_MS = 8000;
|
|
10
|
+
export declare const MAX_SKIP_AFTER_MS = 15000;
|
|
11
|
+
/** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
|
|
12
|
+
export declare function clampSkipAfterMs(v: unknown): number | null;
|
|
4
13
|
/** The defaults shown in the doc. Used when no config was ever fetched. */
|
|
5
14
|
export declare function defaultConfig(serveBase: string): EthiclyConfig;
|
|
6
15
|
/** An https URL, without a trailing slash, or null. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { createEthicly, SESSION_TIMEOUT_MS } from './client';
|
|
1
|
+
export { createEthicly, DEFAULT_LOAD_TIMEOUT_MS, SESSION_TIMEOUT_MS } from './client';
|
|
2
2
|
export type { Ethicly, EthiclyOptions } from './client';
|
|
3
3
|
export { createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4, } from './adapters';
|
|
4
4
|
export type { AppStateLike, ExpoFileSystemLike, ExpoFileSystemModernLike } from './adapters';
|
|
5
5
|
export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
|
|
6
6
|
export { compareVersions, BUNDLED_BASE_URL } from './config';
|
|
7
7
|
export { SDK_VERSION } from '../version';
|
|
8
|
-
export type { AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform, Tracker, } from './types';
|
|
8
|
+
export type { AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform, Tracker, } from './types';
|
|
@@ -52,6 +52,11 @@ export interface FileCacheAdapter {
|
|
|
52
52
|
list?(): Promise<string[]>;
|
|
53
53
|
/** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
|
|
54
54
|
uriFor?(fileName: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Abort every download in flight: each rejects and leaves no file. Optional;
|
|
57
|
+
* used by setAdsEnabled(false) and for a download that takes too long.
|
|
58
|
+
*/
|
|
59
|
+
cancel?(): void;
|
|
55
60
|
}
|
|
56
61
|
export interface Logger {
|
|
57
62
|
debug?(message: string, ...rest: unknown[]): void;
|
|
@@ -168,3 +173,46 @@ export interface WireServe {
|
|
|
168
173
|
test?: boolean;
|
|
169
174
|
request_id?: string;
|
|
170
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* How often ads may show, set in code. Each field set here wins over the
|
|
178
|
+
* dashboard value from /config (interstitial.max_per_session, min_gap_s);
|
|
179
|
+
* an unset field falls back to /config, then to the defaults (3 and 120).
|
|
180
|
+
*/
|
|
181
|
+
export interface FrequencyOptions {
|
|
182
|
+
/**
|
|
183
|
+
* Ads per session. 0 shows none. Any integer >= 0; Infinity (or a large
|
|
184
|
+
* number such as 1000000) means no session limit.
|
|
185
|
+
*/
|
|
186
|
+
maxPerSession?: number;
|
|
187
|
+
/** Seconds between two ads, kept across restarts. 0 means no gap. Finite, >= 0. */
|
|
188
|
+
minGapSeconds?: number;
|
|
189
|
+
}
|
|
190
|
+
/** setFrequency(): a field left out keeps its current value, null goes back to /config. */
|
|
191
|
+
export interface FrequencyUpdate {
|
|
192
|
+
maxPerSession?: number | null;
|
|
193
|
+
minGapSeconds?: number | null;
|
|
194
|
+
}
|
|
195
|
+
/** Why nextAdStatus() says no ad may show now. */
|
|
196
|
+
export type NextAdReason =
|
|
197
|
+
/** The gap between ads (min_gap_s) has not passed: see retryAt. */
|
|
198
|
+
'frequency_capped'
|
|
199
|
+
/** max_per_session ads were shown this session. */
|
|
200
|
+
| 'session_cap'
|
|
201
|
+
/** setAdsEnabled(false), for example a paid user. */
|
|
202
|
+
| 'ads_disabled'
|
|
203
|
+
/** The stored frequency state is still loading (see `ready`). */
|
|
204
|
+
| 'not_ready' | 'invalid_key' | 'unknown_key' | 'sdk_unsupported' | 'app_disabled' | 'interstitial_disabled';
|
|
205
|
+
export interface NextAdStatus {
|
|
206
|
+
/** Same as canShow(). */
|
|
207
|
+
allowed: boolean;
|
|
208
|
+
/** Set when allowed is false. */
|
|
209
|
+
reason?: NextAdReason;
|
|
210
|
+
/** Epoch ms when the gap ends. Only with reason 'frequency_capped'. */
|
|
211
|
+
retryAt?: number;
|
|
212
|
+
/** Ads shown in the current session. */
|
|
213
|
+
shownThisSession: number;
|
|
214
|
+
/** The effective per-session limit (Infinity for none). */
|
|
215
|
+
maxPerSession: number;
|
|
216
|
+
/** The effective gap between ads, in seconds. */
|
|
217
|
+
minGapSeconds: number;
|
|
218
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { type StyleProp, type TextStyle, type ViewStyle } from 'react-native';
|
|
3
|
-
import type { EthiclyAd, Tracker } from '../core/types';
|
|
3
|
+
import type { AudioPolicy, EthiclyAd, Tracker } from '../core/types';
|
|
4
4
|
/** Safe-area insets in points, as react-native-safe-area-context reports them. */
|
|
5
5
|
export interface EthiclyInsets {
|
|
6
6
|
top: number;
|
|
@@ -35,5 +35,17 @@ export interface EthiclyInterstitialProps {
|
|
|
35
35
|
* only move them inward.
|
|
36
36
|
*/
|
|
37
37
|
insets?: EthiclyInsets;
|
|
38
|
+
/**
|
|
39
|
+
* Sound for this screen, over `ad.audio` (createEthicly's `audio` option,
|
|
40
|
+
* else the server's interstitial.audio, else 'on'). 'on' plays with sound,
|
|
41
|
+
* 'optional' starts muted with a sound toggle, 'none' plays muted with no toggle.
|
|
42
|
+
* With expo-video on iPhone, sound plays even with the silent switch on and
|
|
43
|
+
* pauses the user's own audio.
|
|
44
|
+
*/
|
|
45
|
+
audio?: AudioPolicy;
|
|
38
46
|
}
|
|
47
|
+
/** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
|
|
48
|
+
export declare function effectiveAudio(prop: AudioPolicy | undefined, ad: {
|
|
49
|
+
audio?: AudioPolicy;
|
|
50
|
+
}): AudioPolicy;
|
|
39
51
|
export declare function EthiclyInterstitial(props: EthiclyInterstitialProps): React.ReactElement;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Ethicly } from '../core/client';
|
|
2
|
-
import type { EthiclyAd, NoFillReason, Tracker } from '../core/types';
|
|
2
|
+
import type { EthiclyAd, NextAdStatus, NoFillReason, Tracker } from '../core/types';
|
|
3
3
|
export interface UseEthiclyInterstitialOptions {
|
|
4
4
|
/** Preload on mount and after each dismiss. Default true. */
|
|
5
5
|
preload?: boolean;
|
|
@@ -8,7 +8,7 @@ export interface EthiclyInterstitialState {
|
|
|
8
8
|
/** The ad to render, set by a successful show(). */
|
|
9
9
|
ad: EthiclyAd | null;
|
|
10
10
|
tracker: Tracker | null;
|
|
11
|
-
/** Why the last show() found no ad
|
|
11
|
+
/** Why the last show() found no ad: show your house ad, except for 'ads_disabled' (a paid user). */
|
|
12
12
|
reason: NoFillReason | null;
|
|
13
13
|
loading: boolean;
|
|
14
14
|
/** Load the ad to show now. Resolves true when `ad` is set, false on no fill. */
|
|
@@ -16,5 +16,7 @@ export interface EthiclyInterstitialState {
|
|
|
16
16
|
/** Close the current ad: flushes queued events and preloads the next one. */
|
|
17
17
|
dismiss(): void;
|
|
18
18
|
canShow(): boolean;
|
|
19
|
+
/** Whether an ad may show now and, when not, why and until when. Same as ethicly.nextAdStatus(). */
|
|
20
|
+
nextAdStatus(): NextAdStatus;
|
|
19
21
|
}
|
|
20
22
|
export declare function useEthiclyInterstitial(ethicly: Ethicly, options?: UseEthiclyInterstitialOptions): EthiclyInterstitialState;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
|
|
2
|
-
export declare const SDK_VERSION = "0.
|
|
2
|
+
export declare const SDK_VERSION = "0.3.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ethicly/react-native",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Ethicly fullscreen video ads for React Native and Expo. Headless core plus an optional ready-made screen.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://ethicly.ch",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
49
49
|
"test": "jest",
|
|
50
50
|
"test:live": "npm run build && node scripts/live-test.mjs",
|
|
51
|
-
"
|
|
51
|
+
"prepack": "npm run build",
|
|
52
52
|
"build": "node scripts/clean.mjs && tsc -p tsconfig.build.json --module commonjs --outDir lib/commonjs && tsc -p tsconfig.build.json --module es2020 --outDir lib/module && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --outDir lib/typescript"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
package/src/core/adapters.ts
CHANGED
|
@@ -130,7 +130,8 @@ function isLegacyFs(fs: unknown): fs is ExpoFileSystemLike {
|
|
|
130
130
|
* A file cache over either expo-file-system API: the object API of SDK 54+
|
|
131
131
|
* (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
|
|
132
132
|
* `downloadAsync`, ...). Anything else gets the streaming cache, which writes
|
|
133
|
-
* nothing to disk, and one warning through `logger` (default `console`
|
|
133
|
+
* nothing to disk, and one warning through `logger` (default `console` in
|
|
134
|
+
* development, nothing in a release build).
|
|
134
135
|
*/
|
|
135
136
|
export function createExpoFileCache(
|
|
136
137
|
fs: ExpoFileSystemLike | ExpoFileSystemModernLike,
|
|
@@ -140,7 +141,8 @@ export function createExpoFileCache(
|
|
|
140
141
|
const sub = safeCacheSubdirectory(subdirectory);
|
|
141
142
|
if (isModernFs(fs)) return modernFileCache(fs, sub);
|
|
142
143
|
if (isLegacyFs(fs)) return legacyFileCache(fs, sub);
|
|
143
|
-
|
|
144
|
+
// console only in development: a release build stays quiet unless the app passes a logger.
|
|
145
|
+
safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn(
|
|
144
146
|
'createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream',
|
|
145
147
|
);
|
|
146
148
|
return createMemoryFileCache();
|
|
@@ -154,6 +156,8 @@ function consoleLogger(): Logger {
|
|
|
154
156
|
function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter {
|
|
155
157
|
const dir = `${fs.cacheDirectory}${sub}`;
|
|
156
158
|
let made: Promise<void> | null = null;
|
|
159
|
+
/** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
|
|
160
|
+
const inflight = new Set<() => void>();
|
|
157
161
|
const sizeOf = async (uri: string): Promise<number> => {
|
|
158
162
|
const info = await fs.getInfoAsync(uri, { size: true });
|
|
159
163
|
return info.exists && typeof info.size === 'number' ? info.size : 0;
|
|
@@ -168,14 +172,20 @@ function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter
|
|
|
168
172
|
let tooBig = false;
|
|
169
173
|
if (max !== undefined && fs.createDownloadResumable) {
|
|
170
174
|
// Stop as soon as the server announces, or we have written, more than the budget.
|
|
175
|
+
const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
|
|
171
176
|
const dl = fs.createDownloadResumable(url, target, {}, (p) => {
|
|
172
177
|
if (tooBig) return;
|
|
173
178
|
if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
|
|
174
179
|
tooBig = true;
|
|
175
|
-
|
|
180
|
+
stop();
|
|
176
181
|
}
|
|
177
182
|
});
|
|
178
|
-
|
|
183
|
+
inflight.add(stop);
|
|
184
|
+
try {
|
|
185
|
+
res = await dl.downloadAsync().catch(() => undefined);
|
|
186
|
+
} finally {
|
|
187
|
+
inflight.delete(stop);
|
|
188
|
+
}
|
|
179
189
|
} else {
|
|
180
190
|
res = await fs.downloadAsync(url, target);
|
|
181
191
|
}
|
|
@@ -189,6 +199,9 @@ function legacyFileCache(fs: ExpoFileSystemLike, sub: string): FileCacheAdapter
|
|
|
189
199
|
async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
|
|
190
200
|
size: sizeOf,
|
|
191
201
|
uriFor: (fileName) => dir + fileName,
|
|
202
|
+
cancel() {
|
|
203
|
+
inflight.forEach((stop) => { try { stop(); } catch { /* already settled */ } });
|
|
204
|
+
},
|
|
192
205
|
async list() {
|
|
193
206
|
if (!fs.readDirectoryAsync) return [];
|
|
194
207
|
const names = await fs.readDirectoryAsync(dir).catch(() => [] as string[]);
|
|
@@ -222,6 +235,7 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
222
235
|
return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
|
|
223
236
|
};
|
|
224
237
|
let made = false;
|
|
238
|
+
const inflight = new Set<{ cancel(): void }>();
|
|
225
239
|
return {
|
|
226
240
|
async download(url, fileName, opts) {
|
|
227
241
|
if (!made) {
|
|
@@ -232,6 +246,7 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
232
246
|
const target = dir() + fileName;
|
|
233
247
|
const max = opts?.maxBytes;
|
|
234
248
|
let tooBig = false;
|
|
249
|
+
let cancelled = false;
|
|
235
250
|
try {
|
|
236
251
|
remove(target);
|
|
237
252
|
const createTask = fs.File.createDownloadTask;
|
|
@@ -244,7 +259,13 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
244
259
|
try { task.cancel(); } catch { /* already settled */ }
|
|
245
260
|
},
|
|
246
261
|
});
|
|
247
|
-
|
|
262
|
+
const handle = { cancel: () => { cancelled = true; task.cancel(); } };
|
|
263
|
+
inflight.add(handle);
|
|
264
|
+
try {
|
|
265
|
+
await task.downloadAsync();
|
|
266
|
+
} finally {
|
|
267
|
+
inflight.delete(handle);
|
|
268
|
+
}
|
|
248
269
|
} else {
|
|
249
270
|
await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
|
|
250
271
|
}
|
|
@@ -255,6 +276,10 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
255
276
|
// Without a progress callback the whole file lands first: check it now
|
|
256
277
|
// and delete it if it is over the budget.
|
|
257
278
|
const bytes = await sizeOf(target);
|
|
279
|
+
if (cancelled) {
|
|
280
|
+
try { remove(target); } catch { /* ignore */ }
|
|
281
|
+
throw new Error('download cancelled');
|
|
282
|
+
}
|
|
258
283
|
if (tooBig || (max !== undefined && bytes > max)) {
|
|
259
284
|
try { remove(target); } catch { /* ignore */ }
|
|
260
285
|
throw new Error('creative over the cache budget');
|
|
@@ -265,6 +290,9 @@ function modernFileCache(fs: ExpoFileSystemModernLike, sub: string): FileCacheAd
|
|
|
265
290
|
async delete(uri) { remove(uri); },
|
|
266
291
|
size: sizeOf,
|
|
267
292
|
uriFor: (fileName) => dir() + fileName,
|
|
293
|
+
cancel() {
|
|
294
|
+
inflight.forEach((t) => { try { t.cancel(); } catch { /* already settled */ } });
|
|
295
|
+
},
|
|
268
296
|
async list() {
|
|
269
297
|
const d = new fs.Directory(dir());
|
|
270
298
|
if (!d.exists) return [];
|
package/src/core/cache.ts
CHANGED
|
@@ -24,6 +24,14 @@ export interface CachedMedia {
|
|
|
24
24
|
uris: Record<string, string>;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* The longest one creative file may take to download. A slower (trickling)
|
|
29
|
+
* download is cancelled when the adapter supports it, else abandoned: the
|
|
30
|
+
* creative streams and later downloads are not held up behind it. A file it
|
|
31
|
+
* still writes afterwards is not indexed, so the next launch's sweep deletes it.
|
|
32
|
+
*/
|
|
33
|
+
export const DOWNLOAD_TIMEOUT_MS = 60000;
|
|
34
|
+
|
|
27
35
|
/** Content-Length of a URL, or null when unknown. */
|
|
28
36
|
export type SizeProbe = (url: string) => Promise<number | null>;
|
|
29
37
|
|
|
@@ -48,6 +56,8 @@ export class CreativeCache {
|
|
|
48
56
|
private pending: string[] = [];
|
|
49
57
|
private loaded: Promise<void> | null = null;
|
|
50
58
|
private chain: Promise<unknown> = Promise.resolve();
|
|
59
|
+
/** Bumped by cancel(): a download started before it no longer counts. */
|
|
60
|
+
private generation = 0;
|
|
51
61
|
|
|
52
62
|
constructor(
|
|
53
63
|
private files: FileCacheAdapter,
|
|
@@ -56,8 +66,37 @@ export class CreativeCache {
|
|
|
56
66
|
private now: () => number,
|
|
57
67
|
private log: Required<Logger>,
|
|
58
68
|
private probeSize: SizeProbe = async () => null,
|
|
69
|
+
private downloadTimeoutMs: number = DOWNLOAD_TIMEOUT_MS,
|
|
59
70
|
) {}
|
|
60
71
|
|
|
72
|
+
/**
|
|
73
|
+
* Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
|
|
74
|
+
* and skip the files not started yet. For setAdsEnabled(false).
|
|
75
|
+
*/
|
|
76
|
+
cancel(): void {
|
|
77
|
+
this.generation += 1;
|
|
78
|
+
try { this.files.cancel?.(); } catch (e) { this.log.warn('could not cancel the creative download', e); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The adapter's download, given up on after downloadTimeoutMs. */
|
|
82
|
+
private async downloadWithin(url: string, name: string, maxBytes: number): Promise<{ uri: string; bytes?: number }> {
|
|
83
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
84
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
85
|
+
timer = setTimeout(() => {
|
|
86
|
+
try { this.files.cancel?.(); } catch { /* best effort */ }
|
|
87
|
+
reject(new Error(`download took longer than ${this.downloadTimeoutMs} ms`));
|
|
88
|
+
}, this.downloadTimeoutMs);
|
|
89
|
+
});
|
|
90
|
+
const dl = this.files.download(url, name, { maxBytes });
|
|
91
|
+
// A late rejection of an abandoned download must not go unhandled.
|
|
92
|
+
dl.catch(() => undefined);
|
|
93
|
+
try {
|
|
94
|
+
return await Promise.race([dl, timeout]);
|
|
95
|
+
} finally {
|
|
96
|
+
if (timer) clearTimeout(timer);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
61
100
|
private load(): Promise<void> {
|
|
62
101
|
if (!this.loaded) this.loaded = this.loadNow();
|
|
63
102
|
return this.loaded;
|
|
@@ -127,7 +166,8 @@ export class CreativeCache {
|
|
|
127
166
|
* Make sure the files of one creative are on disk. Never throws: a file that
|
|
128
167
|
* cannot be cached is simply left out of the result and streamed instead.
|
|
129
168
|
* `allowed()` is checked before every download so setAdsEnabled(false)
|
|
130
|
-
* stops a download that has not started yet
|
|
169
|
+
* stops a download that has not started yet; cancel() also stops the one in
|
|
170
|
+
* flight when the adapter supports it.
|
|
131
171
|
*/
|
|
132
172
|
ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
|
|
133
173
|
const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
|
|
@@ -149,10 +189,12 @@ export class CreativeCache {
|
|
|
149
189
|
this.entries.push(entry);
|
|
150
190
|
}
|
|
151
191
|
entry.lastUsed = this.now();
|
|
192
|
+
const generation = this.generation;
|
|
193
|
+
const go = () => allowed() && generation === this.generation;
|
|
152
194
|
|
|
153
195
|
for (const url of urls) {
|
|
154
196
|
if (entry.files.some((f) => f.url === url)) continue;
|
|
155
|
-
if (!
|
|
197
|
+
if (!go()) break;
|
|
156
198
|
// One creative may use the whole budget (older ones are evicted), never more.
|
|
157
199
|
const budget = limits.maxBytes - this.size(entry);
|
|
158
200
|
const known = await this.probeSize(url).catch(() => null);
|
|
@@ -166,11 +208,14 @@ export class CreativeCache {
|
|
|
166
208
|
this.pending = [name];
|
|
167
209
|
await this.persist();
|
|
168
210
|
try {
|
|
169
|
-
const res = await this.
|
|
211
|
+
const res = await this.downloadWithin(url, name, budget);
|
|
170
212
|
const bytes = typeof res.bytes === 'number' && res.bytes > 0 ? res.bytes : await this.files.size(res.uri).catch(() => 0);
|
|
171
213
|
if (bytes > budget) {
|
|
172
214
|
await this.files.delete(res.uri).catch(() => undefined);
|
|
173
215
|
this.log.info(`${url} is over the cache budget: it will stream`);
|
|
216
|
+
} else if (!go()) {
|
|
217
|
+
// Cancelled while it was landing: keep nothing for a paid user.
|
|
218
|
+
await this.files.delete(res.uri).catch(() => undefined);
|
|
174
219
|
} else {
|
|
175
220
|
entry.files.push({ url, uri: res.uri, bytes });
|
|
176
221
|
}
|
package/src/core/click.ts
CHANGED
|
@@ -14,3 +14,13 @@ export function appendClickToken(destinationUrl: string, clickToken: string | nu
|
|
|
14
14
|
|
|
15
15
|
/** The /click budget: the website snippet aborts at exactly 500 ms. */
|
|
16
16
|
export const CLICK_TIMEOUT_MS = 500;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True for an absolute http: or https: URL with a host. Anything else (tel:,
|
|
20
|
+
* intent:, javascript:, a custom app scheme, a relative path) is never opened.
|
|
21
|
+
*/
|
|
22
|
+
export function isWebUrl(url: unknown): url is string {
|
|
23
|
+
return typeof url === 'string'
|
|
24
|
+
&& /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
|
|
25
|
+
&& !/[\s\u0000-\u001f\u007f]/.test(url);
|
|
26
|
+
}
|