@chipmobilesdk/rn-ads 0.5.0 → 0.6.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.
@@ -1,57 +1,56 @@
1
- /**
2
- * Instance context (US1).
3
- *
4
- * Supplies one `AdsInstance` to the tree so `AdsBanner` and the hooks can reach
5
- * it without every screen threading it through props.
6
- *
7
- * The provider does not create the instance. The app does, and passes it in —
8
- * because `createAds` throws on a misconfigured catalog (FR-008, FR-012), and a
9
- * throw during render is a far worse place to discover that than a throw at
10
- * startup where the app can decide what to do about it.
11
- */
12
-
13
- import React, { createContext, useContext, useEffect, type ReactNode } from 'react';
14
- import { AppState, type AppStateStatus } from 'react-native';
15
-
16
- import type { AdsInstance } from '../core/adsInstance';
17
-
18
- const AdsContext = createContext<AdsInstance | null>(null);
19
-
20
- export interface AdsProviderProps {
21
- readonly instance: AdsInstance;
22
- /**
23
- * Whether the provider forwards foreground/background transitions to the
24
- * instance. On by default: FR-034's "never show while inactive" and
25
- * "re-evaluate a stale ad on return" both depend on the instance being told.
26
- * Turn it off only when the app already drives `setAppActive` itself.
27
- */
28
- readonly trackAppState?: boolean;
29
- readonly children: ReactNode;
30
- }
31
-
32
- export function AdsProvider({ instance, trackAppState = true, children }: AdsProviderProps) {
33
- useEffect(() => {
34
- if (!trackAppState) {
35
- return;
36
- }
37
- const subscription = AppState.addEventListener('change', (status: AppStateStatus) => {
38
- instance.setAppActive(status === 'active');
39
- });
40
- return () => {
41
- subscription.remove();
42
- };
43
- }, [instance, trackAppState]);
44
-
45
- return <AdsContext.Provider value={instance}>{children}</AdsContext.Provider>;
46
- }
47
-
48
- /**
49
- * Returns the instance, or null outside a provider.
50
- *
51
- * Null rather than a throw on purpose: a screen that renders a banner should
52
- * degrade to rendering nothing when ads are not wired up, not take the screen
53
- * down with it (NFR-005).
54
- */
55
- export function useAds(): AdsInstance | null {
56
- return useContext(AdsContext);
57
- }
1
+ /**
2
+ * Instance context (US1).
3
+ *
4
+ * Supplies one `AdsInstance` to the tree so `AdsBanner` and the hooks can reach
5
+ * it without every screen threading it through props.
6
+ *
7
+ * The provider does not create the instance. The app does, and passes it in —
8
+ * because `createAds` throws on a misconfigured catalog (FR-008, FR-012), and a
9
+ * throw during render is a far worse place to discover that than a throw at
10
+ * startup where the app can decide what to do about it.
11
+ */
12
+
13
+ import { appLifecycle } from '@chipmobilesdk/rn-core';
14
+ import React, { createContext, useContext, useEffect, type ReactNode } from 'react';
15
+
16
+ import type { AdsInstance } from '../core/adsInstance';
17
+
18
+ const AdsContext = createContext<AdsInstance | null>(null);
19
+
20
+ export interface AdsProviderProps {
21
+ readonly instance: AdsInstance;
22
+ /**
23
+ * Whether the provider forwards foreground/background transitions to the
24
+ * instance. On by default: FR-034's "never show while inactive" and
25
+ * "re-evaluate a stale ad on return" both depend on the instance being told.
26
+ * Turn it off only when the app already drives `setAppActive` itself. The
27
+ * transitions come from rn-core's shared `appLifecycle()`; `inactive` counts as
28
+ * not active.
29
+ */
30
+ readonly trackAppState?: boolean;
31
+ readonly children: ReactNode;
32
+ }
33
+
34
+ export function AdsProvider({ instance, trackAppState = true, children }: AdsProviderProps) {
35
+ useEffect(() => {
36
+ if (!trackAppState) {
37
+ return;
38
+ }
39
+ return appLifecycle().subscribe(state => {
40
+ instance.setAppActive(state === 'active');
41
+ });
42
+ }, [instance, trackAppState]);
43
+
44
+ return <AdsContext.Provider value={instance}>{children}</AdsContext.Provider>;
45
+ }
46
+
47
+ /**
48
+ * Returns the instance, or null outside a provider.
49
+ *
50
+ * Null rather than a throw on purpose: a screen that renders a banner should
51
+ * degrade to rendering nothing when ads are not wired up, not take the screen
52
+ * down with it (NFR-005).
53
+ */
54
+ export function useAds(): AdsInstance | null {
55
+ return useContext(AdsContext);
56
+ }
@@ -1,75 +1,70 @@
1
- /**
2
- * React bindings (US1, FR-027).
3
- *
4
- * Each hook subscribes to exactly what it reads. `usePlacementState` subscribes
5
- * to one placement rather than to the whole event stream, which is what keeps a
6
- * banner from re-rendering because an unrelated interstitial was clicked —
7
- * PERF-002's bounded re-render assertion depends on it.
8
- *
9
- * None of these hand back an ad object. A consumer queries and subscribes to
10
- * state; it never holds provider-owned memory (FR-027).
11
- */
12
-
13
- import { useEffect, useState } from 'react';
14
-
15
- import type { InitStatus, PlacementState } from '../config/types';
16
- import type { AdEventListener } from '../diagnostics/events';
17
- import { useAds } from './AdsProvider';
18
-
19
- /** Live state for one placement. `unavailable` outside a provider. */
20
- export function usePlacementState(placementKey: string): PlacementState {
21
- const ads = useAds();
22
- const [state, setState] = useState<PlacementState>(() =>
23
- ads ? ads.getPlacementState(placementKey) : 'unavailable',
24
- );
25
-
26
- useEffect(() => {
27
- if (!ads) {
28
- setState('unavailable');
29
- return;
30
- }
31
- // Re-read on subscribe: the state may have moved between the initial
32
- // render and this effect, and dropping that transition would leave the
33
- // UI showing a state the instance has already left.
34
- setState(ads.getPlacementState(placementKey));
35
- return ads.subscribePlacement(placementKey, setState);
36
- }, [ads, placementKey]);
37
-
38
- return state;
39
- }
40
-
41
- /** Live initialization status. `unavailable` outside a provider. */
42
- export function useAdsStatus(): InitStatus {
43
- const ads = useAds();
44
- const [status, setStatus] = useState<InitStatus>(() => (ads ? ads.getStatus() : 'unavailable'));
45
-
46
- useEffect(() => {
47
- if (!ads) {
48
- setStatus('unavailable');
49
- return;
50
- }
51
- setStatus(ads.getStatus());
52
- return ads.subscribeStatus(setStatus);
53
- }, [ads]);
54
-
55
- return status;
56
- }
57
-
58
- /**
59
- * Forwards every event to a listener without causing a render.
60
- *
61
- * Deliberately does not accumulate events into state: a package that kept an
62
- * event log would be persisting exactly the kind of history it promises not to
63
- * (FR-021), and re-rendering on every impression would defeat PERF-002. A screen
64
- * that wants a visible log keeps its own.
65
- */
66
- export function useAdsEvents(listener: AdEventListener): void {
67
- const ads = useAds();
68
-
69
- useEffect(() => {
70
- if (!ads) {
71
- return;
72
- }
73
- return ads.subscribeEvents(listener);
74
- }, [ads, listener]);
75
- }
1
+ /**
2
+ * React bindings (US1, FR-027).
3
+ *
4
+ * Each hook subscribes to exactly what it reads. `usePlacementState` subscribes
5
+ * to one placement rather than to the whole event stream, which is what keeps a
6
+ * banner from re-rendering because an unrelated interstitial was clicked —
7
+ * PERF-002's bounded re-render assertion depends on it.
8
+ *
9
+ * None of these hand back an ad object. A consumer queries and subscribes to
10
+ * state; it never holds provider-owned memory (FR-027).
11
+ */
12
+
13
+ import { useExternalStore, useLatestCallback } from '@chipmobilesdk/rn-core/react';
14
+ import { useCallback, useEffect } from 'react';
15
+
16
+ import type { InitStatus, PlacementState } from '../config/types';
17
+ import type { AdEventListener } from '../diagnostics/events';
18
+ import { useAds } from './AdsProvider';
19
+
20
+ /** Live state for one placement. `unavailable` outside a provider. */
21
+ export function usePlacementState(placementKey: string): PlacementState {
22
+ const ads = useAds();
23
+ const subscribe = useCallback(
24
+ (listener: () => void) =>
25
+ ads ? ads.subscribePlacement(placementKey, listener) : NO_SUBSCRIPTION,
26
+ [ads, placementKey],
27
+ );
28
+ const getSnapshot = useCallback(
29
+ (): PlacementState => (ads ? ads.getPlacementState(placementKey) : 'unavailable'),
30
+ [ads, placementKey],
31
+ );
32
+ // useSyncExternalStore: tear-free, and no transition lost between render and
33
+ // subscription, which the useState copy had to re-read to avoid.
34
+ return useExternalStore(subscribe, getSnapshot);
35
+ }
36
+
37
+ /** Live initialization status. `unavailable` outside a provider. */
38
+ export function useAdsStatus(): InitStatus {
39
+ const ads = useAds();
40
+ const subscribe = useCallback(
41
+ (listener: () => void) => (ads ? ads.subscribeStatus(listener) : NO_SUBSCRIPTION),
42
+ [ads],
43
+ );
44
+ const getSnapshot = useCallback((): InitStatus => (ads ? ads.getStatus() : 'unavailable'), [ads]);
45
+ return useExternalStore(subscribe, getSnapshot);
46
+ }
47
+
48
+ const NO_SUBSCRIPTION = (): void => undefined;
49
+
50
+ /**
51
+ * Forwards every event to a listener without causing a render.
52
+ *
53
+ * Deliberately does not accumulate events into state: a package that kept an
54
+ * event log would be persisting exactly the kind of history it promises not to
55
+ * (FR-021), and re-rendering on every impression would defeat PERF-002. A screen
56
+ * that wants a visible log keeps its own.
57
+ */
58
+ export function useAdsEvents(listener: AdEventListener): void {
59
+ const ads = useAds();
60
+ // An inline listener is a new function every render; subscribing through the
61
+ // latest one keeps a single subscription per instance (PERF-13).
62
+ const latest = useLatestCallback(listener);
63
+
64
+ useEffect(() => {
65
+ if (!ads) {
66
+ return;
67
+ }
68
+ return ads.subscribeEvents(latest);
69
+ }, [ads, latest]);
70
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * What any `AdsEngine` must do (IOS-12, ADS-13).
3
+ *
4
+ * The same checks run against the fake engine and against the AdMob adapter over
5
+ * the provider mock (or the real provider, from a demo screen on a device), so a
6
+ * test that drives the fake proves something about the device path. The subject
7
+ * says how the provider delivers its callbacks; the checks only use the port.
8
+ */
9
+ import {
10
+ ensure,
11
+ runChecks,
12
+ type Check,
13
+ type ConformanceReport,
14
+ } from '@chipmobilesdk/rn-core/testing';
15
+
16
+ import type { Reward } from '../config/types';
17
+ import type { AdsEngine, EngineAdEvent, EngineAdHandle } from '../engine/port';
18
+
19
+ export interface AdsEngineSubject {
20
+ readonly engine: AdsEngine;
21
+ /** The provider finishes loading the ad behind `handle`. */
22
+ deliverLoad(handle: EngineAdHandle): void;
23
+ /** The provider grants a reward for the ad behind `handle`. */
24
+ deliverReward(handle: EngineAdHandle, reward: Reward): void;
25
+ /** The user closes the ad behind `handle`. */
26
+ deliverDismiss(handle: EngineAdHandle): void;
27
+ }
28
+
29
+ export interface AdsEngineHarness {
30
+ create(): AdsEngineSubject;
31
+ }
32
+
33
+ /** Lets callbacks a provider delivers on a later microtask arrive. */
34
+ async function settle(): Promise<void> {
35
+ for (let turn = 0; turn < 3; turn += 1) {
36
+ await Promise.resolve();
37
+ }
38
+ }
39
+
40
+ export const adsEngineChecks: readonly Check<AdsEngineHarness>[] = [
41
+ {
42
+ name: 'is available, and initializes with privacy applied',
43
+ async run(harness) {
44
+ const { engine } = harness.create();
45
+ ensure(engine.isAvailable(), 'reported unavailable');
46
+ await engine.initialize({ childDirected: true, maxAdContentRating: 'G' });
47
+ },
48
+ },
49
+ {
50
+ name: 'delivers loaded to a subscriber of an interstitial, and nothing after unsubscribing',
51
+ async run(harness) {
52
+ const subject = harness.create();
53
+ const handle = await subject.engine.createFullScreen('interstitial', 'conformance/1');
54
+ ensure(typeof handle.id === 'string' && handle.id !== '', 'handle has no id');
55
+ const seen: EngineAdEvent['type'][] = [];
56
+ const stop = subject.engine.subscribe(handle, event => seen.push(event.type));
57
+ subject.deliverLoad(handle);
58
+ await settle();
59
+ ensure(seen.join(',') === 'loaded', `subscriber saw ${seen.join(',') || 'nothing'}`);
60
+ stop();
61
+ stop();
62
+ subject.deliverDismiss(handle);
63
+ await settle();
64
+ ensure(seen.length === 1, `notified after unsubscribing: ${seen.join(',')}`);
65
+ },
66
+ },
67
+ {
68
+ name: 'delivers the reward and the dismissal of a rewarded ad',
69
+ async run(harness) {
70
+ const subject = harness.create();
71
+ const handle = await subject.engine.createFullScreen('rewarded', 'conformance/2', {
72
+ personalizedAds: false,
73
+ });
74
+ const seen: EngineAdEvent[] = [];
75
+ subject.engine.subscribe(handle, event => seen.push(event));
76
+ subject.deliverLoad(handle);
77
+ await settle();
78
+ subject.deliverReward(handle, { type: 'coins', amount: 5 });
79
+ subject.deliverDismiss(handle);
80
+ await settle();
81
+ const reward = seen.find(event => event.type === 'rewarded');
82
+ ensure(reward?.type === 'rewarded', `no reward among ${seen.map(e => e.type).join(',')}`);
83
+ ensure(
84
+ reward.reward.type === 'coins' && reward.reward.amount === 5,
85
+ `reward ${JSON.stringify(reward.reward)}`,
86
+ );
87
+ ensure(seen.at(-1)?.type === 'dismissed', `last event ${seen.at(-1)?.type}`);
88
+ },
89
+ },
90
+ {
91
+ name: 'gives every ad its own handle',
92
+ async run(harness) {
93
+ const { engine } = harness.create();
94
+ const first = await engine.createFullScreen('interstitial', 'conformance/1');
95
+ const second = await engine.createFullScreen('interstitial', 'conformance/1');
96
+ ensure(first.id !== second.id, 'two ads share a handle');
97
+ },
98
+ },
99
+ {
100
+ name: 'disposes safely twice',
101
+ async run(harness) {
102
+ const { engine } = harness.create();
103
+ const handle = await engine.createFullScreen('interstitial', 'conformance/1');
104
+ engine.dispose(handle);
105
+ engine.dispose(handle);
106
+ },
107
+ },
108
+ ];
109
+
110
+ export function runAdsEngineConformance(harness: AdsEngineHarness): Promise<ConformanceReport> {
111
+ return runChecks(() => harness, adsEngineChecks);
112
+ }