@powersync/web 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/index.react_native_web.js +667 -140
  2. package/dist/index.react_native_web.js.map +1 -1
  3. package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js → OPFSCoopSyncVFS-Dujy2ZwX.js} +2 -2
  4. package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js.map → OPFSCoopSyncVFS-Dujy2ZwX.js.map} +1 -1
  5. package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js +2 -0
  6. package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js.map +1 -0
  7. package/dist/worker/worker.js +1 -1
  8. package/dist/worker/worker.js.map +1 -1
  9. package/lib/db/NavigatorTriggerClaimManager.js +1 -1
  10. package/lib/db/NavigatorTriggerClaimManager.js.map +1 -1
  11. package/lib/db/PowerSyncDatabase.js +1 -1
  12. package/lib/db/PowerSyncDatabase.js.map +1 -1
  13. package/lib/db/adapters/options.d.ts +25 -2
  14. package/lib/db/adapters/options.js.map +1 -1
  15. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -7
  16. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js +130 -25
  17. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -1
  18. package/lib/db/adapters/wa-sqlite/DatabaseClient.d.ts +13 -0
  19. package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -1
  20. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +2 -1
  21. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js +12 -6
  22. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -1
  23. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.d.ts +30 -0
  24. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js +210 -0
  25. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js.map +1 -0
  26. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +1 -0
  27. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +178 -75
  28. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
  29. package/lib/db/adapters/wa-sqlite/vfs.d.ts +30 -4
  30. package/lib/db/adapters/wa-sqlite/vfs.js +53 -2
  31. package/lib/db/adapters/wa-sqlite/vfs.js.map +1 -1
  32. package/lib/db/sync/SharedWebStreamingSyncImplementation.js +1 -1
  33. package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
  34. package/lib/db/sync/WebStreamingSyncImplementation.js +1 -1
  35. package/lib/db/sync/WebStreamingSyncImplementation.js.map +1 -1
  36. package/lib/shared/{tab_close_signal.d.ts → locks.d.ts} +13 -0
  37. package/lib/shared/locks.js +56 -0
  38. package/lib/shared/locks.js.map +1 -0
  39. package/lib/worker/db/MultiDatabaseServer.js +37 -12
  40. package/lib/worker/db/MultiDatabaseServer.js.map +1 -1
  41. package/lib/worker/sync/SharedSyncImplementation.js +1 -1
  42. package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
  43. package/lib/worker/sync/WorkerClient.js +1 -1
  44. package/lib/worker/sync/WorkerClient.js.map +1 -1
  45. package/lib/worker/worker.js +67 -1
  46. package/lib/worker/worker.js.map +1 -1
  47. package/package.json +3 -3
  48. package/src/db/NavigatorTriggerClaimManager.ts +1 -1
  49. package/src/db/PowerSyncDatabase.ts +1 -1
  50. package/src/db/adapters/options.ts +27 -2
  51. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +148 -34
  52. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +16 -0
  53. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +16 -7
  54. package/src/db/adapters/wa-sqlite/SimpleOpfsFileSystem.ts +249 -0
  55. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +236 -97
  56. package/src/db/adapters/wa-sqlite/vfs.ts +61 -7
  57. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +1 -1
  58. package/src/db/sync/WebStreamingSyncImplementation.ts +1 -1
  59. package/src/shared/locks.ts +66 -0
  60. package/src/worker/db/MultiDatabaseServer.ts +46 -12
  61. package/src/worker/sync/SharedSyncImplementation.ts +1 -1
  62. package/src/worker/sync/WorkerClient.ts +1 -1
  63. package/src/worker/worker.ts +82 -3
  64. package/lib/shared/navigator.d.ts +0 -1
  65. package/lib/shared/navigator.js +0 -7
  66. package/lib/shared/navigator.js.map +0 -1
  67. package/lib/shared/tab_close_signal.js +0 -27
  68. package/lib/shared/tab_close_signal.js.map +0 -1
  69. package/src/shared/navigator.ts +0 -9
  70. package/src/shared/tab_close_signal.ts +0 -28
