UNPKG

@shopify/checkout-sheet-kit

Version:

A React Native library for Shopify's Checkout Kit.

297 lines (269 loc) 10.2 kB
/* MIT License Copyright 2023 - Present, Shopify Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NativeModules, NativeEventEmitter, PermissionsAndroid, Platform } from 'react-native'; import { ShopifyCheckoutSheetProvider, useShopifyCheckoutSheet } from './context'; import { ColorScheme } from './index.d'; import { CheckoutExpiredError, CheckoutClientError, CheckoutHTTPError, ConfigurationError, InternalError, CheckoutNativeErrorType, GenericError } from './errors.d'; import { CheckoutErrorCode } from './errors.d'; const RNShopifyCheckoutSheetKit = NativeModules.ShopifyCheckoutSheetKit; if (!('ShopifyCheckoutSheetKit' in NativeModules)) { throw new Error(` "@shopify/checkout-sheet-kit" is not correctly linked. If you are building for iOS, make sure to run "pod install" first and restart the metro server.`); } const defaultFeatures = { handleGeolocationRequests: true }; class ShopifyCheckoutSheet { static eventEmitter = new NativeEventEmitter(RNShopifyCheckoutSheetKit); /** * Initializes a new ShopifyCheckoutSheet instance * @param configuration Optional configuration settings for the checkout * @param features Optional feature flags to customize behavior, defaults to defaultFeatures */ constructor(configuration, features = defaultFeatures) { this.features = { ...defaultFeatures, ...features }; if (configuration != null) { this.setConfig(configuration); } if (Platform.OS === 'android' && this.featureEnabled('handleGeolocationRequests')) { this.subscribeToGeolocationRequestPrompts(); } } version = RNShopifyCheckoutSheetKit.version; /** * Dismisses the currently displayed checkout sheet */ dismiss() { RNShopifyCheckoutSheetKit.dismiss(); } /** * Invalidates the checkout that was cached using preload */ invalidate() { RNShopifyCheckoutSheetKit.invalidateCache(); } /** * Preloads checkout for a given URL to improve performance * @param checkoutUrl The URL of the checkout to preload */ preload(checkoutUrl) { RNShopifyCheckoutSheetKit.preload(checkoutUrl); } /** * Presents the checkout sheet for a given checkout URL * @param checkoutUrl The URL of the checkout to display */ present(checkoutUrl) { RNShopifyCheckoutSheetKit.present(checkoutUrl); } /** * Retrieves the current checkout configuration * @returns Promise containing the current Configuration */ async getConfig() { return RNShopifyCheckoutSheetKit.getConfig(); } /** * Updates the checkout configuration * @param configuration New configuration settings to apply */ setConfig(configuration) { RNShopifyCheckoutSheetKit.setConfig(configuration); } /** * Adds an event listener for checkout events * @param event The type of event to listen for * @param callback Function to be called when the event occurs * @returns An EmitterSubscription that can be used to remove the listener */ addEventListener(event, callback) { let eventCallback; switch (event) { case 'pixel': eventCallback = this.interceptEventEmission('pixel', callback, this.parseCustomPixelData); break; case 'completed': eventCallback = this.interceptEventEmission('completed', callback); break; case 'error': eventCallback = this.interceptEventEmission('error', callback, this.parseCheckoutError); break; case 'geolocationRequest': eventCallback = this.interceptEventEmission('geolocationRequest', callback); break; default: eventCallback = callback; } // Default handler for all non-pixel events return ShopifyCheckoutSheet.eventEmitter.addListener(event, eventCallback); } /** * Removes all event listeners for a specific event type * @param event The type of event to remove listeners for */ removeEventListeners(event) { ShopifyCheckoutSheet.eventEmitter.removeAllListeners(event); } /** * Cleans up resources and event listeners used by the checkout sheet */ teardown() { this.geolocationCallback?.remove(); } /** * Initiates a geolocation request for Android devices * Only needed if features.handleGeolocationRequests is false */ async initiateGeolocationRequest(allow) { if (Platform.OS === 'android') { RNShopifyCheckoutSheetKit.initiateGeolocationRequest?.(allow); } } // --- /** * Checks if a specific feature is enabled in the configuration * @param feature The feature to check * @returns boolean indicating if the feature is enabled */ featureEnabled(feature) { return this.features[feature] ?? true; } /** * Sets up geolocation request handling for Android devices */ subscribeToGeolocationRequestPrompts() { this.geolocationCallback = this.addEventListener('geolocationRequest', async () => { const coarseOrFineGrainAccessGranted = await this.requestGeolocation(); this.initiateGeolocationRequest(coarseOrFineGrainAccessGranted); }); } /** * Requests geolocation permissions on Android * @returns Promise<boolean> indicating if permission was granted */ async requestGeolocation() { const coarse = 'android.permission.ACCESS_COARSE_LOCATION'; const fine = 'android.permission.ACCESS_FINE_LOCATION'; const results = await PermissionsAndroid.requestMultiple([coarse, fine]); return [results[coarse], results[fine]].some(this.permissionGranted); } /** * Checks if the given permission status indicates that permission was granted * @param status The permission status to check * @returns boolean indicating if the permission was granted */ permissionGranted(status) { return status === 'granted'; } /** * Parses custom pixel event data from string to object if needed * @param eventData The pixel event data to parse * @returns Parsed PixelEvent object */ parseCustomPixelData(eventData) { if (isCustomPixelEvent(eventData) && eventData.hasOwnProperty('customData') && typeof eventData.customData === 'string') { try { return { ...eventData, customData: JSON.parse(eventData.customData) }; } catch { return eventData; } } return eventData; } /** * Converts native checkout errors into appropriate error class instances * @param exception The native error to parse * @returns Appropriate CheckoutException instance */ parseCheckoutError(exception) { switch (exception?.__typename) { case CheckoutNativeErrorType.InternalError: return new InternalError(exception); case CheckoutNativeErrorType.ConfigurationError: return new ConfigurationError(exception); case CheckoutNativeErrorType.CheckoutClientError: return new CheckoutClientError(exception); case CheckoutNativeErrorType.CheckoutHTTPError: return new CheckoutHTTPError(exception); case CheckoutNativeErrorType.CheckoutExpiredError: return new CheckoutExpiredError(exception); default: return new GenericError(exception); } } /** * Handles event emission parsing and transformation * @param event The type of event being intercepted * @param callback The callback to execute with the parsed data * @param transformData Optional function to transform the event data * @returns Function that handles the event emission */ interceptEventEmission(event, callback, transformData) { return eventData => { try { if (typeof eventData === 'string') { try { let parsed = JSON.parse(eventData); parsed = transformData?.(parsed) ?? parsed; callback(parsed); } catch (error) { const parseError = new LifecycleEventParseError(`Failed to parse "${event}" event data: Invalid JSON`, { cause: 'Invalid JSON' }); // eslint-disable-next-line no-console console.error(parseError, eventData); } } else if (eventData && typeof eventData === 'object') { callback(transformData?.(eventData) ?? eventData); } } catch (error) { const parseError = new LifecycleEventParseError(`Failed to parse "${event}" event data`, { cause: 'Unknown' }); // eslint-disable-next-line no-console console.error(parseError); } }; } } function isCustomPixelEvent(event) { return event.type === 'CUSTOM'; } export class LifecycleEventParseError extends Error { constructor(message, options) { super(message, options); this.name = 'LifecycleEventParseError'; if (Error.captureStackTrace) { Error.captureStackTrace(this, LifecycleEventParseError); } } } // API export { ColorScheme, ShopifyCheckoutSheet, ShopifyCheckoutSheetProvider, useShopifyCheckoutSheet }; // Error classes export { CheckoutClientError, CheckoutErrorCode, CheckoutExpiredError, CheckoutHTTPError, CheckoutNativeErrorType, ConfigurationError, GenericError, InternalError }; // Types //# sourceMappingURL=index.js.map