expo-iap 6.4.2 → 6.4.3

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/build/index.d.ts CHANGED
@@ -427,8 +427,8 @@ export declare function createPurchaseFlow<P extends PurchaseFlowPurchase>(optio
427
427
  export declare function confirmWithIapkit(options: IapkitConfirmationOptions<Purchase>): PurchaseFlowOptions<Purchase>['confirmWithBackend'];
428
428
  /**
429
429
  * Confirms App Store purchases on the device, for apps with neither a backend
430
- * nor IAPKit: StoreKit must still list the transaction as unfinished and
431
- * valid. Credit consumables in `grant`.
430
+ * nor IAPKit: StoreKit must list the transaction as unfinished, or for a
431
+ * restore in its verified history, and valid. Credit consumables in `grant`.
432
432
  */
433
433
  export declare function confirmOnDeviceIOS(options?: {
434
434
  /** Required for consumables; credit each purchase.id only once. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGL,KAAK,yBAAyB,EAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAKL,KAAK,sBAAsB,EAC5B,MAAM,6BAA6B,CAAC;AAcrC,OAAO,KAAK,EAGV,sCAAsC,EAEtC,aAAa,EAEb,OAAO,EACP,gBAAgB,EAEhB,QAAQ,EAER,8BAA8B,EAC9B,UAAU,EAOV,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAGL,KAAK,aAAa,EACnB,MAAM,sBAAsB,CAAC;AAM9B,cAAc,SAAS,CAAC;AACxB,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AAEvB,oBAAY,YAAY;IACtB,eAAe,qBAAqB;IACpC,aAAa,mBAAmB;IAChC,kBAA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AAM,EAAE,WAAW,EAAE,uBAAuB,EAAC,MAAM,WAAW,CAAC;AACvE,YAAY,EACV,aAAa,EACb,qBAAqB,EACrB,uBAAuB,EACvB,wBAAwB,EACxB,yBAAyB,EACzB,gCAAgC,EAChC,0BAA0B,EAC1B,UAAU,EACV,uBAAuB,EACvB,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,oBAAoB,EACpB,cAAc,GACf,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,oBAAoB,EACpB,2BAA2B,EAC3B,YAAY,EACZ,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAC,yBAAyB,EAAC,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,+BAA+B,EAC/B,2BAA2B,EAC3B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,aAAa,IAAI,iBAAiB,EAClC,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC"}
package/build/index.js CHANGED
@@ -1050,11 +1050,14 @@ export function confirmWithIapkit(options) {
1050
1050
  }
1051
1051
  /**
1052
1052
  * Confirms App Store purchases on the device, for apps with neither a backend
1053
- * nor IAPKit: StoreKit must still list the transaction as unfinished and
1054
- * valid. Credit consumables in `grant`.
1053
+ * nor IAPKit: StoreKit must list the transaction as unfinished, or for a
1054
+ * restore in its verified history, and valid. Credit consumables in `grant`.
1055
1055
  */
1056
1056
  export function confirmOnDeviceIOS(options = {}) {
1057
- return createDeviceConfirmationIOS(() => getPendingTransactionsIOS(), options);
1057
+ return createDeviceConfirmationIOS(() => getPendingTransactionsIOS(), {
1058
+ ...options,
1059
+ getTransactionHistoryIOS: () => getAvailablePurchases({ onlyIncludeActiveItemsIOS: false }),
1060
+ });
1058
1061
  }
1059
1062
  export * from './useIAP';
1060
1063
  export { kitApi, KitApiError, resolveLocalizedPayload } from './kit-api';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAC;AAEtC,mBAAmB;AACnB,OAAO,aAAa,EAAE,EAAC,eAAe,EAAC,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAC,QAAQ,EAAC,MAAM,QAAQ,CAAC;AAChC,OAAO,EACL,0BAA0B,EAC1B,yBAAyB,EACzB,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAIN,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,2BAA2B,EAC3B,wBAAwB,GAEzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,aAAa,GAGd,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,gBAAgB,EAChB,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAC,uBAAuB,EAAC,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAC,sBAAsB,EAAC,MAAM,0BAA0B,CAAC;AAChE,OAAO,EACL,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,4BAA4B,CAAC;AAyBpC,OAAO,EAAC,SAAS,EAAE,cAAc,EAAC,MAAM,SAAS,CAAC;AAClD,OAAO,EACL,mBAAmB,EACnB,4BAA4B,GAE7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,sCAAsC,EACtC,6BAA6B,GAC9B,MAAM,qBAAqB,CAAC;AAE7B,cA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,yBAAyB,EAAE,EACjC,OAAO,CACR,CAAC;AACJ,CAAC;AAED,cAAc,UAAU,CAAC;AACzB,OAAO,EAAC,MAAM,EAAE,WAAW,EAAE,uBAAuB,EAAC,MAAM,WAAW,CAAC;AAmBvE,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,sBAAsB,CAAC;AAc9B,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,+BAA+B,EAC/B,2BAA2B,EAC3B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC","sourcesContent":["// External dependencies\nimport {Platform} from 'react-native';\n\n// Internal modules\nimport ExpoIapModule, {getNativeModule} from './ExpoIapModule';\nimport {isVegaOS} from './vega';\nimport {\n deepLinkToSubscriptionsIOS,\n getPendingTransactionsIOS,\n isProductIOS,\n} from './modules/ios';\nimport {\n type PurchaseFlow,\n type PurchaseFlowOptions,\n type PurchaseFlowPurchase,\n} from './purchase-flow-core';\nimport {\n createDeviceConfirmationIOS,\n createIapkitConfirmation,\n type IapkitConfirmationOptions,\n} from './purchase-flow-confirmers';\nimport {\n clearRequested,\n createSdkPurchaseFlow,\n markRequested,\n type PurchaseFlowSdk,\n type SdkPurchaseFlowOptions,\n} from './utils/purchaseFlowBinding';\nimport {\n isProductAndroid,\n deepLinkToSubscriptionsAndroid,\n} from './modules/android';\nimport {ExpoIapConsole} from './utils/debug';\nimport {showFirstPurchaseNotice} from './utils/firstPurchaseNotice';\nimport {restorePurchasesNative} from './utils/restorePurchases';\nimport {\n decodeAndroidPurchases,\n decodeApplePurchases,\n} from './utils/availablePurchases';\n\n// Types\nimport type {\n ActiveSubscription,\n DeepLinkOptions,\n DeveloperProvidedBillingDetailsAndroid,\n IapPlatform,\n MutationField,\n MutationRequestPurchaseArgs,\n Product,\n ProductQueryType,\n ProductSubscription,\n Purchase,\n PurchaseOptions,\n PurchaseUpdatedListenerOptions,\n QueryField,\n RequestPurchasePropsByPlatforms,\n RequestPurchaseAndroidProps,\n RequestPurchaseIosProps,\n RequestSubscriptionPropsByPlatforms,\n RequestSubscriptionAndroidProps,\n RequestSubscriptionIosProps,\n UserChoiceBillingDetails,\n} from './types';\nimport {ErrorCode, resolveStoreId} from './types';\nimport {\n createPurchaseError,\n normalizeErrorCodeFromNative,\n type PurchaseError,\n} from './utils/errorMapping';\nimport {\n createPurchaseErrorFromNativeException,\n invokeNativeWithPurchaseError,\n} from './utils/nativeError';\n\nexport * from './types';\nexport * from './modules/android';\nexport * from './modules/ios';\nexport * from './onside';\nexport * from './vega';\n\nexport enum OpenIapEvent {\n PurchaseUpdated = 'purchase-updated',\n PurchaseError = 'purchase-error',\n PromotedProductIOS = 'promoted-product-ios',\n UserChoiceBillingAndroid = 'user-choice-billing-android',\n /**\n * Fired for External Payments (8.3.0+) and Billing Choice (9.1.0+)\n * developer billing flows. Nullable fields depend on the selected flow.\n */\n DeveloperProvidedBillingAndroid = 'developer-provided-billing-android',\n /** Fired when a subscription enters a billing-issue state; see `subscriptionBillingIssueListener`. */\n SubscriptionBillingIssue = 'subscription-billing-issue',\n}\n\ntype ExpoIapEventPayloads = {\n [OpenIapEvent.PurchaseUpdated]: Purchase;\n [OpenIapEvent.PurchaseError]: PurchaseError;\n [OpenIapEvent.PromotedProductIOS]:\n | Product\n | string\n | {id?: string; productId?: string};\n [OpenIapEvent.UserChoiceBillingAndroid]: UserChoiceBillingDetails;\n [OpenIapEvent.DeveloperProvidedBillingAndroid]: DeveloperProvidedBillingDetailsAndroid;\n [OpenIapEvent.SubscriptionBillingIssue]: Purchase;\n};\n\ntype ExpoIapEventListener<E extends OpenIapEvent> = (\n payload: ExpoIapEventPayloads[E],\n) => void;\n\ntype ExpoIapEmitter = {\n addListener<E extends OpenIapEvent>(\n eventName: E,\n listener: ExpoIapEventListener<E>,\n ): {remove: () => void};\n removeListener<E extends OpenIapEvent>(\n eventName: E,\n listener: ExpoIapEventListener<E>,\n ): void;\n};\n\nconst isStorePlatform = (): boolean =>\n Platform.OS === 'ios' || Platform.OS === 'android';\n\nconst isStoreRuntime = (): boolean =>\n Platform.OS === 'ios' || isAndroidStoreRuntime();\n\nconst unsupportedPlatformError = (): Error =>\n new Error(`Unsupported platform: ${Platform.OS}`);\n\n// Platform tag for PurchaseErrors built from native rejections.\nconst nativePlatform = (): IapPlatform =>\n Platform.OS === 'ios' ? 'ios' : 'android';\n\n// Listener calls go to the raw native module (see getNativeModule), resolved\n// lazily so importing this module doesn't throw on unsupported platforms.\nexport const emitter: ExpoIapEmitter = {\n addListener(eventName, listener) {\n const nativeModule = getNativeModule();\n const nativeSubscription = nativeModule.addListener(eventName, listener);\n let removed = false;\n\n return {\n remove: () => {\n if (removed) {\n return;\n }\n removed = true;\n\n if (typeof nativeSubscription?.remove === 'function') {\n nativeSubscription.remove();\n return;\n }\n\n nativeModule.removeListener?.(eventName, listener);\n },\n };\n },\n removeListener(eventName, listener) {\n return getNativeModule().removeListener?.(eventName, listener);\n },\n};\n\nlet nonDedupingPurchaseUpdatedListenerCountIOS = 0;\nconst purchaseUpdatedDedupeHistoryLimitIOS = 512;\nconst purchaseUpdatedDedupeHistoryIOS = {\n ids: new Set<string>(),\n order: [] as string[],\n start: 0,\n};\nlet purchaseUpdatedDedupeGenerationIOS = 0;\n\ntype PurchaseUpdatedDedupeHistoryIOS = {\n ids: Set<string>;\n order: string[];\n start: number;\n};\n\nconst purchaseUpdatedTransactionIdIOS = (purchase: Purchase) => {\n if (typeof purchase.id === 'string' && purchase.id.length > 0) {\n return purchase.id;\n }\n return null;\n};\n\nconst rememberPurchaseUpdatedTransactionIOS = (\n transactionId: string,\n history: PurchaseUpdatedDedupeHistoryIOS,\n) => {\n if (history.ids.has(transactionId)) {\n return;\n }\n\n history.ids.add(transactionId);\n history.order.push(transactionId);\n if (\n history.order.length - history.start >\n purchaseUpdatedDedupeHistoryLimitIOS\n ) {\n const evicted = history.order[history.start];\n history.start += 1;\n if (evicted != null) {\n history.ids.delete(evicted);\n }\n if (history.start > 128 && history.start * 2 > history.order.length) {\n history.order = history.order.slice(history.start);\n history.start = 0;\n }\n }\n};\n\nconst clearPurchaseUpdatedDedupeHistoryIOS = (\n history: PurchaseUpdatedDedupeHistoryIOS,\n) => {\n history.ids.clear();\n history.order.length = 0;\n history.start = 0;\n};\n\nconst resetPurchaseUpdatedDedupeHistoryIOS = () => {\n clearPurchaseUpdatedDedupeHistoryIOS(purchaseUpdatedDedupeHistoryIOS);\n purchaseUpdatedDedupeGenerationIOS += 1;\n};\n\nconst configurePurchaseUpdatedListenerOptionsIOS = (\n dedupeTransactionIOS: boolean,\n) => {\n if (Platform.OS !== 'ios') return;\n\n const promise = getNativeModule().setPurchaseUpdatedListenerOptions?.({\n dedupeTransactionIOS,\n });\n void promise?.catch((error: unknown) => {\n ExpoIapConsole.warn(\n 'Failed to configure purchase updated listener options:',\n error,\n );\n });\n};\n\nexport type ProductTypeInput = ProductQueryType;\n\nconst normalizeProductType = (type?: ProductTypeInput) => {\n if (!type || type === 'in-app') {\n return {\n canonical: 'in-app' as ProductQueryType,\n native: 'in-app' as const,\n };\n }\n if (type === 'subs') {\n return {\n canonical: 'subs' as ProductQueryType,\n native: 'subs' as const,\n };\n }\n if (type === 'all') {\n return {\n canonical: 'all' as ProductQueryType,\n native: 'all' as const,\n };\n }\n throw new Error(`Unsupported product type: ${type}`);\n};\n\nconst isAndroidStoreRuntime = (): boolean => {\n return Platform.OS === 'android' || isVegaOS();\n};\n\nexport const purchaseUpdatedListener = (\n listener: (event: Purchase) => void,\n options?: PurchaseUpdatedListenerOptions | null,\n) => {\n const receiveDuplicateTransactionUpdatesIOS =\n Platform.OS === 'ios' && options?.dedupeTransactionIOS === false;\n const listenerDedupeHistoryIOS: PurchaseUpdatedDedupeHistoryIOS = {\n ids: new Set(purchaseUpdatedDedupeHistoryIOS.ids),\n order: purchaseUpdatedDedupeHistoryIOS.order.slice(\n purchaseUpdatedDedupeHistoryIOS.start,\n ),\n start: 0,\n };\n let listenerDedupeGenerationIOS = purchaseUpdatedDedupeGenerationIOS;\n\n const wrappedListener = (event: Purchase) => {\n const normalized = event;\n if (Platform.OS === 'ios') {\n if (listenerDedupeGenerationIOS !== purchaseUpdatedDedupeGenerationIOS) {\n clearPurchaseUpdatedDedupeHistoryIOS(listenerDedupeHistoryIOS);\n listenerDedupeGenerationIOS = purchaseUpdatedDedupeGenerationIOS;\n }\n const transactionId = purchaseUpdatedTransactionIdIOS(normalized);\n if (transactionId != null) {\n const isDuplicateForListener =\n listenerDedupeHistoryIOS.ids.has(transactionId);\n rememberPurchaseUpdatedTransactionIOS(\n transactionId,\n listenerDedupeHistoryIOS,\n );\n rememberPurchaseUpdatedTransactionIOS(\n transactionId,\n purchaseUpdatedDedupeHistoryIOS,\n );\n if (!receiveDuplicateTransactionUpdatesIOS && isDuplicateForListener) {\n return;\n }\n }\n }\n listener(normalized);\n };\n const emitterSubscription = emitter.addListener(\n OpenIapEvent.PurchaseUpdated,\n wrappedListener,\n );\n\n if (!receiveDuplicateTransactionUpdatesIOS) {\n return emitterSubscription;\n }\n\n nonDedupingPurchaseUpdatedListenerCountIOS += 1;\n configurePurchaseUpdatedListenerOptionsIOS(false);\n let removed = false;\n\n return {\n remove: () => {\n if (removed) {\n return;\n }\n removed = true;\n try {\n emitterSubscription?.remove?.();\n } finally {\n nonDedupingPurchaseUpdatedListenerCountIOS = Math.max(\n 0,\n nonDedupingPurchaseUpdatedListenerCountIOS - 1,\n );\n configurePurchaseUpdatedListenerOptionsIOS(\n nonDedupingPurchaseUpdatedListenerCountIOS === 0,\n );\n }\n },\n };\n};\n\nexport const purchaseErrorListener = (\n listener: (error: PurchaseError) => void,\n) => {\n // Native events may carry codes outside ErrorCode; deliver canonical codes.\n const wrappedListener = (error: PurchaseError) => {\n listener({...error, code: normalizeErrorCodeFromNative(error.code)});\n };\n const emitterSubscription = emitter.addListener(\n OpenIapEvent.PurchaseError,\n wrappedListener,\n );\n return emitterSubscription;\n};\n\n/**\n * iOS-only listener for App Store promoted product events.\n * This fires when a user taps on a promoted product in the App Store.\n *\n * @param listener - Callback function that receives the promoted product details\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = promotedProductListenerIOS((product) => {\n * console.log('Promoted product:', product);\n * // Handle the promoted product\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform iOS\n */\nexport const promotedProductListenerIOS = (\n listener: (product: Product) => void,\n) => {\n if (Platform.OS !== 'ios') {\n ExpoIapConsole.warn(\n 'promotedProductListenerIOS: This listener is only available on iOS',\n );\n return {remove: () => {}};\n }\n\n let deliveredProductId: string | undefined;\n const deliver = (product: Product) => {\n const productId =\n product.id ?? (product as Product & {productId?: string}).productId;\n if (productId && productId === deliveredProductId) {\n return;\n }\n deliveredProductId = productId;\n listener(product);\n };\n\n const replayPendingProduct = () => {\n let pendingProduct: Promise<Product | null> | undefined;\n try {\n pendingProduct = ExpoIapModule.getPromotedProductIOS() as\n | Promise<Product | null>\n | undefined;\n } catch {\n return Promise.resolve();\n }\n\n if (!pendingProduct || typeof pendingProduct.then !== 'function') {\n return Promise.resolve();\n }\n\n return pendingProduct\n .then((product: Product | null) => {\n if (product) {\n deliver(product);\n }\n })\n .catch(() => {});\n };\n\n const subscription = emitter.addListener(\n OpenIapEvent.PromotedProductIOS,\n (payload) => {\n if (typeof payload === 'string') {\n void replayPendingProduct();\n return;\n }\n\n deliver(payload as Product);\n },\n );\n\n void replayPendingProduct();\n\n return subscription;\n};\n\n/**\n * Android-only listener for User Choice Billing events.\n * This fires when a user selects alternative billing instead of Google Play billing\n * in the User Choice Billing dialog (only in 'user-choice' mode).\n *\n * @param listener - Callback function that receives the external transaction token and product IDs\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = userChoiceBillingListenerAndroid((details) => {\n * console.log('User selected alternative billing');\n * console.log('External transaction token received; send it to your backend without logging it.');\n * console.log('Products:', details.products);\n *\n * // Process payment in your system, then report token to Google\n * await processPaymentAndReportToken(details);\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform Android\n */\nexport const userChoiceBillingListenerAndroid = (\n listener: (details: UserChoiceBillingDetails) => void,\n) => {\n if (Platform.OS !== 'android') {\n ExpoIapConsole.warn(\n 'userChoiceBillingListenerAndroid: This listener is only available on Android',\n );\n return {remove: () => {}};\n }\n return emitter.addListener(OpenIapEvent.UserChoiceBillingAndroid, listener);\n};\n\n/**\n * Android-only listener for Developer Provided Billing events.\n * This fires when a user selects the developer's option in an External Payments\n * or Billing Choice purchase flow.\n *\n * @param listener - Callback that receives selected products and flow details\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = developerProvidedBillingListenerAndroid(async (details) => {\n * await processPaymentWithYourGateway(details.products, details.linkUri);\n * if (details.externalTransactionToken) {\n * await reportExternalTransactionToGoogle(details.externalTransactionToken);\n * }\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform Android (Play Billing Library 8.3.0+; Billing Choice 9.1.0+)\n */\nexport const developerProvidedBillingListenerAndroid = (\n listener: (details: DeveloperProvidedBillingDetailsAndroid) => void,\n) => {\n if (Platform.OS !== 'android') {\n ExpoIapConsole.warn(\n 'developerProvidedBillingListenerAndroid: This listener is only available on Android',\n );\n return {remove: () => {}};\n }\n return emitter.addListener(\n OpenIapEvent.DeveloperProvidedBillingAndroid,\n listener,\n );\n};\n\n/**\n * Listen for subscription billing-issue events (cross-platform).\n *\n * Fires when a user's active subscription enters a state that needs attention\n * for a payment problem. Unifies:\n * - iOS / Mac Catalyst 16.4+ and visionOS 1.0+: StoreKit 2 `Message.Reason.billingIssue`.\n * - Android (Play Billing 8.1+): when `Purchase.isSuspendedAndroid === true`.\n * - Meta Horizon, Amazon, macOS, tvOS, watchOS, and iOS before 16.4: never fires.\n *\n * Recommended UX: call `deepLinkToSubscriptions()` when this fires so the user\n * can update their payment method in the platform subscription center.\n *\n * @example\n * ```typescript\n * const subscription = subscriptionBillingIssueListener((purchase) => {\n * console.warn('Needs attention:', purchase.productId);\n * deepLinkToSubscriptions({\n * skuAndroid: purchase.productId,\n * packageNameAndroid: 'com.example.app',\n * });\n * });\n * ```\n */\nexport const subscriptionBillingIssueListener = (\n listener: (purchase: Purchase) => void,\n) => {\n const wrappedListener = (event: Purchase) => {\n listener(event);\n };\n return emitter.addListener(\n OpenIapEvent.SubscriptionBillingIssue,\n wrappedListener,\n );\n};\n\n/**\n * Initialize the store connection. Must be called before any other IAP API.\n *\n * @param config Optional connection config. Use `enableBillingProgramAndroid` (Android,\n * Play Billing 8.2.0+) to opt into a billing program. For Billing Choice 9.1.0+, set\n * `billingChoiceScreenTypeAndroid` to the renderer configured in Play Console.\n * iOS ignores Android-specific fields.\n * @returns Promise resolving to `true` when the platform billing client is connected.\n * @throws When the platform billing client fails to initialize.\n *\n * @example\n * ```ts\n * await initConnection();\n * await initConnection({ enableBillingProgramAndroid: 'external-offer' });\n * await initConnection({\n * enableBillingProgramAndroid: 'billing-choice',\n * billingChoiceScreenTypeAndroid: 'developer-rendered',\n * });\n * ```\n *\n * @remarks When using `useIAP()`, connection is auto-managed on mount/unmount —\n * pass options to the hook instead of calling this directly.\n *\n * @see {@link https://openiap.dev/docs/apis/init-connection}\n */\nexport const initConnection: MutationField<'initConnection'> = async (\n config,\n) => {\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.initConnection(config ?? null),\n nativePlatform(),\n );\n if (\n result === true &&\n Platform.OS === 'ios' &&\n nonDedupingPurchaseUpdatedListenerCountIOS > 0\n ) {\n configurePurchaseUpdatedListenerOptionsIOS(false);\n }\n return result;\n};\n\n/**\n * Close the store connection and release resources.\n *\n * @see {@link https://openiap.dev/docs/apis/end-connection}\n */\nexport const endConnection: MutationField<'endConnection'> = async () => {\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.endConnection(),\n nativePlatform(),\n );\n if (result === true && Platform.OS === 'ios') {\n resetPurchaseUpdatedDedupeHistoryIOS();\n }\n return result;\n};\n\n/**\n * Retrieve products or subscriptions from the store by SKU.\n *\n * @param request `ProductRequest` — `skus` (string[]) and optional `type`\n * (`'in-app' | 'subs' | 'all'`, defaults to `'in-app'`).\n * @returns Promise resolving to a `FetchProductsResult` union — `Product[]` for `'in-app'`,\n * `ProductSubscription[]` for `'subs'`, or a mixed array for `'all'`.\n * @throws When the store rejects the request (empty `skus`, not connected,\n * network/store error). Unknown SKUs are omitted from the result, not thrown.\n *\n * @example\n * ```ts\n * const products = await fetchProducts({\n * skus: ['com.app.coins_100', 'com.app.premium'],\n * type: 'in-app',\n * });\n * ```\n *\n * @remarks Promise-based, unlike the event-based `request*` APIs such as `requestPurchase`.\n *\n * @see {@link https://openiap.dev/docs/apis/fetch-products}\n */\nexport const fetchProducts: QueryField<'fetchProducts'> = async (request) => {\n ExpoIapConsole.debug('fetchProducts called with:', request);\n const {skus, type} = request ?? {};\n\n if (!Array.isArray(skus) || skus.length === 0) {\n throw createPurchaseError({\n message: 'No SKUs provided',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {canonical, native} = normalizeProductType(\n type as ProductTypeInput | undefined,\n );\n const skuSet = new Set(skus);\n\n const filterIosItems = (\n items: unknown[],\n ): (Product | ProductSubscription)[] =>\n items.filter((item): item is Product | ProductSubscription => {\n if (!isProductIOS(item)) {\n return false;\n }\n const candidate = item as Product | ProductSubscription;\n return typeof candidate.id === 'string' && skuSet.has(candidate.id);\n });\n\n const filterAndroidItems = (\n items: unknown[],\n ): (Product | ProductSubscription)[] =>\n items.filter((item): item is Product | ProductSubscription => {\n if (!isProductAndroid(item)) {\n return false;\n }\n const candidate = item as Product | ProductSubscription;\n return typeof candidate.id === 'string' && skuSet.has(candidate.id);\n });\n\n const castResult = (\n items: (Product | ProductSubscription)[],\n ):\n | (Product | ProductSubscription)[]\n | Product[]\n | ProductSubscription[]\n | null => {\n if (canonical === 'in-app') {\n return items as Product[];\n }\n if (canonical === 'subs') {\n return items as ProductSubscription[];\n }\n // 'all' mixes products and subscriptions; returned as-is to keep the discriminated union.\n return items;\n };\n\n if (Platform.OS === 'ios') {\n const rawItems = await invokeNativeWithPurchaseError<unknown[]>(\n () => ExpoIapModule.fetchProducts({skus, type: native}),\n 'ios',\n {\n code: ErrorCode.QueryProduct,\n message: 'Failed to query products',\n productIds: skus,\n productType: canonical,\n },\n );\n return castResult(filterIosItems(rawItems));\n }\n\n if (isAndroidStoreRuntime()) {\n const rawItems = await invokeNativeWithPurchaseError<unknown[]>(\n () => ExpoIapModule.fetchProducts(native, skus),\n 'android',\n {\n code: ErrorCode.QueryProduct,\n message: 'Failed to query products',\n productIds: skus,\n productType: canonical,\n },\n );\n return castResult(filterAndroidItems(rawItems));\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * List the user's unfinished purchases: non-consumables, active subscriptions,\n * and pending transactions.\n *\n * @param options Optional `PurchaseOptions`. iOS-only flags:\n * `alsoPublishToEventListenerIOS`, `onlyIncludeActiveItemsIOS`.\n * @returns Promise resolving to an array of `Purchase` currently held by the store.\n * @throws When the platform query fails.\n *\n * @example\n * ```ts\n * const purchases = await getAvailablePurchases();\n * for (const p of purchases) {\n * if (await verifyOnServer(p)) await finishTransaction({ purchase: p, isConsumable: false });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-available-purchases}\n */\nexport const getAvailablePurchases: QueryField<\n 'getAvailablePurchases'\n> = async (options) => {\n const normalizedOptions = {\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n } satisfies PurchaseOptions;\n\n if (isVegaOS()) {\n const purchases = await ExpoIapModule.getAvailableItems(normalizedOptions);\n return decodeAndroidPurchases(purchases);\n }\n\n let purchases: Purchase[];\n\n if (Platform.OS === 'ios') {\n purchases = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.getAvailableItems(\n normalizedOptions.alsoPublishToEventListenerIOS,\n normalizedOptions.onlyIncludeActiveItemsIOS,\n ),\n 'ios',\n )) as Purchase[];\n } else if (Platform.OS === 'android') {\n purchases = (await invokeNativeWithPurchaseError(\n () => ExpoIapModule.getAvailableItems(normalizedOptions),\n 'android',\n )) as Purchase[];\n } else {\n throw unsupportedPlatformError();\n }\n\n return Platform.OS === 'ios'\n ? decodeApplePurchases(purchases)\n : decodeAndroidPurchases(purchases);\n};\n\n/**\n * Get all active subscriptions. On iOS each entry carries `renewalInfoIOS`\n * (e.g. pendingUpgradeProductId, willAutoRenew, autoRenewPreference); on\n * Android they are filtered from the available purchases.\n *\n * @param subscriptionIds - Optional array of subscription product IDs to filter. If not provided, returns all active subscriptions.\n * @returns Promise resolving to array of active subscriptions with details\n *\n * @example\n * ```typescript\n * // Get all active subscriptions\n * const subs = await getActiveSubscriptions();\n *\n * // Get specific subscriptions\n * const premiumSubs = await getActiveSubscriptions(['premium', 'premium_year']);\n *\n * // Check for pending upgrades (iOS)\n * subs.forEach(sub => {\n * if (sub.renewalInfoIOS?.pendingUpgradeProductId) {\n * console.log(`Upgrade pending to: ${sub.renewalInfoIOS.pendingUpgradeProductId}`);\n * }\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-active-subscriptions}\n */\nexport const getActiveSubscriptions: QueryField<\n 'getActiveSubscriptions'\n> = async (subscriptionIds) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.getActiveSubscriptions(subscriptionIds ?? null),\n nativePlatform(),\n );\n return (result ?? []) as ActiveSubscription[];\n};\n\n/**\n * Check if user has any active subscriptions.\n *\n * @param subscriptionIds - Optional array of subscription product IDs to check. If not provided, checks all subscriptions.\n * @returns Promise resolving to true if user has at least one active subscription\n *\n * @example\n * ```typescript\n * // Check any active subscription\n * const hasAny = await hasActiveSubscriptions();\n *\n * // Check specific subscriptions\n * const hasPremium = await hasActiveSubscriptions(['premium', 'premium_year']);\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/has-active-subscriptions}\n */\nexport const hasActiveSubscriptions: QueryField<\n 'hasActiveSubscriptions'\n> = async (subscriptionIds) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n return !!(await invokeNativeWithPurchaseError(\n () => ExpoIapModule.hasActiveSubscriptions(subscriptionIds ?? null),\n nativePlatform(),\n ));\n};\n\n/**\n * Return the user's storefront country code.\n *\n * @see {@link https://openiap.dev/docs/apis/get-storefront}\n */\nexport const getStorefront: QueryField<'getStorefront'> = async () => {\n if (Platform.OS !== 'ios' && !isAndroidStoreRuntime()) {\n throw createPurchaseError({\n code: ErrorCode.FeatureNotSupported,\n message: `Storefront lookup is not supported on ${Platform.OS}.`,\n });\n }\n\n const platform = nativePlatform();\n if (typeof ExpoIapModule.getStorefront !== 'function') {\n throw createPurchaseError({\n code: ErrorCode.FeatureNotSupported,\n message: 'Native getStorefront is not available on this build.',\n platform,\n });\n }\n\n let storefront: unknown;\n try {\n storefront = await ExpoIapModule.getStorefront();\n } catch (error) {\n throw createPurchaseErrorFromNativeException(error, platform, {\n code: ErrorCode.ServiceError,\n message: 'Failed to get storefront.',\n debugMessage: error instanceof Error ? error.message : String(error),\n });\n }\n\n if (typeof storefront !== 'string' || storefront.trim().length === 0) {\n throw createPurchaseError({\n code: ErrorCode.ServiceError,\n message: 'Storefront lookup returned no country code.',\n platform,\n });\n }\n return storefront;\n};\n\nfunction normalizeRequestProps(\n request: RequestPurchasePropsByPlatforms,\n platform: 'ios',\n): RequestPurchaseIosProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestPurchasePropsByPlatforms,\n platform: 'android',\n): RequestPurchaseAndroidProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestSubscriptionPropsByPlatforms,\n platform: 'ios',\n): RequestSubscriptionIosProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestSubscriptionPropsByPlatforms,\n platform: 'android',\n): RequestSubscriptionAndroidProps | null | undefined;\nfunction normalizeRequestProps(\n request:\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms,\n platform: 'ios' | 'android',\n) {\n if (platform === 'ios') {\n return request.apple;\n }\n return request.google;\n}\n\nfunction validateAndroidPurchaseBranchOptions(\n request: unknown,\n type: ProductQueryType,\n): void {\n if (request == null || typeof request !== 'object') return;\n const fields = request as Record<string, unknown>;\n const subscriptionOnlyFields = [\n 'subscriptionOffers',\n 'subscriptionProductReplacementParams',\n 'purchaseToken',\n 'originalExternalTransactionId',\n ];\n if (\n (type === 'in-app' &&\n subscriptionOnlyFields.some((field) => fields[field] != null)) ||\n (type === 'subs' && fields.offerToken != null)\n ) {\n throw createPurchaseError({\n code: ErrorCode.DeveloperError,\n message:\n 'Invalid request for Android. Purchase options must match the selected product type.',\n });\n }\n}\n\n/** Verify app acquisition; send Android integrity tokens to your backend. */\nexport const verifyAppOwnership: QueryField<'verifyAppOwnership'> = async (\n options,\n) => {\n if (\n isVegaOS() ||\n ExpoIapModule.USING_ONSIDE_SDK ||\n (Platform.OS !== 'ios' && Platform.OS !== 'android')\n ) {\n return {\n status: 'unknown',\n reason: 'unsupported',\n storeId: isVegaOS()\n ? 'amazon'\n : ExpoIapModule.USING_ONSIDE_SDK\n ? 'onside'\n : 'unknown',\n };\n }\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyAppOwnership(options ?? {}),\n nativePlatform(),\n {\n code: ErrorCode.ServiceError,\n },\n );\n};\n\n/**\n * Initiate a purchase or subscription flow. The result arrives through\n * `purchaseUpdatedListener` / `purchaseErrorListener` (or `useIAP`'s\n * `onPurchaseSuccess` / `onPurchaseError`), not the return value.\n *\n * @param args `RequestPurchaseProps`, discriminated by `type`:\n * - `type: 'in-app'` — pass `request.apple.sku` (iOS) and/or `request.google.skus` (Android).\n * - `type: 'subs'` — same shape, plus `request.google.subscriptionOffers: [{ sku, offerToken }]`.\n * @returns The dispatched purchase payload; do not rely on it for the outcome.\n * @throws Synchronous rejection from the store (e.g. `ErrorCode.NotPrepared`, validation failure).\n *\n * @example\n * ```ts\n * await requestPurchase({\n * request: {\n * apple: { sku: 'com.app.premium' },\n * google: { skus: ['com.app.premium'] },\n * },\n * type: 'in-app',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/request-purchase}\n */\nexport const requestPurchase: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const {request} = args;\n markRequested([request.apple?.sku, ...(request.google?.skus ?? [])]);\n try {\n return await requestPurchaseFromStore(args);\n } catch (error) {\n clearRequested();\n throw error;\n }\n};\n\nconst requestPurchaseFromStore: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const {request, type} = args;\n const {canonical, native} = normalizeProductType(type as ProductTypeInput);\n if (canonical === 'all') {\n throw createPurchaseError({\n code: ErrorCode.DeveloperError,\n message: 'Product type all is only supported for product queries.',\n });\n }\n const isInAppPurchase = canonical === 'in-app';\n\n if (Platform.OS === 'ios') {\n const normalizedRequest = normalizeRequestProps(request, 'ios');\n\n if (!normalizedRequest?.sku) {\n throw createPurchaseError({\n message:\n 'Invalid request for Apple. The `sku` property is required and must be a string.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"product_id\" },\\n' +\n ' google: { skus: [\"product_id\"] }\\n' +\n ' },\\n' +\n ' type: \"in-app\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n if (canonical !== 'in-app' && canonical !== 'subs') {\n throw new Error(`Unsupported product type: ${canonical}`);\n }\n\n const payload: MutationRequestPurchaseArgs = {\n type: canonical === 'in-app' ? 'in-app' : 'subs',\n request: {apple: normalizedRequest},\n };\n\n const purchase = (await invokeNativeWithPurchaseError(\n () => ExpoIapModule.requestPurchase(payload),\n 'ios',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: normalizedRequest.sku,\n productIds: [normalizedRequest.sku],\n productType: canonical,\n },\n )) as Purchase | Purchase[] | null;\n\n if (Array.isArray(purchase)) {\n return purchase;\n }\n\n if (purchase) {\n return purchase;\n }\n\n return canonical === 'subs' ? [] : null;\n }\n\n if (isAndroidStoreRuntime()) {\n validateAndroidPurchaseBranchOptions(\n (\n request as\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms\n )?.google,\n canonical,\n );\n if (isInAppPurchase) {\n const normalizedRequest = normalizeRequestProps(\n request as RequestPurchasePropsByPlatforms,\n 'android',\n ) as RequestPurchaseAndroidProps | null | undefined;\n\n if (!normalizedRequest?.skus?.length) {\n throw createPurchaseError({\n message:\n 'Invalid request for Google. The `skus` property is required and must be a non-empty array.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"product_id\" },\\n' +\n ' google: { skus: [\"product_id\"] }\\n' +\n ' },\\n' +\n ' type: \"in-app\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {\n skus,\n obfuscatedAccountId,\n obfuscatedProfileId,\n isOfferPersonalized,\n offerToken,\n developerBillingOption,\n } = normalizedRequest;\n\n const result = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.requestPurchase({\n type: native,\n skus,\n purchaseToken: undefined,\n obfuscatedAccountId: obfuscatedAccountId,\n obfuscatedProfileId: obfuscatedProfileId,\n offerToken: offerToken,\n developerBillingOption: developerBillingOption ?? undefined,\n isOfferPersonalized: isOfferPersonalized ?? false,\n }),\n 'android',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: skus[0],\n productIds: skus,\n productType: canonical,\n },\n )) as Purchase[];\n\n return result;\n }\n\n if (canonical === 'subs') {\n const normalizedRequest = normalizeRequestProps(\n request as RequestSubscriptionPropsByPlatforms,\n 'android',\n ) as RequestSubscriptionAndroidProps | null | undefined;\n\n if (!normalizedRequest?.skus?.length) {\n throw createPurchaseError({\n message:\n 'Invalid request for Google. The `skus` property is required and must be a non-empty array.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"subscription_id\" },\\n' +\n ' google: { skus: [\"subscription_id\"] }\\n' +\n ' },\\n' +\n ' type: \"subs\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {\n skus,\n obfuscatedAccountId,\n obfuscatedProfileId,\n isOfferPersonalized,\n subscriptionOffers,\n purchaseToken: purchaseTokenInput,\n originalExternalTransactionId,\n developerBillingOption,\n subscriptionProductReplacementParams,\n } = normalizedRequest;\n\n const normalizedOffers = subscriptionOffers ?? [];\n const purchaseToken = purchaseTokenInput ?? undefined;\n\n const result = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.requestPurchase({\n type: native,\n skus,\n purchaseToken,\n originalExternalTransactionId:\n originalExternalTransactionId ?? undefined,\n obfuscatedAccountId: obfuscatedAccountId,\n obfuscatedProfileId: obfuscatedProfileId,\n subscriptionOffers: normalizedOffers,\n isOfferPersonalized: isOfferPersonalized ?? false,\n developerBillingOption: developerBillingOption ?? undefined,\n subscriptionProductReplacementParams:\n subscriptionProductReplacementParams ?? undefined,\n }),\n 'android',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: skus[0],\n productIds: skus,\n productType: canonical,\n },\n )) as Purchase[];\n\n return result;\n }\n\n throw new Error(\n \"Invalid request for Android: Expected a valid request object with 'skus' array.\",\n );\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * Complete a purchase transaction. Call after server-side verification to remove it\n * from the queue.\n *\n * @param args.purchase The `Purchase` to finalize.\n * @param args.isConsumable `true` for consumables (consumes the token so the SKU can be\n * re-bought, e.g. coins); `false` (default) for non-consumables and subscriptions.\n * @returns Promise that resolves once the platform finalizes the transaction.\n * @throws When the platform finalize call fails.\n *\n * @example\n * ```ts\n * // Inside purchaseUpdatedListener:\n * if (await verifyOnServer(purchase)) {\n * await finishTransaction({ purchase, isConsumable: false });\n * }\n * ```\n *\n * @remarks Android purchases must be finalized within 3 days or Google\n * auto-refunds. iOS unfinished transactions replay on every app launch.\n *\n * @see {@link https://openiap.dev/docs/apis/finish-transaction}\n */\nexport const finishTransaction: MutationField<'finishTransaction'> = async ({\n purchase,\n isConsumable,\n}) => {\n // The schema allows explicit null; the native boolean cannot take it.\n const consumable = isConsumable ?? false;\n const platform = nativePlatform();\n if (\n Platform.OS === 'ios' ||\n (isAndroidStoreRuntime() && purchase.store === 'unknown')\n ) {\n await invokeNativeWithPurchaseError(\n () => ExpoIapModule.finishTransaction(purchase, consumable),\n platform,\n {productId: purchase.productId},\n );\n } else if (isAndroidStoreRuntime()) {\n const token = purchase.purchaseToken ?? undefined;\n\n if (!token) {\n throw createPurchaseError({\n message: 'Purchase token is required to finish transaction',\n code: ErrorCode.DeveloperError,\n productId: purchase.productId,\n platform: 'android',\n });\n }\n\n // Native rejects when the store refuses the token, so a failure cannot pass as finished.\n await invokeNativeWithPurchaseError(\n () =>\n consumable\n ? ExpoIapModule.consumePurchaseAndroid(token)\n : ExpoIapModule.acknowledgePurchaseAndroid(token),\n 'android',\n {productId: purchase.productId},\n );\n } else {\n throw unsupportedPlatformError();\n }\n\n showFirstPurchaseNotice(purchase);\n};\n\n/**\n * Restore completed transactions. Returns nothing; read the restored items with\n * `getAvailablePurchases` or from hook state.\n *\n * - iOS: sync (or Onside restore when OnsideKit is active), then fetch available purchases.\n * - Android: run the provider's restore, then fetch available purchases.\n *\n * @see {@link https://openiap.dev/docs/apis/restore-purchases}\n */\nexport const restorePurchases: MutationField<'restorePurchases'> = async () => {\n await restorePurchasesNative();\n\n await getAvailablePurchases({\n alsoPublishToEventListenerIOS: false,\n onlyIncludeActiveItemsIOS: true,\n });\n};\n\n/**\n * Deeplinks to native interface that allows users to manage their subscriptions\n * @param options.skuAndroid - Required for Android to locate specific subscription (ignored on iOS)\n * @param options.packageNameAndroid - Required for Android to identify your app (ignored on iOS)\n *\n * @returns Promise that resolves when the deep link is successfully opened\n *\n * @throws {Error} When called on unsupported platform or when required Android parameters are missing\n *\n * @example\n * import { deepLinkToSubscriptions } from 'expo-iap';\n *\n * // Works on both iOS and Android\n * await deepLinkToSubscriptions({\n * skuAndroid: 'your_subscription_sku',\n * packageNameAndroid: 'com.example.app'\n * });\n *\n * @see {@link https://openiap.dev/docs/apis/deep-link-to-subscriptions}\n */\nexport const deepLinkToSubscriptions: MutationField<\n 'deepLinkToSubscriptions'\n> = async (options) => {\n if (Platform.OS === 'ios') {\n await deepLinkToSubscriptionsIOS();\n return;\n }\n\n if (Platform.OS === 'android') {\n await deepLinkToSubscriptionsAndroid((options as DeepLinkOptions) ?? null);\n return;\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * Open the platform's offer/promo code redemption flow.\n *\n * Resolves the redeemed purchase only when the store reports it synchronously;\n * every other path resolves null, so reconcile with `getAvailablePurchases`\n * when the app resumes.\n *\n * @returns Promise resolving to the redeemed purchase, or null\n * @throws Error when a redemption flow exists but cannot be opened\n *\n * @see {@link https://openiap.dev/docs/apis/open-redeem-offer-code}\n */\nexport const openRedeemOfferCode: MutationField<\n 'openRedeemOfferCode'\n> = async () => {\n if (isVegaOS()) return null;\n if (Platform.OS !== 'ios' && !isAndroidStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.openRedeemOfferCode(),\n nativePlatform(),\n {code: ErrorCode.PurchaseError, message: 'Failed to redeem offer code.'},\n );\n};\n\n/**\n * Verify purchase with the configured providers.\n *\n * @param options - Receipt validation options containing the SKU\n * @returns Promise resolving to receipt validation result\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase}\n */\nexport const verifyPurchase: MutationField<'verifyPurchase'> = async (\n options,\n) => {\n if (!isStorePlatform()) {\n throw unsupportedPlatformError();\n }\n\n // The native result is already the flat union member, with `__typename`.\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyPurchase(options),\n nativePlatform(),\n );\n};\n\n/**\n * Verify purchase with a specific provider (e.g., IAPKit).\n *\n * @param options - Verification options including provider and credentials\n * @returns Promise resolving to provider-specific verification result\n *\n * @example\n * ```typescript\n * const result = await verifyPurchaseWithProvider({\n * provider: 'iapkit',\n * iapkit: {\n * apiKey: 'your-api-key',\n * // Choose exactly one store payload.\n * // apple: { jws: purchase.purchaseToken },\n * // google: { purchaseToken: purchase.purchaseToken },\n * amazon: {\n * expectedProductId: purchase.productId,\n * userId: amazonUserId,\n * receiptId: purchase.purchaseToken,\n * // Enable only for App Tester after the IAPKit project opt-in.\n * sandbox: amazonSandboxEnabled,\n * }\n * }\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase-with-provider}\n */\nexport const verifyPurchaseWithProvider: MutationField<\n 'verifyPurchaseWithProvider'\n> = async (options) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n let resolvedOptions = options;\n\n if (\n resolvedOptions.provider === 'iapkit' &&\n resolvedOptions.iapkit &&\n !resolvedOptions.iapkit.apiKey\n ) {\n let configApiKey: unknown;\n try {\n // Dynamically import expo-constants to avoid hard dependency\n const {default: Constants} = await import('expo-constants');\n configApiKey = Constants.expoConfig?.extra?.iapkitApiKey;\n } catch (error) {\n throw new Error(\n 'Could not read iapkitApiKey from expo-constants. Install it with ' +\n '`npx expo install expo-constants`, or pass apiKey in ' +\n 'verifyPurchaseWithProvider options.',\n {cause: error},\n );\n }\n if (typeof configApiKey === 'string' && configApiKey.length > 0) {\n resolvedOptions = {\n ...resolvedOptions,\n iapkit: {\n ...resolvedOptions.iapkit,\n apiKey: configApiKey,\n },\n };\n }\n }\n\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyPurchaseWithProvider(resolvedOptions),\n nativePlatform(),\n );\n if (result.iapkit == null) {\n return result;\n }\n\n const {clientPayload, productId, ...iapkit} = result.iapkit;\n return {\n ...result,\n iapkit: {\n ...iapkit,\n storeId: resolveStoreId(iapkit.storeId, iapkit.store),\n ...(clientPayload == null ? {} : {clientPayload}),\n ...(productId == null ? {} : {productId}),\n },\n };\n};\n\nexport type {SdkPurchaseFlowOptions} from './utils/purchaseFlowBinding';\n\nconst purchaseFlowSdk: PurchaseFlowSdk = {\n finishTransaction: (args) => finishTransaction(args),\n // The active-only iOS list drops subscriptions in billing grace.\n getAvailablePurchases: () =>\n getAvailablePurchases({onlyIncludeActiveItemsIOS: false}),\n getPendingTransactionsIOS:\n Platform.OS === 'ios' ? () => getPendingTransactionsIOS() : undefined,\n purchaseUpdatedListener: (listener) =>\n purchaseUpdatedListener(listener, {dedupeTransactionIOS: false}),\n purchaseErrorListener: (listener) => purchaseErrorListener(listener),\n};\n\n/**\n * Creates the app's purchase flow. It confirms and finishes every purchase the\n * store delivers, and recovers unfinished ones, through this SDK. Create one\n * per signed-in account, dispose it when the account changes, and pass it to\n * `useIAP({purchaseFlow})`.\n * @see {@link https://kit.openiap.dev/docs/purchase-flow}\n */\nexport function createPurchaseFlow(\n options: SdkPurchaseFlowOptions,\n): PurchaseFlow<Purchase>;\nexport function createPurchaseFlow<P extends PurchaseFlowPurchase>(\n options: PurchaseFlowOptions<P>,\n): PurchaseFlow<P>;\nexport function createPurchaseFlow(\n options: SdkPurchaseFlowOptions,\n): PurchaseFlow<Purchase> {\n return createSdkPurchaseFlow(purchaseFlowSdk, options);\n}\n\n/**\n * Confirms purchases with IAPKit from the app, for apps without a backend:\n * pass it as `confirmWithBackend` with a publishable key. Credit consumables\n * in `grant`, which runs before the purchase is consumed.\n */\nexport function confirmWithIapkit(\n options: IapkitConfirmationOptions<Purchase>,\n): PurchaseFlowOptions<Purchase>['confirmWithBackend'] {\n return createIapkitConfirmation(verifyPurchaseWithProvider, options);\n}\n\n/**\n * Confirms App Store purchases on the device, for apps with neither a backend\n * nor IAPKit: StoreKit must still list the transaction as unfinished and\n * valid. Credit consumables in `grant`.\n */\nexport function confirmOnDeviceIOS(\n options: {\n /** Required for consumables; credit each purchase.id only once. */\n grant?: (\n purchase: Purchase,\n context: {isConsumable: boolean},\n ) => Promise<void>;\n } = {},\n): PurchaseFlowOptions<Purchase>['confirmWithBackend'] {\n return createDeviceConfirmationIOS<Purchase>(\n () => getPendingTransactionsIOS(),\n options,\n );\n}\n\nexport * from './useIAP';\nexport {kitApi, KitApiError, resolveLocalizedPayload} from './kit-api';\nexport type {\n KitApiOptions,\n KitClientPayloadCache,\n KitClientPayloadOptions,\n KitClientPayloadResponse,\n KitLocalizedClientPayload,\n KitLocalizedClientPayloadOptions,\n KitLocalizedPayloadOptions,\n KitProduct,\n KitProductClientPayload,\n KitProductOffer,\n KitProductPlatform,\n KitProductsOptions,\n KitProductsResponse,\n KitSubscription,\n EntitlementsResponse,\n StatusResponse,\n} from './kit-api';\nexport {\n describePurchaseFlowStatus,\n toPurchaseConfirmationRequest,\n} from './purchase-flow-core';\nexport type {\n PurchaseConfirmation,\n PurchaseConfirmationRequest,\n PurchaseFlow,\n PurchaseFlowGuidance,\n PurchaseFlowGuidanceKey,\n PurchaseFlowOptions,\n PurchaseFlowOutcome,\n PurchaseFlowPurchase,\n PurchaseFlowStatus,\n RecoverPurchasesOptions,\n} from './purchase-flow-core';\nexport type {IapkitConfirmationOptions} from './purchase-flow-confirmers';\nexport {\n ErrorCodeUtils,\n ErrorCodeMapping,\n createPurchaseError,\n createPurchaseErrorFromPlatform,\n getUserFriendlyErrorMessage,\n isRecoverableError,\n isUserCancelledError,\n} from './utils/errorMapping';\nexport type {\n PurchaseError as ExpoPurchaseError,\n PurchaseErrorProps,\n} from './utils/errorMapping';\nexport {ExpoIapConsole} from './utils/debug';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,QA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AAsB,CAAC;AAc9B,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,+BAA+B,EAC/B,2BAA2B,EAC3B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC","sourcesContent":["// External dependencies\nimport {Platform} from 'react-native';\n\n// Internal modules\nimport ExpoIapModule, {getNativeModule} from './ExpoIapModule';\nimport {isVegaOS} from './vega';\nimport {\n deepLinkToSubscriptionsIOS,\n getPendingTransactionsIOS,\n isProductIOS,\n} from './modules/ios';\nimport {\n type PurchaseFlow,\n type PurchaseFlowOptions,\n type PurchaseFlowPurchase,\n} from './purchase-flow-core';\nimport {\n createDeviceConfirmationIOS,\n createIapkitConfirmation,\n type IapkitConfirmationOptions,\n} from './purchase-flow-confirmers';\nimport {\n clearRequested,\n createSdkPurchaseFlow,\n markRequested,\n type PurchaseFlowSdk,\n type SdkPurchaseFlowOptions,\n} from './utils/purchaseFlowBinding';\nimport {\n isProductAndroid,\n deepLinkToSubscriptionsAndroid,\n} from './modules/android';\nimport {ExpoIapConsole} from './utils/debug';\nimport {showFirstPurchaseNotice} from './utils/firstPurchaseNotice';\nimport {restorePurchasesNative} from './utils/restorePurchases';\nimport {\n decodeAndroidPurchases,\n decodeApplePurchases,\n} from './utils/availablePurchases';\n\n// Types\nimport type {\n ActiveSubscription,\n DeepLinkOptions,\n DeveloperProvidedBillingDetailsAndroid,\n IapPlatform,\n MutationField,\n MutationRequestPurchaseArgs,\n Product,\n ProductQueryType,\n ProductSubscription,\n Purchase,\n PurchaseOptions,\n PurchaseUpdatedListenerOptions,\n QueryField,\n RequestPurchasePropsByPlatforms,\n RequestPurchaseAndroidProps,\n RequestPurchaseIosProps,\n RequestSubscriptionPropsByPlatforms,\n RequestSubscriptionAndroidProps,\n RequestSubscriptionIosProps,\n UserChoiceBillingDetails,\n} from './types';\nimport {ErrorCode, resolveStoreId} from './types';\nimport {\n createPurchaseError,\n normalizeErrorCodeFromNative,\n type PurchaseError,\n} from './utils/errorMapping';\nimport {\n createPurchaseErrorFromNativeException,\n invokeNativeWithPurchaseError,\n} from './utils/nativeError';\n\nexport * from './types';\nexport * from './modules/android';\nexport * from './modules/ios';\nexport * from './onside';\nexport * from './vega';\n\nexport enum OpenIapEvent {\n PurchaseUpdated = 'purchase-updated',\n PurchaseError = 'purchase-error',\n PromotedProductIOS = 'promoted-product-ios',\n UserChoiceBillingAndroid = 'user-choice-billing-android',\n /**\n * Fired for External Payments (8.3.0+) and Billing Choice (9.1.0+)\n * developer billing flows. Nullable fields depend on the selected flow.\n */\n DeveloperProvidedBillingAndroid = 'developer-provided-billing-android',\n /** Fired when a subscription enters a billing-issue state; see `subscriptionBillingIssueListener`. */\n SubscriptionBillingIssue = 'subscription-billing-issue',\n}\n\ntype ExpoIapEventPayloads = {\n [OpenIapEvent.PurchaseUpdated]: Purchase;\n [OpenIapEvent.PurchaseError]: PurchaseError;\n [OpenIapEvent.PromotedProductIOS]:\n | Product\n | string\n | {id?: string; productId?: string};\n [OpenIapEvent.UserChoiceBillingAndroid]: UserChoiceBillingDetails;\n [OpenIapEvent.DeveloperProvidedBillingAndroid]: DeveloperProvidedBillingDetailsAndroid;\n [OpenIapEvent.SubscriptionBillingIssue]: Purchase;\n};\n\ntype ExpoIapEventListener<E extends OpenIapEvent> = (\n payload: ExpoIapEventPayloads[E],\n) => void;\n\ntype ExpoIapEmitter = {\n addListener<E extends OpenIapEvent>(\n eventName: E,\n listener: ExpoIapEventListener<E>,\n ): {remove: () => void};\n removeListener<E extends OpenIapEvent>(\n eventName: E,\n listener: ExpoIapEventListener<E>,\n ): void;\n};\n\nconst isStorePlatform = (): boolean =>\n Platform.OS === 'ios' || Platform.OS === 'android';\n\nconst isStoreRuntime = (): boolean =>\n Platform.OS === 'ios' || isAndroidStoreRuntime();\n\nconst unsupportedPlatformError = (): Error =>\n new Error(`Unsupported platform: ${Platform.OS}`);\n\n// Platform tag for PurchaseErrors built from native rejections.\nconst nativePlatform = (): IapPlatform =>\n Platform.OS === 'ios' ? 'ios' : 'android';\n\n// Listener calls go to the raw native module (see getNativeModule), resolved\n// lazily so importing this module doesn't throw on unsupported platforms.\nexport const emitter: ExpoIapEmitter = {\n addListener(eventName, listener) {\n const nativeModule = getNativeModule();\n const nativeSubscription = nativeModule.addListener(eventName, listener);\n let removed = false;\n\n return {\n remove: () => {\n if (removed) {\n return;\n }\n removed = true;\n\n if (typeof nativeSubscription?.remove === 'function') {\n nativeSubscription.remove();\n return;\n }\n\n nativeModule.removeListener?.(eventName, listener);\n },\n };\n },\n removeListener(eventName, listener) {\n return getNativeModule().removeListener?.(eventName, listener);\n },\n};\n\nlet nonDedupingPurchaseUpdatedListenerCountIOS = 0;\nconst purchaseUpdatedDedupeHistoryLimitIOS = 512;\nconst purchaseUpdatedDedupeHistoryIOS = {\n ids: new Set<string>(),\n order: [] as string[],\n start: 0,\n};\nlet purchaseUpdatedDedupeGenerationIOS = 0;\n\ntype PurchaseUpdatedDedupeHistoryIOS = {\n ids: Set<string>;\n order: string[];\n start: number;\n};\n\nconst purchaseUpdatedTransactionIdIOS = (purchase: Purchase) => {\n if (typeof purchase.id === 'string' && purchase.id.length > 0) {\n return purchase.id;\n }\n return null;\n};\n\nconst rememberPurchaseUpdatedTransactionIOS = (\n transactionId: string,\n history: PurchaseUpdatedDedupeHistoryIOS,\n) => {\n if (history.ids.has(transactionId)) {\n return;\n }\n\n history.ids.add(transactionId);\n history.order.push(transactionId);\n if (\n history.order.length - history.start >\n purchaseUpdatedDedupeHistoryLimitIOS\n ) {\n const evicted = history.order[history.start];\n history.start += 1;\n if (evicted != null) {\n history.ids.delete(evicted);\n }\n if (history.start > 128 && history.start * 2 > history.order.length) {\n history.order = history.order.slice(history.start);\n history.start = 0;\n }\n }\n};\n\nconst clearPurchaseUpdatedDedupeHistoryIOS = (\n history: PurchaseUpdatedDedupeHistoryIOS,\n) => {\n history.ids.clear();\n history.order.length = 0;\n history.start = 0;\n};\n\nconst resetPurchaseUpdatedDedupeHistoryIOS = () => {\n clearPurchaseUpdatedDedupeHistoryIOS(purchaseUpdatedDedupeHistoryIOS);\n purchaseUpdatedDedupeGenerationIOS += 1;\n};\n\nconst configurePurchaseUpdatedListenerOptionsIOS = (\n dedupeTransactionIOS: boolean,\n) => {\n if (Platform.OS !== 'ios') return;\n\n const promise = getNativeModule().setPurchaseUpdatedListenerOptions?.({\n dedupeTransactionIOS,\n });\n void promise?.catch((error: unknown) => {\n ExpoIapConsole.warn(\n 'Failed to configure purchase updated listener options:',\n error,\n );\n });\n};\n\nexport type ProductTypeInput = ProductQueryType;\n\nconst normalizeProductType = (type?: ProductTypeInput) => {\n if (!type || type === 'in-app') {\n return {\n canonical: 'in-app' as ProductQueryType,\n native: 'in-app' as const,\n };\n }\n if (type === 'subs') {\n return {\n canonical: 'subs' as ProductQueryType,\n native: 'subs' as const,\n };\n }\n if (type === 'all') {\n return {\n canonical: 'all' as ProductQueryType,\n native: 'all' as const,\n };\n }\n throw new Error(`Unsupported product type: ${type}`);\n};\n\nconst isAndroidStoreRuntime = (): boolean => {\n return Platform.OS === 'android' || isVegaOS();\n};\n\nexport const purchaseUpdatedListener = (\n listener: (event: Purchase) => void,\n options?: PurchaseUpdatedListenerOptions | null,\n) => {\n const receiveDuplicateTransactionUpdatesIOS =\n Platform.OS === 'ios' && options?.dedupeTransactionIOS === false;\n const listenerDedupeHistoryIOS: PurchaseUpdatedDedupeHistoryIOS = {\n ids: new Set(purchaseUpdatedDedupeHistoryIOS.ids),\n order: purchaseUpdatedDedupeHistoryIOS.order.slice(\n purchaseUpdatedDedupeHistoryIOS.start,\n ),\n start: 0,\n };\n let listenerDedupeGenerationIOS = purchaseUpdatedDedupeGenerationIOS;\n\n const wrappedListener = (event: Purchase) => {\n const normalized = event;\n if (Platform.OS === 'ios') {\n if (listenerDedupeGenerationIOS !== purchaseUpdatedDedupeGenerationIOS) {\n clearPurchaseUpdatedDedupeHistoryIOS(listenerDedupeHistoryIOS);\n listenerDedupeGenerationIOS = purchaseUpdatedDedupeGenerationIOS;\n }\n const transactionId = purchaseUpdatedTransactionIdIOS(normalized);\n if (transactionId != null) {\n const isDuplicateForListener =\n listenerDedupeHistoryIOS.ids.has(transactionId);\n rememberPurchaseUpdatedTransactionIOS(\n transactionId,\n listenerDedupeHistoryIOS,\n );\n rememberPurchaseUpdatedTransactionIOS(\n transactionId,\n purchaseUpdatedDedupeHistoryIOS,\n );\n if (!receiveDuplicateTransactionUpdatesIOS && isDuplicateForListener) {\n return;\n }\n }\n }\n listener(normalized);\n };\n const emitterSubscription = emitter.addListener(\n OpenIapEvent.PurchaseUpdated,\n wrappedListener,\n );\n\n if (!receiveDuplicateTransactionUpdatesIOS) {\n return emitterSubscription;\n }\n\n nonDedupingPurchaseUpdatedListenerCountIOS += 1;\n configurePurchaseUpdatedListenerOptionsIOS(false);\n let removed = false;\n\n return {\n remove: () => {\n if (removed) {\n return;\n }\n removed = true;\n try {\n emitterSubscription?.remove?.();\n } finally {\n nonDedupingPurchaseUpdatedListenerCountIOS = Math.max(\n 0,\n nonDedupingPurchaseUpdatedListenerCountIOS - 1,\n );\n configurePurchaseUpdatedListenerOptionsIOS(\n nonDedupingPurchaseUpdatedListenerCountIOS === 0,\n );\n }\n },\n };\n};\n\nexport const purchaseErrorListener = (\n listener: (error: PurchaseError) => void,\n) => {\n // Native events may carry codes outside ErrorCode; deliver canonical codes.\n const wrappedListener = (error: PurchaseError) => {\n listener({...error, code: normalizeErrorCodeFromNative(error.code)});\n };\n const emitterSubscription = emitter.addListener(\n OpenIapEvent.PurchaseError,\n wrappedListener,\n );\n return emitterSubscription;\n};\n\n/**\n * iOS-only listener for App Store promoted product events.\n * This fires when a user taps on a promoted product in the App Store.\n *\n * @param listener - Callback function that receives the promoted product details\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = promotedProductListenerIOS((product) => {\n * console.log('Promoted product:', product);\n * // Handle the promoted product\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform iOS\n */\nexport const promotedProductListenerIOS = (\n listener: (product: Product) => void,\n) => {\n if (Platform.OS !== 'ios') {\n ExpoIapConsole.warn(\n 'promotedProductListenerIOS: This listener is only available on iOS',\n );\n return {remove: () => {}};\n }\n\n let deliveredProductId: string | undefined;\n const deliver = (product: Product) => {\n const productId =\n product.id ?? (product as Product & {productId?: string}).productId;\n if (productId && productId === deliveredProductId) {\n return;\n }\n deliveredProductId = productId;\n listener(product);\n };\n\n const replayPendingProduct = () => {\n let pendingProduct: Promise<Product | null> | undefined;\n try {\n pendingProduct = ExpoIapModule.getPromotedProductIOS() as\n | Promise<Product | null>\n | undefined;\n } catch {\n return Promise.resolve();\n }\n\n if (!pendingProduct || typeof pendingProduct.then !== 'function') {\n return Promise.resolve();\n }\n\n return pendingProduct\n .then((product: Product | null) => {\n if (product) {\n deliver(product);\n }\n })\n .catch(() => {});\n };\n\n const subscription = emitter.addListener(\n OpenIapEvent.PromotedProductIOS,\n (payload) => {\n if (typeof payload === 'string') {\n void replayPendingProduct();\n return;\n }\n\n deliver(payload as Product);\n },\n );\n\n void replayPendingProduct();\n\n return subscription;\n};\n\n/**\n * Android-only listener for User Choice Billing events.\n * This fires when a user selects alternative billing instead of Google Play billing\n * in the User Choice Billing dialog (only in 'user-choice' mode).\n *\n * @param listener - Callback function that receives the external transaction token and product IDs\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = userChoiceBillingListenerAndroid((details) => {\n * console.log('User selected alternative billing');\n * console.log('External transaction token received; send it to your backend without logging it.');\n * console.log('Products:', details.products);\n *\n * // Process payment in your system, then report token to Google\n * await processPaymentAndReportToken(details);\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform Android\n */\nexport const userChoiceBillingListenerAndroid = (\n listener: (details: UserChoiceBillingDetails) => void,\n) => {\n if (Platform.OS !== 'android') {\n ExpoIapConsole.warn(\n 'userChoiceBillingListenerAndroid: This listener is only available on Android',\n );\n return {remove: () => {}};\n }\n return emitter.addListener(OpenIapEvent.UserChoiceBillingAndroid, listener);\n};\n\n/**\n * Android-only listener for Developer Provided Billing events.\n * This fires when a user selects the developer's option in an External Payments\n * or Billing Choice purchase flow.\n *\n * @param listener - Callback that receives selected products and flow details\n * @returns EventSubscription that can be used to unsubscribe\n *\n * @example\n * ```typescript\n * const subscription = developerProvidedBillingListenerAndroid(async (details) => {\n * await processPaymentWithYourGateway(details.products, details.linkUri);\n * if (details.externalTransactionToken) {\n * await reportExternalTransactionToGoogle(details.externalTransactionToken);\n * }\n * });\n *\n * // Later, clean up\n * subscription.remove();\n * ```\n *\n * @platform Android (Play Billing Library 8.3.0+; Billing Choice 9.1.0+)\n */\nexport const developerProvidedBillingListenerAndroid = (\n listener: (details: DeveloperProvidedBillingDetailsAndroid) => void,\n) => {\n if (Platform.OS !== 'android') {\n ExpoIapConsole.warn(\n 'developerProvidedBillingListenerAndroid: This listener is only available on Android',\n );\n return {remove: () => {}};\n }\n return emitter.addListener(\n OpenIapEvent.DeveloperProvidedBillingAndroid,\n listener,\n );\n};\n\n/**\n * Listen for subscription billing-issue events (cross-platform).\n *\n * Fires when a user's active subscription enters a state that needs attention\n * for a payment problem. Unifies:\n * - iOS / Mac Catalyst 16.4+ and visionOS 1.0+: StoreKit 2 `Message.Reason.billingIssue`.\n * - Android (Play Billing 8.1+): when `Purchase.isSuspendedAndroid === true`.\n * - Meta Horizon, Amazon, macOS, tvOS, watchOS, and iOS before 16.4: never fires.\n *\n * Recommended UX: call `deepLinkToSubscriptions()` when this fires so the user\n * can update their payment method in the platform subscription center.\n *\n * @example\n * ```typescript\n * const subscription = subscriptionBillingIssueListener((purchase) => {\n * console.warn('Needs attention:', purchase.productId);\n * deepLinkToSubscriptions({\n * skuAndroid: purchase.productId,\n * packageNameAndroid: 'com.example.app',\n * });\n * });\n * ```\n */\nexport const subscriptionBillingIssueListener = (\n listener: (purchase: Purchase) => void,\n) => {\n const wrappedListener = (event: Purchase) => {\n listener(event);\n };\n return emitter.addListener(\n OpenIapEvent.SubscriptionBillingIssue,\n wrappedListener,\n );\n};\n\n/**\n * Initialize the store connection. Must be called before any other IAP API.\n *\n * @param config Optional connection config. Use `enableBillingProgramAndroid` (Android,\n * Play Billing 8.2.0+) to opt into a billing program. For Billing Choice 9.1.0+, set\n * `billingChoiceScreenTypeAndroid` to the renderer configured in Play Console.\n * iOS ignores Android-specific fields.\n * @returns Promise resolving to `true` when the platform billing client is connected.\n * @throws When the platform billing client fails to initialize.\n *\n * @example\n * ```ts\n * await initConnection();\n * await initConnection({ enableBillingProgramAndroid: 'external-offer' });\n * await initConnection({\n * enableBillingProgramAndroid: 'billing-choice',\n * billingChoiceScreenTypeAndroid: 'developer-rendered',\n * });\n * ```\n *\n * @remarks When using `useIAP()`, connection is auto-managed on mount/unmount —\n * pass options to the hook instead of calling this directly.\n *\n * @see {@link https://openiap.dev/docs/apis/init-connection}\n */\nexport const initConnection: MutationField<'initConnection'> = async (\n config,\n) => {\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.initConnection(config ?? null),\n nativePlatform(),\n );\n if (\n result === true &&\n Platform.OS === 'ios' &&\n nonDedupingPurchaseUpdatedListenerCountIOS > 0\n ) {\n configurePurchaseUpdatedListenerOptionsIOS(false);\n }\n return result;\n};\n\n/**\n * Close the store connection and release resources.\n *\n * @see {@link https://openiap.dev/docs/apis/end-connection}\n */\nexport const endConnection: MutationField<'endConnection'> = async () => {\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.endConnection(),\n nativePlatform(),\n );\n if (result === true && Platform.OS === 'ios') {\n resetPurchaseUpdatedDedupeHistoryIOS();\n }\n return result;\n};\n\n/**\n * Retrieve products or subscriptions from the store by SKU.\n *\n * @param request `ProductRequest` — `skus` (string[]) and optional `type`\n * (`'in-app' | 'subs' | 'all'`, defaults to `'in-app'`).\n * @returns Promise resolving to a `FetchProductsResult` union — `Product[]` for `'in-app'`,\n * `ProductSubscription[]` for `'subs'`, or a mixed array for `'all'`.\n * @throws When the store rejects the request (empty `skus`, not connected,\n * network/store error). Unknown SKUs are omitted from the result, not thrown.\n *\n * @example\n * ```ts\n * const products = await fetchProducts({\n * skus: ['com.app.coins_100', 'com.app.premium'],\n * type: 'in-app',\n * });\n * ```\n *\n * @remarks Promise-based, unlike the event-based `request*` APIs such as `requestPurchase`.\n *\n * @see {@link https://openiap.dev/docs/apis/fetch-products}\n */\nexport const fetchProducts: QueryField<'fetchProducts'> = async (request) => {\n ExpoIapConsole.debug('fetchProducts called with:', request);\n const {skus, type} = request ?? {};\n\n if (!Array.isArray(skus) || skus.length === 0) {\n throw createPurchaseError({\n message: 'No SKUs provided',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {canonical, native} = normalizeProductType(\n type as ProductTypeInput | undefined,\n );\n const skuSet = new Set(skus);\n\n const filterIosItems = (\n items: unknown[],\n ): (Product | ProductSubscription)[] =>\n items.filter((item): item is Product | ProductSubscription => {\n if (!isProductIOS(item)) {\n return false;\n }\n const candidate = item as Product | ProductSubscription;\n return typeof candidate.id === 'string' && skuSet.has(candidate.id);\n });\n\n const filterAndroidItems = (\n items: unknown[],\n ): (Product | ProductSubscription)[] =>\n items.filter((item): item is Product | ProductSubscription => {\n if (!isProductAndroid(item)) {\n return false;\n }\n const candidate = item as Product | ProductSubscription;\n return typeof candidate.id === 'string' && skuSet.has(candidate.id);\n });\n\n const castResult = (\n items: (Product | ProductSubscription)[],\n ):\n | (Product | ProductSubscription)[]\n | Product[]\n | ProductSubscription[]\n | null => {\n if (canonical === 'in-app') {\n return items as Product[];\n }\n if (canonical === 'subs') {\n return items as ProductSubscription[];\n }\n // 'all' mixes products and subscriptions; returned as-is to keep the discriminated union.\n return items;\n };\n\n if (Platform.OS === 'ios') {\n const rawItems = await invokeNativeWithPurchaseError<unknown[]>(\n () => ExpoIapModule.fetchProducts({skus, type: native}),\n 'ios',\n {\n code: ErrorCode.QueryProduct,\n message: 'Failed to query products',\n productIds: skus,\n productType: canonical,\n },\n );\n return castResult(filterIosItems(rawItems));\n }\n\n if (isAndroidStoreRuntime()) {\n const rawItems = await invokeNativeWithPurchaseError<unknown[]>(\n () => ExpoIapModule.fetchProducts(native, skus),\n 'android',\n {\n code: ErrorCode.QueryProduct,\n message: 'Failed to query products',\n productIds: skus,\n productType: canonical,\n },\n );\n return castResult(filterAndroidItems(rawItems));\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * List the user's unfinished purchases: non-consumables, active subscriptions,\n * and pending transactions.\n *\n * @param options Optional `PurchaseOptions`. iOS-only flags:\n * `alsoPublishToEventListenerIOS`, `onlyIncludeActiveItemsIOS`.\n * @returns Promise resolving to an array of `Purchase` currently held by the store.\n * @throws When the platform query fails.\n *\n * @example\n * ```ts\n * const purchases = await getAvailablePurchases();\n * for (const p of purchases) {\n * if (await verifyOnServer(p)) await finishTransaction({ purchase: p, isConsumable: false });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-available-purchases}\n */\nexport const getAvailablePurchases: QueryField<\n 'getAvailablePurchases'\n> = async (options) => {\n const normalizedOptions = {\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n } satisfies PurchaseOptions;\n\n if (isVegaOS()) {\n const purchases = await ExpoIapModule.getAvailableItems(normalizedOptions);\n return decodeAndroidPurchases(purchases);\n }\n\n let purchases: Purchase[];\n\n if (Platform.OS === 'ios') {\n purchases = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.getAvailableItems(\n normalizedOptions.alsoPublishToEventListenerIOS,\n normalizedOptions.onlyIncludeActiveItemsIOS,\n ),\n 'ios',\n )) as Purchase[];\n } else if (Platform.OS === 'android') {\n purchases = (await invokeNativeWithPurchaseError(\n () => ExpoIapModule.getAvailableItems(normalizedOptions),\n 'android',\n )) as Purchase[];\n } else {\n throw unsupportedPlatformError();\n }\n\n return Platform.OS === 'ios'\n ? decodeApplePurchases(purchases)\n : decodeAndroidPurchases(purchases);\n};\n\n/**\n * Get all active subscriptions. On iOS each entry carries `renewalInfoIOS`\n * (e.g. pendingUpgradeProductId, willAutoRenew, autoRenewPreference); on\n * Android they are filtered from the available purchases.\n *\n * @param subscriptionIds - Optional array of subscription product IDs to filter. If not provided, returns all active subscriptions.\n * @returns Promise resolving to array of active subscriptions with details\n *\n * @example\n * ```typescript\n * // Get all active subscriptions\n * const subs = await getActiveSubscriptions();\n *\n * // Get specific subscriptions\n * const premiumSubs = await getActiveSubscriptions(['premium', 'premium_year']);\n *\n * // Check for pending upgrades (iOS)\n * subs.forEach(sub => {\n * if (sub.renewalInfoIOS?.pendingUpgradeProductId) {\n * console.log(`Upgrade pending to: ${sub.renewalInfoIOS.pendingUpgradeProductId}`);\n * }\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-active-subscriptions}\n */\nexport const getActiveSubscriptions: QueryField<\n 'getActiveSubscriptions'\n> = async (subscriptionIds) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.getActiveSubscriptions(subscriptionIds ?? null),\n nativePlatform(),\n );\n return (result ?? []) as ActiveSubscription[];\n};\n\n/**\n * Check if user has any active subscriptions.\n *\n * @param subscriptionIds - Optional array of subscription product IDs to check. If not provided, checks all subscriptions.\n * @returns Promise resolving to true if user has at least one active subscription\n *\n * @example\n * ```typescript\n * // Check any active subscription\n * const hasAny = await hasActiveSubscriptions();\n *\n * // Check specific subscriptions\n * const hasPremium = await hasActiveSubscriptions(['premium', 'premium_year']);\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/has-active-subscriptions}\n */\nexport const hasActiveSubscriptions: QueryField<\n 'hasActiveSubscriptions'\n> = async (subscriptionIds) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n return !!(await invokeNativeWithPurchaseError(\n () => ExpoIapModule.hasActiveSubscriptions(subscriptionIds ?? null),\n nativePlatform(),\n ));\n};\n\n/**\n * Return the user's storefront country code.\n *\n * @see {@link https://openiap.dev/docs/apis/get-storefront}\n */\nexport const getStorefront: QueryField<'getStorefront'> = async () => {\n if (Platform.OS !== 'ios' && !isAndroidStoreRuntime()) {\n throw createPurchaseError({\n code: ErrorCode.FeatureNotSupported,\n message: `Storefront lookup is not supported on ${Platform.OS}.`,\n });\n }\n\n const platform = nativePlatform();\n if (typeof ExpoIapModule.getStorefront !== 'function') {\n throw createPurchaseError({\n code: ErrorCode.FeatureNotSupported,\n message: 'Native getStorefront is not available on this build.',\n platform,\n });\n }\n\n let storefront: unknown;\n try {\n storefront = await ExpoIapModule.getStorefront();\n } catch (error) {\n throw createPurchaseErrorFromNativeException(error, platform, {\n code: ErrorCode.ServiceError,\n message: 'Failed to get storefront.',\n debugMessage: error instanceof Error ? error.message : String(error),\n });\n }\n\n if (typeof storefront !== 'string' || storefront.trim().length === 0) {\n throw createPurchaseError({\n code: ErrorCode.ServiceError,\n message: 'Storefront lookup returned no country code.',\n platform,\n });\n }\n return storefront;\n};\n\nfunction normalizeRequestProps(\n request: RequestPurchasePropsByPlatforms,\n platform: 'ios',\n): RequestPurchaseIosProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestPurchasePropsByPlatforms,\n platform: 'android',\n): RequestPurchaseAndroidProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestSubscriptionPropsByPlatforms,\n platform: 'ios',\n): RequestSubscriptionIosProps | null | undefined;\nfunction normalizeRequestProps(\n request: RequestSubscriptionPropsByPlatforms,\n platform: 'android',\n): RequestSubscriptionAndroidProps | null | undefined;\nfunction normalizeRequestProps(\n request:\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms,\n platform: 'ios' | 'android',\n) {\n if (platform === 'ios') {\n return request.apple;\n }\n return request.google;\n}\n\nfunction validateAndroidPurchaseBranchOptions(\n request: unknown,\n type: ProductQueryType,\n): void {\n if (request == null || typeof request !== 'object') return;\n const fields = request as Record<string, unknown>;\n const subscriptionOnlyFields = [\n 'subscriptionOffers',\n 'subscriptionProductReplacementParams',\n 'purchaseToken',\n 'originalExternalTransactionId',\n ];\n if (\n (type === 'in-app' &&\n subscriptionOnlyFields.some((field) => fields[field] != null)) ||\n (type === 'subs' && fields.offerToken != null)\n ) {\n throw createPurchaseError({\n code: ErrorCode.DeveloperError,\n message:\n 'Invalid request for Android. Purchase options must match the selected product type.',\n });\n }\n}\n\n/** Verify app acquisition; send Android integrity tokens to your backend. */\nexport const verifyAppOwnership: QueryField<'verifyAppOwnership'> = async (\n options,\n) => {\n if (\n isVegaOS() ||\n ExpoIapModule.USING_ONSIDE_SDK ||\n (Platform.OS !== 'ios' && Platform.OS !== 'android')\n ) {\n return {\n status: 'unknown',\n reason: 'unsupported',\n storeId: isVegaOS()\n ? 'amazon'\n : ExpoIapModule.USING_ONSIDE_SDK\n ? 'onside'\n : 'unknown',\n };\n }\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyAppOwnership(options ?? {}),\n nativePlatform(),\n {\n code: ErrorCode.ServiceError,\n },\n );\n};\n\n/**\n * Initiate a purchase or subscription flow. The result arrives through\n * `purchaseUpdatedListener` / `purchaseErrorListener` (or `useIAP`'s\n * `onPurchaseSuccess` / `onPurchaseError`), not the return value.\n *\n * @param args `RequestPurchaseProps`, discriminated by `type`:\n * - `type: 'in-app'` — pass `request.apple.sku` (iOS) and/or `request.google.skus` (Android).\n * - `type: 'subs'` — same shape, plus `request.google.subscriptionOffers: [{ sku, offerToken }]`.\n * @returns The dispatched purchase payload; do not rely on it for the outcome.\n * @throws Synchronous rejection from the store (e.g. `ErrorCode.NotPrepared`, validation failure).\n *\n * @example\n * ```ts\n * await requestPurchase({\n * request: {\n * apple: { sku: 'com.app.premium' },\n * google: { skus: ['com.app.premium'] },\n * },\n * type: 'in-app',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/request-purchase}\n */\nexport const requestPurchase: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const {request} = args;\n markRequested([request.apple?.sku, ...(request.google?.skus ?? [])]);\n try {\n return await requestPurchaseFromStore(args);\n } catch (error) {\n clearRequested();\n throw error;\n }\n};\n\nconst requestPurchaseFromStore: MutationField<'requestPurchase'> = async (\n args,\n) => {\n const {request, type} = args;\n const {canonical, native} = normalizeProductType(type as ProductTypeInput);\n if (canonical === 'all') {\n throw createPurchaseError({\n code: ErrorCode.DeveloperError,\n message: 'Product type all is only supported for product queries.',\n });\n }\n const isInAppPurchase = canonical === 'in-app';\n\n if (Platform.OS === 'ios') {\n const normalizedRequest = normalizeRequestProps(request, 'ios');\n\n if (!normalizedRequest?.sku) {\n throw createPurchaseError({\n message:\n 'Invalid request for Apple. The `sku` property is required and must be a string.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"product_id\" },\\n' +\n ' google: { skus: [\"product_id\"] }\\n' +\n ' },\\n' +\n ' type: \"in-app\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n if (canonical !== 'in-app' && canonical !== 'subs') {\n throw new Error(`Unsupported product type: ${canonical}`);\n }\n\n const payload: MutationRequestPurchaseArgs = {\n type: canonical === 'in-app' ? 'in-app' : 'subs',\n request: {apple: normalizedRequest},\n };\n\n const purchase = (await invokeNativeWithPurchaseError(\n () => ExpoIapModule.requestPurchase(payload),\n 'ios',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: normalizedRequest.sku,\n productIds: [normalizedRequest.sku],\n productType: canonical,\n },\n )) as Purchase | Purchase[] | null;\n\n if (Array.isArray(purchase)) {\n return purchase;\n }\n\n if (purchase) {\n return purchase;\n }\n\n return canonical === 'subs' ? [] : null;\n }\n\n if (isAndroidStoreRuntime()) {\n validateAndroidPurchaseBranchOptions(\n (\n request as\n | RequestPurchasePropsByPlatforms\n | RequestSubscriptionPropsByPlatforms\n )?.google,\n canonical,\n );\n if (isInAppPurchase) {\n const normalizedRequest = normalizeRequestProps(\n request as RequestPurchasePropsByPlatforms,\n 'android',\n ) as RequestPurchaseAndroidProps | null | undefined;\n\n if (!normalizedRequest?.skus?.length) {\n throw createPurchaseError({\n message:\n 'Invalid request for Google. The `skus` property is required and must be a non-empty array.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"product_id\" },\\n' +\n ' google: { skus: [\"product_id\"] }\\n' +\n ' },\\n' +\n ' type: \"in-app\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {\n skus,\n obfuscatedAccountId,\n obfuscatedProfileId,\n isOfferPersonalized,\n offerToken,\n developerBillingOption,\n } = normalizedRequest;\n\n const result = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.requestPurchase({\n type: native,\n skus,\n purchaseToken: undefined,\n obfuscatedAccountId: obfuscatedAccountId,\n obfuscatedProfileId: obfuscatedProfileId,\n offerToken: offerToken,\n developerBillingOption: developerBillingOption ?? undefined,\n isOfferPersonalized: isOfferPersonalized ?? false,\n }),\n 'android',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: skus[0],\n productIds: skus,\n productType: canonical,\n },\n )) as Purchase[];\n\n return result;\n }\n\n if (canonical === 'subs') {\n const normalizedRequest = normalizeRequestProps(\n request as RequestSubscriptionPropsByPlatforms,\n 'android',\n ) as RequestSubscriptionAndroidProps | null | undefined;\n\n if (!normalizedRequest?.skus?.length) {\n throw createPurchaseError({\n message:\n 'Invalid request for Google. The `skus` property is required and must be a non-empty array.\\n\\n' +\n 'Expected format:\\n' +\n ' requestPurchase({\\n' +\n ' request: {\\n' +\n ' apple: { sku: \"subscription_id\" },\\n' +\n ' google: { skus: [\"subscription_id\"] }\\n' +\n ' },\\n' +\n ' type: \"subs\"\\n' +\n ' })\\n\\n' +\n 'See: https://openiap.dev/docs/apis/request-purchase',\n code: ErrorCode.EmptySkuList,\n });\n }\n\n const {\n skus,\n obfuscatedAccountId,\n obfuscatedProfileId,\n isOfferPersonalized,\n subscriptionOffers,\n purchaseToken: purchaseTokenInput,\n originalExternalTransactionId,\n developerBillingOption,\n subscriptionProductReplacementParams,\n } = normalizedRequest;\n\n const normalizedOffers = subscriptionOffers ?? [];\n const purchaseToken = purchaseTokenInput ?? undefined;\n\n const result = (await invokeNativeWithPurchaseError(\n () =>\n ExpoIapModule.requestPurchase({\n type: native,\n skus,\n purchaseToken,\n originalExternalTransactionId:\n originalExternalTransactionId ?? undefined,\n obfuscatedAccountId: obfuscatedAccountId,\n obfuscatedProfileId: obfuscatedProfileId,\n subscriptionOffers: normalizedOffers,\n isOfferPersonalized: isOfferPersonalized ?? false,\n developerBillingOption: developerBillingOption ?? undefined,\n subscriptionProductReplacementParams:\n subscriptionProductReplacementParams ?? undefined,\n }),\n 'android',\n {\n code: ErrorCode.PurchaseError,\n message: 'Failed to request purchase',\n productId: skus[0],\n productIds: skus,\n productType: canonical,\n },\n )) as Purchase[];\n\n return result;\n }\n\n throw new Error(\n \"Invalid request for Android: Expected a valid request object with 'skus' array.\",\n );\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * Complete a purchase transaction. Call after server-side verification to remove it\n * from the queue.\n *\n * @param args.purchase The `Purchase` to finalize.\n * @param args.isConsumable `true` for consumables (consumes the token so the SKU can be\n * re-bought, e.g. coins); `false` (default) for non-consumables and subscriptions.\n * @returns Promise that resolves once the platform finalizes the transaction.\n * @throws When the platform finalize call fails.\n *\n * @example\n * ```ts\n * // Inside purchaseUpdatedListener:\n * if (await verifyOnServer(purchase)) {\n * await finishTransaction({ purchase, isConsumable: false });\n * }\n * ```\n *\n * @remarks Android purchases must be finalized within 3 days or Google\n * auto-refunds. iOS unfinished transactions replay on every app launch.\n *\n * @see {@link https://openiap.dev/docs/apis/finish-transaction}\n */\nexport const finishTransaction: MutationField<'finishTransaction'> = async ({\n purchase,\n isConsumable,\n}) => {\n // The schema allows explicit null; the native boolean cannot take it.\n const consumable = isConsumable ?? false;\n const platform = nativePlatform();\n if (\n Platform.OS === 'ios' ||\n (isAndroidStoreRuntime() && purchase.store === 'unknown')\n ) {\n await invokeNativeWithPurchaseError(\n () => ExpoIapModule.finishTransaction(purchase, consumable),\n platform,\n {productId: purchase.productId},\n );\n } else if (isAndroidStoreRuntime()) {\n const token = purchase.purchaseToken ?? undefined;\n\n if (!token) {\n throw createPurchaseError({\n message: 'Purchase token is required to finish transaction',\n code: ErrorCode.DeveloperError,\n productId: purchase.productId,\n platform: 'android',\n });\n }\n\n // Native rejects when the store refuses the token, so a failure cannot pass as finished.\n await invokeNativeWithPurchaseError(\n () =>\n consumable\n ? ExpoIapModule.consumePurchaseAndroid(token)\n : ExpoIapModule.acknowledgePurchaseAndroid(token),\n 'android',\n {productId: purchase.productId},\n );\n } else {\n throw unsupportedPlatformError();\n }\n\n showFirstPurchaseNotice(purchase);\n};\n\n/**\n * Restore completed transactions. Returns nothing; read the restored items with\n * `getAvailablePurchases` or from hook state.\n *\n * - iOS: sync (or Onside restore when OnsideKit is active), then fetch available purchases.\n * - Android: run the provider's restore, then fetch available purchases.\n *\n * @see {@link https://openiap.dev/docs/apis/restore-purchases}\n */\nexport const restorePurchases: MutationField<'restorePurchases'> = async () => {\n await restorePurchasesNative();\n\n await getAvailablePurchases({\n alsoPublishToEventListenerIOS: false,\n onlyIncludeActiveItemsIOS: true,\n });\n};\n\n/**\n * Deeplinks to native interface that allows users to manage their subscriptions\n * @param options.skuAndroid - Required for Android to locate specific subscription (ignored on iOS)\n * @param options.packageNameAndroid - Required for Android to identify your app (ignored on iOS)\n *\n * @returns Promise that resolves when the deep link is successfully opened\n *\n * @throws {Error} When called on unsupported platform or when required Android parameters are missing\n *\n * @example\n * import { deepLinkToSubscriptions } from 'expo-iap';\n *\n * // Works on both iOS and Android\n * await deepLinkToSubscriptions({\n * skuAndroid: 'your_subscription_sku',\n * packageNameAndroid: 'com.example.app'\n * });\n *\n * @see {@link https://openiap.dev/docs/apis/deep-link-to-subscriptions}\n */\nexport const deepLinkToSubscriptions: MutationField<\n 'deepLinkToSubscriptions'\n> = async (options) => {\n if (Platform.OS === 'ios') {\n await deepLinkToSubscriptionsIOS();\n return;\n }\n\n if (Platform.OS === 'android') {\n await deepLinkToSubscriptionsAndroid((options as DeepLinkOptions) ?? null);\n return;\n }\n\n throw unsupportedPlatformError();\n};\n\n/**\n * Open the platform's offer/promo code redemption flow.\n *\n * Resolves the redeemed purchase only when the store reports it synchronously;\n * every other path resolves null, so reconcile with `getAvailablePurchases`\n * when the app resumes.\n *\n * @returns Promise resolving to the redeemed purchase, or null\n * @throws Error when a redemption flow exists but cannot be opened\n *\n * @see {@link https://openiap.dev/docs/apis/open-redeem-offer-code}\n */\nexport const openRedeemOfferCode: MutationField<\n 'openRedeemOfferCode'\n> = async () => {\n if (isVegaOS()) return null;\n if (Platform.OS !== 'ios' && !isAndroidStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.openRedeemOfferCode(),\n nativePlatform(),\n {code: ErrorCode.PurchaseError, message: 'Failed to redeem offer code.'},\n );\n};\n\n/**\n * Verify purchase with the configured providers.\n *\n * @param options - Receipt validation options containing the SKU\n * @returns Promise resolving to receipt validation result\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase}\n */\nexport const verifyPurchase: MutationField<'verifyPurchase'> = async (\n options,\n) => {\n if (!isStorePlatform()) {\n throw unsupportedPlatformError();\n }\n\n // The native result is already the flat union member, with `__typename`.\n return invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyPurchase(options),\n nativePlatform(),\n );\n};\n\n/**\n * Verify purchase with a specific provider (e.g., IAPKit).\n *\n * @param options - Verification options including provider and credentials\n * @returns Promise resolving to provider-specific verification result\n *\n * @example\n * ```typescript\n * const result = await verifyPurchaseWithProvider({\n * provider: 'iapkit',\n * iapkit: {\n * apiKey: 'your-api-key',\n * // Choose exactly one store payload.\n * // apple: { jws: purchase.purchaseToken },\n * // google: { purchaseToken: purchase.purchaseToken },\n * amazon: {\n * expectedProductId: purchase.productId,\n * userId: amazonUserId,\n * receiptId: purchase.purchaseToken,\n * // Enable only for App Tester after the IAPKit project opt-in.\n * sandbox: amazonSandboxEnabled,\n * }\n * }\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase-with-provider}\n */\nexport const verifyPurchaseWithProvider: MutationField<\n 'verifyPurchaseWithProvider'\n> = async (options) => {\n if (!isStoreRuntime()) {\n throw unsupportedPlatformError();\n }\n\n let resolvedOptions = options;\n\n if (\n resolvedOptions.provider === 'iapkit' &&\n resolvedOptions.iapkit &&\n !resolvedOptions.iapkit.apiKey\n ) {\n let configApiKey: unknown;\n try {\n // Dynamically import expo-constants to avoid hard dependency\n const {default: Constants} = await import('expo-constants');\n configApiKey = Constants.expoConfig?.extra?.iapkitApiKey;\n } catch (error) {\n throw new Error(\n 'Could not read iapkitApiKey from expo-constants. Install it with ' +\n '`npx expo install expo-constants`, or pass apiKey in ' +\n 'verifyPurchaseWithProvider options.',\n {cause: error},\n );\n }\n if (typeof configApiKey === 'string' && configApiKey.length > 0) {\n resolvedOptions = {\n ...resolvedOptions,\n iapkit: {\n ...resolvedOptions.iapkit,\n apiKey: configApiKey,\n },\n };\n }\n }\n\n const result = await invokeNativeWithPurchaseError(\n () => ExpoIapModule.verifyPurchaseWithProvider(resolvedOptions),\n nativePlatform(),\n );\n if (result.iapkit == null) {\n return result;\n }\n\n const {clientPayload, productId, ...iapkit} = result.iapkit;\n return {\n ...result,\n iapkit: {\n ...iapkit,\n storeId: resolveStoreId(iapkit.storeId, iapkit.store),\n ...(clientPayload == null ? {} : {clientPayload}),\n ...(productId == null ? {} : {productId}),\n },\n };\n};\n\nexport type {SdkPurchaseFlowOptions} from './utils/purchaseFlowBinding';\n\nconst purchaseFlowSdk: PurchaseFlowSdk = {\n finishTransaction: (args) => finishTransaction(args),\n // The active-only iOS list drops subscriptions in billing grace.\n getAvailablePurchases: () =>\n getAvailablePurchases({onlyIncludeActiveItemsIOS: false}),\n getPendingTransactionsIOS:\n Platform.OS === 'ios' ? () => getPendingTransactionsIOS() : undefined,\n purchaseUpdatedListener: (listener) =>\n purchaseUpdatedListener(listener, {dedupeTransactionIOS: false}),\n purchaseErrorListener: (listener) => purchaseErrorListener(listener),\n};\n\n/**\n * Creates the app's purchase flow. It confirms and finishes every purchase the\n * store delivers, and recovers unfinished ones, through this SDK. Create one\n * per signed-in account, dispose it when the account changes, and pass it to\n * `useIAP({purchaseFlow})`.\n * @see {@link https://kit.openiap.dev/docs/purchase-flow}\n */\nexport function createPurchaseFlow(\n options: SdkPurchaseFlowOptions,\n): PurchaseFlow<Purchase>;\nexport function createPurchaseFlow<P extends PurchaseFlowPurchase>(\n options: PurchaseFlowOptions<P>,\n): PurchaseFlow<P>;\nexport function createPurchaseFlow(\n options: SdkPurchaseFlowOptions,\n): PurchaseFlow<Purchase> {\n return createSdkPurchaseFlow(purchaseFlowSdk, options);\n}\n\n/**\n * Confirms purchases with IAPKit from the app, for apps without a backend:\n * pass it as `confirmWithBackend` with a publishable key. Credit consumables\n * in `grant`, which runs before the purchase is consumed.\n */\nexport function confirmWithIapkit(\n options: IapkitConfirmationOptions<Purchase>,\n): PurchaseFlowOptions<Purchase>['confirmWithBackend'] {\n return createIapkitConfirmation(verifyPurchaseWithProvider, options);\n}\n\n/**\n * Confirms App Store purchases on the device, for apps with neither a backend\n * nor IAPKit: StoreKit must list the transaction as unfinished, or for a\n * restore in its verified history, and valid. Credit consumables in `grant`.\n */\nexport function confirmOnDeviceIOS(\n options: {\n /** Required for consumables; credit each purchase.id only once. */\n grant?: (\n purchase: Purchase,\n context: {isConsumable: boolean},\n ) => Promise<void>;\n } = {},\n): PurchaseFlowOptions<Purchase>['confirmWithBackend'] {\n return createDeviceConfirmationIOS<Purchase>(\n () => getPendingTransactionsIOS(),\n {\n ...options,\n getTransactionHistoryIOS: () =>\n getAvailablePurchases({onlyIncludeActiveItemsIOS: false}),\n },\n );\n}\n\nexport * from './useIAP';\nexport {kitApi, KitApiError, resolveLocalizedPayload} from './kit-api';\nexport type {\n KitApiOptions,\n KitClientPayloadCache,\n KitClientPayloadOptions,\n KitClientPayloadResponse,\n KitLocalizedClientPayload,\n KitLocalizedClientPayloadOptions,\n KitLocalizedPayloadOptions,\n KitProduct,\n KitProductClientPayload,\n KitProductOffer,\n KitProductPlatform,\n KitProductsOptions,\n KitProductsResponse,\n KitSubscription,\n EntitlementsResponse,\n StatusResponse,\n} from './kit-api';\nexport {\n describePurchaseFlowStatus,\n toPurchaseConfirmationRequest,\n} from './purchase-flow-core';\nexport type {\n PurchaseConfirmation,\n PurchaseConfirmationRequest,\n PurchaseFlow,\n PurchaseFlowGuidance,\n PurchaseFlowGuidanceKey,\n PurchaseFlowOptions,\n PurchaseFlowOutcome,\n PurchaseFlowPurchase,\n PurchaseFlowStatus,\n RecoverPurchasesOptions,\n} from './purchase-flow-core';\nexport type {IapkitConfirmationOptions} from './purchase-flow-confirmers';\nexport {\n ErrorCodeUtils,\n ErrorCodeMapping,\n createPurchaseError,\n createPurchaseErrorFromPlatform,\n getUserFriendlyErrorMessage,\n isRecoverableError,\n isUserCancelledError,\n} from './utils/errorMapping';\nexport type {\n PurchaseError as ExpoPurchaseError,\n PurchaseErrorProps,\n} from './utils/errorMapping';\nexport {ExpoIapConsole} from './utils/debug';\n"]}
@@ -74,14 +74,22 @@ export declare function createIapkitConfirmation<P extends PurchaseFlowPurchase>
74
74
  * @internal Use the SDK's confirmOnDeviceIOS.
75
75
  * The SDK's `confirmOnDeviceIOS`, given its `getPendingTransactionsIOS`, for an
76
76
  * app with neither a backend nor IAPKit. StoreKit verified the transaction if
77
- * it is still unfinished, unrevoked, not upgraded, unexpired, and from the
78
- * purchase's environment; `grant` then runs before the flow finishes it.
77
+ * it lists it as unfinished, or, for a purchase the flow already finished, in
78
+ * `getTransactionHistoryIOS`, from the purchase's environment. A revoked or
79
+ * upgraded one is `invalid`, and an expired one `verification_delayed`, since
80
+ * billing grace can still cover it; `grant` runs before an unfinished one is
81
+ * finished, and again for a finished non-consumable a restore reads.
79
82
  */
80
83
  export declare function createDeviceConfirmationIOS<P extends PurchaseFlowPurchase>(getPendingTransactionsIOS: () => Promise<P[]>, options?: {
81
84
  /** Required for consumables; credit each purchase.id only once. */
82
85
  grant?: (purchase: P, context: {
83
86
  isConsumable: boolean;
84
87
  }) => Promise<void>;
88
+ /**
89
+ * StoreKit's verified history, such as `getAvailablePurchases` with
90
+ * `onlyIncludeActiveItemsIOS: false`; without it a finished purchase throws.
91
+ */
92
+ getTransactionHistoryIOS?: () => Promise<P[]>;
85
93
  }): PurchaseFlowOptions<P>["confirmWithBackend"];
86
94
  /** @internal Builds the IAPKit request; throws for a store IAPKit cannot verify. */
87
95
  export declare function toIapkitVerificationProps<P extends PurchaseFlowPurchase>(purchase: P, options: IapkitConfirmationOptions<P>): IapkitVerificationProps;
@@ -1 +1 @@
1
- {"version":3,"file":"purchase-flow-confirmers.d.ts","sourceRoot":"","sources":["../src/purchase-flow-confirmers.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,sBAAsB,CAAC;AAE9B,KAAK,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE7D,yEAAyE;AACzE,MAAM,WAAW,yBAAyB,CACxC,CAAC,SAAS,oBAAoB,GAAG,oBAAoB;IAErD;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE;QACP,oEAAoE;QACpE,OAAO,CAAC,EA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AGG;IACH,wBAAwB,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CAC1C,GACL,mBAAmB,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAiD9C;AAgBD,oFAAoF;AACpF,wBAAgB,yBAAyB,CAAC,CAAC,SAAS,oBAAoB,EACtE,QAAQ,EAAE,CAAC,EACX,OAAO,EAAE,yBAAyB,CAAC,CAAC,CAAC,GACpC,uBAAuB,CAmDzB;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,oBAAoB,EACnE,MAAM,EAAE,wBAAwB,EAChC,QAAQ,EAAE,CAAC,EACX,OAAO,EAAE;IAAE,YAAY,EAAE,OAAO,CAAA;CAAE,EAClC,OAAO,GAAE,IAAI,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAM,GACzD,oBAAoB,CAsDtB"}
@@ -1,4 +1,6 @@
1
1
  const IAPKIT_UNKNOWN_RETRY_MS = 30_000;
2
+ // An expired App Store receipt may still be in billing grace; check it again.
3
+ const DEVICE_EXPIRED_RETRY_MS = 30_000;
2
4
  /**
3
5
  * @internal Use the SDK's confirmWithIapkit.
4
6
  * The SDK's `confirmWithIapkit`, given its `verifyPurchaseWithProvider`:
@@ -19,8 +21,11 @@ export function createIapkitConfirmation(verifyPurchaseWithProvider, options) {
19
21
  * @internal Use the SDK's confirmOnDeviceIOS.
20
22
  * The SDK's `confirmOnDeviceIOS`, given its `getPendingTransactionsIOS`, for an
21
23
  * app with neither a backend nor IAPKit. StoreKit verified the transaction if
22
- * it is still unfinished, unrevoked, not upgraded, unexpired, and from the
23
- * purchase's environment; `grant` then runs before the flow finishes it.
24
+ * it lists it as unfinished, or, for a purchase the flow already finished, in
25
+ * `getTransactionHistoryIOS`, from the purchase's environment. A revoked or
26
+ * upgraded one is `invalid`, and an expired one `verification_delayed`, since
27
+ * billing grace can still cover it; `grant` runs before an unfinished one is
28
+ * finished, and again for a finished non-consumable a restore reads.
24
29
  */
25
30
  export function createDeviceConfirmationIOS(getPendingTransactionsIOS, options = {}) {
26
31
  return async (purchase, context) => {
@@ -30,24 +35,36 @@ export function createDeviceConfirmationIOS(getPendingTransactionsIOS, options =
30
35
  (purchase.storeId ?? "apple") !== "apple") {
31
36
  throw new Error(`Device confirmation covers App Store purchases, not ${purchase.storeId ?? purchase.store}`);
32
37
  }
33
- const pending = await getPendingTransactionsIOS();
34
- // After the query: a transaction can expire while StoreKit answers.
35
- const now = Date.now();
36
- const verified = pending.some((candidate) => candidate.store === "apple" &&
38
+ const isSame = (candidate) => candidate.store === "apple" &&
37
39
  purchase.id !== "" &&
38
40
  candidate.id === purchase.id &&
39
41
  candidate.productId === purchase.productId &&
40
- candidate.revocationDateIOS == null &&
41
- candidate.isUpgradedIOS !== true &&
42
- (candidate.expirationDateIOS == null ||
43
- candidate.expirationDateIOS > now) &&
44
42
  (purchase.environmentIOS == null ||
45
- candidate.environmentIOS === purchase.environmentIOS));
46
- if (!verified) {
47
- throw new Error(`StoreKit lists no valid unfinished transaction for ${purchase.productId}`);
43
+ candidate.environmentIOS === purchase.environmentIOS);
44
+ const pending = (await getPendingTransactionsIOS()).find(isSame);
45
+ const transaction = pending ?? (await options.getTransactionHistoryIOS?.())?.find(isSame);
46
+ if (!transaction) {
47
+ throw new Error(`StoreKit lists no transaction for ${purchase.productId}`);
48
48
  }
49
- await options.grant?.(purchase, context);
50
- return { status: "entitled", alreadyGranted: false };
49
+ if (transaction.revocationDateIOS != null) {
50
+ return { status: "invalid", reason: "revoked" };
51
+ }
52
+ if (transaction.isUpgradedIOS === true) {
53
+ return { status: "invalid", reason: "upgraded" };
54
+ }
55
+ // After the reads: a transaction can expire while StoreKit answers.
56
+ if (transaction.expirationDateIOS != null &&
57
+ transaction.expirationDateIOS <= Date.now()) {
58
+ return {
59
+ status: "verification_delayed",
60
+ retryAfterMs: DEVICE_EXPIRED_RETRY_MS,
61
+ };
62
+ }
63
+ // A finished consumable was credited before it was consumed.
64
+ if (pending || !context.isConsumable) {
65
+ await options.grant?.(purchase, context);
66
+ }
67
+ return { status: "entitled", alreadyGranted: !pending };
51
68
  };
52
69
  }
53
70
  // Checked before verifying: a consumable must never pass without a way to credit it.
@@ -1 +1 @@
1
- {"version":3,"file":"purchase-flow-confirmers.js","sourceRoot":"","sources":["../src/purchase-flow-confirmers.ts"],"names":[],"mappings":"AAmEA,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAEvC;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,0BAEsC,EACtC,OAAqC;IAErC,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;QACjC,YAAY,CAAC,mBAAmB,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9D,MAAM,YAAY,GAAG,sBAAsB,CACzC,MAAM,0BAA0B,CAC9B,yBAAyB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAC7C,EACD,QAAQ,EACR,OAAO,EACP,OAAO,CACR,CAAC;QACF,IAAI,YAAY,CAAC,MAAM,KAAK,UAAU,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;YACvE,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,2BAA2B,CACzC,yBAA6C,EAC7C,UAGI,EAAE;IAEN,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;QACjC,YAAY,CAAC,oBAAoB,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC/D,uEAAuE;QACvE,IACE,QAAQ,CAAC,KAAK,KAAK,OAAO;YAC1B,CAAC,QAAQ,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,OAAO,EACzC,CAAC;YACD,MAAM,IAAI,KAAK,CACb,u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.\n// Each adapter uses the same lifecycle contract as other verification services.\nimport type {\n PurchaseConfirmation,\n PurchaseFlowOptions,\n PurchaseFlowPurchase,\n} from \"./purchase-flow-core\";\n\ntype IapkitStore = \"apple\" | \"google\" | \"amazon\" | \"horizon\";\n\n/** How an app without its own backend confirms purchases with IAPKit. */\nexport interface IapkitConfirmationOptions<\n P extends PurchaseFlowPurchase = PurchaseFlowPurchase,\n> {\n /**\n * A publishable key (`openiap-kit_pk_...`), which is safe to ship in an\n * app. Leave it out where the SDK has one configured, such as Expo's\n * `iapkitApiKey`.\n */\n apiKey?: string;\n /** A self-hosted or local IAPKit origin. Defaults to https://kit.openiap.dev. */\n baseUrl?: string;\n amazon?: {\n /** Verify App Tester receipts with the Amazon RVS Cloud Sandbox. */\n sandbox?: boolean;\n /** Expected verdict environment; defaults to Sandbox with sandbox, otherwise Production. */\n expectedEnvironment?: \"Sandbox\" | \"Production\";\n /** RVS reports a subscription term under its parent SKU; maps one to the other. */\n verifiedProductId?: (productId: string) => string;\n };\n /** The IAPKit store that verifies a community store's evidence, such as an Amazon RVS adapter. */\n verifyAs?: (purchase: P) => IapkitStore | undefined;\n /** Credits consumables before finishing; must be idempotent per purchase.id. */\n grant?: (purchase: P, context: { isConsumable: boolean }) => Promise<void>;\n}\n\n/** @internal Use the SDK's VerifyPurchaseWithProviderProps. */\nexport interface IapkitVerificationProps {\n provider: \"iapkit\";\n iapkit: {\n apiKey?: string;\n baseUrl?: string;\n apple?: { jws: string };\n google?: { purchaseToken: string };\n amazon?: {\n receiptId: string;\n expectedProductId: string;\n sandbox: boolean;\n userId?: string;\n };\n horizon?: { sku: string };\n };\n}\n\n/** @internal Use the SDK's VerifyPurchaseWithProviderResult. */\nexport interface IapkitVerificationResult {\n iapkit?: {\n store: string;\n storeId: string;\n environment?: string | null;\n isValid: boolean;\n state: string;\n productId?: string | null;\n } | null;\n errors?: { code?: string | null; message: string }[] | null;\n}\n\nconst IAPKIT_UNKNOWN_RETRY_MS = 30_000;\n\n/**\n * @internal Use the SDK's confirmWithIapkit.\n * The SDK's `confirmWithIapkit`, given its `verifyPurchaseWithProvider`:\n * verifies the purchase with IAPKit, then runs `grant` before the flow\n * finishes it.\n */\nexport function createIapkitConfirmation<P extends PurchaseFlowPurchase>(\n verifyPurchaseWithProvider: (\n props: IapkitVerificationProps,\n ) => Promise<IapkitVerificationResult>,\n options: IapkitConfirmationOptions<P>,\n): PurchaseFlowOptions<P>[\"confirmWithBackend\"] {\n return async (purchase, context) => {\n requireGrant(\"confirmWithIapkit\", purchase, context, options);\n const confirmation = readIapkitVerification(\n await verifyPurchaseWithProvider(\n toIapkitVerificationProps(purchase, options),\n ),\n purchase,\n context,\n options,\n );\n if (confirmation.status === \"entitled\" && !confirmation.alreadyGranted) {\n await options.grant?.(purchase, context);\n }\n return confirmation;\n };\n}\n\n/**\n * @internal Use the SDK's confirmOnDeviceIOS.\n * The SDK's `confirmOnDeviceIOS`, given its `getPendingTransactionsIOS`, for an\n * app with neither a backend nor IAPKit. StoreKit verified the transaction if\n * it is still unfinished, unrevoked, not upgraded, unexpired, and from the\n * purchase's environment; `grant` then runs before the flow finishes it.\n */\nexport function createDeviceConfirmationIOS<P extends PurchaseFlowPurchase>(\n getPendingTransactionsIOS: () => Promise<P[]>,\n options: {\n /** Required for consumables; credit each purchase.id only once. */\n grant?: (purchase: P, context: { isConsumable: boolean }) => Promise<void>;\n } = {},\n): PurchaseFlowOptions<P>[\"confirmWithBackend\"] {\n return async (purchase, context) => {\n requireGrant(\"confirmOnDeviceIOS\", purchase, context, options);\n // A community provider may report store \"apple\" under its own storeId.\n if (\n purchase.store !== \"apple\" ||\n (purchase.storeId ?? \"apple\") !== \"apple\"\n ) {\n throw new Error(\n `Device confirmation covers App Store purchases, not ${purchase.storeId ?? purchase.store}`,\n );\n }\n const pending = await getPendingTransactionsIOS();\n // After the query: a transaction can expire while StoreKit answers.\n const now = Date.now();\n const verified = pending.some(\n (candidate) =>\n candidate.store === \"apple\" &&\n purchase.id !== \"\" &&\n candidate.id === purchase.id &&\n candidate.productId === purchase.productId &&\n candidate.revocationDateIOS == null &&\n candidate.isUpgradedIOS !== true &&\n (candidate.expirationDateIOS == null ||\n candidate.expirationDateIOS > now) &&\n (purchase.environmentIOS == null ||\n candidate.environmentIOS === purchase.environmentIOS),\n );\n if (!verified) {\n throw new Error(\n `StoreKit lists no valid unfinished transaction for ${purchase.productId}`,\n );\n }\n await options.grant?.(purchase, context);\n return { status: \"entitled\", alreadyGranted: false };\n };\n}\n\n// Checked before verifying: a consumable must never pass without a way to credit it.\nfunction requireGrant<P extends PurchaseFlowPurchase>(\n name: string,\n purchase: P,\n context: { isConsumable: boolean },\n options: Pick<IapkitConfirmationOptions<P>, \"grant\">,\n): void {\n if (context.isConsumable && !options.grant) {\n throw new Error(\n `${name} needs grant to credit consumable ${purchase.productId} before it is consumed`,\n );\n }\n}\n\n/** @internal Builds the IAPKit request; throws for a store IAPKit cannot verify. */\nexport function toIapkitVerificationProps<P extends PurchaseFlowPurchase>(\n purchase: P,\n options: IapkitConfirmationOptions<P>,\n): IapkitVerificationProps {\n const apiKey = options.apiKey?.trim();\n // An unset environment variable, not a deliberate fallback to the SDK's key.\n if (apiKey === \"\") throw new Error(\"IAPKit apiKey is empty\");\n const baseUrl = options.baseUrl?.trim();\n const base = {\n ...(apiKey ? { apiKey } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n };\n const token = (): string => {\n if (!purchase.purchaseToken) {\n throw new Error(\n `Purchase ${purchase.productId} has no purchase token to verify`,\n );\n }\n return purchase.purchaseToken;\n };\n const store = verifyingStore(purchase, options);\n switch (store) {\n case \"apple\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, apple: { jws: token() } },\n };\n case \"google\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, google: { purchaseToken: token() } },\n };\n case \"amazon\":\n amazonExpectedEnvironment(options.amazon);\n return {\n provider: \"iapkit\",\n iapkit: {\n ...base,\n amazon: {\n receiptId: token(),\n expectedProductId: amazonProductId(purchase, options),\n sandbox: options.amazon?.sandbox ?? false,\n ...(purchase.userIdAmazon ? { userId: purchase.userIdAmazon } : {}),\n },\n },\n };\n case \"horizon\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, horizon: { sku: purchase.productId } },\n };\n default:\n throw new Error(`IAPKit cannot verify store ${purchase.store}`);\n }\n}\n\n/**\n * @internal Use the SDK's confirmWithIapkit.\n * Turns IAPKit's answer into the flow's confirmation. Anything that may be a\n * configuration error rather than a rejected payment throws, so the flow\n * reports `failed` and leaves the purchase unfinished: evidence for another\n * store, product, or environment, `inauthentic` (IAPKit's answer to a product\n * or package mismatch, and to every Horizon rejection), and a valid state this\n * product type cannot be granted from.\n */\nexport function readIapkitVerification<P extends PurchaseFlowPurchase>(\n result: IapkitVerificationResult,\n purchase: P,\n context: { isConsumable: boolean },\n options: Omit<IapkitConfirmationOptions<P>, \"apiKey\"> = {},\n): PurchaseConfirmation {\n const verified = result.iapkit;\n if (!verified) {\n const errors = (result.errors ?? []).map((error) =>\n error.code ? `[${error.code}] ${error.message}` : error.message,\n );\n throw new Error(\n errors.join(\"\\n\") || \"IAPKit returned no verification result\",\n );\n }\n switch (verified.state) {\n case \"pending\":\n return { status: \"store_pending\" };\n // The store gave no usable answer: retry instead of rejecting a payment.\n case \"unknown\":\n return {\n status: \"verification_delayed\",\n retryAfterMs: IAPKIT_UNKNOWN_RETRY_MS,\n };\n }\n const store = verifyingStore(purchase, options);\n const expectedProductId =\n store === \"amazon\"\n ? amazonProductId(purchase, options)\n : purchase.productId;\n const mismatch =\n verified.store !== purchase.store\n ? `store ${verified.store}, expected ${purchase.store}`\n : purchase.storeId && verified.storeId !== purchase.storeId\n ? `store id ${verified.storeId}, expected ${purchase.storeId}`\n : verified.productId !== expectedProductId\n ? `product ${verified.productId ?? \"(none)\"}, expected ${expectedProductId}`\n : environmentMismatch(verified.environment, store, purchase, options);\n if (mismatch) throw new Error(`IAPKit verified ${mismatch}`);\n if (!verified.isValid) {\n switch (verified.state) {\n case \"canceled\":\n case \"expired\":\n return { status: \"invalid\", reason: verified.state };\n // Only a granted purchase is consumed; the flow grants before finishing.\n case \"consumed\":\n return { status: \"entitled\", alreadyGranted: true };\n default:\n throw new Error(`IAPKit rejected the purchase: ${verified.state}`);\n }\n }\n if (!grantsAccess(store, verified.state, context.isConsumable)) {\n throw new Error(\n `IAPKit state ${verified.state} cannot grant this ${\n context.isConsumable ? \"consumable\" : \"non-consumable\"\n } ${purchase.store} purchase`,\n );\n }\n return { status: \"entitled\", alreadyGranted: false };\n}\n\nfunction verifyingStore<P extends PurchaseFlowPurchase>(\n purchase: P,\n options: Pick<IapkitConfirmationOptions<P>, \"verifyAs\">,\n): string {\n return options.verifyAs?.(purchase) ?? purchase.store;\n}\n\nfunction amazonProductId(\n purchase: PurchaseFlowPurchase,\n options: Pick<IapkitConfirmationOptions, \"amazon\">,\n): string {\n return (\n options.amazon?.verifiedProductId?.(purchase.productId) ??\n purchase.productId\n );\n}\n\nfunction amazonExpectedEnvironment(\n amazon: IapkitConfirmationOptions[\"amazon\"],\n): \"Sandbox\" | \"Production\" {\n const expected =\n amazon?.expectedEnvironment ?? (amazon?.sandbox ? \"Sandbox\" : \"Production\");\n if (expected !== \"Sandbox\" && expected !== \"Production\") {\n throw new Error(\"Amazon expectedEnvironment must be Sandbox or Production\");\n }\n if (amazon?.sandbox && expected === \"Production\") {\n throw new Error(\n \"Amazon Cloud Sandbox requires expectedEnvironment Sandbox\",\n );\n }\n return expected;\n}\n\nfunction environmentMismatch(\n environment: string | null | undefined,\n store: string,\n purchase: PurchaseFlowPurchase,\n options: Pick<IapkitConfirmationOptions, \"amazon\">,\n): string | null {\n const expected =\n store === \"amazon\"\n ? amazonExpectedEnvironment(options.amazon)\n : store === \"apple\"\n ? purchase.environmentIOS\n : null;\n return expected && environment !== expected\n ? `environment ${environment ?? \"(none)\"}, expected ${expected}`\n : null;\n}\n\n// Apple and Amazon keep a consumable at ready-to-consume until it is finished;\n// Google reports a granted purchase as pending-acknowledgment until then.\nfunction grantsAccess(\n store: string,\n state: string,\n isConsumable: boolean,\n): boolean {\n switch (store) {\n case \"apple\":\n case \"amazon\":\n return state === (isConsumable ? \"ready-to-consume\" : \"entitled\");\n case \"google\":\n return (\n state === \"entitled\" ||\n state === \"pending-acknowledgment\" ||\n (isConsumable && state === \"ready-to-consume\")\n );\n case \"horizon\":\n return state === \"entitled\";\n default:\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"purchase-flow-confirmers.js","sourceRoot":"","sources":["../src/purchase-flow-confirmers.ts"],"names":[],"mappings":"AAmEA,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,8EAA8E;AAC9E,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAEvC;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,0BAEsC,EACtC,OAAqC;IAErC,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;QACjC,YAAY,CAAC,mBAAmB,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9D,MAAM,YAAY,GAAG,sBAAsB,CACzC,MAAM,0BAA0B,CAC9B,yBAAyB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAC7C,EACD,QAAQ,EACR,OAAO,EACP,OAAO,CACR,CAAC;QACF,IAAI,YAAY,CAAC,MAAM,KAAK,UAAU,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;YACvE,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,2BAA2B,CACzC,yBAA6C,EAC7C,UAQI,EAAE;IAEN,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;QACjC,YAAY,CAAC,oBAAoB,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAA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QAAQ;QACzC,CAAC,CAAC,eAAe,WAAW,IAAI,QAAQ,cAAc,QAAQ,EAAE;QAChE,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,+EAA+E;AAC/E,0EAA0E;AAC1E,SAAS,YAAY,CACnB,KAAa,EACb,KAAa,EACb,YAAqB;IAErB,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,OAAO,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,KAAK,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;QACpE,KAAK,QAAQ;YACX,OAAO,CACL,KAAK,KAAK,UAAU;gBACpB,KAAK,KAAK,wBAAwB;gBAClC,CAAC,YAAY,IAAI,KAAK,KAAK,kBAAkB,CAAC,CAC/C,CAAC;QACJ,KAAK,SAAS;YACZ,OAAO,KAAK,KAAK,UAAU,CAAC;QAC9B;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["// Internal adapters for SDK confirmation helpers; apps use SDK root imports.\n// Each adapter uses the same lifecycle contract as other verification services.\nimport type {\n PurchaseConfirmation,\n PurchaseFlowOptions,\n PurchaseFlowPurchase,\n} from \"./purchase-flow-core\";\n\ntype IapkitStore = \"apple\" | \"google\" | \"amazon\" | \"horizon\";\n\n/** How an app without its own backend confirms purchases with IAPKit. */\nexport interface IapkitConfirmationOptions<\n P extends PurchaseFlowPurchase = PurchaseFlowPurchase,\n> {\n /**\n * A publishable key (`openiap-kit_pk_...`), which is safe to ship in an\n * app. Leave it out where the SDK has one configured, such as Expo's\n * `iapkitApiKey`.\n */\n apiKey?: string;\n /** A self-hosted or local IAPKit origin. Defaults to https://kit.openiap.dev. */\n baseUrl?: string;\n amazon?: {\n /** Verify App Tester receipts with the Amazon RVS Cloud Sandbox. */\n sandbox?: boolean;\n /** Expected verdict environment; defaults to Sandbox with sandbox, otherwise Production. */\n expectedEnvironment?: \"Sandbox\" | \"Production\";\n /** RVS reports a subscription term under its parent SKU; maps one to the other. */\n verifiedProductId?: (productId: string) => string;\n };\n /** The IAPKit store that verifies a community store's evidence, such as an Amazon RVS adapter. */\n verifyAs?: (purchase: P) => IapkitStore | undefined;\n /** Credits consumables before finishing; must be idempotent per purchase.id. */\n grant?: (purchase: P, context: { isConsumable: boolean }) => Promise<void>;\n}\n\n/** @internal Use the SDK's VerifyPurchaseWithProviderProps. */\nexport interface IapkitVerificationProps {\n provider: \"iapkit\";\n iapkit: {\n apiKey?: string;\n baseUrl?: string;\n apple?: { jws: string };\n google?: { purchaseToken: string };\n amazon?: {\n receiptId: string;\n expectedProductId: string;\n sandbox: boolean;\n userId?: string;\n };\n horizon?: { sku: string };\n };\n}\n\n/** @internal Use the SDK's VerifyPurchaseWithProviderResult. */\nexport interface IapkitVerificationResult {\n iapkit?: {\n store: string;\n storeId: string;\n environment?: string | null;\n isValid: boolean;\n state: string;\n productId?: string | null;\n } | null;\n errors?: { code?: string | null; message: string }[] | null;\n}\n\nconst IAPKIT_UNKNOWN_RETRY_MS = 30_000;\n// An expired App Store receipt may still be in billing grace; check it again.\nconst DEVICE_EXPIRED_RETRY_MS = 30_000;\n\n/**\n * @internal Use the SDK's confirmWithIapkit.\n * The SDK's `confirmWithIapkit`, given its `verifyPurchaseWithProvider`:\n * verifies the purchase with IAPKit, then runs `grant` before the flow\n * finishes it.\n */\nexport function createIapkitConfirmation<P extends PurchaseFlowPurchase>(\n verifyPurchaseWithProvider: (\n props: IapkitVerificationProps,\n ) => Promise<IapkitVerificationResult>,\n options: IapkitConfirmationOptions<P>,\n): PurchaseFlowOptions<P>[\"confirmWithBackend\"] {\n return async (purchase, context) => {\n requireGrant(\"confirmWithIapkit\", purchase, context, options);\n const confirmation = readIapkitVerification(\n await verifyPurchaseWithProvider(\n toIapkitVerificationProps(purchase, options),\n ),\n purchase,\n context,\n options,\n );\n if (confirmation.status === \"entitled\" && !confirmation.alreadyGranted) {\n await options.grant?.(purchase, context);\n }\n return confirmation;\n };\n}\n\n/**\n * @internal Use the SDK's confirmOnDeviceIOS.\n * The SDK's `confirmOnDeviceIOS`, given its `getPendingTransactionsIOS`, for an\n * app with neither a backend nor IAPKit. StoreKit verified the transaction if\n * it lists it as unfinished, or, for a purchase the flow already finished, in\n * `getTransactionHistoryIOS`, from the purchase's environment. A revoked or\n * upgraded one is `invalid`, and an expired one `verification_delayed`, since\n * billing grace can still cover it; `grant` runs before an unfinished one is\n * finished, and again for a finished non-consumable a restore reads.\n */\nexport function createDeviceConfirmationIOS<P extends PurchaseFlowPurchase>(\n getPendingTransactionsIOS: () => Promise<P[]>,\n options: {\n /** Required for consumables; credit each purchase.id only once. */\n grant?: (purchase: P, context: { isConsumable: boolean }) => Promise<void>;\n /**\n * StoreKit's verified history, such as `getAvailablePurchases` with\n * `onlyIncludeActiveItemsIOS: false`; without it a finished purchase throws.\n */\n getTransactionHistoryIOS?: () => Promise<P[]>;\n } = {},\n): PurchaseFlowOptions<P>[\"confirmWithBackend\"] {\n return async (purchase, context) => {\n requireGrant(\"confirmOnDeviceIOS\", purchase, context, options);\n // A community provider may report store \"apple\" under its own storeId.\n if (\n purchase.store !== \"apple\" ||\n (purchase.storeId ?? \"apple\") !== \"apple\"\n ) {\n throw new Error(\n `Device confirmation covers App Store purchases, not ${purchase.storeId ?? purchase.store}`,\n );\n }\n const isSame = (candidate: P) =>\n candidate.store === \"apple\" &&\n purchase.id !== \"\" &&\n candidate.id === purchase.id &&\n candidate.productId === purchase.productId &&\n (purchase.environmentIOS == null ||\n candidate.environmentIOS === purchase.environmentIOS);\n const pending = (await getPendingTransactionsIOS()).find(isSame);\n const transaction =\n pending ?? (await options.getTransactionHistoryIOS?.())?.find(isSame);\n if (!transaction) {\n throw new Error(\n `StoreKit lists no transaction for ${purchase.productId}`,\n );\n }\n if (transaction.revocationDateIOS != null) {\n return { status: \"invalid\", reason: \"revoked\" };\n }\n if (transaction.isUpgradedIOS === true) {\n return { status: \"invalid\", reason: \"upgraded\" };\n }\n // After the reads: a transaction can expire while StoreKit answers.\n if (\n transaction.expirationDateIOS != null &&\n transaction.expirationDateIOS <= Date.now()\n ) {\n return {\n status: \"verification_delayed\",\n retryAfterMs: DEVICE_EXPIRED_RETRY_MS,\n };\n }\n // A finished consumable was credited before it was consumed.\n if (pending || !context.isConsumable) {\n await options.grant?.(purchase, context);\n }\n return { status: \"entitled\", alreadyGranted: !pending };\n };\n}\n\n// Checked before verifying: a consumable must never pass without a way to credit it.\nfunction requireGrant<P extends PurchaseFlowPurchase>(\n name: string,\n purchase: P,\n context: { isConsumable: boolean },\n options: Pick<IapkitConfirmationOptions<P>, \"grant\">,\n): void {\n if (context.isConsumable && !options.grant) {\n throw new Error(\n `${name} needs grant to credit consumable ${purchase.productId} before it is consumed`,\n );\n }\n}\n\n/** @internal Builds the IAPKit request; throws for a store IAPKit cannot verify. */\nexport function toIapkitVerificationProps<P extends PurchaseFlowPurchase>(\n purchase: P,\n options: IapkitConfirmationOptions<P>,\n): IapkitVerificationProps {\n const apiKey = options.apiKey?.trim();\n // An unset environment variable, not a deliberate fallback to the SDK's key.\n if (apiKey === \"\") throw new Error(\"IAPKit apiKey is empty\");\n const baseUrl = options.baseUrl?.trim();\n const base = {\n ...(apiKey ? { apiKey } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n };\n const token = (): string => {\n if (!purchase.purchaseToken) {\n throw new Error(\n `Purchase ${purchase.productId} has no purchase token to verify`,\n );\n }\n return purchase.purchaseToken;\n };\n const store = verifyingStore(purchase, options);\n switch (store) {\n case \"apple\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, apple: { jws: token() } },\n };\n case \"google\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, google: { purchaseToken: token() } },\n };\n case \"amazon\":\n amazonExpectedEnvironment(options.amazon);\n return {\n provider: \"iapkit\",\n iapkit: {\n ...base,\n amazon: {\n receiptId: token(),\n expectedProductId: amazonProductId(purchase, options),\n sandbox: options.amazon?.sandbox ?? false,\n ...(purchase.userIdAmazon ? { userId: purchase.userIdAmazon } : {}),\n },\n },\n };\n case \"horizon\":\n return {\n provider: \"iapkit\",\n iapkit: { ...base, horizon: { sku: purchase.productId } },\n };\n default:\n throw new Error(`IAPKit cannot verify store ${purchase.store}`);\n }\n}\n\n/**\n * @internal Use the SDK's confirmWithIapkit.\n * Turns IAPKit's answer into the flow's confirmation. Anything that may be a\n * configuration error rather than a rejected payment throws, so the flow\n * reports `failed` and leaves the purchase unfinished: evidence for another\n * store, product, or environment, `inauthentic` (IAPKit's answer to a product\n * or package mismatch, and to every Horizon rejection), and a valid state this\n * product type cannot be granted from.\n */\nexport function readIapkitVerification<P extends PurchaseFlowPurchase>(\n result: IapkitVerificationResult,\n purchase: P,\n context: { isConsumable: boolean },\n options: Omit<IapkitConfirmationOptions<P>, \"apiKey\"> = {},\n): PurchaseConfirmation {\n const verified = result.iapkit;\n if (!verified) {\n const errors = (result.errors ?? []).map((error) =>\n error.code ? `[${error.code}] ${error.message}` : error.message,\n );\n throw new Error(\n errors.join(\"\\n\") || \"IAPKit returned no verification result\",\n );\n }\n switch (verified.state) {\n case \"pending\":\n return { status: \"store_pending\" };\n // The store gave no usable answer: retry instead of rejecting a payment.\n case \"unknown\":\n return {\n status: \"verification_delayed\",\n retryAfterMs: IAPKIT_UNKNOWN_RETRY_MS,\n };\n }\n const store = verifyingStore(purchase, options);\n const expectedProductId =\n store === \"amazon\"\n ? amazonProductId(purchase, options)\n : purchase.productId;\n const mismatch =\n verified.store !== purchase.store\n ? `store ${verified.store}, expected ${purchase.store}`\n : purchase.storeId && verified.storeId !== purchase.storeId\n ? `store id ${verified.storeId}, expected ${purchase.storeId}`\n : verified.productId !== expectedProductId\n ? `product ${verified.productId ?? \"(none)\"}, expected ${expectedProductId}`\n : environmentMismatch(verified.environment, store, purchase, options);\n if (mismatch) throw new Error(`IAPKit verified ${mismatch}`);\n if (!verified.isValid) {\n switch (verified.state) {\n case \"canceled\":\n case \"expired\":\n return { status: \"invalid\", reason: verified.state };\n // Only a granted purchase is consumed; the flow grants before finishing.\n case \"consumed\":\n return { status: \"entitled\", alreadyGranted: true };\n default:\n throw new Error(`IAPKit rejected the purchase: ${verified.state}`);\n }\n }\n if (!grantsAccess(store, verified.state, context.isConsumable)) {\n throw new Error(\n `IAPKit state ${verified.state} cannot grant this ${\n context.isConsumable ? \"consumable\" : \"non-consumable\"\n } ${purchase.store} purchase`,\n );\n }\n return { status: \"entitled\", alreadyGranted: false };\n}\n\nfunction verifyingStore<P extends PurchaseFlowPurchase>(\n purchase: P,\n options: Pick<IapkitConfirmationOptions<P>, \"verifyAs\">,\n): string {\n return options.verifyAs?.(purchase) ?? purchase.store;\n}\n\nfunction amazonProductId(\n purchase: PurchaseFlowPurchase,\n options: Pick<IapkitConfirmationOptions, \"amazon\">,\n): string {\n return (\n options.amazon?.verifiedProductId?.(purchase.productId) ??\n purchase.productId\n );\n}\n\nfunction amazonExpectedEnvironment(\n amazon: IapkitConfirmationOptions[\"amazon\"],\n): \"Sandbox\" | \"Production\" {\n const expected =\n amazon?.expectedEnvironment ?? (amazon?.sandbox ? \"Sandbox\" : \"Production\");\n if (expected !== \"Sandbox\" && expected !== \"Production\") {\n throw new Error(\"Amazon expectedEnvironment must be Sandbox or Production\");\n }\n if (amazon?.sandbox && expected === \"Production\") {\n throw new Error(\n \"Amazon Cloud Sandbox requires expectedEnvironment Sandbox\",\n );\n }\n return expected;\n}\n\nfunction environmentMismatch(\n environment: string | null | undefined,\n store: string,\n purchase: PurchaseFlowPurchase,\n options: Pick<IapkitConfirmationOptions, \"amazon\">,\n): string | null {\n const expected =\n store === \"amazon\"\n ? amazonExpectedEnvironment(options.amazon)\n : store === \"apple\"\n ? purchase.environmentIOS\n : null;\n return expected && environment !== expected\n ? `environment ${environment ?? \"(none)\"}, expected ${expected}`\n : null;\n}\n\n// Apple and Amazon keep a consumable at ready-to-consume until it is finished;\n// Google reports a granted purchase as pending-acknowledgment until then.\nfunction grantsAccess(\n store: string,\n state: string,\n isConsumable: boolean,\n): boolean {\n switch (store) {\n case \"apple\":\n case \"amazon\":\n return state === (isConsumable ? \"ready-to-consume\" : \"entitled\");\n case \"google\":\n return (\n state === \"entitled\" ||\n state === \"pending-acknowledgment\" ||\n (isConsumable && state === \"ready-to-consume\")\n );\n case \"horizon\":\n return state === \"entitled\";\n default:\n return false;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"useIAP.d.ts","sourceRoot":"","sources":["../src/useIAP.ts"],"names":[],"mappings":"AAMA,OAAO,EAWL,eAAe,IAAI,uBAAuB,EAO1C,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACtB,MAAM,SAAS,CAAC;AAEjB,OAAO,KAAK,EAAC,YAAY,EAAE,mBAAmB,EAAC,MAAM,sBAAsB,CAAC;AAa5E,OAAO,KAAK,EACV,OAAO,EACP,mBAAmB,EAGnB,8BAA8B,EAC9B,qBAAqB,EACrB,sCAAsC,EAEtC,QAAQ,EACR,2BAA2B,EAE3B,8BAA8B,EAC9B,mBAAmB,EACnB,oBAAoB,EACpB,+BAA+B,EAC/B,gCAAgC,EAChC,eAAe,EACf,aAAa,EACb,UAAU,EACV,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAEjB,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,sBAAsB,CAAC;AAkBxD,KAAK,MAAM,GAAG;IACZ,SAAS,EAAE,OAAO,CAAC;IACnB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,aAAa,EAAE,mBAAmB,EAAE,CAAC;IACrC,kBAAkB,EAAE,QAAQ,EAAE,CAAC;IAC/B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,mBAAmB,EAAE,kBAAkB,EAAE,CAAC;IAC1C,iBAAiB,EAAE,CAAC,EAClB,QAAQ,EACR,YAAY,GACb,EAAE;QACD,QAAQ,EAAE,QAAQ,CAAC;QACnB,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpB,qB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OAIG;IACH,8BAA8B,CAAC,EAAE,8BAA8B,GAAG,IAAI,CAAC;IACvE;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,oBAAoB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IAClD,0BAA0B,CAAC,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,IAAI,CAAC;IACzE;;;OAGG;IACH,iCAAiC,CAAC,EAAE,CAClC,OAAO,EAAE,sCAAsC,KAC5C,IAAI,CAAC;IACV,8DAA8D;IAC9D,0BAA0B,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;IAC1D;;;;;OAKG;IACH,2BAA2B,CAAC,EAAE,qBAAqB,CAAC;IACpD;;;OAGG;IACH,8BAA8B,CAAC,EAAE,8BAA8B,CAAC;CACjE;AAwCD;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM,CA4rBtD"}
package/build/useIAP.js CHANGED
@@ -284,16 +284,30 @@ export function useIAP(options) {
284
284
  getActiveSubscriptionsInternal,
285
285
  ]);
286
286
  /**
287
- * Restore non-consumable and active subscription purchases.
287
+ * Restore non-consumable and active subscription purchases. With
288
+ * `purchaseFlow`, confirms every owned purchase through the flow instead of
289
+ * the provider's restore, so iOS asks for no App Store sign-in, and rejects
290
+ * when a confirmation fails.
288
291
  *
289
292
  * @see {@link https://openiap.dev/docs/apis/restore-purchases}
290
293
  */
291
294
  const restorePurchasesInternal = useCallback(async (options) => {
292
295
  try {
293
- await restorePurchasesNative();
294
- await optionsRef.current?.purchaseFlow?.recoverPurchases({
295
- includeFinished: true,
296
- });
296
+ const flow = optionsRef.current?.purchaseFlow;
297
+ // The provider's restore adds an iOS sign-in and Horizon redeliveries;
298
+ // the flow reads the store's history itself.
299
+ if (flow) {
300
+ const outcomes = await flow.recoverPurchases({ includeFinished: true });
301
+ // A failed confirmation fails the restore; its purchase stays
302
+ // unfinished, so the next restore retries it.
303
+ for (const { status } of outcomes) {
304
+ if (status.status === 'failed')
305
+ throw status.error;
306
+ }
307
+ }
308
+ else {
309
+ await restorePurchasesNative();
310
+ }
297
311
  const read = startRead(availablePurchasesReads.current);
298
312
  const purchases = await getAvailablePurchases({
299
313
  alsoPublishToEventListenerIOS: options?.alsoPublishToEventListenerIOS ?? false,
@@ -1 +1 @@
1
- {"version":3,"file":"useIAP.js","sourceRoot":"","sources":["../src/useIAP.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,EAAC,MAAM,OAAO,CAAC;AAChF,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAC;AAGtC,mBAAmB;AACnB,OAAO,EACL,aAAa,EACb,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,gCAAgC,EAChC,uCAAuC,EACvC,gCAAgC,EAChC,qBAAqB,EACrB,iBAAiB,IAAI,yBAAyB,EAC9C,eAAe,IAAI,uBAAuB,EAC1C,aAAa,EACb,cAAc,IAAI,sBAAsB,EACxC,0BAA0B,IAAI,kCAAkC,EAChE,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,GAGpB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAC,qBAAqB,EAAC,MAAM,eAAe,CAAC;AACpD,OAAO,EAAC,sBAAsB,EAAC,MAAM,0BAA0B,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAChC,2CAA2C,EAC3C,yBAAyB,EACzB,0CAA0C,EAC1C,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAyB3B,OAAO,EAAC,SAAS,EAAC,MAAM,SAAS,CAAC;AAElC,OAAO,EACL,2BAA2B,EAC3B,oBAAoB,EACpB,kBAA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B;QACzB,0CAA0C;QAC1C,wBAAwB;QACxB,wBAAwB;QACxB,mBAAmB;KACpB,CAAC;AACJ,CAAC","sourcesContent":["// External dependencies\nimport {useCallback, useEffect, useLayoutEffect, useState, useRef} from 'react';\nimport {Platform} from 'react-native';\nimport type {EventSubscription} from 'expo-modules-core';\n\n// Internal modules\nimport {\n endConnection,\n initConnection,\n purchaseErrorListener,\n purchaseUpdatedListener,\n promotedProductListenerIOS,\n userChoiceBillingListenerAndroid,\n developerProvidedBillingListenerAndroid,\n subscriptionBillingIssueListener,\n getAvailablePurchases,\n finishTransaction as finishTransactionInternal,\n requestPurchase as requestPurchaseInternal,\n fetchProducts,\n verifyPurchase as verifyPurchaseInternal,\n verifyPurchaseWithProvider as verifyPurchaseWithProviderInternal,\n getActiveSubscriptions,\n hasActiveSubscriptions,\n openRedeemOfferCode,\n type ActiveSubscription,\n type ProductTypeInput,\n} from './index';\nimport {ExpoIapConsole} from './utils/debug';\nimport type {PurchaseFlow, PurchaseFlowOutcome} from './purchase-flow-core';\nimport {getPromotedProductIOS} from './modules/ios';\nimport {restorePurchasesNative} from './utils/restorePurchases';\nimport {\n getBillingChoiceInfoAndroid,\n isBillingProgramAvailableAndroid,\n createBillingProgramReportingDetailsAndroid,\n launchExternalLinkAndroid,\n showBillingProgramInformationDialogAndroid,\n showInAppMessagesAndroid,\n} from './modules/android';\n\n// Types\nimport type {\n Product,\n ProductSubscription,\n ProductQueryType,\n ProductRequest,\n BillingChoiceScreenTypeAndroid,\n BillingProgramAndroid,\n DeveloperProvidedBillingDetailsAndroid,\n InitConnectionConfig,\n Purchase,\n MutationRequestPurchaseArgs,\n PurchaseInput,\n PurchaseUpdatedListenerOptions,\n VerifyPurchaseProps,\n VerifyPurchaseResult,\n VerifyPurchaseWithProviderProps,\n VerifyPurchaseWithProviderResult,\n PurchaseOptions,\n MutationField,\n QueryField,\n UserChoiceBillingDetails,\n} from './types';\nimport {ErrorCode} from './types';\nimport type {PurchaseError} from './utils/errorMapping';\nimport {\n getUserFriendlyErrorMessage,\n isUserCancelledError,\n isRecoverableError,\n} from './utils/errorMapping';\n\n// Hooks share one native connection; the last mounted hook ends it.\nlet connectionOwnerCount = 0;\n\nconst releaseConnection = (): void => {\n connectionOwnerCount = Math.max(0, connectionOwnerCount - 1);\n if (connectionOwnerCount > 0) return;\n endConnection().catch((error: unknown) => {\n ExpoIapConsole.warn('[useIAP] endConnection failed:', error);\n });\n};\n\ntype UseIap = {\n connected: boolean;\n products: Product[];\n subscriptions: ProductSubscription[];\n availablePurchases: Purchase[];\n promotedProductIOS?: Product;\n activeSubscriptions: ActiveSubscription[];\n finishTransaction: ({\n purchase,\n isConsumable,\n }: {\n purchase: Purchase;\n isConsumable?: boolean;\n }) => Promise<void>;\n getAvailablePurchases: (options?: PurchaseOptions) => Promise<void>;\n fetchProducts: (params: {\n skus: string[];\n type?: ProductTypeInput;\n }) => Promise<void>;\n\n requestPurchase: (\n params: MutationRequestPurchaseArgs,\n ) => ReturnType<typeof requestPurchaseInternal>;\n verifyPurchase: (props: VerifyPurchaseProps) => Promise<VerifyPurchaseResult>;\n verifyPurchaseWithProvider: (\n props: VerifyPurchaseWithProviderProps,\n ) => Promise<VerifyPurchaseWithProviderResult>;\n restorePurchases: (options?: PurchaseOptions) => Promise<void>;\n getPromotedProductIOS: () => Promise<Product | null>;\n getActiveSubscriptions: (subscriptionIds?: string[]) => Promise<void>;\n hasActiveSubscriptions: (subscriptionIds?: string[]) => Promise<boolean>;\n /**\n * Manually retry the store connection.\n * Useful when the initial auto-connect fails (e.g., Play Store not ready at mount time).\n * Updates the `connected` state on success.\n */\n reconnect: () => Promise<boolean>;\n getBillingChoiceInfoAndroid: QueryField<'getBillingChoiceInfoAndroid'>;\n isBillingProgramAvailableAndroid: MutationField<'isBillingProgramAvailableAndroid'>;\n createBillingProgramReportingDetailsAndroid: MutationField<'createBillingProgramReportingDetailsAndroid'>;\n launchExternalLinkAndroid: MutationField<'launchExternalLinkAndroid'>;\n showBillingProgramInformationDialogAndroid: MutationField<'showBillingProgramInformationDialogAndroid'>;\n showInAppMessagesAndroid: MutationField<'showInAppMessagesAndroid'>;\n openRedeemOfferCode: MutationField<'openRedeemOfferCode'>;\n};\n\nexport interface UseIAPOptions {\n onPurchaseSuccess?: (purchase: Purchase) => void;\n /**\n * The app's flow from `createPurchaseFlow`, which confirms and finishes\n * every purchase. The hook recovers unfinished purchases once connected or\n * when the flow changes, reports outcomes, and refreshes ownership after\n * each. Leave finishing out of `onPurchaseSuccess` when this is set.\n */\n purchaseFlow?: PurchaseFlow<Purchase>;\n /** Each purchase's outcome from `purchaseFlow`. */\n onPurchaseFlowOutcome?: (outcome: PurchaseFlowOutcome<Purchase>) => void;\n onPurchaseError?: (error: PurchaseError) => void;\n /**\n * Options for the purchase success listener. iOS defaults to suppressing\n * StoreKit replay events for the same transaction ID; set\n * `dedupeTransactionIOS` to false only for diagnostics.\n */\n purchaseUpdatedListenerOptions?: PurchaseUpdatedListenerOptions | null;\n /**\n * Called when a hook method such as fetchProducts, getAvailablePurchases,\n * getActiveSubscriptions or restorePurchases fails.\n */\n onError?: (error: Error) => void;\n onPromotedProductIOS?: (product: Product) => void;\n onUserChoiceBillingAndroid?: (details: UserChoiceBillingDetails) => void;\n /**\n * Fires when the user selects developer-provided billing in an External\n * Payments or Google-rendered Billing Choice flow.\n */\n onDeveloperProvidedBillingAndroid?: (\n details: DeveloperProvidedBillingDetailsAndroid,\n ) => void;\n /** Fires when a subscription enters a billing-issue state. */\n onSubscriptionBillingIssue?: (purchase: Purchase) => void;\n /**\n * Enable a specific billing program for Android (8.2.0+).\n * Use 'external-payments' for Developer Provided Billing (Japan only, 8.3.0+).\n * Use 'user-choice-billing' for User Choice Billing (7.0+).\n * Use 'billing-choice' for Billing Choice (9.1.0+).\n */\n enableBillingProgramAndroid?: BillingProgramAndroid;\n /**\n * Select who renders the Billing Choice screen (9.1.0+). Must match the\n * choiceScreenType returned by isBillingProgramAvailableAndroid.\n */\n billingChoiceScreenTypeAndroid?: BillingChoiceScreenTypeAndroid;\n}\n\n// The store refused a new billing program because a purchase is in progress;\n// the live connection stays up.\nconst isRefusedRebuild = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === ErrorCode.DeveloperError;\n\n// A fetched item replaces the one it updates, keeping the list's order.\nfunction mergeByKey<T>(\n existingItems: T[],\n newItems: T[],\n getKey: (item: T) => string,\n): T[] {\n const merged = new Map(\n existingItems.map((item) => [getKey(item), item] as const),\n );\n newItems.forEach((item) => merged.set(getKey(item), item));\n return Array.from(merged.values());\n}\n\n// Store reads can resolve out of order. A result publishes only when no newer\n// read has published, so a failed newer read lets an older result through,\n// and a purchase makes every read that started before it stale.\ninterface ReadOrder {\n started: number;\n published: number;\n}\nconst startRead = (order: ReadOrder): number => ++order.started;\nconst claimPublish = (order: ReadOrder, read: number): boolean => {\n if (read <= order.published) return false;\n order.published = read;\n return true;\n};\nconst invalidateReads = (order: ReadOrder): void => {\n order.published = ++order.started;\n};\n\n/**\n * React Hook for managing In-App Purchases. Mounted hooks share one store\n * connection, which ends when the last of them unmounts.\n * See documentation at https://openiap.dev/docs/setup/expo#useIAP-hook\n */\nexport function useIAP(options?: UseIAPOptions): UseIap {\n const [connected, setConnected] = useState<boolean>(false);\n const [products, setProducts] = useState<Product[]>([]);\n const [subscriptions, setSubscriptions] = useState<ProductSubscription[]>([]);\n\n const [availablePurchases, setAvailablePurchases] = useState<Purchase[]>([]);\n const [promotedProductIOS, setPromotedProductIOS] = useState<Product>();\n const [activeSubscriptions, setActiveSubscriptions] = useState<\n ActiveSubscription[]\n >([]);\n\n const optionsRef = useRef<UseIAPOptions | undefined>(options);\n const connectedRef = useRef<boolean>(false);\n const isMountedRef = useRef<boolean>(false);\n const initializationGenerationRef = useRef(0);\n const startedInitializationGenerationRef = useRef(0);\n const availablePurchasesReads = useRef<ReadOrder>({started: 0, published: 0});\n const activeSubscriptionsReads = useRef<ReadOrder>({\n started: 0,\n published: 0,\n });\n\n // Before any effect runs, so a purchase never reaches a stale callback.\n useLayoutEffect(() => {\n optionsRef.current = options;\n }, [options]);\n\n useEffect(() => {\n connectedRef.current = connected;\n }, [connected]);\n\n const subscriptionsRef = useRef<{\n purchaseUpdate?: EventSubscription;\n purchaseError?: EventSubscription;\n promotedProductIOS?: EventSubscription;\n userChoiceBillingAndroid?: EventSubscription;\n developerProvidedBillingAndroid?: EventSubscription;\n subscriptionBillingIssue?: EventSubscription;\n }>({});\n\n const subscriptionsRefState = useRef<ProductSubscription[]>([]);\n\n useEffect(() => {\n subscriptionsRefState.current = subscriptions;\n }, [subscriptions]);\n\n const normalizeProductQueryType = useCallback(\n (type?: ProductTypeInput): ProductQueryType => {\n if (!type || type === 'in-app') {\n return 'in-app';\n }\n return type;\n },\n [],\n );\n\n const canonicalProductType = useCallback(\n (value?: string): ProductQueryType => {\n if (!value) {\n return 'in-app';\n }\n\n const normalized = value.trim().toLowerCase().replace(/[_-]/g, '');\n return normalized === 'subs' ? 'subs' : 'in-app';\n },\n [],\n );\n\n const toPurchaseInput = useCallback(\n (purchase: Purchase): PurchaseInput => ({\n ...purchase,\n ids: purchase.ids ?? undefined,\n }),\n [],\n );\n\n const invokeOnError = useCallback((error: unknown) => {\n if (isMountedRef.current && optionsRef.current?.onError) {\n optionsRef.current.onError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }, []);\n\n /**\n * Retrieve products or subscriptions from the store by SKU.\n *\n * @param params `ProductRequest` — `skus` (string[]) and optional `type`\n * (`'in-app' | 'subs' | 'all'`, defaults to `'in-app'`).\n * @returns Promise that resolves when the request is dispatched; results land in the\n * hook's reactive `products` / `subscriptions` state.\n * @throws When the store rejects the request (empty `skus`, not connected,\n * network/store error). Unknown SKUs are omitted from the result, not thrown.\n *\n * @example\n * ```ts\n * const { fetchProducts, products } = useIAP();\n * await fetchProducts({\n * skus: ['com.app.coins_100', 'com.app.premium'],\n * type: 'in-app',\n * });\n * ```\n *\n * @remarks Promise-based, unlike the event-based `request*` APIs such as `requestPurchase`.\n *\n * @see {@link https://openiap.dev/docs/apis/fetch-products}\n */\n const fetchProductsInternal = useCallback(\n async (params: {\n skus: string[];\n type?: ProductTypeInput;\n }): Promise<void> => {\n try {\n const queryType = normalizeProductQueryType(params.type);\n const request: ProductRequest = {skus: params.skus, type: queryType};\n const result = await fetchProducts(request);\n const items = (result ?? []) as (Product | ProductSubscription)[];\n\n ExpoIapConsole.debug('Fetched products:', items);\n\n if (queryType === 'subs') {\n const subscriptionsResult = items as ProductSubscription[];\n setSubscriptions((prevSubscriptions) =>\n mergeByKey(\n prevSubscriptions,\n subscriptionsResult,\n (subscription) => subscription.id,\n ),\n );\n } else if (queryType === 'in-app') {\n const productsResult = items as Product[];\n setProducts((prevProducts) =>\n mergeByKey(prevProducts, productsResult, (product) => product.id),\n );\n } else {\n const productItems = items.filter(\n (item) => canonicalProductType(item.type as string) === 'in-app',\n ) as Product[];\n\n const subscriptionItems = items.filter(\n (item) => canonicalProductType(item.type as string) === 'subs',\n ) as ProductSubscription[];\n\n setProducts((prevProducts) =>\n mergeByKey(prevProducts, productItems, (product) => product.id),\n );\n\n setSubscriptions((prevSubscriptions) =>\n mergeByKey(\n prevSubscriptions,\n subscriptionItems,\n (subscription) => subscription.id,\n ),\n );\n }\n } catch (error) {\n ExpoIapConsole.error('Error fetching products:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [canonicalProductType, invokeOnError, normalizeProductQueryType],\n );\n\n /**\n * List the user's unfinished purchases: non-consumables, active subscriptions,\n * and pending transactions.\n *\n * @param options Optional `PurchaseOptions`. iOS-only flags:\n * `alsoPublishToEventListenerIOS`, `onlyIncludeActiveItemsIOS`.\n * @returns Promise that resolves when the request is dispatched; results land in the\n * hook's reactive `availablePurchases` state.\n * @throws When the platform query fails.\n *\n * @example\n * ```ts\n * const { getAvailablePurchases, availablePurchases } = useIAP();\n * await getAvailablePurchases();\n * for (const p of availablePurchases) {\n * if (await verifyOnServer(p)) await finishTransaction({ purchase: p, isConsumable: false });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-available-purchases}\n */\n const getAvailablePurchasesInternal = useCallback(\n async (options?: PurchaseOptions): Promise<void> => {\n const read = startRead(availablePurchasesReads.current);\n try {\n const result = await getAvailablePurchases({\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n });\n if (claimPublish(availablePurchasesReads.current, read)) {\n setAvailablePurchases(result);\n }\n } catch (error) {\n ExpoIapConsole.error('Error fetching available purchases:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Get details of all currently active subscriptions.\n *\n * @see {@link https://openiap.dev/docs/apis/get-active-subscriptions}\n */\n const getActiveSubscriptionsInternal = useCallback(\n async (subscriptionIds?: string[]): Promise<void> => {\n const read = startRead(activeSubscriptionsReads.current);\n try {\n const result = await getActiveSubscriptions(subscriptionIds);\n if (claimPublish(activeSubscriptionsReads.current, read)) {\n setActiveSubscriptions(result);\n }\n } catch (error) {\n ExpoIapConsole.error('Error getting active subscriptions:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Check whether the user has any active subscription.\n *\n * @see {@link https://openiap.dev/docs/apis/has-active-subscriptions}\n */\n const hasActiveSubscriptionsInternal = useCallback(\n async (subscriptionIds?: string[]): Promise<boolean> => {\n try {\n return await hasActiveSubscriptions(subscriptionIds);\n } catch (error) {\n ExpoIapConsole.error('Error checking active subscriptions:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Complete a purchase transaction. Call after server-side verification to remove it\n * from the queue.\n *\n * @param args.purchase The `Purchase` to finalize.\n * @param args.isConsumable `true` for consumables (consumes the token so the SKU can be\n * re-bought, e.g. coins); `false` (default) for non-consumables and subscriptions.\n * @returns Promise that resolves once the platform finalizes the transaction.\n * @throws When the platform finalize call fails.\n *\n * @example\n * ```ts\n * // Inside purchaseUpdatedListener:\n * if (await verifyOnServer(purchase)) {\n * await finishTransaction({ purchase, isConsumable: false });\n * }\n * ```\n *\n * @remarks Android purchases must be finalized within 3 days or Google\n * auto-refunds. iOS unfinished transactions replay on every app launch.\n *\n * @see {@link https://openiap.dev/docs/apis/finish-transaction}\n */\n const finishTransaction = useCallback(\n async ({\n purchase,\n isConsumable,\n }: {\n purchase: Purchase;\n isConsumable?: boolean;\n }): Promise<void> => {\n await finishTransactionInternal({\n purchase: toPurchaseInput(purchase),\n isConsumable,\n });\n },\n [toPurchaseInput],\n );\n\n // Replaces the reads a purchase invalidated; a known subscription also\n // refreshes its catalog entry first.\n const refreshAfterPurchase = useCallback(\n async (productId: string) => {\n const generation = initializationGenerationRef.current;\n const isCurrent = (): boolean =>\n isMountedRef.current &&\n initializationGenerationRef.current === generation;\n const ownership = [\n getAvailablePurchasesInternal,\n getActiveSubscriptionsInternal,\n ];\n const refreshes = subscriptionsRefState.current.some(\n (sub) => sub.id === productId,\n )\n ? [\n () => fetchProductsInternal({skus: [productId], type: 'subs'}),\n ...ownership,\n ]\n : ownership;\n for (const refresh of refreshes) {\n if (!isCurrent()) return;\n try {\n await refresh();\n } catch (error) {\n if (isCurrent()) {\n ExpoIapConsole.warn('Failed to refresh after a purchase:', error);\n }\n }\n }\n },\n [\n fetchProductsInternal,\n getAvailablePurchasesInternal,\n getActiveSubscriptionsInternal,\n ],\n );\n\n /**\n * Restore non-consumable and active subscription purchases.\n *\n * @see {@link https://openiap.dev/docs/apis/restore-purchases}\n */\n const restorePurchasesInternal = useCallback(\n async (options?: PurchaseOptions): Promise<void> => {\n try {\n await restorePurchasesNative();\n await optionsRef.current?.purchaseFlow?.recoverPurchases({\n includeFinished: true,\n });\n\n const read = startRead(availablePurchasesReads.current);\n const purchases = await getAvailablePurchases({\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n });\n if (claimPublish(availablePurchasesReads.current, read)) {\n setAvailablePurchases(purchases);\n }\n } catch (error) {\n ExpoIapConsole.warn('Failed to restore purchases:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Verify a purchase against your own backend (returns isValid + raw store metadata).\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase}\n */\n const verifyPurchase = useCallback(async (props: VerifyPurchaseProps) => {\n return verifyPurchaseInternal(props);\n }, []);\n\n /**\n * Verify via a managed provider; `iapkit` (IAPKit) is the only one.\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase-with-provider}\n */\n const verifyPurchaseWithProvider = useCallback(\n async (props: VerifyPurchaseWithProviderProps) => {\n return verifyPurchaseWithProviderInternal(props);\n },\n [],\n );\n\n const buildConnectionConfig = useCallback(():\n | InitConnectionConfig\n | undefined => {\n if (optionsRef.current?.enableBillingProgramAndroid) {\n return {\n enableBillingProgramAndroid:\n optionsRef.current.enableBillingProgramAndroid,\n ...(optionsRef.current.billingChoiceScreenTypeAndroid\n ? {\n billingChoiceScreenTypeAndroid:\n optionsRef.current.billingChoiceScreenTypeAndroid,\n }\n : {}),\n };\n }\n\n return undefined;\n }, []);\n\n const handlePurchaseUpdate = useCallback(\n async (purchase: Purchase): Promise<void> => {\n // Before the callback, which may read again: a read that started before\n // this purchase is stale.\n invalidateReads(availablePurchasesReads.current);\n invalidateReads(activeSubscriptionsReads.current);\n // Deliver first so a store refresh cannot delay finishing the transaction.\n try {\n const callbackResult: unknown =\n optionsRef.current?.onPurchaseSuccess?.(purchase);\n Promise.resolve(callbackResult).catch((error: unknown) => {\n ExpoIapConsole.error('[useIAP] onPurchaseSuccess failed:', error);\n });\n } catch (error) {\n ExpoIapConsole.error('[useIAP] onPurchaseSuccess failed:', error);\n }\n\n // With a purchase flow, its outcome refreshes once the purchase is\n // finished instead.\n if (!optionsRef.current?.purchaseFlow) {\n await refreshAfterPurchase(purchase.productId);\n }\n },\n [refreshAfterPurchase],\n );\n\n // Registers only missing listeners, so reconnect can restore removed ones.\n const registerListeners = useCallback(() => {\n const current = subscriptionsRef.current;\n if (!current.purchaseUpdate) {\n current.purchaseUpdate = purchaseUpdatedListener(\n handlePurchaseUpdate,\n optionsRef.current?.purchaseUpdatedListenerOptions,\n );\n }\n\n if (!current.purchaseError) {\n current.purchaseError = purchaseErrorListener((error: PurchaseError) => {\n if (!connectedRef.current && error.code === ErrorCode.InitConnection) {\n return; // Ignore initialization error before connected\n }\n if (\n error.code !== ErrorCode.AlreadyOwned &&\n !isUserCancelledError(error) &&\n !isRecoverableError(error)\n ) {\n ExpoIapConsole.warn(\n '[useIAP] Purchase error:',\n getUserFriendlyErrorMessage(error),\n );\n }\n optionsRef.current?.onPurchaseError?.(error);\n });\n }\n\n // Android billing callbacks are read at event time, so they may be set after mount.\n if (Platform.OS === 'android' && !current.userChoiceBillingAndroid) {\n current.userChoiceBillingAndroid = userChoiceBillingListenerAndroid(\n (details) => {\n optionsRef.current?.onUserChoiceBillingAndroid?.(details);\n },\n );\n }\n\n if (Platform.OS === 'android' && !current.developerProvidedBillingAndroid) {\n current.developerProvidedBillingAndroid =\n developerProvidedBillingListenerAndroid((details) => {\n optionsRef.current?.onDeveloperProvidedBillingAndroid?.(details);\n });\n }\n\n if (!current.subscriptionBillingIssue) {\n current.subscriptionBillingIssue = subscriptionBillingIssueListener(\n (purchase) => {\n optionsRef.current?.onSubscriptionBillingIssue?.(purchase);\n },\n );\n }\n\n if (Platform.OS === 'ios' && !current.promotedProductIOS) {\n current.promotedProductIOS = promotedProductListenerIOS(\n (product: Product) => {\n setPromotedProductIOS(product);\n optionsRef.current?.onPromotedProductIOS?.(product);\n },\n );\n }\n }, [handlePurchaseUpdate]);\n\n /**\n * Initiate a purchase or subscription flow. The result arrives through\n * `purchaseUpdatedListener` / `purchaseErrorListener`, not the return value.\n *\n * @param props `RequestPurchaseProps`, discriminated by `type`:\n * - `type: 'in-app'` — pass `request.apple.sku` (iOS) and/or `request.google.skus` (Android).\n * - `type: 'subs'` — same shape, plus `request.google.subscriptionOffers: [{ sku, offerToken }]`.\n * @returns Promise that resolves when the request is dispatched; the actual purchase\n * outcome lands in the hook's `onPurchaseSuccess` / `onPurchaseError` callbacks.\n * @throws Synchronous rejection from the store (e.g. `ErrorCode.NotPrepared`, validation failure).\n *\n * @example\n * ```ts\n * await requestPurchase({\n * request: {\n * apple: { sku: 'com.app.premium' },\n * google: { skus: ['com.app.premium'] },\n * },\n * type: 'in-app',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/request-purchase}\n */\n const requestPurchase = useCallback(\n (requestObj: MutationRequestPurchaseArgs) => {\n // A failed hook init removes the purchase listener; restore it before buying.\n if (isMountedRef.current) {\n registerListeners();\n }\n return requestPurchaseInternal(requestObj);\n },\n [registerListeners],\n );\n\n // Purchase-error listening stays on so later retries still report errors.\n const removePurchaseListeners = useCallback(() => {\n subscriptionsRef.current.purchaseUpdate?.remove();\n subscriptionsRef.current.promotedProductIOS?.remove();\n subscriptionsRef.current.purchaseUpdate = undefined;\n subscriptionsRef.current.promotedProductIOS = undefined;\n }, []);\n\n const cleanupListeners = useCallback(() => {\n const current = subscriptionsRef.current;\n current.purchaseUpdate?.remove();\n current.purchaseError?.remove();\n current.promotedProductIOS?.remove();\n current.userChoiceBillingAndroid?.remove();\n current.developerProvidedBillingAndroid?.remove();\n current.subscriptionBillingIssue?.remove();\n subscriptionsRef.current = {};\n }, []);\n\n const initIapWithSubscriptions = useCallback(\n async (generation: number): Promise<void> => {\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n return;\n }\n startedInitializationGenerationRef.current = generation;\n connectionOwnerCount += 1;\n\n // Register listeners before initConnection; events can fire as soon as it connects.\n registerListeners();\n\n const config = buildConnectionConfig();\n\n try {\n const result = await initConnection(config);\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n if (startedInitializationGenerationRef.current === generation) {\n startedInitializationGenerationRef.current = 0;\n releaseConnection();\n }\n return;\n }\n setConnected(result);\n if (!result) {\n ExpoIapConsole.warn(\n '[useIAP] Connection failed, cleaning up listeners...',\n );\n removePurchaseListeners();\n }\n } catch (error) {\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n return;\n }\n invokeOnError(error);\n if (isRefusedRebuild(error)) {\n setConnected(true);\n return;\n }\n ExpoIapConsole.error('initConnection failed:', error);\n removePurchaseListeners();\n }\n },\n [\n buildConnectionConfig,\n registerListeners,\n removePurchaseListeners,\n invokeOnError,\n ],\n );\n\n const reconnect = useCallback(async (): Promise<boolean> => {\n const config = buildConnectionConfig();\n\n try {\n const result = await initConnection(config);\n setConnected(result);\n\n if (result) {\n registerListeners();\n }\n\n return result;\n } catch (error) {\n if (!isRefusedRebuild(error)) {\n ExpoIapConsole.error('[useIAP] reconnect failed:', error);\n }\n invokeOnError(error);\n return false;\n }\n }, [buildConnectionConfig, registerListeners, invokeOnError]);\n\n const purchaseFlow = options?.purchaseFlow;\n useEffect(\n () =>\n purchaseFlow?.subscribe((outcome) => {\n // Reads that started before the purchase settled are stale.\n invalidateReads(availablePurchasesReads.current);\n invalidateReads(activeSubscriptionsReads.current);\n try {\n optionsRef.current?.onPurchaseFlowOutcome?.(outcome);\n } catch (error) {\n ExpoIapConsole.error('[useIAP] onPurchaseFlowOutcome failed:', error);\n }\n void refreshAfterPurchase(outcome.purchase.productId);\n }),\n [purchaseFlow, refreshAfterPurchase],\n );\n\n // Once connected, and again for a new account's flow.\n useEffect(() => {\n if (!connected || !purchaseFlow) return;\n purchaseFlow.recoverPurchases().catch((error: unknown) => {\n ExpoIapConsole.warn('[useIAP] purchase recovery failed:', error);\n invokeOnError(error);\n });\n }, [connected, purchaseFlow, invokeOnError]);\n\n useEffect(() => {\n const generation = ++initializationGenerationRef.current;\n isMountedRef.current = true;\n void Promise.resolve().then(() => initIapWithSubscriptions(generation));\n\n return () => {\n isMountedRef.current = false;\n cleanupListeners();\n if (startedInitializationGenerationRef.current === generation) {\n startedInitializationGenerationRef.current = 0;\n releaseConnection();\n }\n setConnected(false);\n };\n }, [initIapWithSubscriptions, cleanupListeners]);\n\n return {\n connected,\n products,\n subscriptions,\n finishTransaction,\n availablePurchases,\n promotedProductIOS,\n activeSubscriptions,\n getAvailablePurchases: getAvailablePurchasesInternal,\n fetchProducts: fetchProductsInternal,\n requestPurchase,\n verifyPurchase,\n verifyPurchaseWithProvider,\n restorePurchases: restorePurchasesInternal,\n getPromotedProductIOS,\n getActiveSubscriptions: getActiveSubscriptionsInternal,\n hasActiveSubscriptions: hasActiveSubscriptionsInternal,\n reconnect,\n getBillingChoiceInfoAndroid,\n isBillingProgramAvailableAndroid,\n createBillingProgramReportingDetailsAndroid,\n launchExternalLinkAndroid,\n showBillingProgramInformationDialogAndroid,\n showInAppMessagesAndroid,\n // Offer code redemption\n openRedeemOfferCode,\n };\n}\n"]}
1
+ {"version":3,"file":"useIAP.js","sourceRoot":"","sources":["../src/useIAP.ts"],"names":[],"mappings":"AAAA,wBAAwB;AACxB,OAAO,EAAC,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,EAAC,MAAM,OAAO,CAAC;AAChF,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAC;AAGtC,mBAAmB;AACnB,OAAO,EACL,aAAa,EACb,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,gCAAgC,EAChC,uCAAuC,EACvC,gCAAgC,EAChC,qBAAqB,EACrB,iBAAiB,IAAI,yBAAyB,EAC9C,eAAe,IAAI,uBAAuB,EAC1C,aAAa,EACb,cAAc,IAAI,sBAAsB,EACxC,0BAA0B,IAAI,kCAAkC,EAChE,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,GAGpB,MAAM,SAAS,CAAC;AACjB,OAAO,EA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O,GAAG,EAAE;YACV,YAAY,CAAC,OAAO,GAAG,KAAK,CAAC;YAC7B,gBAAgB,EAAE,CAAC;YACnB,IAAI,kCAAkC,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;gBAC9D,kCAAkC,CAAC,OAAO,GAAG,CAAC,CAAC;gBAC/C,iBAAiB,EAAE,CAAC;YACtB,CAAC;YACD,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,wBAAwB,EAAE,gBAAgB,CAAC,CAAC,CAAC;IAEjD,OAAO;QACL,SAAS;QACT,QAAQ;QACR,aAAa;QACb,iBAAiB;QACjB,kBAAkB;QAClB,kBAAkB;QAClB,mBAAmB;QACnB,qBAAqB,EAAE,6BAA6B;QACpD,aAAa,EAAE,qBAAqB;QACpC,eAAe;QACf,cAAc;QACd,0BAA0B;QAC1B,gBAAgB,EAAE,wBAAwB;QAC1C,qBAAqB;QACrB,sBAAsB,EAAE,8BAA8B;QACtD,sBAAsB,EAAE,8BAA8B;QACtD,SAAS;QACT,2BAA2B;QAC3B,gCAAgC;QAChC,2CAA2C;QAC3C,yBAAyB;QACzB,0CAA0C;QAC1C,wBAAwB;QACxB,wBAAwB;QACxB,mBAAmB;KACpB,CAAC;AACJ,CAAC","sourcesContent":["// External dependencies\nimport {useCallback, useEffect, useLayoutEffect, useState, useRef} from 'react';\nimport {Platform} from 'react-native';\nimport type {EventSubscription} from 'expo-modules-core';\n\n// Internal modules\nimport {\n endConnection,\n initConnection,\n purchaseErrorListener,\n purchaseUpdatedListener,\n promotedProductListenerIOS,\n userChoiceBillingListenerAndroid,\n developerProvidedBillingListenerAndroid,\n subscriptionBillingIssueListener,\n getAvailablePurchases,\n finishTransaction as finishTransactionInternal,\n requestPurchase as requestPurchaseInternal,\n fetchProducts,\n verifyPurchase as verifyPurchaseInternal,\n verifyPurchaseWithProvider as verifyPurchaseWithProviderInternal,\n getActiveSubscriptions,\n hasActiveSubscriptions,\n openRedeemOfferCode,\n type ActiveSubscription,\n type ProductTypeInput,\n} from './index';\nimport {ExpoIapConsole} from './utils/debug';\nimport type {PurchaseFlow, PurchaseFlowOutcome} from './purchase-flow-core';\nimport {getPromotedProductIOS} from './modules/ios';\nimport {restorePurchasesNative} from './utils/restorePurchases';\nimport {\n getBillingChoiceInfoAndroid,\n isBillingProgramAvailableAndroid,\n createBillingProgramReportingDetailsAndroid,\n launchExternalLinkAndroid,\n showBillingProgramInformationDialogAndroid,\n showInAppMessagesAndroid,\n} from './modules/android';\n\n// Types\nimport type {\n Product,\n ProductSubscription,\n ProductQueryType,\n ProductRequest,\n BillingChoiceScreenTypeAndroid,\n BillingProgramAndroid,\n DeveloperProvidedBillingDetailsAndroid,\n InitConnectionConfig,\n Purchase,\n MutationRequestPurchaseArgs,\n PurchaseInput,\n PurchaseUpdatedListenerOptions,\n VerifyPurchaseProps,\n VerifyPurchaseResult,\n VerifyPurchaseWithProviderProps,\n VerifyPurchaseWithProviderResult,\n PurchaseOptions,\n MutationField,\n QueryField,\n UserChoiceBillingDetails,\n} from './types';\nimport {ErrorCode} from './types';\nimport type {PurchaseError} from './utils/errorMapping';\nimport {\n getUserFriendlyErrorMessage,\n isUserCancelledError,\n isRecoverableError,\n} from './utils/errorMapping';\n\n// Hooks share one native connection; the last mounted hook ends it.\nlet connectionOwnerCount = 0;\n\nconst releaseConnection = (): void => {\n connectionOwnerCount = Math.max(0, connectionOwnerCount - 1);\n if (connectionOwnerCount > 0) return;\n endConnection().catch((error: unknown) => {\n ExpoIapConsole.warn('[useIAP] endConnection failed:', error);\n });\n};\n\ntype UseIap = {\n connected: boolean;\n products: Product[];\n subscriptions: ProductSubscription[];\n availablePurchases: Purchase[];\n promotedProductIOS?: Product;\n activeSubscriptions: ActiveSubscription[];\n finishTransaction: ({\n purchase,\n isConsumable,\n }: {\n purchase: Purchase;\n isConsumable?: boolean;\n }) => Promise<void>;\n getAvailablePurchases: (options?: PurchaseOptions) => Promise<void>;\n fetchProducts: (params: {\n skus: string[];\n type?: ProductTypeInput;\n }) => Promise<void>;\n\n requestPurchase: (\n params: MutationRequestPurchaseArgs,\n ) => ReturnType<typeof requestPurchaseInternal>;\n verifyPurchase: (props: VerifyPurchaseProps) => Promise<VerifyPurchaseResult>;\n verifyPurchaseWithProvider: (\n props: VerifyPurchaseWithProviderProps,\n ) => Promise<VerifyPurchaseWithProviderResult>;\n restorePurchases: (options?: PurchaseOptions) => Promise<void>;\n getPromotedProductIOS: () => Promise<Product | null>;\n getActiveSubscriptions: (subscriptionIds?: string[]) => Promise<void>;\n hasActiveSubscriptions: (subscriptionIds?: string[]) => Promise<boolean>;\n /**\n * Manually retry the store connection.\n * Useful when the initial auto-connect fails (e.g., Play Store not ready at mount time).\n * Updates the `connected` state on success.\n */\n reconnect: () => Promise<boolean>;\n getBillingChoiceInfoAndroid: QueryField<'getBillingChoiceInfoAndroid'>;\n isBillingProgramAvailableAndroid: MutationField<'isBillingProgramAvailableAndroid'>;\n createBillingProgramReportingDetailsAndroid: MutationField<'createBillingProgramReportingDetailsAndroid'>;\n launchExternalLinkAndroid: MutationField<'launchExternalLinkAndroid'>;\n showBillingProgramInformationDialogAndroid: MutationField<'showBillingProgramInformationDialogAndroid'>;\n showInAppMessagesAndroid: MutationField<'showInAppMessagesAndroid'>;\n openRedeemOfferCode: MutationField<'openRedeemOfferCode'>;\n};\n\nexport interface UseIAPOptions {\n onPurchaseSuccess?: (purchase: Purchase) => void;\n /**\n * The app's flow from `createPurchaseFlow`, which confirms and finishes\n * every purchase. The hook recovers unfinished purchases once connected or\n * when the flow changes, reports outcomes, and refreshes ownership after\n * each. Leave finishing out of `onPurchaseSuccess` when this is set.\n */\n purchaseFlow?: PurchaseFlow<Purchase>;\n /** Each purchase's outcome from `purchaseFlow`. */\n onPurchaseFlowOutcome?: (outcome: PurchaseFlowOutcome<Purchase>) => void;\n onPurchaseError?: (error: PurchaseError) => void;\n /**\n * Options for the purchase success listener. iOS defaults to suppressing\n * StoreKit replay events for the same transaction ID; set\n * `dedupeTransactionIOS` to false only for diagnostics.\n */\n purchaseUpdatedListenerOptions?: PurchaseUpdatedListenerOptions | null;\n /**\n * Called when a hook method such as fetchProducts, getAvailablePurchases,\n * getActiveSubscriptions or restorePurchases fails.\n */\n onError?: (error: Error) => void;\n onPromotedProductIOS?: (product: Product) => void;\n onUserChoiceBillingAndroid?: (details: UserChoiceBillingDetails) => void;\n /**\n * Fires when the user selects developer-provided billing in an External\n * Payments or Google-rendered Billing Choice flow.\n */\n onDeveloperProvidedBillingAndroid?: (\n details: DeveloperProvidedBillingDetailsAndroid,\n ) => void;\n /** Fires when a subscription enters a billing-issue state. */\n onSubscriptionBillingIssue?: (purchase: Purchase) => void;\n /**\n * Enable a specific billing program for Android (8.2.0+).\n * Use 'external-payments' for Developer Provided Billing (Japan only, 8.3.0+).\n * Use 'user-choice-billing' for User Choice Billing (7.0+).\n * Use 'billing-choice' for Billing Choice (9.1.0+).\n */\n enableBillingProgramAndroid?: BillingProgramAndroid;\n /**\n * Select who renders the Billing Choice screen (9.1.0+). Must match the\n * choiceScreenType returned by isBillingProgramAvailableAndroid.\n */\n billingChoiceScreenTypeAndroid?: BillingChoiceScreenTypeAndroid;\n}\n\n// The store refused a new billing program because a purchase is in progress;\n// the live connection stays up.\nconst isRefusedRebuild = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === ErrorCode.DeveloperError;\n\n// A fetched item replaces the one it updates, keeping the list's order.\nfunction mergeByKey<T>(\n existingItems: T[],\n newItems: T[],\n getKey: (item: T) => string,\n): T[] {\n const merged = new Map(\n existingItems.map((item) => [getKey(item), item] as const),\n );\n newItems.forEach((item) => merged.set(getKey(item), item));\n return Array.from(merged.values());\n}\n\n// Store reads can resolve out of order. A result publishes only when no newer\n// read has published, so a failed newer read lets an older result through,\n// and a purchase makes every read that started before it stale.\ninterface ReadOrder {\n started: number;\n published: number;\n}\nconst startRead = (order: ReadOrder): number => ++order.started;\nconst claimPublish = (order: ReadOrder, read: number): boolean => {\n if (read <= order.published) return false;\n order.published = read;\n return true;\n};\nconst invalidateReads = (order: ReadOrder): void => {\n order.published = ++order.started;\n};\n\n/**\n * React Hook for managing In-App Purchases. Mounted hooks share one store\n * connection, which ends when the last of them unmounts.\n * See documentation at https://openiap.dev/docs/setup/expo#useIAP-hook\n */\nexport function useIAP(options?: UseIAPOptions): UseIap {\n const [connected, setConnected] = useState<boolean>(false);\n const [products, setProducts] = useState<Product[]>([]);\n const [subscriptions, setSubscriptions] = useState<ProductSubscription[]>([]);\n\n const [availablePurchases, setAvailablePurchases] = useState<Purchase[]>([]);\n const [promotedProductIOS, setPromotedProductIOS] = useState<Product>();\n const [activeSubscriptions, setActiveSubscriptions] = useState<\n ActiveSubscription[]\n >([]);\n\n const optionsRef = useRef<UseIAPOptions | undefined>(options);\n const connectedRef = useRef<boolean>(false);\n const isMountedRef = useRef<boolean>(false);\n const initializationGenerationRef = useRef(0);\n const startedInitializationGenerationRef = useRef(0);\n const availablePurchasesReads = useRef<ReadOrder>({started: 0, published: 0});\n const activeSubscriptionsReads = useRef<ReadOrder>({\n started: 0,\n published: 0,\n });\n\n // Before any effect runs, so a purchase never reaches a stale callback.\n useLayoutEffect(() => {\n optionsRef.current = options;\n }, [options]);\n\n useEffect(() => {\n connectedRef.current = connected;\n }, [connected]);\n\n const subscriptionsRef = useRef<{\n purchaseUpdate?: EventSubscription;\n purchaseError?: EventSubscription;\n promotedProductIOS?: EventSubscription;\n userChoiceBillingAndroid?: EventSubscription;\n developerProvidedBillingAndroid?: EventSubscription;\n subscriptionBillingIssue?: EventSubscription;\n }>({});\n\n const subscriptionsRefState = useRef<ProductSubscription[]>([]);\n\n useEffect(() => {\n subscriptionsRefState.current = subscriptions;\n }, [subscriptions]);\n\n const normalizeProductQueryType = useCallback(\n (type?: ProductTypeInput): ProductQueryType => {\n if (!type || type === 'in-app') {\n return 'in-app';\n }\n return type;\n },\n [],\n );\n\n const canonicalProductType = useCallback(\n (value?: string): ProductQueryType => {\n if (!value) {\n return 'in-app';\n }\n\n const normalized = value.trim().toLowerCase().replace(/[_-]/g, '');\n return normalized === 'subs' ? 'subs' : 'in-app';\n },\n [],\n );\n\n const toPurchaseInput = useCallback(\n (purchase: Purchase): PurchaseInput => ({\n ...purchase,\n ids: purchase.ids ?? undefined,\n }),\n [],\n );\n\n const invokeOnError = useCallback((error: unknown) => {\n if (isMountedRef.current && optionsRef.current?.onError) {\n optionsRef.current.onError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }, []);\n\n /**\n * Retrieve products or subscriptions from the store by SKU.\n *\n * @param params `ProductRequest` — `skus` (string[]) and optional `type`\n * (`'in-app' | 'subs' | 'all'`, defaults to `'in-app'`).\n * @returns Promise that resolves when the request is dispatched; results land in the\n * hook's reactive `products` / `subscriptions` state.\n * @throws When the store rejects the request (empty `skus`, not connected,\n * network/store error). Unknown SKUs are omitted from the result, not thrown.\n *\n * @example\n * ```ts\n * const { fetchProducts, products } = useIAP();\n * await fetchProducts({\n * skus: ['com.app.coins_100', 'com.app.premium'],\n * type: 'in-app',\n * });\n * ```\n *\n * @remarks Promise-based, unlike the event-based `request*` APIs such as `requestPurchase`.\n *\n * @see {@link https://openiap.dev/docs/apis/fetch-products}\n */\n const fetchProductsInternal = useCallback(\n async (params: {\n skus: string[];\n type?: ProductTypeInput;\n }): Promise<void> => {\n try {\n const queryType = normalizeProductQueryType(params.type);\n const request: ProductRequest = {skus: params.skus, type: queryType};\n const result = await fetchProducts(request);\n const items = (result ?? []) as (Product | ProductSubscription)[];\n\n ExpoIapConsole.debug('Fetched products:', items);\n\n if (queryType === 'subs') {\n const subscriptionsResult = items as ProductSubscription[];\n setSubscriptions((prevSubscriptions) =>\n mergeByKey(\n prevSubscriptions,\n subscriptionsResult,\n (subscription) => subscription.id,\n ),\n );\n } else if (queryType === 'in-app') {\n const productsResult = items as Product[];\n setProducts((prevProducts) =>\n mergeByKey(prevProducts, productsResult, (product) => product.id),\n );\n } else {\n const productItems = items.filter(\n (item) => canonicalProductType(item.type as string) === 'in-app',\n ) as Product[];\n\n const subscriptionItems = items.filter(\n (item) => canonicalProductType(item.type as string) === 'subs',\n ) as ProductSubscription[];\n\n setProducts((prevProducts) =>\n mergeByKey(prevProducts, productItems, (product) => product.id),\n );\n\n setSubscriptions((prevSubscriptions) =>\n mergeByKey(\n prevSubscriptions,\n subscriptionItems,\n (subscription) => subscription.id,\n ),\n );\n }\n } catch (error) {\n ExpoIapConsole.error('Error fetching products:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [canonicalProductType, invokeOnError, normalizeProductQueryType],\n );\n\n /**\n * List the user's unfinished purchases: non-consumables, active subscriptions,\n * and pending transactions.\n *\n * @param options Optional `PurchaseOptions`. iOS-only flags:\n * `alsoPublishToEventListenerIOS`, `onlyIncludeActiveItemsIOS`.\n * @returns Promise that resolves when the request is dispatched; results land in the\n * hook's reactive `availablePurchases` state.\n * @throws When the platform query fails.\n *\n * @example\n * ```ts\n * const { getAvailablePurchases, availablePurchases } = useIAP();\n * await getAvailablePurchases();\n * for (const p of availablePurchases) {\n * if (await verifyOnServer(p)) await finishTransaction({ purchase: p, isConsumable: false });\n * }\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/get-available-purchases}\n */\n const getAvailablePurchasesInternal = useCallback(\n async (options?: PurchaseOptions): Promise<void> => {\n const read = startRead(availablePurchasesReads.current);\n try {\n const result = await getAvailablePurchases({\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n });\n if (claimPublish(availablePurchasesReads.current, read)) {\n setAvailablePurchases(result);\n }\n } catch (error) {\n ExpoIapConsole.error('Error fetching available purchases:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Get details of all currently active subscriptions.\n *\n * @see {@link https://openiap.dev/docs/apis/get-active-subscriptions}\n */\n const getActiveSubscriptionsInternal = useCallback(\n async (subscriptionIds?: string[]): Promise<void> => {\n const read = startRead(activeSubscriptionsReads.current);\n try {\n const result = await getActiveSubscriptions(subscriptionIds);\n if (claimPublish(activeSubscriptionsReads.current, read)) {\n setActiveSubscriptions(result);\n }\n } catch (error) {\n ExpoIapConsole.error('Error getting active subscriptions:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Check whether the user has any active subscription.\n *\n * @see {@link https://openiap.dev/docs/apis/has-active-subscriptions}\n */\n const hasActiveSubscriptionsInternal = useCallback(\n async (subscriptionIds?: string[]): Promise<boolean> => {\n try {\n return await hasActiveSubscriptions(subscriptionIds);\n } catch (error) {\n ExpoIapConsole.error('Error checking active subscriptions:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Complete a purchase transaction. Call after server-side verification to remove it\n * from the queue.\n *\n * @param args.purchase The `Purchase` to finalize.\n * @param args.isConsumable `true` for consumables (consumes the token so the SKU can be\n * re-bought, e.g. coins); `false` (default) for non-consumables and subscriptions.\n * @returns Promise that resolves once the platform finalizes the transaction.\n * @throws When the platform finalize call fails.\n *\n * @example\n * ```ts\n * // Inside purchaseUpdatedListener:\n * if (await verifyOnServer(purchase)) {\n * await finishTransaction({ purchase, isConsumable: false });\n * }\n * ```\n *\n * @remarks Android purchases must be finalized within 3 days or Google\n * auto-refunds. iOS unfinished transactions replay on every app launch.\n *\n * @see {@link https://openiap.dev/docs/apis/finish-transaction}\n */\n const finishTransaction = useCallback(\n async ({\n purchase,\n isConsumable,\n }: {\n purchase: Purchase;\n isConsumable?: boolean;\n }): Promise<void> => {\n await finishTransactionInternal({\n purchase: toPurchaseInput(purchase),\n isConsumable,\n });\n },\n [toPurchaseInput],\n );\n\n // Replaces the reads a purchase invalidated; a known subscription also\n // refreshes its catalog entry first.\n const refreshAfterPurchase = useCallback(\n async (productId: string) => {\n const generation = initializationGenerationRef.current;\n const isCurrent = (): boolean =>\n isMountedRef.current &&\n initializationGenerationRef.current === generation;\n const ownership = [\n getAvailablePurchasesInternal,\n getActiveSubscriptionsInternal,\n ];\n const refreshes = subscriptionsRefState.current.some(\n (sub) => sub.id === productId,\n )\n ? [\n () => fetchProductsInternal({skus: [productId], type: 'subs'}),\n ...ownership,\n ]\n : ownership;\n for (const refresh of refreshes) {\n if (!isCurrent()) return;\n try {\n await refresh();\n } catch (error) {\n if (isCurrent()) {\n ExpoIapConsole.warn('Failed to refresh after a purchase:', error);\n }\n }\n }\n },\n [\n fetchProductsInternal,\n getAvailablePurchasesInternal,\n getActiveSubscriptionsInternal,\n ],\n );\n\n /**\n * Restore non-consumable and active subscription purchases. With\n * `purchaseFlow`, confirms every owned purchase through the flow instead of\n * the provider's restore, so iOS asks for no App Store sign-in, and rejects\n * when a confirmation fails.\n *\n * @see {@link https://openiap.dev/docs/apis/restore-purchases}\n */\n const restorePurchasesInternal = useCallback(\n async (options?: PurchaseOptions): Promise<void> => {\n try {\n const flow = optionsRef.current?.purchaseFlow;\n // The provider's restore adds an iOS sign-in and Horizon redeliveries;\n // the flow reads the store's history itself.\n if (flow) {\n const outcomes = await flow.recoverPurchases({includeFinished: true});\n // A failed confirmation fails the restore; its purchase stays\n // unfinished, so the next restore retries it.\n for (const {status} of outcomes) {\n if (status.status === 'failed') throw status.error;\n }\n } else {\n await restorePurchasesNative();\n }\n\n const read = startRead(availablePurchasesReads.current);\n const purchases = await getAvailablePurchases({\n alsoPublishToEventListenerIOS:\n options?.alsoPublishToEventListenerIOS ?? false,\n onlyIncludeActiveItemsIOS: options?.onlyIncludeActiveItemsIOS ?? true,\n includeSuspendedAndroid: options?.includeSuspendedAndroid ?? false,\n });\n if (claimPublish(availablePurchasesReads.current, read)) {\n setAvailablePurchases(purchases);\n }\n } catch (error) {\n ExpoIapConsole.warn('Failed to restore purchases:', error);\n invokeOnError(error);\n throw error;\n }\n },\n [invokeOnError],\n );\n\n /**\n * Verify a purchase against your own backend (returns isValid + raw store metadata).\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase}\n */\n const verifyPurchase = useCallback(async (props: VerifyPurchaseProps) => {\n return verifyPurchaseInternal(props);\n }, []);\n\n /**\n * Verify via a managed provider; `iapkit` (IAPKit) is the only one.\n *\n * @see {@link https://openiap.dev/docs/features/validation#verify-purchase-with-provider}\n */\n const verifyPurchaseWithProvider = useCallback(\n async (props: VerifyPurchaseWithProviderProps) => {\n return verifyPurchaseWithProviderInternal(props);\n },\n [],\n );\n\n const buildConnectionConfig = useCallback(():\n | InitConnectionConfig\n | undefined => {\n if (optionsRef.current?.enableBillingProgramAndroid) {\n return {\n enableBillingProgramAndroid:\n optionsRef.current.enableBillingProgramAndroid,\n ...(optionsRef.current.billingChoiceScreenTypeAndroid\n ? {\n billingChoiceScreenTypeAndroid:\n optionsRef.current.billingChoiceScreenTypeAndroid,\n }\n : {}),\n };\n }\n\n return undefined;\n }, []);\n\n const handlePurchaseUpdate = useCallback(\n async (purchase: Purchase): Promise<void> => {\n // Before the callback, which may read again: a read that started before\n // this purchase is stale.\n invalidateReads(availablePurchasesReads.current);\n invalidateReads(activeSubscriptionsReads.current);\n // Deliver first so a store refresh cannot delay finishing the transaction.\n try {\n const callbackResult: unknown =\n optionsRef.current?.onPurchaseSuccess?.(purchase);\n Promise.resolve(callbackResult).catch((error: unknown) => {\n ExpoIapConsole.error('[useIAP] onPurchaseSuccess failed:', error);\n });\n } catch (error) {\n ExpoIapConsole.error('[useIAP] onPurchaseSuccess failed:', error);\n }\n\n // With a purchase flow, its outcome refreshes once the purchase is\n // finished instead.\n if (!optionsRef.current?.purchaseFlow) {\n await refreshAfterPurchase(purchase.productId);\n }\n },\n [refreshAfterPurchase],\n );\n\n // Registers only missing listeners, so reconnect can restore removed ones.\n const registerListeners = useCallback(() => {\n const current = subscriptionsRef.current;\n if (!current.purchaseUpdate) {\n current.purchaseUpdate = purchaseUpdatedListener(\n handlePurchaseUpdate,\n optionsRef.current?.purchaseUpdatedListenerOptions,\n );\n }\n\n if (!current.purchaseError) {\n current.purchaseError = purchaseErrorListener((error: PurchaseError) => {\n if (!connectedRef.current && error.code === ErrorCode.InitConnection) {\n return; // Ignore initialization error before connected\n }\n if (\n error.code !== ErrorCode.AlreadyOwned &&\n !isUserCancelledError(error) &&\n !isRecoverableError(error)\n ) {\n ExpoIapConsole.warn(\n '[useIAP] Purchase error:',\n getUserFriendlyErrorMessage(error),\n );\n }\n optionsRef.current?.onPurchaseError?.(error);\n });\n }\n\n // Android billing callbacks are read at event time, so they may be set after mount.\n if (Platform.OS === 'android' && !current.userChoiceBillingAndroid) {\n current.userChoiceBillingAndroid = userChoiceBillingListenerAndroid(\n (details) => {\n optionsRef.current?.onUserChoiceBillingAndroid?.(details);\n },\n );\n }\n\n if (Platform.OS === 'android' && !current.developerProvidedBillingAndroid) {\n current.developerProvidedBillingAndroid =\n developerProvidedBillingListenerAndroid((details) => {\n optionsRef.current?.onDeveloperProvidedBillingAndroid?.(details);\n });\n }\n\n if (!current.subscriptionBillingIssue) {\n current.subscriptionBillingIssue = subscriptionBillingIssueListener(\n (purchase) => {\n optionsRef.current?.onSubscriptionBillingIssue?.(purchase);\n },\n );\n }\n\n if (Platform.OS === 'ios' && !current.promotedProductIOS) {\n current.promotedProductIOS = promotedProductListenerIOS(\n (product: Product) => {\n setPromotedProductIOS(product);\n optionsRef.current?.onPromotedProductIOS?.(product);\n },\n );\n }\n }, [handlePurchaseUpdate]);\n\n /**\n * Initiate a purchase or subscription flow. The result arrives through\n * `purchaseUpdatedListener` / `purchaseErrorListener`, not the return value.\n *\n * @param props `RequestPurchaseProps`, discriminated by `type`:\n * - `type: 'in-app'` — pass `request.apple.sku` (iOS) and/or `request.google.skus` (Android).\n * - `type: 'subs'` — same shape, plus `request.google.subscriptionOffers: [{ sku, offerToken }]`.\n * @returns Promise that resolves when the request is dispatched; the actual purchase\n * outcome lands in the hook's `onPurchaseSuccess` / `onPurchaseError` callbacks.\n * @throws Synchronous rejection from the store (e.g. `ErrorCode.NotPrepared`, validation failure).\n *\n * @example\n * ```ts\n * await requestPurchase({\n * request: {\n * apple: { sku: 'com.app.premium' },\n * google: { skus: ['com.app.premium'] },\n * },\n * type: 'in-app',\n * });\n * ```\n *\n * @see {@link https://openiap.dev/docs/apis/request-purchase}\n */\n const requestPurchase = useCallback(\n (requestObj: MutationRequestPurchaseArgs) => {\n // A failed hook init removes the purchase listener; restore it before buying.\n if (isMountedRef.current) {\n registerListeners();\n }\n return requestPurchaseInternal(requestObj);\n },\n [registerListeners],\n );\n\n // Purchase-error listening stays on so later retries still report errors.\n const removePurchaseListeners = useCallback(() => {\n subscriptionsRef.current.purchaseUpdate?.remove();\n subscriptionsRef.current.promotedProductIOS?.remove();\n subscriptionsRef.current.purchaseUpdate = undefined;\n subscriptionsRef.current.promotedProductIOS = undefined;\n }, []);\n\n const cleanupListeners = useCallback(() => {\n const current = subscriptionsRef.current;\n current.purchaseUpdate?.remove();\n current.purchaseError?.remove();\n current.promotedProductIOS?.remove();\n current.userChoiceBillingAndroid?.remove();\n current.developerProvidedBillingAndroid?.remove();\n current.subscriptionBillingIssue?.remove();\n subscriptionsRef.current = {};\n }, []);\n\n const initIapWithSubscriptions = useCallback(\n async (generation: number): Promise<void> => {\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n return;\n }\n startedInitializationGenerationRef.current = generation;\n connectionOwnerCount += 1;\n\n // Register listeners before initConnection; events can fire as soon as it connects.\n registerListeners();\n\n const config = buildConnectionConfig();\n\n try {\n const result = await initConnection(config);\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n if (startedInitializationGenerationRef.current === generation) {\n startedInitializationGenerationRef.current = 0;\n releaseConnection();\n }\n return;\n }\n setConnected(result);\n if (!result) {\n ExpoIapConsole.warn(\n '[useIAP] Connection failed, cleaning up listeners...',\n );\n removePurchaseListeners();\n }\n } catch (error) {\n if (\n !isMountedRef.current ||\n initializationGenerationRef.current !== generation\n ) {\n return;\n }\n invokeOnError(error);\n if (isRefusedRebuild(error)) {\n setConnected(true);\n return;\n }\n ExpoIapConsole.error('initConnection failed:', error);\n removePurchaseListeners();\n }\n },\n [\n buildConnectionConfig,\n registerListeners,\n removePurchaseListeners,\n invokeOnError,\n ],\n );\n\n const reconnect = useCallback(async (): Promise<boolean> => {\n const config = buildConnectionConfig();\n\n try {\n const result = await initConnection(config);\n setConnected(result);\n\n if (result) {\n registerListeners();\n }\n\n return result;\n } catch (error) {\n if (!isRefusedRebuild(error)) {\n ExpoIapConsole.error('[useIAP] reconnect failed:', error);\n }\n invokeOnError(error);\n return false;\n }\n }, [buildConnectionConfig, registerListeners, invokeOnError]);\n\n const purchaseFlow = options?.purchaseFlow;\n useEffect(\n () =>\n purchaseFlow?.subscribe((outcome) => {\n // Reads that started before the purchase settled are stale.\n invalidateReads(availablePurchasesReads.current);\n invalidateReads(activeSubscriptionsReads.current);\n try {\n optionsRef.current?.onPurchaseFlowOutcome?.(outcome);\n } catch (error) {\n ExpoIapConsole.error('[useIAP] onPurchaseFlowOutcome failed:', error);\n }\n void refreshAfterPurchase(outcome.purchase.productId);\n }),\n [purchaseFlow, refreshAfterPurchase],\n );\n\n // Once connected, and again for a new account's flow.\n useEffect(() => {\n if (!connected || !purchaseFlow) return;\n purchaseFlow.recoverPurchases().catch((error: unknown) => {\n ExpoIapConsole.warn('[useIAP] purchase recovery failed:', error);\n invokeOnError(error);\n });\n }, [connected, purchaseFlow, invokeOnError]);\n\n useEffect(() => {\n const generation = ++initializationGenerationRef.current;\n isMountedRef.current = true;\n void Promise.resolve().then(() => initIapWithSubscriptions(generation));\n\n return () => {\n isMountedRef.current = false;\n cleanupListeners();\n if (startedInitializationGenerationRef.current === generation) {\n startedInitializationGenerationRef.current = 0;\n releaseConnection();\n }\n setConnected(false);\n };\n }, [initIapWithSubscriptions, cleanupListeners]);\n\n return {\n connected,\n products,\n subscriptions,\n finishTransaction,\n availablePurchases,\n promotedProductIOS,\n activeSubscriptions,\n getAvailablePurchases: getAvailablePurchasesInternal,\n fetchProducts: fetchProductsInternal,\n requestPurchase,\n verifyPurchase,\n verifyPurchaseWithProvider,\n restorePurchases: restorePurchasesInternal,\n getPromotedProductIOS,\n getActiveSubscriptions: getActiveSubscriptionsInternal,\n hasActiveSubscriptions: hasActiveSubscriptionsInternal,\n reconnect,\n getBillingChoiceInfoAndroid,\n isBillingProgramAvailableAndroid,\n createBillingProgramReportingDetailsAndroid,\n launchExternalLinkAndroid,\n showBillingProgramInformationDialogAndroid,\n showInAppMessagesAndroid,\n // Offer code redemption\n openRedeemOfferCode,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
- "clientProtocol": "1.3.2",
3
- "google": "4.0.9",
4
- "apple": "4.0.8",
2
+ "clientProtocol": "1.3.3",
3
+ "google": "4.0.10",
4
+ "apple": "4.0.9",
5
5
  "plugin": "0.1.1"
6
6
  }
package/osv-scanner.toml CHANGED
@@ -1,14 +1,14 @@
1
1
  [[IgnoredVulns]]
2
2
  id = "GHSA-gcqx-w48m-w2h4"
3
- ignoreUntil = 2026-11-04
4
- reason = "No patched deepmerge release exists. This lock reaches it only through Jest, Expo configuration, or React Native/Kepler CLI configuration used for trusted local builds and tests; mobile entry points and the published SDK runtime do not import those tools. Do not load untrusted project configuration. Revisit the upstream fix before expiry: https://github.com/advisories/GHSA-gcqx-w48m-w2h4."
3
+ ignoreUntil = 2026-12-04
4
+ reason = "No patched deepmerge release exists. This lock reaches it only through Jest, Expo configuration, or React Native/Kepler CLI configuration used for trusted local builds and tests; mobile entry points and the published SDK runtime do not import those tools. Do not load untrusted project configuration. Revisit the upstream fix before expiry: https://github.com/advisories/GHSA-gcqx-w48m-w2h4. Rechecked 2026-11-04: still no patched release."
5
5
 
6
6
  [[IgnoredVulns]]
7
7
  id = "GHSA-3g3m-2fjr-6pw4"
8
- ignoreUntil = 2026-11-04
9
- reason = "The fix is glob 14.0.2, outside Expo 57 dependency ranges. Expo uses glob for trusted local project discovery and builds, including early cancellation after the first match; cancellation must not be treated as an enforced traversal budget. The published expo-iap mobile entry points do not import glob. Do not run this tooling on untrusted directory trees or expose it as a public request handler. Recheck compatible upstream upgrades before expiry: https://github.com/advisories/GHSA-3g3m-2fjr-6pw4."
8
+ ignoreUntil = 2026-12-04
9
+ reason = "The fix is glob 14.0.2, outside Expo 57 dependency ranges. Expo uses glob for trusted local project discovery and builds, including early cancellation after the first match; cancellation must not be treated as an enforced traversal budget. The published expo-iap mobile entry points do not import glob. Do not run this tooling on untrusted directory trees or expose it as a public request handler. Recheck compatible upstream upgrades before expiry: https://github.com/advisories/GHSA-3g3m-2fjr-6pw4. Rechecked 2026-11-04: still no fix inside these dependency ranges."
10
10
 
11
11
  [[IgnoredVulns]]
12
12
  id = "GHSA-g3hv-75wg-m249"
13
- ignoreUntil = 2026-11-04
14
- reason = "The fix is minimatch 11.0.1, outside the Expo 57, Jest and ESLint dependency ranges. These copies serve local project discovery, fingerprinting, lint and coverage; the published expo-iap mobile entry points do not import them. Patterns come from the trusted checkout and build configuration; do not load untrusted project patterns or expose this tooling as a public request handler. Recheck compatible upstream upgrades before expiry: https://github.com/advisories/GHSA-g3hv-75wg-m249."
13
+ ignoreUntil = 2026-12-04
14
+ reason = "The fix is minimatch 11.0.1, outside the Expo 57, Jest and ESLint dependency ranges. These copies serve local project discovery, fingerprinting, lint and coverage; the published expo-iap mobile entry points do not import them. Patterns come from the trusted checkout and build configuration; do not load untrusted project patterns or expose this tooling as a public request handler. Recheck compatible upstream upgrades before expiry: https://github.com/advisories/GHSA-g3hv-75wg-m249. Rechecked 2026-11-04: still no fix inside these dependency ranges."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-iap",
3
- "version": "6.4.2",
3
+ "version": "6.4.3",
4
4
  "description": "In App Purchase module in Expo",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
package/src/index.ts CHANGED
@@ -1509,8 +1509,8 @@ export function confirmWithIapkit(
1509
1509
 
1510
1510
  /**
1511
1511
  * Confirms App Store purchases on the device, for apps with neither a backend
1512
- * nor IAPKit: StoreKit must still list the transaction as unfinished and
1513
- * valid. Credit consumables in `grant`.
1512
+ * nor IAPKit: StoreKit must list the transaction as unfinished, or for a
1513
+ * restore in its verified history, and valid. Credit consumables in `grant`.
1514
1514
  */
1515
1515
  export function confirmOnDeviceIOS(
1516
1516
  options: {
@@ -1523,7 +1523,11 @@ export function confirmOnDeviceIOS(
1523
1523
  ): PurchaseFlowOptions<Purchase>['confirmWithBackend'] {
1524
1524
  return createDeviceConfirmationIOS<Purchase>(
1525
1525
  () => getPendingTransactionsIOS(),
1526
- options,
1526
+ {
1527
+ ...options,
1528
+ getTransactionHistoryIOS: () =>
1529
+ getAvailablePurchases({onlyIncludeActiveItemsIOS: false}),
1530
+ },
1527
1531
  );
1528
1532
  }
1529
1533
 
@@ -66,6 +66,8 @@ export interface IapkitVerificationResult {
66
66
  }
67
67
 
68
68
  const IAPKIT_UNKNOWN_RETRY_MS = 30_000;
69
+ // An expired App Store receipt may still be in billing grace; check it again.
70
+ const DEVICE_EXPIRED_RETRY_MS = 30_000;
69
71
 
70
72
  /**
71
73
  * @internal Use the SDK's confirmWithIapkit.
@@ -100,14 +102,22 @@ export function createIapkitConfirmation<P extends PurchaseFlowPurchase>(
100
102
  * @internal Use the SDK's confirmOnDeviceIOS.
101
103
  * The SDK's `confirmOnDeviceIOS`, given its `getPendingTransactionsIOS`, for an
102
104
  * app with neither a backend nor IAPKit. StoreKit verified the transaction if
103
- * it is still unfinished, unrevoked, not upgraded, unexpired, and from the
104
- * purchase's environment; `grant` then runs before the flow finishes it.
105
+ * it lists it as unfinished, or, for a purchase the flow already finished, in
106
+ * `getTransactionHistoryIOS`, from the purchase's environment. A revoked or
107
+ * upgraded one is `invalid`, and an expired one `verification_delayed`, since
108
+ * billing grace can still cover it; `grant` runs before an unfinished one is
109
+ * finished, and again for a finished non-consumable a restore reads.
105
110
  */
106
111
  export function createDeviceConfirmationIOS<P extends PurchaseFlowPurchase>(
107
112
  getPendingTransactionsIOS: () => Promise<P[]>,
108
113
  options: {
109
114
  /** Required for consumables; credit each purchase.id only once. */
110
115
  grant?: (purchase: P, context: { isConsumable: boolean }) => Promise<void>;
116
+ /**
117
+ * StoreKit's verified history, such as `getAvailablePurchases` with
118
+ * `onlyIncludeActiveItemsIOS: false`; without it a finished purchase throws.
119
+ */
120
+ getTransactionHistoryIOS?: () => Promise<P[]>;
111
121
  } = {},
112
122
  ): PurchaseFlowOptions<P>["confirmWithBackend"] {
113
123
  return async (purchase, context) => {
@@ -121,29 +131,42 @@ export function createDeviceConfirmationIOS<P extends PurchaseFlowPurchase>(
121
131
  `Device confirmation covers App Store purchases, not ${purchase.storeId ?? purchase.store}`,
122
132
  );
123
133
  }
124
- const pending = await getPendingTransactionsIOS();
125
- // After the query: a transaction can expire while StoreKit answers.
126
- const now = Date.now();
127
- const verified = pending.some(
128
- (candidate) =>
129
- candidate.store === "apple" &&
130
- purchase.id !== "" &&
131
- candidate.id === purchase.id &&
132
- candidate.productId === purchase.productId &&
133
- candidate.revocationDateIOS == null &&
134
- candidate.isUpgradedIOS !== true &&
135
- (candidate.expirationDateIOS == null ||
136
- candidate.expirationDateIOS > now) &&
137
- (purchase.environmentIOS == null ||
138
- candidate.environmentIOS === purchase.environmentIOS),
139
- );
140
- if (!verified) {
134
+ const isSame = (candidate: P) =>
135
+ candidate.store === "apple" &&
136
+ purchase.id !== "" &&
137
+ candidate.id === purchase.id &&
138
+ candidate.productId === purchase.productId &&
139
+ (purchase.environmentIOS == null ||
140
+ candidate.environmentIOS === purchase.environmentIOS);
141
+ const pending = (await getPendingTransactionsIOS()).find(isSame);
142
+ const transaction =
143
+ pending ?? (await options.getTransactionHistoryIOS?.())?.find(isSame);
144
+ if (!transaction) {
141
145
  throw new Error(
142
- `StoreKit lists no valid unfinished transaction for ${purchase.productId}`,
146
+ `StoreKit lists no transaction for ${purchase.productId}`,
143
147
  );
144
148
  }
145
- await options.grant?.(purchase, context);
146
- return { status: "entitled", alreadyGranted: false };
149
+ if (transaction.revocationDateIOS != null) {
150
+ return { status: "invalid", reason: "revoked" };
151
+ }
152
+ if (transaction.isUpgradedIOS === true) {
153
+ return { status: "invalid", reason: "upgraded" };
154
+ }
155
+ // After the reads: a transaction can expire while StoreKit answers.
156
+ if (
157
+ transaction.expirationDateIOS != null &&
158
+ transaction.expirationDateIOS <= Date.now()
159
+ ) {
160
+ return {
161
+ status: "verification_delayed",
162
+ retryAfterMs: DEVICE_EXPIRED_RETRY_MS,
163
+ };
164
+ }
165
+ // A finished consumable was credited before it was consumed.
166
+ if (pending || !context.isConsumable) {
167
+ await options.grant?.(purchase, context);
168
+ }
169
+ return { status: "entitled", alreadyGranted: !pending };
147
170
  };
148
171
  }
149
172
 
package/src/useIAP.ts CHANGED
@@ -542,17 +542,29 @@ export function useIAP(options?: UseIAPOptions): UseIap {
542
542
  );
543
543
 
544
544
  /**
545
- * Restore non-consumable and active subscription purchases.
545
+ * Restore non-consumable and active subscription purchases. With
546
+ * `purchaseFlow`, confirms every owned purchase through the flow instead of
547
+ * the provider's restore, so iOS asks for no App Store sign-in, and rejects
548
+ * when a confirmation fails.
546
549
  *
547
550
  * @see {@link https://openiap.dev/docs/apis/restore-purchases}
548
551
  */
549
552
  const restorePurchasesInternal = useCallback(
550
553
  async (options?: PurchaseOptions): Promise<void> => {
551
554
  try {
552
- await restorePurchasesNative();
553
- await optionsRef.current?.purchaseFlow?.recoverPurchases({
554
- includeFinished: true,
555
- });
555
+ const flow = optionsRef.current?.purchaseFlow;
556
+ // The provider's restore adds an iOS sign-in and Horizon redeliveries;
557
+ // the flow reads the store's history itself.
558
+ if (flow) {
559
+ const outcomes = await flow.recoverPurchases({includeFinished: true});
560
+ // A failed confirmation fails the restore; its purchase stays
561
+ // unfinished, so the next restore retries it.
562
+ for (const {status} of outcomes) {
563
+ if (status.status === 'failed') throw status.error;
564
+ }
565
+ } else {
566
+ await restorePurchasesNative();
567
+ }
556
568
 
557
569
  const read = startRead(availablePurchasesReads.current);
558
570
  const purchases = await getAvailablePurchases({