@devitek/mailsink-cli 0.0.0-stage → 0.3.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,98 @@
1
+ import { createInterface } from "node:readline";
2
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
3
+ // src/commands/mcp.ts
4
+ /** `http://host:3000` and `http://host:3000/mcp` both name the endpoint. */
5
+ function mcpEndpoint(url) {
6
+ let parsed;
7
+ try {
8
+ parsed = new URL(url);
9
+ } catch {
10
+ throw new Error("Invalid MAILSINK_URL: expected an http(s) URL");
11
+ }
12
+ if (!/^https?:$/.test(parsed.protocol)) throw new Error("Invalid MAILSINK_URL: expected an http(s) URL");
13
+ const path = parsed.pathname.replace(/\/+$/, "");
14
+ if (!path.endsWith("/mcp")) parsed.pathname = `${path}/mcp`;
15
+ return parsed;
16
+ }
17
+ const requestId = (m) => "method" in m && "id" in m ? m.id : void 0;
18
+ const responseId = (m) => !("method" in m) && "id" in m ? m.id : void 0;
19
+ /**
20
+ * Runs the proxy until stdin ends and every forwarded request got its answer, so
21
+ * `printf '…' | mailsink mcp` works as well as a long-lived client.
22
+ */
23
+ async function mcpCommand(options, io) {
24
+ const stdin = options.stdin ?? process.stdin;
25
+ const stdout = options.stdout ?? process.stdout;
26
+ const headers = { Authorization: `Bearer ${options.key}` };
27
+ if (options.workspace) headers["X-Mailsink-Workspace"] = options.workspace;
28
+ const upstream = new StreamableHTTPClientTransport(mcpEndpoint(options.url), {
29
+ requestInit: { headers },
30
+ ...options.fetch ? { fetch: options.fetch } : {}
31
+ });
32
+ const pending = /* @__PURE__ */ new Set();
33
+ let drained;
34
+ const settle = (id) => {
35
+ if (id === void 0) return;
36
+ pending.delete(id);
37
+ if (pending.size === 0) drained?.();
38
+ };
39
+ const sends = /* @__PURE__ */ new Set();
40
+ let closing = false;
41
+ const write = (message) => stdout.write(`${JSON.stringify(message)}\n`);
42
+ const fail = (reason) => io.err(`[mailsink mcp] ${reason}`);
43
+ upstream.onmessage = (message) => {
44
+ const result = "result" in message ? message.result : null;
45
+ if (typeof result?.protocolVersion === "string") upstream.setProtocolVersion(result.protocolVersion);
46
+ write(message);
47
+ settle(responseId(message));
48
+ };
49
+ upstream.onerror = (error) => {
50
+ if (!closing) fail(error.message);
51
+ };
52
+ const forward = (message) => {
53
+ const id = requestId(message);
54
+ if (id !== void 0) pending.add(id);
55
+ const sent = upstream.send(message).catch((error) => {
56
+ const reason = error instanceof Error ? error.message : String(error);
57
+ if (id === void 0) return;
58
+ write({
59
+ jsonrpc: "2.0",
60
+ id,
61
+ error: {
62
+ code: -32e3,
63
+ message: `Mailsink MCP endpoint unreachable or refused: ${reason}`
64
+ }
65
+ });
66
+ settle(id);
67
+ });
68
+ sends.add(sent);
69
+ sent.finally(() => sends.delete(sent));
70
+ };
71
+ await upstream.start();
72
+ for await (const line of createInterface({
73
+ input: stdin,
74
+ crlfDelay: 1e400
75
+ })) {
76
+ if (!line.trim()) continue;
77
+ let message;
78
+ try {
79
+ message = JSON.parse(line);
80
+ } catch {
81
+ write({
82
+ jsonrpc: "2.0",
83
+ id: null,
84
+ error: {
85
+ code: -32700,
86
+ message: "Parse error"
87
+ }
88
+ });
89
+ continue;
90
+ }
91
+ forward(message);
92
+ }
93
+ await Promise.allSettled([...sends]);
94
+ if (pending.size > 0) await new Promise((resolve) => drained = resolve);
95
+ closing = true;
96
+ await upstream.close();
97
+ }
98
+ export { mcpCommand };
@@ -0,0 +1,570 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import { drizzle } from "drizzle-orm/node-postgres";
3
+ import { drizzle as drizzle$1 } from "drizzle-orm/pglite";
4
+ import pg from "pg";
5
+ import { bigserial, boolean, check, customType, index, integer, jsonb, pgEnum, pgTable, primaryKey, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
6
+ import { sql } from "drizzle-orm";
7
+ import { fileURLToPath } from "node:url";
8
+ import { migrate as migrate$1 } from "drizzle-orm/node-postgres/migrator";
9
+ import { migrate as migrate$2 } from "drizzle-orm/pglite/migrator";
10
+ import { existsSync } from "node:fs";
11
+ // \0rolldown/runtime.js
12
+ var __defProp = Object.defineProperty;
13
+ var __exportAll = (all, flags) => {
14
+ let target = Object.setPrototypeOf({}, null);
15
+ for (var name in all) __defProp(target, name, {
16
+ get: all[name],
17
+ enumerable: true
18
+ });
19
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
20
+ return flags & 2 ? target : Object.preventExtensions(target);
21
+ };
22
+ // ../db/src/schema/columns.ts
23
+ /** `timestamptz` column, the only timestamp flavour used by the schema. */
24
+ const tstz = (name) => timestamp(name, { withTimezone: true });
25
+ /** `timestamptz not null default now()`. */
26
+ const createdAt = (name = "created_at") => tstz(name).notNull().defaultNow();
27
+ /** Binary column (D8). Both drivers return a Uint8Array (node-postgres: a Buffer). */
28
+ const bytea = customType({ dataType: () => "bytea" });
29
+ // ../db/src/schema/workspaces.ts
30
+ /** Default of `workspaces.simulation`: the defaults of the SimulationSettings contract. */
31
+ const DEFAULT_SIMULATION_SETTINGS = {
32
+ rates: { delivered: 100 },
33
+ rules: [],
34
+ latency: {
35
+ minMs: 0,
36
+ maxMs: 0
37
+ },
38
+ openRate: 0,
39
+ clickRate: 0
40
+ };
41
+ const workspaces = pgTable("workspaces", {
42
+ id: text("id").primaryKey(),
43
+ slug: text("slug").notNull().unique(),
44
+ name: text("name").notNull(),
45
+ description: text("description"),
46
+ ephemeral: boolean("ephemeral").notNull().default(false),
47
+ idleTtlSeconds: integer("idle_ttl_seconds"),
48
+ lastActivityAt: tstz("last_activity_at").notNull().defaultNow(),
49
+ expiresAt: tstz("expires_at"),
50
+ retentionSeconds: integer("retention_seconds").notNull().default(604800),
51
+ maxMessages: integer("max_messages"),
52
+ rateLimit: jsonb("rate_limit").$type(),
53
+ simulation: jsonb("simulation").$type().notNull().default(DEFAULT_SIMULATION_SETTINGS),
54
+ metadata: jsonb("metadata").$type(),
55
+ timezone: text("timezone").notNull().default("UTC"),
56
+ createdVia: text("created_via", { enum: ["ui", "admin_api"] }).notNull(),
57
+ createdAt: createdAt(),
58
+ updatedAt: createdAt("updated_at")
59
+ }, (t) => [index("workspaces_expiry_idx").on(t.expiresAt).where(sql`${t.ephemeral}`), index("workspaces_picker_idx").on(t.ephemeral, t.name)]);
60
+ // ../db/src/schema/blobs.ts
61
+ const blobs = pgTable("blobs", {
62
+ id: text("id").primaryKey(),
63
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
64
+ sha256: text("sha256").notNull(),
65
+ sizeBytes: integer("size_bytes").notNull(),
66
+ data: bytea("data").notNull(),
67
+ createdAt: createdAt()
68
+ }, (t) => [uniqueIndex("blobs_dedup_uq").on(t.workspaceId, t.sha256)]);
69
+ // ../db/src/search-document.ts
70
+ /**
71
+ * Characters of `subject text html` indexed for the capture full text search. A tsvector is
72
+ * capped at 1 MB by Postgres: without a bound, one large body made every search of its
73
+ * workspace fail. 100 000 characters stay under the cap in the worst case measured
74
+ * (unique two-character CJK words, about 470 kB).
75
+ */
76
+ const SEARCH_DOCUMENT_MAX_CHARS = 1e5;
77
+ /**
78
+ * The searched document of a message. The GIN index `messages_search_gin` is built on this
79
+ * very expression: a query must use it unchanged for the planner to pick the index.
80
+ */
81
+ function searchDocument(c) {
82
+ return sql`to_tsvector('simple', left(${c.subject} || ' ' || coalesce(${c.text}, '') || ' ' ||
83
+ coalesce(${c.html}, ''), ${sql.raw(String(SEARCH_DOCUMENT_MAX_CHARS))}))`;
84
+ }
85
+ // ../db/src/schema/enums.ts
86
+ const connectionKind = pgEnum("connection_kind", [
87
+ "resend",
88
+ "brevo",
89
+ "smtp"
90
+ ]);
91
+ const messageSource = pgEnum("message_source", [
92
+ "native",
93
+ "resend",
94
+ "brevo",
95
+ "smtp"
96
+ ]);
97
+ const deliveryStatus = pgEnum("delivery_status", [
98
+ "queued",
99
+ "sent",
100
+ "delivered",
101
+ "deferred",
102
+ "soft_bounce",
103
+ "hard_bounce",
104
+ "complained",
105
+ "failed",
106
+ "invalid",
107
+ "suppressed"
108
+ ]);
109
+ const eventType = pgEnum("event_type", [
110
+ "accepted",
111
+ "sent",
112
+ "delivered",
113
+ "deferred",
114
+ "soft_bounce",
115
+ "hard_bounce",
116
+ "complained",
117
+ "failed",
118
+ "invalid",
119
+ "suppressed",
120
+ "opened",
121
+ "clicked"
122
+ ]);
123
+ const eventOrigin = pgEnum("event_origin", [
124
+ "simulation",
125
+ "api",
126
+ "ui",
127
+ "mcp"
128
+ ]);
129
+ const recipientKind = pgEnum("recipient_kind", [
130
+ "to",
131
+ "cc",
132
+ "bcc"
133
+ ]);
134
+ const apiKeyScope = pgEnum("api_key_scope", ["workspace", "connection"]);
135
+ const suppressionReason = pgEnum("suppression_reason", [
136
+ "hard_bounce",
137
+ "complained",
138
+ "manual"
139
+ ]);
140
+ const payloadFormat = pgEnum("payload_format", [
141
+ "unified",
142
+ "resend",
143
+ "brevo"
144
+ ]);
145
+ const webhookEvent = pgEnum("webhook_event", [
146
+ "email.sent",
147
+ "email.delivered",
148
+ "email.deferred",
149
+ "email.soft_bounced",
150
+ "email.hard_bounced",
151
+ "email.complained",
152
+ "email.opened",
153
+ "email.clicked",
154
+ "email.suppressed",
155
+ "email.failed",
156
+ "email.invalid"
157
+ ]);
158
+ const brevoAuthType = pgEnum("brevo_auth_type", [
159
+ "none",
160
+ "bearer",
161
+ "basic"
162
+ ]);
163
+ const replayMode = pgEnum("replay_mode", ["exact", "resign"]);
164
+ const webhookDeliveryStatus = pgEnum("webhook_delivery_status", [
165
+ "pending",
166
+ "retrying",
167
+ "succeeded",
168
+ "failed"
169
+ ]);
170
+ const apiDialect = pgEnum("api_dialect", [
171
+ "native",
172
+ "resend",
173
+ "brevo",
174
+ "admin",
175
+ "capture",
176
+ "mcp"
177
+ ]);
178
+ const smtpOutcome = pgEnum("smtp_outcome", [
179
+ "accepted",
180
+ "rejected",
181
+ "auth_failed",
182
+ "error"
183
+ ]);
184
+ // ../db/src/schema/connections.ts
185
+ const connections = pgTable("connections", {
186
+ id: text("id").primaryKey(),
187
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
188
+ name: text("name").notNull(),
189
+ kind: connectionKind("kind").notNull(),
190
+ smtpUsername: text("smtp_username").unique(),
191
+ smtpPasswordHash: text("smtp_password_hash"),
192
+ retentionSeconds: integer("retention_seconds"),
193
+ rateLimit: jsonb("rate_limit").$type(),
194
+ simulation: jsonb("simulation").$type(),
195
+ disabledAt: tstz("disabled_at"),
196
+ createdAt: createdAt(),
197
+ updatedAt: createdAt("updated_at")
198
+ }, (t) => [index("connections_workspace_idx").on(t.workspaceId), check("connections_smtp_creds", sql`(${t.kind} = 'smtp') = (${t.smtpUsername} is not null)`)]);
199
+ // ../db/src/schema/messages.ts
200
+ const messages = pgTable("messages", {
201
+ id: text("id").primaryKey(),
202
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
203
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "set null" }),
204
+ source: messageSource("source").notNull(),
205
+ providerMessageId: text("provider_message_id").notNull(),
206
+ from: jsonb("from").$type().notNull(),
207
+ replyTo: jsonb("reply_to").$type(),
208
+ subject: text("subject").notNull().default(""),
209
+ html: text("html"),
210
+ text: text("text"),
211
+ headers: jsonb("headers").$type().notNull().default({}),
212
+ tags: jsonb("tags").$type().notNull().default([]),
213
+ metadata: jsonb("metadata").$type(),
214
+ templateRef: jsonb("template_ref").$type(),
215
+ links: jsonb("links").$type().notNull().default([]),
216
+ rawBlobId: text("raw_blob_id").references(() => blobs.id, { onDelete: "set null" }),
217
+ sizeBytes: integer("size_bytes").notNull(),
218
+ status: deliveryStatus("status").notNull().default("queued"),
219
+ simulation: jsonb("simulation").$type(),
220
+ idempotencyKey: text("idempotency_key"),
221
+ createdAt: createdAt(),
222
+ statusUpdatedAt: createdAt("status_updated_at")
223
+ }, (t) => [
224
+ index("messages_raw_blob_idx").on(t.rawBlobId),
225
+ index("messages_ws_created_idx").on(t.workspaceId, t.createdAt, t.id),
226
+ index("messages_ws_status_idx").on(t.workspaceId, t.status),
227
+ index("messages_ws_connection_idx").on(t.workspaceId, t.connectionId, t.createdAt.desc()),
228
+ index("messages_tags_gin").using("gin", t.tags),
229
+ index("messages_search_gin").using("gin", searchDocument(t)),
230
+ uniqueIndex("messages_provider_id_uq").on(t.workspaceId, t.providerMessageId)
231
+ ]);
232
+ const messageRecipients = pgTable("message_recipients", {
233
+ id: text("id").primaryKey(),
234
+ messageId: text("message_id").notNull().references(() => messages.id, { onDelete: "cascade" }),
235
+ workspaceId: text("workspace_id").notNull(),
236
+ kind: recipientKind("kind").notNull(),
237
+ email: text("email").notNull(),
238
+ name: text("name"),
239
+ status: deliveryStatus("status").notNull().default("queued"),
240
+ statusReason: text("status_reason"),
241
+ updatedAt: createdAt("updated_at")
242
+ }, (t) => [index("recipients_ws_email_idx").on(t.workspaceId, t.email), index("recipients_message_idx").on(t.messageId)]);
243
+ // ../db/src/schema/attachments.ts
244
+ const attachments = pgTable("attachments", {
245
+ id: text("id").primaryKey(),
246
+ messageId: text("message_id").notNull().references(() => messages.id, { onDelete: "cascade" }),
247
+ filename: text("filename"),
248
+ contentType: text("content_type").notNull(),
249
+ contentId: text("content_id"),
250
+ disposition: text("disposition", { enum: ["attachment", "inline"] }).notNull(),
251
+ sizeBytes: integer("size_bytes").notNull(),
252
+ blobId: text("blob_id").notNull().references(() => blobs.id, { onDelete: "cascade" })
253
+ }, (t) => [index("attachments_message_idx").on(t.messageId), index("attachments_blob_idx").on(t.blobId)]);
254
+ // ../db/src/schema/events.ts
255
+ const messageEvents = pgTable("message_events", {
256
+ id: text("id").primaryKey(),
257
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
258
+ messageId: text("message_id").notNull().references(() => messages.id, { onDelete: "cascade" }),
259
+ recipientEmail: text("recipient_email"),
260
+ type: eventType("type").notNull(),
261
+ origin: eventOrigin("origin").notNull(),
262
+ data: jsonb("data").$type(),
263
+ occurredAt: tstz("occurred_at").notNull().defaultNow()
264
+ }, (t) => [index("events_message_idx").on(t.messageId, t.occurredAt), index("events_ws_time_idx").on(t.workspaceId, t.occurredAt)]);
265
+ // ../db/src/schema/idempotency.ts
266
+ const idempotencyKeys = pgTable("idempotency_keys", {
267
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
268
+ key: text("key").notNull(),
269
+ requestHash: text("request_hash").notNull(),
270
+ responseStatus: integer("response_status").notNull(),
271
+ responseBody: jsonb("response_body").notNull(),
272
+ expiresAt: tstz("expires_at").notNull()
273
+ }, (t) => [primaryKey({ columns: [t.workspaceId, t.key] })]);
274
+ // ../db/src/schema/jobs.ts
275
+ const jobKinds = ["simulate_delivery", "deliver_webhook"];
276
+ const jobs = pgTable("jobs", {
277
+ id: bigserial("id", { mode: "number" }).primaryKey(),
278
+ kind: text("kind", { enum: jobKinds }).notNull(),
279
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
280
+ payload: jsonb("payload").notNull(),
281
+ runAt: tstz("run_at").notNull().defaultNow(),
282
+ attempts: integer("attempts").notNull().default(0),
283
+ lockedUntil: tstz("locked_until"),
284
+ lastError: text("last_error"),
285
+ failedAt: tstz("failed_at")
286
+ }, (t) => [index("jobs_due_idx").on(t.runAt)]);
287
+ // ../db/src/schema/keys.ts
288
+ const apiKeys = pgTable("api_keys", {
289
+ id: text("id").primaryKey(),
290
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
291
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "cascade" }),
292
+ scope: apiKeyScope("scope").notNull(),
293
+ name: text("name"),
294
+ displayPrefix: text("display_prefix").notNull(),
295
+ hash: text("hash").notNull().unique(),
296
+ lastUsedAt: tstz("last_used_at"),
297
+ revokedAt: tstz("revoked_at"),
298
+ createdAt: createdAt()
299
+ }, (t) => [check("api_keys_scope", sql`(${t.scope} = 'connection') = (${t.connectionId} is not null)`)]);
300
+ // ../db/src/schema/logs.ts
301
+ const apiLogs = pgTable("api_logs", {
302
+ id: text("id").primaryKey(),
303
+ workspaceId: text("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
304
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "set null" }),
305
+ dialect: apiDialect("dialect").notNull(),
306
+ method: text("method").notNull(),
307
+ path: text("path").notNull(),
308
+ statusCode: integer("status_code").notNull(),
309
+ durationMs: integer("duration_ms").notNull(),
310
+ requestHeaders: jsonb("request_headers").$type(),
311
+ requestBody: jsonb("request_body"),
312
+ responseHeaders: jsonb("response_headers").$type(),
313
+ responseBody: jsonb("response_body"),
314
+ messageIds: text("message_ids").array(),
315
+ errorCode: text("error_code"),
316
+ ip: text("ip"),
317
+ createdAt: createdAt()
318
+ }, (t) => [index("api_logs_ws_time_idx").on(t.workspaceId, t.createdAt.desc())]);
319
+ const smtpSessions = pgTable("smtp_sessions", {
320
+ id: text("id").primaryKey(),
321
+ workspaceId: text("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
322
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "set null" }),
323
+ remoteAddress: text("remote_address").notNull(),
324
+ clientHostname: text("client_hostname"),
325
+ authUser: text("auth_user"),
326
+ secure: boolean("secure").notNull().default(false),
327
+ transcript: jsonb("transcript").$type().notNull(),
328
+ messageIds: text("message_ids").array(),
329
+ outcome: smtpOutcome("outcome").notNull(),
330
+ error: text("error"),
331
+ startedAt: tstz("started_at").notNull(),
332
+ endedAt: tstz("ended_at")
333
+ }, (t) => [index("smtp_sessions_ws_time_idx").on(t.workspaceId, t.startedAt.desc())]);
334
+ // ../db/src/schema/overrides.ts
335
+ const overrides = pgTable("overrides", {
336
+ id: text("id").primaryKey(),
337
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
338
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "cascade" }),
339
+ config: jsonb("config").$type().notNull(),
340
+ activatedVia: eventOrigin("activated_via").notNull(),
341
+ expiresAt: tstz("expires_at"),
342
+ createdAt: createdAt(),
343
+ resetAt: tstz("reset_at")
344
+ }, (t) => [uniqueIndex("overrides_active_scope_uq").on(t.workspaceId, sql`coalesce(${t.connectionId}, '')`).where(sql`${t.resetAt} is null`)]);
345
+ // ../db/src/schema/suppressions.ts
346
+ const suppressions = pgTable("suppressions", {
347
+ id: text("id").primaryKey(),
348
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
349
+ email: text("email").notNull(),
350
+ reason: suppressionReason("reason").notNull(),
351
+ messageId: text("message_id").references(() => messages.id, { onDelete: "set null" }),
352
+ createdAt: createdAt()
353
+ }, (t) => [uniqueIndex("suppressions_ws_email_uq").on(t.workspaceId, t.email)]);
354
+ // ../db/src/schema/templates.ts
355
+ const templates = pgTable("templates", {
356
+ id: text("id").primaryKey(),
357
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
358
+ externalId: integer("external_id").notNull(),
359
+ name: text("name").notNull(),
360
+ subject: text("subject").notNull(),
361
+ html: text("html"),
362
+ text: text("text"),
363
+ sender: jsonb("sender").$type(),
364
+ createdAt: createdAt(),
365
+ updatedAt: createdAt("updated_at")
366
+ }, (t) => [uniqueIndex("templates_external_uq").on(t.workspaceId, t.externalId)]);
367
+ // ../db/src/schema/webhooks.ts
368
+ const webhookEndpoints = pgTable("webhook_endpoints", {
369
+ id: text("id").primaryKey(),
370
+ numericId: integer("numeric_id").generatedAlwaysAsIdentity().notNull().unique(),
371
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
372
+ connectionId: text("connection_id").references(() => connections.id, { onDelete: "cascade" }),
373
+ url: text("url").notNull(),
374
+ payloadFormat: payloadFormat("payload_format").notNull(),
375
+ events: webhookEvent("events").array().notNull(),
376
+ secret: text("secret"),
377
+ brevoAuth: brevoAuthType("brevo_auth").notNull().default("none"),
378
+ customHeaders: jsonb("custom_headers").$type().notNull().default([]),
379
+ description: text("description"),
380
+ enabled: boolean("enabled").notNull().default(true),
381
+ createdAt: createdAt(),
382
+ updatedAt: createdAt("updated_at")
383
+ }, (t) => [index("webhook_endpoints_scope_idx").on(t.workspaceId, t.connectionId), check("webhook_secret_required", sql`${t.payloadFormat} = 'brevo' or ${t.secret} is not null`)]);
384
+ // ../db/src/schema/webhook-deliveries.ts
385
+ const webhookDeliveries = pgTable("webhook_deliveries", {
386
+ id: text("id").primaryKey(),
387
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
388
+ endpointId: text("endpoint_id").notNull().references(() => webhookEndpoints.id, { onDelete: "cascade" }),
389
+ eventId: text("event_id").references(() => messageEvents.id, { onDelete: "set null" }),
390
+ messageId: text("message_id").references(() => messages.id, { onDelete: "set null" }),
391
+ payloadFormat: payloadFormat("payload_format").notNull(),
392
+ canonicalEvent: webhookEvent("canonical_event").notNull(),
393
+ dialectEvent: text("dialect_event").notNull(),
394
+ recipient: text("recipient"),
395
+ body: text("body").notNull(),
396
+ contentType: text("content_type").notNull().default("application/json"),
397
+ status: webhookDeliveryStatus("status").notNull().default("pending"),
398
+ attemptCount: integer("attempt_count").notNull().default(0),
399
+ nextAttemptAt: tstz("next_attempt_at"),
400
+ lastStatusCode: integer("last_status_code"),
401
+ replayOf: text("replay_of"),
402
+ replayMode: replayMode("replay_mode"),
403
+ createdAt: createdAt()
404
+ }, (t) => [
405
+ index("deliveries_ws_time_idx").on(t.workspaceId, t.createdAt.desc()),
406
+ index("deliveries_message_idx").on(t.messageId),
407
+ index("deliveries_ws_format_idx").on(t.workspaceId, t.payloadFormat)
408
+ ]);
409
+ const webhookAttempts = pgTable("webhook_attempts", {
410
+ id: text("id").primaryKey(),
411
+ deliveryId: text("delivery_id").notNull().references(() => webhookDeliveries.id, { onDelete: "cascade" }),
412
+ attemptNo: integer("attempt_no").notNull(),
413
+ requestHeaders: jsonb("request_headers").$type().notNull(),
414
+ signedAt: integer("signed_at"),
415
+ responseStatus: integer("response_status"),
416
+ responseBody: text("response_body"),
417
+ durationMs: integer("duration_ms").notNull(),
418
+ error: text("error"),
419
+ createdAt: createdAt()
420
+ }, (t) => [index("attempts_delivery_idx").on(t.deliveryId)]);
421
+ // ../db/src/schema/index.ts
422
+ var schema_exports = /* @__PURE__ */ __exportAll({
423
+ DEFAULT_SIMULATION_SETTINGS: () => DEFAULT_SIMULATION_SETTINGS,
424
+ apiDialect: () => apiDialect,
425
+ apiKeyScope: () => apiKeyScope,
426
+ apiKeys: () => apiKeys,
427
+ apiLogs: () => apiLogs,
428
+ attachments: () => attachments,
429
+ blobs: () => blobs,
430
+ brevoAuthType: () => brevoAuthType,
431
+ connectionKind: () => connectionKind,
432
+ connections: () => connections,
433
+ deliveryStatus: () => deliveryStatus,
434
+ eventOrigin: () => eventOrigin,
435
+ eventType: () => eventType,
436
+ idempotencyKeys: () => idempotencyKeys,
437
+ jobKinds: () => jobKinds,
438
+ jobs: () => jobs,
439
+ messageEvents: () => messageEvents,
440
+ messageRecipients: () => messageRecipients,
441
+ messageSource: () => messageSource,
442
+ messages: () => messages,
443
+ overrides: () => overrides,
444
+ payloadFormat: () => payloadFormat,
445
+ recipientKind: () => recipientKind,
446
+ replayMode: () => replayMode,
447
+ smtpOutcome: () => smtpOutcome,
448
+ smtpSessions: () => smtpSessions,
449
+ suppressionReason: () => suppressionReason,
450
+ suppressions: () => suppressions,
451
+ templates: () => templates,
452
+ webhookAttempts: () => webhookAttempts,
453
+ webhookDeliveries: () => webhookDeliveries,
454
+ webhookDeliveryStatus: () => webhookDeliveryStatus,
455
+ webhookEndpoints: () => webhookEndpoints,
456
+ webhookEvent: () => webhookEvent,
457
+ workspaces: () => workspaces
458
+ });
459
+ // ../db/src/url.ts
460
+ const DEFAULT_DATABASE_URL = "pglite://./data";
461
+ const PGLITE = "pglite://";
462
+ /** Parses `DATABASE_URL`: `postgres://…`, `postgresql://…`, `pglite://<dir>`, `pglite://memory`. */
463
+ function parseDatabaseUrl(url) {
464
+ if (url.startsWith("postgres://") || url.startsWith("postgresql://")) return {
465
+ driver: "postgres",
466
+ connectionString: url
467
+ };
468
+ if (url.startsWith(PGLITE)) {
469
+ const path = url.slice(9);
470
+ if (path === "memory") return {
471
+ driver: "pglite",
472
+ dataDir: void 0
473
+ };
474
+ if (path.length > 0) return {
475
+ driver: "pglite",
476
+ dataDir: path
477
+ };
478
+ }
479
+ const scheme = url.includes("://") ? `${url.split("://")[0]}://` : "no scheme";
480
+ throw new Error(`Invalid DATABASE_URL (${scheme}): expected postgres://…, pglite://<dir> or pglite://memory`);
481
+ }
482
+ // ../db/src/client.ts
483
+ function warnConnectionLost(error) {
484
+ console.warn(`[mailsink] database connection lost: ${error.message}`);
485
+ }
486
+ /** Opens the database named by `DATABASE_URL` (default `pglite://./data`). */
487
+ function createDb(url = DEFAULT_DATABASE_URL, options = {}) {
488
+ const target = parseDatabaseUrl(url);
489
+ if (target.driver === "postgres") {
490
+ const pool = new pg.Pool({
491
+ connectionString: target.connectionString,
492
+ max: options.maxConnections ?? 10
493
+ });
494
+ pool.on("error", options.onConnectionError ?? warnConnectionLost);
495
+ return handle(drizzle({
496
+ client: pool,
497
+ schema: schema_exports
498
+ }), "postgres", pool, () => pool.end());
499
+ }
500
+ const client = new PGlite(target.dataDir);
501
+ return handle(drizzle$1({
502
+ client,
503
+ schema: schema_exports
504
+ }), "pglite", client, () => client.close());
505
+ }
506
+ function handle(db, driver, client, close) {
507
+ let closed;
508
+ return {
509
+ db,
510
+ driver,
511
+ client,
512
+ close: () => {
513
+ closed ??= close();
514
+ return closed;
515
+ }
516
+ };
517
+ }
518
+ // ../db/src/migrate.ts
519
+ /** SQL migrations generated by drizzle-kit, shipped next to the package sources. */
520
+ const MIGRATIONS_FOLDER = fileURLToPath(new URL("../migrations", import.meta.url));
521
+ const MIGRATION_LOCK_KEY = 7042026;
522
+ /**
523
+ * Applies pending migrations. Idempotent: already applied migrations are skipped.
524
+ * On Postgres a session advisory lock serializes concurrent callers (boot vs CLI).
525
+ */
526
+ async function migrate(handle, options = {}) {
527
+ const config = { migrationsFolder: options.migrationsFolder ?? MIGRATIONS_FOLDER };
528
+ if (handle.driver === "pglite") {
529
+ await migrate$2(handle.db, config);
530
+ return;
531
+ }
532
+ const conn = await handle.client.connect();
533
+ try {
534
+ await conn.query("select pg_advisory_lock($1)", [MIGRATION_LOCK_KEY]);
535
+ await migrate$1(drizzle({ client: conn }), config);
536
+ } finally {
537
+ await conn.query("select pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]).catch(() => {});
538
+ conn.release();
539
+ }
540
+ }
541
+ messages.connectionId;
542
+ apiLogs.createdAt, apiLogs.durationMs, apiLogs.statusCode;
543
+ messages.workspaceId, messages.connectionId, messages.createdAt;
544
+ // ../db/src/repositories/messages-read.ts
545
+ const outerMessageId = sql.raw("\"messages\".\"id\"");
546
+ sql`exists (select 1 from ${attachments}
547
+ where ${attachments.messageId} = ${outerMessageId} and ${attachments.disposition} = 'attachment')`;
548
+ sql`to_char(${messages.createdAt} at time zone 'UTC',
549
+ 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
550
+ searchDocument(messages);
551
+ // src/migrations-folder.ts
552
+ /**
553
+ * The built bin ships the SQL migrations in `dist/migrations` (copied by tsdown), next to
554
+ * the bundle. From sources this folder does not exist and @mailsink/db uses its own.
555
+ */
556
+ function bundledMigrationsFolder() {
557
+ const folder = fileURLToPath(new URL("./migrations", import.meta.url));
558
+ return existsSync(folder) ? folder : void 0;
559
+ }
560
+ // src/commands/migrate.ts
561
+ async function migrateCommand(options, io) {
562
+ const handle = createDb(options.databaseUrl || "pglite://./data");
563
+ try {
564
+ await migrate(handle, { migrationsFolder: bundledMigrationsFolder() });
565
+ io.out(`Migrations applied (${handle.driver}).`);
566
+ } finally {
567
+ await handle.close();
568
+ }
569
+ }
570
+ export { migrateCommand };