From 84f4797804f5314177b60e4c8f5c92bf2278fcf2 Mon Sep 17 00:00:00 2001 From: Will McLemore Date: Wed, 25 Nov 2026 09:11:39 -0600 Subject: [PATCH] refactor(cli): strict parseArgs, unified --json contract, mailbox/body/date fixes, and updated docs --- CHANGELOG.md | 30 + README.md | 105 ++- src/cli.ts | 1265 +++++++++++++++++++++++++++-------- src/json-format.ts | 82 ++- test/cli-ergonomics.test.js | 420 ++++++++++++ 5 files changed, 1563 insertions(+), 339 deletions(-) create mode 100644 test/cli-ergonomics.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 4528e9e..ff482ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## Unreleased + +### Added +- `gmcli --version` / `-v` flag reading version from `package.json` (with `--json` support). +- Unified `--json` output across all remaining commands: `labels `, `drafts get --download`, `drafts create`, `drafts delete`, `drafts send`, `send`, and `accounts list|add|remove|credentials`. +- `drafts audit` read-only stale-draft auditor with `--check-sent` duplicate detection, markdown/table/JSON outputs, and short alias `-m` (#17). +- Canonical `npm run install-local` script to rebuild, install globally, and verify the `gmcli` binary on `PATH` (#16). +- Help and `parseArgs` short-alias parity tests (#15) and CLI ergonomics test suite. + +### Changed +- Strict `parseArgs` parsing across all commands (`accounts`, `thread`, `drafts get/delete/send`, `url`, `search`, `labels`, `drafts create`, `send`); unknown flags fail cleanly instead of being silently ignored or treated as positional IDs. +- Shared compose argument parser for `drafts create` and `send`: rejects specifying both `--body` and `--body-file` together and reports the exact missing required option (`--to`, `--subject`, `--body` or `--body-file`). +- Error usage (`usage(1)`) now writes to `stderr`, while explicit `--help` / `-h` writes to `stdout`. +- `thread` output now displays `Gmail-Message-ID:` separately from RFC 822 `Message-ID:` and includes `Cc:` when present. +- `search` now summarizes each thread using its latest message for sender/date and the union of labels across all messages in the thread, validates `--max` as a positive integer, guards malformed `Date` headers, and sanitizes control/tab characters in TSV columns. +- CI now runs tests and non-mutating lint/typecheck checks; cleaned Biome and `package.json` config (#18). +- Refreshed `--help` output and `README.md` for `--json`, `--version`, `--body-file`, `--html`, short aliases, and env-first Doppler credentials. + +### Fixed +- Stopped global `-h` / `--help` and `--json` scanning from hijacking option values (e.g., `--subject "foo --json"` or `--body=-h`). +- `labels ` now exits `1` if neither `--add` nor `--remove` is provided or if any thread modification fails (printing errors to `stderr` in text mode or structured `results`/`errors` in `--json` mode). +- `accounts remove ` now exits `1` when the account is not found. +- `decodeBody` now skips named attachments and non-`text/*` MIME parts so inline binary attachments are never dumped as message text. +- `formatSize` now clamps unit indexes so sizes >= 1 TB never format as `undefined`. +- `parseMailboxList` now respects quoted display names containing commas (e.g. `"McLemore, Will" , jane@example.com`). +- `drafts create --reply-to` now preserves the Gmail thread when given a `threadId` (#14). + +### Security +- Hardened MIME header/body encoding, inbound/outbound attachment path validation, OAuth CSRF state and HTML error escaping, and `0700`/`0600` atomic token storage (#19). + ## 0.5.0 ### Added diff --git a/README.md b/README.md index 8cd03bb..d09743a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Minimal Gmail CLI for searching, reading threads, managing labels, drafts, and sending emails. -> **Fork Notice:** This is a fork of [@mariozechner/gmcli](https://github.com/badlogic/gmcli) by Mario Zechner with bug fixes for `--reply-to` thread ID handling and `drafts send` crash. See [CHANGELOG.md](CHANGELOG.md) for details. +> **Fork Notice:** This is a fork of [@mariozechner/gmcli](https://github.com/badlogic/gmcli) by Mario Zechner with bug fixes, `--json` support across all commands, stale-draft auditing, and security hardening. See [CHANGELOG.md](CHANGELOG.md) for details. ## Install @@ -33,7 +33,16 @@ Before adding an account, you need OAuth2 credentials from Google Cloud Console: - Application type: "Desktop app" - Download the JSON file -Then: +### Env-first credentials (recommended, e.g. Doppler) + +`gmcli` checks `GMCLI_CLIENT_ID` and `GMCLI_CLIENT_SECRET` in the environment before falling back to `~/.gmcli/credentials.json`. You can inject them at runtime without storing OAuth client secrets on disk: + +```bash +doppler run -- gmcli accounts add you@gmail.com +doppler run -- gmcli you@gmail.com search "in:inbox" +``` + +### File-based credentials (fallback) ```bash gmcli accounts credentials ~/path/to/credentials.json @@ -43,30 +52,45 @@ gmcli accounts add you@gmail.com ## Usage ``` -gmcli accounts Account management +gmcli accounts [options] Account management gmcli [options] Gmail operations +gmcli --help | -h Show help +gmcli --version | -v Show version ``` +### Global options & short aliases + +- `--json` — Supported on all commands (`accounts`, `search`, `thread`, `labels`, `drafts`, `send`, `url`). Emits a single JSON object with `"ok": true` on success or `{"ok": false, "error": "..."}` on failure. +- `--help`, `-h` — Show usage on stdout and exit `0`. Usage errors print to stderr and exit `1`. +- `--version`, `-v` — Print the installed `gmcli` version (supports `--json`). +- Short aliases: + - Global: `--help`/`-h`, `--version`/`-v` + - `search`: `--max`/`-m`, `--page`/`-p` + - `labels`: `--add`/`-a`, `--remove`/`-r` + - `drafts audit`: `--max`/`-m` + ## Commands ### accounts ```bash -gmcli accounts credentials # Set OAuth credentials (once) -gmcli accounts list # List configured accounts -gmcli accounts add # Add account (opens browser) -gmcli accounts add --manual # Add account (browserless, paste redirect URL) -gmcli accounts remove # Remove account +gmcli accounts credentials [--json] # Set fallback OAuth credentials (once) +gmcli accounts list [--json] # List configured accounts +gmcli accounts add [--json] # Add account (opens browser) +gmcli accounts add --manual [--json] # Add account (browserless, paste redirect URL) +gmcli accounts remove [--json] # Remove account (exits 1 if not found) ``` ### search -Search threads using Gmail query syntax. Returns thread ID, date, sender, subject, and labels. +Search threads using Gmail query syntax. Returns thread ID, latest message date and sender, subject, and the union of thread labels. ```bash -gmcli search [--max N] [--page TOKEN] +gmcli search [--max N|-m N] [--page TOKEN|-p TOKEN] [--json] ``` +`--max` / `-m` must be a positive integer (default: `10`). + Query examples: - `in:inbox`, `in:sent`, `in:drafts`, `in:trash`, `in:spam` - `is:unread`, `is:starred`, `is:important` @@ -80,19 +104,19 @@ Query examples: Examples: ```bash gmcli you@gmail.com search "in:inbox" -gmcli you@gmail.com search "is:unread" --max 50 +gmcli you@gmail.com search "is:unread" -m 50 --json gmcli you@gmail.com search "from:someone@example.com has:attachment" ``` ### thread -Get a thread with all messages. Shows Message-ID, headers, body, and attachments for each message. +Get a thread with all messages. Shows `Gmail-Message-ID`, RFC 822 `Message-ID`, headers (including `Cc`), body, and attachments for each message. > **Send verification note:** `gmcli thread` alone is not sufficient send verification because Gmail threads can include `DRAFT` messages inline alongside sent messages. Use `gmcli drafts audit --check-sent` or an explicit `in:sent` search to verify whether a message was actually sent. ```bash -gmcli thread # View thread -gmcli thread --download # Download attachments +gmcli thread [--json] # View thread +gmcli thread --download [--json] # Download attachments ``` Attachments are saved to `~/.gmcli/attachments/`. @@ -100,34 +124,34 @@ Attachments are saved to `~/.gmcli/attachments/`. ### labels ```bash -gmcli labels list # List all labels (ID, name, type) -gmcli labels [--add L] [--remove L] # Modify labels on threads +gmcli labels list [--json] # List all labels (ID, name, type) +gmcli labels [--add L|-a L] [--remove L|-r L] [--json] # Modify labels on threads ``` -You can use label names or IDs when modifying (names are case-insensitive). +At least one of `--add` (`-a`) or `--remove` (`-r`) is required when modifying labels, and the command exits `1` if any thread fails. You can use label names or IDs (names are case-insensitive). System labels: `INBOX`, `UNREAD`, `STARRED`, `IMPORTANT`, `TRASH`, `SPAM` Examples: ```bash -gmcli you@gmail.com labels list -gmcli you@gmail.com labels abc123 --remove UNREAD +gmcli you@gmail.com labels list --json +gmcli you@gmail.com labels abc123 -r UNREAD gmcli you@gmail.com labels abc123 --add Work --remove INBOX -gmcli you@gmail.com labels abc123 def456 --add STARRED +gmcli you@gmail.com labels abc123 def456 -a STARRED --json ``` ### drafts ```bash -gmcli drafts list # List all drafts +gmcli drafts list [--json] # List all drafts gmcli drafts audit [--older-than 1d] [--check-sent] [--max N|-m N] [--format markdown|table] [--json] - # Read-only stale draft audit with sent-duplicate evidence -gmcli drafts get # View draft with attachments -gmcli drafts get --download # Download draft attachments -gmcli drafts delete # Delete draft -gmcli drafts send # Send draft + # Read-only stale draft audit with sent-duplicate evidence +gmcli drafts get [--json] # View draft with attachments +gmcli drafts get --download [--json] # Download draft attachments +gmcli drafts delete [--json] # Delete draft +gmcli drafts send [--json] # Send draft -gmcli drafts create --to --subject --body [options] +gmcli drafts create --to --subject (--body | --body-file ) [options] ``` `drafts audit` is strictly read-only (never sends or deletes mail) and classifies each stale draft as `likely_duplicate_sent`, `conflicting_obsolete_candidate`, `not_proven_duplicate`, or `needs_human_decision`. Default `--format markdown` produces a table ready to paste into a task note. @@ -137,38 +161,45 @@ gmcli drafts create --to --subject --body [options] Send an email directly. ```bash -gmcli send --to --subject --body [options] +gmcli send --to --subject (--body | --body-file ) [options] ``` Options for `drafts create` and `send`: - `--to ` - Recipients (comma-separated, required) - `--subject ` - Subject line (required) -- `--body ` - Message body (required) +- `--body ` - Message body (mutually exclusive with `--body-file`) +- `--body-file ` - Read message body from a file (mutually exclusive with `--body`; recommended for multiline bodies) +- `--html` - Send body as `text/html` instead of `text/plain` - `--cc ` - CC recipients (comma-separated) - `--bcc ` - BCC recipients (comma-separated) - `--reply-to ` - Reply to message (sets In-Reply-To/References headers and thread; accepts Gmail message ID or thread ID; canonicalizes equivalent reply subjects to Gmail's source thread subject) - `--in-reply-to ` - Alias for `--reply-to` - `--thread ` - Force a specific Gmail thread without setting reply headers; prefer `--reply-to` for normal replies - `--attach ` - Attach file (can be used multiple times) +- `--json` - Emit machine-readable JSON response Examples: ```bash # Create draft gmcli you@gmail.com drafts create --to a@x.com --subject "Hi" --body "Hello" +# Create HTML draft from file with JSON output +gmcli you@gmail.com drafts create --to a@x.com --subject "Update" \ + --body-file update.html --html --json + # Create reply draft gmcli you@gmail.com drafts create --to a@x.com --subject "Re: Topic" \ --body "My reply" --reply-to 19aea1f2f3532db5 # Send draft -gmcli you@gmail.com drafts send r1234567890 +gmcli you@gmail.com drafts send r1234567890 --json # Send directly gmcli you@gmail.com send --to a@x.com --subject "Hi" --body "Hello" # Send reply with attachment gmcli you@gmail.com send --to a@x.com --subject "Re: Topic" \ - --body "See attached" --reply-to 19aea1f2f3532db5 --attach doc.pdf + --body-file reply.txt --reply-to 19aea1f2f3532db5 --attach doc.pdf ``` ### url @@ -176,20 +207,20 @@ gmcli you@gmail.com send --to a@x.com --subject "Re: Topic" \ Generate Gmail web URLs for threads. Uses canonical URL format with email parameter (works regardless of account order in browser). ```bash -gmcli url +gmcli url [--json] ``` Example: ```bash -gmcli you@gmail.com url 19aea1f2f3532db5 19aea1f2f3532db6 +gmcli you@gmail.com url 19aea1f2f3532db5 19aea1f2f3532db6 --json ``` ## Data Storage -All data is stored in `~/.gmcli/`: -- `credentials.json` - OAuth client credentials -- `accounts.json` - Account tokens -- `attachments/` - Downloaded attachments +- `GMCLI_CLIENT_ID` / `GMCLI_CLIENT_SECRET` — Env-first OAuth client credentials (e.g. via `doppler run --`), checked before `~/.gmcli/credentials.json` +- `~/.gmcli/credentials.json` — Fallback OAuth client credentials file (`0600`) +- `~/.gmcli/accounts.json` — Account refresh tokens (`0600`) +- `~/.gmcli/attachments/` — Downloaded attachments (`0700` dir, `0600` files) ## Development diff --git a/src/cli.ts b/src/cli.ts index 1fa6470..9104aa7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,35 +1,88 @@ #!/usr/bin/env node import * as fs from "fs"; +import * as path from "path"; +import { fileURLToPath } from "url"; import { parseArgs } from "util"; import { formatDraftAuditMarkdown, formatDraftAuditTable } from "./drafts-audit.js"; -import { GmailService, collectAttachmentParts, isDraftMessage } from "./gmail-service.js"; -import { consumeJsonFlag, parseMailbox, parseMailboxList } from "./json-format.js"; +import { GmailService, type ThreadSearchResult, collectAttachmentParts, isDraftMessage } from "./gmail-service.js"; +import { type Mailbox, parseMailbox, parseMailboxList, splitMailboxList } from "./json-format.js"; const service = new GmailService(); let jsonOutput = false; +export interface ParsedComposeArgs { + to: string[]; + cc?: string[]; + bcc?: string[]; + subject: string; + body: string; + html?: boolean; + threadId?: string; + replyToMessageId?: string; + attachments?: string[]; + json: boolean; + help: boolean; +} + +export interface HeaderEntry { + name?: string | null; + value?: string | null; +} + +export interface SearchThreadSummary { + id: string; + date: string | null; + dateFormatted: string; + fromRaw: string; + from: Mailbox | null; + subject: string | null; + labels: string[]; + snippet: string | null; + messageIds: string[]; +} + +export function getPackageVersion(): string { + const dir = path.dirname(fileURLToPath(import.meta.url)); + const pkgPath = path.resolve(dir, "..", "package.json"); + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")) as { version?: string }; + return pkg.version || "0.0.0"; +} + function usage(exitCode = 1): never { - console.log(`gmcli - Gmail CLI + const write = exitCode === 0 ? console.log : console.error; + write(`gmcli - Gmail CLI USAGE - gmcli accounts Account management + gmcli accounts [options] Account management gmcli [options] Gmail operations + gmcli --help | -h Show this help message + gmcli --version | -v Show gmcli version + +GLOBAL OPTIONS + + --json Emit machine-readable JSON output + (supported on all commands; errors emit + {"ok":false,"error":"..."}) + --help, -h Show this help message + --version, -v Print version and exit ACCOUNT COMMANDS - gmcli accounts credentials Set OAuth credentials (once) - gmcli accounts list List configured accounts - gmcli accounts add [--manual] Add account (--manual for browserless OAuth) - gmcli accounts remove Remove account + gmcli accounts credentials [--json] + Set OAuth credentials (once) + gmcli accounts list [--json] List configured accounts + gmcli accounts add [--manual] [--json] + Add account (--manual for browserless OAuth) + gmcli accounts remove [--json] Remove account (exits 1 if not found) GMAIL COMMANDS - gmcli search [--max N|-m N] [--page TOKEN|-p TOKEN] + gmcli search [--max N|-m N] [--page TOKEN|-p TOKEN] [--json] Search threads using Gmail query syntax. - Returns: thread ID, date, sender, subject, labels. - --max, -m sets the result limit (default: 10). + Returns: thread ID, latest date, latest sender, subject, thread labels. + --max, -m sets the result limit as a positive integer (default: 10). --page, -p fetches a Gmail next-page token from a prior search. --json emits a stable machine-readable object instead of TSV/prose. @@ -42,24 +95,25 @@ GMAIL COMMANDS label:Work, label:UNREAD Combine: "in:inbox is:unread from:boss@company.com" - gmcli thread [--download] + gmcli thread [--download] [--json] Get thread with all messages. - Shows: Message-ID, headers, body, attachments. + Shows: Gmail-Message-ID, Message-ID, headers (including Cc), body, attachments. --download saves attachments to ~/.gmcli/attachments/ Note: 'gmcli thread' alone is not sufficient send verification because drafts can render inline in a thread like sent messages. Verify sent status with 'drafts audit --check-sent' or an 'in:sent' search. - gmcli labels list + gmcli labels list [--json] List all labels with ID, name, and type. - gmcli labels [--add L|-a L] [--remove L|-r L] + gmcli labels [--add L|-a L] [--remove L|-r L] [--json] Modify labels on threads (comma-separated for multiple). + Requires at least one of --add or --remove; exits 1 if any thread fails. Accepts label names or IDs (names are case-insensitive). System labels: INBOX, UNREAD, STARRED, IMPORTANT, TRASH, SPAM --add, -a adds label names or IDs; --remove, -r removes them. - gmcli drafts list + gmcli drafts list [--json] List all drafts. Returns: draft ID, message ID. gmcli drafts audit [--older-than 1d] [--check-sent] [--max N|-m N] @@ -79,27 +133,27 @@ GMAIL COMMANDS Note: 'gmcli thread' alone is not sufficient send verification because drafts can render inline like sent messages. - gmcli drafts get [--download] + gmcli drafts get [--download] [--json] View draft with attachments. --download saves attachments to ~/.gmcli/attachments/ - gmcli drafts delete + gmcli drafts delete [--json] Delete a draft. - gmcli drafts send + gmcli drafts send [--json] Send a draft. - gmcli drafts create --to --subject --body [options] + gmcli drafts create --to --subject (--body | --body-file ) [options] Create a new draft. - gmcli send --to --subject --body [options] + gmcli send --to --subject (--body | --body-file ) [options] Send an email directly. Options for drafts create / send: --to Recipients (comma-separated, required) --subject Subject line (required) - --body Message body (required) - --body-file Read body from file (overrides --body) + --body Message body (mutually exclusive with --body-file) + --body-file Read body from file (mutually exclusive with --body) --html Send as HTML email (default: plain text) --cc CC recipients (comma-separated) --bcc BCC recipients (comma-separated) @@ -113,26 +167,30 @@ GMAIL COMMANDS reply headers. Use --reply-to in normal cases; --thread is only for unusual threading needs. --attach Attach file (use multiple times for multiple files) + --json Emit machine-readable JSON response Short aliases: + global: --help/-h, --version/-v search: --max/-m, --page/-p labels: --add/-a, --remove/-r drafts audit: --max/-m - gmcli url + gmcli url [--json] Generate Gmail web URLs for threads. Uses canonical URL format with email parameter. EXAMPLES - gmcli accounts list + gmcli --version + gmcli accounts list --json gmcli you@gmail.com search "in:inbox is:unread" - gmcli you@gmail.com search "from:boss@company.com" --max 50 + gmcli you@gmail.com search "from:boss@company.com" --max 50 --json gmcli you@gmail.com thread 19aea1f2f3532db5 gmcli you@gmail.com thread 19aea1f2f3532db5 --download gmcli you@gmail.com labels list gmcli you@gmail.com labels abc123 --add Work --remove UNREAD gmcli you@gmail.com drafts create --to a@x.com --subject "Hi" --body "Hello" + gmcli you@gmail.com drafts create --to a@x.com --subject "Hi" --body-file body.txt --json gmcli you@gmail.com drafts audit --older-than=1d --check-sent gmcli you@gmail.com drafts send r1234567890 gmcli you@gmail.com send --to a@x.com --subject "Hi" --body "Hello" @@ -142,7 +200,10 @@ EXAMPLES DATA STORAGE - ~/.gmcli/credentials.json OAuth client credentials + GMCLI_CLIENT_ID / GMCLI_CLIENT_SECRET + Preferred OAuth client credentials via environment + (e.g. Doppler); checked before credentials.json + ~/.gmcli/credentials.json Fallback OAuth client credentials file ~/.gmcli/accounts.json Account tokens ~/.gmcli/attachments/ Downloaded attachments`); process.exit(exitCode); @@ -161,19 +222,351 @@ function emitJson(payload: Record): void { console.log(JSON.stringify(payload)); } +function hasStandaloneJsonFlag( + args: string[], + valueLongOptions: ReadonlySet, + valueShortOptions: ReadonlySet = new Set(), +): boolean { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") break; + if (arg === "--json") return true; + if (arg.startsWith("--")) { + if (arg.includes("=")) continue; + const name = arg.slice(2); + if (valueLongOptions.has(name)) { + i++; + } + } else if (arg.startsWith("-") && arg.length === 2) { + const short = arg.slice(1); + if (valueShortOptions.has(short)) { + i++; + } + } + } + return false; +} + +function maybeEnableJsonFromError( + args: string[], + valueLongOptions: ReadonlySet = new Set(), + valueShortOptions: ReadonlySet = new Set(), +): void { + if (!jsonOutput && hasStandaloneJsonFlag(args, valueLongOptions, valueShortOptions)) { + jsonOutput = true; + } +} + +export function getHeader(headers: HeaderEntry[] | undefined, name: string): string { + if (!headers) return ""; + const lower = name.toLowerCase(); + return headers.find((h) => h.name?.toLowerCase() === lower)?.value || ""; +} + +export function formatInternalDate(internalDate: string | null | undefined): string { + if (!internalDate) return ""; + const timestamp = Number(internalDate); + if (!Number.isFinite(timestamp)) return ""; + const date = new Date(timestamp); + if (!Number.isFinite(date.getTime())) return ""; + return date.toISOString(); +} + +export function formatSearchDate(dateHeader: string | undefined, internalDate?: string | null | undefined): string { + if (dateHeader) { + const parsed = new Date(dateHeader); + if (Number.isFinite(parsed.getTime())) { + return parsed.toISOString().slice(0, 16).replace("T", " "); + } + } + if (internalDate) { + const timestamp = Number(internalDate); + if (Number.isFinite(timestamp)) { + const parsed = new Date(timestamp); + if (Number.isFinite(parsed.getTime())) { + return parsed.toISOString().slice(0, 16).replace("T", " "); + } + } + } + return ""; +} + +export function sanitizeTsvField(value: string | undefined | null): string { + if (!value) return ""; + return value.replace(/[\r\n\t]+/g, " ").trim(); +} + +export function formatSize(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB"]; + const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1); + return `${(bytes / 1024 ** i).toFixed(i > 0 ? 1 : 0)} ${units[i]}`; +} + +function isTextBodyPart(part: any): boolean { + if (!part) return false; + if (typeof part.filename === "string" && part.filename.trim().length > 0) { + return false; + } + const mimeType = typeof part.mimeType === "string" ? part.mimeType.toLowerCase() : ""; + if (mimeType && !mimeType.startsWith("text/")) { + return false; + } + return true; +} + +export function decodeBody(payload: any): string { + if (!payload) return ""; + if (payload.body?.data && isTextBodyPart(payload)) { + return Buffer.from(payload.body.data, "base64url").toString(); + } + if (Array.isArray(payload.parts)) { + for (const part of payload.parts) { + if (part?.mimeType?.toLowerCase() === "text/plain" && isTextBodyPart(part) && part.body?.data) { + return Buffer.from(part.body.data, "base64url").toString(); + } + } + for (const part of payload.parts) { + if (Array.isArray(part?.parts)) { + const nested = decodeBody(part); + if (nested) return nested; + } + } + for (const part of payload.parts) { + if (isTextBodyPart(part) && part?.body?.data) { + return Buffer.from(part.body.data, "base64url").toString(); + } + } + } + return ""; +} + +export function parsePositiveIntOption(name: string, raw: string | undefined, defaultValue: number): number { + if (raw === undefined) return defaultValue; + const trimmed = raw.trim(); + if (!/^\d+$/.test(trimmed)) { + throw new Error(`Invalid --${name} value '${raw}'. Expected a positive integer.`); + } + const parsed = Number(trimmed); + if (!Number.isSafeInteger(parsed) || parsed <= 0) { + throw new Error(`Invalid --${name} value '${raw}'. Expected a positive integer.`); + } + return parsed; +} + +export function summarizeSearchThread( + thread: ThreadSearchResult["threads"][number], + idToName: Map, +): SearchThreadSummary { + const messages = thread.messages || []; + const latestMsg = messages[messages.length - 1]; + const firstMsg = messages[0]; + + const labelIdSet = new Set(); + for (const msg of messages) { + for (const id of msg.labelIds || []) { + labelIdSet.add(id); + } + } + const labels = [...labelIdSet].map((id) => idToName.get(id) || id); + + return { + id: thread.id, + date: latestMsg?.date || latestMsg?.internalDate || null, + dateFormatted: formatSearchDate(latestMsg?.date, latestMsg?.internalDate), + fromRaw: latestMsg?.from || "", + from: parseMailbox(latestMsg?.from), + subject: latestMsg?.subject || firstMsg?.subject || null, + labels, + snippet: latestMsg?.snippet || null, + messageIds: messages.map((m) => m.id).filter(Boolean), + }; +} + +// Accept both --reply-to and its --in-reply-to alias. If the caller supplies both +// with conflicting values, fail loudly rather than silently picking one. +export function resolveReplyToFlag(replyTo: string | undefined, inReplyTo: string | undefined): string | undefined { + if (replyTo && inReplyTo && replyTo !== inReplyTo) { + throw new Error( + `--reply-to (${replyTo}) and --in-reply-to (${inReplyTo}) were both supplied with different values. ` + + "Pass only one (they are aliases for the same option).", + ); + } + return replyTo ?? inReplyTo; +} + +const COMPOSE_VALUE_OPTIONS = new Set([ + "to", + "cc", + "bcc", + "subject", + "body", + "body-file", + "thread", + "reply-to", + "in-reply-to", + "attach", +]); + +export function parseComposeArgs(args: string[]): ParsedComposeArgs { + let values: { + to?: string; + cc?: string; + bcc?: string; + subject?: string; + body?: string; + "body-file"?: string; + html?: boolean; + thread?: string; + "reply-to"?: string; + "in-reply-to"?: string; + attach?: string[]; + json?: boolean; + help?: boolean; + }; + + try { + ({ values } = parseArgs({ + args, + options: { + to: { type: "string" }, + cc: { type: "string" }, + bcc: { type: "string" }, + subject: { type: "string" }, + body: { type: "string" }, + "body-file": { type: "string" }, + html: { type: "boolean" }, + thread: { type: "string" }, + "reply-to": { type: "string" }, + "in-reply-to": { type: "string" }, + attach: { type: "string", multiple: true }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: false, + })); + } catch (e) { + maybeEnableJsonFromError(args, COMPOSE_VALUE_OPTIONS); + throw e; + } + + const json = Boolean(values.json); + if (json) jsonOutput = true; + + if (values.help) { + return { + to: [], + subject: "", + body: "", + json, + help: true, + }; + } + + if (values.body !== undefined && values["body-file"] !== undefined) { + throw new Error("Cannot specify both --body and --body-file. Pass only one."); + } + + const to = splitMailboxList(values.to); + if (to.length === 0) { + throw new Error("Missing required option: --to"); + } + if (!values.subject?.trim()) { + throw new Error("Missing required option: --subject"); + } + + const hasBody = values.body !== undefined; + const hasBodyFile = values["body-file"] !== undefined; + if (!hasBody && !hasBodyFile) { + throw new Error("Missing required option: --body or --body-file"); + } + + const bodyContent = hasBodyFile ? fs.readFileSync(values["body-file"]!, "utf8") : values.body!; + if (!bodyContent) { + throw new Error( + hasBodyFile + ? `Message body file '${values["body-file"]}' is empty.` + : "Missing required option: --body must not be empty", + ); + } + + const cc = values.cc !== undefined ? splitMailboxList(values.cc) : undefined; + const bcc = values.bcc !== undefined ? splitMailboxList(values.bcc) : undefined; + const replyToMessageId = resolveReplyToFlag(values["reply-to"], values["in-reply-to"]); + + return { + to, + cc: cc && cc.length > 0 ? cc : undefined, + bcc: bcc && bcc.length > 0 ? bcc : undefined, + subject: values.subject, + body: bodyContent, + html: values.html, + threadId: values.thread, + replyToMessageId, + attachments: values.attach, + json, + help: false, + }; +} + +function consumeLeadingFlags( + args: string[], + allowVersion: boolean, +): { help: boolean; version: boolean; rest: string[] } { + let help = false; + let version = false; + let i = 0; + + while (i < args.length && args[i].startsWith("-")) { + const arg = args[i]; + if (arg === "--help" || arg === "-h") { + help = true; + i++; + } else if (allowVersion && (arg === "--version" || arg === "-v")) { + version = true; + i++; + } else if (arg === "--json") { + jsonOutput = true; + i++; + } else { + error(`Unknown option '${arg}'`); + } + } + + return { help, version, rest: args.slice(i) }; +} + async function main() { const args = process.argv.slice(2); - if (args.includes("--help") || args.includes("-h")) { - usage(0); - } if (args.length === 0) { usage(1); } - const first = args[0]; - const rest = args.slice(1); - try { + const top = consumeLeadingFlags(args, true); + if (top.help) { + usage(0); + } + if (top.version) { + if (top.rest.length > 0) { + error(`Unexpected argument '${top.rest[0]}' with --version`); + } + const version = getPackageVersion(); + if (jsonOutput) { + emitJson({ ok: true, version }); + } else { + console.log(version); + } + return; + } + + if (top.rest.length === 0) { + error("Missing command. Use --help for usage."); + } + + const first = top.rest[0]; + const rest = top.rest.slice(1); + // Handle 'accounts' command separately (no email required) if (first === "accounts") { await handleAccounts(rest); @@ -182,10 +575,12 @@ async function main() { // All other commands: first arg is email, second is command const account = first; - const consumed = consumeJsonFlag(rest); - jsonOutput = consumed.json; - const command = consumed.args[0]; - const commandArgs = consumed.args.slice(1); + const afterAccount = consumeLeadingFlags(rest, false); + if (afterAccount.help) { + usage(0); + } + const command = afterAccount.rest[0]; + const commandArgs = afterAccount.rest.slice(1); if (!command) { error("Missing command. Use --help for usage."); @@ -219,12 +614,40 @@ async function main() { } async function handleAccounts(args: string[]) { - const action = args[0]; + const leading = consumeLeadingFlags(args, false); + if (leading.help) usage(0); + + const action = leading.rest[0]; + const actionArgs = leading.rest.slice(1); if (!action) error("Missing action: list|add|remove|credentials"); switch (action) { case "list": { + let values: { json?: boolean; help?: boolean }; + try { + ({ values } = parseArgs({ + args: actionArgs, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: false, + })); + } catch (e) { + maybeEnableJsonFromError(actionArgs); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + const accounts = service.listAccounts(); + if (jsonOutput) { + emitJson({ + ok: true, + accounts: accounts.map((a) => ({ email: a.email })), + }); + break; + } if (accounts.length === 0) { console.log("No accounts configured"); } else { @@ -235,31 +658,100 @@ async function handleAccounts(args: string[]) { break; } case "credentials": { - const credFile = args[1]; - if (!credFile) error("Usage: accounts credentials "); + let values: { json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: actionArgs, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(actionArgs); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: accounts credentials "); + const credFile = positionals[0]; const creds = JSON.parse(fs.readFileSync(credFile, "utf8")); const installed = creds.installed || creds.web; if (!installed) error("Invalid credentials file"); service.setCredentials(installed.client_id, installed.client_secret); - console.log("Credentials saved"); + if (jsonOutput) { + emitJson({ ok: true, saved: true }); + } else { + console.log("Credentials saved"); + } break; } case "add": { - const manual = args.includes("--manual"); - const filtered = args.slice(1).filter((a) => a !== "--manual"); - const email = filtered[0]; - if (!email) error("Usage: accounts add [--manual]"); + let values: { manual?: boolean; json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: actionArgs, + options: { + manual: { type: "boolean" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(actionArgs); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: accounts add [--manual]"); + const email = positionals[0]; + const manual = Boolean(values.manual); const creds = service.getCredentials(); if (!creds) error("No credentials configured. Run: gmcli accounts credentials "); await service.addGmailAccount(email, creds.clientId, creds.clientSecret, manual); - console.log(`Account '${email}' added`); + if (jsonOutput) { + emitJson({ ok: true, email, manual }); + } else { + console.log(`Account '${email}' added`); + } break; } case "remove": { - const email = args[1]; - if (!email) error("Usage: accounts remove "); + let values: { json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: actionArgs, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(actionArgs); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: accounts remove "); + const email = positionals[0]; const deleted = service.deleteAccount(email); - console.log(deleted ? `Removed '${email}'` : `Not found: ${email}`); + if (!deleted) { + error(`Account '${email}' not found`); + } + if (jsonOutput) { + emitJson({ ok: true, email, removed: true }); + } else { + console.log(`Removed '${email}'`); + } break; } default: @@ -268,53 +760,64 @@ async function handleAccounts(args: string[]) { } async function handleSearch(account: string, args: string[]) { - const { values, positionals } = parseArgs({ - args, - options: { - max: { type: "string", short: "m" }, - page: { type: "string", short: "p" }, - }, - allowPositionals: true, - }); + let values: { max?: string; page?: string; json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args, + options: { + max: { type: "string", short: "m" }, + page: { type: "string", short: "p" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(args, new Set(["max", "page"]), new Set(["m", "p"])); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + const maxResults = parsePositiveIntOption("max", values.max, 10); const query = positionals.join(" "); if (!query) error("Usage: search "); - const results = await service.searchThreads(account, query, Number(values.max) || 10, values.page); + const results = await service.searchThreads(account, query, maxResults, values.page); const { idToName } = await service.getLabelMap(account); + const summaries = results.threads.map((t) => summarizeSearchThread(t, idToName)); if (jsonOutput) { emitJson({ ok: true, query, - threads: results.threads.map((t) => { - const msg = t.messages[0]; - return { - id: t.id, - date: msg?.date || msg?.internalDate || null, - from: parseMailbox(msg?.from), - subject: msg?.subject || null, - labels: msg?.labelIds?.map((id) => idToName.get(id) || id) || [], - snippet: msg?.snippet || null, - message_ids: t.messages.map((m) => m.id).filter(Boolean), - }; - }), + threads: summaries.map((s) => ({ + id: s.id, + date: s.date, + from: s.from, + subject: s.subject, + labels: s.labels, + snippet: s.snippet, + message_ids: s.messageIds, + })), next_page_token: results.nextPageToken || null, }); return; } - if (results.threads.length === 0) { + if (summaries.length === 0) { console.log("No results"); } else { console.log("ID\tDATE\tFROM\tSUBJECT\tLABELS"); - for (const t of results.threads) { - const msg = t.messages[0]; - const date = msg?.date ? new Date(msg.date).toISOString().slice(0, 16).replace("T", " ") : ""; - const from = msg?.from?.replace(/\t/g, " ") || ""; - const subject = msg?.subject?.replace(/\t/g, " ") || "(no subject)"; - const labels = msg?.labelIds?.map((id) => idToName.get(id) || id).join(",") || ""; - console.log(`${t.id}\t${date}\t${from}\t${subject}\t${labels}`); + for (const s of summaries) { + const id = sanitizeTsvField(s.id); + const date = sanitizeTsvField(s.dateFormatted); + const from = sanitizeTsvField(s.fromRaw); + const subject = sanitizeTsvField(s.subject) || "(no subject)"; + const labels = sanitizeTsvField(s.labels.join(",")); + console.log(`${id}\t${date}\t${from}\t${subject}\t${labels}`); } if (results.nextPageToken) { console.log(`\n# Next page: --page ${results.nextPageToken}`); @@ -323,11 +826,29 @@ async function handleSearch(account: string, args: string[]) { } async function handleThread(account: string, args: string[]) { - const download = args.includes("--download"); - const filtered = args.filter((a) => a !== "--download"); - const threadId = filtered[0]; + let values: { download?: boolean; json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args, + options: { + download: { type: "boolean" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(args); + throw e; + } + + if (values.json) jsonOutput = true; + if (values.help) usage(0); - if (!threadId) error("Usage: thread "); + if (positionals.length !== 1) error("Usage: thread [--download]"); + const threadId = positionals[0]; + const download = Boolean(values.download); const result = await service.getThread(account, threadId, download); @@ -362,16 +883,14 @@ async function handleThread(account: string, args: string[]) { thread_id: thread.id || threadId, messages: (thread.messages || []).map((msg: any) => { const headers = msg.payload?.headers || []; - const getHeader = (name: string) => - headers.find((h: any) => h.name?.toLowerCase() === name.toLowerCase())?.value || ""; return { id: msg.id, - rfc822_message_id: getHeader("message-id") || null, - from: parseMailbox(getHeader("from")), - to: parseMailboxList(getHeader("to")), - cc: parseMailboxList(getHeader("cc")), - date: getHeader("date") || formatInternalDate(msg.internalDate) || null, - subject: getHeader("subject") || null, + rfc822_message_id: getHeader(headers, "message-id") || null, + from: parseMailbox(getHeader(headers, "from")), + to: parseMailboxList(getHeader(headers, "to")), + cc: parseMailboxList(getHeader(headers, "cc")), + date: getHeader(headers, "date") || formatInternalDate(msg.internalDate) || null, + subject: getHeader(headers, "subject") || null, body: decodeBody(msg.payload), is_draft: isDraftMessage(msg), label_ids: msg.labelIds || [], @@ -388,21 +907,27 @@ async function handleThread(account: string, args: string[]) { } for (const msg of thread.messages || []) { const headers = msg.payload?.headers || []; - const getHeader = (name: string) => - headers.find((h: any) => h.name?.toLowerCase() === name.toLowerCase())?.value || ""; const isDraft = isDraftMessage(msg); - console.log(`Message-ID: ${msg.id}`); + console.log(`Gmail-Message-ID: ${msg.id}`); + const rfcMessageId = getHeader(headers, "message-id"); + if (rfcMessageId) { + console.log(`Message-ID: ${rfcMessageId}`); + } if (isDraft) { console.log("Status: DRAFT (not sent)"); } - console.log(`From: ${getHeader("from")}`); - console.log(`To: ${getHeader("to")}`); + console.log(`From: ${getHeader(headers, "from")}`); + console.log(`To: ${getHeader(headers, "to")}`); + const cc = getHeader(headers, "cc"); + if (cc) { + console.log(`Cc: ${cc}`); + } if (isDraft) { - console.log(`Last-saved: ${formatInternalDate(msg.internalDate) || getHeader("date")}`); + console.log(`Last-saved: ${formatInternalDate(msg.internalDate) || getHeader(headers, "date")}`); } else { - console.log(`Date: ${getHeader("date")}`); + console.log(`Date: ${getHeader(headers, "date")}`); } - console.log(`Subject: ${getHeader("subject")}`); + console.log(`Subject: ${getHeader(headers, "subject")}`); console.log(""); console.log(decodeBody(msg.payload)); console.log(""); @@ -419,48 +944,27 @@ async function handleThread(account: string, args: string[]) { } } -function formatInternalDate(internalDate: string | null | undefined): string { - if (!internalDate) return ""; - const timestamp = Number(internalDate); - if (!Number.isFinite(timestamp)) return ""; - return new Date(timestamp).toISOString(); -} - -function formatSize(bytes: number): string { - if (bytes === 0) return "0 B"; - const units = ["B", "KB", "MB", "GB"]; - const i = Math.floor(Math.log(bytes) / Math.log(1024)); - return `${(bytes / 1024 ** i).toFixed(i > 0 ? 1 : 0)} ${units[i]}`; -} - -function decodeBody(payload: any): string { - if (!payload) return ""; - if (payload.body?.data) { - return Buffer.from(payload.body.data, "base64url").toString(); - } - if (payload.parts) { - for (const part of payload.parts) { - if (part.mimeType === "text/plain" && part.body?.data) { - return Buffer.from(part.body.data, "base64url").toString(); - } - } - for (const part of payload.parts) { - const nested = decodeBody(part); - if (nested) return nested; - } +async function handleLabels(account: string, args: string[]) { + let values: { add?: string; remove?: string; json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args, + options: { + add: { type: "string", short: "a" }, + remove: { type: "string", short: "r" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(args, new Set(["add", "remove"]), new Set(["a", "r"])); + throw e; } - return ""; -} -async function handleLabels(account: string, args: string[]) { - const { values, positionals } = parseArgs({ - args, - options: { - add: { type: "string", short: "a" }, - remove: { type: "string", short: "r" }, - }, - allowPositionals: true, - }); + if (values.json) jsonOutput = true; + if (values.help) usage(0); if (positionals.length === 0) { error("Usage: labels list | labels [--add L] [--remove L]"); @@ -468,6 +972,9 @@ async function handleLabels(account: string, args: string[]) { // labels list if (positionals[0] === "list") { + if (positionals.length > 1 || values.add !== undefined || values.remove !== undefined) { + error("Usage: labels list"); + } const labels = await service.listLabels(account); if (jsonOutput) { emitJson({ @@ -485,25 +992,90 @@ async function handleLabels(account: string, args: string[]) { // labels [--add] [--remove] const threadIds = positionals; + const rawAdd = values.add + ? values.add + .split(",") + .map((s) => s.trim()) + .filter(Boolean) + : []; + const rawRemove = values.remove + ? values.remove + .split(",") + .map((s) => s.trim()) + .filter(Boolean) + : []; + + if (rawAdd.length === 0 && rawRemove.length === 0) { + error("At least one of --add or --remove is required."); + } const { nameToId } = await service.getLabelMap(account); - const addLabels = values.add ? service.resolveLabelIds(values.add.split(","), nameToId) : []; - const removeLabels = values.remove ? service.resolveLabelIds(values.remove.split(","), nameToId) : []; + const addLabels = rawAdd.length > 0 ? service.resolveLabelIds(rawAdd, nameToId) : []; + const removeLabels = rawRemove.length > 0 ? service.resolveLabelIds(rawRemove, nameToId) : []; const results = await service.modifyLabels(account, threadIds, addLabels, removeLabels); + const failed = results.filter((r) => !r.success); + + if (jsonOutput) { + emitJson({ + ok: failed.length === 0, + added: addLabels, + removed: removeLabels, + results: results.map((r) => ({ + thread_id: r.threadId, + ok: r.success, + ...(r.error ? { error: r.error } : {}), + })), + errors: failed.map((r) => ({ + thread_id: r.threadId, + error: r.error || "Unknown error", + })), + }); + if (failed.length > 0) { + process.exit(1); + } + return; + } for (const r of results) { - console.log(`${r.threadId}: ${r.success ? "ok" : r.error}`); + if (r.success) { + console.log(`${r.threadId}: ok`); + } else { + console.error(`${r.threadId}: ${r.error || "Unknown error"}`); + } + } + if (failed.length > 0) { + process.exit(1); } } async function handleDrafts(account: string, args: string[]) { - const action = args[0]; - const rest = args.slice(1); + const leading = consumeLeadingFlags(args, false); + if (leading.help) usage(0); + + const action = leading.rest[0]; + const rest = leading.rest.slice(1); if (!action) error("Usage: drafts "); switch (action) { case "list": { + let values: { json?: boolean; help?: boolean }; + try { + ({ values } = parseArgs({ + args: rest, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: false, + })); + } catch (e) { + maybeEnableJsonFromError(rest); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + const drafts = await service.listDrafts(account); if (jsonOutput) { emitJson({ @@ -527,29 +1099,40 @@ async function handleDrafts(account: string, args: string[]) { break; } case "audit": { - const { values } = parseArgs({ - args: rest, - options: { - "older-than": { type: "string" }, - "check-sent": { type: "boolean" }, - max: { type: "string", short: "m" }, - format: { type: "string" }, - }, - }); + let values: { + "older-than"?: string; + "check-sent"?: boolean; + max?: string; + format?: string; + json?: boolean; + help?: boolean; + }; + try { + ({ values } = parseArgs({ + args: rest, + options: { + "older-than": { type: "string" }, + "check-sent": { type: "boolean" }, + max: { type: "string", short: "m" }, + format: { type: "string" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: false, + })); + } catch (e) { + maybeEnableJsonFromError(rest, new Set(["older-than", "max", "format"]), new Set(["m"])); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); const format = (values.format || "markdown").toLowerCase(); if (format !== "markdown" && format !== "table") { error(`Invalid --format '${values.format}'. Expected 'markdown' or 'table'.`); } - let maxResults = 50; - if (values.max !== undefined) { - const parsedMax = Number(values.max); - if (!Number.isInteger(parsedMax) || parsedMax <= 0) { - error(`Invalid --max value '${values.max}'. Expected a positive integer.`); - } - maxResults = parsedMax; - } + const maxResults = parsePositiveIntOption("max", values.max, 50); const result = await service.auditDrafts(account, { olderThan: values["older-than"] ?? "1d", @@ -570,113 +1153,201 @@ async function handleDrafts(account: string, args: string[]) { break; } case "get": { - const download = rest.includes("--download"); - const filtered = rest.filter((a) => a !== "--download"); - const draftId = filtered[0]; - if (!draftId) error("Usage: drafts get [--download]"); + let values: { download?: boolean; json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: rest, + options: { + download: { type: "boolean" }, + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(rest); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: drafts get [--download]"); + const draftId = positionals[0]; + const download = Boolean(values.download); + const draft = await service.getDraft(account, draftId); const msg = draft.message; - if (msg) { - if (download) { - const downloaded = await service.downloadMessageAttachments(account, msg.id!); - if (downloaded.length === 0) { - console.log("No attachments"); - } else { - console.log("FILENAME\tPATH\tSIZE"); - for (const a of downloaded) { - console.log(`${a.filename}\t${a.path}\t${a.size}`); - } - } + if (!msg) { + if (jsonOutput) { + emitJson( + download + ? { ok: true, draft_id: draft.id || draftId, message_id: null, attachments: [] } + : { + ok: true, + draft_id: draft.id || draftId, + message_id: null, + thread_id: null, + to: [], + cc: [], + subject: null, + body: "", + attachments: [], + }, + ); + } + break; + } + + if (download) { + const downloaded = await service.downloadMessageAttachments(account, msg.id!); + if (jsonOutput) { + emitJson({ + ok: true, + draft_id: draft.id || draftId, + message_id: msg.id || null, + attachments: downloaded.map((a) => ({ + filename: a.filename, + path: a.path, + size: a.size, + mime_type: a.mimeType || null, + })), + }); + break; + } + if (downloaded.length === 0) { + console.log("No attachments"); } else { - const headers = msg.payload?.headers || []; - const getHeader = (name: string) => - headers.find((h: any) => h.name?.toLowerCase() === name.toLowerCase())?.value || ""; - if (jsonOutput) { - emitJson({ - ok: true, - draft_id: draft.id, - message_id: msg.id || null, - thread_id: msg.threadId || null, - to: parseMailboxList(getHeader("to")), - cc: parseMailboxList(getHeader("cc")), - subject: getHeader("subject") || null, - body: decodeBody(msg.payload), - attachments: collectAttachmentParts(msg.payload).map((att) => ({ - filename: att.filename, - mime_type: att.mimeType, - size: att.size, - })), - }); - break; + console.log("FILENAME\tPATH\tSIZE"); + for (const a of downloaded) { + console.log(`${a.filename}\t${a.path}\t${a.size}`); } - console.log(`Draft-ID: ${draft.id}`); - console.log(`To: ${getHeader("to")}`); - console.log(`Cc: ${getHeader("cc")}`); - console.log(`Subject: ${getHeader("subject")}`); - console.log(""); - console.log(decodeBody(msg.payload)); - console.log(""); - const attachments = collectAttachmentParts(msg.payload); - if (attachments.length > 0) { - console.log("Attachments:"); - for (const att of attachments) { - console.log(` - ${att.filename} (${formatSize(att.size)}, ${att.mimeType})`); - } + } + } else { + const headers = msg.payload?.headers || []; + if (jsonOutput) { + emitJson({ + ok: true, + draft_id: draft.id, + message_id: msg.id || null, + thread_id: msg.threadId || null, + to: parseMailboxList(getHeader(headers, "to")), + cc: parseMailboxList(getHeader(headers, "cc")), + subject: getHeader(headers, "subject") || null, + body: decodeBody(msg.payload), + attachments: collectAttachmentParts(msg.payload).map((att) => ({ + filename: att.filename, + mime_type: att.mimeType, + size: att.size, + })), + }); + break; + } + console.log(`Draft-ID: ${draft.id}`); + console.log(`To: ${getHeader(headers, "to")}`); + console.log(`Cc: ${getHeader(headers, "cc")}`); + console.log(`Subject: ${getHeader(headers, "subject")}`); + console.log(""); + console.log(decodeBody(msg.payload)); + console.log(""); + const attachments = collectAttachmentParts(msg.payload); + if (attachments.length > 0) { + console.log("Attachments:"); + for (const att of attachments) { + console.log(` - ${att.filename} (${formatSize(att.size)}, ${att.mimeType})`); } } } break; } case "delete": { - const draftId = rest[0]; - if (!draftId) error("Usage: drafts delete "); + let values: { json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: rest, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(rest); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: drafts delete "); + const draftId = positionals[0]; await service.deleteDraft(account, draftId); - console.log("Deleted"); + if (jsonOutput) { + emitJson({ ok: true, draft_id: draftId, deleted: true }); + } else { + console.log("Deleted"); + } break; } case "send": { - const draftId = rest[0]; - if (!draftId) error("Usage: drafts send "); + let values: { json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args: rest, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(rest); + throw e; + } + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length !== 1) error("Usage: drafts send "); + const draftId = positionals[0]; const msg = await service.sendDraft(account, draftId); - console.log(`Sent: ${msg.id}${msg.threadId ? ` thread: ${msg.threadId}` : ""}`); + if (jsonOutput) { + emitJson({ + ok: true, + draft_id: draftId, + message_id: msg.id || null, + thread_id: msg.threadId || null, + }); + } else { + console.log(`Sent: ${msg.id}${msg.threadId ? ` thread: ${msg.threadId}` : ""}`); + } break; } case "create": { - const { values } = parseArgs({ - args: rest, - options: { - to: { type: "string" }, - cc: { type: "string" }, - bcc: { type: "string" }, - subject: { type: "string" }, - body: { type: "string" }, - "body-file": { type: "string" }, - html: { type: "boolean" }, - thread: { type: "string" }, - "reply-to": { type: "string" }, - "in-reply-to": { type: "string" }, - attach: { type: "string", multiple: true }, - }, + const parsed = parseComposeArgs(rest); + if (parsed.help) usage(0); + + const draft = await service.createDraft(account, parsed.to, parsed.subject, parsed.body, { + cc: parsed.cc, + bcc: parsed.bcc, + threadId: parsed.threadId, + replyToMessageId: parsed.replyToMessageId, + attachments: parsed.attachments, + html: parsed.html, }); - const bodyContent = values["body-file"] ? fs.readFileSync(values["body-file"], "utf8") : values.body; - if (!values.to || !values.subject || !bodyContent) { - error( - "Usage: drafts create --to --subject --body [--body-file ] [--html] [--reply-to | --in-reply-to | --thread ]", + const draftMessage = draft.message; + if (jsonOutput) { + emitJson({ + ok: true, + draft_id: draft.id || null, + message_id: draftMessage?.id || null, + thread_id: draftMessage?.threadId || null, + }); + } else { + console.log( + `Draft created: ${draft.id}${draftMessage?.id ? ` message: ${draftMessage.id}` : ""}${draftMessage?.threadId ? ` thread: ${draftMessage.threadId}` : ""}`, ); } - const replyToMessageId = resolveReplyToFlag(values["reply-to"], values["in-reply-to"]); - const draft = await service.createDraft(account, values.to.split(","), values.subject, bodyContent, { - cc: values.cc?.split(","), - bcc: values.bcc?.split(","), - threadId: values.thread, - replyToMessageId, - attachments: values.attach, - html: values.html, - }); - const draftMessage = draft.message; - console.log( - `Draft created: ${draft.id}${draftMessage?.id ? ` message: ${draftMessage.id}` : ""}${draftMessage?.threadId ? ` thread: ${draftMessage.threadId}` : ""}`, - ); break; } default: @@ -685,65 +1356,56 @@ async function handleDrafts(account: string, args: string[]) { } async function handleSend(account: string, args: string[]) { - const { values } = parseArgs({ - args, - options: { - to: { type: "string" }, - cc: { type: "string" }, - bcc: { type: "string" }, - subject: { type: "string" }, - body: { type: "string" }, - "body-file": { type: "string" }, - html: { type: "boolean" }, - "reply-to": { type: "string" }, - "in-reply-to": { type: "string" }, - thread: { type: "string" }, - attach: { type: "string", multiple: true }, - }, + const parsed = parseComposeArgs(args); + if (parsed.help) usage(0); + + const msg = await service.sendMessage(account, parsed.to, parsed.subject, parsed.body, { + cc: parsed.cc, + bcc: parsed.bcc, + threadId: parsed.threadId, + replyToMessageId: parsed.replyToMessageId, + attachments: parsed.attachments, + html: parsed.html, }); - - const bodyContent = values["body-file"] ? fs.readFileSync(values["body-file"], "utf8") : values.body; - if (!values.to || !values.subject || !bodyContent) { - error( - "Usage: send --to --subject --body [--body-file ] [--html] [--reply-to | --in-reply-to | --thread ]", - ); + if (jsonOutput) { + emitJson({ + ok: true, + message_id: msg.id || null, + thread_id: msg.threadId || null, + }); + return; } - - const replyToMessageId = resolveReplyToFlag(values["reply-to"], values["in-reply-to"]); - const msg = await service.sendMessage(account, values.to.split(","), values.subject, bodyContent, { - cc: values.cc?.split(","), - bcc: values.bcc?.split(","), - threadId: values.thread, - replyToMessageId, - attachments: values.attach, - html: values.html, - }); console.log(`Sent: ${msg.id}${msg.threadId ? ` thread: ${msg.threadId}` : ""}`); } -// Accept both --reply-to and its --in-reply-to alias. If the caller supplies both -// with conflicting values, fail loudly rather than silently picking one. -function resolveReplyToFlag(replyTo: string | undefined, inReplyTo: string | undefined): string | undefined { - if (replyTo && inReplyTo && replyTo !== inReplyTo) { - error( - `--reply-to (${replyTo}) and --in-reply-to (${inReplyTo}) were both supplied with different values. ` + - "Pass only one (they are aliases for the same option).", - ); +function handleUrl(account: string, args: string[]) { + let values: { json?: boolean; help?: boolean }; + let positionals: string[]; + try { + ({ values, positionals } = parseArgs({ + args, + options: { + json: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: true, + })); + } catch (e) { + maybeEnableJsonFromError(args); + throw e; } - return replyTo ?? inReplyTo; -} -function handleUrl(account: string, args: string[]) { - if (args.length === 0) { + if (values.json) jsonOutput = true; + if (values.help) usage(0); + + if (positionals.length === 0) { error("Usage: url "); } - const urls = args - .filter((id) => id !== "--json") - .map((id) => ({ - thread_id: id, - url: `https://mail.google.com/mail/?authuser=${encodeURIComponent(account)}#all/${id}`, - })); + const urls = positionals.map((id) => ({ + thread_id: id, + url: `https://mail.google.com/mail/?authuser=${encodeURIComponent(account)}#all/${id}`, + })); if (jsonOutput) { emitJson({ ok: true, urls }); return; @@ -753,4 +1415,15 @@ function handleUrl(account: string, args: string[]) { } } -main(); +function isMainModule(): boolean { + if (!process.argv[1]) return false; + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); + } +} + +if (isMainModule()) { + void main(); +} diff --git a/src/json-format.ts b/src/json-format.ts index 664fd46..9cd1dd2 100644 --- a/src/json-format.ts +++ b/src/json-format.ts @@ -3,12 +3,74 @@ export type Mailbox = { email: string; }; +export function splitMailboxList(raw: string | undefined): string[] { + if (!raw?.trim()) return []; + + const parts: string[] = []; + let current = ""; + let inQuotes = false; + let escaped = false; + let angleDepth = 0; + let parenDepth = 0; + + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + + if (escaped) { + current += ch; + escaped = false; + continue; + } + + if (ch === "\\" && inQuotes) { + current += ch; + escaped = true; + continue; + } + + if (ch === '"') { + inQuotes = !inQuotes; + current += ch; + continue; + } + + if (!inQuotes) { + if (ch === "<") { + angleDepth++; + } else if (ch === ">" && angleDepth > 0) { + angleDepth--; + } else if (ch === "(") { + parenDepth++; + } else if (ch === ")" && parenDepth > 0) { + parenDepth--; + } else if (ch === "," && angleDepth === 0 && parenDepth === 0) { + const trimmed = current.trim(); + if (trimmed) parts.push(trimmed); + current = ""; + continue; + } + } + + current += ch; + } + + const trailing = current.trim(); + if (trailing) parts.push(trailing); + + return parts; +} + export function parseMailbox(raw: string | undefined): Mailbox | null { if (!raw?.trim()) return null; const trimmed = raw.trim(); const angled = trimmed.match(/^(.*)<([^>]+)>\s*$/); if (angled) { - const name = angled[1].trim().replace(/^"|"$/g, "") || null; + const rawName = angled[1].trim(); + const unquoted = + rawName.startsWith('"') && rawName.endsWith('"') && rawName.length >= 2 + ? rawName.slice(1, -1).replace(/\\(.)/g, "$1") + : rawName; + const name = unquoted.trim() || null; return { name, email: angled[2].trim() }; } if (trimmed.includes("@")) return { name: null, email: trimmed }; @@ -16,9 +78,7 @@ export function parseMailbox(raw: string | undefined): Mailbox | null { } export function parseMailboxList(raw: string | undefined): Mailbox[] { - if (!raw?.trim()) return []; - return raw - .split(",") + return splitMailboxList(raw) .map((part) => parseMailbox(part)) .filter((box): box is Mailbox => box !== null); } @@ -26,9 +86,19 @@ export function parseMailboxList(raw: string | undefined): Mailbox[] { export function consumeJsonFlag(args: string[]): { json: boolean; args: string[] } { let json = false; const next: string[] = []; + let endOfOptions = false; + for (const arg of args) { - if (arg === "--json") json = true; - else next.push(arg); + if (!endOfOptions && arg === "--") { + endOfOptions = true; + next.push(arg); + continue; + } + if (!endOfOptions && arg === "--json") { + json = true; + } else { + next.push(arg); + } } return { json, args: next }; } diff --git a/test/cli-ergonomics.test.js b/test/cli-ergonomics.test.js new file mode 100644 index 0000000..7687b64 --- /dev/null +++ b/test/cli-ergonomics.test.js @@ -0,0 +1,420 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + decodeBody, + formatSearchDate, + formatSize, + parseComposeArgs, + parsePositiveIntOption, + sanitizeTsvField, + summarizeSearchThread, +} from "../dist/cli.js"; +import { parseMailboxList } from "../dist/json-format.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(__dirname, ".."); +const cliDistPath = path.join(repoRoot, "dist", "cli.js"); +const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")); + +function runCli(args, envOverrides = {}) { + return spawnSync(process.execPath, [cliDistPath, ...args], { + encoding: "utf8", + env: { ...process.env, ...envOverrides }, + }); +} + +function withFakeHome(fn) { + const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), "gmcli-ergonomics-")); + try { + return fn(fakeHome); + } finally { + fs.rmSync(fakeHome, { recursive: true, force: true }); + } +} + +test("parseMailboxList preserves quoted display-name commas and escaped quotes", () => { + assert.deepEqual(parseMailboxList('"McLemore, Will" , jane@example.com'), [ + { name: "McLemore, Will", email: "will@mclemoreauction.com" }, + { name: null, email: "jane@example.com" }, + ]); + + assert.deepEqual( + parseMailboxList('"Smith, Jr., John" , "Doe, \\"Jane\\"" '), + [ + { name: "Smith, Jr., John", email: "john@example.com" }, + { name: 'Doe, "Jane"', email: "jane@example.com" }, + ], + ); +}); + +test("parseComposeArgs rejects --body + --body-file conflict and names exact missing required options", () => { + withFakeHome((dir) => { + const bodyFile = path.join(dir, "body.txt"); + fs.writeFileSync(bodyFile, "Body from file", "utf8"); + + assert.throws( + () => + parseComposeArgs([ + "--to", + "a@x.com", + "--subject", + "Test", + "--body", + "Inline", + "--body-file", + bodyFile, + ]), + /Cannot specify both --body and --body-file/, + ); + + assert.throws(() => parseComposeArgs(["--subject", "Test", "--body", "Hi"]), /Missing required option: --to/); + assert.throws(() => parseComposeArgs(["--to", "a@x.com", "--body", "Hi"]), /Missing required option: --subject/); + assert.throws( + () => parseComposeArgs(["--to", "a@x.com", "--subject", "Test"]), + /Missing required option: --body or --body-file/, + ); + + const parsed = parseComposeArgs([ + "--to", + '"McLemore, Will" , jane@example.com', + "--subject", + "Hello", + "--body-file", + bodyFile, + ]); + assert.deepEqual(parsed.to, ['"McLemore, Will" ', "jane@example.com"]); + assert.equal(parsed.body, "Body from file"); + }); +}); + +test("CLI rejects --body + --body-file conflict and names exact missing field for both drafts create and send", () => { + withFakeHome((fakeHome) => { + const bodyFile = path.join(fakeHome, "msg.txt"); + fs.writeFileSync(bodyFile, "From file", "utf8"); + const account = "will@example.invalid"; + + for (const cmd of [["drafts", "create"], ["send"]]) { + const conflict = runCli( + [account, ...cmd, "--to", "a@x.com", "--subject", "Hi", "--body", "Inline", "--body-file", bodyFile], + { HOME: fakeHome }, + ); + assert.equal(conflict.status, 1); + assert.match(conflict.stderr, /Cannot specify both --body and --body-file/); + + const missingTo = runCli([account, ...cmd, "--subject", "Hi", "--body", "Hello"], { HOME: fakeHome }); + assert.equal(missingTo.status, 1); + assert.match(missingTo.stderr, /Missing required option: --to/); + assert.doesNotMatch(missingTo.stderr, /DATA STORAGE/); + + const missingSubj = runCli([account, ...cmd, "--to", "a@x.com", "--body", "Hello"], { HOME: fakeHome }); + assert.equal(missingSubj.status, 1); + assert.match(missingSubj.stderr, /Missing required option: --subject/); + + const missingBody = runCli([account, ...cmd, "--to", "a@x.com", "--subject", "Hi"], { HOME: fakeHome }); + assert.equal(missingBody.status, 1); + assert.match(missingBody.stderr, /Missing required option: --body or --body-file/); + } + }); +}); + +test("search validates --max as a positive integer", () => { + assert.equal(parsePositiveIntOption("max", "25", 10), 25); + assert.equal(parsePositiveIntOption("max", undefined, 10), 10); + assert.throws(() => parsePositiveIntOption("max", "bogus", 10), /Invalid --max value 'bogus'/); + assert.throws(() => parsePositiveIntOption("max", "0", 10), /Invalid --max value '0'/); + assert.throws(() => parsePositiveIntOption("max", "-3", 10), /Invalid --max value '-3'/); + assert.throws(() => parsePositiveIntOption("max", "1.5", 10), /Invalid --max value '1\.5'/); + + withFakeHome((fakeHome) => { + for (const args of [ + ["user@example.invalid", "search", "in:inbox", "--max", "bogus"], + ["user@example.invalid", "search", "in:inbox", "--max", "0"], + ["user@example.invalid", "search", "in:inbox", "--max=-5"], + ]) { + const res = runCli(args, { HOME: fakeHome }); + assert.equal(res.status, 1); + assert.match(res.stderr, /Invalid --max value/); + } + }); +}); + +test("strict parseArgs rejects unknown flags on thread, drafts get/delete/send, url, and accounts", () => { + withFakeHome((fakeHome) => { + const account = "user@example.invalid"; + const cases = [ + [account, "thread", "t123", "--bogus"], + [account, "drafts", "get", "d123", "--bogus"], + [account, "drafts", "delete", "d123", "--bogus"], + [account, "drafts", "send", "d123", "--bogus"], + [account, "drafts", "list", "--bogus"], + [account, "url", "t123", "--bogus"], + ["accounts", "list", "--bogus"], + ["accounts", "add", "a@x.com", "--bogus"], + ["accounts", "remove", "a@x.com", "--bogus"], + ["--bogus"], + ]; + + for (const args of cases) { + const res = runCli(args, { HOME: fakeHome }); + assert.equal(res.status, 1, `Expected exit 1 for: ${args.join(" ")}`); + assert.match(res.stderr, /Unknown option '--bogus'/, `Unexpected stderr for ${args.join(" ")}: ${res.stderr}`); + } + + const jsonUnknown = runCli([account, "thread", "t123", "--json", "--bogus"], { HOME: fakeHome }); + assert.equal(jsonUnknown.status, 1); + assert.equal(jsonUnknown.stderr, ""); + const parsedErr = JSON.parse(jsonUnknown.stdout); + assert.equal(parsedErr.ok, false); + assert.match(parsedErr.error, /Unknown option '--bogus'/); + }); +}); + +test("-h and --json inside option values do not hijack help or JSON mode", () => { + withFakeHome((fakeHome) => { + const account = "missing@example.invalid"; + + // Option values containing --json or starting with - via = syntax reach account lookup without triggering help/JSON + const okVal = runCli( + [account, "send", "--to", "a@x.com", "--subject", "foo --json", "--body=-h"], + { HOME: fakeHome }, + ); + assert.equal(okVal.status, 1); + assert.equal(okVal.stdout, ""); + assert.match(okVal.stderr, /Account 'missing@example\.invalid' not found/); + assert.doesNotMatch(okVal.stderr, /gmcli - Gmail CLI/); + + const exactJsonVal = runCli( + [account, "drafts", "create", "--to", "a@x.com", "--subject=--json", "--body=-h"], + { HOME: fakeHome }, + ); + assert.equal(exactJsonVal.status, 1); + assert.equal(exactJsonVal.stdout, ""); + assert.match(exactJsonVal.stderr, /Account 'missing@example\.invalid' not found/); + + // Separate --body "-h" / --subject "--json" fail cleanly in parseArgs without printing help or JSON + const spaceDashHelp = runCli( + [account, "send", "--to", "a@x.com", "--subject", "Test", "--body", "-h"], + { HOME: fakeHome }, + ); + assert.equal(spaceDashHelp.status, 1); + assert.equal(spaceDashHelp.stdout, ""); + assert.doesNotMatch(spaceDashHelp.stderr, /gmcli - Gmail CLI/); + assert.match(spaceDashHelp.stderr, /Option '--body' argument is ambiguous/); + + const spaceDashJson = runCli( + [account, "send", "--to", "a@x.com", "--subject", "--json", "--body", "Hello"], + { HOME: fakeHome }, + ); + assert.equal(spaceDashJson.status, 1); + assert.equal(spaceDashJson.stdout, ""); + assert.match(spaceDashJson.stderr, /Option '--subject' argument is ambiguous/); + }); +}); + +test("--version / -v prints package version and error usage writes to stderr while --help writes to stdout", () => { + for (const flag of ["--version", "-v"]) { + const res = runCli([flag]); + assert.equal(res.status, 0); + assert.equal(res.stdout.trim(), pkg.version); + assert.equal(res.stderr, ""); + } + + const versionJson = runCli(["--json", "--version"]); + assert.equal(versionJson.status, 0); + assert.deepEqual(JSON.parse(versionJson.stdout), { ok: true, version: pkg.version }); + + const noArgs = runCli([]); + assert.equal(noArgs.status, 1); + assert.equal(noArgs.stdout, ""); + assert.match(noArgs.stderr, /gmcli - Gmail CLI/); + + const help = runCli(["--help"]); + assert.equal(help.status, 0); + assert.equal(help.stderr, ""); + assert.match(help.stdout, /gmcli - Gmail CLI/); + assert.match(help.stdout, /GMCLI_CLIENT_ID/); + assert.match(help.stdout, /GMCLI_CLIENT_SECRET/); + assert.match(help.stdout, /--version, -v/); +}); + +test("honest exit codes and --json on accounts list/remove, labels validation, and url", () => { + withFakeHome((fakeHome) => { + const listJson = runCli(["accounts", "list", "--json"], { HOME: fakeHome }); + assert.equal(listJson.status, 0); + assert.deepEqual(JSON.parse(listJson.stdout), { ok: true, accounts: [] }); + + const removeMissing = runCli(["accounts", "remove", "nobody@example.com"], { HOME: fakeHome }); + assert.equal(removeMissing.status, 1); + assert.match(removeMissing.stderr, /Account 'nobody@example\.com' not found/); + + const removeMissingJson = runCli(["accounts", "remove", "nobody@example.com", "--json"], { HOME: fakeHome }); + assert.equal(removeMissingJson.status, 1); + assert.deepEqual(JSON.parse(removeMissingJson.stdout), { + ok: false, + error: "Account 'nobody@example.com' not found", + }); + + const labelsNoOps = runCli(["user@example.invalid", "labels", "thread123"], { HOME: fakeHome }); + assert.equal(labelsNoOps.status, 1); + assert.match(labelsNoOps.stderr, /At least one of --add or --remove is required/); + + const labelsNoOpsJson = runCli(["user@example.invalid", "labels", "thread123", "--json"], { HOME: fakeHome }); + assert.equal(labelsNoOpsJson.status, 1); + assert.deepEqual(JSON.parse(labelsNoOpsJson.stdout), { + ok: false, + error: "At least one of --add or --remove is required.", + }); + + const urlJson = runCli(["you@gmail.com", "url", "t1", "t2", "--json"], { HOME: fakeHome }); + assert.equal(urlJson.status, 0); + assert.deepEqual(JSON.parse(urlJson.stdout), { + ok: true, + urls: [ + { thread_id: "t1", url: "https://mail.google.com/mail/?authuser=you%40gmail.com#all/t1" }, + { thread_id: "t2", url: "https://mail.google.com/mail/?authuser=you%40gmail.com#all/t2" }, + ], + }); + }); +}); + +test("decodeBody skips binary and named attachments while extracting nested text bodies", () => { + const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).toString("base64url"); + + // Only a binary inline attachment => must return empty string, not raw PNG bytes + assert.equal( + decodeBody({ + mimeType: "multipart/related", + parts: [ + { + filename: "logo.png", + mimeType: "image/png", + body: { data: pngBytes }, + }, + ], + }), + "", + ); + + // Unnamed non-text binary part => skipped + assert.equal( + decodeBody({ + mimeType: "application/octet-stream", + body: { data: pngBytes }, + }), + "", + ); + + // Named text/plain attachment skipped in favor of actual HTML body + assert.equal( + decodeBody({ + mimeType: "multipart/mixed", + parts: [ + { + filename: "notes.txt", + mimeType: "text/plain", + body: { data: Buffer.from("attachment text").toString("base64url") }, + }, + { + mimeType: "text/html", + body: { data: Buffer.from("

