import { ShareStore } from "@tkey/common-types" ; import WebStorageError from "./errors" ; import { getWindow } from "./utils" ; const win = getWindow ( ) ; function storageAvailable ( type ) { let storage ; try { storage = win [ type ] ; const x = "__storage_test__" ; storage . setItem ( x , x ) ; storage . removeItem ( x ) ; return true ; } catch ( e ) { return ( e instanceof DOMException && ( e . code === 22 || e . code === 1014 || e . name === "QuotaExceededError" || e . name === "NS_ERROR_DOM_QUOTA_REACHED" ) && storage && storage . length !== 0 ) ; } } export const storeShareOnLocalStorage = async ( share , key ) : Promise < void > => { const fileStr = JSON . stringify ( share ) ; if ( ! storageAvailable ( "localStorage" ) ) { throw WebStorageError . localStorageUnavailable ( ) ; } win . localStorage . setItem ( key , fileStr ) ; } ; export const getShareFromLocalStorage = async ( key ) : Promise < ShareStore > => { if ( ! storageAvailable ( "localStorage" ) ) { throw WebStorageError . localStorageUnavailable ( ) ; } const foundFile = win . localStorage . getItem ( key ) ; if ( ! foundFile ) throw WebStorageError . shareUnavailableInLocalStorage ( ) ; return ShareStore . fromJSON ( JSON . parse ( foundFile ) ) ; } ;