@aztec/kv-store 0.0.1-commit.b8a057fa → 0.0.1-commit.be03c316

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.
@@ -1,13 +1,7 @@
1
- import { type Logger } from '@aztec/foundation/log';
2
- import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
1
  import { AztecIndexedDBStore } from './store.js';
4
2
  export { AztecIndexedDBStore } from './store.js';
5
- /**
6
- * @deprecated The IndexedDB backend is being retired. Use `@aztec/kv-store/sqlite-opfs` instead.
7
- */
8
- export declare function createStore(name: string, config: DataStoreConfig, schemaVersion?: number | undefined, log?: Logger): Promise<AztecIndexedDBStore>;
9
3
  /**
10
4
  * @deprecated The IndexedDB backend is being retired. Use `@aztec/kv-store/sqlite-opfs` instead.
11
5
  */
12
6
  export declare function openTmpStore(ephemeral?: boolean): Promise<AztecIndexedDBStore>;
13
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZXByZWNhdGVkL2luZGV4ZWRkYi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsS0FBSyxNQUFNLEVBQWdCLE1BQU0sdUJBQXVCLENBQUM7QUFDbEUsT0FBTyxLQUFLLEVBQUUsZUFBZSxFQUFFLE1BQU0sd0JBQXdCLENBQUM7QUFHOUQsT0FBTyxFQUFFLG1CQUFtQixFQUFFLE1BQU0sWUFBWSxDQUFDO0FBRWpELE9BQU8sRUFBRSxtQkFBbUIsRUFBRSxNQUFNLFlBQVksQ0FBQztBQUVqRDs7R0FFRztBQUNILHdCQUFzQixXQUFXLENBQy9CLElBQUksRUFBRSxNQUFNLEVBQ1osTUFBTSxFQUFFLGVBQWUsRUFDdkIsYUFBYSxHQUFFLE1BQU0sR0FBRyxTQUFxQixFQUM3QyxHQUFHLEdBQUUsTUFBaUMsZ0NBY3ZDO0FBRUQ7O0dBRUc7QUFDSCx3QkFBZ0IsWUFBWSxDQUFDLFNBQVMsR0FBRSxPQUFlLEdBQUcsT0FBTyxDQUFDLG1CQUFtQixDQUFDLENBRXJGIn0=
7
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZXByZWNhdGVkL2luZGV4ZWRkYi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxPQUFPLEVBQUUsbUJBQW1CLEVBQUUsTUFBTSxZQUFZLENBQUM7QUFFakQsT0FBTyxFQUFFLG1CQUFtQixFQUFFLE1BQU0sWUFBWSxDQUFDO0FBRWpEOztHQUVHO0FBQ0gsd0JBQWdCLFlBQVksQ0FBQyxTQUFTLEdBQUUsT0FBZSxHQUFHLE9BQU8sQ0FBQyxtQkFBbUIsQ0FBQyxDQUVyRiJ9
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/deprecated/indexeddb/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAgB,MAAM,uBAAuB,CAAC;AAClE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAG9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD;;GAEG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,eAAe,EACvB,aAAa,GAAE,MAAM,GAAG,SAAqB,EAC7C,GAAG,GAAE,MAAiC,gCAcvC;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,SAAS,GAAE,OAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAErF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/deprecated/indexeddb/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD;;GAEG;AACH,wBAAgB,YAAY,CAAC,SAAS,GAAE,OAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAErF"}
@@ -1,18 +1,6 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
- import { initStoreForRollupAndSchemaVersion } from '../../utils.js';
3
2
  import { AztecIndexedDBStore } from './store.js';
4
3
  export { AztecIndexedDBStore } from './store.js';