@@ -62,7 +62,22 @@ export interface WebSpecificOpenOptions {
62
62
  */
63
63
  encryptionKey: string | undefined;
64
64
 
65
- vfs: WASQLiteVFS;
65
+ /**
66
+ * The virtual file system used to store the database.
67
+ *
68
+ * For a discussion of different options and which one to use, see {@link https://docs.powersync.com/client-sdks/reference/javascript-web#sqlite-virtual-file-systems}.
69
+ *
70
+ * In addition to a concrete {@link WASQLiteVFS}, this can be set to `'auto'` to pick a suitable storage
71
+ * implementation depending on browser features. Currently, this uses {@link WASQLiteVFS.SimpleOpfsVFS} when OPFS is
72
+ * available and falls back to an in-memory database otherwise. In the future, this might add additional checks to use
73
+ * {@link WASQLiteVFS.OPFSWriteAheadVFS} where available or {@link WASQLiteVFS.IDBBatchAtomicVFS} instead of an
74
+ * in-memory fallback.
75
+ *
76
+ * You can rely on `'auto'` being _stable_: Once it persists data, that data won't be lost later. Once this option
77
+ * supports multiple persistence options, it will check for existing data instead of picking the best one (to avoid
78
+ * e.g. a browser update unlocking a new VFS causing lost data).
79
+ */
80
+ vfs: WASQLiteVFS | 'auto';
66
81
 
67
82
  /**
68
83
  * Names of additional no-argument WebAssembly exports to call after the PowerSync core initializer and before
@@ -92,7 +107,7 @@ export interface WebSpecificOpenOptions {
92
107
  * You can either provide a path to the worker script
93
108
  * or a factory method that returns a worker.
94
109
  */
95
- worker?: string | URL | ((options: ResolvedWebSQLOpenOptions) => Worker | SharedWorker);
110
+ worker?: string | URL | ((options: CustomWorkerOptions) => Worker | SharedWorker);
96
111
 
97
112
  /**
98
113
  * Use an existing port to an initialized worker.
@@ -128,6 +143,16 @@ export interface WebSpecificOpenOptions {
128
143
  * Uses the default bucket when no option is given.
129
144
  */
130
145
  storageBucket?: string;
146
+
147
+ /** @internal Only used internally for testing */
148
+ simpleMode?: unknown;
149
+ }
150
+
151
+ export interface CustomWorkerOptions extends ResolvedWebSQLOpenOptions {
152
+ /**
153
+ * Whether the SDK intends to spawn a shared worker for this call.
154
+ */
155
+ readonly shared: boolean;
131
156
  }
132
157
 
133
158
  export interface ResolvedWebSQLOpenOptions extends SQLOpenOptions, WebSpecificOpenOptions {}
@@ -1,5 +1,7 @@
1
1
  import { Mutex, UnlockFn } from '@powersync/shared-internals';
2
2
  import { RawSqliteConnection, RawWaSqliteDatabaseOptions } from './RawSqliteConnection.js';
3
+ import type { SimpleOpfsFileSystem } from './SimpleOpfsFileSystem.js';
4
+ import { requestNavigatorLock } from '../../../shared/locks.js';
3
5
 
4
6
  /**
5
7
  * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.
@@ -12,48 +14,29 @@ import { RawSqliteConnection, RawWaSqliteDatabaseOptions } from './RawSqliteConn
12
14
  */
13
15
  export class ConcurrentSqliteConnection {
14
16
  /**
15
- * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
16
- *
17
- * If null, we'll use navigator locks instead.
17
+ * The {@link SimpleOpfsFileSystem} used by the inner connection, if any. SQLite closing its files doesn't close the
18
+ * sync access handles of that file system, so we do that after closing the connection.
18
19
  */
19
- private leaseMutex: Mutex | null;
20
+ simpleOpfsVfs: SimpleOpfsFileSystem | null = null;
20
21
 
21
- /**
22
- * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.
23
- *
24
- * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
25
- * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
26
- * In those setups, we use navigator locks instead of an internal mutex to guard access..
27
- */
28
22
  constructor(
29
23
  private readonly inner: RawSqliteConnection,
30
- needsNavigatorLocks: boolean
31
- ) {
32
- this.leaseMutex = needsNavigatorLocks ? null : new Mutex();
33
- }
24
+ /**
25
+ * A mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
26
+ *
27
+ * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
28
+ * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
29
+ * In those setups, we use navigator locks instead of an internal mutex to guard access.
30
+ */
31
+ private readonly mutex: ConnectionMutex
32
+ ) {}
34
33
 