Real body

").toString("base64url") }, + }, + ], + }), + "

Real body

", + ); + + // Prefers nested text/plain over sibling HTML or attachments + assert.equal( + decodeBody({ + mimeType: "multipart/mixed", + parts: [ + { + filename: "logo.png", + mimeType: "image/png", + body: { data: pngBytes }, + }, + { + mimeType: "multipart/alternative", + parts: [ + { + mimeType: "text/plain", + body: { data: Buffer.from("Plain text body").toString("base64url") }, + }, + { + mimeType: "text/html", + body: { data: Buffer.from("

HTML body

").toString("base64url") }, + }, + ], + }, + ], + }), + "Plain text body", + ); +}); + +test("formatSize clamps at largest unit for >= 1 TB", () => { + assert.equal(formatSize(0), "0 B"); + assert.equal(formatSize(512), "512 B"); + assert.equal(formatSize(1024 ** 4), "1.0 TB"); + assert.equal(formatSize(1024 ** 5), "1024.0 TB"); + assert.equal(formatSize(1024 ** 5).includes("undefined"), false); +}); + +test("search summary selects latest message, unions labels, guards malformed dates, and sanitizes TSV", () => { + const idToName = new Map([ + ["INBOX", "INBOX"], + ["Label_1", "Clients"], + ["SENT", "SENT"], + ]); + + const summary = summarizeSearchThread( + { + id: "thread-1", + historyId: "100", + messages: [ + { + id: "m1", + threadId: "thread-1", + labelIds: ["INBOX", "Label_1"], + snippet: "First", + historyId: "99", + internalDate: "1700000000000", + from: "First Sender ", + to: "will@example.com", + subject: "Original\tSubject\nLine2", + date: "Tue, 14 Nov 2023 22:13:20 +0000", + hasAttachments: false, + }, + { + id: "m2", + threadId: "thread-1", + labelIds: ["SENT", "Label_1"], + snippet: "Latest snippet", + historyId: "100", + internalDate: "1700086400000", + from: '"McLemore, Will" ', + to: "first@example.com", + subject: "Re: Original\tSubject\r\nLine2", + date: "not-a-valid-date", + hasAttachments: false, + }, + ], + }, + idToName, + ); + + assert.equal(summary.id, "thread-1"); + assert.deepEqual(summary.from, { name: "McLemore, Will", email: "will@example.com" }); + assert.deepEqual(summary.labels, ["INBOX", "Clients", "SENT"]); + assert.equal(summary.snippet, "Latest snippet"); + assert.deepEqual(summary.messageIds, ["m1", "m2"]); + // Malformed Date header falls back safely to internalDate instead of throwing RangeError + assert.equal(summary.dateFormatted, "2023-11-15 22:13"); + assert.equal(formatSearchDate("totally-invalid-date", undefined), ""); + assert.equal(sanitizeTsvField("Re: Original\tSubject\r\nLine2"), "Re: Original Subject Line2"); +});