@agenticmail/enterprise 0.5.7 → 0.5.9

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,496 @@
1
+ import {
2
+ getAllCreateStatements
3
+ } from "./chunk-XMDE2NGH.js";
4
+ import {
5
+ DatabaseAdapter
6
+ } from "./chunk-FLRYMSKY.js";
7
+ import "./chunk-KFQGP6VL.js";
8
+
9
+ // src/db/turso.ts
10
+ import { randomUUID, createHash } from "crypto";
11
+ var libsqlClient;
12
+ async function getClient() {
13
+ if (!libsqlClient) {
14
+ try {
15
+ const { resolveDriver } = await import("./resolve-driver-VQXMFKLJ.js");
16
+ libsqlClient = await resolveDriver("@libsql/client", "Turso/LibSQL driver not found. Install it: npm install @libsql/client");
17
+ } catch {
18
+ throw new Error("Turso driver not found. Install: npm install @libsql/client");
19
+ }
20
+ }
21
+ return libsqlClient;
22
+ }
23
+ var TursoAdapter = class extends DatabaseAdapter {
24
+ type = "turso";
25
+ client = null;
26
+ async connect(config) {
27
+ const lib = await getClient();
28
+ this.client = lib.createClient({
29
+ url: config.connectionString || "file:./agenticmail-enterprise.db",
30
+ authToken: config.authToken
31
+ });
32
+ }
33
+ async disconnect() {
34
+ if (this.client) this.client.close();
35
+ }
36
+ isConnected() {
37
+ return this.client !== null;
38
+ }
39
+ // ─── Engine Integration ──────────────────────────────────
40
+ getEngineDB() {
41
+ if (!this.client) return null;
42
+ const client = this.client;
43
+ return {
44
+ run: async (sql, params) => {
45
+ await client.execute({ sql, args: params || [] });
46
+ },
47
+ get: async (sql, params) => {
48
+ const result = await client.execute({ sql, args: params || [] });
49
+ return result.rows?.[0] || void 0;
50
+ },
51
+ all: async (sql, params) => {
52
+ const result = await client.execute({ sql, args: params || [] });
53
+ return result.rows || [];
54
+ }
55
+ };
56
+ }
57
+ getDialect() {
58
+ return "turso";
59
+ }
60
+ async run(sql, args = []) {
61
+ return this.client.execute({ sql, args });
62
+ }
63
+ async get(sql, args = []) {
64
+ const result = await this.run(sql, args);
65
+ if (!result.rows || result.rows.length === 0) return null;
66
+ return result.rows[0];
67
+ }
68
+ async all(sql, args = []) {
69
+ const result = await this.run(sql, args);
70
+ return result.rows || [];
71
+ }
72
+ async migrate() {
73
+ const stmts = getAllCreateStatements();
74
+ await this.client.batch(
75
+ stmts.map((sql) => ({ sql, args: [] })).concat([
76
+ { sql: `INSERT OR IGNORE INTO retention_policy (id) VALUES ('default')`, args: [] }
77
+ ]),
78
+ "write"
79
+ );
80
+ }
81
+ // ─── Company ─────────────────────────────────────────────
82
+ async getSettings() {
83
+ const r = await this.get("SELECT * FROM company_settings WHERE id = ?", ["default"]);
84
+ return r ? this.mapSettings(r) : null;
85
+ }
86
+ async updateSettings(updates) {
87
+ const map = {
88
+ name: "name",
89
+ domain: "domain",
90
+ subdomain: "subdomain",
91
+ smtpHost: "smtp_host",
92
+ smtpPort: "smtp_port",
93
+ smtpUser: "smtp_user",
94
+ smtpPass: "smtp_pass",
95
+ dkimPrivateKey: "dkim_private_key",
96
+ logoUrl: "logo_url",
97
+ primaryColor: "primary_color",
98
+ plan: "plan",
99
+ deploymentKeyHash: "deployment_key_hash",
100
+ domainRegistrationId: "domain_registration_id",
101
+ domainDnsChallenge: "domain_dns_challenge",
102
+ domainVerifiedAt: "domain_verified_at",
103
+ domainRegisteredAt: "domain_registered_at",
104
+ domainStatus: "domain_status"
105
+ };
106
+ const sets = [];
107
+ const vals = [];
108
+ for (const [key, col] of Object.entries(map)) {
109
+ if (updates[key] !== void 0) {
110
+ sets.push(`${col} = ?`);
111
+ vals.push(updates[key]);
112
+ }
113
+ }
114
+ if (updates.ssoConfig !== void 0) {
115
+ sets.push("sso_config = ?");
116
+ vals.push(JSON.stringify(updates.ssoConfig));
117
+ }
118
+ if (updates.toolSecurityConfig !== void 0) {
119
+ sets.push("tool_security_config = ?");
120
+ vals.push(JSON.stringify(updates.toolSecurityConfig));
121
+ }
122
+ if (updates.firewallConfig !== void 0) {
123
+ sets.push("firewall_config = ?");
124
+ vals.push(JSON.stringify(updates.firewallConfig));
125
+ }
126
+ if (updates.modelPricingConfig !== void 0) {
127
+ sets.push("model_pricing_config = ?");
128
+ vals.push(JSON.stringify(updates.modelPricingConfig));
129
+ }
130
+ sets.push("updated_at = datetime('now')");
131
+ vals.push("default");
132
+ await this.run(`UPDATE company_settings SET ${sets.join(", ")} WHERE id = ?`, vals);
133
+ return this.getSettings();
134
+ }
135
+ // ─── Agents ──────────────────────────────────────────────
136
+ async createAgent(input) {
137
+ const id = input.id || randomUUID();
138
+ const email = input.email || `${input.name.toLowerCase().replace(/\s+/g, "-")}@localhost`;
139
+ await this.run(
140
+ `INSERT INTO agents (id, name, email, role, metadata, created_by) VALUES (?, ?, ?, ?, ?, ?)`,
141
+ [id, input.name, email, input.role || "assistant", JSON.stringify(input.metadata || {}), input.createdBy]
142
+ );
143
+ return await this.getAgent(id);
144
+ }
145
+ async getAgent(id) {
146
+ const r = await this.get("SELECT * FROM agents WHERE id = ?", [id]);
147
+ return r ? this.mapAgent(r) : null;
148
+ }
149
+ async getAgentByName(name) {
150
+ const r = await this.get("SELECT * FROM agents WHERE name = ?", [name]);
151
+ return r ? this.mapAgent(r) : null;
152
+ }
153
+ async listAgents(opts) {
154
+ let q = "SELECT * FROM agents";
155
+ const params = [];
156
+ if (opts?.status) {
157
+ q += " WHERE status = ?";
158
+ params.push(opts.status);
159
+ }
160
+ q += " ORDER BY created_at DESC";
161
+ if (opts?.limit) q += ` LIMIT ${opts.limit}`;
162
+ if (opts?.offset) q += ` OFFSET ${opts.offset}`;
163
+ return (await this.all(q, params)).map((r) => this.mapAgent(r));
164
+ }
165
+ async updateAgent(id, updates) {
166
+ const fields = [];
167
+ const vals = [];
168
+ for (const [key, col] of Object.entries({ name: "name", email: "email", role: "role", status: "status" })) {
169
+ if (updates[key] !== void 0) {
170
+ fields.push(`${col} = ?`);
171
+ vals.push(updates[key]);
172
+ }
173
+ }
174
+ if (updates.metadata) {
175
+ fields.push("metadata = ?");
176
+ vals.push(JSON.stringify(updates.metadata));
177
+ }
178
+ fields.push("updated_at = datetime('now')");
179
+ vals.push(id);
180
+ await this.run(`UPDATE agents SET ${fields.join(", ")} WHERE id = ?`, vals);
181
+ return await this.getAgent(id);
182
+ }
183
+ async archiveAgent(id) {
184
+ await this.run("UPDATE agents SET status = 'archived', updated_at = datetime('now') WHERE id = ?", [id]);
185
+ }
186
+ async deleteAgent(id) {
187
+ await this.run("DELETE FROM agents WHERE id = ?", [id]);
188
+ }
189
+ async countAgents(status) {
190
+ const r = status ? await this.get("SELECT COUNT(*) as c FROM agents WHERE status = ?", [status]) : await this.get("SELECT COUNT(*) as c FROM agents", []);
191
+ return r.c;
192
+ }
193
+ // ─── Users ───────────────────────────────────────────────
194
+ async createUser(input) {
195
+ const id = randomUUID();
196
+ let passwordHash = null;
197
+ if (input.password) {
198
+ const { default: bcrypt } = await import("bcryptjs");
199
+ passwordHash = await bcrypt.hash(input.password, 12);
200
+ }
201
+ await this.run(
202
+ `INSERT INTO users (id, email, name, role, password_hash, sso_provider, sso_subject) VALUES (?, ?, ?, ?, ?, ?, ?)`,
203
+ [id, input.email, input.name, input.role, passwordHash, input.ssoProvider || null, input.ssoSubject || null]
204
+ );
205
+ return await this.getUser(id);
206
+ }
207
+ async getUser(id) {
208
+ const r = await this.get("SELECT * FROM users WHERE id = ?", [id]);
209
+ return r ? this.mapUser(r) : null;
210
+ }
211
+ async getUserByEmail(email) {
212
+ const r = await this.get("SELECT * FROM users WHERE email = ?", [email]);
213
+ return r ? this.mapUser(r) : null;
214
+ }
215
+ async getUserBySso(provider, subject) {
216
+ const r = await this.get("SELECT * FROM users WHERE sso_provider = ? AND sso_subject = ?", [provider, subject]);
217
+ return r ? this.mapUser(r) : null;
218
+ }
219
+ async listUsers(opts) {
220
+ let q = "SELECT * FROM users ORDER BY created_at DESC";
221
+ if (opts?.limit) q += ` LIMIT ${opts.limit}`;
222
+ if (opts?.offset) q += ` OFFSET ${opts.offset}`;
223
+ return (await this.all(q)).map((r) => this.mapUser(r));
224
+ }
225
+ async updateUser(id, updates) {
226
+ const fields = [];
227
+ const vals = [];
228
+ for (const key of ["email", "name", "role"]) {
229
+ if (updates[key] !== void 0) {
230
+ fields.push(`${key} = ?`);
231
+ vals.push(updates[key]);
232
+ }
233
+ }
234
+ fields.push("updated_at = datetime('now')");
235
+ vals.push(id);
236
+ await this.run(`UPDATE users SET ${fields.join(", ")} WHERE id = ?`, vals);
237
+ return await this.getUser(id);
238
+ }
239
+ async deleteUser(id) {
240
+ await this.run("DELETE FROM users WHERE id = ?", [id]);
241
+ }
242
+ // ─── Audit ───────────────────────────────────────────────
243
+ async logEvent(event) {
244
+ await this.run(
245
+ `INSERT INTO audit_log (id, actor, actor_type, action, resource, details, ip) VALUES (?, ?, ?, ?, ?, ?, ?)`,
246
+ [randomUUID(), event.actor, event.actorType, event.action, event.resource, JSON.stringify(event.details || {}), event.ip || null]
247
+ );
248
+ }
249
+ async queryAudit(filters) {
250
+ const where = [];
251
+ const params = [];
252
+ if (filters.actor) {
253
+ where.push("actor = ?");
254
+ params.push(filters.actor);
255
+ }
256
+ if (filters.action) {
257
+ where.push("action = ?");
258
+ params.push(filters.action);
259
+ }
260
+ if (filters.resource) {
261
+ where.push("resource LIKE ?");
262
+ params.push(`%${filters.resource}%`);
263
+ }
264
+ if (filters.from) {
265
+ where.push("timestamp >= ?");
266
+ params.push(filters.from.toISOString());
267
+ }
268
+ if (filters.to) {
269
+ where.push("timestamp <= ?");
270
+ params.push(filters.to.toISOString());
271
+ }
272
+ const wc = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
273
+ const countRow = await this.get(`SELECT COUNT(*) as c FROM audit_log ${wc}`, params);
274
+ let q = `SELECT * FROM audit_log ${wc} ORDER BY timestamp DESC`;
275
+ if (filters.limit) q += ` LIMIT ${filters.limit}`;
276
+ if (filters.offset) q += ` OFFSET ${filters.offset}`;
277
+ const rows = await this.all(q, params);
278
+ return {
279
+ events: rows.map((r) => ({
280
+ id: r.id,
281
+ timestamp: new Date(r.timestamp),
282
+ actor: r.actor,
283
+ actorType: r.actor_type,
284
+ action: r.action,
285
+ resource: r.resource,
286
+ details: JSON.parse(r.details || "{}"),
287
+ ip: r.ip
288
+ })),
289
+ total: countRow.c
290
+ };
291
+ }
292
+ // ─── API Keys ────────────────────────────────────────────
293
+ async createApiKey(input) {
294
+ const id = randomUUID();
295
+ const plaintext = `ek_${randomUUID().replace(/-/g, "")}`;
296
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
297
+ const keyPrefix = plaintext.substring(0, 11);
298
+ await this.run(
299
+ `INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_by, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
300
+ [id, input.name, keyHash, keyPrefix, JSON.stringify(input.scopes), input.createdBy, input.expiresAt?.toISOString() || null]
301
+ );
302
+ return { key: await this.getApiKey(id), plaintext };
303
+ }
304
+ async getApiKey(id) {
305
+ const r = await this.get("SELECT * FROM api_keys WHERE id = ?", [id]);
306
+ return r ? this.mapApiKey(r) : null;
307
+ }
308
+ async validateApiKey(plaintext) {
309
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
310
+ const r = await this.get("SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0", [keyHash]);
311
+ if (!r) return null;
312
+ const key = this.mapApiKey(r);
313
+ if (key.expiresAt && /* @__PURE__ */ new Date() > key.expiresAt) return null;
314
+ await this.run("UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?", [key.id]);
315
+ return key;
316
+ }
317
+ async listApiKeys(opts) {
318
+ let q = "SELECT * FROM api_keys";
319
+ const params = [];
320
+ if (opts?.createdBy) {
321
+ q += " WHERE created_by = ?";
322
+ params.push(opts.createdBy);
323
+ }
324
+ q += " ORDER BY created_at DESC";
325
+ return (await this.all(q, params)).map((r) => this.mapApiKey(r));
326
+ }
327
+ async revokeApiKey(id) {
328
+ await this.run("UPDATE api_keys SET revoked = 1 WHERE id = ?", [id]);
329
+ }
330
+ // ─── Rules ───────────────────────────────────────────────
331
+ async createRule(rule) {
332
+ const id = randomUUID();
333
+ await this.run(
334
+ `INSERT INTO email_rules (id, name, agent_id, conditions, actions, priority, enabled) VALUES (?, ?, ?, ?, ?, ?, ?)`,
335
+ [id, rule.name, rule.agentId || null, JSON.stringify(rule.conditions), JSON.stringify(rule.actions), rule.priority, rule.enabled ? 1 : 0]
336
+ );
337
+ const r = await this.get("SELECT * FROM email_rules WHERE id = ?", [id]);
338
+ return this.mapRule(r);
339
+ }
340
+ async getRules(agentId) {
341
+ let q = "SELECT * FROM email_rules";
342
+ const params = [];
343
+ if (agentId) {
344
+ q += " WHERE agent_id = ? OR agent_id IS NULL";
345
+ params.push(agentId);
346
+ }
347
+ q += " ORDER BY priority DESC";
348
+ return (await this.all(q, params)).map((r) => this.mapRule(r));
349
+ }
350
+ async updateRule(id, updates) {
351
+ const fields = [];
352
+ const vals = [];
353
+ if (updates.name !== void 0) {
354
+ fields.push("name = ?");
355
+ vals.push(updates.name);
356
+ }
357
+ if (updates.conditions) {
358
+ fields.push("conditions = ?");
359
+ vals.push(JSON.stringify(updates.conditions));
360
+ }
361
+ if (updates.actions) {
362
+ fields.push("actions = ?");
363
+ vals.push(JSON.stringify(updates.actions));
364
+ }
365
+ if (updates.priority !== void 0) {
366
+ fields.push("priority = ?");
367
+ vals.push(updates.priority);
368
+ }
369
+ if (updates.enabled !== void 0) {
370
+ fields.push("enabled = ?");
371
+ vals.push(updates.enabled ? 1 : 0);
372
+ }
373
+ fields.push("updated_at = datetime('now')");
374
+ vals.push(id);
375
+ await this.run(`UPDATE email_rules SET ${fields.join(", ")} WHERE id = ?`, vals);
376
+ const r = await this.get("SELECT * FROM email_rules WHERE id = ?", [id]);
377
+ return this.mapRule(r);
378
+ }
379
+ async deleteRule(id) {
380
+ await this.run("DELETE FROM email_rules WHERE id = ?", [id]);
381
+ }
382
+ // ─── Retention ───────────────────────────────────────────
383
+ async getRetentionPolicy() {
384
+ const r = await this.get("SELECT * FROM retention_policy WHERE id = ?", ["default"]);
385
+ if (!r) return { enabled: false, retainDays: 365, archiveFirst: true };
386
+ return { enabled: !!r.enabled, retainDays: r.retain_days, excludeTags: JSON.parse(r.exclude_tags || "[]"), archiveFirst: !!r.archive_first };
387
+ }
388
+ async setRetentionPolicy(policy) {
389
+ await this.run(
390
+ `UPDATE retention_policy SET enabled = ?, retain_days = ?, exclude_tags = ?, archive_first = ? WHERE id = 'default'`,
391
+ [policy.enabled ? 1 : 0, policy.retainDays, JSON.stringify(policy.excludeTags || []), policy.archiveFirst ? 1 : 0]
392
+ );
393
+ }
394
+ // ─── Stats ───────────────────────────────────────────────
395
+ async getStats() {
396
+ const [total, active, users, audit] = await Promise.all([
397
+ this.get("SELECT COUNT(*) as c FROM agents"),
398
+ this.get("SELECT COUNT(*) as c FROM agents WHERE status = 'active'"),
399
+ this.get("SELECT COUNT(*) as c FROM users"),
400
+ this.get("SELECT COUNT(*) as c FROM audit_log")
401
+ ]);
402
+ return {
403
+ totalAgents: total.c,
404
+ activeAgents: active.c,
405
+ totalUsers: users.c,
406
+ totalEmails: 0,
407
+ totalAuditEvents: audit.c
408
+ };
409
+ }
410
+ // ─── Mappers ─────────────────────────────────────────────
411
+ mapAgent(r) {
412
+ return {
413
+ id: r.id,
414
+ name: r.name,
415
+ email: r.email,
416
+ role: r.role,
417
+ status: r.status,
418
+ metadata: typeof r.metadata === "string" ? JSON.parse(r.metadata) : r.metadata || {},
419
+ createdAt: new Date(r.created_at),
420
+ updatedAt: new Date(r.updated_at),
421
+ createdBy: r.created_by
422
+ };
423
+ }
424
+ mapUser(r) {
425
+ return {
426
+ id: r.id,
427
+ email: r.email,
428
+ name: r.name,
429
+ role: r.role,
430
+ passwordHash: r.password_hash,
431
+ ssoProvider: r.sso_provider,
432
+ ssoSubject: r.sso_subject,
433
+ createdAt: new Date(r.created_at),
434
+ updatedAt: new Date(r.updated_at),
435
+ lastLoginAt: r.last_login_at ? new Date(r.last_login_at) : void 0
436
+ };
437
+ }
438
+ mapApiKey(r) {
439
+ return {
440
+ id: r.id,
441
+ name: r.name,
442
+ keyHash: r.key_hash,
443
+ keyPrefix: r.key_prefix,
444
+ scopes: typeof r.scopes === "string" ? JSON.parse(r.scopes) : r.scopes || [],
445
+ createdBy: r.created_by,
446
+ createdAt: new Date(r.created_at),
447
+ lastUsedAt: r.last_used_at ? new Date(r.last_used_at) : void 0,
448
+ expiresAt: r.expires_at ? new Date(r.expires_at) : void 0,
449
+ revoked: !!r.revoked
450
+ };
451
+ }
452
+ mapRule(r) {
453
+ return {
454
+ id: r.id,
455
+ name: r.name,
456
+ agentId: r.agent_id,
457
+ conditions: typeof r.conditions === "string" ? JSON.parse(r.conditions) : r.conditions || {},
458
+ actions: typeof r.actions === "string" ? JSON.parse(r.actions) : r.actions || {},
459
+ priority: r.priority,
460
+ enabled: !!r.enabled,
461
+ createdAt: new Date(r.created_at),
462
+ updatedAt: new Date(r.updated_at)
463
+ };
464
+ }
465
+ mapSettings(r) {
466
+ return {
467
+ id: r.id,
468
+ name: r.name,
469
+ domain: r.domain,
470
+ subdomain: r.subdomain,
471
+ smtpHost: r.smtp_host,
472
+ smtpPort: r.smtp_port,
473
+ smtpUser: r.smtp_user,
474
+ smtpPass: r.smtp_pass,
475
+ dkimPrivateKey: r.dkim_private_key,
476
+ logoUrl: r.logo_url,
477
+ primaryColor: r.primary_color,
478
+ ssoConfig: r.sso_config ? typeof r.sso_config === "string" ? JSON.parse(r.sso_config) : r.sso_config : void 0,
479
+ toolSecurityConfig: r.tool_security_config ? typeof r.tool_security_config === "string" ? JSON.parse(r.tool_security_config) : r.tool_security_config : {},
480
+ firewallConfig: r.firewall_config ? typeof r.firewall_config === "string" ? JSON.parse(r.firewall_config) : r.firewall_config : {},
481
+ modelPricingConfig: r.model_pricing_config ? typeof r.model_pricing_config === "string" ? JSON.parse(r.model_pricing_config) : r.model_pricing_config : {},
482
+ plan: r.plan,
483
+ createdAt: new Date(r.created_at),
484
+ updatedAt: new Date(r.updated_at),
485
+ deploymentKeyHash: r.deployment_key_hash,
486
+ domainRegistrationId: r.domain_registration_id,
487
+ domainDnsChallenge: r.domain_dns_challenge,
488
+ domainVerifiedAt: r.domain_verified_at || void 0,
489
+ domainRegisteredAt: r.domain_registered_at || void 0,
490
+ domainStatus: r.domain_status || "unregistered"
491
+ };
492
+ }
493
+ };
494
+ export {
495
+ TursoAdapter
496
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticmail/enterprise",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "description": "AgenticMail Enterprise — cloud-hosted AI agent identity, email, auth & compliance for organizations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,12 +19,10 @@ let ddbDocLib: any;
19
19
 
20
20
  async function getDdb() {
21
21
  if (!ddbLib) {
22
- try {
23
- ddbLib = await import('@aws-sdk/client-dynamodb');
24
- ddbDocLib = await import('@aws-sdk/lib-dynamodb');
25
- } catch {
26
- throw new Error('DynamoDB drivers not found. Install: npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb');
27
- }
22
+ const { resolveDriver } = await import('./resolve-driver.js');
23
+ const errMsg = 'DynamoDB drivers not found. Install: npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb';
24
+ ddbLib = await resolveDriver('@aws-sdk/client-dynamodb', errMsg);
25
+ ddbDocLib = await resolveDriver('@aws-sdk/lib-dynamodb', errMsg);
28
26
  }
29
27
  return { ddbLib, ddbDocLib };
30
28
  }
package/src/db/mongodb.ts CHANGED
@@ -18,7 +18,7 @@ let mongoMod: any;
18
18
  async function getMongo() {
19
19
  if (!mongoMod) {
20
20
  try {
21
- mongoMod = await import('mongodb');
21
+ const { resolveDriver } = await import("./resolve-driver.js"); mongoMod = await resolveDriver("mongodb", "MongoDB driver not found. Install it: npm install mongodb");
22
22
  } catch {
23
23
  throw new Error('MongoDB driver not found. Install: npm install mongodb');
24
24
  }
package/src/db/mysql.ts CHANGED
@@ -19,7 +19,7 @@ let mysql2: any;
19
19
  async function getMysql() {
20
20
  if (!mysql2) {
21
21
  try {
22
- mysql2 = await import('mysql2/promise' as any);
22
+ const { resolveDriver } = await import("./resolve-driver.js"); mysql2 = await resolveDriver("mysql2/promise", "MySQL driver not found. Install it: npm install mysql2");
23
23
  } catch {
24
24
  throw new Error(
25
25
  'MySQL driver not found. Install it: npm install mysql2\n' +
@@ -18,14 +18,11 @@ let pg: any;
18
18
 
19
19
  async function getPg() {
20
20
  if (!pg) {
21
- try {
22
- pg = await import('pg');
23
- } catch {
24
- throw new Error(
25
- 'PostgreSQL driver not found. Install it: npm install pg\n' +
26
- 'For Supabase/Neon/CockroachDB, the same pg driver works.'
27
- );
28
- }
21
+ const { resolveDriver } = await import('./resolve-driver.js');
22
+ pg = await resolveDriver('pg',
23
+ 'PostgreSQL driver not found. Install it: npm install pg\n' +
24
+ 'For Supabase/Neon/CockroachDB, the same pg driver works.'
25
+ );
29
26
  }
30
27
  return pg;
31
28
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Resolve a native driver module using multiple strategies.
3
+ * Works even when running from npx cache where ESM import() can't find
4
+ * packages installed in cwd.
5
+ */
6
+
7
+ import { createRequire } from 'module';
8
+ import { join } from 'path';
9
+
10
+ export async function resolveDriver(name: string, errorMessage: string): Promise<any> {
11
+ // 1. Standard ESM import
12
+ try { return await import(name); } catch {}
13
+
14
+ // 2. CJS require from cwd (covers npm install in user's directory)
15
+ try {
16
+ const req = createRequire(join(process.cwd(), 'index.js'));
17
+ return req(name);
18
+ } catch {}
19
+
20
+ // 3. CJS require from global prefix
21
+ try {
22
+ const { execSync } = await import('child_process');
23
+ const globalPrefix = execSync('npm prefix -g', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
24
+ const req = createRequire(join(globalPrefix, 'lib', 'node_modules', '.package-lock.json'));
25
+ return req(name);
26
+ } catch {}
27
+
28
+ throw new Error(errorMessage);
29
+ }
package/src/db/sqlite.ts CHANGED
@@ -19,7 +19,7 @@ let Database: any;
19
19
  async function getSqlite() {
20
20
  if (!Database) {
21
21
  try {
22
- const mod = await import('better-sqlite3');
22
+ const { resolveDriver } = await import("./resolve-driver.js"); const mod = await resolveDriver("better-sqlite3", "SQLite driver not found. Install it: npm install better-sqlite3");
23
23
  Database = mod.default;
24
24
  } catch {
25
25
  throw new Error('SQLite driver not found. Install it: npm install better-sqlite3');
package/src/db/turso.ts CHANGED
@@ -20,7 +20,7 @@ let libsqlClient: any;
20
20
  async function getClient() {
21
21
  if (!libsqlClient) {
22
22
  try {
23
- libsqlClient = await import('@libsql/client');
23
+ const { resolveDriver } = await import("./resolve-driver.js"); libsqlClient = await resolveDriver("@libsql/client", "Turso/LibSQL driver not found. Install it: npm install @libsql/client");
24
24
  } catch {
25
25
  throw new Error('Turso driver not found. Install: npm install @libsql/client');
26
26
  }
@@ -1262,6 +1262,7 @@ export interface DynamicTableDef {
1262
1262
  */
1263
1263
  export function sqliteToPostgres(sql: string): string {
1264
1264
  return sql
1265
+ .replace(/\bBLOB\b/g, 'BYTEA')
1265
1266
  .replace(/JSON/g, 'JSONB')
1266
1267
  .replace(/datetime\('now'\)/g, "NOW()")
1267
1268
  .replace(/INTEGER NOT NULL DEFAULT 1(?!\d)/g, 'BOOLEAN NOT NULL DEFAULT TRUE')