@tallyui/storage-sqlite 0.2.0 → 3.0.0-next.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.
@@ -0,0 +1,71 @@
1
+ import { RxStorage } from 'rxdb';
2
+
3
+ /**
4
+ * Thrown by the web SQLite worker's storage (ADR-061) when start-up failed
5
+ * with OPFS reachable: another tab holds the opfs-sahpool database, or an
6
+ * unexpected failure. Keeps the original failure as `cause`, and its name
7
+ * and message in this error's message.
8
+ *
9
+ * RxDB's remote-storage channel re-throws a rejected `createStorageInstance`
10
+ * on the main thread as a plain `Error` whose message embeds the original
11
+ * error's `name` as JSON, since `name` itself does not survive the trip.
12
+ * `isStorageWorkerStartError` matches that fixed substring in the message
13
+ * too, for whichever of the error, a `{ name, message }` copy, or the
14
+ * message alone actually arrives.
15
+ */
16
+ declare class StorageWorkerStartError extends Error {
17
+ constructor(message: string, options?: {
18
+ cause?: unknown;
19
+ });
20
+ }
21
+ /**
22
+ * Thrown by the worker's storage when the browser gives it no usable OPFS, as in a Safari private window (#293):
23
+ * `getDirectory()` fails or sync access handles are missing. Closing tabs or reloading can't help, so its message,
24
+ * which carries its name like `StorageWorkerStartError`'s, never contains `StorageWorkerStartError`.
25
+ */
26
+ declare class StorageUnavailableError extends Error {
27
+ constructor(message: string, options?: {
28
+ cause?: unknown;
29
+ });
30
+ }
31
+ /**
32
+ * True for the held `StorageWorkerStartError` (another tab holds the database), its `{ name, message }` copy or its
33
+ * message; false for any other start failure, a stale worker (RM1) or storage unavailable.
34
+ */
35
+ declare function isStorageHeldError(error: unknown): boolean;
36
+ /** True for a `StorageUnavailableError`, its `{ name, message }` copy or its message (see above). */
37
+ declare function isStorageUnavailableError(error: unknown): boolean;
38
+
39
+ /**
40
+ * True for a `StorageWorkerStartError`, its `{ name, message }` copy or its
41
+ * message (see ./errors), and for RxDB's RM1: a stale worker is a failed
42
+ * start too, and reloading loads the matching worker. False for a
43
+ * `StorageUnavailableError`, whose message never names this error.
44
+ * It means "any failed start": to choose wording, an app maps the three
45
+ * specific predicates instead: `isStorageUnavailableError`,
46
+ * `isStorageHeldError`, and `isRxdbRemoteVersionMismatch` (@tallyui/core).
47
+ */
48
+ declare function isStorageWorkerStartError(error: unknown): boolean;
49
+
50
+ /** Marks a storage as this package's web engine (ADR-061), for job 2b to recognise. */
51
+ declare const SQLITE_SAHPOOL_ENGINE = "sqlite-sahpool";
52
+ /** The web storage, with `terminate()` for the live-tab park order (ADR-061, amendment 1). */
53
+ type RxStorageSQLiteWasm = RxStorage<any, any> & {
54
+ tallyEngine: string;
55
+ /**
56
+ * Terminates the storage worker, which releases the opfs-sahpool access
57
+ * handles, and evicts its channel from rxdb's cache, so a new storage built
58
+ * the same way starts a fresh worker. Call it after the databases close.
59
+ * Idempotent. Build one storage per page life (ADR-061): a second storage
60
+ * from the same input while the first is alive shares its worker, and only
61
+ * the storage that created the worker can terminate it.
62
+ */
63
+ terminate(): void;
64
+ };
65
+ /** The web storage (ADR-061): premium SQLite on sqlite-wasm opfs-sahpool, in one dedicated worker. */
66
+ declare function getRxStorageSQLiteWasm(options: {
67
+ workerInput: string | URL | (() => Worker);
68
+ workerName?: string;
69
+ }): RxStorageSQLiteWasm;
70
+
71
+ export { type RxStorageSQLiteWasm, SQLITE_SAHPOOL_ENGINE, StorageUnavailableError, StorageWorkerStartError, getRxStorageSQLiteWasm, isStorageHeldError, isStorageUnavailableError, isStorageWorkerStartError };
@@ -0,0 +1,62 @@
1
+ import {
2
+ StorageUnavailableError,
3
+ StorageWorkerStartError,
4
+ isStorageHeldError,
5
+ isStorageUnavailableError
6
+ } from "../chunk-3OYD5CSS.js";
7
+
8
+ // src/web/index.ts
9
+ import { MESSAGE_CHANNEL_CACHE_BY_IDENTIFIER, OPEN_REMOTE_MESSAGE_CHANNELS } from "rxdb/plugins/storage-remote";
10
+ import { setPremiumFlag } from "rxdb-premium/plugins/shared";
11
+ import { getRxStorageWorker } from "rxdb-premium/plugins/storage-worker";
12
+
13
+ // src/web/is-storage-worker-start-error.ts
14
+ import { isRxdbRemoteVersionMismatch } from "@tallyui/core";
15
+ function isStorageWorkerStartError(error) {
16
+ if (isRxdbRemoteVersionMismatch(error)) return true;
17
+ if (typeof error === "string") return error.includes("StorageWorkerStartError");
18
+ if (!error || typeof error !== "object") return false;
19
+ const { name, message } = error;
20
+ return name === "StorageWorkerStartError" || typeof message === "string" && message.includes("StorageWorkerStartError");
21
+ }
22
+
23
+ // src/web/index.ts
24
+ setPremiumFlag();
25
+ var SQLITE_SAHPOOL_ENGINE = "sqlite-sahpool";
26
+ function getRxStorageSQLiteWasm(options) {
27
+ setPremiumFlag();
28
+ const { workerInput } = options;
29
+ const workerOptions = { type: "module", name: options.workerName ?? "tallyui-storage" };
30
+ let worker;
31
+ const createWorker = () => worker = typeof workerInput === "function" ? workerInput() : new Worker(workerInput, workerOptions);
32
+ createWorker.toString = () => String(workerInput);
33
+ const storage = getRxStorageWorker({ workerInput: createWorker, workerOptions, mode: "one" });
34
+ let terminated = false;
35
+ return Object.assign(storage, {
36
+ tallyEngine: SQLITE_SAHPOOL_ENGINE,
37
+ terminate() {
38
+ if (terminated) return;
39
+ terminated = true;
40
+ worker?.terminate();
41
+ const channel = storage.messageChannelIfOneMode;
42
+ const cache = MESSAGE_CHANNEL_CACHE_BY_IDENTIFIER.get(storage.settings.identifier);
43
+ cache?.forEach((item, key) => {
44
+ if (item.messageChannel === channel) cache.delete(key);
45
+ });
46
+ void channel?.then((open) => {
47
+ OPEN_REMOTE_MESSAGE_CHANNELS.delete(open);
48
+ return open.close();
49
+ }).catch(() => {
50
+ });
51
+ }
52
+ });
53
+ }
54
+ export {
55
+ SQLITE_SAHPOOL_ENGINE,
56
+ StorageUnavailableError,
57
+ StorageWorkerStartError,
58
+ getRxStorageSQLiteWasm,
59
+ isStorageHeldError,
60
+ isStorageUnavailableError,
61
+ isStorageWorkerStartError
62
+ };
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,106 @@
1
+ import {
2
+ sqliteBoolParams
3
+ } from "../chunk-LBITF2LV.js";
4
+ import {
5
+ STORAGE_HELD_MARKER,
6
+ StorageUnavailableError,
7
+ StorageWorkerStartError
8
+ } from "../chunk-3OYD5CSS.js";
9
+
10
+ // src/web/worker.ts
11
+ import sqlite3InitModule from "@sqlite.org/sqlite-wasm";
12
+ import { setPremiumFlag } from "rxdb-premium/plugins/shared";
13
+ import { getRxStorageSQLite } from "rxdb-premium/plugins/storage-sqlite";
14
+ import { exposeWorkerRxStorage } from "rxdb-premium/plugins/storage-worker";
15
+
16
+ // src/web/sqlite-basics-sahpool.ts
17
+ function getSQLiteBasicsOpfsSahPool({ openDb }) {
18
+ const handles = /* @__PURE__ */ new Map();
19
+ const namesByHandle = /* @__PURE__ */ new Map();
20
+ return {
21
+ debugId: "tallyui-sqlite-sahpool",
22
+ journalMode: "WAL",
23
+ open: async (name2) => {
24
+ const cached = handles.get(name2);
25
+ if (cached !== void 0) {
26
+ return cached;
27
+ }
28
+ const opening = (async () => {
29
+ const db = await openDb(name2);
30
+ db.exec({ sql: "PRAGMA locking_mode = exclusive" });
31
+ namesByHandle.set(db, name2);
32
+ return db;
33
+ })();
34
+ handles.set(name2, opening);
35
+ return opening;
36
+ },
37
+ all: async (db, q) => {
38
+ return db.exec({
39
+ sql: q.query,
40
+ bind: sqliteBoolParams(q.params),
41
+ rowMode: "object",
42
+ returnValue: "resultRows"
43
+ });
44
+ },
45
+ run: async (db, q) => {
46
+ db.exec({ sql: q.query, bind: sqliteBoolParams(q.params) });
47
+ },
48
+ setPragma: async (db, key, value) => {
49
+ db.exec({ sql: `pragma ${key} = ${value};` });
50
+ },
51
+ close: async (db) => {
52
+ const name2 = namesByHandle.get(db);
53
+ if (name2 !== void 0) {
54
+ handles.delete(name2);
55
+ namesByHandle.delete(db);
56
+ }
57
+ db.close();
58
+ }
59
+ };
60
+ }
61
+
62
+ // src/web/worker.ts
63
+ var HELD_ERROR_NAMES = ["InvalidStateError", "NoModificationAllowedError"];
64
+ var describeCause = (cause) => cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
65
+ async function requireOpfs() {
66
+ try {
67
+ const handle = globalThis.FileSystemFileHandle?.prototype ?? {};
68
+ if (!("createSyncAccessHandle" in handle)) throw new TypeError("FileSystemFileHandle.createSyncAccessHandle is missing");
69
+ await navigator.storage.getDirectory();
70
+ } catch (cause) {
71
+ const why = `this browser gives the page no OPFS storage (a private window?): ${describeCause(cause)}`;
72
+ throw new StorageUnavailableError(`StorageUnavailableError: ${why}`, { cause });
73
+ }
74
+ }
75
+ setPremiumFlag();
76
+ var { name, rxdbVersion } = getRxStorageSQLite({
77
+ sqliteBasics: getSQLiteBasicsOpfsSahPool({ openDb: () => Promise.reject(new Error("unused: throwaway instance")) })
78
+ });
79
+ var ready = Promise.all([sqlite3InitModule(), requireOpfs()]).then(([sqlite3]) => sqlite3.installOpfsSAHPoolVfs({ name: "tallyui", initialCapacity: 64 })).then(
80
+ (pool) => getRxStorageSQLite({
81
+ sqliteBasics: getSQLiteBasicsOpfsSahPool({
82
+ // The OO1 `exec()` here is the real, overloaded sqlite-wasm signature;
83
+ // `Oo1Db` is the minimal shape this package's adapters need from it.
84
+ openDb: async (dbName) => new pool.OpfsSAHPoolDb("/" + dbName)
85
+ })
86
+ })
87
+ );
88
+ ready.catch(() => {
89
+ });
90
+ var storage = {
91
+ name,
92
+ rxdbVersion,
93
+ createStorageInstance: async (params) => {
94
+ let realStorage;
95
+ try {
96
+ realStorage = await ready;
97
+ } catch (cause) {
98
+ if (cause instanceof StorageUnavailableError) throw cause;
99
+ const held = HELD_ERROR_NAMES.includes(cause?.name ?? "");
100
+ const what = held ? `${STORAGE_HELD_MARKER} (opfs-sahpool)` : "SQLite worker start failed";
101
+ throw new StorageWorkerStartError(`StorageWorkerStartError: ${what}: ${describeCause(cause)}`, { cause });
102
+ }
103
+ return realStorage.createStorageInstance(params);
104
+ }
105
+ };
106
+ exposeWorkerRxStorage({ storage });
package/package.json CHANGED
@@ -1,33 +1,72 @@
1
1
  {
2
2
  "name": "@tallyui/storage-sqlite",
3
- "version": "0.2.0",
3
+ "version": "3.0.0-next.0",
4
4
  "type": "module",
5
- "description": "RxDB storage adapter for SQLite via expo-sqlite",
5
+ "description": "RxDB Premium SQLite storage for a synchronous SQLite handle (expo-sqlite)",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "source": "./src/index.ts",
9
+ "bin": {
10
+ "tallyui-build-sqlite-worker": "./scripts/build-web-worker.mjs"
11
+ },
9
12
  "exports": {
10
13
  ".": {
11
14
  "types": "./dist/index.d.ts",
12
15
  "import": "./dist/index.js",
13
16
  "source": "./src/index.ts"
17
+ },
18
+ "./web": {
19
+ "types": "./dist/web/index.d.ts",
20
+ "import": "./dist/web/index.js",
21
+ "source": "./src/web/index.ts"
22
+ },
23
+ "./web-worker": {
24
+ "types": "./dist/web/worker.d.ts",
25
+ "import": "./dist/web/worker.js",
26
+ "source": "./src/web/worker.ts"
14
27
  }
15
28
  },
16
29
  "files": [
17
30
  "dist",
18
- "src"
31
+ "src",
32
+ "!src/**/*.test.ts",
33
+ "!src/**/*.test-helper.ts",
34
+ "scripts/*.mjs"
19
35
  ],
20
36
  "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/TallyUI/tallyui.git",
40
+ "directory": "packages/storage-sqlite"
41
+ },
21
42
  "dependencies": {
22
- "rxdb": "16.21.1",
43
+ "rxdb": "17.5.0",
23
44
  "rxjs": "7.8.2"
24
45
  },
