@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 268 lines 9.34 KB
Raw
1 /**
2 * Browser-backed `KeyValueStore` layers for client-side Effect programs.
3 *
4 * This module provides browser implementations of the unstable persistence
5 * `KeyValueStore` service. Use {@link layerLocalStorage} for small
6 * origin-scoped values that should survive reloads and browser restarts, use
7 * {@link layerSessionStorage} for tab / page-session state, and use
8 * {@link layerIndexedDb} when the store should be asynchronous and backed by
9 * IndexedDB. The IndexedDB layer requires the browser `IndexedDb` service and
10 * accepts an optional database name.
11 *
12 * @stability unstable
13 * @since 4.0.0
14 */
15 import * as Effect from "effect/Effect"
16 import * as Layer from "effect/Layer"
17 import * as KeyValueStore from "effect/persistence/KeyValueStore"
18 import { IndexedDb } from "./IndexedDb.ts"
19
20 /**
21 * Creates a `KeyValueStore` layer that uses the browser's `localStorage` API and stores values between browser sessions.
22 *
23 * @stability unstable
24 * @category layers
25 * @since 4.0.0
26 */
27 export const layerLocalStorage: Layer.Layer<KeyValueStore.KeyValueStore> = KeyValueStore.layerStorage(() =>
28 globalThis.localStorage
29 )
30
31 /**
32 * Creates a `KeyValueStore` layer that uses the browser's `sessionStorage` API and stores values only for the current session.
33 *
34 * @stability unstable
35 * @category layers
36 * @since 4.0.0
37 */
38 export const layerSessionStorage: Layer.Layer<KeyValueStore.KeyValueStore> = KeyValueStore.layerStorage(() =>
39 globalThis.sessionStorage
40 )
41
42 /**
43 * Creates a `KeyValueStore` layer backed by IndexedDB.
44 *
45 * **When to use**
46 *
47 * Use when you need persistent asynchronous IndexedDB storage for a browser
48 * `KeyValueStore` instead of the synchronous Web Storage APIs.
49 *
50 * **Details**
51 *
52 * The database name defaults to `"effect_key_value_store"`. The layer requires
53 * the `IndexedDb` service and stores string and `Uint8Array` values in the same
54 * backing object store.
55 *
56 * **Gotchas**
57 *
58 * IndexedDB may be unavailable or blocked by browser settings, private browsing,
59 * quota limits, or restricted contexts. The string and `Uint8Array` accessors do
60 * not coerce values stored with the other representation.
61 *
62 * @see {@link layerLocalStorage} for synchronous persistent Web Storage
63 * @see {@link layerSessionStorage} for synchronous tab-session Web Storage
64 *
65 * @stability unstable
66 * @category layers
67 * @since 4.0.0
68 */
69 export const layerIndexedDb = (options?: {
70 readonly database?: string | undefined
71 }): Layer.Layer<KeyValueStore.KeyValueStore, never, IndexedDb> =>
72 Layer.effect(KeyValueStore.KeyValueStore)(
73 Effect.gen(function*() {
74 const { IDBKeyRange } = yield* IndexedDb
75 const db = yield* Effect.acquireRelease(
76 openDatabase(options?.database ?? "effect_key_value_store"),
77 (db) => Effect.sync(() => db.close())
78 ).pipe(Effect.orDie)
79
80 return KeyValueStore.make({
81 clear: Effect.suspend(() => {
82 return idbWriteRequest(
83 db,
84 { method: "clear", message: "Failed to clear backing store" },
85 (store) => store.clear()
86 )
87 }),
88 clearPrefix: (prefix: string) =>
89 Effect.asVoid(Effect.suspend(() => {
90 const range = prefixKeyRange(IDBKeyRange, prefix)
91 return idbWriteRequest(
92 db,
93 { method: "clearPrefix", message: "Failed to clear prefix in backing store", key: prefix },
94 (store) => range === undefined ? store.clear() : store.delete(range)
95 )
96 })),
97 get: (key: string) =>
98 Effect.map(
99 Effect.suspend(() => {
100 const store = getKvsEntriesStore(db, "readonly")
101 return idbRequest<{ key: string; value: string } | undefined>({
102 method: "get",
103 message: "Failed to get value from backing store",
104 key
105 }, () => store.get(key))
106 }),
107 (found) => typeof found?.value === "string" ? found.value : undefined
108 ),
109 getUint8Array: (key: string) =>
110 Effect.map(
111 Effect.suspend(() => {
112 const store = getKvsEntriesStore(db, "readonly")
113 return idbRequest<{ key: string; value: Uint8Array } | undefined>({
114 method: "getUint8Array",
115 message: "Failed to get value from backing store",
116 key
117 }, () => store.get(key))
118 }),
119 (found) => found?.value && found.value instanceof Uint8Array ? found.value : undefined
120 ),
121 has: (key: string) =>
122 Effect.map(
123 Effect.suspend(() => {
124 const store = getKvsEntriesStore(db, "readonly")
125 return idbRequest<number>({
126 method: "has",
127 message: "Failed to check key in backing store",
128 key
129 }, () => store.count(key))
130 }),
131 (count) => count > 0
132 ),
133 set: (key: string, value: string | Uint8Array) =>
134 Effect.asVoid(Effect.suspend(() => {
135 return idbWriteRequest(
136 db,
137 { method: "set", message: "Failed to set value in backing store", key },
138 (store) => store.put({ key, value })
139 )
140 })),
141 size: Effect.suspend(() => {
142 const store = getKvsEntriesStore(db, "readonly")
143 return idbRequest<number>(
144 { method: "size", message: "Failed to get backing store size" },
145 () => store.count()
146 )
147 }),
148 keys: Effect.suspend(() => {
149 const store = getKvsEntriesStore(db, "readonly")
150 return idbRequest(
151 { method: "keys", message: "Failed to get backing store keys" },
152 // keys are always strings since `set` only accepts string keys
153 () => store.getAllKeys() as IDBRequest<Array<string>>
154 )
155 }),
156 remove: (key: string) =>
157 Effect.asVoid(Effect.suspend(() => {
158 return idbWriteRequest(
159 db,
160 { method: "remove", message: "Failed to remove value from backing store", key },
161 (store) => store.delete(key)
162 )
163 }))
164 })
165 })
166 )
167
168 // Strings sort by UTF-16 code unit, so keys starting with `prefix` form one
169 // contiguous range.
170 const prefixKeyRange = (
171 KeyRange: typeof globalThis.IDBKeyRange,
172 prefix: string
173 ): IDBKeyRange | undefined => {
174 let end = prefix.length
175 while (end > 0 && prefix.charCodeAt(end - 1) === 0xffff) end--
176 if (end === 0) {
177 return prefix.length === 0 ? undefined : KeyRange.lowerBound(prefix)
178 }
179 const upper = prefix.slice(0, end - 1) + String.fromCharCode(prefix.charCodeAt(end - 1) + 1)
180 return KeyRange.bound(prefix, upper, false, true)
181 }
182
183 const databaseVersion = 1
184 const entriesStoreName = "entries"
185 const openDatabase = Effect.fnUntraced(function*(database: string) {
186 const idb = (yield* IndexedDb).indexedDB
187 const openRequest = yield* Effect.try({
188 try: () => idb.open(database, databaseVersion),
189 catch: (cause) =>
190 new KeyValueStore.KeyValueStoreError({
191 method: "open",
192 message: "Failed to open backing store database",
193 cause
194 })
195 })
196 openRequest.onupgradeneeded = () => {
197 const db = openRequest.result
198 if (!db.objectStoreNames.contains(entriesStoreName)) {
199 db.createObjectStore(entriesStoreName, { keyPath: "key" })
200 }
201 }
202 return yield* idbRequest({ method: "open", message: "Failed to open backing store database" }, () => openRequest)
203 })
204
205 const idbRequest = <A>(
206 failArgs: { method: string; message: string; key?: string },
207 evaluate: () => IDBRequest<A>
208 ): Effect.Effect<A, KeyValueStore.KeyValueStoreError> =>
209 Effect.callback<A, KeyValueStore.KeyValueStoreError>((resume) => {
210 const request = evaluate()
211 if (request.readyState === "done") {
212 return resume(Effect.succeed(request.result))
213 }
214 request.onsuccess = () => {
215 resume(Effect.succeed(request.result))
216 }
217 request.onerror = () =>
218 resume(Effect.fail(
219 new KeyValueStore.KeyValueStoreError({
220 ...failArgs,
221 cause: request.error
222 })
223 ))
224 })
225
226 const idbWriteRequest = <A>(
227 db: IDBDatabase,
228 failArgs: { method: string; message: string; key?: string },
229 evaluate: (store: IDBObjectStore) => IDBRequest<A>
230 ): Effect.Effect<A, KeyValueStore.KeyValueStoreError> =>
231 Effect.callback<A, KeyValueStore.KeyValueStoreError>((resume) => {
232 const transaction = db.transaction(entriesStoreName, "readwrite")
233 const request = evaluate(transaction.objectStore(entriesStoreName))
234 let result: A
235 let done = false
236
237 const fail = (cause: unknown) => {
238 if (done) return
239 done = true
240 resume(Effect.fail(new KeyValueStore.KeyValueStoreError({ ...failArgs, cause })))
241 }
242
243 if (request.readyState === "done") {
244 result = request.result
245 } else {
246 request.onsuccess = () => {
247 result = request.result
248 }
249 request.onerror = () => fail(request.error)
250 }
251
252 transaction.oncomplete = () => {
253 if (done) return
254 done = true
255 resume(Effect.succeed(result!))
256 }
257 transaction.onerror = () => fail(transaction.error)
258 transaction.onabort = () => fail(transaction.error)
259
260 return Effect.sync(() => {
261 if (!done) transaction.abort()
262 })
263 })
264
265 const getKvsEntriesStore = (db: IDBDatabase, mode: IDBTransactionMode) => {
266 const transaction = db.transaction(entriesStoreName, mode)
267 return transaction.objectStore(entriesStoreName)
268 }