gathergate 0.0.0-stage → 1.0.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -2
  3. package/client/dist/assets/geist-mono-cyrillic-400-normal-C51Di1Mf.woff2 +0 -0
  4. package/client/dist/assets/geist-mono-cyrillic-400-normal-CPJFfJgk.woff +0 -0
  5. package/client/dist/assets/geist-mono-cyrillic-500-normal-D2cXvDHF.woff2 +0 -0
  6. package/client/dist/assets/geist-mono-cyrillic-500-normal-DfuvdVgn.woff +0 -0
  7. package/client/dist/assets/geist-mono-cyrillic-600-normal-Dfv53e6N.woff2 +0 -0
  8. package/client/dist/assets/geist-mono-cyrillic-600-normal-DzvMIgFZ.woff +0 -0
  9. package/client/dist/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  10. package/client/dist/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  11. package/client/dist/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  12. package/client/dist/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  13. package/client/dist/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  14. package/client/dist/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  15. package/client/dist/assets/geist-mono-latin-ext-400-normal-CfzLURNc.woff +0 -0
  16. package/client/dist/assets/geist-mono-latin-ext-400-normal-DI-rJ0UV.woff2 +0 -0
  17. package/client/dist/assets/geist-mono-latin-ext-500-normal-Buglb9-a.woff2 +0 -0
  18. package/client/dist/assets/geist-mono-latin-ext-500-normal-CrWEgvU_.woff +0 -0
  19. package/client/dist/assets/geist-mono-latin-ext-600-normal-B7ybHiTt.woff +0 -0
  20. package/client/dist/assets/geist-mono-latin-ext-600-normal-TphwrhF8.woff2 +0 -0
  21. package/client/dist/assets/geist-mono-symbols2-400-normal-DjbiTEEA.woff +0 -0
  22. package/client/dist/assets/geist-mono-symbols2-500-normal-CmnCPGa0.woff +0 -0
  23. package/client/dist/assets/geist-mono-symbols2-600-normal-D7I4D0GJ.woff +0 -0
  24. package/client/dist/assets/geist-mono-vietnamese-400-normal-CZEPLOgu.woff +0 -0
  25. package/client/dist/assets/geist-mono-vietnamese-500-normal-Dx9-epDo.woff +0 -0
  26. package/client/dist/assets/geist-mono-vietnamese-600-normal-BLL01lwa.woff +0 -0
  27. package/client/dist/assets/index-BWbZAfMJ.js +80 -0
  28. package/client/dist/assets/index-ZnG2njjK.css +2 -0
  29. package/client/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  30. package/client/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  31. package/client/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  32. package/client/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  33. package/client/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  34. package/client/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  35. package/client/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  36. package/client/dist/favicon.svg +12 -0
  37. package/client/dist/index.html +16 -0
  38. package/client/dist/site.webmanifest +16 -0
  39. package/dist/adapters/email.js +125 -0
  40. package/dist/adapters/storage.js +106 -0
  41. package/dist/app.js +2126 -0
  42. package/dist/config.js +106 -0
  43. package/dist/db/client.js +294 -0
  44. package/dist/db/queries.js +898 -0
  45. package/dist/emails/templates.js +221 -0
  46. package/dist/index.js +77 -0
  47. package/dist/jobs/chaser.js +81 -0
  48. package/dist/jobs/demo.js +329 -0
  49. package/dist/jobs/purge.js +22 -0
  50. package/dist/jobs/webhook.js +153 -0
  51. package/dist/security/auth.js +69 -0
  52. package/dist/security/crypto.js +91 -0
  53. package/dist/security/magic-bytes.js +131 -0
  54. package/dist/security/rate-limit.js +72 -0
  55. package/dist/security/ssrf.js +181 -0
  56. package/dist/templates/presets.js +341 -0
  57. package/dist/validators/index.js +52 -0
  58. package/dist/validators/packs/au.js +108 -0
  59. package/dist/validators/packs/eu.js +85 -0
  60. package/dist/validators/packs/generic.js +57 -0
  61. package/dist/validators/packs/types.js +1 -0
  62. package/dist/validators/packs/uk.js +58 -0
  63. package/dist/validators/packs/us.js +82 -0
  64. package/package.json +55 -4