46
+ "devDependencies": {
47
+ "@sqlite.org/sqlite-wasm": "3.53.4-build1",
48
+ "@tallyui/core": "^3.0.0-next.0",
49
+ "esbuild": "0.27.3",
50
+ "expo-sqlite": "16.0.10",
51
+ "rxdb-premium": "17.5.0"
52
+ },
25
53
  "peerDependencies": {
26
- "expo-sqlite": ">=15.0.0"
54
+ "@sqlite.org/sqlite-wasm": "^3.53.4-build1",
55
+ "@tallyui/core": "^3.0.0-next.0",
56
+ "expo-sqlite": ">=15.0.0",
57
+ "rxdb-premium": "17.5.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "@sqlite.org/sqlite-wasm": {
61
+ "optional": true
62
+ },
63
+ "expo-sqlite": {
64
+ "optional": true
65
+ }
27
66
  },
28
67
  "scripts": {
29
68
  "build": "tsup",
30
- "typecheck": "tsc --noEmit",
69
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.expo-handle.json",
31
70
  "test": "vitest run"
32
71
  }
33
72
  }
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ // Prebuilds the sqlite worker for Metro/Expo web apps, which can't bundle a
3
+ // module worker at runtime (see the package README's "Expo web (Metro)"
4
+ // section). Run this from the CONSUMING APP's own build step, e.g.
5
+ // `npx tallyui-build-sqlite-worker public/` — never in this repo. The entry
6
+ // point is this bin's own package source (src/web/worker.ts), not the
7
+ // installed '@tallyui/storage-sqlite/web-worker' export, which resolves to
8
+ // dist/web/worker.js and so wouldn't exist for a consumer that installs
9
+ // TallyUI from a raw checkout with no build step. The output bundle links
10
+ // rxdb-premium code, so it is built under, and bound by, the APP's own RXDB
11
+ // Premium licence, and it must NEVER be committed to this repo or published
12
+ // from this package.
13
+ //
14
+ // Usage: tallyui-build-sqlite-worker <outDir>
15
+
16
+ import { createRequire } from 'node:module';
17
+ import { pathToFileURL, fileURLToPath } from 'node:url';
18
+ import { mkdir, copyFile, writeFile } from 'node:fs/promises';
19
+ import path from 'node:path';
20
+
21
+ const outDir = process.argv[2];
22
+ if (!outDir) {
23
+ console.error('Usage: tallyui-build-sqlite-worker <outDir>');
24
+ process.exit(1);
25
+ }
26
+
27
+ let esbuild;
28
+ try {
29
+ ({ default: esbuild } = await import('esbuild'));
30
+ } catch {
31
+ console.error('esbuild is not installed: install esbuild as a dev dependency to use this script.');
32
+ process.exit(1);
33
+ }
34
+
35
+ const appDir = process.cwd();
36
+ const resolvedOutDir = path.resolve(appDir, outDir);
37
+ await mkdir(resolvedOutDir, { recursive: true });
38
+
39
+ const packageDir = fileURLToPath(new URL('..', import.meta.url));
40
+ const entryPath = fileURLToPath(new URL('../src/web/worker.ts', import.meta.url));
41
+ const entryRelative = path.relative(packageDir, entryPath);
42
+ const metafilePath = process.env.TALLYUI_WORKER_METAFILE;
43
+
44
+ const result = await esbuild.build({
45
+ // The entry is this bin's own package source file (src/web/worker.ts),
46
+ // resolved from the script's own location, not through the package's
47
+ // `exports`: same relative path in a raw checkout and a published
48
+ // install, and neither needs a `dist` build.
49
+ //
50
+ // Everything the entry imports (rxdb-premium, sqlite-wasm) resolves from
51
+ // the entry file's own location, as it did when the entry came through the
52
+ // package export: the installed package's dependencies, which are the
53
+ // app's own peer installs. absWorkingDir keeps output and metafile paths
54
+ // relative to the app.
55
+ absWorkingDir: appDir,
56
+ entryPoints: [entryPath],
57
+ outfile: path.join(resolvedOutDir, 'tallyui-sqlite-worker.js'),
58
+ bundle: true,
59
+ format: 'esm',
60
+ platform: 'browser',
61
+ metafile: Boolean(metafilePath),
62
+ });
63
+
64
+ if (metafilePath) {
65
+ await writeFile(metafilePath, JSON.stringify(result.metafile));
66
+ }
67
+
68
+ // sqlite-wasm's default `locateFile` resolves `sqlite3.wasm` as
69
+ // `new URL('sqlite3.wasm', import.meta.url)`, and esbuild leaves that
70
+ // `import.meta.url` untouched when bundling, so at runtime it evaluates to
71
+ // the worker's own URL. The wasm file must sit next to the built worker for
72
+ // that lookup to find it; no `locateFile` override is needed.
73
+ const require = createRequire(pathToFileURL(path.join(appDir, 'package.json')));
74
+ const wasmSource = require.resolve('@sqlite.org/sqlite-wasm/sqlite3.wasm');
75
+ await copyFile(wasmSource, path.join(resolvedOutDir, 'sqlite3.wasm'));
76
+
77
+ console.log(`Built ${path.join(resolvedOutDir, 'tallyui-sqlite-worker.js')} from ${entryRelative} and copied sqlite3.wasm.`);
@@ -0,0 +1,17 @@
1
+ import { describe, it } from 'vitest';
2
+ import type { openNodeSQLite } from './node-sqlite.test-helper';
3
+ import { getRxStorageSQLite } from './rx-storage-sqlite';
4
+
5
+ declare const nodeDatabase: ReturnType<typeof openNodeSQLite>['database'];
6
+ const missingRunSync = { execSync: () => {}, getAllSync: () => [] };
7
+
8
+ describe('SQLite handle types', () => {
9
+ it('accepts the wrapped node:sqlite handle', () => {
10
+ getRxStorageSQLite(nodeDatabase);
11
+ });
12
+
13
+ it('requires runSync', () => {
14
+ // @ts-expect-error A handle without runSync cannot execute writes.
15
+ getRxStorageSQLite(missingRunSync);
16
+ });
17
+ });
package/src/params.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * RxDB Premium's SQLite storage passes query params as
3
+ * `(string | number | boolean)[]`, but SQLite itself has no boolean type.
4
+ * Every `SQLiteBasics` implementation in this package binds params the same
5
+ * way, so booleans become `0`/`1` here once instead of in each adapter.
6
+ */
7
+ export function sqliteBoolParams(params: readonly (string | number | boolean)[]): (string | number)[] {
8
+ return params.map((param) => (typeof param === 'boolean' ? Number(param) : param));
9
+ }
@@ -1,24 +1,46 @@
1
- import type { RxStorage, RxStorageInstanceCreationParams } from 'rxdb';
2
- import { ensureRxStorageInstanceParamsAreCorrect } from 'rxdb';
3
- import { RXDB_VERSION } from 'rxdb/plugins/utils';
4
- import type { SQLiteDatabase, SQLiteStorageSettings } from './types';
5
- import {
6
- createSQLiteStorageInstance,
7
- type SQLiteStorageInternals,
8
- } from './storage-instance';
1
+ import type { RxStorage } from 'rxdb';
2
+ import type { SQLiteBasics } from 'rxdb/plugins/storage-sqlite';
3
+ import { setPremiumFlag } from 'rxdb-premium/plugins/shared';
4
+ import { getRxStorageSQLite as getPremiumRxStorageSQLite } from 'rxdb-premium/plugins/storage-sqlite';
5
+ import { sqliteBoolParams } from './params';
6
+ import type { SQLiteDatabase } from './types';
9
7
 