35
34
  get options(): RawWaSqliteDatabaseOptions {
36
35
  return this.inner.options;
37
36
  }
38
37
 
39
38
  acquireMutex(abort?: AbortSignal): Promise<UnlockFn> {
40
- if (this.leaseMutex) {
41
- return this.leaseMutex.acquire(abort);
42
- }
43
-
44
- return new Promise((resolve, reject) => {
45
- const options: LockOptions = { signal: abort };
46
-
47
- navigator.locks
48
- .request(`db-lock-${this.options.filename}`, options, (_) => {
49
- return new Promise<void>((returnLock) => {
50
- return resolve(() => {
51
- returnLock();
52
- });
53
- });
54
- })
55
- .catch(reject);
56
- });
39
+ return this.mutex.acquire(abort);
57
40
  }
58
41
 
59
42
  // Unsafe, unguarded access to the SQLite connection.
@@ -86,13 +69,22 @@ export class ConcurrentSqliteConnection {
86
69
  return token;
87
70
  }
88
71
 
89
- async close(): Promise<void> {
90
- const returnMutex = await this.acquireMutex();
72
+ /**
73
+ * @param returnMutex If the caller already holds the mutex (from {@link acquireMutex}), the function returning it.
74
+ */
75
+ async close(returnMutex?: UnlockFn): Promise<void> {
76
+ returnMutex ??= await this.acquireMutex();
91
77
  try {
92
78
  await this.inner.close();
93
79
  } finally {
80
+ this.simpleOpfsVfs?.close();
94
81
  returnMutex();
95
82
  }
83
+
84
+ if (this.mutex instanceof LazyNavigatorMutex) {
85
+ // We won't use this connection again, so don't wait for another tab to steal the navigator locks.
86
+ await this.mutex.releaseNavigatorLocks();
87
+ }
96
88
  }
97
89
  }
98
90
 
@@ -134,3 +126,125 @@ export class ConnectionLeaseToken {
134
126
  });
135
127
  }
136
128
  }
