Skip to content

Commit 3f278a4

Browse files
committed
fix(cache): uses textencoder for better size estimate
1 parent 889518f commit 3f278a4

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/utils/browser/browser-storage.utils.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,10 @@ const reverseFilterObject = (object: Record<string, unknown>, regex: string | Re
2424
/**
2525
* This function is used to get the total size of the local storage.
2626
* @param storage The storage area to get the size of.
27+
* @param encoder The encoder to use to get the size of the keys and values.
2728
*/
28-
const getLocalStorageSize = (storage = window.localStorage) => {
29-
return Object.entries(storage).reduce((acc, [key, value]) => acc + key.length + value.length, 0);
29+
const getLocalStorageSize = (storage = window.localStorage, encoder = new TextEncoder()) => {
30+
return Object.entries(storage).reduce((acc, [key, value]) => acc + encoder.encode(key).length + encoder.encode(value).length, 0);
3031
};
3132

3233
/**
@@ -107,8 +108,11 @@ export const defaultMaxLocalStorageSize = 10485760;
107108

108109
export const localCache: <T>(key: string, value: T, regex?: string | RegExp) => Promise<void> = async (key, value, regex) => {
109110
let inUse = await storage.local.getBytesInUse();
111+
110112
const max = globalThis?.chrome?.storage?.local.QUOTA_BYTES ?? defaultMaxLocalStorageSize;
111-
const payload = JSON.stringify(value).length;
113+
114+
const encoder = new TextEncoder();
115+
const payload = encoder.encode(JSON.stringify(value)).length;
112116

113117
if (payload > max) {
114118
console.warn('Payload is too large to store in local storage.', { payload, max, inUse });

0 commit comments

Comments
 (0)