Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: proxy localStorage and sessionStorage (closes #293) #548

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/lib/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import {
} from './web-worker/worker-constants';
import { debug, getConstructorName, isPromise } from './utils';

export const warnCrossOrgin = (
apiType: 'get' | 'set' | 'remove' | 'clear',
export const warnCrossOrigin = (
apiType: 'get' | 'set' | 'remove' | 'clear' | 'length' | 'key',
apiName: string,
env: WebWorkerEnvironment
) => console.warn(`Partytown unable to ${apiType} cross-origin ${apiName}: ` + env.$location$);
Expand Down
18 changes: 1 addition & 17 deletions src/lib/sandbox/read-main-platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
getConstructorName,
getNodeName,
isValidMemberName,
len,
noop,
serializeConfig,
} from '../utils';
Expand All @@ -13,7 +12,6 @@ import {
InterfaceInfo,
InterfaceMember,
InitWebWorkerData,
StorageItem,
} from '../types';

export const readMainPlatform = () => {
Expand Down Expand Up @@ -68,9 +66,7 @@ export const readMainPlatform = () => {
$config$,
$interfaces$: readImplementations(impls, initialInterfaces),
$libPath$: new URL(libPath, mainWindow.location as any) + '',
$origin$: origin,
$localStorage$: readStorage('localStorage'),
$sessionStorage$: readStorage('sessionStorage'),
$origin$: origin
};

addGlobalConstructorUsingPrototype(
Expand Down Expand Up @@ -186,18 +182,6 @@ const readImplementationMember = (
}
};

const readStorage = (storageName: 'localStorage' | 'sessionStorage') => {
let items: StorageItem[] = [];
let i = 0;
let l = len(mainWindow[storageName]);
let key: string;
for (; i < l; i++) {
key = mainWindow[storageName].key(i)!;
items.push([key, mainWindow[storageName].getItem(key)!]);
}
return items;
};

const getGlobalConstructor = (mainWindow: any, cstrName: string) =>
typeof mainWindow[cstrName] !== 'undefined' ? new mainWindow[cstrName](noop) : 0;

Expand Down
4 changes: 0 additions & 4 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,6 @@ export interface InitWebWorkerData {
$interfaces$: InterfaceInfo[];
$libPath$: string;
$sharedDataBuffer$?: SharedArrayBuffer;
$localStorage$: StorageItem[];
$sessionStorage$: StorageItem[];
$origin$: string;
}

Expand Down Expand Up @@ -639,8 +637,6 @@ export type StateMap = Record<number, StateRecord>;

export type StateRecord = Record<string | number, any>;

export type StorageItem = [/*key*/ string, /*value*/ string];

export const enum CallType {
Blocking = 1,
NonBlocking = 2,
Expand Down
5 changes: 0 additions & 5 deletions src/lib/web-worker/init-web-worker.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import {
commaSplit,
webWorkerCtx,
webWorkerlocalStorage,
webWorkerSessionStorage,
} from './worker-constants';
import type { InitWebWorkerData, PartytownInternalConfig } from '../types';

Expand All @@ -18,9 +16,6 @@ export const initWebWorker = (initWebWorkerData: InitWebWorkerData) => {
webWorkerCtx.$postMessage$ = (postMessage as any).bind(self);
webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;

webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$);
webWorkerSessionStorage.set(locOrigin, initWebWorkerData.$sessionStorage$);

(self as any).importScripts = undefined;
delete (self as any).postMessage;
delete (self as any).WorkerGlobalScope;
Expand Down
5 changes: 0 additions & 5 deletions src/lib/web-worker/worker-constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type {
PostMessageData,
RefHandler,
RefId,
StorageItem,
WebWorkerContext,
WebWorkerEnvironment,
WinId,
Expand All @@ -27,10 +26,6 @@ export const postMessages: PostMessageData[] = [];

export const webWorkerCtx: WebWorkerContext = {} as any;
export const webWorkerInterfaces: InterfaceInfo[] = [];

export const webWorkerlocalStorage = /*#__PURE__*/ new Map<string, StorageItem[]>();
export const webWorkerSessionStorage = /*#__PURE__*/ new Map<string, StorageItem[]>();

export const environments: { [winId: WinId]: WebWorkerEnvironment } = {};

export const cachedDimensions = /*#__PURE__*/ new Map<string, any>();
Expand Down
6 changes: 3 additions & 3 deletions src/lib/web-worker/worker-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ABOUT_BLANK, elementStructurePropNames, IS_TAG_REG, WinIdKey } from './
import { getInstanceStateValue } from './worker-state';
import { getPartytownScript } from './worker-exec';
import { isScriptJsType } from './worker-script';
import { warnCrossOrgin } from '../log';
import { warnCrossOrigin } from '../log';

export const patchDocument = (
WorkerDocument: any,
Expand All @@ -39,15 +39,15 @@ export const patchDocument = (
if (env.$isSameOrigin$) {
return getter(this, ['cookie']);
} else {
warnCrossOrgin('get', 'cookie', env);
warnCrossOrigin('get', 'cookie', env);
return '';
}
},
set(value) {
if (env.$isSameOrigin$) {
setter(this, ['cookie'], value);
} else if (debug) {
warnCrossOrgin('set', 'cookie', env);
warnCrossOrigin('set', 'cookie', env);
}
},
},
Expand Down
64 changes: 24 additions & 40 deletions src/lib/web-worker/worker-storage.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,61 @@
import { callMethod } from './worker-proxy';
import { CallType, StorageItem, WebWorkerEnvironment } from '../types';
import { callMethod, getter } from './worker-proxy';
import { CallType, WebWorkerEnvironment } from '../types';
import { EMPTY_ARRAY } from '../utils';
import { warnCrossOrgin } from '../log';
import { warnCrossOrigin } from '../log';

export const addStorageApi = (
win: any,
storageName: 'localStorage' | 'sessionStorage',
storages: Map<string, StorageItem[]>,
isSameOrigin: boolean,
env: WebWorkerEnvironment
) => {
let getItems = (items?: StorageItem[]) => {
items = storages.get(win.origin);
if (!items) {
storages.set(win.origin, (items = []));
}
return items;
};
let getIndexByKey = (key: string) => getItems().findIndex((i) => i[STORAGE_KEY] === key);
let index: number;
let item: StorageItem;

let storage: Storage = {
getItem(key) {
index = getIndexByKey(key);
return index > -1 ? getItems()[index][STORAGE_VALUE] : null;
if (isSameOrigin) {
return callMethod(win, [storageName, 'getItem'], [key], CallType.Blocking);
} else {
warnCrossOrigin('get', storageName, env);
}
},

setItem(key, value) {
index = getIndexByKey(key);
if (index > -1) {
getItems()[index][STORAGE_VALUE] = value;
} else {
getItems().push([key, value]);
}
if (isSameOrigin) {
callMethod(win, [storageName, 'setItem'], [key, value], CallType.NonBlocking);
callMethod(win, [storageName, 'setItem'], [key, value], CallType.Blocking);
} else {
warnCrossOrgin('set', storageName, env);
warnCrossOrigin('set', storageName, env);
}
},

removeItem(key) {
index = getIndexByKey(key);
if (index > -1) {
getItems().splice(index, 1);
}
if (isSameOrigin) {
callMethod(win, [storageName, 'removeItem'], [key], CallType.NonBlocking);
callMethod(win, [storageName, 'removeItem'], [key], CallType.Blocking);
} else {
warnCrossOrgin('remove', storageName, env);
warnCrossOrigin('remove', storageName, env);
}
},

key(index) {
item = getItems()[index];
return item ? item[STORAGE_KEY] : null;
if (isSameOrigin) {
return callMethod(win, [storageName, 'key'], [index], CallType.Blocking);
} else {
warnCrossOrigin('key', storageName, env);
}
},

clear() {
getItems().length = 0;
if (isSameOrigin) {
callMethod(win, [storageName, 'clear'], EMPTY_ARRAY, CallType.NonBlocking);
callMethod(win, [storageName, 'clear'], EMPTY_ARRAY, CallType.Blocking);
} else {
warnCrossOrgin('clear', storageName, env);
warnCrossOrigin('clear', storageName, env);
}
},

get length() {
return getItems().length;
if (isSameOrigin) {
return getter(win, [storageName, 'length'])
} else {
warnCrossOrigin('length', storageName, env);
}
},
};

Expand Down Expand Up @@ -99,6 +86,3 @@ export const addStorageApi = (
},
});
};

const STORAGE_KEY = 0;
const STORAGE_VALUE = 1;
6 changes: 2 additions & 4 deletions src/lib/web-worker/worker-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import {
NamespaceKey,
postMessages,
webWorkerCtx,
webWorkerlocalStorage,
webWorkerSessionStorage,
WinIdKey,
} from './worker-constants';
import { createCustomElementRegistry } from './worker-custom-elements';
Expand Down Expand Up @@ -419,8 +417,8 @@ export const createWindow = (
win.cancelIdleCallback = (id: number) => clearTimeout(id);

// add storage APIs to the window
addStorageApi(win, 'localStorage', webWorkerlocalStorage, $isSameOrigin$, env);
addStorageApi(win, 'sessionStorage', webWorkerSessionStorage, $isSameOrigin$, env);
addStorageApi(win, 'localStorage', $isSameOrigin$, env);
addStorageApi(win, 'sessionStorage', $isSameOrigin$, env);

if (!$isSameOrigin$) {
win.indexeddb = undefined;
Expand Down
Loading
Loading