129
+
130
+ export interface ConnectionMutex {
131
+ acquire(signal?: AbortSignal): Promise<UnlockFn>;
132
+ }
133
+
134
+ export class NavigatorMutex implements ConnectionMutex {
135
+ constructor(private readonly name: string) {}
136
+
137
+ acquire(signal?: AbortSignal): Promise<UnlockFn> {
138
+ return requestNavigatorLock(this.name, { signal });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * A protocol that only gives up navigator locks when another tab requests them.
144
+ *
145
+ * This is mainly relevant for a {@link SimpleOpfsFileSystem} used without shared workers and without
146
+ * `readwrite-unsafe`, as we have to close sync access handles when another tab wants to use the database. The protocol
147
+ * here works like this:
148
+ *
149
+ * 1. Acquire a temporary lock (to avoid contention, not needed for correctness).
150
+ * 2. Obtain an outer lock, stealing it if necessary.
151
+ * 3. Obtain the inner lock.
152
+ * 4. Release the temporary lock.
153
+ * 5. Run the exclusive operation.
154
+ * 6. Wait for another tab to steal the outer lock from us (as its second step).
155
+ * 7. Close the VFS once we're done with it, and return the inner lock.
156
+ */
157
+ export class LazyNavigatorMutex implements ConnectionMutex {
158
+ /**
159
+ * A file system to open after acquiring navigator locks and to close before returning them.
160
+ */
161
+ linkedVfs: SimpleOpfsFileSystem | null = null;
162
+
163
+ #outerLockName: string;
164
+ #temporaryLockName: string;
165
+
166
+ /**
167
+ * A local mutex guarding access within this context. Requesting it first is cheap, and allows the navigator lock
168
+ * logic to assume exclusive access to {@link LazyNavigatorMutex.#heldNavigatorLocks}.
169
+ */
170
+ #localMutex = new Mutex();
171
+ #heldNavigatorLocks: { outer: UnlockFn; inner: UnlockFn } | null = null;
172
+
173
+ constructor(private readonly name: string) {
174
+ this.#outerLockName = `${name}-outer`;
175
+ this.#temporaryLockName = `${name}-tmp`;
176
+ }
177
+
178
+ async #acquireNavigatorLocks(signal?: AbortSignal) {
179
+ console.assert(this.#heldNavigatorLocks == null);
180
+ let temporary: UnlockFn | undefined;
181
+ let outer: UnlockFn | undefined;
182
+ let inner: UnlockFn | undefined;
183
+
184
+ try {
185
+ // 1. Acquire the temporary lock, so that we don't have multiple tabs stealing the outer lock from each other.
186
+ temporary = await requestNavigatorLock(this.#temporaryLockName, { signal });
187
+
188
+ // 2. Request the outer lock, stealing it from another tab if necessary. Abort signals can't be combined with
189
+ // steal, so we don't pass one here.
190
+ outer = await requestNavigatorLock(this.#outerLockName, {
191
+ steal: true,
192
+ onStolen: () => this.#handleOuterLockStolen()
193
+ });
194
+
195
+ // 3. Obtain the inner lock. The tab we've stolen the outer lock from will return it once it's done.
196
+ inner = await requestNavigatorLock(this.name, { signal });
197
+
198
+ await this.linkedVfs?.open();
199
+ this.#heldNavigatorLocks = { outer, inner };
200
+ } catch (e) {
201
+ // Failed to acquire some locks, ensure they're all released.
202
+ outer?.();
203
+ inner?.();
204
+ throw e;
205
+ } finally {
206
+ // 4. Release the temporary lock.
207
+ temporary?.();
208
+ }
209
+ }
210
+
211
+ #handleOuterLockStolen() {
212
+ // Steps 6 and 7.
213
+ this.releaseNavigatorLocks();
214
+ }
215
+
216
+ async acquire(signal?: AbortSignal): Promise<UnlockFn> {
217
+ const returnLocalMutex = await this.#localMutex.acquire(signal);
218
+ if (this.#heldNavigatorLocks != null) {
219
+ // We already hold the navigator locks, so we can use the database directly.
220
+ return returnLocalMutex;
221
+ }
222
+
223
+ try {
224
+ await this.#acquireNavigatorLocks(signal);
225
+ } catch (e) {
226
+ returnLocalMutex();
227
+ throw e;
228
+ }
229
+
230
+ // Step 5: Run the exclusive operation. Steps 6 and 7 run when the outer lock gets stolen from us, a callback
231
+ // reacting to that has been installed at this point.
232
+ return returnLocalMutex;
233
+ }
234
+
235
+ /**
236
+ * Closes the linked VFS (if any) and returns navigator locks, if they're currently held.
237
+ */
238
+ async releaseNavigatorLocks(): Promise<void> {
239
+ await this.#localMutex.runExclusive(() => {
240
+ const held = this.#heldNavigatorLocks;
241
+ if (held != null) {
242
+ this.linkedVfs?.close();
243
+
244
+ held.outer();
245
+ held.inner();
246
+ this.#heldNavigatorLocks = null;
247
+ }
248
+ });
249
+ }
250
+ }
@@ -19,6 +19,10 @@ import { ConnectionClosedError } from '@powersync/shared-internals';
19
19
  export interface OpenWorkerConnection {
20
20
  connect(config: ConnectToMultiDatabaseServerOptions): Promise<ClientConnectionView>;
21
21
  connectToExisting(options: { identifier: string; lockName: string }): Promise<ClientConnectionView>;
22
+
23
+ sharedFeatureDetection(): Promise<SharedFeatureDetectionResult>;
24
+ dedicatedFeatureDetection(): Promise<DedicatedFeatureDetectionResult>;
25
+ spawnNested(): Promise<MessagePort>;
22
26
  }
23
27
 
