Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/client/lib/CookieStorage.ts
1028 views
1
import StateMachine from 'awaited-dom/base/StateMachine';
2
import ISetCookieOptions from '@secret-agent/interfaces/ISetCookieOptions';
3
import { ICookie } from '@secret-agent/interfaces/ICookie';
4
import CoreFrameEnvironment from './CoreFrameEnvironment';
5
6
const { getState, setState } = StateMachine<CookieStorage, IState>();
7
8
interface IState {
9
coreFrame: Promise<CoreFrameEnvironment>;
10
}
11
12
export default class CookieStorage {
13
public get length(): Promise<number> {
14
return this.getItems().then(x => x.length);
15
}
16
17
public async getItems(): Promise<ICookie[]> {
18
const coreFrame = await getCoreFrame(this);
19
return await coreFrame.getCookies();
20
}
21
22
public async key(index: number): Promise<string> {
23
const cookies = await this.getItems();
24
return Object.keys(cookies)[index];
25
}
26
27
public async clear(): Promise<void> {
28
const coreFrame = await getCoreFrame(this);
29
const cookies = await this.getItems();
30
for (const cookie of cookies) {
31
await coreFrame.removeCookie(cookie.name);
32
}
33
}
34
35
public async getItem(key: string): Promise<ICookie> {
36
const cookies = await this.getItems();
37
return cookies.find(x => x.name === key);
38
}
39
40
public async setItem(key: string, value: string, options?: ISetCookieOptions): Promise<boolean> {
41
const coreFrame = await getCoreFrame(this);
42
return coreFrame.setCookie(key, value, options);
43
}
44
45
public async removeItem(name: string): Promise<boolean> {
46
const coreFrame = await getCoreFrame(this);
47
return coreFrame.removeCookie(name);
48
}
49
}
50
51
function getCoreFrame(cookieStorage: CookieStorage): Promise<CoreFrameEnvironment> {
52
return getState(cookieStorage).coreFrame;
53
}
54
55
export function createCookieStorage(coreFrame: Promise<CoreFrameEnvironment>): CookieStorage {
56
const cookieStorage = new CookieStorage();
57
setState(cookieStorage, { coreFrame });
58
return cookieStorage;
59
}
60
61