@chipmobilesdk/rn-payment 0.4.1 → 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.
- package/CHANGELOG.md +202 -0
- package/README.md +70 -16
- package/package.json +5 -2
- package/skills/sdk-rn-payment/SKILL.md +8 -6
- package/src/adapter/iap-adapter.ts +44 -251
- package/src/adapter/iapShapes.ts +232 -0
- package/src/config/types.ts +8 -0
- package/src/config/validate.ts +19 -4
- package/src/core/mutex.ts +9 -110
- package/src/core/retry.ts +9 -104
- package/src/core/timers.ts +40 -18
- package/src/diagnostics/errors.ts +20 -13
- package/src/diagnostics/events.ts +51 -32
- package/src/diagnostics/messageKeys.ts +15 -9
- package/src/engine/connection.ts +194 -0
- package/src/engine/engine.ts +142 -733
- package/src/engine/foreground.ts +29 -0
- package/src/engine/internals.ts +40 -0
- package/src/engine/products.ts +39 -17
- package/src/engine/purchase.ts +22 -130
- package/src/engine/purchaseFailure.ts +48 -0
- package/src/engine/receiptValidation.ts +101 -0
- package/src/engine/state.ts +253 -0
- package/src/engine/sync.ts +161 -0
- package/src/entitlements/aggregate.ts +37 -5
- package/src/entitlements/mapping.ts +0 -22
- package/src/index.ts +3 -0
- package/src/persistence/mmkv-store.ts +45 -35
- package/src/persistence/snapshot.ts +102 -27
- package/src/react/PaymentProvider.tsx +85 -23
- package/src/react/hooks.ts +23 -34
- package/src/testing/conformance.ts +169 -0
- package/src/testing/fakeStore.ts +11 -29
- package/src/testing/index.ts +9 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine's state and the one way it changes (PAY-10).
|
|
3
|
+
*
|
|
4
|
+
* Status, the persisted snapshot, entitlements and pending purchases live here
|
|
5
|
+
* with the listeners that hear about them. Every change goes through `commit`
|
|
6
|
+
* (the snapshot) or `setStatus`, so diffing and emission are written once:
|
|
7
|
+
* an entitlement is granted or revoked exactly once however many sources it has
|
|
8
|
+
* (FR-079), a renewal that changes nothing emits nothing (FR-068), and an
|
|
9
|
+
* unchanged map is the same object (PERF-03).
|
|
10
|
+
*/
|
|
11
|
+
import { createListenerSet, type ListenerSet } from '@chipmobilesdk/rn-core';
|
|
12
|
+
|
|
13
|
+
import type { ProviderPort } from '../adapter/port';
|
|
14
|
+
import type { ResolvedConfig } from '../config/validate';
|
|
15
|
+
import type { PaymentConfig, PaymentStatus, PendingPurchasesState } from '../config/types';
|
|
16
|
+
import { redact } from '../diagnostics/errors';
|
|
17
|
+
import {
|
|
18
|
+
createEmitter,
|
|
19
|
+
type PaymentEmitter,
|
|
20
|
+
type PaymentEvent,
|
|
21
|
+
type PaymentEventInput,
|
|
22
|
+
} from '../diagnostics/events';
|
|
23
|
+
import {
|
|
24
|
+
aggregate,
|
|
25
|
+
diffEntitlements,
|
|
26
|
+
initialEntitlements,
|
|
27
|
+
shareUnchanged,
|
|
28
|
+
type EntitlementMap,
|
|
29
|
+
} from '../entitlements/aggregate';
|
|
30
|
+
import type { SnapshotStore } from '../persistence/mmkv-store';
|
|
31
|
+
import { emptySnapshot, type PersistedSnapshot } from '../persistence/snapshot';
|
|
32
|
+
import { derivePending, pendingTransitions, samePending, UNKNOWN_PENDING } from './pending';
|
|
33
|
+
|
|
34
|
+
type RevokeReason = 'expired' | 'revoked_by_store' | 'validation_rejected' | 'consumed';
|
|
35
|
+
|
|
36
|
+
export interface EngineState {
|
|
37
|
+
readonly config: PaymentConfig;
|
|
38
|
+
readonly resolved: ResolvedConfig;
|
|
39
|
+
readonly provider: ProviderPort;
|
|
40
|
+
readonly store: SnapshotStore;
|
|
41
|
+
readonly now: () => number;
|
|
42
|
+
readonly emitter: PaymentEmitter;
|
|
43
|
+
readonly statusListeners: ListenerSet<[PaymentStatus]>;
|
|
44
|
+
readonly entitlementListeners: ListenerSet<[EntitlementMap]>;
|
|
45
|
+
readonly pendingListeners: ListenerSet<[PendingPurchasesState]>;
|
|
46
|
+
|
|
47
|
+
disposed: boolean;
|
|
48
|
+
/** Whether the snapshot comes from a sync that succeeded; until then entitlements are `unknown`. */
|
|
49
|
+
hasSynced: boolean;
|
|
50
|
+
snapshot: PersistedSnapshot;
|
|
51
|
+
entitlements: EntitlementMap;
|
|
52
|
+
status: PaymentStatus;
|
|
53
|
+
pending: PendingPurchasesState;
|
|
54
|
+
|
|
55
|
+
emit(event: PaymentEventInput): void;
|
|
56
|
+
setStatus(next: Partial<PaymentStatus>): void;
|
|
57
|
+
/** Writes the snapshot, reports pending purchases that ended, and recomputes. */
|
|
58
|
+
commit(next: PersistedSnapshot): void;
|
|
59
|
+
/** Loads the persisted snapshot at startup (FR-053). */
|
|
60
|
+
hydrate(): void;
|
|
61
|
+
/** Forgets everything local, back to `unknown` (FR-057). */
|
|
62
|
+
forget(): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createEngineState(
|
|
66
|
+
config: PaymentConfig,
|
|
67
|
+
resolved: ResolvedConfig,
|
|
68
|
+
provider: ProviderPort,
|
|
69
|
+
store: SnapshotStore,
|
|
70
|
+
now: () => number,
|
|
71
|
+
): EngineState {
|
|
72
|
+
// A listener that throws is a consumer bug, so it goes to the app's own logger
|
|
73
|
+
// rather than back into the event stream (FR-080, FR-081).
|
|
74
|
+
const emitter = createEmitter((error, event) => {
|
|
75
|
+
config.logger?.error?.('payment event listener threw', {
|
|
76
|
+
eventType: event.type,
|
|
77
|
+
reason: redact(error),
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
const listenerOptions = {
|
|
81
|
+
onListenerError: (error: unknown) =>
|
|
82
|
+
config.logger?.error?.('payment listener threw', { reason: redact(error) }),
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Why an entitlement that was held is held no more, from what its sources left
|
|
87
|
+
* behind (PAY-12): a backend rejection, a consumed item, an expired
|
|
88
|
+
* subscription — or, when the store simply stopped reporting it, a refund.
|
|
89
|
+
*/
|
|
90
|
+
function revokeReason(sources: readonly string[]): RevokeReason {
|
|
91
|
+
const records = state.snapshot.purchases.filter(record => sources.includes(record.productKey));
|
|
92
|
+
if (records.some(record => record.validationState === 'rejected')) {
|
|
93
|
+
return 'validation_rejected';
|
|
94
|
+
}
|
|
95
|
+
if (records.some(record => record.state === 'consumed')) {
|
|
96
|
+
return 'consumed';
|
|
97
|
+
}
|
|
98
|
+
const at = now();
|
|
99
|
+
if (records.some(record => record.expiresAt !== undefined && record.expiresAt <= at)) {
|
|
100
|
+
return 'expired';
|
|
101
|
+
}
|
|
102
|
+
return 'revoked_by_store';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function publishPending(next: PendingPurchasesState): void {
|
|
106
|
+
// Diffed: a sync that changes nothing is the common case, and an app
|
|
107
|
+
// rendering "payment pending" has no use for a re-render that says the same.
|
|
108
|
+
if (samePending(state.pending, next)) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
state.pending = next;
|
|
112
|
+
state.pendingListeners.notify(next);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function recompute(): void {
|
|
116
|
+
if (state.disposed) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const previous = state.entitlements;
|
|
120
|
+
state.entitlements = shareUnchanged(
|
|
121
|
+
previous,
|
|
122
|
+
aggregate({
|
|
123
|
+
config: resolved,
|
|
124
|
+
snapshot: state.snapshot,
|
|
125
|
+
hasSynced: state.hasSynced,
|
|
126
|
+
reportsGraceAndHoldDistinctly: provider.capabilities().reportsGraceAndHoldDistinctly,
|
|
127
|
+
now: now(),
|
|
128
|
+
}),
|
|
129
|
+
);
|
|
130
|
+
for (const change of diffEntitlements(previous, state.entitlements)) {
|
|
131
|
+
if (change.next === 'entitled') {
|
|
132
|
+
state.emit({
|
|
133
|
+
type: 'entitlement_granted',
|
|
134
|
+
entitlementKey: change.key,
|
|
135
|
+
sources: change.sources,
|
|
136
|
+
});
|
|
137
|
+
} else if (change.previous === 'entitled') {
|
|
138
|
+
state.emit({
|
|
139
|
+
type: 'entitlement_revoked',
|
|
140
|
+
entitlementKey: change.key,
|
|
141
|
+
reason: revokeReason(previous[change.key]?.sources ?? []),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (state.entitlements !== previous) {
|
|
146
|
+
state.entitlementListeners.notify(state.entitlements);
|
|
147
|
+
}
|
|
148
|
+
publishPending(
|
|
149
|
+
derivePending({
|
|
150
|
+
config: resolved,
|
|
151
|
+
snapshot: state.snapshot,
|
|
152
|
+
hasSynced: state.hasSynced,
|
|
153
|
+
now: now(),
|
|
154
|
+
}),
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const state: EngineState = {
|
|
159
|
+
config,
|
|
160
|
+
resolved,
|
|
161
|
+
provider,
|
|
162
|
+
store,
|
|
163
|
+
now,
|
|
164
|
+
emitter,
|
|
165
|
+
statusListeners: createListenerSet<[PaymentStatus]>(listenerOptions),
|
|
166
|
+
entitlementListeners: createListenerSet<[EntitlementMap]>(listenerOptions),
|
|
167
|
+
pendingListeners: createListenerSet<[PendingPurchasesState]>(listenerOptions),
|
|
168
|
+
|
|
169
|
+
disposed: false,
|
|
170
|
+
hasSynced: false,
|
|
171
|
+
snapshot: emptySnapshot(config.scopeToken),
|
|
172
|
+
entitlements: initialEntitlements(resolved),
|
|
173
|
+
status: { kind: resolved.enabled ? 'not_started' : 'disabled', blockedOperations: [] },
|
|
174
|
+
pending: UNKNOWN_PENDING,
|
|
175
|
+
|
|
176
|
+
emit(event) {
|
|
177
|
+
emitter.emit({ ...event, timestamp: event.timestamp ?? now() } as PaymentEvent);
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
setStatus(next) {
|
|
181
|
+
if (state.disposed) {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
state.status = { ...state.status, ...next };
|
|
185
|
+
state.emit({
|
|
186
|
+
type: 'initialization',
|
|
187
|
+
status: state.status.kind,
|
|
188
|
+
unavailableReason: state.status.unavailableReason,
|
|
189
|
+
retryable: state.status.retryable,
|
|
190
|
+
});
|
|
191
|
+
state.statusListeners.notify(state.status);
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
commit(next) {
|
|
195
|
+
// Read before the swap: a transition is "pending before, not pending now",
|
|
196
|
+
// and only the commit sees both sides (FR-104).
|
|
197
|
+
const ended = pendingTransitions(state.snapshot, next, resolved, transactionId =>
|
|
198
|
+
provider.pendingEndReason?.(transactionId),
|
|
199
|
+
);
|
|
200
|
+
state.snapshot = next;
|
|
201
|
+
if (store.save(next) === false) {
|
|
202
|
+
// The write-intent-first guarantee (FR-042) did not hold for this write.
|
|
203
|
+
// Said out loud: the app learns its finalize queue may not survive a kill.
|
|
204
|
+
state.emit({
|
|
205
|
+
type: 'internal_error',
|
|
206
|
+
code: 'PAYMENT_STORAGE_UNAVAILABLE',
|
|
207
|
+
operation: 'persist',
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
// Before `recompute`, so `settled` precedes the `entitlement_granted` it
|
|
211
|
+
// causes (FR-102).
|
|
212
|
+
for (const transition of ended) {
|
|
213
|
+
state.emit({
|
|
214
|
+
type: 'purchase_pending_resolved',
|
|
215
|
+
productKey: transition.productKey,
|
|
216
|
+
outcome: transition.outcome,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
recompute();
|
|
220
|
+
},
|
|
221
|
+
|
|
222
|
+
hydrate() {
|
|
223
|
+
state.snapshot = store.load(config.scopeToken);
|
|
224
|
+
// A record with `lastSyncedAt` was written by a sync that succeeded, so it
|
|
225
|
+
// is a basis for asserting entitlement — and the only one a build with
|
|
226
|
+
// selling disabled will ever have (FR-012, FR-053).
|
|
227
|
+
if (state.snapshot.lastSyncedAt !== undefined) {
|
|
228
|
+
state.hasSynced = true;
|
|
229
|
+
}
|
|
230
|
+
if (!store.isDurable()) {
|
|
231
|
+
state.emit({
|
|
232
|
+
type: 'config_warning',
|
|
233
|
+
detail: 'Local storage unavailable; entitlements will not survive restart',
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
recompute();
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
forget() {
|
|
240
|
+
store.clearAll();
|
|
241
|
+
state.snapshot = emptySnapshot(config.scopeToken);
|
|
242
|
+
state.hasSynced = false;
|
|
243
|
+
// Back to `unknown`, not `not_entitled`: after a logout there is no basis
|
|
244
|
+
// for either claim until the next sync.
|
|
245
|
+
state.entitlements = initialEntitlements(resolved);
|
|
246
|
+
state.entitlementListeners.notify(state.entitlements);
|
|
247
|
+
// No `purchase_pending_resolved`: the records were discarded locally, not
|
|
248
|
+
// ended at the store.
|
|
249
|
+
publishPending(UNKNOWN_PENDING);
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
return state;
|
|
253
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Syncing with the store, and the one translation from a store purchase to a
|
|
3
|
+
* persisted record (PAY-10).
|
|
4
|
+
*
|
|
5
|
+
* The purchase flow and sync both build records here, so they cannot disagree
|
|
6
|
+
* about what a transaction still owes: a disagreement is how a paid purchase
|
|
7
|
+
* goes unacknowledged and is refunded three days later.
|
|
8
|
+
*/
|
|
9
|
+
import type { ProviderPurchase } from '../adapter/port';
|
|
10
|
+
import type { ProductKey } from '../config/types';
|
|
11
|
+
import type { ResolvedConfig } from '../config/validate';
|
|
12
|
+
import { PaymentError } from '../diagnostics/errors';
|
|
13
|
+
import type { SyncTrigger } from '../diagnostics/events';
|
|
14
|
+
import { productKeyForStoreId } from '../entitlements/mapping';
|
|
15
|
+
import { createRateLimiter, createSingleFlight, withTimeout } from '../core/mutex';
|
|
16
|
+
import { resolveFinalizeState, type PersistedPurchase } from '../persistence/snapshot';
|
|
17
|
+
import type { EngineState } from './state';
|
|
18
|
+
|
|
19
|
+
export type SyncOutcome =
|
|
20
|
+
{ ok: true; restoredCount: number; revokedCount: number } | { ok: false; error: PaymentError };
|
|
21
|
+
|
|
22
|
+
/** The persisted record for one store purchase, keeping what we already knew about it. */
|
|
23
|
+
export function toPersistedRecord(
|
|
24
|
+
resolved: ResolvedConfig,
|
|
25
|
+
purchase: ProviderPurchase,
|
|
26
|
+
productKey: ProductKey,
|
|
27
|
+
existing: PersistedPurchase | undefined,
|
|
28
|
+
): PersistedPurchase {
|
|
29
|
+
return {
|
|
30
|
+
transactionId: purchase.transactionId,
|
|
31
|
+
productKey,
|
|
32
|
+
productType: resolved.entries.get(productKey)?.productType ?? 'one_time_permanent',
|
|
33
|
+
token: purchase.token,
|
|
34
|
+
state: purchase.state === 'pending' ? 'pending' : 'purchased',
|
|
35
|
+
purchasedAt: purchase.purchasedAt,
|
|
36
|
+
// Finalize progress survives: a sync must never reset a queued
|
|
37
|
+
// acknowledgement and lose the paid transaction.
|
|
38
|
+
finalizeState: resolveFinalizeState(purchase, existing),
|
|
39
|
+
attempts: existing?.attempts ?? 0,
|
|
40
|
+
validationState: existing?.validationState ?? 'not_required',
|
|
41
|
+
expiresAt: purchase.expiresAt,
|
|
42
|
+
willAutoRenew: purchase.willAutoRenew,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Store purchases as records, dropping products this catalog does not know. */
|
|
47
|
+
function toPersisted(
|
|
48
|
+
resolved: ResolvedConfig,
|
|
49
|
+
purchases: readonly ProviderPurchase[],
|
|
50
|
+
known: readonly PersistedPurchase[],
|
|
51
|
+
): PersistedPurchase[] {
|
|
52
|
+
const records: PersistedPurchase[] = [];
|
|
53
|
+
for (const purchase of purchases) {
|
|
54
|
+
// Legitimately possible: a user owns something from a build whose catalog
|
|
55
|
+
// has since changed. Ignored rather than treated as impossible.
|
|
56
|
+
const productKey = productKeyForStoreId(resolved, purchase.storeProductId);
|
|
57
|
+
if (!productKey || !resolved.entries.has(productKey)) {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const existing = known.find(p => p.transactionId === purchase.transactionId);
|
|
61
|
+
if (purchase.state === 'unspecified') {
|
|
62
|
+
// No basis for granting, finalizing or ending anything: a new transaction
|
|
63
|
+
// waits until the store says what it is, a known one keeps what we knew.
|
|
64
|
+
if (existing) {
|
|
65
|
+
records.push(existing);
|
|
66
|
+
}
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
records.push(toPersistedRecord(resolved, purchase, productKey, existing));
|
|
70
|
+
}
|
|
71
|
+
return records;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function purchasedIds(records: readonly PersistedPurchase[]): Set<string> {
|
|
75
|
+
return new Set(records.filter(p => p.state === 'purchased').map(p => p.transactionId));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface Sync {
|
|
79
|
+
sync(trigger?: SyncTrigger): Promise<SyncOutcome>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `settle` runs after every successful sync, outside the sync flight: the finalize
|
|
84
|
+
* drain and backend revalidation (FR-039, FR-042, FR-072a). Inside the flight, one
|
|
85
|
+
* store call or hook that never answered held it, and every later sync joined
|
|
86
|
+
* that stuck promise for the rest of the session.
|
|
87
|
+
*/
|
|
88
|
+
export function createSync(state: EngineState, settle: () => Promise<void>): Sync {
|
|
89
|
+
const { resolved, provider, now } = state;
|
|
90
|
+
const syncFlight = createSingleFlight<SyncOutcome>();
|
|
91
|
+
const settleFlight = createSingleFlight<void>();
|
|
92
|
+
const foregroundLimiter = createRateLimiter(resolved.foregroundSyncMinIntervalMs, now);
|
|
93
|
+
|
|
94
|
+
async function querySnapshot(trigger: SyncTrigger): Promise<SyncOutcome> {
|
|
95
|
+
try {
|
|
96
|
+
const owned = await withTimeout(
|
|
97
|
+
provider.queryOwned(),
|
|
98
|
+
resolved.timeouts.syncMs,
|
|
99
|
+
() =>
|
|
100
|
+
new PaymentError({
|
|
101
|
+
code: 'PAYMENT_TIMEOUT',
|
|
102
|
+
message: 'Syncing entitlements timed out',
|
|
103
|
+
operation: 'sync',
|
|
104
|
+
retryable: true,
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
const before = purchasedIds(state.snapshot.purchases);
|
|
108
|
+
const records = toPersisted(resolved, owned, state.snapshot.purchases);
|
|
109
|
+
const after = purchasedIds(records);
|
|
110
|
+
// A transaction the store no longer reports is revoked — a refund. The
|
|
111
|
+
// cache must not resurrect it (FR-064, FR-055).
|
|
112
|
+
const revokedCount = [...before].filter(id => !after.has(id)).length;
|
|
113
|
+
const restoredCount = [...after].filter(id => !before.has(id)).length;
|
|
114
|
+
|
|
115
|
+
state.hasSynced = true;
|
|
116
|
+
state.commit({ ...state.snapshot, purchases: records, lastSyncedAt: now() });
|
|
117
|
+
state.emit({ type: 'sync_completed', restoredCount, revokedCount, trigger });
|
|
118
|
+
return { ok: true, restoredCount, revokedCount };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const paymentError =
|
|
121
|
+
error instanceof PaymentError
|
|
122
|
+
? error
|
|
123
|
+
: new PaymentError({
|
|
124
|
+
code: 'PAYMENT_STORE_ERROR',
|
|
125
|
+
message: 'Sync failed',
|
|
126
|
+
operation: 'sync',
|
|
127
|
+
retryable: true,
|
|
128
|
+
});
|
|
129
|
+
// A failed sync leaves the previous snapshot in place, so offline
|
|
130
|
+
// entitlements survive rather than being wiped (FR-053).
|
|
131
|
+
state.emit({ type: 'internal_error', code: paymentError.code, operation: 'sync' });
|
|
132
|
+
return { ok: false, error: paymentError };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
async sync(trigger = 'manual') {
|
|
138
|
+
if (state.disposed || !resolved.enabled) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
error: new PaymentError({
|
|
142
|
+
code: 'PAYMENT_DISABLED',
|
|
143
|
+
message: 'Payments are disabled',
|
|
144
|
+
operation: 'sync',
|
|
145
|
+
}),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// Rejected rather than deferred: the next foreground event tries again,
|
|
149
|
+
// whereas queueing would fire a burst once the interval elapsed (PERF-002).
|
|
150
|
+
if (trigger === 'foreground' && !foregroundLimiter.tryAcquire()) {
|
|
151
|
+
return { ok: true, restoredCount: 0, revokedCount: 0 };
|
|
152
|
+
}
|
|
153
|
+
// Concurrent callers join one flight: one store request (FR-063).
|
|
154
|
+
const outcome = await syncFlight.run(() => querySnapshot(trigger));
|
|
155
|
+
if (outcome.ok) {
|
|
156
|
+
await settleFlight.run(settle);
|
|
157
|
+
}
|
|
158
|
+
return outcome;
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* and the package says so rather than asserting the user did not pay.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import { shallowEqual } from '@chipmobilesdk/rn-core';
|
|
19
20
|
import type { ResolvedConfig } from '../config/validate';
|
|
20
21
|
import type { EntitlementKey, ProductKey } from '../config/types';
|
|
21
22
|
import type { PersistedPurchase, PersistedSnapshot } from '../persistence/snapshot';
|
|
@@ -55,11 +56,9 @@ export interface AggregateInput {
|
|
|
55
56
|
|
|
56
57
|
/** A purchase that currently confers its entitlements. */
|
|
57
58
|
function isValidSource(purchase: PersistedPurchase, input: AggregateInput): boolean {
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
if (purchase.state === 'revoked' || purchase.state === 'consumed') {
|
|
59
|
+
// Only a purchase the store confirmed grants. Pending money is not money, and a
|
|
60
|
+
// state this version does not know is no basis for a grant either (PAY-13).
|
|
61
|
+
if (purchase.state !== 'purchased') {
|
|
63
62
|
return false;
|
|
64
63
|
}
|
|
65
64
|
// A backend that said no is final (FR-071). A queued re-validation still
|
|
@@ -225,3 +224,36 @@ export function diffEntitlements(
|
|
|
225
224
|
}
|
|
226
225
|
return changes;
|
|
227
226
|
}
|
|
227
|
+
|
|
228
|
+
function sameEntitlement(a: EntitlementState, b: EntitlementState): boolean {
|
|
229
|
+
return (
|
|
230
|
+
a.status === b.status &&
|
|
231
|
+
a.isStale === b.isStale &&
|
|
232
|
+
a.lastSyncedAt === b.lastSyncedAt &&
|
|
233
|
+
a.sources.length === b.sources.length &&
|
|
234
|
+
a.sources.every((source, index) => source === b.sources[index]) &&
|
|
235
|
+
shallowEqual(a.subscription, b.subscription)
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* `next`, with every entitlement that did not change replaced by the object it
|
|
241
|
+
* replaces, and `previous` itself when nothing changed (PERF-03, PAY-08). A hook
|
|
242
|
+
* selecting one entitlement then sees the same object and does not re-render.
|
|
243
|
+
*/
|
|
244
|
+
export function shareUnchanged(previous: EntitlementMap, next: EntitlementMap): EntitlementMap {
|
|
245
|
+
const keys = Object.keys(next);
|
|
246
|
+
let changed = keys.length !== Object.keys(previous).length;
|
|
247
|
+
const shared: EntitlementMap = {};
|
|
248
|
+
for (const key of keys) {
|
|
249
|
+
const before = previous[key];
|
|
250
|
+
const after = next[key]!;
|
|
251
|
+
if (before && sameEntitlement(before, after)) {
|
|
252
|
+
shared[key] = before;
|
|
253
|
+
} else {
|
|
254
|
+
shared[key] = after;
|
|
255
|
+
changed = true;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return changed ? shared : previous;
|
|
259
|
+
}
|
|
@@ -21,14 +21,6 @@ export function entitlementsFor(
|
|
|
21
21
|
return config.grants.get(productKey) ?? [];
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
/** Products that could grant an entitlement, whether or not any is currently valid. */
|
|
25
|
-
export function sourcesFor(
|
|
26
|
-
config: ResolvedConfig,
|
|
27
|
-
entitlementKey: EntitlementKey,
|
|
28
|
-
): readonly ProductKey[] {
|
|
29
|
-
return config.sources.get(entitlementKey) ?? [];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
24
|
/**
|
|
33
25
|
* Translates a store product id back to the app's own product key.
|
|
34
26
|
*
|
|
@@ -51,17 +43,3 @@ export function storeIdForProductKey(
|
|
|
51
43
|
): string | undefined {
|
|
52
44
|
return config.entries.get(productKey)?.storeProductIds[config.platform];
|
|
53
45
|
}
|
|
54
|
-
|
|
55
|
-
/** Which entitlements a set of granting products covers, de-duplicated. */
|
|
56
|
-
export function entitlementsCoveredBy(
|
|
57
|
-
config: ResolvedConfig,
|
|
58
|
-
productKeys: Iterable<ProductKey>,
|
|
59
|
-
): Set<EntitlementKey> {
|
|
60
|
-
const covered = new Set<EntitlementKey>();
|
|
61
|
-
for (const productKey of productKeys) {
|
|
62
|
-
for (const entitlement of entitlementsFor(config, productKey)) {
|
|
63
|
-
covered.add(entitlement);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
return covered;
|
|
67
|
-
}
|
package/src/index.ts
CHANGED
|
@@ -120,6 +120,8 @@ export type {
|
|
|
120
120
|
SyncOutcome,
|
|
121
121
|
} from './engine/engine';
|
|
122
122
|
|
|
123
|
+
export { syncOnForeground } from './engine/foreground';
|
|
124
|
+
|
|
123
125
|
// --- React -----------------------------------------------------------------
|
|
124
126
|
export { PaymentProvider, usePaymentEngine } from './react/PaymentProvider';
|
|
125
127
|
export type { PaymentProviderProps } from './react/PaymentProvider';
|
|
@@ -150,6 +152,7 @@ export type {
|
|
|
150
152
|
export {
|
|
151
153
|
DEFAULT_DEVELOPER_MESSAGES,
|
|
152
154
|
DEFAULT_MESSAGES,
|
|
155
|
+
paymentMessages,
|
|
153
156
|
DEFAULT_USER_MESSAGES,
|
|
154
157
|
DEVELOPER_MESSAGE_KEYS,
|
|
155
158
|
USER_MESSAGE_KEYS,
|
|
@@ -14,23 +14,29 @@
|
|
|
14
14
|
* attached to a transaction.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { createMemoryKeyValue, lazyPeer, openDurable, type MmkvLike } from '@chipmobilesdk/rn-core';
|
|
18
|
+
|
|
17
19
|
import { emptySnapshot, migrateSnapshot, type PersistedSnapshot } from './snapshot';
|
|
18
20
|
|
|
19
21
|
const INSTANCE_ID = 'chipmobilesdk.payment';
|
|
20
22
|
const KEY_PREFIX = 'snapshot';
|
|
21
23
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
24
|
+
const mmkv = lazyPeer('react-native-mmkv', () => {
|
|
25
|
+
// Inside `try`, so Metro bundles an app that leaves this optional peer out.
|
|
26
|
+
try {
|
|
27
|
+
return require('react-native-mmkv') as { createMMKV: (config?: { id?: string }) => MmkvLike };
|
|
28
|
+
} catch (cause) {
|
|
29
|
+
throw cause;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
30
32
|
|
|
31
33
|
export interface SnapshotStore {
|
|
32
34
|
load(scopeToken?: string): PersistedSnapshot;
|
|
33
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Writes the snapshot. Returns false when the write failed, so the engine can
|
|
37
|
+
* say so; a store returning nothing is taken to have succeeded.
|
|
38
|
+
*/
|
|
39
|
+
save(snapshot: PersistedSnapshot): boolean | void;
|
|
34
40
|
/** Clears every scope — for logout and data-deletion requests (FR-057). */
|
|
35
41
|
clearAll(): void;
|
|
36
42
|
/** Whether writes actually persist. False means the memory fallback is active. */
|
|
@@ -43,20 +49,6 @@ function scopeKey(scopeToken?: string): string {
|
|
|
43
49
|
return `${KEY_PREFIX}:${scopeToken ?? '__default__'}`;
|
|
44
50
|
}
|
|
45
51
|
|
|
46
|
-
/** In-memory fallback, used when the native module is absent. */
|
|
47
|
-
function createMemoryBacking(): MmkvLike {
|
|
48
|
-
const map = new Map<string, string>();
|
|
49
|
-
return {
|
|
50
|
-
getString: key => map.get(key),
|
|
51
|
-
set(key, value) {
|
|
52
|
-
map.set(key, value);
|
|
53
|
-
},
|
|
54
|
-
remove: key => map.delete(key),
|
|
55
|
-
clearAll: () => map.clear(),
|
|
56
|
-
getAllKeys: () => [...map.keys()],
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
|
|
60
52
|
/**
|
|
61
53
|
* Opens the MMKV instance through v4's `createMMKV`.
|
|
62
54
|
*
|
|
@@ -67,15 +59,20 @@ function createMemoryBacking(): MmkvLike {
|
|
|
67
59
|
* Tests could not see it, because the test double still exported a v3 class.
|
|
68
60
|
*/
|
|
69
61
|
function resolveBacking(): { backing: MmkvLike; durable: boolean } {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
62
|
+
// rn-core's port: MMKV when it opens, otherwise memory with `durable: false`.
|
|
63
|
+
const port = openDurable(() =>
|
|
64
|
+
mmkv.require(peer => new Error(`${peer} is not installed`)).createMMKV({ id: INSTANCE_ID }),
|
|
65
|
+
);
|
|
66
|
+
return {
|
|
67
|
+
backing: {
|
|
68
|
+
getString: key => port.getString(key),
|
|
69
|
+
set: (key, value) => port.set(key, value),
|
|
70
|
+
remove: key => port.remove(key),
|
|
71
|
+
clearAll: () => port.clearAll(),
|
|
72
|
+
getAllKeys: () => port.keys(),
|
|
73
|
+
},
|
|
74
|
+
durable: port.durable,
|
|
75
|
+
};
|
|
79
76
|
}
|
|
80
77
|
|
|
81
78
|
/**
|
|
@@ -124,12 +121,15 @@ export function createSnapshotStore(injected?: {
|
|
|
124
121
|
return outcome.snapshot;
|
|
125
122
|
},
|
|
126
123
|
|
|
127
|
-
save(snapshot: PersistedSnapshot):
|
|
124
|
+
save(snapshot: PersistedSnapshot): boolean {
|
|
128
125
|
try {
|
|
129
126
|
backing.set(scopeKey(snapshot.scopeToken), JSON.stringify(snapshot));
|
|
127
|
+
return true;
|
|
130
128
|
} catch {
|
|
131
129
|
// A failed write must never take down a purchase flow. The in-memory
|
|
132
|
-
// state stays correct for this session and the next sync re-derives it
|
|
130
|
+
// state stays correct for this session and the next sync re-derives it;
|
|
131
|
+
// the engine reports it (PAY-13).
|
|
132
|
+
return false;
|
|
133
133
|
}
|
|
134
134
|
},
|
|
135
135
|
|
|
@@ -151,5 +151,15 @@ export function createSnapshotStore(injected?: {
|
|
|
151
151
|
|
|
152
152
|
/** Test seam for driving the store without the native module. */
|
|
153
153
|
export function createMemorySnapshotStore(): SnapshotStore {
|
|
154
|
-
|
|
154
|
+
const memory = createMemoryKeyValue();
|
|
155
|
+
return createSnapshotStore({
|
|
156
|
+
backing: {
|
|
157
|
+
getString: key => memory.getString(key),
|
|
158
|
+
set: (key, value) => memory.set(key, value),
|
|
159
|
+
remove: key => memory.remove(key),
|
|
160
|
+
clearAll: () => memory.clearAll(),
|
|
161
|
+
getAllKeys: () => memory.keys(),
|
|
162
|
+
},
|
|
163
|
+
durable: false,
|
|
164
|
+
});
|
|
155
165
|
}
|