All files / omnium-gatherum/src/controllers/storage chrome-storage.ts

100% Statements 12/12
100% Branches 3/3
100% Functions 6/6
100% Lines 11/11

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 49                          6x   2x 2x       1x       1x                           2x 2x 2x 1x   3x       1x  
import type { Json } from '@metamask/utils';
 
import type { StorageAdapter } from './types.ts';
 
/**
 * Create a storage adapter backed by Chrome Storage API.
 *
 * @param storage - The Chrome storage area to use (defaults to chrome.storage.local).
 * @returns A hardened StorageAdapter instance.
 */
export function makeChromeStorageAdapter(
  storage: chrome.storage.StorageArea = chrome.storage.local,
): StorageAdapter {
  return harden({
    async get<Value extends Json>(key: string): Promise<Value | undefined> {
      const result = await storage.get(key);
      return result[key] as Value | undefined;
    },
 
    async set(key: string, value: Json): Promise<void> {
      await storage.set({ [key]: value });
    },
 
    async delete(key: string): Promise<void> {
      await storage.remove(key);
    },
 
    /**
     * Get all keys, optionally filtered by prefix.
     *
     * Note: This loads all storage data into memory to enumerate keys,
     * as Chrome Storage API doesn't provide a native keys-only method.
     * May be inefficient for large storage.
     *
     * @param prefix - Optional prefix to filter keys by.
     * @returns Array of matching key names.
     */
    async keys(prefix?: string): Promise<string[]> {
      const all = await storage.get(null);
      const allKeys = Object.keys(all);
      if (prefix === undefined) {
        return allKeys;
      }
      return allKeys.filter((k) => k.startsWith(prefix));
    },
  });
}
harden(makeChromeStorageAdapter);