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