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

main
ts 128 lines 5 KB
Raw
1 /**
2 * Runs the worker side of the browser SQLite WASM client that stores data in
3 * OPFS.
4 *
5 * This module opens `@effect/wa-sqlite` with the OPFS access-handle VFS, then
6 * listens on a `MessagePort`-compatible port for the protocol used by
7 * `SqliteClient`. It sends a ready message, executes SQL messages, imports and
8 * exports database bytes, forwards update-hook notifications, and closes when
9 * requested. It is meant to run in a dedicated worker or a `SharedWorker`.
10 *
11 * @stability unstable
12 * @since 4.0.0
13 */
14 /// <reference lib="webworker" />
15 // oxlint-disable-next-line effect/no-import-from-barrel-package
16 import * as WaSqlite from "@effect/wa-sqlite"
17 import SQLiteESMFactory from "@effect/wa-sqlite/dist/wa-sqlite.mjs"
18 import { AccessHandlePoolVFS } from "@effect/wa-sqlite/src/examples/AccessHandlePoolVFS.js"
19 import * as Effect from "effect/Effect"
20 import { classifySqliteError, SqlError } from "effect/sql/SqlError"
21 import type { OpfsWorkerMessage } from "./internal/opfsWorker.ts"
22
23 const classifyError = (cause: unknown, message: string, operation: string) =>
24 classifySqliteError(cause, { message, operation })
25
26 /**
27 * Configuration for the SQLite OPFS worker, including the message port used for the client protocol and the OPFS database name to open.
28 *
29 * @stability unstable
30 * @category models
31 * @since 4.0.0
32 */
33 export interface OpfsWorkerConfig {
34 readonly port: EventTarget & Pick<MessagePort, "postMessage" | "close"> & Partial<Pick<MessagePort, "start">>
35 readonly dbName: string
36 }
37
38 /**
39 * Runs the SQLite OPFS worker loop, opening the configured database, posting a ready message, handling query/import/export/update-hook messages, and closing when a close message is received.
40 *
41 * @stability unstable
42 * @category running
43 * @since 4.0.0
44 */
45 export const run = (
46 options: OpfsWorkerConfig
47 ): Effect.Effect<void, SqlError> =>
48 Effect.gen(function*() {
49 const factory = yield* Effect.promise(() => SQLiteESMFactory())
50 const sqlite3 = WaSqlite.Factory(factory)
51 const vfs = yield* Effect.acquireRelease(
52 Effect.promise(() => AccessHandlePoolVFS.create("opfs", factory)),
53 (vfs) => Effect.promise(() => vfs.close())
54 )
55 sqlite3.vfs_register(vfs, false)
56 const db = yield* Effect.acquireRelease(
57 Effect.try({
58 try: () => sqlite3.open_v2(options.dbName, undefined, "opfs"),
59 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "openDatabase") })
60 }),
61 (db) => Effect.sync(() => sqlite3.close(db))
62 )
63
64 return yield* Effect.callback<void>((resume) => {
65 const onMessage = (event: any) => {
66 let messageId: number
67 const message = event.data as OpfsWorkerMessage
68 try {
69 switch (message[0]) {
70 case "close": {
71 options.port.close()
72 return resume(Effect.void)
73 }
74 case "import": {
75 const [, id, data] = message
76 messageId = id
77 sqlite3.deserialize(db, "main", data, data.length, data.length, 1 | 2)
78 options.port.postMessage([id, void 0, void 0])
79 return
80 }
81 case "export": {
82 const [, id] = message
83 messageId = id
84 const data = sqlite3.serialize(db, "main")
85 options.port.postMessage([id, undefined, data], [data.buffer])
86 return
87 }
88 case "update_hook": {
89 messageId = -1
90 sqlite3.update_hook(db, (_op, _db, table, rowid) => {
91 if (!table) return
92 options.port.postMessage(["update_hook", table, Number(rowid)])
93 })
94 return
95 }
96 default: {
97 const [id, sql, params] = message
98 messageId = id
99 const results: Array<any> = []
100 const columns: Array<Array<string>> = []
101 for (const stmt of sqlite3.statements(db, sql)) {
102 let statementColumns: Array<string> | undefined
103 sqlite3.bind_collection(stmt, params as any)
104 while (sqlite3.step(stmt) === WaSqlite.SQLITE_ROW) {
105 statementColumns = statementColumns ?? sqlite3.column_names(stmt)
106 const row = sqlite3.row(stmt)
107 results.push(row)
108 columns.push(statementColumns)
109 }
110 }
111 options.port.postMessage([id, undefined, [columns, results]])
112 return
113 }
114 }
115 } catch (e: any) {
116 const message = "message" in e ? e.message : String(e)
117 const error = typeof e.code === "number" ? { message, code: e.code } : message
118 options.port.postMessage([messageId!, error, undefined])
119 }
120 }
121 options.port.addEventListener("message", onMessage)
122 options.port.start?.()
123 options.port.postMessage(["ready", undefined, undefined])
124 return Effect.sync(() => {
125 options.port.removeEventListener("message", onMessage)
126 })
127 })
128 }).pipe(Effect.scoped)