5
- /**
6
- * @deprecated The IndexedDB backend is being retired. Use `@aztec/kv-store/sqlite-opfs` instead.
7
- */ export async function createStore(name, config, schemaVersion = undefined, log = createLogger('kv-store')) {
8
- let { dataDirectory } = config;
9
- if (typeof dataDirectory !== 'undefined') {
10
- dataDirectory = `${dataDirectory}/${name}`;
11
- }
12
- log.info(dataDirectory ? `Creating ${name} data store at directory ${dataDirectory} with map size ${config.dataStoreMapSizeKb} KB` : `Creating ${name} ephemeral data store with map size ${config.dataStoreMapSizeKb} KB`);
13
- const store = await AztecIndexedDBStore.open(createLogger('kv-store:indexeddb'), dataDirectory ?? '', false);
14
- return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.rollupAddress, log);
15
- }
16
4
  /**
17
5
  * @deprecated The IndexedDB backend is being retired. Use `@aztec/kv-store/sqlite-opfs` instead.
18
6
  */ export function openTmpStore(ephemeral = false) {
@@ -24,4 +24,31 @@ export declare class SqliteEncryptionError extends Error {
24
24
  * strings.
25
25
  **/
26
26
  export declare function isDecryptFailureMessage(message: string): boolean;
27
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc3FsaXRlLW9wZnMvZXJyb3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7O0dBVUc7QUFDSCxNQUFNLE1BQU0seUJBQXlCLEdBQ2pDLG9CQUFvQixHQUNwQix3Q0FBd0MsR0FDeEMsZ0JBQWdCLENBQUM7QUFFckI7O0lBRUk7QUFDSixxQkFBYSxxQkFBc0IsU0FBUSxLQUFLO0lBQzlDLFFBQVEsQ0FBQyxJQUFJLEVBQUUseUJBQXlCLENBQUM7SUFFekMsWUFBWSxJQUFJLEVBQUUseUJBQXlCLEVBQUUsT0FBTyxFQUFFLE1BQU0sRUFBRSxJQUFJLENBQUMsRUFBRTtRQUFFLEtBQUssQ0FBQyxFQUFFLE9BQU8sQ0FBQTtLQUFFLEVBSXZGO0NBQ0Y7QUFVRDs7O0lBR0k7QUFDSix3QkFBZ0IsdUJBQXVCLENBQUMsT0FBTyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBRWhFIn0=
27
+ /**
28
+ * Error thrown by sqlite-opfs when the on-disk database image is corrupt
29
+ * (`SQLITE_CORRUPT`, result code 11 — "database disk image is malformed").
30
+ *
31
+ * Distinct from {@link SqliteEncryptionError}: no key recovers a corrupt image,
32
+ * so there is nothing to retry. The only escape is to delete the store and start
33
+ * fresh, so consumers pattern-match on `instanceof SqliteCorruptionError` to wipe
34
+ * and reopen rather than surfacing a dead-end error.
35
+ **/
36
+ export declare class SqliteCorruptionError extends Error {
37
+ constructor(message: string, opts?: {
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ /** Error thrown when another browser context already owns a store's OPFS pool. */
42
+ export declare class SqlitePoolBusyError extends Error {
43
+ readonly poolDirectory: string;
44
+ constructor(poolDirectory: string);
45
+ }
46
+ /** Error thrown when the browser context does not expose the Web Locks API required by the OPFS SAH pool. */
47
+ export declare class SqliteWebLocksUnavailableError extends Error {
48
+ constructor();
49
+ }
50
+ /**
51
+ * Returns `true` if `message` matches one of the known SQLite corruption strings.
52
+ **/
53
+ export declare function isCorruptionMessage(message: string): boolean;
54
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc3FsaXRlLW9wZnMvZXJyb3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7O0dBVUc7QUFDSCxNQUFNLE1BQU0seUJBQXlCLEdBQ2pDLG9CQUFvQixHQUNwQix3Q0FBd0MsR0FDeEMsZ0JBQWdCLENBQUM7QUFFckI7O0lBRUk7QUFDSixxQkFBYSxxQkFBc0IsU0FBUSxLQUFLO0lBQzlDLFFBQVEsQ0FBQyxJQUFJLEVBQUUseUJBQXlCLENBQUM7SUFFekMsWUFBWSxJQUFJLEVBQUUseUJBQXlCLEVBQUUsT0FBTyxFQUFFLE1BQU0sRUFBRSxJQUFJLENBQUMsRUFBRTtRQUFFLEtBQUssQ0FBQyxFQUFFLE9BQU8sQ0FBQTtLQUFFLEVBSXZGO0NBQ0Y7QUFVRDs7O0lBR0k7QUFDSix3QkFBZ0IsdUJBQXVCLENBQUMsT0FBTyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBRWhFO0FBRUQ7Ozs7Ozs7O0lBUUk7QUFDSixxQkFBYSxxQkFBc0IsU0FBUSxLQUFLO0lBQzlDLFlBQVksT0FBTyxFQUFFLE1BQU0sRUFBRSxJQUFJLENBQUMsRUFBRTtRQUFFLEtBQUssQ0FBQyxFQUFFLE9BQU8sQ0FBQTtLQUFFLEVBR3REO0NBQ0Y7QUFFRCxrRkFBa0Y7QUFDbEYscUJBQWEsbUJBQW9CLFNBQVEsS0FBSzthQUNoQixhQUFhLEVBQUUsTUFBTTtJQUFqRCxZQUE0QixhQUFhLEVBQUUsTUFBTSxFQUdoRDtDQUNGO0FBRUQsNkdBQTZHO0FBQzdHLHFCQUFhLDhCQUErQixTQUFRLEtBQUs7SUFDdkQsY0FHQztDQUNGO0FBYUQ7O0lBRUk7QUFDSix3QkFBZ0IsbUJBQW1CLENBQUMsT0FBTyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBRTVEIn0=
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/sqlite-opfs/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,yBAAyB,GACjC,oBAAoB,GACpB,wCAAwC,GACxC,gBAAgB,CAAC;AAErB;;IAEI;AACJ,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,EAAE,yBAAyB,CAAC;IAEzC,YAAY,IAAI,EAAE,yBAAyB,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIvF;CACF;AAUD;;;IAGI;AACJ,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/sqlite-opfs/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,yBAAyB,GACjC,oBAAoB,GACpB,wCAAwC,GACxC,gBAAgB,CAAC;AAErB;;IAEI;AACJ,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,EAAE,yBAAyB,CAAC;IAEzC,YAAY,IAAI,EAAE,yBAAyB,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIvF;CACF;AAUD;;;IAGI;AACJ,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED;;;;;;;;IAQI;AACJ,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAGtD;CACF;AAED,kFAAkF;AAClF,qBAAa,mBAAoB,SAAQ,KAAK;aAChB,aAAa,EAAE,MAAM;IAAjD,YAA4B,aAAa,EAAE,MAAM,EAGhD;CACF;AAED,6GAA6G;AAC7G,qBAAa,8BAA+B,SAAQ,KAAK;IACvD,cAGC;CACF;AAaD;;IAEI;AACJ,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE5D"}
@@ -32,3 +32,46 @@
32
32
  **/ export function isDecryptFailureMessage(message) {
33
33
  return SQLITE3MC_DECRYPT_ERROR_PATTERNS.some((p)=>p.test(message));
34
34
  }
35
+ /**
36
+ * Error thrown by sqlite-opfs when the on-disk database image is corrupt
37
+ * (`SQLITE_CORRUPT`, result code 11 — "database disk image is malformed").
38
+ *
39
+ * Distinct from {@link SqliteEncryptionError}: no key recovers a corrupt image,
40
+ * so there is nothing to retry. The only escape is to delete the store and start
41
+ * fresh, so consumers pattern-match on `instanceof SqliteCorruptionError` to wipe
42
+ * and reopen rather than surfacing a dead-end error.
43
+ **/ export class SqliteCorruptionError extends Error {
44
+ constructor(message, opts){
45
+ super(message, opts?.cause !== undefined ? {
46
+ cause: opts.cause
47
+ } : undefined);
48
+ this.name = 'SqliteCorruptionError';
49
+ }
50
+ }
51
+ /** Error thrown when another browser context already owns a store's OPFS pool. */ export class SqlitePoolBusyError extends Error {
52
+ poolDirectory;
53
+ constructor(poolDirectory){
54
+ super(`SQLite-OPFS pool "${poolDirectory}" is already in use by another store instance`), this.poolDirectory = poolDirectory;
55
+ this.name = 'SqlitePoolBusyError';
56
+ }
57
+ }
58
+ /** Error thrown when the browser context does not expose the Web Locks API required by the OPFS SAH pool. */ export class SqliteWebLocksUnavailableError extends Error {
59
+ constructor(){
60
+ super('SQLite-OPFS requires the Web Locks API, but it is unavailable in this browser context');
61
+ this.name = 'SqliteWebLocksUnavailableError';
62
+ }
63
+ }
64
+ /**
65
+ * Strings/codes raised by SQLite when a database image is corrupt. Kept disjoint
66
+ * from {@link SQLITE3MC_DECRYPT_ERROR_PATTERNS}: "file is not a database"
67
+ * (SQLITE_NOTADB) is the decrypt signal, whereas a malformed image is the
68
+ * genuinely-unrecoverable SQLITE_CORRUPT.
69
+ **/ const SQLITE_CORRUPTION_ERROR_PATTERNS = [
70
+ /database disk image is malformed/i,
71
+ /\bSQLITE_CORRUPT\b/i
72
+ ];
73
+ /**
74
+ * Returns `true` if `message` matches one of the known SQLite corruption strings.
75
+ **/ export function isCorruptionMessage(message) {
76
+ return SQLITE_CORRUPTION_ERROR_PATTERNS.some((p)=>p.test(message));
77
+ }
@@ -1,10 +1,8 @@
1
- import { type Logger } from '@aztec/foundation/log';
2
- import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
1
  import { AztecSQLiteOPFSStore } from './store.js';
4
2
  export { AztecSQLiteOPFSStore } from './store.js';
5
- export { SqliteEncryptionError } from './errors.js';
3
+ export { SqliteCorruptionError, SqliteEncryptionError, SqlitePoolBusyError, SqliteWebLocksUnavailableError, } from './errors.js';
6
4
  export type { SqliteEncryptionErrorCode } from './errors.js';
7
- export declare function createStore(name: string, config: DataStoreConfig, schemaVersion?: number | undefined, log?: Logger): Promise<AztecSQLiteOPFSStore>;
5
+ export { OPFS_POOL_DIR_PREFIX, deletePoolDirectory, deleteStore, listStores, storePoolDirectory } from './manage.js';
8
6
  export declare function openTmpStore(ephemeral?: boolean): Promise<AztecSQLiteOPFSStore>;
9
7
  /**
10
8
  * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
@@ -13,4 +11,4 @@ export declare function openTmpStore(ephemeral?: boolean): Promise<AztecSQLiteOP
13
11
  * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
14
12
  */
15
13
  export declare function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string): Promise<AztecSQLiteOPFSStore>;
16
- //# sourceMappingURL=data:application/json;base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,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,eAAe,EACvB,aAAa,GAAE,MAAM,GAAG,SAAqB,EAC7C,GAAG,GAAE,MAAiC,iCAUvC;AAED,wBAAgB,YAAY,CAAC,SAAS,GAAE,OAAe,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAEtF;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,iCAElG"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sqlite-opfs/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,8BAA8B,GAC/B,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,WAAW,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAErH,wBAAgB,YAAY,CAAC,SAAS,GAAE,OAAe,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAEtF;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,iCAElG"}
@@ -1,14 +1,8 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
- import { initStoreForRollupAndSchemaVersion } from '../utils.js';
3
2
  import { AztecSQLiteOPFSStore } from './store.js';
4
3
  export { AztecSQLiteOPFSStore } from './store.js';
5
- export { SqliteEncryptionError } from './errors.js';
6
- export async function createStore(name, config, schemaVersion = undefined, log = createLogger('kv-store')) {
7
- const { dataDirectory } = config;
8
- log.info(dataDirectory ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB` : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`);
9
- const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
10
- return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.rollupAddress, log);
11
- }
4
+ export { SqliteCorruptionError, SqliteEncryptionError, SqlitePoolBusyError, SqliteWebLocksUnavailableError } from './errors.js';
5
+ export { OPFS_POOL_DIR_PREFIX, deletePoolDirectory, deleteStore, listStores, storePoolDirectory } from './manage.js';
12
6
  export function openTmpStore(ephemeral = false) {
13
7
  return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
14
8
  }
@@ -0,0 +1,22 @@
1
+ /** Prefix for the per-store OPFS SAH pool directories owned by this package. */
2
+ export declare const OPFS_POOL_DIR_PREFIX = ".aztec-kv-";
3
+ /**
4
+ * OPFS directory holding a store's SAH pool. One directory per store: the SAH-pool VFS allows only one
5
+ * concurrent instance per directory and its capacity does not grow automatically, so sharing a pool across
6
+ * stores would make concurrently opened stores contend for locks and orphaned stores exhaust pool slots.
7
+ */
8
+ export declare function storePoolDirectory(effectiveName: string): string;
9
+ /**
10
+ * Lists the names of every persistent sqlite-opfs store in this origin, by enumerating the per-store pool
11
+ * directories. Includes stores other than the current one, so wallets can surface and clean up data for
12
+ * networks/versions no longer in use.
13
+ */
14
+ export declare function listStores(): Promise<string[]>;
15
+ /**
16
+ * Permanently deletes a store by effective name (as returned by {@link listStores}). The store must be closed:
17
+ * an open store holds the directory's Web Lock and the removal will reject with `SqlitePoolBusyError`.
18
+ */
19
+ export declare function deleteStore(effectiveName: string): Promise<void>;
20
+ /** Permanently deletes one OPFS SAH-pool directory after exclusively locking it. */
21
+ export declare function deletePoolDirectory(poolDirectory: string): Promise<void>;
22
+ //# sourceMappingURL=data:application/json;base64,e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
@@ -0,0 +1,38 @@
1
+ import { normalizePoolDirectory, withPoolLock } from './pool_lock.js';
2
+ /** Prefix for the per-store OPFS SAH pool directories owned by this package. */ export const OPFS_POOL_DIR_PREFIX = '.aztec-kv-';
3
+ /**
4
+ * OPFS directory holding a store's SAH pool. One directory per store: the SAH-pool VFS allows only one
5
+ * concurrent instance per directory and its capacity does not grow automatically, so sharing a pool across
6
+ * stores would make concurrently opened stores contend for locks and orphaned stores exhaust pool slots.
7
+ */ export function storePoolDirectory(effectiveName) {
8
+ return `${OPFS_POOL_DIR_PREFIX}${effectiveName}`;
9
+ }
10
+ /**
11
+ * Lists the names of every persistent sqlite-opfs store in this origin, by enumerating the per-store pool
12
+ * directories. Includes stores other than the current one, so wallets can surface and clean up data for
13
+ * networks/versions no longer in use.
14
+ */ export async function listStores() {
15
+ const root = await navigator.storage.getDirectory();
16
+ const names = [];
17
+ for await (const [entryName, handle] of root.entries()){
18
+ if (handle.kind === 'directory' && entryName.startsWith(OPFS_POOL_DIR_PREFIX)) {
19
+ names.push(entryName.slice(OPFS_POOL_DIR_PREFIX.length));
20
+ }
21
+ }
22
+ return names;
23
+ }
24
+ /**
25
+ * Permanently deletes a store by effective name (as returned by {@link listStores}). The store must be closed:
26
+ * an open store holds the directory's Web Lock and the removal will reject with `SqlitePoolBusyError`.
27
+ */ export async function deleteStore(effectiveName) {
28
+ await deletePoolDirectory(storePoolDirectory(effectiveName));
29
+ }
30
+ /** Permanently deletes one OPFS SAH-pool directory after exclusively locking it. */ export async function deletePoolDirectory(poolDirectory) {
31
+ poolDirectory = normalizePoolDirectory(poolDirectory);
32
+ await withPoolLock(poolDirectory, async ()=>{
33
+ const root = await navigator.storage.getDirectory();
34
+ await root.removeEntry(poolDirectory, {
35
+ recursive: true
36
+ });
37
+ });
38
+ }
@@ -0,0 +1,20 @@
1
+ export declare const OPFS_QUARANTINE_ROOT_DIRECTORY = ".aztec-sqlite-quarantine";
2
+ export interface DuplicatePoolAssociation {
3
+ logicalPath: string;
4
+ opaqueFileNames: string[];
5
+ }
6
+ export interface PoolQuarantineMetadata {
7
+ formatVersion: 1;
8
+ originalPoolDirectory: string;
9
+ quarantinedAt: string;
10
+ duplicateAssociations: DuplicatePoolAssociation[];
11
+ }
12
+ export interface PoolQuarantineResult extends PoolQuarantineMetadata {
13
+ quarantineDirectory: string;
14
+ }
15
+ /**
16
+ * Detects duplicate SAH logical-file associations and, if found, copies the complete pool into quarantine before
17
+ * removing the original. The caller must hold the pool's exclusive Web Lock for the whole operation.
18
+ */
19
+ export declare function quarantineDuplicatePool(poolDirectory: string): Promise<PoolQuarantineResult | undefined>;
20
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9vbF9pbnRlZ3JpdHkuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zcWxpdGUtb3Bmcy9wb29sX2ludGVncml0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUF5Q0EsZUFBTyxNQUFNLDhCQUE4Qiw2QkFBNkIsQ0FBQztBQUV6RSxNQUFNLFdBQVcsd0JBQXdCO0lBQ3ZDLFdBQVcsRUFBRSxNQUFNLENBQUM7SUFDcEIsZUFBZSxFQUFFLE1BQU0sRUFBRSxDQUFDO0NBQzNCO0FBRUQsTUFBTSxXQUFXLHNCQUFzQjtJQUNyQyxhQUFhLEVBQUUsQ0FBQyxDQUFDO0lBQ2pCLHFCQUFxQixFQUFFLE1BQU0sQ0FBQztJQUM5QixhQUFhLEVBQUUsTUFBTSxDQUFDO0lBQ3RCLHFCQUFxQixFQUFFLHdCQUF3QixFQUFFLENBQUM7Q0FDbkQ7QUFFRCxNQUFNLFdBQVcsb0JBQXFCLFNBQVEsc0JBQXNCO0lBQ2xFLG1CQUFtQixFQUFFLE1BQU0sQ0FBQztDQUM3QjtBQUVEOzs7R0FHRztBQUNILHdCQUFzQix1QkFBdUIsQ0FBQyxhQUFhLEVBQUUsTUFBTSxHQUFHLE9BQU8sQ0FBQyxvQkFBb0IsR0FBRyxTQUFTLENBQUMsQ0E2QzlHIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pool_integrity.d.ts","sourceRoot":"","sources":["../../src/sqlite-opfs/pool_integrity.ts"],"names":[],"mappings":"AAyCA,eAAO,MAAM,8BAA8B,6BAA6B,CAAC;AAEzE,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED,MAAM,WAAW,sBAAsB;IACrC,aAAa,EAAE,CAAC,CAAC;IACjB,qBAAqB,EAAE,MAAM,CAAC;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,qBAAqB,EAAE,wBAAwB,EAAE,CAAC;CACnD;AAED,MAAM,WAAW,oBAAqB,SAAQ,sBAAsB;IAClE,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,SAAS,CAAC,CA6C9G"}
@@ -0,0 +1,282 @@
1
+ import { normalizePoolDirectory } from './pool_lock.js';
2
+ // The constants below mirror the opaque-file header format of the pinned opfs-sahpool VFS
3
+ // (`yarn-project/sqlite3mc-wasm/vendor/jswasm/sqlite3.mjs`, class `OpfsSAHPool`). The pool names its files randomly
4
+ // under `.opaque/` and prepends a header that maps each one back to its logical SQLite path:
5
+ //
6
+ // bytes [0, 512) logical path, NUL-terminated UTF-8 (HEADER_MAX_PATH_SIZE)
7
+ // bytes [512, 516) SQLite open-flags of the file, big-endian uint32 (HEADER_FLAGS_SIZE)
8
+ // bytes [516, 524) digest over the preceding 516 bytes, two uint32 words (HEADER_DIGEST_SIZE)
9
+ //
10
+ // Database content starts at byte 4096 (the pool's SECTOR_SIZE). We re-read the header ourselves rather than asking
11
+ // the VFS because the upstream pool "repairs" anything it cannot validate by disassociating the file — destroying
12
+ // exactly the evidence this module exists to quarantine. The browser regression test writes a real pool through the
13
+ // pinned VFS before duplicating an opaque file, so a vendor upgrade that changes the layout breaks detection loudly
14
+ // rather than silently.
15
+ const OPAQUE_DIRECTORY = '.opaque';
16
+ const HEADER_MAX_PATH_SIZE = 512;
17
+ const HEADER_FLAGS_SIZE = 4;
18
+ const HEADER_DIGEST_SIZE = 8;
19
+ const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
20
+ const HEADER_SIZE = HEADER_CORPUS_SIZE + HEADER_DIGEST_SIZE;
21
+ // Standard SQLite open-flag bit values (sqlite3.h). Restated as literals because the header stores them numerically
22
+ // and this module runs on the main thread, without the sqlite3 WASM bundle that defines `capi.SQLITE_OPEN_*`.
23
+ const SQLITE_OPEN_DELETEONCLOSE = 0x00000008;
24
+ const SQLITE_OPEN_MEMORY = 0x00000080;
25
+ const SQLITE_OPEN_MAIN_DB = 0x00000100;
26
+ const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800;
27
+ const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000;
28
+ const SQLITE_OPEN_WAL = 0x00080000;
29
+ // A live association must name one of the file types the pool persists; transient types (temp DBs, statement
30
+ // journals) never survive in a valid header.
31
+ const PERSISTENT_FILE_TYPES = SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_SUPER_JOURNAL | SQLITE_OPEN_WAL;
32
+ // The upstream VFS repurposes SQLITE_OPEN_MEMORY — meaningless for a file that exists on disk — as a header version
33
+ // marker: headers written with it set carry a real digest, while legacy headers leave it unset and store all-zero
34
+ // digest words.
35
+ const FLAG_COMPUTE_DIGEST_V2 = SQLITE_OPEN_MEMORY;
36
+ export const OPFS_QUARANTINE_ROOT_DIRECTORY = '.aztec-sqlite-quarantine';
37
+ /**
38
+ * Detects duplicate SAH logical-file associations and, if found, copies the complete pool into quarantine before
39
+ * removing the original. The caller must hold the pool's exclusive Web Lock for the whole operation.
40
+ */ export async function quarantineDuplicatePool(poolDirectory) {
41
+ poolDirectory = normalizePoolDirectory(poolDirectory);
42
+ const root = await navigator.storage.getDirectory();
43
+ const source = await getDirectory(root, poolDirectory);
44
+ if (!source) {
45
+ return undefined;
46
+ }
47
+ const opaque = await getChildDirectory(source, OPAQUE_DIRECTORY);
48
+ if (!opaque) {
49
+ return undefined;
50
+ }
51
+ const duplicateAssociations = await findDuplicateAssociations(opaque);
52
+ if (duplicateAssociations.length === 0) {
53
+ return undefined;
54
+ }
55
+ const quarantineRoot = await root.getDirectoryHandle(OPFS_QUARANTINE_ROOT_DIRECTORY, {
56
+ create: true
57
+ });
58
+ const quarantineName = createQuarantineName();
59
+ const destination = await quarantineRoot.getDirectoryHandle(quarantineName, {
60
+ create: true
61
+ });
62
+ const metadata = {
63
+ formatVersion: 1,
64
+ originalPoolDirectory: poolDirectory,
65
+ quarantinedAt: new Date().toISOString(),
66
+ duplicateAssociations
67
+ };
68
+ let quarantineComplete = false;
69
+ try {
70
+ await copyDirectory(source, destination);
71
+ await verifyDirectoryCopy(source, destination);
72
+ await writeJson(destination, 'quarantine.json', metadata);
73
+ quarantineComplete = true;
74
+ await removeDirectory(root, poolDirectory);
75
+ } catch (err) {
76
+ if (!quarantineComplete) {
77
+ await quarantineRoot.removeEntry(quarantineName, {
78
+ recursive: true
79
+ }).catch(()=>{});
80
+ }
81
+ throw err;
82
+ }
83
+ return {
84
+ ...metadata,
85
+ quarantineDirectory: `${OPFS_QUARANTINE_ROOT_DIRECTORY}/${quarantineName}`
86
+ };
87
+ }
88
+ async function findDuplicateAssociations(opaque) {
89
+ const associations = new Map();
90
+ for await (const [opaqueName, handle] of opaque.entries()){
91
+ if (handle.kind !== 'file') {
92
+ continue;
93
+ }
94
+ const logicalPath = await readAssociatedPath(handle);
95
+ if (logicalPath) {
96
+ const names = associations.get(logicalPath) ?? [];
97
+ names.push(opaqueName);
98
+ associations.set(logicalPath, names);
99
+ }
100
+ }
101
+ return [
102
+ ...associations.entries()
103
+ ].filter(([, names])=>names.length > 1).map(([logicalPath, opaqueFileNames])=>({
104
+ logicalPath,
105
+ opaqueFileNames: opaqueFileNames.sort()
106
+ })).sort((a, b)=>a.logicalPath.localeCompare(b.logicalPath));
107
+ }
108
+ /**
109
+ * Returns the logical SQLite path an opaque SAH file is associated with, or undefined if the file is not a live,
110
+ * valid association. Applies the same checks as the vendored pool's `getAssociatedPath`: a non-empty NUL-terminated
111
+ * path, open-flags naming a persistent file type without DELETEONCLOSE, and a matching header digest. Files failing
112
+ * any check are the pool's free-list or garbage entries — the VFS itself would disassociate them on open — so they
113
+ * cannot participate in a duplicate mapping.
114
+ */ async function readAssociatedPath(handle) {
115
+ const file = await handle.getFile();
116
+ if (file.size < HEADER_SIZE) {
117
+ return undefined;
118
+ }
119
+ const header = new Uint8Array(await file.slice(0, HEADER_SIZE).arrayBuffer());
120
+ const pathEnd = header.subarray(0, HEADER_MAX_PATH_SIZE).indexOf(0);
121
+ if (pathEnd <= 0) {
122
+ return undefined;
123
+ }
124
+ const dataView = new DataView(header.buffer, header.byteOffset, header.byteLength);
125
+ const flags = dataView.getUint32(HEADER_MAX_PATH_SIZE);
126
+ if ((flags & SQLITE_OPEN_DELETEONCLOSE) !== 0 || (flags & PERSISTENT_FILE_TYPES) === 0) {
127
+ return undefined;
128
+ }
129
+ if (!hasValidDigest(header, flags)) {
130
+ return undefined;
131
+ }
132
+ try {
133
+ return new TextDecoder('utf-8', {
134
+ fatal: true
135
+ }).decode(header.subarray(0, pathEnd));
136
+ } catch {
137
+ return undefined;
138
+ }
139
+ }
140
+ /**
141
+ * Byte-for-byte port of the vendored pool's `computeDigest`, checked against the digest words stored in the header.
142
+ */ function hasValidDigest(header, flags) {
143
+ let expected0 = 0;
144
+ let expected1 = 0;
145
+ if ((flags & FLAG_COMPUTE_DIGEST_V2) !== 0) {
146
+ // These seeds (0xdeadbeef, 0x41c6ce57) and odd multipliers (2654435761, 104729) are the upstream author's choices
147
+ // (a cyrb53-hash variant) and carry no meaning here beyond having to match the vendored implementation bit for
148
+ // bit.
149
+ expected0 = 0xdeadbeef;
150
+ expected1 = 0x41c6ce57;
151
+ for (const value of header.subarray(0, HEADER_CORPUS_SIZE)){
152
+ expected0 = Math.imul(expected0 ^ value, 2654435761);
153
+ expected1 = Math.imul(expected1 ^ value, 104729);
154
+ }
155
+ expected0 >>>= 0;
156
+ expected1 >>>= 0;
157
+ }
158
+ const dataView = new DataView(header.buffer, header.byteOffset, header.byteLength);
159
+ return dataView.getUint32(HEADER_CORPUS_SIZE, true) === expected0 && dataView.getUint32(HEADER_CORPUS_SIZE + 4, true) === expected1;
160
+ }
161
+ async function getDirectory(root, path) {
162
+ let current = root;
163
+ try {
164
+ for (const segment of path.split('/')){
165
+ current = await current.getDirectoryHandle(segment);
166
+ }
167
+ return current;
168
+ } catch (err) {
169
+ if (err instanceof DOMException && err.name === 'NotFoundError') {
170
+ return undefined;
171
+ }
172
+ throw err;
173
+ }
174
+ }
175
+ async function getChildDirectory(parent, name) {
176
+ try {
177
+ return await parent.getDirectoryHandle(name);
178
+ } catch (err) {
179
+ if (err instanceof DOMException && err.name === 'NotFoundError') {
180
+ return undefined;
181
+ }
182
+ throw err;
183
+ }
184
+ }
185
+ async function removeDirectory(root, path) {
186
+ const segments = path.split('/');
187
+ const name = segments.pop();
188
+ let parent = root;
189
+ for (const segment of segments){
190
+ parent = await parent.getDirectoryHandle(segment);
191
+ }
192
+ await parent.removeEntry(name, {
193
+ recursive: true
194
+ });
195
+ }
196
+ async function copyDirectory(source, destination) {
197
+ for await (const [name, handle] of source.entries()){
198
+ if (handle.kind === 'directory') {
199
+ const childDestination = await destination.getDirectoryHandle(name, {
200
+ create: true
201
+ });
202
+ await copyDirectory(handle, childDestination);
203
+ continue;
204
+ }
205
+ const sourceFile = await handle.getFile();
206
+ const destinationHandle = await destination.getFileHandle(name, {
207
+ create: true
208
+ });
209
+ const writable = await destinationHandle.createWritable();
210
+ try {
211
+ await writable.write(sourceFile);
212
+ await writable.close();
213
+ } catch (err) {
214
+ await writable.abort().catch(()=>{});
215
+ throw err;
216
+ }
217
+ }
218
+ }
219
+ async function verifyDirectoryCopy(source, destination) {
220
+ const sourceEntries = await getSortedEntries(source);
221
+ const destinationEntries = await getSortedEntries(destination);
222
+ if (sourceEntries.length !== destinationEntries.length || sourceEntries.some(([name, handle], index)=>{
223
+ const destinationEntry = destinationEntries[index];
224
+ return name !== destinationEntry[0] || handle.kind !== destinationEntry[1].kind;
225
+ })) {
226
+ throw new Error('Failed to verify quarantined OPFS directory structure');
227
+ }
228
+ for(let i = 0; i < sourceEntries.length; i++){
229
+ const [, sourceHandle] = sourceEntries[i];
230
+ const [, destinationHandle] = destinationEntries[i];
231
+ if (sourceHandle.kind === 'directory') {
232
+ await verifyDirectoryCopy(sourceHandle, destinationHandle);
233
+ } else {
234
+ await verifyFilesEqual(sourceHandle, destinationHandle);
235
+ }
236
+ }
237
+ }
238
+ async function getSortedEntries(directory) {
239
+ const entries = [];
240
+ for await (const entry of directory.entries()){
241
+ entries.push(entry);
242
+ }
243
+ return entries.sort(([a], [b])=>a.localeCompare(b));
244
+ }
245
+ async function verifyFilesEqual(sourceHandle, destinationHandle) {
246
+ const source = await sourceHandle.getFile();
247
+ const destination = await destinationHandle.getFile();
248
+ if (source.size !== destination.size) {
249
+ throw new Error(`Failed to verify quarantined OPFS file "${source.name}"`);
250
+ }
251
+ const chunkSize = 1024 * 1024;
252
+ for(let offset = 0; offset < source.size; offset += chunkSize){
253
+ const [sourceChunk, destinationChunk] = await Promise.all([
254
+ source.slice(offset, offset + chunkSize).arrayBuffer(),
255
+ destination.slice(offset, offset + chunkSize).arrayBuffer()
256
+ ]);
257
+ const sourceBytes = new Uint8Array(sourceChunk);
258
+ const destinationBytes = new Uint8Array(destinationChunk);
259
+ if (sourceBytes.some((value, index)=>value !== destinationBytes[index])) {
260
+ throw new Error(`Failed to verify quarantined OPFS file "${source.name}"`);
261
+ }
262
+ }
263
+ }
264
+ async function writeJson(directory, name, value) {
265
+ const handle = await directory.getFileHandle(name, {
266
+ create: true
267
+ });
268
+ const writable = await handle.createWritable();
269
+ try {
270
+ await writable.write(JSON.stringify(value, undefined, 2));
271
+ await writable.close();
272
+ } catch (err) {
273
+ await writable.abort().catch(()=>{});
274
+ throw err;
275
+ }
276
+ }
277
+ function createQuarantineName() {
278
+ const random = globalThis.crypto.getRandomValues(new Uint8Array(8));
279
+ return `${Date.now()}-${[
280
+ ...random
281
+ ].map((byte)=>byte.toString(16).padStart(2, '0')).join('')}`;
282
+ }
@@ -0,0 +1,8 @@
1
+ export declare const DEFAULT_SAH_POOL_DIRECTORY = ".aztec-kv";
2
+ export interface PoolLockLease {
3
+ release(): Promise<void>;
4
+ }
5
+ export declare function normalizePoolDirectory(poolDirectory?: string): string;
6
+ export declare function acquirePoolLock(poolDirectory?: string): Promise<PoolLockLease>;
7
+ export declare function withPoolLock<T>(poolDirectory: string, callback: () => Promise<T>): Promise<T>;
8
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9vbF9sb2NrLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc3FsaXRlLW9wZnMvcG9vbF9sb2NrLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUVBLGVBQU8sTUFBTSwwQkFBMEIsY0FBYyxDQUFDO0FBSXRELE1BQU0sV0FBVyxhQUFhO0lBQzVCLE9BQU8sSUFBSSxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7Q0FDMUI7QUFFRCx3QkFBZ0Isc0JBQXNCLENBQUMsYUFBYSxDQUFDLEVBQUUsTUFBTSxHQUFHLE1BQU0sQ0FNckU7QUFFRCx3QkFBc0IsZUFBZSxDQUFDLGFBQWEsQ0FBQyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBQUMsYUFBYSxDQUFDLENBa0NwRjtBQUVELHdCQUFzQixZQUFZLENBQUMsQ0FBQyxFQUFFLGFBQWEsRUFBRSxNQUFNLEVBQUUsUUFBUSxFQUFFLE1BQU0sT0FBTyxDQUFDLENBQUMsQ0FBQyxHQUFHLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FPbkcifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pool_lock.d.ts","sourceRoot":"","sources":["../../src/sqlite-opfs/pool_lock.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,cAAc,CAAC;AAItD,MAAM,WAAW,aAAa;IAC5B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,wBAAgB,sBAAsB,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAMrE;AAED,wBAAsB,eAAe,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAkCpF;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOnG"}
@@ -0,0 +1,47 @@
1
+ import { SqlitePoolBusyError, SqliteWebLocksUnavailableError } from './errors.js';
2
+ export const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
3
+ const WEB_LOCK_PREFIX = 'aztec.sqlite-opfs.pool:';
4
+ export function normalizePoolDirectory(poolDirectory) {
5
+ const path = poolDirectory?.split('/').filter((segment)=>segment.length > 0).join('/');
6
+ return path || DEFAULT_SAH_POOL_DIRECTORY;
7
+ }
8
+ export async function acquirePoolLock(poolDirectory) {
9
+ if (!navigator.locks) {
10
+ throw new SqliteWebLocksUnavailableError();
11
+ }
12
+ const normalizedDirectory = normalizePoolDirectory(poolDirectory);
13
+ const acquired = Promise.withResolvers();
14
+ const hold = Promise.withResolvers();
15
+ const request = navigator.locks.request(`${WEB_LOCK_PREFIX}${normalizedDirectory}`, {
16
+ mode: 'exclusive',
17
+ ifAvailable: true
18
+ }, async (lock)=>{
19
+ acquired.resolve(lock);
20
+ if (lock) {
21
+ await hold.promise;
22
+ }
23
+ });
24
+ request.catch(acquired.reject);
25
+ if (!await acquired.promise) {
26
+ await request;
27
+ throw new SqlitePoolBusyError(normalizedDirectory);
28
+ }
29
+ let released = false;
30
+ return {
31
+ release: async ()=>{
32
+ if (!released) {
33
+ released = true;
34
+ hold.resolve();
35
+ }
36
+ await request;
37
+ }
38
+ };
39
+ }
40
+ export async function withPoolLock(poolDirectory, callback) {
41
+ const lease = await acquirePoolLock(poolDirectory);
42
+ try {
43
+ return await callback();
44
+ } finally{
45
+ await lease.release();
46
+ }
47
+ }