{"version":3,"file":"initializePushNotifications.native.mjs","sources":["../../../../../../src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '@aws-amplify/core';\nimport { PushNotificationAction } from '@aws-amplify/core/internals/utils';\nimport { updateEndpoint } from '@aws-amplify/core/internals/providers/pinpoint';\nimport { loadAmplifyPushNotification } from '@aws-amplify/react-native';\nimport { addEventListener, notifyEventListeners, notifyEventListenersAndAwaitHandlers, } from '../../../../eventListeners';\nimport { getPushNotificationUserAgentString, getToken, initialize, isInitialized, resolveCredentials, setToken, } from '../../../utils';\nimport { createMessageEventRecorder, getChannelType, rejectInflightDeviceRegistration, resolveConfig, resolveInflightDeviceRegistration, } from '../utils';\nconst { addMessageEventListener, addTokenEventListener, completeNotification, getConstants, registerHeadlessTask, } = loadAmplifyPushNotification();\nconst logger = new ConsoleLogger('Notifications.PushNotification');\nconst BACKGROUND_TASK_TIMEOUT = 25; // seconds\nexport const initializePushNotifications = () => {\n    if (isInitialized()) {\n        logger.info('Push notifications have already been enabled');\n        return;\n    }\n    addNativeListeners();\n    addAnalyticsListeners();\n    initialize();\n};\nconst addNativeListeners = () => {\n    let launchNotificationOpenedListener;\n    const { NativeEvent, NativeHeadlessTaskKey } = getConstants();\n    const { BACKGROUND_MESSAGE_RECEIVED, FOREGROUND_MESSAGE_RECEIVED, LAUNCH_NOTIFICATION_OPENED, NOTIFICATION_OPENED, TOKEN_RECEIVED, } = NativeEvent;\n    // on platforms that can handle headless tasks, register one to broadcast background message received to\n    // library listeners\n    if (NativeHeadlessTaskKey) {\n        registerHeadlessTask(async (message) => {\n            // keep headless task running until handlers have completed their work\n            await notifyEventListenersAndAwaitHandlers('backgroundMessageReceived', message);\n        });\n    }\n    else if (BACKGROUND_MESSAGE_RECEIVED) {\n        // on platforms that can't handle headless tasks, listen for native background message received event and\n        // broadcast to library listeners\n        addMessageEventListener(BACKGROUND_MESSAGE_RECEIVED, async (message, completionHandlerId) => {\n            // keep background task running until handlers have completed their work\n            try {\n                await Promise.race([\n                    notifyEventListenersAndAwaitHandlers('backgroundMessageReceived', message),\n                    // background tasks will get suspended and all future tasks be deprioritized by the OS if they run for\n                    // more than 30 seconds so we reject with a error in a shorter amount of time to prevent this from\n                    // happening\n                    new Promise((_resolve, reject) => {\n                        setTimeout(() => {\n                            reject(new Error(`onNotificationReceivedInBackground handlers should complete their work within ${BACKGROUND_TASK_TIMEOUT} seconds, but they did not.`));\n                        }, BACKGROUND_TASK_TIMEOUT * 1000);\n                    }),\n                ]);\n            }\n            catch (err) {\n                logger.error(err);\n            }\n            finally {\n                // notify native module that handlers have completed their work (or timed out)\n                if (completionHandlerId) {\n                    completeNotification(completionHandlerId);\n                }\n            }\n        });\n    }\n    addMessageEventListener(\n    // listen for native foreground message received event and broadcast to library listeners\n    FOREGROUND_MESSAGE_RECEIVED, message => {\n        notifyEventListeners('foregroundMessageReceived', message);\n    });\n    launchNotificationOpenedListener = LAUNCH_NOTIFICATION_OPENED\n        ? addMessageEventListener(\n        // listen for native notification opened app (user tapped on notification, opening the app from quit -\n        // not background - state) event. This is broadcasted to an internal listener only as it is not intended\n        // for use otherwise as it produces inconsistent results when used within React Native app context\n        LAUNCH_NOTIFICATION_OPENED, message => {\n            notifyEventListeners('launchNotificationOpened', message);\n            // once we are done with it we can remove the listener\n            launchNotificationOpenedListener?.remove();\n            launchNotificationOpenedListener = undefined;\n        })\n        : undefined;\n    addMessageEventListener(\n    // listen for native notification opened (user tapped on notification, opening the app from background -\n    // not quit - state) event and broadcast to library listeners\n    NOTIFICATION_OPENED, message => {\n        notifyEventListeners('notificationOpened', message);\n        // if we are in this state, we no longer need the listener as the app was launched via some other means\n        launchNotificationOpenedListener?.remove();\n    });\n    addTokenEventListener(\n    // listen for native new token event, automatically re-register device with provider using new token and\n    // broadcast to library listeners\n    TOKEN_RECEIVED, async (token) => {\n        // avoid a race condition where two endpoints are created with the same token on a fresh install\n        if (getToken() === token) {\n            return;\n        }\n        setToken(token);\n        notifyEventListeners('tokenReceived', token);\n        try {\n            await registerDevice(token);\n        }\n        catch (err) {\n            logger.error('Failed to register device for push notifications', err);\n            throw err;\n        }\n    });\n};\nconst addAnalyticsListeners = () => {\n    let launchNotificationOpenedListenerRemover;\n    // wire up default Pinpoint message event handling\n    addEventListener('backgroundMessageReceived', createMessageEventRecorder('received_background'));\n    addEventListener('foregroundMessageReceived', createMessageEventRecorder('received_foreground'));\n    launchNotificationOpenedListenerRemover = addEventListener('launchNotificationOpened', createMessageEventRecorder('opened_notification', \n    // once we are done with it we can remove the listener\n    () => {\n        launchNotificationOpenedListenerRemover?.remove();\n        launchNotificationOpenedListenerRemover = undefined;\n    }));\n    addEventListener('notificationOpened', createMessageEventRecorder('opened_notification', \n    // if we are in this state, we no longer need the listener as the app was launched via some other means\n    () => {\n        launchNotificationOpenedListenerRemover?.remove();\n        launchNotificationOpenedListenerRemover = undefined;\n    }));\n};\nconst registerDevice = async (address) => {\n    const { credentials, identityId } = await resolveCredentials();\n    const { appId, region } = resolveConfig();\n    try {\n        await updateEndpoint({\n            address,\n            appId,\n            category: 'PushNotification',\n            credentials,\n            region,\n            channelType: getChannelType(),\n            identityId,\n            userAgentValue: getPushNotificationUserAgentString(PushNotificationAction.InitializePushNotifications),\n        });\n        // always resolve inflight device registration promise here even though the promise is only awaited on by\n        // `identifyUser` when no endpoint is found in the cache\n        resolveInflightDeviceRegistration();\n    }\n    catch (underlyingError) {\n        rejectInflightDeviceRegistration(underlyingError);\n        throw underlyingError;\n    }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AAQA,MAAM,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,YAAY,EAAE,oBAAoB,GAAG,GAAG,2BAA2B,EAAE;AACnJ,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,gCAAgC,CAAC;AAClE,MAAM,uBA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