1import { CodedError, uuidv4 } from 'expo-modules-core';
2
3import { ServerRegistrationModule } from './ServerRegistrationModule.types';
4
5const INSTALLATION_ID_KEY = 'EXPO_NOTIFICATIONS_INSTALLATION_ID';
6const REGISTRATION_INFO_KEY = 'EXPO_NOTIFICATIONS_REGISTRATION_INFO';
7
8// Lazy fallback installationId per session initializer
9let getFallbackInstallationId = () => {
10  const sessionInstallationId = uuidv4();
11  getFallbackInstallationId = () => sessionInstallationId;
12};
13
14export default {
15  getInstallationIdAsync: async () => {
16    let installationId;
17
18    try {
19      installationId = localStorage.getItem(INSTALLATION_ID_KEY);
20      if (!installationId || typeof installationId !== 'string') {
21        installationId = uuidv4();
22        localStorage.setItem(INSTALLATION_ID_KEY, installationId);
23      }
24    } catch {
25      installationId = getFallbackInstallationId();
26    }
27
28    return installationId;
29  },
30  getRegistrationInfoAsync: async () => {
31    return localStorage.getItem(REGISTRATION_INFO_KEY);
32  },
33  setRegistrationInfoAsync: async (registrationInfo: string | null) => {
34    try {
35      if (registrationInfo) {
36        localStorage.setItem(REGISTRATION_INFO_KEY, registrationInfo);
37      } else {
38        localStorage.removeItem(REGISTRATION_INFO_KEY);
39      }
40    } catch (error) {
41      throw new CodedError(
42        'ERR_NOTIFICATIONS_STORAGE_ERROR',
43        `Could not modify localStorage to persist auto-registration information: ${error}`
44      );
45    }
46  },
47  // mock implementations
48  addListener: () => {},
49  removeListeners: () => {},
50} as ServerRegistrationModule;
51