package/dist/config.js ADDED
@@ -0,0 +1,106 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ export const SENSITIVE_DEFAULT_PURGE_DAYS = 14;
5
+ function parseBool(val, fallback) {
6
+ if (val === undefined || val === "")
7
+ return fallback;
8
+ return ["1", "true", "yes", "on"].includes(val.toLowerCase());
9
+ }
10
+ function parseIntSafe(val, fallback) {
11
+ if (val === undefined || val === "")
12
+ return fallback;
13
+ const parsed = Number.parseInt(val, 10);
14
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
15
+ }
16
+ function readValidatedKeyFile(filePath) {
17
+ const stored = fs.readFileSync(filePath, "utf8").trim();
18
+ if (!/^[0-9a-fA-F]{64}$/.test(stored)) {
19
+ throw new Error(`Invalid MASTER_KEY file at ${filePath}; expected 64 hex characters.`);
20
+ }
21
+ return Buffer.from(stored, "hex");
22
+ }
23
+ function resolveMasterKey(env, dataDir) {
24
+ const raw = env.MASTER_KEY?.trim();
25
+ if (raw) {
26
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
27
+ throw new Error("MASTER_KEY must be a 64-character hex string (32 bytes)");
28
+ }
29
+ return { key: Buffer.from(raw, "hex"), source: "env" };
30
+ }
31
+ // Auto-generate and persist in dataDir so single-command Docker starts cleanly; fail closed if file is corrupt.
32
+ fs.mkdirSync(dataDir, { recursive: true });
33
+ const keyFile = path.join(dataDir, ".master.key");
34
+ if (fs.existsSync(keyFile)) {
35
+ return { key: readValidatedKeyFile(keyFile), source: "file", filePath: keyFile };
36
+ }
37
+ const legacyKeyFile = path.join(dataDir, ".dev-master.key");
38
+ if (fs.existsSync(legacyKeyFile)) {
39
+ return { key: readValidatedKeyFile(legacyKeyFile), source: "file", filePath: legacyKeyFile };
40
+ }
41
+ const generated = crypto.randomBytes(32);
42
+ fs.writeFileSync(keyFile, generated.toString("hex") + "\n", { mode: 0o600 });
43
+ return { key: generated, source: "file", filePath: keyFile };
44
+ }
45
+ export function loadConfig(env = process.env) {
46
+ const dataDir = path.resolve(env.DATA_DIR || "./data");
47
+ const dbPath = env.DB_PATH || path.join(dataDir, "gathergate.sqlite");
48
+ const storageBackend = (env.STORAGE_BACKEND || "local");
49
+ const emailBackend = (env.EMAIL_BACKEND || "console");
50
+ const resolvedKey = resolveMasterKey(env, dataDir);
51
+ const config = {
52
+ port: parseIntSafe(env.PORT, 3080),
53
+ host: env.HOST || "127.0.0.1",
54
+ baseUrl: (env.BASE_URL || `http://localhost:${parseIntSafe(env.PORT, 3080)}`).replace(/\/+$/, ""),
55
+ dataDir,
56
+ dbPath,
57
+ masterKey: resolvedKey.key,
58
+ masterKeySource: resolvedKey.source,
59
+ masterKeyFilePath: resolvedKey.filePath,
60
+ trustProxy: parseBool(env.TRUST_PROXY, false),
61
+ multiTenant: parseBool(env.MULTI_TENANT, false),
62
+ freeMaxActiveRequests: parseIntSafe(env.FREE_MAX_ACTIVE_REQUESTS, 5),
63
+ freeMaxStorageBytes: parseIntSafe(env.FREE_MAX_STORAGE_BYTES, 1024 * 1024 * 1024),
64
+ storageBackend,
65
+ emailBackend,
66
+ emailFrom: env.EMAIL_FROM || "GatherGate <noreply@localhost>",
67
+ cronIntervalMinutes: parseIntSafe(env.CRON_INTERVAL_MINUTES, 15),
68
+ defaultPurgeDays: Math.max(1, parseIntSafe(env.DEFAULT_PURGE_DAYS, 30)),
69
+ nodeEnv: env.NODE_ENV || "development",
70
+ };
71
+ if (storageBackend === "s3") {
72
+ const endpoint = env.S3_ENDPOINT?.trim() || "";
73
+ const bucket = env.S3_BUCKET?.trim() || "";
74
+ const accessKeyId = env.S3_ACCESS_KEY_ID?.trim() || "";
75
+ const secretAccessKey = env.S3_SECRET_ACCESS_KEY?.trim() || "";
76
+ if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {
77
+ throw new Error("S3 storage requires S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY");
78
+ }
79
+ config.s3 = {
80
+ endpoint: endpoint.replace(/\/+$/, ""),
81
+ region: env.S3_REGION?.trim() || "auto",
82
+ bucket,
83
+ accessKeyId,
84
+ secretAccessKey,
85
+ };
86
+ }
87
+ if (emailBackend === "resend") {
88
+ const apiKey = env.RESEND_API_KEY?.trim();
89
+ if (!apiKey)
90
+ throw new Error("RESEND_API_KEY is required when EMAIL_BACKEND=resend");
91
+ config.resendApiKey = apiKey;
92
+ }
93
+ else if (emailBackend === "smtp") {
94
+ const host = env.SMTP_HOST?.trim() || "";
95
+ if (!host)
96
+ throw new Error("SMTP_HOST is required when EMAIL_BACKEND=smtp");
97
+ config.smtp = {
98
+ host,
99
+ port: parseIntSafe(env.SMTP_PORT, 587),
100
+ secure: parseBool(env.SMTP_SECURE, false),
101
+ user: env.SMTP_USER || "",
102
+ pass: env.SMTP_PASS || "",
103
+ };
104
+ }
105
+ return config;
106
+ }
@@ -0,0 +1,294 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ const PRAGMAS_SQL = `
5
+ PRAGMA journal_mode = WAL;
6
+ PRAGMA foreign_keys = ON;
7
+ PRAGMA busy_timeout = 5000;
8
+ `;
9
+ const SCHEMA_SQL = `
10
+ CREATE TABLE IF NOT EXISTS workspaces (
11
+ id TEXT PRIMARY KEY,
12
+ name TEXT NOT NULL,
13
+ slug TEXT NOT NULL UNIQUE,
14
+ plan TEXT NOT NULL DEFAULT 'self_hosted',
15
+ max_active_requests INTEGER NOT NULL DEFAULT 0,
16
+ max_storage_bytes INTEGER NOT NULL DEFAULT 0,
17
+ webhook_url TEXT,
18
+ webhook_secret TEXT,
19
+ email_backend TEXT,
20
+ email_from TEXT,
21
+ email_reply_to TEXT,
22
+ email_config_encrypted TEXT,
23
+ created_at TEXT NOT NULL
24
+ );
25
+
26
+ CREATE TABLE IF NOT EXISTS users (
27
+ id TEXT PRIMARY KEY,
28
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
29
+ email TEXT NOT NULL UNIQUE,
30
+ display_name TEXT,
31
+ password_hash TEXT NOT NULL,
32
+ created_at TEXT NOT NULL
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS sessions (
36
+ id TEXT PRIMARY KEY,
37
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
38
+ token_hash TEXT NOT NULL UNIQUE,
39
+ expires_at TEXT NOT NULL,
40
+ created_at TEXT NOT NULL
41
+ );
42
+
43
+ CREATE TABLE IF NOT EXISTS templates (
44
+ id TEXT PRIMARY KEY,
45
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
46
+ name TEXT NOT NULL,
47
+ description TEXT NOT NULL DEFAULT '',
48
+ is_builtin INTEGER NOT NULL DEFAULT 0,
49
+ items_json TEXT NOT NULL,
50
+ created_at TEXT NOT NULL
51
+ );
52
+
53
+ CREATE TABLE IF NOT EXISTS requests (
54
+ id TEXT PRIMARY KEY,
55
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
56
+ template_id TEXT REFERENCES templates(id) ON DELETE SET NULL,
57
+ title TEXT NOT NULL,
58
+ client_name TEXT NOT NULL,
59
+ client_email TEXT NOT NULL,
60
+ token_hash TEXT NOT NULL UNIQUE,
61
+ token_encrypted TEXT NOT NULL,
62
+ require_otp INTEGER NOT NULL DEFAULT 0,
63
+ status TEXT NOT NULL DEFAULT 'open',
64
+ reminder_interval_days INTEGER NOT NULL DEFAULT 3,
65
+ max_reminders INTEGER NOT NULL DEFAULT 4,
66
+ reminders_sent INTEGER NOT NULL DEFAULT 0,
67
+ reminders_paused INTEGER NOT NULL DEFAULT 0,
68
+ next_reminder_at TEXT,
69
+ purge_after_days INTEGER NOT NULL DEFAULT 30,
70
+ purge_at TEXT,
71
+ completed_at TEXT,
72
+ is_demo INTEGER NOT NULL DEFAULT 0,
73
+ due_at TEXT,
74
+ client_subject TEXT,
75
+ welcome_note TEXT,
76
+ last_opened_at TEXT,
77
+ last_manual_reminder_at TEXT,
78
+ created_at TEXT NOT NULL
79
+ );
80
+
81
+ CREATE INDEX IF NOT EXISTS idx_requests_workspace ON requests(workspace_id, created_at DESC);
82
+ CREATE INDEX IF NOT EXISTS idx_requests_reminder ON requests(status, reminders_paused, next_reminder_at);
83
+ CREATE INDEX IF NOT EXISTS idx_requests_purge ON requests(purge_at);
84
+
85
+ CREATE TABLE IF NOT EXISTS request_items (
86
+ id TEXT PRIMARY KEY,
87
+ request_id TEXT NOT NULL REFERENCES requests(id) ON DELETE CASCADE,
88
+ position INTEGER NOT NULL,
89
+ section TEXT NOT NULL DEFAULT 'General',
90
+ label TEXT NOT NULL,
91
+ help_text TEXT NOT NULL DEFAULT '',
92
+ kind TEXT NOT NULL,
93
+ required INTEGER NOT NULL DEFAULT 1,
94
+ validator TEXT NOT NULL DEFAULT 'none',
95
+ config_json TEXT NOT NULL DEFAULT '{}',
96
+ status TEXT NOT NULL DEFAULT 'pending',
97
+ value_encrypted TEXT,
98
+ review_note TEXT,
99
+ updated_at TEXT NOT NULL
100
+ );
101
+
102
+ CREATE INDEX IF NOT EXISTS idx_request_items_req ON request_items(request_id, position);
103
+
104
+ CREATE TABLE IF NOT EXISTS uploads (
105
+ id TEXT PRIMARY KEY,
106
+ request_item_id TEXT NOT NULL REFERENCES request_items(id) ON DELETE CASCADE,
107
+ original_name TEXT NOT NULL,
108
+ canonical_name TEXT NOT NULL,
109
+ detected_mime TEXT NOT NULL,
110
+ size_bytes INTEGER NOT NULL,
111
+ storage_key TEXT NOT NULL,
112
+ enc_version TEXT NOT NULL DEFAULT 'v1',
113
+ enc_iv TEXT NOT NULL,
114
+ enc_tag TEXT NOT NULL,
115
+ enc_salt TEXT NOT NULL,
116
+ sha256 TEXT NOT NULL,
117
+ created_at TEXT NOT NULL,
118
+ purged_at TEXT
119
+ );
120
+
121
+ CREATE INDEX IF NOT EXISTS idx_uploads_item ON uploads(request_item_id);
122
+
123
+ CREATE TABLE IF NOT EXISTS otp_codes (
124
+ id TEXT PRIMARY KEY,
125
+ request_id TEXT NOT NULL REFERENCES requests(id) ON DELETE CASCADE,
126
+ code_hash TEXT NOT NULL,
127
+ attempts INTEGER NOT NULL DEFAULT 0,
128
+ expires_at TEXT NOT NULL,
129
+ verified_at TEXT,
130
+ created_at TEXT NOT NULL
131
+ );
132
+
133
+ CREATE TABLE IF NOT EXISTS client_sessions (
134
+ id TEXT PRIMARY KEY,
135
+ request_id TEXT NOT NULL REFERENCES requests(id) ON DELETE CASCADE,
136
+ token_hash TEXT NOT NULL UNIQUE,
137
+ expires_at TEXT NOT NULL,
138
+ created_at TEXT NOT NULL
139
+ );
140
+
141
+ CREATE TABLE IF NOT EXISTS audit_events (
142
+ id TEXT PRIMARY KEY,
143
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
144
+ request_id TEXT REFERENCES requests(id) ON DELETE CASCADE,
145
+ actor TEXT NOT NULL,
146
+ action TEXT NOT NULL,
147
+ meta_json TEXT NOT NULL DEFAULT '{}',
148
+ created_at TEXT NOT NULL
149
+ );
150
+
151
+ CREATE INDEX IF NOT EXISTS idx_audit_request ON audit_events(request_id, created_at DESC);
152
+
153
+ CREATE TABLE IF NOT EXISTS outbox_emails (
154
+ id TEXT PRIMARY KEY,
155
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
156
+ request_id TEXT REFERENCES requests(id) ON DELETE CASCADE,
157
+ recipient TEXT NOT NULL,
158
+ subject TEXT NOT NULL,
159
+ text_body TEXT NOT NULL,
160
+ kind TEXT NOT NULL DEFAULT 'general',
161
+ is_demo INTEGER NOT NULL DEFAULT 0,
162
+ created_at TEXT NOT NULL
163
+ );
164
+
165
+ CREATE INDEX IF NOT EXISTS idx_outbox_workspace ON outbox_emails(workspace_id, created_at DESC);
166
+ `;
167
+ function ensureColumn(db, table, col, def) {
168
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
169
+ if (!cols.some((c) => c.name === col)) {
170
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
171
+ }
172
+ }
173
+ function ensureColumns(db, tableCols) {
174
+ for (const [table, columns] of Object.entries(tableCols)) {
175
+ for (const [col, def] of columns) {
176
+ ensureColumn(db, table, col, def);
177
+ }
178
+ }
179
+ }
180
+ // Append-only versioned migrations; never renumber or alter previously released entries.
181
+ const MIGRATIONS = [
182
+ {
183
+ version: 1,
184
+ name: "001_initial_schema",
185
+ up: (db) => {
186
+ db.exec(SCHEMA_SQL);
187
+ },
188
+ },
189
+ {
190
+ version: 2,
191
+ name: "002_portal_branding_and_client_notes",
192
+ up: (db) => {
193
+ ensureColumns(db, {
194
+ requests: [
195
+ ["is_demo", "INTEGER NOT NULL DEFAULT 0"],
196
+ ["due_at", "TEXT"],
197
+ ["client_subject", "TEXT"],
198
+ ["welcome_note", "TEXT"],
199
+ ["last_opened_at", "TEXT"],
200
+ ["last_manual_reminder_at", "TEXT"],
201
+ ],
202
+ workspaces: [
203
+ ["brand_color", "TEXT"],
204
+ ["logo_mime", "TEXT"],
205
+ ["logo_b64", "TEXT"],
206
+ ["support_email", "TEXT"],
207
+ ["support_phone", "TEXT"],
208
+ ],
209
+ request_items: [
210
+ ["client_note_encrypted", "TEXT"],
211
+ ["client_na", "INTEGER NOT NULL DEFAULT 0"],
212
+ ],
213
+ outbox_emails: [["html_body", "TEXT"]],
214
+ });
215
+ },
216
+ },
217
+ {
218
+ version: 3,
219
+ name: "003_workspace_email_and_user_profile",
220
+ up: (db) => {
221
+ ensureColumns(db, {
222
+ workspaces: [
223
+ ["email_backend", "TEXT"],
224
+ ["email_from", "TEXT"],
225
+ ["email_reply_to", "TEXT"],
226
+ ["email_config_encrypted", "TEXT"],
227
+ ],
228
+ users: [["display_name", "TEXT"]],
229
+ });
230
+ },
231
+ },
232
+ {
233
+ version: 4,
234
+ name: "004_upload_enc_version",
235
+ up: (db) => {
236
+ ensureColumn(db, "uploads", "enc_version", "TEXT NOT NULL DEFAULT 'v1'");
237
+ },
238
+ },
239
+ ];
240
+ export const LATEST_SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1].version;
241
+ export function getSchemaVersion(db) {
242
+ const tableExists = db
243
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'")
244
+ .get();
245
+ if (!tableExists)
246
+ return 0;
247
+ const row = db.prepare("SELECT MAX(version) AS v FROM schema_migrations").get();
248
+ return row?.v ?? 0;
249
+ }
250
+ function applyVersionedMigrations(db) {
251
+ db.exec(`
252
+ CREATE TABLE IF NOT EXISTS schema_migrations (
253
+ version INTEGER PRIMARY KEY,
254
+ name TEXT NOT NULL,
255
+ applied_at TEXT NOT NULL
256
+ );
257
+ `);
258
+ const appliedRows = db.prepare("SELECT version FROM schema_migrations").all();
259
+ const applied = new Set(appliedRows.map((r) => Number(r.version)));
260
+ const maxApplied = appliedRows.reduce((max, r) => Math.max(max, Number(r.version)), 0);
261
+ if (maxApplied > LATEST_SCHEMA_VERSION) {
262
+ throw new Error(`Database schema version ${maxApplied} is newer than supported version ${LATEST_SCHEMA_VERSION}`);
263
+ }
264
+ for (const migration of MIGRATIONS) {
265
+ if (applied.has(migration.version))
266
+ continue;
267
+ db.exec("BEGIN");
268
+ try {
269
+ migration.up(db);
270
+ db.prepare("INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)").run(migration.version, migration.name, new Date().toISOString());
271
+ db.exec(`PRAGMA user_version = ${migration.version};`);
272
+ db.exec("COMMIT");
273
+ }
274
+ catch (err) {
275
+ db.exec("ROLLBACK");
276
+ throw err;
277
+ }
278
+ }
279
+ }
280
+ export function openDatabase(dbPath) {
281
+ if (dbPath !== ":memory:") {
282
+ fs.mkdirSync(path.dirname(dbPath), { recursive: true });
283
+ }
284
+ const db = new DatabaseSync(dbPath);
285
+ try {
286
+ db.exec(PRAGMAS_SQL);
287
+ applyVersionedMigrations(db);
288
+ return db;
289
+ }
290
+ catch (err) {
291
+ db.close();
292
+ throw err;
293
+ }
294
+ }