@rediads/react-native-ads-gam 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.
Files changed (34) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/LICENSE +201 -0
  3. package/README.md +230 -2
  4. package/android/build.gradle +54 -0
  5. package/android/consumer-rules.pro +7 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMBannerSlot.kt +99 -0
  8. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMModule.kt +306 -0
  9. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMRenderedModule.kt +233 -0
  10. package/app.plugin.js +2 -0
  11. package/build/RediadsGAM.d.ts +46 -0
  12. package/build/RediadsGAM.js +66 -0
  13. package/build/RediadsGAMBanner.d.ts +26 -0
  14. package/build/RediadsGAMBanner.js +40 -0
  15. package/build/RediadsGAMBannerBiddingOnly.d.ts +23 -0
  16. package/build/RediadsGAMBannerBiddingOnly.js +39 -0
  17. package/build/RediadsGAMBiddingOnlyFullScreenAd.d.ts +59 -0
  18. package/build/RediadsGAMBiddingOnlyFullScreenAd.js +128 -0
  19. package/build/RediadsGAMFullScreenAd.d.ts +70 -0
  20. package/build/RediadsGAMFullScreenAd.js +140 -0
  21. package/build/index.d.ts +6 -0
  22. package/build/index.js +7 -0
  23. package/build/native.d.ts +45 -0
  24. package/build/native.js +18 -0
  25. package/build/renderedNative.d.ts +34 -0
  26. package/build/renderedNative.js +15 -0
  27. package/build/types.d.ts +77 -0
  28. package/build/types.js +1 -0
  29. package/expo-module.config.json +18 -0
  30. package/ios/RediadsAdsGAM.podspec +34 -0
  31. package/ios/RediadsGAMModule.swift +355 -0
  32. package/ios/RediadsGAMRenderedModule.swift +208 -0
  33. package/package.json +57 -4
  34. package/plugin/withRediadsGAM.js +161 -0