24
28
  export interface ClientOptions {
@@ -40,6 +44,18 @@ export interface ClientOptions {
40
44
  onClose?: () => void;
41
45
  }
42
46
 
47
+ export interface SharedFeatureDetectionResult {
48
+ /** When this shared worker can spawn nested dedicated workers, features available in that worker. */
49
+ readonly worker: DedicatedFeatureDetectionResult | null;
50
+ }
51
+
52
+ export interface DedicatedFeatureDetectionResult {
53
+ /** Whether the browser supports the `mode:` parameter when opening file handles. */
54
+ readonly openWithMode: boolean;
55
+ /** Whether this browser supports `navigator.storage.getDirectory()` */
56
+ readonly opfs: boolean;
57
+ }
58
+
43
59
  /**
44
60
  * A single-connection {@link ConnectionPool} implementation based on a worker connection.
45
61
  */
@@ -1,6 +1,6 @@
1
1
  import { Factory as WaSqliteFactory, SQLITE_ROW } from '@journeyapps/wa-sqlite';
2
2
 
3
- import { loadModuleAndVfs, WASQLiteVFS } from './vfs.js';
3
+ import { WASQLiteVFS } from './vfs.js';
4
4
  import { TemporaryStorageOption } from '../options.js';
5
5
  import { RawQueryResult, SqliteValue } from '@powersync/common';
6
6
  import { maxPathNameLength } from '../resolveAndValidateOptions.js';
@@ -15,6 +15,8 @@ export interface RawResultSet {
15
15
  rawRows: SqliteValue[][];
16
16
  }
17
17
 
18
+ export type SimpleOpfsMode = 'shared' | 'rw-unsafe' | 'fallback';
19
+
18
20
  /**
19
21
  * @internal
20
22
  */
@@ -34,6 +36,7 @@ export interface RawWaSqliteDatabaseOptions {
34
36
  * The name of a Storage Bucket to keep the database files in, for the OPFS-based VFS implementations.
35
37
  */
36
38
  storageBucket?: string;
39
+ simpleMode?: SimpleOpfsMode;
37
40
  }
38
41
 
39
42
  /**
@@ -61,15 +64,17 @@ export class RawSqliteConnection {
61
64
  return this.db != 0;
62
65
  }
63
66
 
64
- async init() {
65
- const { module, vfs } = await loadModuleAndVfs(this.options);
66
- await this.initWithModule(module, vfs);
67
- }
68
-
69
67
  async initWithModule(module: any, vfs: any) {
70
68
  const api = (this._sqliteAPI = await this.openSQLiteAPI(module, vfs));
69
+ let fileName = this.options.filename;
70
+ const isSimpleOpfsVfs = this.options.vfs == WASQLiteVFS.SimpleOpfsVFS;
71
+ if (isSimpleOpfsVfs) {
72
+ // The simple VFS doesn't support flexible file names, we use a nested OPFS directory instead.
73
+ fileName = '/database';
74
+ }
75
+
71
76
  this.db = await api.open_v2(
72
- this.options.filename,
77
+ fileName,
73
78
  this.options.readonly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */
74
79
  );
75
80
  await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
@@ -78,6 +83,10 @@ export class RawSqliteConnection {
78
83
  await this.executeRaw(`PRAGMA key = '${escapedKey}';`);
79
84
  }
80
85
  await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
86
+ if (isSimpleOpfsVfs) {
87
+ // This VFS does not support deleting files, so we use the TRUNCATE journaling mode instead.
88
+ await this.executeRaw(`PRAGMA journal_mode = TRUNCATE`);
89
+ }
81
90
 
82
91
  await this.executeRaw(`SELECT powersync_update_hooks('install');`);
83
92
  }