10
- export type RxStorageSQLite = RxStorage<SQLiteStorageInternals, SQLiteStorageSettings>;
8
+ // Also at import, before anything else can make RxDB cache the flag's first check as false.
9
+ setPremiumFlag();
11
10
 
12
- export function getRxStorageSQLite(
13
- database: SQLiteDatabase
14
- ): RxStorageSQLite {
15
- const storage: RxStorageSQLite = {
16
- name: 'sqlite',
17
- rxdbVersion: RXDB_VERSION,
18
- createStorageInstance(params: RxStorageInstanceCreationParams<any, SQLiteStorageSettings>) {
19
- ensureRxStorageInstanceParamsAreCorrect(params);
20
- return createSQLiteStorageInstance(storage, params, database);
11
+ /**
12
+ * Wraps a synchronous SQLite handle with RxDB Premium SQLite storage.
13
+ * Apps install the RxDB Premium peer dependency under their own RxDB Premium licence.
14
+ * One SQLite handle serves exactly one RxDB database.
15
+ */
16
+ export function getRxStorageSQLite(database: SQLiteDatabase): RxStorage<any, any> {
17
+ // RxDB 17 caps a process at 13 open collections unless the premium flag is
18
+ // set; premium storages do not set it themselves. RxDB caches the first
19
+ // flag check, so this must run before any collection is created.
20
+ setPremiumFlag();
21
+ let databaseName: string | undefined;
22
+ const sqliteBasics: SQLiteBasics<SQLiteDatabase> = {
23
+ debugId: 'tallyui-sqlite-sync',
24
+ journalMode: 'WAL',
25
+ open: (name) => {
26
+ if (databaseName !== undefined && databaseName !== name) {
27
+ throw new Error(`one SQLite handle serves exactly one RxDB database: "${databaseName}" and "${name}"`);
28
+ }
29
+ databaseName = name;
30
+ return Promise.resolve(database);
31
+ },
32
+ all: async (db, q) => {
33
+ return db.getAllSync(q.query, sqliteBoolParams(q.params));
34
+ },
35
+ run: async (db, q) => {
36
+ db.runSync(q.query, sqliteBoolParams(q.params));
37
+ },
38
+ setPragma: async (db, key, value) => {
39
+ db.execSync('pragma ' + key + ' = ' + value + ';');
40
+ },
41
+ close: async () => {
42
+ // The caller opened the handle and owns its lifetime.
21
43
  },
22
44
  };
23
- return storage;
45
+ return getPremiumRxStorageSQLite({ sqliteBasics });
24
46
  }
package/src/types.ts CHANGED
@@ -1,7 +1,9 @@
1
+ import type { SQLResultRow } from 'rxdb/plugins/storage-sqlite';
2
+
1
3
  export interface SQLiteDatabase {
2
4
  execSync(source: string): void;
3
- getAllSync<T>(source: string, params?: any[]): T[];
4
- runSync(source: string, params?: any[]): { changes: number; lastInsertRowId: number };
5
+ getAllSync(source: string, params: (string | number)[]): SQLResultRow[];
6
+ runSync(source: string, params: (string | number)[]): unknown;
5
7
  }
6
8
 
7
9
  export interface SQLiteStorageSettings {
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Thrown by the web SQLite worker's storage (ADR-061) when start-up failed
3
+ * with OPFS reachable: another tab holds the opfs-sahpool database, or an
4
+ * unexpected failure. Keeps the original failure as `cause`, and its name
5
+ * and message in this error's message.
6
+ *
7
+ * RxDB's remote-storage channel re-throws a rejected `createStorageInstance`
8
+ * on the main thread as a plain `Error` whose message embeds the original
9
+ * error's `name` as JSON, since `name` itself does not survive the trip.
10
+ * `isStorageWorkerStartError` matches that fixed substring in the message
11
+ * too, for whichever of the error, a `{ name, message }` copy, or the
12
+ * message alone actually arrives.
13
+ */
14
+ export class StorageWorkerStartError extends Error {
15
+ constructor(message: string, options?: { cause?: unknown }) {
16
+ super(message, options);
17
+ this.name = 'StorageWorkerStartError';
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Thrown by the worker's storage when the browser gives it no usable OPFS, as in a Safari private window (#293):
23
+ * `getDirectory()` fails or sync access handles are missing. Closing tabs or reloading can't help, so its message,
24
+ * which carries its name like `StorageWorkerStartError`'s, never contains `StorageWorkerStartError`.
25
+ */
26
+ export class StorageUnavailableError extends Error {
27
+ constructor(message: string, options?: { cause?: unknown }) {
28
+ super(message, options);
29
+ this.name = 'StorageUnavailableError';
30
+ }
31
+ }
32
+
33
+ /** The fixed text of the held `StorageWorkerStartError`'s message: the worker writes it, `isStorageHeldError` reads it. */
34
+ export const STORAGE_HELD_MARKER = 'another tab holds the database';
35
+
36
+ /**
37
+ * True for the held `StorageWorkerStartError` (another tab holds the database), its `{ name, message }` copy or its
38
+ * message; false for any other start failure, a stale worker (RM1) or storage unavailable.
39
+ */
40
+ export function isStorageHeldError(error: unknown): boolean {
41
+ const text = typeof error === 'string' ? error : (error as { message?: unknown } | null | undefined)?.message;
42
+ return typeof text === 'string' && text.includes('StorageWorkerStartError') && text.includes(STORAGE_HELD_MARKER);
43
+ }
44
+
45
+ /** True for a `StorageUnavailableError`, its `{ name, message }` copy or its message (see above). */
46
+ export function isStorageUnavailableError(error: unknown): boolean {
47
+ if (typeof error === 'string') return error.includes('StorageUnavailableError');
48
+ if (!error || typeof error !== 'object') return false;
49
+ const { name, message } = error as { name?: unknown; message?: unknown };
50
+ return name === 'StorageUnavailableError' || (typeof message === 'string' && message.includes('StorageUnavailableError'));
51
+ }
@@ -0,0 +1,71 @@
1
+ import type { RxStorage } from 'rxdb';
2
+ import { MESSAGE_CHANNEL_CACHE_BY_IDENTIFIER, OPEN_REMOTE_MESSAGE_CHANNELS } from 'rxdb/plugins/storage-remote';
3
+ import { setPremiumFlag } from 'rxdb-premium/plugins/shared';
4
+ import { getRxStorageWorker } from 'rxdb-premium/plugins/storage-worker';
5
+
6
+ export { StorageWorkerStartError, StorageUnavailableError, isStorageUnavailableError, isStorageHeldError } from './errors';
7
+ export { isStorageWorkerStartError } from './is-storage-worker-start-error';
8
+
9
+ // Also at import, before anything else can make RxDB cache the flag's first check as false.
10
+ setPremiumFlag();
11
+
12
+ /** Marks a storage as this package's web engine (ADR-061), for job 2b to recognise. */
13
+ export const SQLITE_SAHPOOL_ENGINE = 'sqlite-sahpool';
14
+
15
+ /** The web storage, with `terminate()` for the live-tab park order (ADR-061, amendment 1). */
16
+ export type RxStorageSQLiteWasm = RxStorage<any, any> & {
17
+ tallyEngine: string;
18
+ /**
19
+ * Terminates the storage worker, which releases the opfs-sahpool access
20
+ * handles, and evicts its channel from rxdb's cache, so a new storage built
21
+ * the same way starts a fresh worker. Call it after the databases close.
22
+ * Idempotent. Build one storage per page life (ADR-061): a second storage
23
+ * from the same input while the first is alive shares its worker, and only
24
+ * the storage that created the worker can terminate it.
25
+ */
26
+ terminate(): void;
27
+ };
28
+
29
+ /** The web storage (ADR-061): premium SQLite on sqlite-wasm opfs-sahpool, in one dedicated worker. */
30
+ export function getRxStorageSQLiteWasm(options: {
31
+ workerInput: string | URL | (() => Worker);
32
+ workerName?: string;
33
+ }): RxStorageSQLiteWasm {
34
+ // RxDB 17 caps a process at 13 open collections unless the premium flag is
35
+ // set; premium storages do not set it themselves. RxDB caches the first
36
+ // flag check, so this must run before any collection is created.
37
+ setPremiumFlag();
38
+ const { workerInput } = options;
39
+ const workerOptions = { type: 'module' as const, name: options.workerName ?? 'tallyui-storage' };
40
+ // Premium creates the worker inside its own closure, out of reach, so this
41
+ // creates it instead and holds the reference that terminate() needs.
42
+ let worker: Worker | undefined;
43
+ const createWorker = () =>
44
+ (worker = typeof workerInput === 'function' ? workerInput() : new Worker(workerInput, workerOptions));
45
+ // Premium's cache identifier is `'rx-storage-worker-' + workerInput`: keep
46
+ // it the caller's input, not this closure's source text.
47
+ createWorker.toString = () => String(workerInput);
48
+ const storage = getRxStorageWorker({ workerInput: createWorker, workerOptions, mode: 'one' });
49
+ let terminated = false;
50
+ return Object.assign(storage, {
51
+ tallyEngine: SQLITE_SAHPOOL_ENGINE,
52
+ terminate() {
53
+ if (terminated) return;
54
+ terminated = true;
55
+ worker?.terminate();
56
+ // Mode 'one' keeps its channel alive forever in rxdb's storage-remote
57
+ // cache, keyed by the identifier above. Left there, the next storage
58
+ // built from the same input reuses the dead channel, and every call hangs.
59
+ const channel = storage.messageChannelIfOneMode;
60
+ const cache = MESSAGE_CHANNEL_CACHE_BY_IDENTIFIER.get(storage.settings.identifier);
61
+ cache?.forEach((item, key) => {
62
+ if (item.messageChannel === channel) cache.delete(key);
63
+ });
64
+ // A worker that never started, or a close that fails, has nothing left to release.
65
+ void channel?.then((open) => {
66
+ OPEN_REMOTE_MESSAGE_CHANNELS.delete(open);
67
+ return open.close();
68
+ }).catch(() => {});
69
+ },
70
+ });
71
+ }
@@ -0,0 +1,20 @@
1
+ // Kept apart from `StorageWorkerStartError` (./errors), which the worker imports: @tallyui/core's
2
+ // main entry carries React context, and it must stay out of the worker bundle.
3
+ import { isRxdbRemoteVersionMismatch } from '@tallyui/core';
4
+
5
+ /**
6
+ * True for a `StorageWorkerStartError`, its `{ name, message }` copy or its
7
+ * message (see ./errors), and for RxDB's RM1: a stale worker is a failed
8
+ * start too, and reloading loads the matching worker. False for a
9
+ * `StorageUnavailableError`, whose message never names this error.
10
+ * It means "any failed start": to choose wording, an app maps the three
11
+ * specific predicates instead: `isStorageUnavailableError`,
12
+ * `isStorageHeldError`, and `isRxdbRemoteVersionMismatch` (@tallyui/core).
13
+ */
14
+ export function isStorageWorkerStartError(error: unknown): boolean {
15
+ if (isRxdbRemoteVersionMismatch(error)) return true;
16
+ if (typeof error === 'string') return error.includes('StorageWorkerStartError');
17
+ if (!error || typeof error !== 'object') return false;
18
+ const { name, message } = error as { name?: unknown; message?: unknown };
19
+ return name === 'StorageWorkerStartError' || (typeof message === 'string' && message.includes('StorageWorkerStartError'));
20
+ }