@chipmobilesdk/rn-payment 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.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The binding's shapes, and their translation into the port's vocabulary
3
+ * (PAY-12).
4
+ *
5
+ * The binding speaks Google Play: prices as micros in strings, offer tokens,
6
+ * numeric purchase states, store error codes. The port speaks this package's
7
+ * own. Keeping the translation here, with no I/O, no listeners and no module
8
+ * loading, is what makes it checkable against recorded payloads — and leaves
9
+ * the adapter next door about the calls it actually makes.
10
+ *
11
+ * The raw types are declared narrowly on purpose: they document the coupling,
12
+ * and a binding upgrade that changes one of these shapes fails to typecheck
13
+ * here rather than failing silently on a user's device.
14
+ */
15
+ import type { ProductType } from '../config/types';
16
+ import type { ProviderFailureReason, ProviderProduct, ProviderPurchase } from './port';
17
+
18
+ export interface RawProduct {
19
+ id?: string;
20
+ productId?: string;
21
+ title?: string;
22
+ name?: string;
23
+ description?: string;
24
+ displayPrice?: string;
25
+ localizedPrice?: string;
26
+ currency?: string;
27
+ currencyCode?: string;
28
+ price?: string | number;
29
+ oneTimePurchaseOfferDetails?: {
30
+ formattedPrice?: string;
31
+ priceAmountMicros?: string | number;
32
+ priceCurrencyCode?: string;
33
+ };
34
+ subscriptionOfferDetails?: RawSubscriptionOffer[];
35
+ }
36
+
37
+ export interface RawSubscriptionOffer {
38
+ offerToken?: string;
39
+ offerId?: string;
40
+ basePlanId?: string;
41
+ pricingPhases?: {
42
+ pricingPhaseList?: Array<{
43
+ formattedPrice?: string;
44
+ priceAmountMicros?: string | number;
45
+ priceCurrencyCode?: string;
46
+ billingPeriod?: string;
47
+ recurrenceMode?: number;
48
+ billingCycleCount?: number;
49
+ }>;
50
+ };
51
+ }
52
+
53
+ export interface RawPurchase {
54
+ id?: string;
55
+ transactionId?: string;
56
+ productId?: string;
57
+ ids?: string[];
58
+ purchaseToken?: string;
59
+ purchaseStateAndroid?: number | null;
60
+ /** A string in the 16.x binding: `'pending' | 'purchased' | 'unknown'`. */
61
+ purchaseState?: number | string;
62
+ transactionDate?: number;
63
+ isAcknowledgedAndroid?: boolean;
64
+ isAcknowledged?: boolean;
65
+ autoRenewingAndroid?: boolean;
66
+ isAutoRenewing?: boolean;
67
+ expirationDateAndroid?: number;
68
+ transactionReceipt?: string;
69
+ dataAndroid?: string;
70
+ }
71
+
72
+ /** What `purchaseErrorListener` delivers. */
73
+ export interface RawPurchaseError {
74
+ code?: string;
75
+ message?: string;
76
+ productId?: string | null;
77
+ }
78
+
79
+ /** Play's `PurchaseState`: 0 unspecified, 1 purchased, 2 pending. */
80
+ const PLAY_STATE_PURCHASED = 1;
81
+ const PLAY_STATE_PENDING = 2;
82
+
83
+ // Required lazily (rn-core's lazy peer) so importing the package does not require
84
+ // the native module.
85
+
86
+ export function toMicros(value: string | number | undefined): number {
87
+ if (typeof value === 'number') {
88
+ return value;
89
+ }
90
+ if (typeof value === 'string') {
91
+ const parsed = Number.parseInt(value, 10);
92
+ return Number.isFinite(parsed) ? parsed : 0;
93
+ }
94
+ return 0;
95
+ }
96
+
97
+ export function normalizeProduct(raw: RawProduct, productType: ProductType): ProviderProduct {
98
+ const oneTime = raw.oneTimePurchaseOfferDetails;
99
+ const currencyCode = oneTime?.priceCurrencyCode ?? raw.currencyCode ?? raw.currency ?? '';
100
+
101
+ return {
102
+ storeProductId: raw.id ?? raw.productId ?? '',
103
+ productType,
104
+ title: raw.title ?? raw.name ?? '',
105
+ description: raw.description ?? '',
106
+ // Store-formatted, never built here: only the store knows the right currency
107
+ // symbol, separator, and placement for the user's locale (FR-028).
108
+ formattedPrice: oneTime?.formattedPrice ?? raw.displayPrice ?? raw.localizedPrice ?? '',
109
+ currencyCode,
110
+ priceAmountMicros: toMicros(oneTime?.priceAmountMicros ?? raw.price),
111
+ offers: (raw.subscriptionOfferDetails ?? []).map(offer => normalizeOffer(offer, currencyCode)),
112
+ };
113
+ }
114
+
115
+ export function normalizeOffer(
116
+ offer: RawSubscriptionOffer,
117
+ fallbackCurrency: string,
118
+ ): ProviderProduct['offers'][number] {
119
+ const phases = offer.pricingPhases?.pricingPhaseList ?? [];
120
+ // The last phase is the recurring price; earlier ones are trial or
121
+ // introductory. Play orders them that way.
122
+ const recurring = phases[phases.length - 1];
123
+ const intro = phases.length > 1 ? phases[0] : undefined;
124
+ const isFreeTrial = intro !== undefined && toMicros(intro.priceAmountMicros) === 0;
125
+
126
+ return {
127
+ offerKey: offer.offerToken ?? offer.offerId ?? offer.basePlanId ?? '',
128
+ billingPeriod: recurring?.billingPeriod ?? '',
129
+ formattedPrice: recurring?.formattedPrice ?? '',
130
+ priceAmountMicros: toMicros(recurring?.priceAmountMicros),
131
+ currencyCode: recurring?.priceCurrencyCode ?? fallbackCurrency,
132
+ trialPeriod: isFreeTrial ? intro?.billingPeriod : undefined,
133
+ introductoryPrice:
134
+ intro && !isFreeTrial
135
+ ? {
136
+ formattedPrice: intro.formattedPrice ?? '',
137
+ period: intro.billingPeriod ?? '',
138
+ cycles: intro.billingCycleCount ?? 1,
139
+ }
140
+ : undefined,
141
+ // Play decides eligibility by only returning offers the user qualifies for,
142
+ // so forwarding `true` reports the store's determination rather than
143
+ // computing our own (FR-026).
144
+ isEligible: true,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Reads the purchase state from whichever field the binding filled.
150
+ *
151
+ * Pending is preserved, never flattened to purchased: that distinction is what
152
+ * stops an entitlement being granted for money that has not arrived (FR-037).
153
+ * And an unrecognized or missing state is `unspecified`, never `purchased`.
154
+ *
155
+ * 0.1.0 read only Play's numeric state and treated anything else as purchased.
156
+ * The 16.x binding hands JavaScript the *string* state and does not carry the
157
+ * numeric one across, so on a device every pending purchase arrived as a string,
158
+ * fell through to the default, and was granted. Unit tests could not see it: they
159
+ * drive the fake store, which never passes through here.
160
+ */
161
+ export function toProviderPurchaseState(
162
+ raw: Pick<RawPurchase, 'purchaseStateAndroid' | 'purchaseState'>,
163
+ ): ProviderPurchase['state'] {
164
+ let numeric: number | undefined;
165
+ if (typeof raw.purchaseStateAndroid === 'number') {
166
+ numeric = raw.purchaseStateAndroid;
167
+ } else if (typeof raw.purchaseState === 'number') {
168
+ numeric = raw.purchaseState;
169
+ }
170
+ if (numeric !== undefined) {
171
+ if (numeric === PLAY_STATE_PENDING) {
172
+ return 'pending';
173
+ }
174
+ return numeric === PLAY_STATE_PURCHASED ? 'purchased' : 'unspecified';
175
+ }
176
+
177
+ switch (typeof raw.purchaseState === 'string' ? raw.purchaseState.toLowerCase() : '') {
178
+ case 'purchased':
179
+ case 'restored':
180
+ return 'purchased';
181
+ case 'pending':
182
+ case 'deferred':
183
+ return 'pending';
184
+ default:
185
+ return 'unspecified';
186
+ }
187
+ }
188
+
189
+ export function normalizePurchase(raw: RawPurchase): ProviderPurchase {
190
+ return {
191
+ storeProductId: raw.productId ?? raw.ids?.[0] ?? '',
192
+ transactionId: raw.id ?? raw.transactionId ?? raw.purchaseToken ?? '',
193
+ token: raw.purchaseToken ?? '',
194
+ state: toProviderPurchaseState(raw),
195
+ purchasedAt: raw.transactionDate ?? Date.now(),
196
+ isAcknowledged: raw.isAcknowledgedAndroid ?? raw.isAcknowledged ?? false,
197
+ expiresAt: raw.expirationDateAndroid,
198
+ willAutoRenew: raw.autoRenewingAndroid ?? raw.isAutoRenewing,
199
+ // Opaque material for the app's backend. Carried here and handed to the
200
+ // validation hook only — never logged or put in an event (FR-074).
201
+ verificationPayload: raw.transactionReceipt ?? raw.dataAndroid,
202
+ };
203
+ }
204
+
205
+ /** Maps a binding error code onto the port's vocabulary, so no store code escapes. */
206
+ export function mapErrorCode(code: string | undefined): ProviderFailureReason {
207
+ switch (code) {
208
+ case 'E_USER_CANCELLED':
209
+ case 'user-cancelled':
210
+ return 'user_cancelled';
211
+ case 'E_ALREADY_OWNED':
212
+ case 'already-owned':
213
+ case 'item-already-owned':
214
+ return 'already_owned';
215
+ case 'E_ITEM_UNAVAILABLE':
216
+ case 'item-unavailable':
217
+ case 'sku-not-found':
218
+ return 'unknown_product';
219
+ case 'E_NOT_PREPARED':
220
+ case 'not-prepared':
221
+ return 'not_ready';
222
+ case 'E_NETWORK_ERROR':
223
+ case 'network-error':
224
+ return 'network_error';
225
+ case 'E_DEFERRED_PAYMENT':
226
+ // Not a failure — a pending purchase. The caller resolves it from the
227
+ // purchase update rather than from this error.
228
+ return 'store_error';
229
+ default:
230
+ return 'store_error';
231
+ }
232
+ }
@@ -130,6 +130,14 @@ export interface PaymentConfig {
130
130
  * proceed (FR-015).
131
131
  */
132
132
  isProductionBuild: boolean;
133
+ /**
134
+ * Lets a non-production build complete purchases through the real store, so a
135
+ * Play license tester can buy on a debug build (PAY-16). Accepted only with
136
+ * `environment: 'test'`; any other environment rejects it at startup. License
137
+ * testers are not charged; any other account on the device would be, so keep
138
+ * it out of builds that reach real users.
139
+ */
140
+ allowStoreTestPurchases?: boolean;
133
141
  /**
134
142
  * Global sell switch. When false, purchases report `disabled` but entitlements
135
143
  * already held stay readable — turning off selling is not the same as taking
@@ -199,6 +199,16 @@ export function validateConfig(
199
199
  * continuing silently is exactly the failure this package exists to prevent.
200
200
  */
201
201
  export function assertEnvironmentSafe(config: PaymentConfig): void {
202
+ if (config.allowStoreTestPurchases === true && config.environment !== 'test') {
203
+ throw new PaymentConfigError({
204
+ code: 'PAYMENT_INVALID_CONFIG',
205
+ message:
206
+ `allowStoreTestPurchases is only accepted with environment "test", not ` +
207
+ `"${config.environment}": it exists for license testers, not for real users.`,
208
+ operation: 'configure',
209
+ offenders: ['allowStoreTestPurchases'],
210
+ });
211
+ }
202
212
  if (config.environment === 'production' && !config.isProductionBuild) {
203
213
  throw new PaymentConfigError({
204
214
  code: 'PAYMENT_PRODUCTION_CONFIG_IN_NON_PRODUCTION_BUILD',
@@ -213,12 +223,17 @@ export function assertEnvironmentSafe(config: PaymentConfig): void {
213
223
  }
214
224
 
215
225
  /**
216
- * Whether this configuration may hand a real purchase to a real store (FR-014).
226
+ * Whether this configuration may hand a purchase to a real store (FR-014).
217
227
  *
218
- * False outside production regardless of what else is configured. The engine
219
- * records each refusal in observable status so a test can assert the block
220
- * happened — the difference between a guarantee and a hope.
228
+ * True in a production build configured for production, and in a `test`
229
+ * environment that opted in with `allowStoreTestPurchases` (PAY-16). False
230
+ * everywhere else. The engine records each refusal in observable status so a
231
+ * test can assert the block happened — the difference between a guarantee and a
232
+ * hope.
221
233
  */
222
234
  export function mayCreateRealTransaction(config: PaymentConfig): boolean {
235
+ if (config.environment === 'test' && config.allowStoreTestPurchases === true) {
236
+ return true;
237
+ }
223
238
  return config.environment === 'production' && config.isProductionBuild;
224
239
  }
package/src/core/retry.ts CHANGED
@@ -9,17 +9,10 @@
9
9
  * schedule without burning real time.
10
10
  */
11
11
 
12
- import {
13
- computeBackoff,
14
- runWithRetry as runCoreRetry,
15
- type RetryHandle,
16
- } from '@chipmobilesdk/rn-core';
12
+ import { computeBackoff } from '@chipmobilesdk/rn-core';
17
13
 
18
14
  import type { BackoffConfig } from '../config/types';
19
15
 
20
- /** Opaque timer handle: a Node Timeout and a browser numeric id are both valid. */
21
- type TimerHandle = ReturnType<typeof setTimeout> | number;
22
-
23
16
  /**
24
17
  * Delay before `attempt` (1-based), capped and optionally jittered.
25
18
  *
@@ -43,53 +36,3 @@ function toSpec(config: Required<BackoffConfig>) {
43
36
  maxAttempts: config.maxAttempts,
44
37
  };
45
38
  }
46
-
47
- /** The full schedule, for asserting a retry policy without waiting for it. */
48
- export function backoffSchedule(config: Required<BackoffConfig>): number[] {
49
- const delays: number[] = [];
50
- for (let attempt = 1; attempt <= config.maxAttempts; attempt += 1) {
51
- delays.push(backoffDelayMs(attempt, config, () => 1));
52
- }
53
- return delays;
54
- }
55
-
56
- export type { RetryHandle } from '@chipmobilesdk/rn-core';
57
-
58
- export interface RetryRunnerOptions {
59
- config: Required<BackoffConfig>;
60
- /** Return true when the attempt succeeded and retrying should stop. */
61
- attempt: (attemptNumber: number) => Promise<boolean>;
62
- /** Called once the per-session budget is spent without success. */
63
- onExhausted?: (attempts: number) => void;
64
- /**
65
- * Injected so a test can run the whole schedule synchronously instead of
66
- * waiting minutes of real backoff. The handle is opaque, because a Node
67
- * `Timeout` and a browser numeric id are both valid here.
68
- */
69
- setTimeoutFn?: (fn: () => void, ms: number) => TimerHandle;
70
- clearTimeoutFn?: (handle: TimerHandle) => void;
71
- random?: () => number;
72
- }
73
-
74
- /**
75
- * Runs `attempt` under the bounded schedule (rn-core's runner).
76
- *
77
- * Exhaustion is reported rather than thrown: for finalization, a spent session
78
- * budget is not a failure but a handoff to the next launch, and the caller is
79
- * the only one that knows which of the two it is. A throwing attempt is a failed
80
- * attempt, nothing more: letting it escape would silently drop a paid transaction.
81
- */
82
- export function runWithRetry(options: RetryRunnerOptions): RetryHandle {
83
- const setTimeoutFn = options.setTimeoutFn ?? setTimeout;
84
- const clearTimeoutFn = options.clearTimeoutFn ?? clearTimeout;
85
- return runCoreRetry({
86
- spec: toSpec(options.config),
87
- attempt: options.attempt,
88
- onExhausted: options.onExhausted,
89
- random: options.random,
90
- scheduler: {
91
- setTimeout: (callback, ms) => setTimeoutFn(callback, ms),
92
- clearTimeout: handle => clearTimeoutFn(handle as TimerHandle),
93
- },
94
- });
95
- }
@@ -257,7 +257,7 @@ export function createEmitter(
257
257
  /**
258
258
  * Fields that must never appear in an event payload.
259
259
  *
260
- * Used by `__tests__/redaction.test.ts` to walk every emitted event across the
260
+ * Used by `__tests__/diagnostics.test.ts` to walk every emitted event across the
261
261
  * whole suite. Enumerating the ban here rather than in the test keeps the rule
262
262
  * next to the type it constrains.
263
263
  */
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The billing connection: connecting, watching it, and reconnecting with bounded
3
+ * backoff (FR-018 – FR-024, PAY-10).
4
+ *
5
+ * A reconnect is always a full teardown-then-connect cycle. The upstream
6
+ * binding's own `reconnect()` has reported success without rebuilding anything
7
+ * (openiap#408), so no shortcut is trusted here.
8
+ */
9
+ import type { ProviderPurchase } from '../adapter/port';
10
+ import type { Unsubscribe } from '../config/types';
11
+ import { backoffDelayMs } from '../core/retry';
12
+ import { withTimeout } from '../core/mutex';
13
+ import { PaymentError } from '../diagnostics/errors';
14
+ import type { EngineState } from './state';
15
+
16
+ export type InitOutcome = { ok: true } | { ok: false; error: PaymentError };
17
+
18
+ export interface Connection {
19
+ /** Connects and attaches the watchers; status follows the outcome. */
20
+ connect(): Promise<InitOutcome>;
21
+ /**
22
+ * A fresh reconnect budget and one immediate attempt, when an earlier budget
23
+ * ran out: a foreground return is when the network the app lost is usually
24
+ * back.
25
+ */
26
+ recover(): Promise<void>;
27
+ dispose(): void;
28
+ }
29
+
30
+ export function createConnection(
31
+ state: EngineState,
32
+ onPurchase: (purchase: ProviderPurchase) => void,
33
+ ): Connection {
34
+ const { provider, resolved } = state;
35
+ let connectionSub: Unsubscribe | undefined;
36
+ let purchaseSub: Unsubscribe | undefined;
37
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
38
+ let reconnectAttempts = 0;
39
+ /**
40
+ * Set once a connection succeeded. Recovery after an exhausted budget is only
41
+ * meaningful from there; a first connection that failed is the app's to retry
42
+ * through `initialize`.
43
+ */
44
+ let everConnected = false;
45
+
46
+ function scheduleReconnect(): void {
47
+ if (state.disposed) {
48
+ return;
49
+ }
50
+ if (reconnectAttempts >= resolved.retry.reconnect.maxAttempts) {
51
+ // Out of budget for now, not for good: a retryable failure rather than a
52
+ // `connecting` that promised a reconnect nobody was going to make.
53
+ state.setStatus({ kind: 'failed', retryable: true, reconnectAttempts });
54
+ return;
55
+ }
56
+ const attempt = reconnectAttempts + 1;
57
+ reconnectTimer = setTimeout(
58
+ () => {
59
+ reconnectTimer = undefined;
60
+ if (state.disposed) {
61
+ return;
62
+ }
63
+ reconnectAttempts = attempt;
64
+ state.setStatus({ kind: 'connecting', reconnectAttempts });
65
+ reconnectOnce().catch(() => undefined);
66
+ },
67
+ backoffDelayMs(attempt, resolved.retry.reconnect),
68
+ );
69
+ }
70
+
71
+ async function reconnectOnce(): Promise<void> {
72
+ try {
73
+ await provider.disconnect();
74
+ } catch {
75
+ // Already down; nothing to tear down.
76
+ }
77
+ const outcome = await provider.connect();
78
+ if (state.disposed) {
79
+ return;
80
+ }
81
+ if (outcome.ok) {
82
+ reconnectAttempts = 0;
83
+ state.setStatus({ kind: 'ready', reconnectAttempts: 0 });
84
+ } else {
85
+ scheduleReconnect();
86
+ }
87
+ }
88
+
89
+ /** Replaced, never stacked: a second subscription would hear everything twice. */
90
+ function watch(): void {
91
+ connectionSub?.();
92
+ connectionSub = provider.observeConnection((connected, reason) => {
93
+ if (state.disposed) {
94
+ return;
95
+ }
96
+ state.emit({ type: 'connection_changed', connected, reason, attempt: reconnectAttempts });
97
+ if (!connected && state.status.kind === 'ready') {
98
+ state.setStatus({ kind: 'connecting' });
99
+ scheduleReconnect();
100
+ }
101
+ });
102
+ // Session-long: a pending purchase settling between sessions arrives here
103
+ // (FR-039), not only while a purchase is open.
104
+ purchaseSub?.();
105
+ purchaseSub = provider.observePurchases(purchase => {
106
+ if (!state.disposed) {
107
+ onPurchase(purchase);
108
+ }
109
+ });
110
+ }
111
+
112
+ return {
113
+ async connect() {
114
+ const outcome = await withTimeout(
115
+ provider.connect(),
116
+ resolved.timeouts.connectMs,
117
+ () =>
118
+ new PaymentError({
119
+ code: 'PAYMENT_TIMEOUT',
120
+ message: 'Connecting to the billing service timed out',
121
+ operation: 'initialize',
122
+ retryable: true,
123
+ }),
124
+ ).catch((error: PaymentError) => ({
125
+ ok: false as const,
126
+ reason: 'store_error' as const,
127
+ retryable: error.retryable,
128
+ }));
129
+
130
+ if (!outcome.ok) {
131
+ if (outcome.reason === 'store_error') {
132
+ state.setStatus({ kind: 'failed', retryable: outcome.retryable });
133
+ return {
134
+ ok: false,
135
+ error: new PaymentError({
136
+ code: 'PAYMENT_STORE_ERROR',
137
+ message: 'Could not connect to the billing service',
138
+ operation: 'initialize',
139
+ retryable: outcome.retryable,
140
+ }),
141
+ };
142
+ }
143
+ // No billing service, an outdated one, or an unsupported platform: each
144
+ // distinguishable, and none of them may break the host app (FR-021, FR-023).
145
+ state.setStatus({
146
+ kind: 'unavailable',
147
+ unavailableReason: outcome.reason,
148
+ retryable: outcome.retryable,
149
+ });
150
+ return {
151
+ ok: false,
152
+ error: new PaymentError({
153
+ code:
154
+ outcome.reason === 'platform_unsupported'
155
+ ? 'PAYMENT_UNSUPPORTED_PLATFORM'
156
+ : 'PAYMENT_UNAVAILABLE',
157
+ message: `Billing unavailable: ${outcome.reason}`,
158
+ operation: 'initialize',
159
+ retryable: outcome.retryable,
160
+ }),
161
+ };
162
+ }
163
+
164
+ watch();
165
+ everConnected = true;
166
+ state.setStatus({ kind: 'ready', reconnectAttempts: 0 });
167
+ return { ok: true };
168
+ },
169
+
170
+ async recover() {
171
+ if (
172
+ everConnected &&
173
+ !state.disposed &&
174
+ state.status.kind === 'failed' &&
175
+ reconnectTimer === undefined
176
+ ) {
177
+ reconnectAttempts = 0;
178
+ state.setStatus({ kind: 'connecting', reconnectAttempts: 0 });
179
+ await reconnectOnce().catch(() => undefined);
180
+ }
181
+ },
182
+
183
+ dispose() {
184
+ connectionSub?.();
185
+ connectionSub = undefined;
186
+ purchaseSub?.();
187
+ purchaseSub = undefined;
188
+ if (reconnectTimer !== undefined) {
189
+ clearTimeout(reconnectTimer);
190
+ reconnectTimer = undefined;
191
+ }
192
+ },
193
+ };
194
+ }