diff --git a/.circleci/config.yml b/.circleci/config.yml index 83fc236b9..2c0c5a21d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -115,6 +115,10 @@ jobs: name: Prepare Galaxy Store package working_directory: react-native-purchases-store-galaxy command: yarn prepare + - run: + name: Prepare AdMob package + working_directory: react-native-purchases-admob + command: yarn prepare - run: name: Tests command: yarn test --maxWorkers=2 @@ -127,12 +131,18 @@ jobs: - run: name: Galaxy Store API Tests command: yarn workspace react-native-purchases-store-galaxy apitest + - run: + name: AdMob API Tests + command: yarn workspace react-native-purchases-admob apitest - run: name: UI Tests command: yarn workspace react-native-purchases-ui test - run: name: Galaxy Store Tests command: yarn workspace react-native-purchases-store-galaxy test + - run: + name: AdMob Tests + command: yarn workspace react-native-purchases-admob test - run: name: Linter command: yarn run tslint diff --git a/fastlane/Fastfile b/fastlane/Fastfile index 3bbb93198..961ed8e00 100644 --- a/fastlane/Fastfile +++ b/fastlane/Fastfile @@ -10,6 +10,7 @@ files_with_version_number = { './react-native-purchases-store-galaxy/android/build.gradle' => ['versionName \'{x}\''], './examples/purchaseTesterTypescript/package.json' => ['"react-native-purchases-store-galaxy": "{x}"'], './react-native-purchases-ui/package.json' => ['"version": "{x}"', '"react-native-purchases": "{x}"'], + './react-native-purchases-admob/package.json' => ['"version": "{x}"', '"react-native-purchases": "{x}"'], './ios/RNPurchases.m' => ['return @"{x}"'], './android/build.gradle' => ['versionName \'{x}\''], './react-native-purchases-ui/android/build.gradle' => ['versionName \'{x}\''], @@ -110,7 +111,7 @@ lane :github_release do |options| ) end -desc "Creates GitHub release and publishes react-native-purchases and react-native-purchases-ui" +desc "Creates GitHub release and publishes react-native-purchases, react-native-purchases-ui, react-native-purchases-store-galaxy and react-native-purchases-admob" lane :release do |options| version_number = current_version_number is_prerelease = prerelease? @@ -136,6 +137,9 @@ lane :release do |options| Dir.chdir(File.expand_path('react-native-purchases-store-galaxy', get_root_folder)) do sh(args) end + Dir.chdir(File.expand_path('react-native-purchases-admob', get_root_folder)) do + sh(args) + end github_release(version: version_number) end diff --git a/fastlane/README.md b/fastlane/README.md index bb5c66943..c85fcbfb7 100644 --- a/fastlane/README.md +++ b/fastlane/README.md @@ -51,7 +51,7 @@ Make github release [bundle exec] fastlane release ``` -Creates GitHub release and publishes react-native-purchases and react-native-purchases-ui +Creates GitHub release and publishes react-native-purchases, react-native-purchases-ui, react-native-purchases-store-galaxy and react-native-purchases-admob ### build_example diff --git a/package.json b/package.json index f92acfa09..558bd589e 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "!**/*.iml", "!**/.DS_Store", "!**/.gitignore", + "!react-native-purchases-admob", "!react-native-purchases-store-galaxy", "!react-native-purchases-ui", "!scripts/docs/index.html", @@ -47,6 +48,7 @@ }, "workspaces": [ "examples/purchaseTesterTypescript", + "react-native-purchases-admob", "react-native-purchases-store-galaxy", "react-native-purchases-ui", "e2e-tests/MaestroTestApp" @@ -108,6 +110,7 @@ "preset": "@react-native/jest-preset", "modulePathIgnorePatterns": [ "/examples/purchaseTesterTypescript/", + "/react-native-purchases-admob/", "/react-native-purchases-store-galaxy/", "/react-native-purchases-ui/", "/dir/" diff --git a/react-native-purchases-admob/.gitignore b/react-native-purchases-admob/.gitignore new file mode 100644 index 000000000..7f1209e93 --- /dev/null +++ b/react-native-purchases-admob/.gitignore @@ -0,0 +1,80 @@ +# OSX +# +.DS_Store + +# XDE +.expo/ + +# VSCode +.vscode/ +jsconfig.json + +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate +project.xcworkspace + +# Android/IJ +# +.classpath +.cxx +.gradle +.idea +.project +.settings +local.properties +android.iml + +# Cocoapods +# +example/ios/Pods + +# Ruby +example/vendor/ + +# node.js +# +node_modules/ +npm-debug.log +yarn-debug.log +yarn-error.log + +# BUCK +buck-out/ +\.buckd/ +android/app/libs +android/keystores/debug.keystore + +# Yarn +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + +# Expo +.expo/ + +# Turborepo +.turbo/ + +# generated by bob +lib/ + +dist/ diff --git a/react-native-purchases-admob/CHANGELOG.md b/react-native-purchases-admob/CHANGELOG.md new file mode 100644 index 000000000..bf9958f02 --- /dev/null +++ b/react-native-purchases-admob/CHANGELOG.md @@ -0,0 +1,3 @@ +## 10.14.0 +### ✨ New Features +* Initial release of `react-native-purchases-admob`: automatic ad tracking and rewarded-ad reward verification for `react-native-google-mobile-ads` 17+. diff --git a/react-native-purchases-admob/LICENSE b/react-native-purchases-admob/LICENSE new file mode 100644 index 000000000..cc2f416d2 --- /dev/null +++ b/react-native-purchases-admob/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2023 RevenueCat +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/react-native-purchases-admob/README.md b/react-native-purchases-admob/README.md new file mode 100644 index 000000000..616661b4d --- /dev/null +++ b/react-native-purchases-admob/README.md @@ -0,0 +1,92 @@ +

+ RevenueCat +
+ +[![npm](https://img.shields.io/npm/v/react-native-purchases-admob.svg)](https://www.npmjs.com/package/react-native-purchases-admob) + +## react-native-purchases-admob + +_react-native-purchases-admob_ connects [react-native-google-mobile-ads](https://github.com/invertase/react-native-google-mobile-ads) to [RevenueCat](https://www.revenuecat.com/)'s ad tracking and reward verification. Create your ads through the adapter and it reports loaded, failed-to-load, displayed, opened, revenue and earned-reward events for you; rewarded ads can additionally have their rewards verified server-side. See the [AdMob integration docs](https://www.revenuecat.com/docs/ad-monetization/admob) for the full picture. + +## Installation + +```sh +yarn add react-native-purchases react-native-google-mobile-ads react-native-purchases-admob +``` + +Requires `react-native-google-mobile-ads` 17 or newer (the first version that exposes `responseInfo` and `valueMicros` on every ad format). Configure `Purchases` and initialize `mobileAds()` as you normally would; the adapter only tracks while `Purchases` is configured. + +## Tracking full-screen ads + +Replace `InterstitialAd.createForAdRequest(...)` with the matching `RevenueCatAdMob.create...` call. The returned object is the same `InterstitialAd`, so `load()`, listeners and `destroy()` work as before; `placement` is a free-form label for where the ad is shown. + +```ts +import { RevenueCatAdMob } from "react-native-purchases-admob"; + +const interstitial = RevenueCatAdMob.createInterstitialAd(adUnitId, { + placement: "level_complete", + requestOptions: { keywords: ["game"] }, +}); +interstitial.addAdEventListener(AdEventType.LOADED, () => setReady(true)); +interstitial.load(); + +// Later. The placement given here overrides the load-time one for this impression. +await RevenueCatAdMob.showAndTrack(interstitial, { + placement: "level_complete_retry", +}); +``` + +`createAppOpenAd` works the same way. For an ad you created yourself, call `RevenueCatAdMob.trackAd(ad, { placement })` before `load()`. + +## Banner and native ads + +```tsx +import { useTrackingBannerAdProps } from "react-native-purchases-admob"; + +function HomeBanner() { + const bannerProps = useTrackingBannerAdProps({ + unitId, + size: BannerAdSize.BANNER, + placement: "home_bottom", + onPaid: (paid) => console.log(paid.value), + }); + return ; +} + +const nativeAd = await NativeAd.createForAdRequest(adUnitId); +RevenueCatAdMob.trackNativeAd(nativeAd, { placement: "feed" }); +``` + +Banners are a component, not an ad object, and their events arrive through props that React re-evaluates on every render, which is why they get a hook while every other format does not. Your own banner callbacks (`onAdLoaded`, `onPaid`, ...) are forwarded. Class components can use `RevenueCatAdMob.trackingBannerAdProps(...)` instead; it returns the same props but starts a new tracking state on every call, so call it once per banner instance (for example in the constructor), not inside `render`. + +## Reward verification + +`react-native-google-mobile-ads` only accepts server-side verification options when the ad request is created, before AdMob's response id exists. The adapter therefore generates the impression id itself when you opt in, attaches the RevenueCat token to the request, and uses that id for every tracking event of the ad. + +```ts +const rewarded = await RevenueCatAdMob.createRewardedAd(adUnitId, { + placement: "extra_life", + enableRewardVerification: true, +}); +rewarded.load(); + +await RevenueCatAdMob.showWithRewardVerification(rewarded, { + onRewardVerificationStarted: () => showSpinner(), + onRewardVerificationCompleted: (result) => { + if (result.failed) return showError(); + grant(result.reward); + }, +}); +``` + +Verification tokens are single-use, so create a new ad for every verified show rather than calling `load()` again on the same instance; after it has loaded, a second `load()` on a verified instance logs a warning and does nothing (a retry after a load error still works). `onRewardVerificationCompleted` is called at most once per show, after the user earns the reward; it is not called when the ad is dismissed or fails before a reward. The ad unit's server-side verification URL must point at RevenueCat and a reward must be configured for it in the RevenueCat dashboard; see the [rewards docs](https://www.revenuecat.com/docs/ad-monetization/rewards). + +## Not covered + +The `useInterstitialAd` / `useRewardedAd` hooks create their ads internally and cannot be routed through the adapter; use the class API above. Ad pools and multi-format requests are not tracked. + +## Requirements + +- iOS 15.0+ (ad tracking is unavailable below that; calls are ignored with a warning) +- `react-native-google-mobile-ads` 17.x (17.0.0 needs React Native 0.76+, 17.1.0+ needs 0.86+) and the New Architecture +- `react-native-purchases` 10.14.0 diff --git a/react-native-purchases-admob/__tests__/index.test.ts b/react-native-purchases-admob/__tests__/index.test.ts new file mode 100644 index 000000000..247034de7 --- /dev/null +++ b/react-native-purchases-admob/__tests__/index.test.ts @@ -0,0 +1,675 @@ +type Listener = (info: { type: string; payload?: unknown }) => void; + +class FakeAd { + public static created: FakeAd[] = []; + public loaded = false; + public responseInfo: unknown = null; + public listeners: Listener[] = []; + public typed: Array<{ type: string; listener: (p: unknown) => void }> = []; + public shown: unknown[] = []; + public loads = 0; + constructor(public adUnitId: string, public requestOptions: unknown) { + FakeAd.created.push(this); + } + static createForAdRequest(adUnitId: string, requestOptions?: unknown) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return new (this as any)(adUnitId, requestOptions ?? {}); + } + addAdEventsListener(listener: Listener) { + this.listeners.push(listener); + return () => { + this.listeners = this.listeners.filter((l) => l !== listener); + }; + } + addAdEventListener(type: string, listener: (p: unknown) => void) { + const entry = { type, listener }; + this.typed.push(entry); + return () => { + this.typed = this.typed.filter((e) => e !== entry); + }; + } + load() { + this.loads++; + } + show(options?: unknown) { + this.shown.push(options); + return Promise.resolve(); + } + emit(type: string, payload?: unknown) { + this.listeners.forEach((l) => l({ type, payload })); + this.typed + .filter((e) => e.type === type) + .forEach((e) => e.listener(payload)); + } +} +class FakeInterstitial extends FakeAd {} +class FakeRewarded extends FakeAd {} +class FakeRewardedInterstitial extends FakeAd {} +class FakeAppOpen extends FakeAd {} + +const adTracker = { + trackAdLoaded: jest.fn(() => Promise.resolve()), + trackAdFailedToLoad: jest.fn(() => Promise.resolve()), + trackAdDisplayed: jest.fn(() => Promise.resolve()), + trackAdOpened: jest.fn(() => Promise.resolve()), + trackAdRevenue: jest.fn(() => Promise.resolve()), + trackAdRewardEarnedUnverified: jest.fn(() => Promise.resolve()), +}; +const generateRewardVerificationToken = jest.fn(); +const pollRewardVerification = jest.fn(); + +jest.mock("react-native-purchases", () => ({ + __esModule: true, + default: { + adTracker, + generateRewardVerificationToken: (id: string) => + generateRewardVerificationToken(id), + pollRewardVerification: (id: string, meta: unknown) => + pollRewardVerification(id, meta), + }, + AdCaptureMethod: { reactNativeAdMobAdapter: "react_native_admob_adapter" }, + AdFormat: { + banner: "banner", + interstitial: "interstitial", + rewarded: "rewarded", + rewardedInterstitial: "rewarded_interstitial", + nativeAd: "native", + appOpen: "app_open", + }, + AdMediatorName: { adMob: "AdMob" }, + AdRevenuePrecision: { + exact: "exact", + publisherDefined: "publisher_defined", + estimated: "estimated", + unknown: "unknown", + }, +})); + +jest.mock("react-native-google-mobile-ads", () => ({ + AdEventType: { + LOADED: "loaded", + ERROR: "error", + OPENED: "opened", + PAID: "paid", + CLICKED: "clicked", + CLOSED: "closed", + IMPRESSION: "impression", + }, + RewardedAdEventType: { + LOADED: "rewarded_loaded", + EARNED_REWARD: "rewarded_earned_reward", + }, + NativeAdEventType: { + IMPRESSION: "impression", + CLICKED: "clicked", + PAID: "paid", + }, + InterstitialAd: FakeInterstitial, + RewardedAd: FakeRewarded, + RewardedInterstitialAd: FakeRewardedInterstitial, + AppOpenAd: FakeAppOpen, + NativeAd: class {}, +})); + +jest.mock("react-native", () => ({ Platform: { OS: "android" } })); + +import React from "react"; +import TestRenderer, { act } from "react-test-renderer"; + +import { Platform } from "react-native"; + +import { RevenueCatAdMob, useTrackingBannerAdProps } from "../src"; +import { mediatorErrorCode } from "../src/tracker"; +import type { BannerAdTrackingProps } from "../src"; + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +const responseInfo = (id: string) => ({ + responseId: id, + adapterClassName: "Mediation", + loadedAdapterResponse: { adapterClassName: "com.google.Adapter" }, + adapterResponses: [], + extras: {}, +}); + +beforeEach(() => { + jest.clearAllMocks(); + FakeAd.created = []; + generateRewardVerificationToken.mockResolvedValue({ + customData: "custom-data", + clientTransactionId: "ctx-1", + appUserID: "user-1", + }); + pollRewardVerification.mockResolvedValue({ + failed: false, + reward: { type: "virtual_currency", code: "GEM", amount: 3 }, + moreRewards: [], + }); +}); + +const flush = () => new Promise((resolve) => setImmediate(resolve)); + +describe("interstitial", () => { + it("tracks the lifecycle with a show-time placement override", async () => { + const ad = RevenueCatAdMob.createInterstitialAd("unit-1", { + placement: "home", + }) as unknown as FakeAd; + ad.responseInfo = responseInfo("resp-1"); + ad.emit("loaded"); + expect(adTracker.trackAdLoaded).toHaveBeenCalledWith({ + networkName: "com.google.Adapter", + mediatorName: "AdMob", + adFormat: "interstitial", + placement: "home", + adUnitId: "unit-1", + impressionId: "resp-1", + captureMethod: "react_native_admob_adapter", + }); + + await RevenueCatAdMob.showAndTrack(ad as never, { + placement: "home_retry", + }); + expect(ad.shown).toHaveLength(1); + ad.emit("impression"); + ad.emit("clicked"); + ad.emit("paid", { + currency: "USD", + precision: 3, + value: 1.5, + valueMicros: "1500000", + }); + + expect(adTracker.trackAdDisplayed).toHaveBeenCalledWith( + expect.objectContaining({ + placement: "home_retry", + impressionId: "resp-1", + }) + ); + expect(adTracker.trackAdOpened).toHaveBeenCalledWith( + expect.objectContaining({ placement: "home_retry" }) + ); + expect(adTracker.trackAdRevenue).toHaveBeenCalledWith( + expect.objectContaining({ + revenueMicros: 1500000, + currency: "USD", + precision: "exact", + captureMethod: "react_native_admob_adapter", + }) + ); + }); + + it("derives micros from value when valueMicros is missing", () => { + const ad = RevenueCatAdMob.createInterstitialAd( + "unit-1" + ) as unknown as FakeAd; + ad.emit("paid", { currency: "EUR", precision: 1, value: 0.0125 }); + expect(adTracker.trackAdRevenue).toHaveBeenCalledWith( + expect.objectContaining({ revenueMicros: 12500, precision: "estimated" }) + ); + }); + + it("tracks load failures but ignores show failures", () => { + const ad = RevenueCatAdMob.createAppOpenAd("unit-2", { + placement: "launch", + }) as unknown as FakeAd; + ad.emit("error", { phase: "load", reason: "no-fill" }); + ad.emit("error", { phase: "show", reason: "internal-error" }); + expect(adTracker.trackAdFailedToLoad).toHaveBeenCalledTimes(1); + expect(adTracker.trackAdFailedToLoad).toHaveBeenCalledWith({ + mediatorName: "AdMob", + adFormat: "app_open", + placement: "launch", + adUnitId: "unit-2", + mediatorErrorCode: 3, + captureMethod: "react_native_admob_adapter", + }); + }); + + it("does not throw when the tracker rejects", async () => { + adTracker.trackAdLoaded.mockRejectedValueOnce(new Error("not configured")); + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = RevenueCatAdMob.createInterstitialAd( + "unit-1" + ) as unknown as FakeAd; + ad.emit("loaded"); + await flush(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("Could not track ad loaded") + ); + warn.mockRestore(); + }); +}); + +describe("reward verification", () => { + it("pins the impression id, attaches SSV options and polls once", async () => { + const ad = (await RevenueCatAdMob.createRewardedInterstitialAd("ri-1", { + placement: "bonus", + enableRewardVerification: true, + requestOptions: { keywords: ["a"] }, + })) as unknown as FakeAd; + + const impressionId = RevenueCatAdMob.impressionIdOf(ad)!; + expect(impressionId).toMatch(/^[0-9a-f-]{36}$/); + expect(generateRewardVerificationToken).toHaveBeenCalledWith(impressionId); + expect(ad.requestOptions).toEqual({ + keywords: ["a"], + serverSideVerificationOptions: { + userId: "user-1", + customData: "custom-data", + }, + }); + + ad.responseInfo = responseInfo("ri-resp"); + ad.emit("loaded"); + ad.emit("rewarded_loaded"); + expect(adTracker.trackAdLoaded).toHaveBeenCalledTimes(1); + expect(adTracker.trackAdLoaded).toHaveBeenCalledWith( + expect.objectContaining({ + impressionId, + adFormat: "rewarded_interstitial", + }) + ); + + const results: unknown[] = []; + let started = 0; + const rewards: unknown[] = []; + await RevenueCatAdMob.showWithRewardVerification(ad as never, { + placement: "bonus_shown", + onUserEarnedReward: (r) => rewards.push(r), + onRewardVerificationStarted: () => started++, + onRewardVerificationCompleted: (r) => results.push(r), + }); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + await flush(); + + expect(rewards).toHaveLength(2); + expect(started).toBe(2); + expect(results).toHaveLength(1); + expect(pollRewardVerification).toHaveBeenCalledWith("ctx-1", { + networkName: "com.google.Adapter", + mediatorName: "AdMob", + adFormat: "rewarded_interstitial", + placement: "bonus_shown", + adUnitId: "ri-1", + impressionId, + captureMethod: "react_native_admob_adapter", + }); + + ad.emit("closed"); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + expect(rewards).toHaveLength(2); + expect(adTracker.trackAdRewardEarnedUnverified).not.toHaveBeenCalled(); + }); + + it("tracks the earned reward itself when verification is not enabled", async () => { + const ad = (await RevenueCatAdMob.createRewardedAd("r-2", { + placement: "bonus", + })) as unknown as FakeAd; + ad.responseInfo = responseInfo("r2-resp"); + ad.emit("rewarded_loaded"); + await RevenueCatAdMob.showAndTrack(ad as never, { + placement: "bonus_shown", + }); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + + expect(adTracker.trackAdRewardEarnedUnverified).toHaveBeenCalledTimes(1); + expect(adTracker.trackAdRewardEarnedUnverified).toHaveBeenCalledWith({ + networkName: "com.google.Adapter", + mediatorName: "AdMob", + adFormat: "rewarded", + placement: "bonus_shown", + adUnitId: "r-2", + impressionId: "r2-resp", + captureMethod: "react_native_admob_adapter", + }); + }); + + it("ignores a second load() on a verified ad", async () => { + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = (await RevenueCatAdMob.createRewardedAd("r-3", { + enableRewardVerification: true, + })) as unknown as FakeAd; + const pinned = RevenueCatAdMob.impressionIdOf(ad)!; + ad.load(); + ad.responseInfo = responseInfo("first"); + ad.emit("rewarded_loaded"); + ad.emit("closed"); + expect(ad.loads).toBe(1); + expect(warn).not.toHaveBeenCalled(); + + ad.load(); + expect(ad.loads).toBe(1); + expect(adTracker.trackAdLoaded).toHaveBeenCalledTimes(1); + expect(RevenueCatAdMob.impressionIdOf(ad)).toBe(pinned); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("single-use")); + warn.mockRestore(); + }); + + it("allows load() again after a load error on a verified ad", async () => { + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = (await RevenueCatAdMob.createRewardedAd("r-5", { + enableRewardVerification: true, + })) as unknown as FakeAd; + ad.load(); + ad.emit("error", { phase: "load", reason: "no-fill" }); + ad.load(); + expect(ad.loads).toBe(2); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it("does not restrict load() on an unverified rewarded ad", async () => { + const ad = (await RevenueCatAdMob.createRewardedAd( + "r-4" + )) as unknown as FakeAd; + ad.load(); + ad.load(); + expect(ad.loads).toBe(2); + }); + + it("fails fast when verification was not enabled", async () => { + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = (await RevenueCatAdMob.createRewardedAd( + "r-1" + )) as unknown as FakeAd; + const results: { failed: boolean }[] = []; + await RevenueCatAdMob.showWithRewardVerification(ad as never, { + onRewardVerificationCompleted: (r) => results.push(r), + }); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + expect(results).toEqual([{ failed: true, moreRewards: [] }]); + expect(pollRewardVerification).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it("reports a failed result when polling rejects", async () => { + pollRewardVerification.mockRejectedValueOnce(new Error("boom")); + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = (await RevenueCatAdMob.createRewardedAd("r-1", { + enableRewardVerification: true, + })) as unknown as FakeAd; + const results: { failed: boolean }[] = []; + await RevenueCatAdMob.showWithRewardVerification(ad as never, { + onRewardVerificationCompleted: (r) => results.push(r), + }); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + await flush(); + expect(results).toEqual([{ failed: true, moreRewards: [] }]); + warn.mockRestore(); + }); + + it("removes its listeners when show rejects so a retry does not stack them", async () => { + const ad = (await RevenueCatAdMob.createRewardedAd("r-1", { + enableRewardVerification: true, + })) as unknown as FakeAd; + const rewards: unknown[] = []; + const options = { + onUserEarnedReward: (r: unknown) => rewards.push(r), + onRewardVerificationCompleted: () => undefined, + }; + + const notLoaded = new Error("not loaded"); + ad.show = () => Promise.reject(notLoaded); + await expect( + RevenueCatAdMob.showWithRewardVerification(ad as never, options) + ).rejects.toBe(notLoaded); + expect(ad.typed).toHaveLength(0); + + ad.show = () => Promise.resolve(); + await RevenueCatAdMob.showWithRewardVerification(ad as never, options); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + expect(rewards).toHaveLength(1); + }); + + it("removes its listeners when the show fails with an error event", async () => { + const ad = (await RevenueCatAdMob.createRewardedAd("r-1", { + enableRewardVerification: true, + })) as unknown as FakeAd; + const rewards: unknown[] = []; + await RevenueCatAdMob.showWithRewardVerification(ad as never, { + onUserEarnedReward: (r) => rewards.push(r), + onRewardVerificationCompleted: () => undefined, + }); + expect(ad.typed).toHaveLength(3); + ad.emit("error", { phase: "show", reason: "internal-error" }); + expect(ad.typed).toHaveLength(0); + ad.emit("rewarded_earned_reward", { type: "coin", amount: 1 }); + expect(rewards).toHaveLength(0); + }); + + it("falls back to tracking without verification when the token fails", async () => { + generateRewardVerificationToken.mockRejectedValueOnce(new Error("offline")); + const warn = jest + .spyOn(console, "warn") + .mockImplementation(() => undefined); + const ad = (await RevenueCatAdMob.createRewardedAd("r-1", { + enableRewardVerification: true, + })) as unknown as FakeAd; + expect(ad.requestOptions).toEqual({}); + ad.responseInfo = responseInfo("r-resp"); + ad.emit("rewarded_loaded"); + expect(adTracker.trackAdLoaded).toHaveBeenCalledWith( + expect.objectContaining({ impressionId: "r-resp" }) + ); + warn.mockRestore(); + }); +}); + +describe("banner", () => { + it("wraps banner props and forwards to the developer's handlers", () => { + const userLoaded = jest.fn(); + const props = RevenueCatAdMob.trackingBannerAdProps({ + unitId: "banner-1", + size: "BANNER", + placement: "bottom", + onAdLoaded: userLoaded, + }); + expect((props as { placement?: string }).placement).toBeUndefined(); + props.onAdLoaded!({ + width: 320, + height: 50, + responseInfo: responseInfo("b-1") as never, + }); + props.onAdImpression!(); + props.onPaid!({ + currency: "USD", + precision: 2, + value: 0.002, + valueMicros: "2000", + }); + props.onAdLoaded!({ + width: 320, + height: 50, + responseInfo: responseInfo("b-2") as never, + }); + props.onAdClicked!(); + props.onAdFailedToLoad!( + Object.assign(new Error("x"), { reason: "network-error" }) + ); + + expect(userLoaded).toHaveBeenCalledTimes(2); + expect( + adTracker.trackAdLoaded.mock.calls.map((c) => (c as unknown[])[0]) + ).toEqual([ + expect.objectContaining({ impressionId: "b-1", adFormat: "banner" }), + expect.objectContaining({ impressionId: "b-2" }), + ]); + expect(adTracker.trackAdDisplayed).toHaveBeenCalledWith( + expect.objectContaining({ impressionId: "b-1", placement: "bottom" }) + ); + expect(adTracker.trackAdRevenue).toHaveBeenCalledWith( + expect.objectContaining({ + revenueMicros: 2000, + precision: "publisher_defined", + }) + ); + expect(adTracker.trackAdOpened).toHaveBeenCalledWith( + expect.objectContaining({ impressionId: "b-2" }) + ); + expect(adTracker.trackAdFailedToLoad).toHaveBeenCalledWith( + expect.objectContaining({ mediatorErrorCode: 2 }) + ); + }); + + it("keeps one tracking state across rerenders when used as a hook", () => { + let latest: ReturnType | undefined; + const Banner = (props: BannerAdTrackingProps) => { + latest = useTrackingBannerAdProps(props); + return null; + }; + const render = (onPaid: jest.Mock) => + React.createElement(Banner, { + unitId: "banner-1", + size: "BANNER", + placement: "bottom", + onPaid, + }); + + const firstPaid = jest.fn(); + const secondPaid = jest.fn(); + let renderer!: TestRenderer.ReactTestRenderer; + act(() => { + renderer = TestRenderer.create(render(firstPaid)); + }); + act(() => { + latest!.onAdLoaded!({ + width: 320, + height: 50, + responseInfo: responseInfo("b-1") as never, + }); + }); + act(() => { + renderer.update(render(secondPaid)); + }); + latest!.onAdImpression!(); + latest!.onPaid!({ + currency: "USD", + precision: 2, + value: 0.002, + valueMicros: "2000", + }); + + expect(adTracker.trackAdDisplayed).toHaveBeenCalledWith( + expect.objectContaining({ impressionId: "b-1", placement: "bottom" }) + ); + expect(adTracker.trackAdRevenue).toHaveBeenCalledWith( + expect.objectContaining({ + impressionId: "b-1", + networkName: "com.google.Adapter", + }) + ); + expect(firstPaid).not.toHaveBeenCalled(); + expect(secondPaid).toHaveBeenCalledTimes(1); + act(() => { + renderer.unmount(); + }); + }); +}); + +describe("error codes", () => { + const platform = Platform as { OS: string }; + + afterEach(() => { + platform.OS = "android"; + }); + + it("maps reasons onto AdRequest error codes on Android", () => { + platform.OS = "android"; + expect( + Object.fromEntries( + [ + "internal-error", + "invalid-request", + "network-error", + "no-fill", + "app-id-missing", + "mediation-no-fill", + "request-id-mismatch", + "invalid-ad-string", + "timeout", + "mediation-adapter-error", + ].map((reason) => [reason, mediatorErrorCode(reason)]) + ) + ).toEqual({ + "internal-error": 0, + "invalid-request": 1, + "network-error": 2, + "no-fill": 3, + "app-id-missing": 8, + "mediation-no-fill": 9, + "request-id-mismatch": 10, + "invalid-ad-string": 11, + timeout: null, + "mediation-adapter-error": null, + }); + }); + + it("maps reasons onto GADErrorCode on iOS", () => { + platform.OS = "ios"; + expect( + Object.fromEntries( + [ + "invalid-request", + "no-fill", + "network-error", + "server-error", + "timeout", + "mediation-data-error", + "mediation-adapter-error", + "mediation-invalid-ad-size", + "internal-error", + "invalid-argument", + "ad-already-used", + "app-id-missing", + "invalid-ad-string", + "request-id-mismatch", + ].map((reason) => [reason, mediatorErrorCode(reason)]) + ) + ).toEqual({ + "invalid-request": 0, + "no-fill": 1, + "network-error": 2, + "server-error": 3, + timeout: 5, + "mediation-data-error": 7, + "mediation-adapter-error": 8, + "mediation-invalid-ad-size": 10, + "internal-error": 11, + "invalid-argument": 12, + "ad-already-used": 19, + "app-id-missing": 20, + "invalid-ad-string": 21, + "request-id-mismatch": null, + }); + }); + + it("falls back to numeric reasons and null otherwise", () => { + expect(mediatorErrorCode("7")).toBe(7); + expect(mediatorErrorCode("unknown")).toBeNull(); + expect(mediatorErrorCode(undefined)).toBeNull(); + }); + + it("reports the platform's code for a load failure", () => { + platform.OS = "ios"; + const ad = RevenueCatAdMob.createInterstitialAd( + "unit-ios" + ) as unknown as FakeAd; + ad.emit("error", { phase: "load", reason: "no-fill" }); + expect(adTracker.trackAdFailedToLoad).toHaveBeenCalledWith( + expect.objectContaining({ mediatorErrorCode: 1 }) + ); + }); +}); diff --git a/react-native-purchases-admob/apitesters/admob.ts b/react-native-purchases-admob/apitesters/admob.ts new file mode 100644 index 000000000..9a4affe3b --- /dev/null +++ b/react-native-purchases-admob/apitesters/admob.ts @@ -0,0 +1,76 @@ +import type { + AppOpenAd, + BannerAdProps, + InterstitialAd, + NativeAd, + RewardedAd, + RewardedInterstitialAd, +} from "react-native-google-mobile-ads"; +import type { RewardVerificationResult } from "react-native-purchases"; +import RevenueCatAdMob, { + RevenueCatAdMob as Named, + useTrackingBannerAdProps, +} from "react-native-purchases-admob"; +import type { + RewardedTrackingOptions, + ShowWithRewardVerificationOptions, + TrackableAd, + BannerAdTrackingProps, + TrackingOptions, +} from "react-native-purchases-admob"; + +async function checkApi(nativeAd: NativeAd) { + const options: TrackingOptions = { placement: "p", requestOptions: {} }; + const rewardedOptions: RewardedTrackingOptions = { + ...options, + enableRewardVerification: true, + }; + const interstitial: InterstitialAd = RevenueCatAdMob.createInterstitialAd( + "u", + options + ); + const appOpen: AppOpenAd = Named.createAppOpenAd("u"); + const rewarded: RewardedAd = await RevenueCatAdMob.createRewardedAd( + "u", + rewardedOptions + ); + const rewardedInterstitial: RewardedInterstitialAd = + await RevenueCatAdMob.createRewardedInterstitialAd("u"); + RevenueCatAdMob.trackAd(appOpen, { placement: "x" }); + await RevenueCatAdMob.showAndTrack(interstitial, { placement: "y" }); + const showOptions: ShowWithRewardVerificationOptions = { + placement: "z", + onUserEarnedReward: (reward) => reward.amount, + onRewardVerificationStarted: () => undefined, + onRewardVerificationCompleted: (result: RewardVerificationResult) => + result.failed, + }; + await RevenueCatAdMob.showWithRewardVerification(rewarded, showOptions); + await RevenueCatAdMob.showWithRewardVerification( + rewardedInterstitial, + showOptions + ); + const trackedBannerProps: BannerAdTrackingProps = { + unitId: "u", + size: "BANNER", + placement: "b", + }; + const bannerProps: BannerAdProps = + RevenueCatAdMob.trackingBannerAdProps(trackedBannerProps); + RevenueCatAdMob.trackNativeAd(nativeAd, { placement: "n" }); + const impressionId: string | null = RevenueCatAdMob.impressionIdOf(rewarded); + const trackable: TrackableAd = interstitial; + return { bannerProps, impressionId, trackable }; +} + +function checkHooks() { + const bannerProps: BannerAdProps = useTrackingBannerAdProps({ + unitId: "u", + size: "BANNER", + placement: "b", + onPaid: (paid) => paid.value, + }); + return bannerProps; +} + +export { checkApi, checkHooks }; diff --git a/react-native-purchases-admob/apitesters/tsconfig.json b/react-native-purchases-admob/apitesters/tsconfig.json new file mode 100644 index 000000000..13fabe96c --- /dev/null +++ b/react-native-purchases-admob/apitesters/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "baseUrl": "..", + "paths": { + "react-native-purchases": ["../dist/index"], + "react-native-purchases-admob": ["./src/index"] + }, + "noEmit": true, + "noUnusedLocals": false, + "noUnusedParameters": false + }, + "include": ["./**/*"], + "exclude": ["../node_modules", "../lib"] +} diff --git a/react-native-purchases-admob/babel.config.js b/react-native-purchases-admob/babel.config.js new file mode 100644 index 000000000..f7b3da3b3 --- /dev/null +++ b/react-native-purchases-admob/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ['module:@react-native/babel-preset'], +}; diff --git a/react-native-purchases-admob/package.json b/react-native-purchases-admob/package.json new file mode 100644 index 000000000..40ced3b27 --- /dev/null +++ b/react-native-purchases-admob/package.json @@ -0,0 +1,111 @@ +{ + "name": "react-native-purchases-admob", + "title": "React Native Purchases AdMob", + "version": "10.14.0", + "description": "RevenueCat adapter for react-native-google-mobile-ads: automatic ad tracking and rewarded-ad reward verification.", + "main": "lib/commonjs/index", + "module": "lib/module/index", + "types": "lib/typescript/src/index.d.ts", + "react-native": "src/index", + "source": "src/index", + "files": [ + "src", + "lib", + "!**/__tests__", + "!**/__fixtures__", + "!**/__mocks__", + "!**/.*" + ], + "scripts": { + "test": "jest", + "typecheck": "tsc --noEmit", + "tslint": "tslint -c tslint.json 'src/*.ts'", + "prepare": "bob build", + "apitest": "echo \"Running react-native-purchases-admob API type checks\" && tsc --project apitesters/tsconfig.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/revenuecat/react-native-purchases.git", + "baseUrl": "https://github.com/revenuecat/react-native-purchases" + }, + "keywords": [ + "react-native", + "admob", + "ads", + "revenuecat", + "iOS", + "Android" + ], + "author": "RevenueCat, Inc.", + "license": "MIT", + "readmeFilename": "README.md", + "devDependencies": { + "@types/jest": "^29.5.12", + "@types/react": "^18.2.44", + "@types/react-dom": "~18.2.0", + "@types/react-test-renderer": "^18.0.7", + "jest": "^29.7.0", + "jest-react-native": "^18.0.0", + "prettier": "^2.0.5", + "react": "18.2.0", + "react-native": "0.78.0", + "react-native-builder-bob": "^0.20.0", + "react-native-google-mobile-ads": "^17.0.0", + "react-test-renderer": "18.2.0", + "ts-jest": "^29.1.2", + "tslint": "^5.20.0", + "tslint-config-prettier": "^1.18.0", + "typescript": "^5.2.2" + }, + "resolutions": { + "@types/react": "^18.2.44", + "@types/react-dom": "18.2.0" + }, + "peerDependencies": { + "react": "*", + "react-native": ">= 0.76.0", + "react-native-google-mobile-ads": ">= 17.0.0 < 18.0.0", + "react-native-purchases": "10.14.0" + }, + "packageManager": "yarn@3.6.1+sha512.de524adec81a6c3d7a26d936d439d2832e351cdfc5728f9d91f3fc85dd20b04391c038e9b4ecab11cae2b0dd9f0d55fd355af766bc5c1a7f8d25d96bb2a0b2ca", + "jest": { + "preset": "ts-jest", + "testEnvironment": "node", + "modulePathIgnorePatterns": [ + "/lib/" + ], + "moduleFileExtensions": [ + "ts", + "tsx", + "js" + ], + "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", + "testPathIgnorePatterns": [ + "\\.snap$", + "/node_modules/" + ], + "cacheDirectory": ".jest/cache", + "globals": { + "ts-jest": { + "tsconfig": "tsconfig.test.json" + } + }, + "moduleNameMapper": { + "^react-native-purchases$": "/../dist/index" + } + }, + "react-native-builder-bob": { + "source": "src", + "output": "lib", + "targets": [ + "commonjs", + "module", + [ + "typescript", + { + "project": "tsconfig.build.json" + } + ] + ] + } +} diff --git a/react-native-purchases-admob/src/index.ts b/react-native-purchases-admob/src/index.ts new file mode 100644 index 000000000..77cd550de --- /dev/null +++ b/react-native-purchases-admob/src/index.ts @@ -0,0 +1,623 @@ +import { useRef } from "react"; +import Purchases, { AdFormat } from "react-native-purchases"; +import type { RewardVerificationResult } from "react-native-purchases"; +import { + AdEventType, + AppOpenAd, + InterstitialAd, + NativeAd, + NativeAdEventType, + RewardedAd, + RewardedAdEventType, + RewardedInterstitialAd, +} from "react-native-google-mobile-ads"; +import type { + AdShowOptions, + BannerAdProps, + PaidEvent, + RequestOptions, + ResponseInfo, + RewardedAdReward, +} from "react-native-google-mobile-ads"; + +import { + generateImpressionId, + setState, + stateFor, + TrackedAdState, +} from "./state"; +import { AdMobTracker, logWarning } from "./tracker"; + +export type { TrackedAdState } from "./state"; + +/** + * The structural shape of a `react-native-google-mobile-ads` full-screen ad + * (`InterstitialAd`, `AppOpenAd`, `RewardedAd`, `RewardedInterstitialAd`). + * Typed structurally so the adapter works across the library's per-class + * listener generics and duplicate type installations. + */ +export interface TrackableAd { + readonly adUnitId: string; + readonly loaded: boolean; + readonly responseInfo: ResponseInfo | null; + load(): void; + destroy(): void; + addAdEventsListener( + listener: (event: { type: string; payload?: unknown }) => void + ): () => void; + addAdEventListener( + type: string, + // tslint:disable-next-line:no-any + listener: (payload: any) => void + ): () => void; + show(showOptions?: AdShowOptions): Promise; +} + +export interface TrackingOptions { + /** Free-form label for where in your app the ad is shown. */ + placement?: string | null; + /** Passed through to `createForAdRequest`. */ + requestOptions?: RequestOptions; +} + +export interface RewardedTrackingOptions extends TrackingOptions { + /** + * Attach a RevenueCat reward-verification token to AdMob's server-side + * verification options. The token has to exist before the ad request is + * created, so the adapter generates the impression id itself and uses it for + * every tracking event of this ad. Tokens are single-use: create a new ad + * for each verified show instead of calling `load()` again on this one. + */ + enableRewardVerification?: boolean; +} + +export interface ShowOptions { + /** Overrides the load-time placement for this impression's events. */ + placement?: string | null; + showOptions?: AdShowOptions; +} + +export type BannerAdTrackingProps = BannerAdProps & { + placement?: string | null; +}; + +export type RewardVerificationStartedCallback = () => void; +export type RewardVerificationCompletedCallback = ( + result: RewardVerificationResult +) => void; + +export interface ShowWithRewardVerificationOptions extends ShowOptions { + onUserEarnedReward?: (reward: RewardedAdReward) => void; + onRewardVerificationStarted?: RewardVerificationStartedCallback; + onRewardVerificationCompleted: RewardVerificationCompletedCallback; +} + +const failedResult: RewardVerificationResult = { + failed: true, + moreRewards: [], +}; + +function formatOf(ad: TrackableAd): AdFormat | null { + if (ad instanceof InterstitialAd) { + return AdFormat.interstitial; + } + if (ad instanceof RewardedInterstitialAd) { + return AdFormat.rewardedInterstitial; + } + if (ad instanceof RewardedAd) { + return AdFormat.rewarded; + } + if (ad instanceof AppOpenAd) { + return AdFormat.appOpen; + } + return null; +} + +/** + * Attaches RevenueCat tracking to an already created full-screen ad. Listeners + * are additive, so your own `addAdEventListener` calls keep working. + */ +function trackAd( + ad: TrackableAd, + adFormat: AdFormat, + placement: string | null | undefined, + pinnedImpressionId: string | null = null +): TrackedAdState { + const state = setState( + ad, + new TrackedAdState(adFormat, ad.adUnitId, placement, pinnedImpressionId) + ); + const rewarded = + ad instanceof RewardedAd || ad instanceof RewardedInterstitialAd; + + ad.addAdEventsListener(({ type, payload }) => { + switch (type) { + case AdEventType.LOADED: + case RewardedAdEventType.LOADED: + if (type === AdEventType.LOADED && rewarded) { + return; + } + state.loadedOnce = true; + state.updateFromResponse(ad.responseInfo); + AdMobTracker.trackLoaded(state); + return; + case AdEventType.ERROR: { + const error = payload as + | { phase?: string; reason?: string } + | undefined; + if (error?.phase === "show") { + return; + } + AdMobTracker.trackFailedToLoad( + ad.adUnitId, + adFormat, + state.loadPlacement, + error?.reason + ); + return; + } + case AdEventType.IMPRESSION: + AdMobTracker.trackDisplayed(state); + return; + case AdEventType.CLICKED: + AdMobTracker.trackOpened(state); + return; + case AdEventType.PAID: + AdMobTracker.trackRevenue(state, payload as PaidEvent); + return; + case RewardedAdEventType.EARNED_REWARD: + // With verification enabled the core SDK reports earning from the poll. + if (!state.clientTransactionId) { + AdMobTracker.trackRewardEarnedUnverified(state); + } + return; + default: + return; + } + }); + return state; +} + +async function createRewarded( + create: (requestOptions: RequestOptions) => T, + adFormat: AdFormat, + options: RewardedTrackingOptions +): Promise { + let requestOptions = options.requestOptions ?? {}; + let pinnedImpressionId: string | null = null; + let clientTransactionId: string | null = null; + + if (options.enableRewardVerification) { + pinnedImpressionId = generateImpressionId(); + try { + const token = await Purchases.generateRewardVerificationToken( + pinnedImpressionId + ); + clientTransactionId = token.clientTransactionId; + requestOptions = { + ...requestOptions, + serverSideVerificationOptions: { + userId: token.appUserID, + customData: token.customData, + }, + }; + } catch (e) { + logWarning(`Could not enable reward verification: ${e}`); + pinnedImpressionId = null; + } + } + + const ad = create(requestOptions); + const state = trackAd(ad, adFormat, options.placement, pinnedImpressionId); + state.clientTransactionId = clientTransactionId; + if (pinnedImpressionId) { + preventReload(ad, state); + } + return ad; +} + +/** + * The SSV token travels with the request options, which the library reuses + * and attaches natively on every successful load, so a reload after the ad + * has loaded would send the already used token to AdMob. Shadow `load` on + * the instance so it is ignored once the ad has loaded; a retry after a load + * error never consumed the token and still goes through. + */ +function preventReload(ad: TrackableAd, state: TrackedAdState): void { + const load = ad.load.bind(ad); + ad.load = () => { + if (state.loadedOnce) { + logWarning( + "Reward verification tokens are single-use; load() was ignored. " + + "Create a new ad through createRewardedAd for each verified show." + ); + return; + } + load(); + }; +} + +function trackedBannerProps( + state: TrackedAdState, + props: BannerAdProps +): BannerAdProps { + return { + ...props, + onAdLoaded: (dimensions) => { + state.updateFromResponse(dimensions.responseInfo); + AdMobTracker.trackLoaded(state); + props.onAdLoaded?.(dimensions); + }, + onAdFailedToLoad: (error) => { + AdMobTracker.trackFailedToLoad( + props.unitId, + AdFormat.banner, + state.loadPlacement, + error.reason + ); + props.onAdFailedToLoad?.(error); + }, + onAdImpression: () => { + AdMobTracker.trackDisplayed(state); + props.onAdImpression?.(); + }, + onAdClicked: () => { + AdMobTracker.trackOpened(state); + props.onAdClicked?.(); + }, + onPaid: (paid) => { + AdMobTracker.trackRevenue(state, paid); + props.onPaid?.(paid); + }, + }; +} + +/** + * Returns `BannerAd` props that report to RevenueCat, forwarding to the + * props you pass in. Spread the result into ``. + * The tracking state lives for the lifetime of the calling component, so + * rerenders keep the impression id of the banner that loaded. + * + * @example + * ```tsx + * function HomeBanner() { + * const bannerProps = useTrackingBannerAdProps({ + * unitId, + * size: BannerAdSize.BANNER, + * placement: "home_bottom", + * }); + * return ; + * } + * ``` + */ +export function useTrackingBannerAdProps( + props: BannerAdTrackingProps +): BannerAdProps { + const { placement, ...rest } = props; + const state = useRef(null); + if (state.current === null) { + state.current = new TrackedAdState( + AdFormat.banner, + props.unitId, + placement + ); + } + return trackedBannerProps(state.current, rest); +} + +function prepareShow( + ad: TrackableAd, + placement?: string | null +): TrackedAdState | undefined { + const state = stateFor(ad); + if (!state) { + logWarning( + "This ad was not created through RevenueCatAdMob; it will not be tracked." + ); + return undefined; + } + if (placement != null) { + state.showPlacement = placement; + } + return state; +} + +/** + * Entry point of the RevenueCat AdMob adapter for React Native. + * + * Create full-screen ads through `create...` instead of + * `createForAdRequest`, then `load()` and show them through + * `showAndTrack` / `showWithRewardVerification`. Banner components spread + * `useTrackingBannerAdProps(...)`; native ads go through `trackNativeAd`. + */ +export const RevenueCatAdMob = { + /** + * Creates an interstitial ad whose loaded, displayed, opened, revenue and + * failed-to-load events are reported to RevenueCat. Use it in place of + * `InterstitialAd.createForAdRequest`, then `load()` and show it through + * `showAndTrack`. + * + * @example + * ```typescript + * const interstitial = RevenueCatAdMob.createInterstitialAd(adUnitId, { + * placement: "level_complete", + * }); + * interstitial.addAdEventListener(AdEventType.LOADED, () => setReady(true)); + * interstitial.load(); + * // Later + * await RevenueCatAdMob.showAndTrack(interstitial); + * ``` + */ + createInterstitialAd( + adUnitId: string, + options: TrackingOptions = {} + ): InterstitialAd { + const ad = InterstitialAd.createForAdRequest( + adUnitId, + options.requestOptions + ); + trackAd(ad, AdFormat.interstitial, options.placement); + return ad; + }, + + /** + * Creates an app open ad tracked by RevenueCat. Use it in place of + * `AppOpenAd.createForAdRequest`, then `load()` and show it through + * `showAndTrack`. + * + * @example + * ```typescript + * const appOpen = RevenueCatAdMob.createAppOpenAd(adUnitId, { + * placement: "cold_start", + * }); + * appOpen.load(); + * // When the app comes to the foreground + * await RevenueCatAdMob.showAndTrack(appOpen); + * ``` + */ + createAppOpenAd(adUnitId: string, options: TrackingOptions = {}): AppOpenAd { + const ad = AppOpenAd.createForAdRequest(adUnitId, options.requestOptions); + trackAd(ad, AdFormat.appOpen, options.placement); + return ad; + }, + + /** + * Creates a rewarded ad tracked by RevenueCat. Use it in place of + * `RewardedAd.createForAdRequest`. With `enableRewardVerification` the + * adapter requests a verification token first, which is why this resolves + * asynchronously; show such ads through `showWithRewardVerification`. + * + * @example + * ```typescript + * const rewarded = await RevenueCatAdMob.createRewardedAd(adUnitId, { + * placement: "extra_life", + * enableRewardVerification: true, + * }); + * rewarded.load(); + * // Later + * await RevenueCatAdMob.showWithRewardVerification(rewarded, { + * onRewardVerificationCompleted: (result) => { + * if (!result.failed) grant(result.reward); + * }, + * }); + * ``` + */ + createRewardedAd( + adUnitId: string, + options: RewardedTrackingOptions = {} + ): Promise { + return createRewarded( + (requestOptions) => + RewardedAd.createForAdRequest(adUnitId, requestOptions), + AdFormat.rewarded, + options + ); + }, + + /** + * Creates a rewarded interstitial ad tracked by RevenueCat. Use it in place + * of `RewardedInterstitialAd.createForAdRequest`; otherwise identical to + * `createRewardedAd`. + * + * @example + * ```typescript + * const ad = await RevenueCatAdMob.createRewardedInterstitialAd(adUnitId, { + * placement: "chapter_end", + * }); + * ad.load(); + * // Later + * await RevenueCatAdMob.showAndTrack(ad); + * ``` + */ + createRewardedInterstitialAd( + adUnitId: string, + options: RewardedTrackingOptions = {} + ): Promise { + return createRewarded( + (requestOptions) => + RewardedInterstitialAd.createForAdRequest(adUnitId, requestOptions), + AdFormat.rewardedInterstitial, + options + ); + }, + + /** + * Attaches tracking to a full-screen ad you created yourself. Call before + * `load()`. Reward verification is only available for ads created through + * `createRewardedAd` / `createRewardedInterstitialAd`. + */ + trackAd(ad: TrackableAd, options: TrackingOptions = {}): void { + const adFormat = formatOf(ad); + if (!adFormat) { + logWarning("Unsupported ad type; it will not be tracked."); + return; + } + trackAd(ad, adFormat, options.placement); + }, + + /** + * Shows a tracked full-screen ad, optionally overriding its placement. + * + * @example + * ```typescript + * await RevenueCatAdMob.showAndTrack(interstitial, { + * placement: "level_complete_retry", + * }); + * ``` + */ + showAndTrack(ad: TrackableAd, options: ShowOptions = {}): Promise { + prepareShow(ad, options.placement); + return ad.show(options.showOptions); + }, + + /** + * Shows a rewarded ad and verifies the earned reward with RevenueCat. + * `onRewardVerificationCompleted` is called at most once per show, after + * the user earns the reward; it is not called when the ad is dismissed or + * fails before a reward. It receives a failed result when the ad was + * created without `enableRewardVerification`. + * + * @example + * ```typescript + * await RevenueCatAdMob.showWithRewardVerification(rewarded, { + * onRewardVerificationStarted: () => showSpinner(), + * onRewardVerificationCompleted: (result) => { + * if (result.failed) return showError(); + * grant(result.reward); + * }, + * }); + * ``` + */ + showWithRewardVerification( + ad: TrackableAd, + options: ShowWithRewardVerificationOptions + ): Promise { + const state = prepareShow(ad, options.placement); + if (state) { + state.rewardVerificationDelivered = false; + } + + const unsubscribe = ad.addAdEventListener( + RewardedAdEventType.EARNED_REWARD, + (reward: RewardedAdReward) => { + options.onUserEarnedReward?.(reward); + options.onRewardVerificationStarted?.(); + + const deliver = (result: RewardVerificationResult) => { + if (state?.rewardVerificationDelivered) { + return; + } + if (state) { + state.rewardVerificationDelivered = true; + } + options.onRewardVerificationCompleted(result); + }; + + const clientTransactionId = state?.clientTransactionId; + if (!state || !clientTransactionId) { + logWarning( + "Reward earned but reward verification was not enabled for this ad. " + + "Create it with enableRewardVerification: true." + ); + deliver(failedResult); + return; + } + Purchases.pollRewardVerification( + clientTransactionId, + state.trackingMetadata + ) + .then(deliver) + .catch((e) => { + logWarning(`Reward verification failed: ${e}`); + deliver(failedResult); + }); + } + ); + const unsubscribeAll = () => { + unsubscribe(); + unsubscribeOnClose(); + unsubscribeOnError(); + }; + const unsubscribeOnClose = ad.addAdEventListener( + AdEventType.CLOSED, + unsubscribeAll + ); + const unsubscribeOnError = ad.addAdEventListener( + AdEventType.ERROR, + unsubscribeAll + ); + const shown = ad.show(options.showOptions); + // A rejected show never emits CLOSED, so the listeners would outlive it. + shown.catch(unsubscribeAll); + return shown; + }, + + /** + * Returns `BannerAd` props that report to RevenueCat, forwarding to the + * props you pass in. Spread the result into ``. + * Each call starts a new tracking state, so call it once per banner + * instance (for example in a class component's constructor), never inside + * `render`. Function components should use `useTrackingBannerAdProps` instead. + * + * @example + * ```tsx + * class HomeBanner extends React.Component { + * bannerProps = RevenueCatAdMob.trackingBannerAdProps({ + * unitId, + * size: BannerAdSize.BANNER, + * placement: "home_bottom", + * }); + * render() { + * return ; + * } + * } + * ``` + */ + trackingBannerAdProps(props: BannerAdTrackingProps): BannerAdProps { + const { placement, ...rest } = props; + return trackedBannerProps( + new TrackedAdState(AdFormat.banner, props.unitId, placement), + rest + ); + }, + + /** + * Tracks a loaded native ad. `NativeAd.createForAdRequest` resolves with a + * loaded ad, so the loaded event is reported immediately. + * + * @example + * ```typescript + * const nativeAd = await NativeAd.createForAdRequest(adUnitId); + * RevenueCatAdMob.trackNativeAd(nativeAd, { placement: "feed" }); + * ``` + */ + trackNativeAd( + ad: NativeAd, + options: { placement?: string | null } = {} + ): void { + const state = setState( + ad, + new TrackedAdState(AdFormat.nativeAd, ad.adUnitId, options.placement) + ); + state.updateFromResponse( + ad.responseInfo ?? ({ responseId: ad.responseId } as ResponseInfo) + ); + AdMobTracker.trackLoaded(state); + ad.addAdEventListener(NativeAdEventType.IMPRESSION, () => + AdMobTracker.trackDisplayed(state) + ); + ad.addAdEventListener(NativeAdEventType.CLICKED, () => + AdMobTracker.trackOpened(state) + ); + ad.addAdEventListener(NativeAdEventType.PAID, (paid) => + AdMobTracker.trackRevenue(state, paid as unknown as PaidEvent) + ); + }, + + /** The impression id the adapter uses for a tracked ad, once known. */ + impressionIdOf(ad: object): string | null { + return stateFor(ad)?.impressionId ?? null; + }, +}; + +export default RevenueCatAdMob; diff --git a/react-native-purchases-admob/src/state.ts b/react-native-purchases-admob/src/state.ts new file mode 100644 index 000000000..4914ca41f --- /dev/null +++ b/react-native-purchases-admob/src/state.ts @@ -0,0 +1,109 @@ +import { AdCaptureMethod, AdMediatorName } from "react-native-purchases"; +import type { + AdFormat, + RewardedAdTrackingMetadata, +} from "react-native-purchases"; +import type { ResponseInfo } from "react-native-google-mobile-ads"; + +/** + * Per-ad bookkeeping, kept in a weak side table so the adapter never changes + * the lifetime of the `react-native-google-mobile-ads` objects it tracks. + */ +export class TrackedAdState { + loadPlacement: string | null; + showPlacement: string | null = null; + /** + * Either AdMob's response id (read once the ad loads) or, for ads created + * with reward verification, the id generated before the request so the SSV + * token and every tracking event share one impression id. + */ + impressionId: string = ""; + networkName: string | null = null; + clientTransactionId: string | null = null; + rewardVerificationDelivered = false; + loadedOnce = false; + + constructor( + readonly adFormat: AdFormat, + readonly adUnitId: string, + placement?: string | null, + public pinnedImpressionId: string | null = null + ) { + this.loadPlacement = placement ?? null; + if (pinnedImpressionId) { + this.impressionId = pinnedImpressionId; + } + } + + get placement(): string | null { + return this.showPlacement ?? this.loadPlacement; + } + + updateFromResponse(info: ResponseInfo | null | undefined): void { + if (!this.pinnedImpressionId) { + this.impressionId = info?.responseId ?? ""; + } + this.networkName = + info?.loadedAdapterResponse?.adapterClassName ?? + info?.adapterClassName ?? + null; + } + + get trackingMetadata(): RewardedAdTrackingMetadata { + return { + networkName: this.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: this.adFormat, + placement: this.placement, + adUnitId: this.adUnitId, + impressionId: this.impressionId, + captureMethod: AdCaptureMethod.reactNativeAdMobAdapter, + } as RewardedAdTrackingMetadata; + } +} + +const states = new WeakMap(); + +export function stateFor(ad: object): TrackedAdState | undefined { + return states.get(ad); +} + +export function setState(ad: object, state: TrackedAdState): TrackedAdState { + states.set(ad, state); + return state; +} + +/** + * UUID v4. Uses `crypto` when the runtime or a polyfill such as + * `react-native-get-random-values` provides it; Hermes has none by default, + * so it falls back to `Math.random`, which is enough for a correlation key. + */ +interface CryptoLike { + randomUUID?: () => string; + getRandomValues?: (array: Uint8Array) => Uint8Array; +} + +export function generateImpressionId(): string { + const cryptoObj = (globalThis as { crypto?: CryptoLike }).crypto; + if (cryptoObj?.randomUUID) { + return cryptoObj.randomUUID(); + } + const bytes = new Uint8Array(16); + if (cryptoObj?.getRandomValues) { + cryptoObj.getRandomValues(bytes); + } else { + for (let i = 0; i < bytes.length; i++) { + bytes[i] = Math.floor(Math.random() * 256); + } + } + bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; + bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")); + return [ + hex.slice(0, 4).join(""), + hex.slice(4, 6).join(""), + hex.slice(6, 8).join(""), + hex.slice(8, 10).join(""), + hex.slice(10, 16).join(""), + ].join("-"); +} diff --git a/react-native-purchases-admob/src/tracker.ts b/react-native-purchases-admob/src/tracker.ts new file mode 100644 index 000000000..1b77b4d57 --- /dev/null +++ b/react-native-purchases-admob/src/tracker.ts @@ -0,0 +1,200 @@ +import Purchases, { + AdCaptureMethod, + AdMediatorName, + AdRevenuePrecision, +} from "react-native-purchases"; +import type { + AdDisplayedData, + AdFailedToLoadData, + AdFormat, + AdLoadedData, + AdOpenedData, + AdRevenueData, + AdRewardEarnedUnverifiedData, +} from "react-native-purchases"; +import type { PaidEvent } from "react-native-google-mobile-ads"; +import { Platform } from "react-native"; + +import { TrackedAdState } from "./state"; + +export function logWarning(message: string): void { + // tslint:disable-next-line:no-console + console.warn(`[react-native-purchases-admob] ${message}`); +} + +// The data types mark this field @internal, hence the assertions below. +const captureMethod = AdCaptureMethod.reactNativeAdMobAdapter; + +/** + * `react-native-google-mobile-ads` reports load failures with a string reason + * rather than the platform SDK's numeric error code, and the two SDKs number + * their codes differently. Each table inverts the library's own native mapping + * for that platform (ReactNativeGoogleMobileAdsCommon.java and + * RNGoogleMobileAdsOwnedMappers.m), so the emitted number matches what the + * native integration on the same platform reports. + */ +const androidErrorCodes: Record = { + "internal-error": 0, + "invalid-request": 1, + "network-error": 2, + "no-fill": 3, + "app-id-missing": 8, + "mediation-no-fill": 9, + "request-id-mismatch": 10, + "invalid-ad-string": 11, +}; + +const iosErrorCodes: Record = { + "invalid-request": 0, + "no-fill": 1, + "network-error": 2, + "server-error": 3, + timeout: 5, + "mediation-data-error": 7, + "mediation-adapter-error": 8, + "mediation-invalid-ad-size": 10, + "internal-error": 11, + "invalid-argument": 12, + "ad-already-used": 19, + "app-id-missing": 20, + "invalid-ad-string": 21, +}; + +export function mediatorErrorCode(reason: string | undefined): number | null { + if (!reason) { + return null; + } + const table = Platform.OS === "ios" ? iosErrorCodes : androidErrorCodes; + const mapped = table[reason]; + if (mapped !== undefined) { + return mapped; + } + const numeric = Number(reason); + return Number.isInteger(numeric) ? numeric : null; +} + +export function revenueMicrosFrom(paid: PaidEvent): number { + if (paid.valueMicros != null) { + const micros = Number(paid.valueMicros); + if (Number.isFinite(micros)) { + return Math.round(micros); + } + } + return Math.round(paid.value * 1_000_000); +} + +export function precisionFrom(precision: number): AdRevenuePrecision { + switch (precision) { + case 1: + return AdRevenuePrecision.estimated; + case 2: + return AdRevenuePrecision.publisherDefined; + case 3: + return AdRevenuePrecision.exact; + default: + return AdRevenuePrecision.unknown; + } +} + +function swallow(event: string, promise: Promise): void { + promise.catch((e) => logWarning(`Could not track ${event}: ${e}`)); +} + +export const AdMobTracker = { + trackLoaded(state: TrackedAdState): void { + swallow( + "ad loaded", + Purchases.adTracker.trackAdLoaded({ + networkName: state.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: state.adFormat, + placement: state.loadPlacement, + adUnitId: state.adUnitId, + impressionId: state.impressionId, + captureMethod, + } as AdLoadedData) + ); + }, + + trackFailedToLoad( + adUnitId: string, + adFormat: AdFormat, + placement: string | null, + reason: string | undefined + ): void { + swallow( + "ad failed to load", + Purchases.adTracker.trackAdFailedToLoad({ + mediatorName: AdMediatorName.adMob, + adFormat, + placement, + adUnitId, + mediatorErrorCode: mediatorErrorCode(reason), + captureMethod, + } as AdFailedToLoadData) + ); + }, + + trackDisplayed(state: TrackedAdState): void { + swallow( + "ad displayed", + Purchases.adTracker.trackAdDisplayed({ + networkName: state.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: state.adFormat, + placement: state.placement, + adUnitId: state.adUnitId, + impressionId: state.impressionId, + captureMethod, + } as AdDisplayedData) + ); + }, + + trackOpened(state: TrackedAdState): void { + swallow( + "ad opened", + Purchases.adTracker.trackAdOpened({ + networkName: state.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: state.adFormat, + placement: state.placement, + adUnitId: state.adUnitId, + impressionId: state.impressionId, + captureMethod, + } as AdOpenedData) + ); + }, + + trackRewardEarnedUnverified(state: TrackedAdState): void { + swallow( + "reward earned", + Purchases.adTracker.trackAdRewardEarnedUnverified({ + networkName: state.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: state.adFormat, + placement: state.placement, + adUnitId: state.adUnitId, + impressionId: state.impressionId, + captureMethod, + } as AdRewardEarnedUnverifiedData) + ); + }, + + trackRevenue(state: TrackedAdState, paid: PaidEvent): void { + swallow( + "ad revenue", + Purchases.adTracker.trackAdRevenue({ + networkName: state.networkName, + mediatorName: AdMediatorName.adMob, + adFormat: state.adFormat, + placement: state.placement, + adUnitId: state.adUnitId, + impressionId: state.impressionId, + revenueMicros: revenueMicrosFrom(paid), + currency: paid.currency, + precision: precisionFrom(paid.precision), + captureMethod, + } as AdRevenueData) + ); + }, +}; diff --git a/react-native-purchases-admob/tsconfig.build.json b/react-native-purchases-admob/tsconfig.build.json new file mode 100644 index 000000000..376af06cd --- /dev/null +++ b/react-native-purchases-admob/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig", + "exclude": [] +} diff --git a/react-native-purchases-admob/tsconfig.json b/react-native-purchases-admob/tsconfig.json new file mode 100644 index 000000000..a76de45c3 --- /dev/null +++ b/react-native-purchases-admob/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "rootDir": ".", + "paths": { + "react-native-purchases": ["../dist/index"], + "react-native-purchases-admob": ["./src/index"] + }, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "lib": ["esnext", "dom"], + "module": "esnext", + "moduleResolution": "node", + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "noImplicitUseStrict": false, + "noStrictGenericChecks": false, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "strict": true, + "target": "esnext", + "verbatimModuleSyntax": true + }, + "include": ["src"], + "exclude": ["node_modules", "lib", "apitesters"] +} diff --git a/react-native-purchases-admob/tsconfig.test.json b/react-native-purchases-admob/tsconfig.test.json new file mode 100644 index 000000000..560e1af1c --- /dev/null +++ b/react-native-purchases-admob/tsconfig.test.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "verbatimModuleSyntax": false, + "module": "commonjs" + }, + "include": ["src", "__tests__"] +} diff --git a/react-native-purchases-admob/tslint.json b/react-native-purchases-admob/tslint.json new file mode 100644 index 000000000..5e11b83c4 --- /dev/null +++ b/react-native-purchases-admob/tslint.json @@ -0,0 +1,21 @@ +{ + "defaultSeverity": "error", + "extends": ["tslint:recommended", "tslint-config-prettier"], + "jsRules": {}, + "rules": { + "ordered-imports": false, + "object-literal-sort-keys": false, + "arrow-parens": false, + "interface-name": false, + "no-empty": false, + "jsx-no-lambda": false, + "jsx-boolean-value": false, + "no-empty-interface": false, + "interface-over-type-literal": false, + "trailing-comma": true + }, + "rulesDirectory": [], + "linterOptions": { + "exclude": ["**/*.test.ts"] + } +} diff --git a/src/purchases.ts b/src/purchases.ts index fedb2d702..25392e087 100644 --- a/src/purchases.ts +++ b/src/purchases.ts @@ -222,6 +222,16 @@ export const AdRevenuePrecision = { } as const; export type AdRevenuePrecision = string; +/** + * Identifies the integration that emitted an ad event. Reserved for the + * official RevenueCat ad-network adapters (for example + * `react-native-purchases-admob`); leave it unset when tracking manually. + */ +export const AdCaptureMethod = { + reactNativeAdMobAdapter: "react_native_admob_adapter", +} as const; +export type AdCaptureMethod = string; + export interface AdDisplayedData { mediatorName: AdMediatorName; adFormat: AdFormat; @@ -229,6 +239,8 @@ export interface AdDisplayedData { impressionId: string; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdOpenedData { @@ -238,6 +250,8 @@ export interface AdOpenedData { impressionId: string; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdLoadedData { @@ -247,6 +261,8 @@ export interface AdLoadedData { impressionId: string; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdRevenueData { @@ -259,6 +275,8 @@ export interface AdRevenueData { precision: AdRevenuePrecision; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdFailedToLoadData { @@ -267,6 +285,8 @@ export interface AdFailedToLoadData { adUnitId: string; mediatorErrorCode?: number | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdRewardEarnedUnverifiedData { @@ -276,6 +296,8 @@ export interface AdRewardEarnedUnverifiedData { impressionId: string; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } export interface AdRewardPromptShownData { @@ -358,6 +380,8 @@ export interface RewardedAdTrackingMetadata { impressionId: string; networkName?: string | null; placement?: string | null; + /** @internal Reserved for the official RevenueCat ad-network adapters. */ + captureMethod?: AdCaptureMethod | null; } let debugEventListeners: DebugEventListener[] = []; @@ -534,7 +558,7 @@ export default class Purchases { */ public static PURCHASES_ARE_COMPLETED_BY_TYPE = PURCHASES_ARE_COMPLETED_BY_TYPE; - + public static UninitializedPurchasesError = UninitializedPurchasesError; public static UnsupportedPlatformError = UnsupportedPlatformError; @@ -1137,7 +1161,7 @@ export default class Purchases { } /** - * Removes a given TrackedEventListener. + * Removes a given TrackedEventListener. * This is a debug API not meant for public use. * @internal * @param trackedEventListener TrackedEvent listener to remove @@ -1170,9 +1194,9 @@ export default class Purchases { } } } - + /** - * Removes a given DebugEventListener. + * Removes a given DebugEventListener. * This is a debug API not meant for public use. * @internal * @param debugEventListener DebugEventListener listener to remove diff --git a/yarn.lock b/yarn.lock index 5f2ebe38b..2b793d0a9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3448,6 +3448,13 @@ __metadata: languageName: node linkType: hard +"@babel/runtime@npm:^7.12.5": + version: 7.29.10 + resolution: "@babel/runtime@npm:7.29.10" + checksum: b0ea4fdc84105e46d4a22fe6af7f835397294b0291795f9c0c3e1ad917a5bfdbd38914ea717007e12904ec4ccb8b5a4b05a1acd45ccae3e424cdc0ef2df4912a + languageName: node + linkType: hard + "@babel/runtime@npm:^7.25.0, @babel/runtime@npm:^7.8.4": version: 7.26.9 resolution: "@babel/runtime@npm:7.26.9" @@ -3613,6 +3620,13 @@ __metadata: languageName: node linkType: hard +"@iabtcf/core@npm:^1.5.6": + version: 1.5.6 + resolution: "@iabtcf/core@npm:1.5.6" + checksum: 561626b626ee476dea5dd3a6ed0ebc26caac2475fc9509583f0e66c92ad67c3a2c2816b3516a4f043904b40607c9a4d44cbacbf09a5897740fd273e057c02c2c + languageName: node + linkType: hard + "@isaacs/cliui@npm:^8.0.2": version: 8.0.2 resolution: "@isaacs/cliui@npm:8.0.2" @@ -5225,6 +5239,15 @@ __metadata: languageName: node linkType: hard +"@types/react-test-renderer@npm:^18.0.7": + version: 18.3.1 + resolution: "@types/react-test-renderer@npm:18.3.1" + dependencies: + "@types/react": ^18 + checksum: f8cc23cc8decdb6068cdc8f8c306e189eab8e569443ce97b216e757ee42eb20b18d2280ef41e2955668413f14be92765a3ba86cfcfeeae6b20c965acd9674786 + languageName: node + linkType: hard + "@types/react@npm:18.2.44": version: 18.2.44 resolution: "@types/react@npm:18.2.44" @@ -6546,6 +6569,13 @@ __metadata: languageName: node linkType: hard +"dequal@npm:^2.0.2": + version: 2.0.3 + resolution: "dequal@npm:2.0.3" + checksum: 8679b850e1a3d0ebbc46ee780d5df7b478c23f335887464023a631d1b9af051ad4a6595a44220f9ff8ff95a8ddccf019b5ad778a976fd7bbf77383d36f412f90 + languageName: node + linkType: hard + "destroy@npm:1.2.0": version: 1.2.0 resolution: "destroy@npm:1.2.0" @@ -9656,6 +9686,13 @@ __metadata: languageName: node linkType: hard +"object-assign@npm:^4.1.1": + version: 4.1.1 + resolution: "object-assign@npm:4.1.1" + checksum: fcc6e4ea8c7fe48abfbb552578b1c53e0d194086e2e6bbbf59e0a536381a292f39943c6e9628af05b5528aa5e3318bb30d6b2e53cadaf5b8fe9e12c4b69af23f + languageName: node + linkType: hard + "object-inspect@npm:^1.13.3, object-inspect@npm:^1.13.4": version: 1.13.4 resolution: "object-inspect@npm:1.13.4" @@ -10190,6 +10227,13 @@ __metadata: languageName: node linkType: hard +"react-is@npm:^16.12.0 || ^17.0.0 || ^18.0.0, react-is@npm:^18.0.0, react-is@npm:^18.2.0": + version: 18.3.1 + resolution: "react-is@npm:18.3.1" + checksum: e20fe84c86ff172fc8d898251b7cc2c43645d108bf96d0b8edf39b98f9a2cae97b40520ee7ed8ee0085ccc94736c4886294456033304151c3f94978cec03df21 + languageName: node + linkType: hard + "react-is@npm:^16.13.0": version: 16.13.1 resolution: "react-is@npm:16.13.1" @@ -10204,13 +10248,6 @@ __metadata: languageName: node linkType: hard -"react-is@npm:^18.0.0": - version: 18.3.1 - resolution: "react-is@npm:18.3.1" - checksum: e20fe84c86ff172fc8d898251b7cc2c43645d108bf96d0b8edf39b98f9a2cae97b40520ee7ed8ee0085ccc94736c4886294456033304151c3f94978cec03df21 - languageName: node - linkType: hard - "react-is@npm:^19.1.0": version: 19.2.4 resolution: "react-is@npm:19.2.4" @@ -10251,6 +10288,23 @@ __metadata: languageName: node linkType: hard +"react-native-google-mobile-ads@npm:^17.0.0": + version: 17.2.0 + resolution: "react-native-google-mobile-ads@npm:17.2.0" + dependencies: + "@iabtcf/core": ^1.5.6 + use-deep-compare-effect: ^1.8.1 + peerDependencies: + expo: ">=47.0.0" + react: "*" + react-native: ">=0.86.0" + peerDependenciesMeta: + expo: + optional: true + checksum: 62e676f0d139320198b44d38796b98ec29aa56fdfa206b1fc372af34e5f947b2fd281d9740ab6cfea8231d78e43dbf1af2eed68de9a25f9c51fdd0e1c58051e7 + languageName: node + linkType: hard + "react-native-is-edge-to-edge@npm:^1.1.7": version: 1.1.7 resolution: "react-native-is-edge-to-edge@npm:1.1.7" @@ -10261,6 +10315,34 @@ __metadata: languageName: node linkType: hard +"react-native-purchases-admob@workspace:react-native-purchases-admob": + version: 0.0.0-use.local + resolution: "react-native-purchases-admob@workspace:react-native-purchases-admob" + dependencies: + "@types/jest": ^29.5.12 + "@types/react": ^18.2.44 + "@types/react-dom": ~18.2.0 + "@types/react-test-renderer": ^18.0.7 + jest: ^29.7.0 + jest-react-native: ^18.0.0 + prettier: ^2.0.5 + react: 18.2.0 + react-native: 0.78.0 + react-native-builder-bob: ^0.20.0 + react-native-google-mobile-ads: ^17.0.0 + react-test-renderer: 18.2.0 + ts-jest: ^29.1.2 + tslint: ^5.20.0 + tslint-config-prettier: ^1.18.0 + typescript: ^5.2.2 + peerDependencies: + react: "*" + react-native: ">= 0.76.0" + react-native-google-mobile-ads: ">= 17.0.0 < 18.0.0" + react-native-purchases: 10.14.0 + languageName: unknown + linkType: soft + "react-native-purchases-store-galaxy@10.14.0, react-native-purchases-store-galaxy@workspace:react-native-purchases-store-galaxy": version: 0.0.0-use.local resolution: "react-native-purchases-store-galaxy@workspace:react-native-purchases-store-galaxy" @@ -10509,6 +10591,31 @@ __metadata: languageName: node linkType: hard +"react-shallow-renderer@npm:^16.15.0": + version: 16.15.0 + resolution: "react-shallow-renderer@npm:16.15.0" + dependencies: + object-assign: ^4.1.1 + react-is: ^16.12.0 || ^17.0.0 || ^18.0.0 + peerDependencies: + react: ^16.0.0 || ^17.0.0 || ^18.0.0 + checksum: 6052c7e3e9627485120ebd8257f128aad8f56386fe8d42374b7743eac1be457c33506d153c7886b4e32923c0c352d402ab805ef9ca02dbcd8393b2bdeb6e5af8 + languageName: node + linkType: hard + +"react-test-renderer@npm:18.2.0": + version: 18.2.0 + resolution: "react-test-renderer@npm:18.2.0" + dependencies: + react-is: ^18.2.0 + react-shallow-renderer: ^16.15.0 + scheduler: ^0.23.0 + peerDependencies: + react: ^18.2.0 + checksum: 6b6980ced93fa2b72662d5e4ab3b4896833586940047ce52ca9aca801e5432adf05fcbe28289b0af3ce6a2a7c590974e25dcc8aa43d0de658bfe8bbcd686f958 + languageName: node + linkType: hard + "react@npm:18.2.0": version: 18.2.0 resolution: "react@npm:18.2.0" @@ -10861,6 +10968,15 @@ __metadata: languageName: node linkType: hard +"scheduler@npm:^0.23.0": + version: 0.23.2 + resolution: "scheduler@npm:0.23.2" + dependencies: + loose-envify: ^1.1.0 + checksum: 3e82d1f419e240ef6219d794ff29c7ee415fbdc19e038f680a10c067108e06284f1847450a210b29bbaf97b9d8a97ced5f624c31c681248ac84c80d56ad5a2c4 + languageName: node + linkType: hard + "selfsigned@npm:^2.4.1": version: 2.4.1 resolution: "selfsigned@npm:2.4.1" @@ -11805,6 +11921,18 @@ __metadata: languageName: node linkType: hard +"use-deep-compare-effect@npm:^1.8.1": + version: 1.8.1 + resolution: "use-deep-compare-effect@npm:1.8.1" + dependencies: + "@babel/runtime": ^7.12.5 + dequal: ^2.0.2 + peerDependencies: + react: ">=16.13" + checksum: 2b9b6291df3f772f44d259b352e5d998963ccee0db2efeb76bb05525d928064aeeb69bb0dee5a5e428fea7cf3db67c097a770ebd30caa080662b565f6ef02b2e + languageName: node + linkType: hard + "use-latest-callback@npm:^0.2.1": version: 0.2.4 resolution: "use-latest-callback@npm:0.2.4"