Open History to see the last commit
1import type { Session } from "electron";
2import { session } from "electron";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as Layer from "effect/Layer";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import * as SynchronizedRef from "effect/SynchronizedRef";
11
12const PREVIEW_PARTITION_PREFIX = "persist:v12-preview-";
13
14export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
15 "BrowserSessionPartitionDerivationError",
16 {
17 scope: Schema.String,
18 cause: Schema.instanceOf(PlatformError.PlatformError),
19 },
20) {
21 override get message(): string {
22 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
23 }
24}
25
26export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
27 "BrowserSessionCreationError",
28 {
29 scope: Schema.String,
30 partition: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
36 }
37}
38
39export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
40 "BrowserSessionStorageClearError",
41 {
42 partition: Schema.String,
43 cause: Schema.Defect(),
44 },
45) {
46 override get message(): string {
47 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
48 }
49}
50
51export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
52 "BrowserSessionCacheClearError",
53 {
54 partition: Schema.String,
55 cause: Schema.Defect(),
56 },
57) {
58 override get message(): string {
59 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
60 }
61}
62
63export const BrowserSessionGetSessionError = Schema.Union([
64 BrowserSessionPartitionDerivationError,
65 BrowserSessionCreationError,
66]);
67export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
68export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
69
70export const BrowserSessionError = Schema.Union([
71 BrowserSessionPartitionDerivationError,
72 BrowserSessionCreationError,
73 BrowserSessionStorageClearError,
74 BrowserSessionCacheClearError,
75]);
76export type BrowserSessionError = typeof BrowserSessionError.Type;
77export const isBrowserSessionError = Schema.is(BrowserSessionError);
78
79export class BrowserSession extends Context.Service<
80 BrowserSession,
81 {
82 readonly getPartition: (
83 scope?: string,
84 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
85 readonly isPartition: (partition: string) => boolean;
86 readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
87 readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
88 readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
89 }
90>()("@v12/desktop/preview/BrowserSession") {}
91
92export const make = Effect.gen(function* BrowserSessionMake() {
93 const crypto = yield* Crypto.Crypto;
94 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
95
96 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
97 const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
98 Effect.mapError(
99 (cause) =>
100 new BrowserSessionPartitionDerivationError({
101 scope,
102 cause,
103 }),
104 ),
105 );
106 return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
107 });
108
109 const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
110 const partition = yield* getPartition(scope);
111 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
112 const existing = sessions.get(partition);
113 if (existing) return Effect.succeed([existing, sessions] as const);
114 return Effect.try({
115 try: () => {
116 const browserSession = session.fromPartition(partition);
117 const userAgent = browserSession
118 .getUserAgent()
119 .replace(/Electron\/[\d.]+ /, "")
120 .replace(/\s*v12\/[\d.]+/, "");
121 browserSession.setUserAgent(userAgent);
122 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
123 const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
124 callback(allowed.includes(permission));
125 });
126 const next = new Map(sessions);
127 next.set(partition, browserSession);
128 return [browserSession, next] as const;
129 },
130 catch: (cause) =>
131 new BrowserSessionCreationError({
132 scope,
133 partition,
134 cause,
135 }),
136 });
137 });
138 });
139
140 return BrowserSession.of({
141 getPartition,
142 isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
143 getSession,
144 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
145 const sessions = yield* SynchronizedRef.get(sessionsRef);
146 yield* Effect.all(
147 [...sessions.entries()].map(([partition, browserSession]) =>
148 Effect.tryPromise({
149 try: () =>
150 browserSession.clearStorageData({
151 storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
152 }),
153 catch: (cause) =>
154 new BrowserSessionStorageClearError({
155 partition,
156 cause,
157 }),
158 }),
159 ),
160 { concurrency: "unbounded", discard: true },
161 );
162 }),
163 clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
164 const sessions = yield* SynchronizedRef.get(sessionsRef);
165 yield* Effect.all(
166 [...sessions.entries()].map(([partition, browserSession]) =>
167 Effect.tryPromise({
168 try: () => browserSession.clearCache(),
169 catch: (cause) =>
170 new BrowserSessionCacheClearError({
171 partition,
172 cause,
173 }),
174 }),
175 ),
176 { concurrency: "unbounded", discard: true },
177 );
178 }),
179 });
180}).pipe(Effect.withSpan("BrowserSession.make"));
181
182export const layer = Layer.effect(BrowserSession, make);