Skip to content

Email for professionals and teams

Permanently delete messages from Trash and Spam

midegob0ee52c37d9e
diff --git a/docs/api.md b/docs/api.md
index 2d0d0ed..38aae8f 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -178,6 +178,8 @@ To send a reply that threads correctly in the recipient's client, pass the paren
`GET /api/messages/{id}/thread` (session auth) returns every stored message in the same conversation, oldest first, excluding drafts and trash. `GET /api/messages?group=thread` collapses a list to one row per conversation (its newest message matching the filter) and adds `threadCount`, `threadUnread` and `threadMessageIds`, the ids that row stands for within the current filter, so bulk actions can act on the whole conversation.
+`POST /api/messages/bulk` (session auth) with `action: "delete"` permanently removes the given messages, including their raw MIME and attachment objects, but only those already in Trash or Spam; others are skipped and counted in `skipped`. `POST /api/messages/empty` with `{ mailboxId, folder: "trash" | "spam" }` permanently deletes that folder's messages in batches of 100 and returns `{ deleted, remaining }`; call it again until `remaining` is 0. Both write an `email.delete` audit entry per message with `permanent: true`.
+
Messages composed in Mailflare are sent as HTML with a plain-text alternative derived from it. Quoted or forwarded content is wrapped in `<div class="mailflare-quote" data-mailflare-quote="1">` so the reader can fold it. `POST /api/drafts` accepts `forwardOfMessageId`, which copies that message's attachments onto the new draft; `DELETE /api/drafts/{id}/attachments/{attachmentId}` removes one, and `POST /api/send` with `draftId` sends the draft's stored files along with any uploaded in the request.
The dashboard composer accepts up to 10 attachments. An administrator sets the outgoing per-file and combined limit from 1 to 25 MB on **General** (`/general`); the default is 25 MB. Attachment metadata is stored in D1 and file content is stored in R2. Normal message downloads require access to the mailbox containing the message.
diff --git a/src/app/api/messages/bulk/route.ts b/src/app/api/messages/bulk/route.ts
index aea7b34..27a400f 100644
--- a/src/app/api/messages/bulk/route.ts
+++ b/src/app/api/messages/bulk/route.ts
@@ -6,12 +6,14 @@ import { getCurrentUser } from "@/lib/auth/cookies";
import { getEnv } from "@/lib/cloudflare";
import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
import { createAuditLog } from "@/lib/mailboxes/audit";
+import { permanentlyDeleteMessages } from "@/lib/email/permanent-delete";
import { applySpamFeedback } from "@/lib/spam/feedback";
import type { BulkMessagePayload } from "./types";
import {
getReadValueForBulkAction,
getStatusForBulkAction,
isAllowedBulkMessageAction,
+ isPermanentlyDeletableStatus,
} from "./utils";
export async function POST(request: Request) {
@@ -59,7 +61,7 @@ export async function POST(request: Request) {
...(folderId !== undefined ? { folderId } : {}),
};
- if (Object.keys(values).length === 0) {
+ if (payload.action !== "delete" && Object.keys(values).length === 0) {
return NextResponse.json({ error: "No changes requested" }, { status: 400 });
}
@@ -77,6 +79,14 @@ export async function POST(request: Request) {
if (allowedMessageIds.length === 0) {
return NextResponse.json({ error: "No accessible messages" }, { status: 404 });
}
+ if (payload.action === "delete") {
+ // Only mail already in Trash or Spam can be destroyed; anything else is skipped.
+ const deletable = selectedMessages.filter(
+ (message) => allowedMessageIds.includes(message.id) && isPermanentlyDeletableStatus(message.status),
+ );
+ const deleted = await permanentlyDeleteMessages(env, db, user.id, deletable, "bulk");
+ return NextResponse.json({ ok: true, deleted, skipped: allowedMessageIds.length - deleted });
+ }
if (payload.action === "spam") {
for (const messageId of allowedMessageIds) await applySpamFeedback(env, user, messageId, "spam");
return NextResponse.json({ ok: true });
diff --git a/src/app/api/messages/bulk/types.d.ts b/src/app/api/messages/bulk/types.d.ts
index 95de860..b2d93d1 100644
--- a/src/app/api/messages/bulk/types.d.ts
+++ b/src/app/api/messages/bulk/types.d.ts
@@ -1,4 +1,7 @@
-export type BulkMessageAction = "archive" | "trash" | "spam" | "read" | "unread" | "inbox" | "folder";
+export type BulkMessageAction = "archive" | "trash" | "spam" | "read" | "unread" | "inbox" | "folder" | "delete";
+
+/** Folders whose messages can be permanently deleted or emptied in one go. */
+export type PermanentDeleteFolder = "trash" | "spam";
export type BulkMessagePayload = {
messageIds?: string[];
diff --git a/src/app/api/messages/bulk/utils.ts b/src/app/api/messages/bulk/utils.ts
index 71a9175..05a090c 100644
--- a/src/app/api/messages/bulk/utils.ts
+++ b/src/app/api/messages/bulk/utils.ts
@@ -1,4 +1,4 @@
-import type { BulkMessageAction } from "./types";
+import type { BulkMessageAction, PermanentDeleteFolder } from "./types";
const allowedBulkActions = new Set<BulkMessageAction>([
"archive",
@@ -8,6 +8,7 @@ const allowedBulkActions = new Set<BulkMessageAction>([
"unread",
"inbox",
"folder",
+ "delete",
]);
export function isAllowedBulkMessageAction(action: unknown): action is BulkMessageAction {
@@ -28,3 +29,15 @@ export function getReadValueForBulkAction(action: BulkMessageAction): boolean |
if (action === "unread") return false;
return null;
}
+
+/**
+ * Permanent deletion is only offered for mail the user already threw away, so a
+ * stray "delete" can never destroy something still in the inbox, a folder or Sent.
+ */
+export function isPermanentlyDeletableStatus(status: string | null | undefined): status is PermanentDeleteFolder {
+ return status === "trash" || status === "spam";
+}
+
+export function isPermanentDeleteFolder(folder: unknown): folder is PermanentDeleteFolder {
+ return folder === "trash" || folder === "spam";
+}
diff --git a/src/app/api/messages/empty/route.ts b/src/app/api/messages/empty/route.ts
new file mode 100644
index 0000000..46d62e3
--- /dev/null
+++ b/src/app/api/messages/empty/route.ts
@@ -0,0 +1,46 @@
+import { and, count, eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { messages } from "@/db/schema";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { permanentlyDeleteMessages } from "@/lib/email/permanent-delete";
+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
+import { isPermanentDeleteFolder } from "../bulk/utils";
+import type { EmptyFolderPayload } from "./types";
+import { EMPTY_FOLDER_BATCH_SIZE } from "./utils";
+
+/**
+ * Permanently delete everything in a mailbox's Trash or Spam. Work is done in
+ * batches so a large folder stays within one Worker invocation's limits; the
+ * response reports what is left and the client calls again until it is zero.
+ */
+export async function POST(request: Request) {
+ const env = getEnv();
+ const user = await getCurrentUser(env, request);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const payload = (await request.json().catch(() => ({}))) as EmptyFolderPayload;
+ if (!payload.mailboxId || !isPermanentDeleteFolder(payload.folder)) {
+ return NextResponse.json({ error: "A mailbox and a Trash or Spam folder are required" }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const access = await getMailboxAccessLevel(db, user, payload.mailboxId);
+ if (!access?.canManage) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+
+ const inFolder = and(eq(messages.mailboxId, payload.mailboxId), eq(messages.status, payload.folder));
+ const batch = await db
+ .select({ id: messages.id, mailboxId: messages.mailboxId, rawR2Key: messages.rawR2Key, status: messages.status })
+ .from(messages)
+ .where(inFolder)
+ .limit(EMPTY_FOLDER_BATCH_SIZE);
+ const deleted = await permanentlyDeleteMessages(env, db, user.id, batch, "empty");
+ const [left] = await db.select({ n: count() }).from(messages).where(inFolder);
+
+ return NextResponse.json({ ok: true, deleted, remaining: left?.n ?? 0 });
+}
diff --git a/src/app/api/messages/empty/types.d.ts b/src/app/api/messages/empty/types.d.ts
new file mode 100644
index 0000000..17d3687
--- /dev/null
+++ b/src/app/api/messages/empty/types.d.ts
@@ -0,0 +1,13 @@
+import type { PermanentDeleteFolder } from "../bulk/types";
+
+export type EmptyFolderPayload = {
+ mailboxId?: string;
+ folder?: PermanentDeleteFolder;
+};
+
+export type EmptyFolderResponse = {
+ ok?: boolean;
+ deleted?: number;
+ remaining?: number;
+ error?: string;
+};
diff --git a/src/app/api/messages/empty/utils.ts b/src/app/api/messages/empty/utils.ts
new file mode 100644
index 0000000..e9f3cc9
--- /dev/null
+++ b/src/app/api/messages/empty/utils.ts
@@ -0,0 +1,2 @@
+/** Messages removed per request; each one costs an R2 delete and two D1 writes. */
+export const EMPTY_FOLDER_BATCH_SIZE = 100;
diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx
index e405421..b5e59a3 100644
--- a/src/components/message-actions/message-actions.tsx
+++ b/src/components/message-actions/message-actions.tsx
@@ -12,6 +12,7 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { MessageActionsProps, ReplyMode } from "./types";
+import { getPermanentDeleteConfirmText, supportsPermanentDelete } from "@/lib/messages/permanent-delete-utils";
import {
confirmTrashWithoutUnsubscribe,
blockMessageContact,
@@ -19,6 +20,7 @@ import {
createReplyDraft,
createTrashSenderRule,
getMessageActionRedirect,
+ getMessageBackHref,
getMoveMessageActions,
getReplyRecipients,
getReplyThreading,
@@ -71,6 +73,26 @@ export function MessageActions({
}
}, [messageId, direction, router]);
+ // In Trash and Spam the delete button removes the message for good instead of
+ // being a no-op, after the user confirms.
+ const canDeleteForever = supportsPermanentDelete(status);
+ const deleteForever = useCallback(async () => {
+ if (!window.confirm(getPermanentDeleteConfirmText(1))) return;
+ setMoreOpen(false);
+ setPendingAction("delete");
+ setError(null);
+ try {
+ await runSingleMessageAction(messageId, "delete");
+ router.push(getMessageBackHref(direction, status));
+ router.refresh();
+ } catch {
+ setError("Could not delete message");
+ setPendingAction(null);
+ }
+ }, [messageId, direction, status, router]);
+ const onTrashClick = () => (canDeleteForever ? void deleteForever() : void runAction("trash"));
+ const trashLabel = canDeleteForever ? "Delete forever" : "Move to trash";
+
const replyable = useMemo(() => message ?? {
direction,
fromAddr: senderAddress,
@@ -245,9 +267,9 @@ export function MessageActions({
<Button
variant="ghost"
size="roundedSM"
- aria-label="Move to trash"
- disabled={disabled || status === "trash"}
- onClick={() => runAction("trash")}
+ aria-label={trashLabel}
+ disabled={disabled}
+ onClick={onTrashClick}
>
<Trash2 size={iconSize} />
</Button>
@@ -286,13 +308,14 @@ export function MessageActions({
<ShieldAlert size={iconSize} />
</Button>
</Tooltip>
- <Tooltip label={shortcutsEnabled ? "Delete (#)" : "Delete"}>
+ <Tooltip label={canDeleteForever ? "Delete forever" : shortcutsEnabled ? "Delete (#)" : "Delete"}>
<Button
variant="ghost"
size="roundedSM"
- aria-label={shortcutsEnabled ? "Move to trash (#)" : "Move to trash"}
- disabled={disabled || status === "trash"}
- onClick={() => runAction("trash")}
+ aria-label={canDeleteForever ? trashLabel : shortcutsEnabled ? "Move to trash (#)" : "Move to trash"}
+ disabled={disabled}
+ onClick={onTrashClick}
+ className={canDeleteForever ? "text-red-600 hover:text-red-700" : undefined}
>
<Trash2 size={iconSize} />
</Button>
diff --git a/src/components/messages/bulk-message-toolbar.tsx b/src/components/messages/bulk-message-toolbar.tsx
index 9064485..fcfa474 100644
--- a/src/components/messages/bulk-message-toolbar.tsx
+++ b/src/components/messages/bulk-message-toolbar.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMailboxFolders } from "./use-mailbox-folders";
import { Tooltip } from "@/components/ui/tooltip";
+import { supportsPermanentDelete } from "@/lib/messages/permanent-delete-utils";
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { BulkMessageToolbarProps } from "./types";
@@ -32,6 +33,8 @@ export function BulkMessageToolbar({
const trash = folder === "trash"
? { action: "inbox", label: "Restore", Icon: Undo2 }
: { action: "trash", label: "Delete", Icon: Trash2 };
+ // Trash and Spam also offer the irreversible delete; the page confirms before running it.
+ const canDeleteForever = supportsPermanentDelete(folder);
const moveOptions = [
{ value: "inbox", label: "Inbox", Icon: Inbox, hidden: !folder || folder === "inbox" },
{ value: "archive", label: "Archived", Icon: Archive, hidden: folder === "archived" },
@@ -63,6 +66,13 @@ export function BulkMessageToolbar({
<trash.Icon className="h-4 w-4" />
</Button>
</Tooltip>
+ {canDeleteForever && (
+ <Tooltip label="Delete forever">
+ <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700" onClick={() => onAction("delete")} disabled={pending} aria-label="Delete forever">
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ )}
<Tooltip label={hasUnreadSelection ? "Mark as read" : "Mark as unread"}>
<Button
variant="ghost"
@@ -120,6 +130,9 @@ export function BulkMessageToolbar({
<DropdownMenu.Content align="end" sideOffset={4} className="z-[130] min-w-44 rounded-xl border border-neutral-200 bg-white p-1 shadow-xl md:hidden">
<DropdownMenu.Item className={menuItemClass} onSelect={() => onAction(archive.action as BulkMessageAction)}><archive.Icon className="h-4 w-4" />{archive.label}</DropdownMenu.Item>
<DropdownMenu.Item className={menuItemClass} onSelect={() => onAction(spam.action as BulkMessageAction)}><spam.Icon className="h-4 w-4" />{spam.label}</DropdownMenu.Item>
+ {canDeleteForever && (
+ <DropdownMenu.Item className={`${menuItemClass} text-red-600`} onSelect={() => onAction("delete")}><Trash2 className="h-4 w-4" />Delete forever</DropdownMenu.Item>
+ )}
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
<DropdownMenu.Item className={menuItemClass} onSelect={onClearSelection}><X className="h-4 w-4" />Clear selection</DropdownMenu.Item>
</DropdownMenu.Content>
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index baff6bf..9ac17bd 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -3,7 +3,7 @@
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import type { MouseEvent } from "react";
-import { Archive, ChevronLeft, ChevronRight, ListFilter, Mail, MailOpen } from "lucide-react";
+import { Archive, ChevronLeft, ChevronRight, ListFilter, Mail, MailOpen, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Tooltip } from "@/components/ui/tooltip";
@@ -34,7 +34,14 @@ import {
formatEmailPageTitle,
getMailboxAddress,
runBulkMessageAction,
+ emptyMessageFolder,
} from "./utils";
+import {
+ getEmptyFolderConfirmText,
+ getEmptyFolderLabel,
+ getPermanentDeleteConfirmText,
+ supportsPermanentDelete,
+} from "@/lib/messages/permanent-delete-utils";
import clsx from "clsx";
const pageSize = 25;
@@ -282,6 +289,7 @@ export function MessageFolderPage({
Array<{ id: string; read: boolean }>
>([]);
const [pendingBulkAction, setPendingBulkAction] = useState(false);
+ const [emptyingFolder, setEmptyingFolder] = useState(false);
const [unreadOnly, setUnreadOnly] = useState(false);
const [conversationView] = useConversationView();
const grouped = conversationView && config.folder !== "drafts";
@@ -364,8 +372,28 @@ export function MessageFolderPage({
});
}
+ const permanentDeleteFolder = !config.folderId && supportsPermanentDelete(config.folder) ? config.folder : null;
+ async function emptyFolder() {
+ if (!permanentDeleteFolder || !selectedMailbox?.id) return;
+ if (!window.confirm(getEmptyFolderConfirmText(permanentDeleteFolder, titleTotal))) return;
+ setEmptyingFolder(true);
+ try {
+ await emptyMessageFolder(selectedMailbox.id, permanentDeleteFolder);
+ setOffset(0);
+ } catch (error) {
+ console.error(error);
+ window.alert(`Could not empty ${permanentDeleteFolder === "trash" ? "Trash" : "Spam"}. Please try again.`);
+ } finally {
+ setEmptyingFolder(false);
+ }
+ }
+
async function runSelectedAction(action: BulkMessageAction, folderId?: string) {
if (selectedIds.length === 0) return;
+ if (action === "delete") {
+ const ids = expandSelectedIds(selectedIds);
+ if (!window.confirm(getPermanentDeleteConfirmText(ids.length))) return;
+ }
setPendingBulkAction(true);
const previousMessages = messages;
@@ -470,6 +498,22 @@ export function MessageFolderPage({
</Button>
</Tooltip>
)}
+ {permanentDeleteFolder && (
+ <Tooltip label={getEmptyFolderLabel(permanentDeleteFolder)}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={getEmptyFolderLabel(permanentDeleteFolder)}
+ disabled={emptyingFolder || isLoading || total === 0}
+ onClick={() => void emptyFolder()}
+ className="gap-1.5 text-xs font-medium text-red-600 hover:text-red-700"
+ >
+ <Trash2 className="h-4 w-4" />
+ {!compact && <span className="max-md:hidden">{emptyingFolder ? "Emptying…" : getEmptyFolderLabel(permanentDeleteFolder)}</span>}
+ </Button>
+ </Tooltip>
+ )}
{!compact && headerIcons.map((Icon, index) => (
<Icon key={index} className="h-4 w-4" />
))}
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index 71d216e..15bc901 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -7,6 +7,8 @@ import type { MailboxOption } from "@/components/mailbox-provider";
import type { EmailPageTitleInput } from "./types";
import type { MessageFolderConfig } from "./types";
import type { PageRange } from "./types";
+import type { PermanentDeleteFolder } from "@/app/api/messages/bulk/types";
+import type { EmptyFolderResponse } from "@/app/api/messages/empty/types";
export function getMessageParty(
message: Message,
@@ -91,3 +93,24 @@ export async function runBulkMessageAction(messageIds: string[], action: string,
if (action === "read" || action === "unread") markMessagesReadInCaches(messageIds, action === "read");
if (notify) window.dispatchEvent(new Event("mailflare:messages-changed"));
}
+
+/**
+ * Empty a mailbox's Trash or Spam. The API deletes in batches and reports what is
+ * left, so keep calling until nothing remains (or a call stops making progress).
+ */
+export async function emptyMessageFolder(mailboxId: string, folder: PermanentDeleteFolder): Promise<number> {
+ let deletedTotal = 0;
+ for (;;) {
+ const response = await authFetch("/api/messages/empty", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mailboxId, folder }),
+ });
+ const data = (await response.json().catch(() => ({}))) as EmptyFolderResponse;
+ if (!response.ok) throw new Error(data.error ?? "Unable to empty folder");
+ deletedTotal += data.deleted ?? 0;
+ if (!data.remaining || !data.deleted) break;
+ }
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
+ return deletedTotal;
+}
diff --git a/src/lib/email/permanent-delete.ts b/src/lib/email/permanent-delete.ts
new file mode 100644
index 0000000..f38270a
--- /dev/null
+++ b/src/lib/email/permanent-delete.ts
@@ -0,0 +1,34 @@
+import type { AppDatabase } from "@/db";
+import { deleteMessageWithObjects } from "@/lib/email/message-cleanup";
+import { createAuditLog } from "@/lib/mailboxes/audit";
+
+type DeletableMessage = {
+ id: string;
+ mailboxId: string | null;
+ rawR2Key: string | null;
+ status: string;
+};
+
+/**
+ * Permanently remove messages (row, raw MIME and attachment objects) and audit
+ * each one. The audit row cannot point at the deleted message, since its
+ * `message_id` is a foreign key, so the id travels in the metadata instead.
+ */
+export async function permanentlyDeleteMessages(
+ env: CloudflareEnv,
+ db: AppDatabase,
+ actorUserId: string,
+ rows: DeletableMessage[],
+ source: "bulk" | "empty",
+): Promise<number> {
+ for (const row of rows) {
+ await deleteMessageWithObjects(env, db, row.id, row.rawR2Key);
+ await createAuditLog(env, {
+ actorUserId,
+ mailboxId: row.mailboxId,
+ action: "email.delete",
+ metadata: { permanent: true, source, messageId: row.id, previousStatus: row.status },
+ });
+ }
+ return rows.length;
+}
diff --git a/src/lib/messages/permanent-delete-utils.ts b/src/lib/messages/permanent-delete-utils.ts
new file mode 100644
index 0000000..657da8a
--- /dev/null
+++ b/src/lib/messages/permanent-delete-utils.ts
@@ -0,0 +1,22 @@
+import type { PermanentDeleteFolder } from "@/app/api/messages/bulk/types";
+
+const folderLabels: Record<PermanentDeleteFolder, string> = { trash: "Trash", spam: "Spam" };
+
+/** Whether the folder being viewed offers "Delete forever" and "Empty …". */
+export function supportsPermanentDelete(folder: string | null | undefined): folder is PermanentDeleteFolder {
+ return folder === "trash" || folder === "spam";
+}
+
+export function getEmptyFolderLabel(folder: PermanentDeleteFolder): string {
+ return `Empty ${folderLabels[folder]}`;
+}
+
+export function getPermanentDeleteConfirmText(count: number): string {
+ const subject = count === 1 ? "this message" : `these ${count} messages`;
+ return `Permanently delete ${subject}? This cannot be undone.`;
+}
+
+export function getEmptyFolderConfirmText(folder: PermanentDeleteFolder, total?: number): string {
+ const what = total === 1 ? "the 1 message" : total && total > 1 ? `all ${total} messages` : "every message";
+ return `Permanently delete ${what} in ${folderLabels[folder]}? This cannot be undone.`;
+}
diff --git a/tests/permanent-delete.test.mjs b/tests/permanent-delete.test.mjs
new file mode 100644
index 0000000..21c83bf
--- /dev/null
+++ b/tests/permanent-delete.test.mjs
@@ -0,0 +1,62 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const directory = mkdtempSync(join(root, "node_modules", "mailflare-permanent-delete-test-"));
+after(() => rmSync(directory, { recursive: true, force: true }));
+await build({
+ stdin: {
+ contents: `
+ export { isAllowedBulkMessageAction, getStatusForBulkAction, getReadValueForBulkAction, isPermanentlyDeletableStatus, isPermanentDeleteFolder } from "./src/app/api/messages/bulk/utils.ts";
+ export { supportsPermanentDelete, getEmptyFolderLabel, getPermanentDeleteConfirmText, getEmptyFolderConfirmText } from "./src/lib/messages/permanent-delete-utils.ts";
+ `,
+ resolveDir: root,
+ sourcefile: "permanent-delete-test-entry.ts",
+ },
+ outfile: join(directory, "entry.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node24",
+ tsconfig: join(root, "tsconfig.json"),
+ packages: "external",
+ logLevel: "silent",
+});
+const m = await import(pathToFileURL(join(directory, "entry.mjs")).href);
+
+test("delete is an accepted bulk action that changes neither status nor read state", () => {
+ assert.equal(m.isAllowedBulkMessageAction("delete"), true);
+ assert.equal(m.getStatusForBulkAction("delete"), null);
+ assert.equal(m.getReadValueForBulkAction("delete"), null);
+ assert.equal(m.isAllowedBulkMessageAction("destroy"), false);
+});
+
+test("only Trash and Spam messages can be permanently deleted", () => {
+ for (const status of ["trash", "spam"]) assert.equal(m.isPermanentlyDeletableStatus(status), true);
+ for (const status of ["received", "sent", "draft", "archived", "", null, undefined]) {
+ assert.equal(m.isPermanentlyDeletableStatus(status), false, String(status));
+ }
+ assert.equal(m.isPermanentDeleteFolder("trash"), true);
+ assert.equal(m.isPermanentDeleteFolder("inbox"), false);
+});
+
+test("the UI offers permanent delete only in Trash and Spam", () => {
+ assert.equal(m.supportsPermanentDelete("trash"), true);
+ assert.equal(m.supportsPermanentDelete("spam"), true);
+ assert.equal(m.supportsPermanentDelete("inbox"), false);
+ assert.equal(m.supportsPermanentDelete(undefined), false);
+ assert.equal(m.getEmptyFolderLabel("trash"), "Empty Trash");
+ assert.equal(m.getEmptyFolderLabel("spam"), "Empty Spam");
+});
+
+test("confirmation text says how much is lost and that it is irreversible", () => {
+ assert.equal(m.getPermanentDeleteConfirmText(1), "Permanently delete this message? This cannot be undone.");
+ assert.equal(m.getPermanentDeleteConfirmText(3), "Permanently delete these 3 messages? This cannot be undone.");
+ assert.equal(m.getEmptyFolderConfirmText("trash", 12), "Permanently delete all 12 messages in Trash? This cannot be undone.");
+ assert.equal(m.getEmptyFolderConfirmText("spam", 1), "Permanently delete the 1 message in Spam? This cannot be undone.");
+ assert.equal(m.getEmptyFolderConfirmText("trash"), "Permanently delete every message in Trash? This cannot be undone.");
+});