@rediads/react-native-ads 0.0.0-stage → 0.1.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.
@@ -0,0 +1,195 @@
1
+ package com.rediads.reactnative
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import com.rediads.core.RediadsAdEvent
6
+ import com.rediads.core.RediadsAdEventType
7
+ import com.rediads.core.RediadsAdFormat
8
+ import com.rediads.core.RediadsAdListener
9
+ import com.rediads.core.RediadsAds
10
+ import com.rediads.core.RediadsReward
11
+ import com.rediads.display.RediadsInterstitial
12
+ import com.rediads.display.RediadsRewarded
13
+ import expo.modules.kotlin.Promise
14
+ import expo.modules.kotlin.functions.Queues
15
+ import expo.modules.kotlin.modules.Module
16
+ import expo.modules.kotlin.modules.ModuleDefinition
17
+ import expo.modules.kotlin.records.Field
18
+ import expo.modules.kotlin.records.Record
19
+
20
+ /** Options of `start`, from `RediadsAds.start` in src/RediadsAds.ts. */
21
+ class StartOptions : Record {
22
+ @Field val accountId: String = ""
23
+ @Field val serverUrl: String = RediadsAds.defaultServerURL
24
+ @Field val testMode: Boolean = false
25
+ @Field val debugLogging: Boolean = false
26
+ @Field val childDirected: Boolean = false
27
+ /** iOS only. */
28
+ @Field val appStoreId: String? = null
29
+ }
30
+
31
+ /**
32
+ * Starts the Rediads SDK, hosts its banners as React Native views and runs interstitial and rewarded
33
+ * ads by the ID JavaScript gives them (src/RediadsFullScreenAd.ts). Everything that touches the SDK
34
+ * runs on the main thread, where the SDK also calls back.
35
+ */
36
+ class RediadsAdsModule : Module() {
37
+ /** Interstitials and rewarded ads by ID. Main thread only. */
38
+ private val ads = HashMap<Int, Any>()
39
+
40
+ override fun definition() = ModuleDefinition {
41
+ Name("RediadsAds")
42
+
43
+ Constant("sdkVersion") {
44
+ RediadsAds.sdkVersion
45
+ }
46
+
47
+ Events("onFullScreenAdEvent")
48
+
49
+ AsyncFunction("start") { options: StartOptions, promise: Promise ->
50
+ val context = appContext.reactContext
51
+ if (context == null) {
52
+ promise.resolve("There is no Android context yet.")
53
+ return@AsyncFunction
54
+ }
55
+ RediadsAds.testMode = options.testMode
56
+ RediadsAds.debugLogging = options.debugLogging
57
+ RediadsAds.childDirected = options.childDirected
58
+ RediadsAds.start(context, options.accountId, options.serverUrl) { error ->
59
+ promise.resolve(error?.message)
60
+ }
61
+ }.runOnQueue(Queues.MAIN)
62
+
63
+ AsyncFunction("setChildDirected") { value: Boolean ->
64
+ RediadsAds.childDirected = value
65
+ }.runOnQueue(Queues.MAIN)
66
+
67
+ AsyncFunction("loadInterstitial") { adId: Int, placement: String, format: String, promise: Promise ->
68
+ // Created with the Activity that will show it, as the SDK asks.
69
+ val activity = appContext.currentActivity
70
+ if (activity == null) {
71
+ promise.resolve("There is no Activity to show the ad in.")
72
+ return@AsyncFunction
73
+ }
74
+ discard(adId)
75
+ val ad = RediadsInterstitial(activity, placement, format(format))
76
+ ad.listener = forward(adId)
77
+ ads[adId] = ad
78
+ ad.load { error -> promise.resolve(error?.message) }
79
+ }.runOnQueue(Queues.MAIN)
80
+
81
+ AsyncFunction("loadRewarded") {
82
+ adId: Int, placement: String, rewardType: String, rewardAmount: Int, format: String,
83
+ displaySeconds: Int, promise: Promise ->
84
+ val activity = appContext.currentActivity
85
+ if (activity == null) {
86
+ promise.resolve("There is no Activity to show the ad in.")
87
+ return@AsyncFunction
88
+ }
89
+ discard(adId)
90
+ val ad = RediadsRewarded(
91
+ activity,
92
+ placement,
93
+ RediadsReward(rewardType, rewardAmount),
94
+ format(format),
95
+ if (displaySeconds > 0) displaySeconds else RediadsRewarded.defaultDisplaySeconds,
96
+ )
97
+ ad.listener = forward(adId)
98
+ ads[adId] = ad
99
+ ad.load { error -> promise.resolve(error?.message) }
100
+ }.runOnQueue(Queues.MAIN)
101
+
102
+ AsyncFunction("isReady") { adId: Int ->
103
+ when (val ad = ads[adId]) {
104
+ is RediadsInterstitial -> ad.isReady
105
+ is RediadsRewarded -> ad.isReady
106
+ else -> false
107
+ }
108
+ }.runOnQueue(Queues.MAIN)
109
+
110
+ AsyncFunction("show") { adId: Int ->
111
+ when (val ad = ads[adId]) {
112
+ is RediadsInterstitial -> ad.show()
113
+ is RediadsRewarded -> ad.show()
114
+ else -> Unit
115
+ }
116
+ }.runOnQueue(Queues.MAIN)
117
+
118
+ AsyncFunction("destroy") { adId: Int ->
119
+ discard(adId)
120
+ }.runOnQueue(Queues.MAIN)
121
+
122
+ OnDestroy {
123
+ // The JavaScript side went away (a reload): free every full-screen ad.
124
+ Handler(Looper.getMainLooper()).post {
125
+ ads.keys.toList().forEach { discard(it) }
126
+ }
127
+ }
128
+
129
+ View(RediadsBannerSlot::class) {
130
+ Events("onAdEvent")
131
+
132
+ Prop("placement") { view: RediadsBannerSlot, placement: String ->
133
+ view.placement = placement
134
+ }
135
+
136
+ Prop("size") { view: RediadsBannerSlot, size: String ->
137
+ view.size = size
138
+ }
139
+
140
+ Prop("format") { view: RediadsBannerSlot, format: String ->
141
+ view.format = format
142
+ }
143
+
144
+ OnViewDidUpdateProps { view: RediadsBannerSlot ->
145
+ view.loadIfReady()
146
+ }
147
+
148
+ OnViewDestroys { view: RediadsBannerSlot ->
149
+ view.destroy()
150
+ }
151
+ }
152
+ }
153
+
154
+ private fun discard(adId: Int) {
155
+ when (val ad = ads.remove(adId)) {
156
+ is RediadsInterstitial -> ad.destroy()
157
+ is RediadsRewarded -> ad.destroy()
158
+ }
159
+ }
160
+
161
+ /** Sends an ad's events to JavaScript under its ID. */
162
+ private fun forward(adId: Int) = RediadsAdListener { event: RediadsAdEvent ->
163
+ sendEvent(
164
+ "onFullScreenAdEvent",
165
+ mapOf(
166
+ "adId" to adId,
167
+ "type" to eventName(event.type),
168
+ "placement" to event.placement,
169
+ "error" to event.error?.message,
170
+ "rewardType" to event.reward?.type,
171
+ "rewardAmount" to event.reward?.amount,
172
+ ),
173
+ )
174
+ }
175
+
176
+ companion object {
177
+ /** The JavaScript format names: display, video, displayAndVideo. */
178
+ fun format(name: String) = when (name) {
179
+ "video" -> RediadsAdFormat.VIDEO
180
+ "displayAndVideo" -> RediadsAdFormat.DISPLAY_AND_VIDEO
181
+ else -> RediadsAdFormat.DISPLAY
182
+ }
183
+
184
+ fun eventName(type: RediadsAdEventType) = when (type) {
185
+ RediadsAdEventType.LOADED -> "loaded"
186
+ RediadsAdEventType.DISPLAYED -> "displayed"
187
+ RediadsAdEventType.FAILED -> "failed"
188
+ RediadsAdEventType.CLICKED -> "clicked"
189
+ RediadsAdEventType.PRESENTED -> "presented"
190
+ RediadsAdEventType.DISMISSED -> "dismissed"
191
+ RediadsAdEventType.LEFT_APPLICATION -> "leftApplication"
192
+ RediadsAdEventType.REWARDED -> "rewarded"
193
+ }
194
+ }
195
+ }
@@ -0,0 +1,58 @@
1
+ package com.rediads.reactnative
2
+
3
+ import android.content.Context
4
+ import android.view.Gravity
5
+ import android.widget.LinearLayout
6
+ import com.rediads.core.RediadsAdListener
7
+ import com.rediads.display.RediadsBannerView
8
+ import expo.modules.kotlin.AppContext
9
+ import expo.modules.kotlin.viewevent.EventDispatcher
10
+ import expo.modules.kotlin.views.ExpoView
11
+
12
+ /**
13
+ * One banner slot. The banner is made once React has set the props and is kept for the life of the
14
+ * view (JavaScript gives the view a new key when they change); the SDK refreshes it while on screen.
15
+ */
16
+ class RediadsBannerSlot(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
17
+ // React Native doesn't lay out views added natively; let ExpoView measure the banner.
18
+ override val shouldUseAndroidLayout = true
19
+
20
+ private val onAdEvent by EventDispatcher()
21
+ var placement = ""
22
+ var size = "320x50"
23
+ var format = "display"
24
+ private var banner: RediadsBannerView? = null
25
+
26
+ init {
27
+ gravity = Gravity.CENTER
28
+ }
29
+
30
+ fun loadIfReady() {
31
+ if (banner != null || placement.isEmpty()) return
32
+ val adSize =
33
+ if (size == "300x250") RediadsBannerView.mediumRectangle300x250 else RediadsBannerView.banner320x50
34
+ // The Activity, so a click opens the in-app browser over the app.
35
+ val host = appContext.currentActivity ?: context
36
+ val banner = RediadsBannerView(host, placement, adSize, RediadsAdsModule.format(format))
37
+ banner.listener = RediadsAdListener { event ->
38
+ val payload = mutableMapOf<String, Any>(
39
+ "type" to RediadsAdsModule.eventName(event.type),
40
+ "placement" to event.placement,
41
+ )
42
+ event.error?.message?.let { payload["error"] = it }
43
+ onAdEvent(payload)
44
+ }
45
+ val density = resources.displayMetrics.density
46
+ addView(
47
+ banner,
48
+ LinearLayout.LayoutParams((adSize.width * density).toInt(), (adSize.height * density).toInt()),
49
+ )
50
+ this.banner = banner
51
+ banner.load()
52
+ }
53
+
54
+ fun destroy() {
55
+ banner?.destroy()
56
+ banner = null
57
+ }
58
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,2 @@
1
+ // Expo looks for the config plugin here when an app lists '@rediads/react-native-ads' in `plugins`.
2
+ module.exports = require('./plugin/withRediadsAds');
@@ -0,0 +1,60 @@
1
+ export interface RediadsStartOptions {
2
+ /** Your Rediads account ID. The app's bundle ID (iOS) and package name (Android) must be registered for it. */
3
+ accountId: string;
4
+ /** Another auction endpoint, for testing only. Defaults to `RediadsAds.DEFAULT_SERVER_URL`. */
5
+ serverUrl?: string;
6
+ /** Asks the server for test bids. Never ship it on. */
7
+ testMode?: boolean;
8
+ /** Detailed native SDK logs (Xcode console, Logcat). */
9
+ debugLogging?: boolean;
10
+ /**
11
+ * For apps directed at children under 13 (US COPPA): requests carry `regs.coppa = 1` and the server
12
+ * strips device IDs before bidders see them. Can be changed later with `setChildDirected`.
13
+ */
14
+ childDirected?: boolean;
15
+ /**
16
+ * iOS only: your app's App Store ID, the number in its App Store link (`123456789` for
17
+ * `apps.apple.com/app/id123456789`). Ad networks need it for app-install ads. Leave it out until the
18
+ * app is on the App Store.
19
+ */
20
+ appStoreId?: string;
21
+ }
22
+ /**
23
+ * Starts the Rediads SDK. Call `RediadsAds.start` once, early (for example in your root component),
24
+ * before loading any ad.
25
+ */
26
+ export declare const RediadsAds: {
27
+ /** The Rediads auction endpoint, used when `start` gets no `serverUrl`. */
28
+ DEFAULT_SERVER_URL: string;
29
+ /** This package's version; the native SDKs report theirs in `sdkVersion`. */
30
+ PACKAGE_VERSION: string;
31
+ /**
32
+ * False in Expo Go, on web and in builds made before this package was added. Then `start` and every
33
+ * load resolve with an error and banners render nothing, so the app's no-ad path runs.
34
+ */
35
+ isAvailable: boolean;
36
+ /** The native Rediads SDK's version, or null when the module isn't in this build. */
37
+ readonly sdkVersion: string | null;
38
+ /** True once `start` has finished, even with an error (ads may still load later). */
39
+ readonly isStarted: boolean;
40
+ readonly childDirected: boolean;
41
+ /**
42
+ * Configures the SDK for the Rediads server. Resolves with null, or the reason the server check
43
+ * failed (bad account, no network); after a network failure ads still load once the network is back.
44
+ * Calling it again returns the first call's result.
45
+ */
46
+ start(options: RediadsStartOptions): Promise<string | null>;
47
+ /**
48
+ * Resolves once `start` has finished, or at once when `start` hasn't been called. Ad loads made
49
+ * through other packages (such as `@rediads/react-native-ads-admob`) wait for it, so a load right
50
+ * after `start` doesn't find the SDK not started yet.
51
+ */
52
+ whenStarted(): Promise<void>;
53
+ /**
54
+ * Marks ad requests as directed to children under 13 (US COPPA). Applies from the next ad request;
55
+ * can be called before or after `start`.
56
+ */
57
+ setChildDirected(value: boolean): void;
58
+ };
59
+ /** Resolves once `start` has finished; null when `start` hasn't been called. */
60
+ export declare function pendingStart(): Promise<string | null> | null;
@@ -0,0 +1,80 @@
1
+ import { NOT_AVAILABLE, native } from './native';
2
+ const DEFAULT_SERVER_URL = 'https://bidding.rediads.com/openrtb2/auction';
3
+ let startPromise = null;
4
+ let started = false;
5
+ let childDirected = false;
6
+ /**
7
+ * Starts the Rediads SDK. Call `RediadsAds.start` once, early (for example in your root component),
8
+ * before loading any ad.
9
+ */
10
+ export const RediadsAds = {
11
+ /** The Rediads auction endpoint, used when `start` gets no `serverUrl`. */
12
+ DEFAULT_SERVER_URL,
13
+ /** This package's version; the native SDKs report theirs in `sdkVersion`. */
14
+ PACKAGE_VERSION: '0.1.0',
15
+ /**
16
+ * False in Expo Go, on web and in builds made before this package was added. Then `start` and every
17
+ * load resolve with an error and banners render nothing, so the app's no-ad path runs.
18
+ */
19
+ isAvailable: native != null,
20
+ /** The native Rediads SDK's version, or null when the module isn't in this build. */
21
+ get sdkVersion() {
22
+ return native?.sdkVersion ?? null;
23
+ },
24
+ /** True once `start` has finished, even with an error (ads may still load later). */
25
+ get isStarted() {
26
+ return started;
27
+ },
28
+ get childDirected() {
29
+ return childDirected;
30
+ },
31
+ /**
32
+ * Configures the SDK for the Rediads server. Resolves with null, or the reason the server check
33
+ * failed (bad account, no network); after a network failure ads still load once the network is back.
34
+ * Calling it again returns the first call's result.
35
+ */
36
+ start(options) {
37
+ if (startPromise)
38
+ return startPromise;
39
+ if (options.childDirected !== undefined)
40
+ childDirected = options.childDirected;
41
+ const nativeModule = native;
42
+ startPromise = !nativeModule
43
+ ? Promise.resolve(NOT_AVAILABLE)
44
+ : nativeModule
45
+ .start({
46
+ accountId: options.accountId,
47
+ serverUrl: options.serverUrl || DEFAULT_SERVER_URL,
48
+ testMode: options.testMode ?? false,
49
+ debugLogging: options.debugLogging ?? false,
50
+ childDirected,
51
+ appStoreId: options.appStoreId ?? null,
52
+ })
53
+ .catch((error) => String(error));
54
+ startPromise.then(() => {
55
+ started = true;
56
+ });
57
+ return startPromise;
58
+ },
59
+ /**
60
+ * Resolves once `start` has finished, or at once when `start` hasn't been called. Ad loads made
61
+ * through other packages (such as `@rediads/react-native-ads-admob`) wait for it, so a load right
62
+ * after `start` doesn't find the SDK not started yet.
63
+ */
64
+ whenStarted() {
65
+ return (pendingStart() ?? Promise.resolve()).then(() => undefined);
66
+ },
67
+ /**
68
+ * Marks ad requests as directed to children under 13 (US COPPA). Applies from the next ad request;
69
+ * can be called before or after `start`.
70
+ */
71
+ setChildDirected(value) {
72
+ childDirected = value;
73
+ if (started)
74
+ native?.setChildDirected(value).catch(() => { });
75
+ },
76
+ };
77
+ /** Resolves once `start` has finished; null when `start` hasn't been called. */
78
+ export function pendingStart() {
79
+ return started ? null : startPromise;
80
+ }
@@ -0,0 +1,20 @@
1
+ import { type ViewProps } from 'react-native';
2
+ import type { RediadsAdEvent, RediadsAdFormat, RediadsBannerSize } from './types';
3
+ export interface RediadsBannerProps extends ViewProps {
4
+ /** The slot name, sent as gpid: the slot in Rediads analytics. For example "home_banner". */
5
+ placement: string;
6
+ /** Defaults to 320x50. The component takes this size unless `style` says otherwise. */
7
+ size?: RediadsBannerSize;
8
+ /** Defaults to display. Video needs 300x250. */
9
+ format?: RediadsAdFormat;
10
+ /** Every event of this banner. */
11
+ onAdEvent?: (event: RediadsAdEvent) => void;
12
+ }
13
+ /**
14
+ * A banner ad in your layout. It loads when it mounts (after `RediadsAds.start` has finished, if a start
15
+ * is under way) and refreshes itself every 60 s while on screen. Unmount it to remove it. Changing
16
+ * `placement`, `size` or `format` replaces the banner with a new one.
17
+ *
18
+ * Renders nothing where the native module isn't built in (Expo Go, web).
19
+ */
20
+ export declare function RediadsBanner({ placement, size, format, onAdEvent, style, ...rest }: RediadsBannerProps): import("react").JSX.Element | null;
@@ -0,0 +1,38 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { requireNativeView } from 'expo';
3
+ import { useEffect, useState } from 'react';
4
+ import { View } from 'react-native';
5
+ import { pendingStart } from './RediadsAds';
6
+ import { native } from './native';
7
+ const NativeBanner = native
8
+ ? requireNativeView('RediadsAds')
9
+ : null;
10
+ const SIZES = {
11
+ '320x50': { width: 320, height: 50 },
12
+ '300x250': { width: 300, height: 250 },
13
+ };
14
+ /**
15
+ * A banner ad in your layout. It loads when it mounts (after `RediadsAds.start` has finished, if a start
16
+ * is under way) and refreshes itself every 60 s while on screen. Unmount it to remove it. Changing
17
+ * `placement`, `size` or `format` replaces the banner with a new one.
18
+ *
19
+ * Renders nothing where the native module isn't built in (Expo Go, web).
20
+ */
21
+ export function RediadsBanner({ placement, size = '320x50', format = 'display', onAdEvent, style, ...rest }) {
22
+ const [canLoad, setCanLoad] = useState(() => pendingStart() === null);
23
+ useEffect(() => {
24
+ if (canLoad)
25
+ return;
26
+ let mounted = true;
27
+ (pendingStart() ?? Promise.resolve(null)).then(() => mounted && setCanLoad(true));
28
+ return () => {
29
+ mounted = false;
30
+ };
31
+ }, [canLoad]);
32
+ if (!NativeBanner)
33
+ return null;
34
+ const sizeStyle = SIZES[size];
35
+ if (!canLoad)
36
+ return _jsx(View, { style: [sizeStyle, style], ...rest });
37
+ return (_jsx(NativeBanner, { placement: placement, size: size, format: format, onAdEvent: onAdEvent ? (event) => onAdEvent(event.nativeEvent) : undefined, style: [sizeStyle, style], ...rest }, `${placement}|${size}|${format}`));
38
+ }
@@ -0,0 +1,60 @@
1
+ import type { RediadsAdEvent, RediadsAdFormat, RediadsAdListener, RediadsReward, RediadsSubscription } from './types';
2
+ /** What interstitials and rewarded ads share. */
3
+ declare abstract class FullScreenAd {
4
+ /** The slot name, sent as gpid: the slot in Rediads analytics. */
5
+ readonly placement: string;
6
+ readonly format: RediadsAdFormat;
7
+ private readonly id;
8
+ private readonly listeners;
9
+ private loaded;
10
+ private destroyed;
11
+ protected constructor(placement: string, format: RediadsAdFormat);
12
+ /** Every event of this ad: loaded, presented, dismissed, clicked, rewarded, failed... */
13
+ addListener(listener: RediadsAdListener): RediadsSubscription;
14
+ /**
15
+ * Loads an ad. Resolves with null when it's ready to show, or the reason it isn't (no fill, timeout,
16
+ * not started). Loading again after a show gets the next ad; the same object can be reused.
17
+ */
18
+ load(): Promise<string | null>;
19
+ /** True once loaded and not shown yet. */
20
+ isReady(): Promise<boolean>;
21
+ /** Shows the ad full screen. If it isn't ready, a `failed` event says why. */
22
+ show(): Promise<void>;
23
+ /** Frees the native ad. The object can't be used again. */
24
+ destroy(): void;
25
+ /** @internal */
26
+ emit(event: RediadsAdEvent): void;
27
+ protected abstract loadNative(id: number): Promise<string | null>;
28
+ }
29
+ /**
30
+ * A full-screen ad shown at a natural break (level end, between screens). Load it ahead of time and
31
+ * show it when ready:
32
+ *
33
+ * ```ts
34
+ * const ad = new RediadsInterstitial('level_end');
35
+ * if ((await ad.load()) === null) await ad.show();
36
+ * ```
37
+ */
38
+ export declare class RediadsInterstitial extends FullScreenAd {
39
+ constructor(placement: string, options?: {
40
+ format?: RediadsAdFormat;
41
+ });
42
+ protected loadNative(id: number): Promise<string | null>;
43
+ }
44
+ export interface RediadsRewardedOptions {
45
+ /** Defaults to display. */
46
+ format?: RediadsAdFormat;
47
+ /** Seconds a display ad stays on screen before the reward; the SDK's default (and limits) when left out. */
48
+ displaySeconds?: number;
49
+ }
50
+ /**
51
+ * A full-screen ad the user chooses to watch for a reward you define. The SDK grants it with a
52
+ * `rewarded` event: a video when it completes, a display ad after `displaySeconds`.
53
+ */
54
+ export declare class RediadsRewarded extends FullScreenAd {
55
+ readonly reward: RediadsReward;
56
+ readonly displaySeconds: number;
57
+ constructor(placement: string, reward: RediadsReward, options?: RediadsRewardedOptions);
58
+ protected loadNative(id: number): Promise<string | null>;
59
+ }
60
+ export type { FullScreenAd };
@@ -0,0 +1,133 @@
1
+ import { NOT_AVAILABLE, native } from './native';
2
+ let nextId = 1;
3
+ /** Ads that have been loaded and not destroyed, by ID, so native events reach them. */
4
+ const live = new Map();
5
+ let nativeSubscription = null;
6
+ function listenToNative() {
7
+ if (nativeSubscription || !native)
8
+ return;
9
+ nativeSubscription = native.addListener('onFullScreenAdEvent', (event) => {
10
+ live.get(event.adId)?.emit(toAdEvent(event));
11
+ });
12
+ }
13
+ function toAdEvent(event) {
14
+ return {
15
+ type: event.type,
16
+ placement: event.placement,
17
+ ...(event.error ? { error: event.error } : {}),
18
+ ...(event.type === 'rewarded'
19
+ ? { reward: { type: event.rewardType ?? '', amount: event.rewardAmount ?? 0 } }
20
+ : {}),
21
+ };
22
+ }
23
+ /** What interstitials and rewarded ads share. */
24
+ class FullScreenAd {
25
+ /** The slot name, sent as gpid: the slot in Rediads analytics. */
26
+ placement;
27
+ format;
28
+ id = nextId++;
29
+ listeners = new Set();
30
+ loaded = false;
31
+ destroyed = false;
32
+ constructor(placement, format) {
33
+ this.placement = placement;
34
+ this.format = format;
35
+ }
36
+ /** Every event of this ad: loaded, presented, dismissed, clicked, rewarded, failed... */
37
+ addListener(listener) {
38
+ this.listeners.add(listener);
39
+ return { remove: () => this.listeners.delete(listener) };
40
+ }
41
+ /**
42
+ * Loads an ad. Resolves with null when it's ready to show, or the reason it isn't (no fill, timeout,
43
+ * not started). Loading again after a show gets the next ad; the same object can be reused.
44
+ */
45
+ async load() {
46
+ if (this.destroyed)
47
+ return 'This ad was destroyed.';
48
+ const nativeModule = native;
49
+ if (!nativeModule)
50
+ return NOT_AVAILABLE;
51
+ listenToNative();
52
+ live.set(this.id, this);
53
+ this.loaded = true;
54
+ try {
55
+ return await this.loadNative(this.id);
56
+ }
57
+ catch (error) {
58
+ return String(error);
59
+ }
60
+ }
61
+ /** True once loaded and not shown yet. */
62
+ async isReady() {
63
+ if (this.destroyed || !this.loaded || !native)
64
+ return false;
65
+ return native.isReady(this.id);
66
+ }
67
+ /** Shows the ad full screen. If it isn't ready, a `failed` event says why. */
68
+ async show() {
69
+ if (this.destroyed)
70
+ return;
71
+ if (!this.loaded || !native) {
72
+ this.emit({ type: 'failed', placement: this.placement, error: 'The ad was not loaded.' });
73
+ return;
74
+ }
75
+ await native.show(this.id);
76
+ }
77
+ /** Frees the native ad. The object can't be used again. */
78
+ destroy() {
79
+ if (this.destroyed)
80
+ return;
81
+ this.destroyed = true;
82
+ live.delete(this.id);
83
+ this.listeners.clear();
84
+ if (this.loaded)
85
+ native?.destroy(this.id).catch(() => { });
86
+ }
87
+ /** @internal */
88
+ emit(event) {
89
+ // A listener that throws must not stop the others, nor reach the native event callback: an uncaught
90
+ // error there closes a release build.
91
+ for (const listener of [...this.listeners]) {
92
+ try {
93
+ listener(event);
94
+ }
95
+ catch (error) {
96
+ console.error('[Rediads] An ad listener threw:', error);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * A full-screen ad shown at a natural break (level end, between screens). Load it ahead of time and
103
+ * show it when ready:
104
+ *
105
+ * ```ts
106
+ * const ad = new RediadsInterstitial('level_end');
107
+ * if ((await ad.load()) === null) await ad.show();
108
+ * ```
109
+ */
110
+ export class RediadsInterstitial extends FullScreenAd {
111
+ constructor(placement, options = {}) {
112
+ super(placement, options.format ?? 'display');
113
+ }
114
+ loadNative(id) {
115
+ return native.loadInterstitial(id, this.placement, this.format);
116
+ }
117
+ }
118
+ /**
119
+ * A full-screen ad the user chooses to watch for a reward you define. The SDK grants it with a
120
+ * `rewarded` event: a video when it completes, a display ad after `displaySeconds`.
121
+ */
122
+ export class RediadsRewarded extends FullScreenAd {
123
+ reward;
124
+ displaySeconds;
125
+ constructor(placement, reward, options = {}) {
126
+ super(placement, options.format ?? 'display');
127
+ this.reward = { type: reward.type, amount: Math.trunc(reward.amount) };
128
+ this.displaySeconds = Math.max(0, Math.trunc(options.displaySeconds ?? 0));
129
+ }
130
+ loadNative(id) {
131
+ return native.loadRewarded(id, this.placement, this.reward.type, this.reward.amount, this.format, this.displaySeconds);
132
+ }
133
+ }
@@ -0,0 +1,4 @@
1
+ export { RediadsAds, type RediadsStartOptions } from './RediadsAds';
2
+ export { RediadsBanner, type RediadsBannerProps } from './RediadsBanner';
3
+ export { RediadsInterstitial, RediadsRewarded, type FullScreenAd, type RediadsRewardedOptions, } from './RediadsFullScreenAd';
4
+ export type * from './types';
package/build/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { RediadsAds } from './RediadsAds';
2
+ export { RediadsBanner } from './RediadsBanner';
3
+ export { RediadsInterstitial, RediadsRewarded, } from './RediadsFullScreenAd';