@@ -0,0 +1,208 @@
1
+ import ExpoModulesCore
2
+ import RediadsDisplay
3
+ import RediadsGAM
4
+
5
+ /// Google Ad Manager, SDK-rendered, through the SDK's RediadsGAMBannerView, RediadsGAMInterstitial and
6
+ /// RediadsGAMRewarded: GAM decides which ad wins; when a Rediads line item wins (its app-event creative
7
+ /// signals it), the Rediads SDK renders our ad itself, otherwise GAM's ad shows. Interstitials and
8
+ /// rewarded ads go by the ID JavaScript gives them (src/RediadsGAMFullScreenAd.ts). Everything runs on
9
+ /// the main queue, where the SDK calls back.
10
+ public class RediadsGAMRenderedModule: Module {
11
+ /// RediadsGAMInterstitial and RediadsGAMRewarded by ID. Main queue only.
12
+ private var ads: [Int: NSObject] = [:]
13
+
14
+ public func definition() -> ModuleDefinition {
15
+ Name("RediadsGAMRendered")
16
+
17
+ Events("onRenderedEvent")
18
+
19
+ AsyncFunction("loadInterstitial") {
20
+ (adId: Int, placement: String, adUnitId: String, format: String, promise: Promise) in
21
+ self.discard(adId)
22
+ let ad = RediadsGAMInterstitial(
23
+ placement: placement, gamAdUnitID: adUnitId, format: RediadsGAMModule.format(format))
24
+ ad.onEvent = self.forward(adId) { [weak ad] in ad?.lastRenderer ?? RediadsGAMRenderer.none }
25
+ self.ads[adId] = ad
26
+ ad.load { error in
27
+ promise.resolve(error?.localizedDescription)
28
+ }
29
+ }.runOnQueue(.main)
30
+
31
+ AsyncFunction("loadRewarded") {
32
+ (adId: Int, placement: String, adUnitId: String, rewardType: String, rewardAmount: Int,
33
+ format: String, displaySeconds: Int, promise: Promise) in
34
+ self.discard(adId)
35
+ let ad = RediadsGAMRewarded(
36
+ placement: placement,
37
+ gamAdUnitID: adUnitId,
38
+ reward: RediadsReward(type: rewardType, amount: rewardAmount),
39
+ format: RediadsGAMModule.format(format),
40
+ displaySeconds: displaySeconds > 0 ? displaySeconds : RediadsRewarded.defaultDisplaySeconds
41
+ )
42
+ ad.onEvent = self.forward(adId) { [weak ad] in ad?.lastRenderer ?? RediadsGAMRenderer.none }
43
+ self.ads[adId] = ad
44
+ ad.load { error in
45
+ promise.resolve(error?.localizedDescription)
46
+ }
47
+ }.runOnQueue(.main)
48
+
49
+ AsyncFunction("isReady") { (adId: Int) -> Bool in
50
+ switch self.ads[adId] {
51
+ case let ad as RediadsGAMInterstitial: return ad.isReady
52
+ case let ad as RediadsGAMRewarded: return ad.isReady
53
+ default: return false
54
+ }
55
+ }.runOnQueue(.main)
56
+
57
+ AsyncFunction("renderer") { (adId: Int) -> String in
58
+ switch self.ads[adId] {
59
+ case let ad as RediadsGAMInterstitial: return Self.name(of: ad.lastRenderer)
60
+ case let ad as RediadsGAMRewarded: return Self.name(of: ad.lastRenderer)
61
+ default: return "none"
62
+ }
63
+ }.runOnQueue(.main)
64
+
65
+ AsyncFunction("show") { (adId: Int) in
66
+ guard let ad = self.ads[adId] else { return }
67
+ // The top view controller, above any modal React Native has presented.
68
+ guard let host = self.appContext?.utilities?.currentViewController() else {
69
+ let placement = (ad as? RediadsGAMInterstitial)?.placement ?? (ad as? RediadsGAMRewarded)?.placement ?? ""
70
+ self.sendEvent("onRenderedEvent", [
71
+ "adId": adId, "type": "failed", "placement": placement,
72
+ "error": "There is no view controller to show the ad from.",
73
+ ])
74
+ return
75
+ }
76
+ if let ad = ad as? RediadsGAMInterstitial {
77
+ ad.show(from: host)
78
+ } else if let ad = ad as? RediadsGAMRewarded {
79
+ ad.show(from: host)
80
+ }
81
+ }.runOnQueue(.main)
82
+
83
+ AsyncFunction("destroy") { (adId: Int) in
84
+ self.discard(adId)
85
+ }.runOnQueue(.main)
86
+
87
+ View(RediadsGAMRenderedBannerSlot.self) {
88
+ Events("onAdEvent")
89
+
90
+ Prop("placement") { (view: RediadsGAMRenderedBannerSlot, value: String) in
91
+ view.placement = value
92
+ }
93
+
94
+ Prop("adUnitId") { (view: RediadsGAMRenderedBannerSlot, value: String) in
95
+ view.adUnitId = value
96
+ }
97
+
98
+ Prop("size") { (view: RediadsGAMRenderedBannerSlot, value: String) in
99
+ view.size = value
100
+ }
101
+
102
+ Prop("format") { (view: RediadsGAMRenderedBannerSlot, value: String) in
103
+ view.format = value
104
+ }
105
+
106
+ Prop("refreshInterval") { (view: RediadsGAMRenderedBannerSlot, value: Double) in
107
+ view.refreshInterval = value
108
+ }
109
+
110
+ OnViewDidUpdateProps { (view: RediadsGAMRenderedBannerSlot) in
111
+ view.loadIfReady()
112
+ }
113
+ }
114
+ }
115
+
116
+ /// Lets go of the ad under this ID, as Android's `discard` does: a load under an ID in use (JavaScript
117
+ /// reuses an ad's ID when it loads again) replaces the old ad, and none of the old ad's events reach
118
+ /// JavaScript as the new ad's.
119
+ private func discard(_ adId: Int) {
120
+ switch self.ads.removeValue(forKey: adId) {
121
+ case let ad as RediadsGAMInterstitial: ad.onEvent = nil
122
+ case let ad as RediadsGAMRewarded: ad.onEvent = nil
123
+ default: break
124
+ }
125
+ }
126
+
127
+ /// Sends an ad's events to JavaScript under its ID; `loaded` says who renders it.
128
+ private func forward(_ adId: Int, renderer: @escaping () -> RediadsGAMRenderer) -> (RediadsAdEvent) -> Void {
129
+ return { [weak self] event in
130
+ var payload = Self.payload(of: event, renderer: renderer())
131
+ payload["adId"] = adId
132
+ self?.sendEvent("onRenderedEvent", payload)
133
+ }
134
+ }
135
+
136
+ /// An event's fields for JavaScript.
137
+ static func payload(of event: RediadsAdEvent, renderer: RediadsGAMRenderer) -> [String: Any] {
138
+ var payload: [String: Any] = ["type": name(of: event.type), "placement": event.placement]
139
+ if let error = event.error { payload["error"] = error.localizedDescription }
140
+ if event.type == .loaded { payload["renderer"] = name(of: renderer) }
141
+ if let reward = event.reward {
142
+ payload["rewardType"] = reward.type
143
+ payload["rewardAmount"] = reward.amount
144
+ }
145
+ return payload
146
+ }
147
+
148
+ static func name(of renderer: RediadsGAMRenderer) -> String {
149
+ switch renderer {
150
+ case .rediads: return "rediads"
151
+ case .gam: return "gam"
152
+ default: return "none"
153
+ }
154
+ }
155
+
156
+ static func name(of type: RediadsAdEventType) -> String {
157
+ switch type {
158
+ case .loaded: return "loaded"
159
+ case .displayed: return "displayed"
160
+ case .failed: return "failed"
161
+ case .clicked: return "clicked"
162
+ case .presented: return "presented"
163
+ case .dismissed: return "dismissed"
164
+ case .leftApplication: return "leftApplication"
165
+ case .rewarded: return "rewarded"
166
+ @unknown default: return "unknown"
167
+ }
168
+ }
169
+ }
170
+
171
+ /// One SDK-rendered GAM banner slot. The banner is made once React has set the props and kept for the
172
+ /// life of the view (JavaScript gives the view a new key when they change); the SDK refreshes it while
173
+ /// on screen, with a new auction each time.
174
+ final class RediadsGAMRenderedBannerSlot: ExpoView {
175
+ let onAdEvent = EventDispatcher()
176
+ var placement = ""
177
+ var adUnitId = ""
178
+ var size = "300x250"
179
+ var format = "display"
180
+ var refreshInterval: Double = 0
181
+ private var banner: RediadsGAMBannerView?
182
+
183
+ func loadIfReady() {
184
+ guard banner == nil, !placement.isEmpty, !adUnitId.isEmpty else { return }
185
+ let adSize = RediadsGAMModule.bannerSize(size)
186
+ let banner = RediadsGAMBannerView(
187
+ placement: placement, gamAdUnitID: adUnitId, size: adSize, format: RediadsGAMModule.format(format))
188
+ if refreshInterval > 0 {
189
+ banner.refreshInterval = refreshInterval
190
+ }
191
+ banner.onEvent = { [weak self, weak banner] event in
192
+ self?.onAdEvent(RediadsGAMRenderedModule.payload(of: event, renderer: banner?.lastRenderer ?? RediadsGAMRenderer.none))
193
+ }
194
+ banner.frame = CGRect(origin: .zero, size: adSize)
195
+ addSubview(banner)
196
+ self.banner = banner
197
+ banner.load()
198
+ }
199
+
200
+ deinit {
201
+ banner?.stopRefresh()
202
+ }
203
+
204
+ override func layoutSubviews() {
205
+ super.layoutSubviews()
206
+ banner?.center = CGPoint(x: bounds.midX, y: bounds.midY)
207
+ }
208
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@rediads/react-native-ads-gam",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Rediads bids in Google Ad Manager for React Native apps: SDK-rendered (GAM decides, the Rediads SDK draws a Rediads win) or bidding only (the hb_ keys for your GAM requests, GAM draws).",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "files": [
8
+ "build/**/*.js",
9
+ "build/**/*.d.ts",
10
+ "ios/*.podspec",
11
+ "ios/*.swift",
12
+ "android/build.gradle",
13
+ "android/consumer-rules.pro",
14
+ "android/src/main/",
15
+ "plugin/",
16
+ "app.plugin.js",
17
+ "expo-module.config.json",
18
+ "README.md",
19
+ "LICENSE",
20
+ "CHANGELOG.md"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p .",
24
+ "clean": "rm -rf build",
25
+ "lint": "eslint src/ plugin/ app.plugin.js",
26
+ "prepack": "tsc -p ."
27
+ },
28
+ "keywords": [
29
+ "react-native",
30
+ "expo",
31
+ "ads",
32
+ "advertising",
33
+ "rediads",
34
+ "google-ad-manager",
35
+ "gam",
36
+ "header-bidding",
37
+ "prebid"
38
+ ],
39
+ "author": "Rediads (https://rediads.com)",
40
+ "license": "Apache-2.0",
41
+ "homepage": "https://rediads.com",
42
+ "devDependencies": {
43
+ "@rediads/react-native-ads": "0.1.0",
44
+ "@types/react": "~19.3.0",
45
+ "eslint": "~9.39.4",
46
+ "eslint-config-universe": "^16.1.2",
47
+ "expo": "^58.0.21",
48
+ "prettier": "^3.0.0",
49
+ "react": "19.3.0",
50
+ "react-native": "0.88.1",
51
+ "typescript": "~6.0.3"
52
+ },
53
+ "peerDependencies": {
54
+ "@rediads/react-native-ads": "0.1.0",
55
+ "expo": ">=58.0.0",
56
+ "react": "*",
57
+ "react-native": "*"
58
+ }
59
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Expo config plugin of @rediads/react-native-ads-gam. It runs during `npx expo prebuild` (and
3
+ * `expo run:ios|android`, EAS Build) and sets up Google's Mobile Ads SDK and the Rediads GAM pods:
4
+ *
5
+ * plugins: [
6
+ * '@rediads/react-native-ads',
7
+ * ['@rediads/react-native-ads-gam', {
8
+ * // Optional: the app's IDs from Ad Manager (Inventory → Apps) or AdMob, "ca-app-pub-XXXX~YYYY".
9
+ * // Without them, the app is marked as an Ad Manager app (GADIsAdManagerApp /
10
+ * // com.google.android.gms.ads.AD_MANAGER_APP), which Google's SDK accepts instead.
11
+ * iosAppId: 'ca-app-pub-XXXX~YYYY',
12
+ * androidAppId: 'ca-app-pub-XXXX~ZZZZ',
13
+ * // Optional, Android: the Google Mobile Ads SDK (play-services-ads) version to add when nothing
14
+ * // else in the app asks for one; default "25.5.0". The app's own version, or
15
+ * // react-native-google-mobile-ads's, always wins over it. "none" adds nothing.
16
+ * // androidGoogleMobileAdsVersion: '25.5.0',
17
+ * // SDK development only: the same local iOS SDK checkout as for @rediads/react-native-ads.
18
+ * // iosSdkPath: '../rediads-ios-sdk',
19
+ * }],
20
+ * ]
21
+ *
22
+ * - iOS: the app ID (or the Ad Manager flag) and Google's SKAdNetwork ID in Info.plist. The pods are
23
+ * binaries from Rediads' pod list, which this plugin adds as a Podfile source (as
24
+ * @rediads/react-native-ads does); with iosSdkPath, the RediadsGAM and RediadsGAMEventHandlers pods
25
+ * come from that checkout.
26
+ * - Android: the app ID (or the Ad Manager flag) meta-data in AndroidManifest.xml. The SDK comes
27
+ * from Maven Central (or @rediads/react-native-ads's androidMavenRepo option).
28
+ *
29
+ * Other plugins that set the app ID must use the same value. An ID given only to
30
+ * react-native-google-mobile-ads's config plugin is used here too, and two different IDs stop the
31
+ * prebuild; with that library in the app the IDs are required (its library manifest declares the app
32
+ * ID item, so the Ad Manager flag alone isn't enough). With @rediads/react-native-ads-admob, give
33
+ * the same IDs here too, so this plugin doesn't mark the app as Ad Manager only.
34
+ */
35
+ const {
36
+ addGoogleMetaData,
37
+ addSources,
38
+ googleAppIds,
39
+ withGoogleMobileAdsVersion,
40
+ } = require('@rediads/react-native-ads/app.plugin');
41
+ const {
42
+ AndroidConfig,
43
+ createRunOncePlugin,
44
+ withAndroidManifest,
45
+ withInfoPlist,
46
+ withPodfile,
47
+ } = require('expo/config-plugins');
48
+ const fs = require('fs');
49
+ const path = require('path');
50
+
51
+ const pkg = require('../package.json');
52
+
53
+ const TAG = '@rediads/react-native-ads-gam';
54
+ const PODS = ['RediadsGAM', 'RediadsGAMEventHandlers'];
55
+ const APP_ID = /^ca-app-pub-\d+~\d+$/;
56
+ const GOOGLE_SKADNETWORK = 'cstr6suwn9.skadnetwork';
57
+ const ANDROID_APP_ID = 'com.google.android.gms.ads.APPLICATION_ID';
58
+ const ANDROID_AD_MANAGER_APP = 'com.google.android.gms.ads.AD_MANAGER_APP';
59
+
60
+ function escapeRegExp(text) {
61
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
62
+ }
63
+
64
+ /** Removes the block an earlier prebuild added, so a changed path replaces it. */
65
+ function removeBlock(contents) {
66
+ const begin = escapeRegExp(`# @generated begin ${TAG}`);
67
+ const end = escapeRegExp(`# @generated end ${TAG}`);
68
+ return contents.replace(new RegExp(`[ \\t]*${begin} [\\s\\S]*?${end}\\n`), '');
69
+ }
70
+
71
+ function addPods(podfile, sdkPath) {
72
+ const contents = removeBlock(podfile);
73
+ // The app's own target; extension targets come after it.
74
+ const anchor = /^target '[^']+' do\n([ \t]*)use_expo_modules![^\n]*\n/m;
75
+ const match = contents.match(anchor);
76
+ if (!match) {
77
+ throw new Error(
78
+ `${TAG}: could not find the app target's \`use_expo_modules!\` in ios/Podfile, so the Rediads GAM pods could not be added.`
79
+ );
80
+ }
81
+ const indent = match[1];
82
+ const text = [
83
+ `${indent}# @generated begin ${TAG} - Rediads GAM pods from a local checkout`,
84
+ ...PODS.map((name) => `${indent}pod '${name}', :path => ${JSON.stringify(sdkPath)}`),
85
+ `${indent}# @generated end ${TAG}`,
86
+ '',
87
+ ].join('\n');
88
+ return contents.replace(anchor, (found) => `${found}${text}`);
89
+ }
90
+
91
+ function checkAppId(name, value) {
92
+ if (value && !APP_ID.test(value)) {
93
+ throw new Error(
94
+ `${TAG}: ${name} "${value}" is not an app ID. It looks like "ca-app-pub-XXXX~YYYY" (with "~"; ad unit IDs have "/").`
95
+ );
96
+ }
97
+ }
98
+
99
+ /**
100
+ * @param {import('expo/config').ExpoConfig} config
101
+ * @param {{ iosAppId?: string, androidAppId?: string, iosSdkPath?: string, androidGoogleMobileAdsVersion?: string } | undefined} options
102
+ */
103
+ function withRediadsGAM(config, options = {}) {
104
+ const { iosSdkPath } = options ?? {};
105
+ const { iosAppId, androidAppId, withGoogleMobileAds } = googleAppIds(config, TAG, options ?? {});
106
+ checkAppId('iosAppId', iosAppId);
107
+ checkAppId('androidAppId', androidAppId);
108
+ if (withGoogleMobileAds && (!iosAppId || !androidAppId)) {
109
+ throw new Error(
110
+ `${TAG}: react-native-google-mobile-ads is in the app, so Google's SDK needs the app IDs ("ca-app-pub-XXXX~YYYY", from Ad Manager → Inventory → Apps); the Ad Manager flag isn't enough with it. Set iosAppId and androidAppId in its plugin or here.`
111
+ );
112
+ }
113
+
114
+ config = withInfoPlist(config, (config) => {
115
+ const plist = config.modResults;
116
+ if (iosAppId) {
117
+ plist.GADApplicationIdentifier = iosAppId;
118
+ } else if (!plist.GADApplicationIdentifier) {
119
+ plist.GADIsAdManagerApp = true;
120
+ }
121
+ const items = Array.isArray(plist.SKAdNetworkItems) ? plist.SKAdNetworkItems : [];
122
+ if (!items.some((item) => item?.SKAdNetworkIdentifier === GOOGLE_SKADNETWORK)) {
123
+ items.push({ SKAdNetworkIdentifier: GOOGLE_SKADNETWORK });
124
+ }
125
+ plist.SKAdNetworkItems = items;
126
+ return config;
127
+ });
128
+
129
+ config = withPodfile(config, (config) => {
130
+ if (iosSdkPath) {
131
+ const folder = path.resolve(config.modRequest.projectRoot, iosSdkPath);
132
+ if (!fs.existsSync(path.join(folder, 'RediadsGAM.podspec'))) {
133
+ throw new Error(`${TAG}: iosSdkPath ${folder} has no RediadsGAM.podspec.`);
134
+ }
135
+ config.modResults.contents = addPods(config.modResults.contents, folder);
136
+ } else {
137
+ // Published pods: Rediads' pod list as a source (the same block @rediads/react-native-ads
138
+ // adds, so listing that plugin too doesn't add it twice); drop local pods of an earlier prebuild.
139
+ config.modResults.contents = addSources(removeBlock(config.modResults.contents));
140
+ }
141
+ return config;
142
+ });
143
+
144
+ config = withAndroidManifest(config, (config) => {
145
+ const { Manifest } = AndroidConfig;
146
+ const application = Manifest.getMainApplicationOrThrow(config.modResults);
147
+ if (androidAppId) {
148
+ addGoogleMetaData(config.modResults, ANDROID_APP_ID, androidAppId);
149
+ } else if (!Manifest.getMainApplicationMetaDataValue(config.modResults, ANDROID_APP_ID)) {
150
+ Manifest.addMetaDataItemToMainApplication(application, ANDROID_AD_MANAGER_APP, 'true');
151
+ }
152
+ return config;
153
+ });
154
+
155
+ config = withGoogleMobileAdsVersion(config, TAG, options?.androidGoogleMobileAdsVersion);
156
+
157
+ return config;
158
+ }
159
+
160
+ module.exports = createRunOncePlugin(withRediadsGAM, pkg.name, pkg.version);
161
+ module.exports.addPods = addPods;