@@ -0,0 +1,249 @@
1
+ // @ts-expect-error
2
+ import { FacadeVFS } from '@journeyapps/wa-sqlite/src/FacadeVFS.js';
3
+ import { MemoryVFS } from '@journeyapps/wa-sqlite/src/examples/MemoryVFS.js';
4
+ import * as VFS from '@journeyapps/wa-sqlite/src/VFS.js';
5
+
6
+ type DirectoryResolver = () => Promise<{ dir: FileSystemDirectoryHandle; readWriteUnsafe: boolean }>;
7
+
8
+ export class SimpleOpfsFileSystem extends FacadeVFS {
9
+ #files: OpfsFiles | null = null;
10
+ #memory: any;
11
+ #openedFiles = new Map<number, PersistedFile>();
12
+ #openRoot: DirectoryResolver;
13
+
14
+ constructor(name: string, module: object, openRoot: DirectoryResolver) {
15
+ super(name, module);
16
+ this.#memory = new MemoryVFS(`${name}-memory`, module);
17
+ this.#openRoot = openRoot;
18
+ }
19
+
20
+ #requireFiles(): OpfsFiles {
21
+ if (this.#files == null) {
22
+ throw new Error(`Called OPFS method while closed.`);
23
+ }
24
+
25
+ return this.#files;
26
+ }
27
+
28
+ #requireFile(file: PersistedFile): FileSystemSyncAccessHandle {
29
+ return this.#requireFiles().files[file.index];
30
+ }
31
+
32
+ #useFile(options: {
33
+ fileId: number;
34
+ opfs: (file: FileSystemSyncAccessHandle) => number;
35
+ memory: (memory: any) => number;
36
+ }): number {
37
+ const opened = this.#openedFiles.get(options.fileId);
38
+ if (opened != null) {
39
+ try {
40
+ return options.opfs(this.#requireFile(opened));
41
+ } catch (e) {
42
+ console.error('OPFS VFS error', e);
43
+ return VFS.SQLITE_IOERR;
44
+ }
45
+ } else {
46
+ return options.memory(this.#memory);
47
+ }
48
+ }
49
+
50
+ jOpen(zName: string | null, fileId: number, flags: number, pOutFlags: DataView): number {
51
+ if (flags & VFS.SQLITE_OPEN_MAIN_DB) {
52
+ if (zName != '/database') {
53
+ return VFS.SQLITE_CANTOPEN;
54
+ }
55
+
56
+ this.#openedFiles.set(fileId, database);
57
+ return VFS.SQLITE_OK;
58
+ } else if (flags & VFS.SQLITE_OPEN_MAIN_JOURNAL) {
59
+ if (zName != '/database-journal') {
60
+ return VFS.SQLITE_CANTOPEN;
61
+ }
62
+
63
+ this.#openedFiles.set(fileId, databaseJournal);
64
+ return VFS.SQLITE_OK;
65
+ } else {
66
+ // We don't care about other files (like those for materialized views). Back them by the in-memory VFS.
67
+ return this.#memory.jOpen(zName, fileId, flags, pOutFlags);
68
+ }
69
+ }
70
+
71
+ jDelete(name: string, syncDir: number): number {
72
+ switch (name) {
73
+ case '/database':
74
+ case '/database-journal':
75
+ // We don't support deleting files in this VFS, and use a journal mode where that is not necessary.
76
+ return VFS.SQLITE_IOERR_DELETE;
77
+ default:
78
+ return this.#memory.jDelete(name, syncDir);
79
+ }
80
+ }
81
+
82
+ jAccess(zName: string, flags: number, pResOut: DataView): number {
83
+ switch (zName) {
84
+ case '/database':
85
+ case '/database-journal':
86
+ // These always exist
87
+ pResOut.setInt32(0, 1, true);
88
+ return VFS.SQLITE_OK;
89
+ default:
90
+ return this.#memory.jAccess(zName, flags, pResOut);
91
+ }
92
+ }
93
+
94
+ jClose(fileId: number): number {
95
+ return this.#useFile({
96
+ fileId,
97
+ opfs: () => {
98
+ this.#openedFiles.delete(fileId);
99
+ return VFS.SQLITE_OK;
100
+ },
101
+ memory: (m) => m.jClose(fileId)
102
+ });
103
+ }
104
+
105
+ jRead(fileId: number, data: Uint8Array, iOffset: number): number {
106
+ return this.#useFile({
107
+ fileId,
108
+ opfs: (file) => {
109
+ const bytesRead = file.read(data.subarray(), { at: iOffset });
110
+
111
+ if (bytesRead < data.byteLength) {
112
+ data.fill(0, bytesRead);
113
+ return VFS.SQLITE_IOERR_SHORT_READ;
114
+ }
115
+ return VFS.SQLITE_OK;
116
+ },
117
+ memory: (m) => m.jRead(fileId, data, iOffset)
118
+ });
119
+ }
120
+
121
+ jWrite(fileId: number, data: Uint8Array, iOffset: number): number {
122
+ return this.#useFile({
123
+ fileId,
124
+ opfs: (file) => {
125
+ const nBytes = file.write(data.subarray(), { at: iOffset });
126
+ if (nBytes !== data.byteLength) throw new Error('short write');
127
+ return VFS.SQLITE_OK;
128
+ },
129
+ memory: (m) => m.jWrite(fileId, data, iOffset)
130
+ });
131
+ }
132
+
133
+ jTruncate(fileId: number, iSize: number): number {
134
+ return this.#useFile({
135
+ fileId,
136
+ opfs: (file) => {
137
+ file.truncate(iSize);
138
+ return VFS.SQLITE_OK;
139
+ },
140
+ memory: (m) => m.jTruncate(fileId, iSize)
141
+ });
142
+ }
143
+
144
+ jSync(fileId: number, flags: number): number {
145
+ return this.#useFile({
146
+ fileId,
147
+ opfs: (file) => {
148
+ file.flush();
149
+ return VFS.SQLITE_OK;
150
+ },
151
+ memory: (m) => m.jSync(fileId, flags)
152
+ });
153
+ }
154
+
155
+ jFileSize(fileId: number, pSize64: DataView): number {
156
+ return this.#useFile({
157
+ fileId,
158
+ opfs: (file) => {
159
+ pSize64.setBigInt64(0, BigInt(file.getSize()), true);
160
+ return VFS.SQLITE_OK;
161
+ },
162
+ memory: (m) => m.jFileSize(fileId, pSize64)
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Re-opens a file system previously closed with {@link SimpleOpfsFileSystem.close}.
168
+ */
169
+ async open() {
170
+ console.assert(this.#files == null);
171
+ const { dir, readWriteUnsafe } = await this.#openRoot();
172
+ this.#files = await OpfsFiles.open(dir, readWriteUnsafe);
173
+ }
174
+
175
+ /**
176
+ * Closes the synchronous access handles kept open while this file system is active.
177
+ *
178
+ * This file system can be re-opened afterwards with {@link SimpleOpfsFileSystem.open}.
179
+ */
180
+ close() {
181
+ this.#files?.close();
182
+ this.#files = null;
183
+ }
184
+
185
+ static directoryResolver(
186
+ name: string,
187
+ readWriteUnsafe: boolean,
188
+ getRoot?: () => Promise<FileSystemDirectoryHandle>
189
+ ): DirectoryResolver {
190
+ const url = new URL(name, 'file://');
191
+
192
+ return async () => {
193
+ let dir = await (getRoot ? getRoot() : navigator.storage.getDirectory());
194
+
195
+ for (const segment of ['powersync', ...url.pathname.split('/')]) {
196
+ if (!segment.length) continue; // Skip initial / and empty directory names
197
+
198
+ dir = await dir.getDirectoryHandle(segment, { create: true });
199
+ }
200
+
201
+ return { dir, readWriteUnsafe };
202
+ };
203
+ }
204
+ }
205
+
206
+ class OpfsFiles {
207
+ readonly files: ReadonlyArray<FileSystemSyncAccessHandle>;
208
+
209
+ constructor(database: FileSystemSyncAccessHandle, journal: FileSystemSyncAccessHandle) {
210
+ this.files = [database, journal];
211
+ }
212
+
213
+ close() {
214
+ for (const file of this.files) {
215
+ file.close();
216
+ }
217
+ }
218
+
219
+ static async open(root: FileSystemDirectoryHandle, readWriteUnsafe: boolean): Promise<OpfsFiles> {
220
+ async function open(name: string) {
221
+ const handle = await root.getFileHandle(name, { create: true });
222
+ return await (readWriteUnsafe
223
+ ? // @ts-expect-error
224
+ handle.createSyncAccessHandle({ mode: 'readwrite-unsafe' })
225
+ : handle.createSyncAccessHandle());
226
+ }
227
+
228
+ const [database, journal] = await Promise.allSettled([open('database'), open('journal')]);
229
+ if (database.status === 'fulfilled' && journal.status === 'fulfilled') {
230
+ return new OpfsFiles(database.value, journal.value);
231
+ }
232
+
233
+ if (database.status === 'fulfilled') {
234
+ database.value.close();
235
+ throw (journal as PromiseRejectedResult).reason;
236
+ } else if (journal.status === 'fulfilled') {
237
+ journal.value.close();
238
+ }
239
+ throw database.reason;
240
+ }
241
+ }
242
+
243
+ interface PersistedFile {
244
+ index: number;
245
+ name: string;
246
+ }
247
+
248
+ const database: PersistedFile = Object.freeze({ index: 0, name: '/database' });
249
+ const databaseJournal: PersistedFile = Object.freeze({ index: 1, name: '/database-journal' });