All files / src/connect/common utils.ts

50% Statements 10/20
0% Branches 0/17
25% Functions 1/4
57.14% Lines 8/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 495x 5x 5x   5x                                               5x                               5x 3x 3x    
import { bytesToHex, getGlobalObject } from 'micro-stacks/common';
import { IS_BROWSER } from './constants';
import { getPublicKey } from 'micro-stacks/crypto';
 
const _localStorage = getGlobalObject('localStorage', { returnEmptyObject: true });
 
type Unsubscribe = () => void;
 
export interface StorageAdapter<Value> {
  setItem(key: string, value: Value): void;
 
  getItem(key: string): Value | null | undefined;
 
  removeItem(key: string): void;
 
  subscribe?: (key: string, callback: (value: Value) => void) => Unsubscribe;
}
 
export interface AsyncStorageAdapter<Value> {
  setItem(key: string, value: Value): Promise<void>;
 
  getItem(key: string): Promise<Value | null | undefined>;
 
  removeItem(key: string): Promise<void>;
 
  subscribe?: (key: string, callback: (value: Value) => void) => Unsubscribe;
}
 
export const defaultStorageAdapter: StorageAdapter<string> = {
  setItem: (key: string, value: string) => {
    Iif (IS_BROWSER) return _localStorage?.setItem(key, value);
  },
  getItem: (key: string) => {
    Iif (IS_BROWSER) {
      const storedValue = _localStorage?.getItem(key);
      Iif (storedValue === null) throw new Error('defaultStorageAdapter: no value stored');
      return storedValue;
    }
  },
  removeItem: (key: string) => {
    Iif (IS_BROWSER) return _localStorage?.removeItem(key);
  },
};
 
export const safeGetPublicKey = (privateKey?: string) => {
  Iif (!privateKey) return null;
  return bytesToHex(getPublicKey(privateKey, true));
};