@infaris/calendar-cli 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
3
- import { Command, Option } from "commander";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, resolve as resolvePath } from "node:path";
4
+ import { Command, InvalidArgumentError, Option } from "commander";
4
5
  import { beginLogin, completeLogin, login, pendingLoginStatus, readLoginCode, } from "./auth.js";
5
- import { addTaskAttachment, getTaskContext, commentOnTask, linkTaskPullRequest, createEvent, createMailDraft, createTask, deleteEvent, deleteTask, findEvent, getSettings, listCalendars, listEvents, listHours, listTasks, listTeamMembers, resolveTaskId, updateDefaultCalendar, updateEvent, updateTask, PRIORITIES, PRODUCTS, STATUSES, } from "./api.js";
6
+ import { addTaskAttachment, getTaskContext, commentOnTask, linkTaskPullRequest, createEvent, createMailDraft, deleteMailDraft, listMailboxes, listMailDrafts, listMailMessages, mailDraftStatus, readMailMessage, SendOutcomeUnknownError, sendMailDraft, createTask, deleteEvent, deleteTask, findEvent, getSettings, listCalendars, listEvents, listHours, listTasks, listTeamMembers, resolveTaskId, updateDefaultCalendar, updateEvent, updateTask, PRIORITIES, PRODUCTS, STATUSES, } from "./api.js";
6
7
  import { formatDayHeading, formatTime, localDayKey, parseDateInput, resolveRange, startOfDay, endOfDay, } from "./dates.js";
7
8
  import { computeFreeSlots, parseHm } from "./freebusy.js";
8
9
  import { resolveCreateEventTimes } from "./event-input.js";
@@ -10,6 +11,8 @@ import { resolveAttendeeIds, resolveWritableCalendarId } from "./selectors.js";
10
11
  import { crmFetch } from "./crm-api.js";
11
12
  import { downloadTaskAttachments } from "./task-download.js";
12
13
  import { registerHoursCommands } from "./hours-cli.js";
14
+ import { applyReplaceMap, buildDraft, draftSummary, parseReplaceMap, previewPage, replaceKey, } from "./mail-draft.js";
15
+ import { describeSend, MAX_SEND_PER_RUN, parseDelay, parseMax, parseUidList, sendBatch, } from "./mail-send.js";
13
16
  import { DEFAULT_BASE_URL, clearCredentials, credentialsPath, loadCredentials, } from "./config.js";
14
17
  function fail(message) {
15
18
  process.stderr.write(`\x1b[31mError:\x1b[0m ${message}\n`);
@@ -22,7 +25,7 @@ const program = new Command();
22
25
  program
23
26
  .name("infaris-calendar")
24
27
  .description("Calendar CLI: agenda, tasks, mail drafts, and the urenstaat (hours).")
25
- .version("0.9.0");
28
+ .version("0.10.0");
26
29
  const loginCmd = program
27
30
  .command("login")
28
31
  .description("Sign in with Infaris in your browser and store a token")
@@ -848,36 +851,510 @@ attach
848
851
  }
849
852
  });
850
853
  // --- mail ... ---
851
- const mail = program.command("mail").description("Stage mail concepts");
854
+ const mail = program
855
+ .command("mail")
856
+ .description("Mail drafts (concepten), read-only lookups and, only with --yes, sending an existing draft (`mail send`). Run `mail send` only when the user explicitly asked to send.");
857
+ function parseUid(value) {
858
+ const uid = Number(value);
859
+ if (!Number.isInteger(uid) || uid <= 0) {
860
+ throw new InvalidArgumentError("Expected a positive message UID");
861
+ }
862
+ return uid;
863
+ }
864
+ function formatBytes(bytes) {
865
+ return bytes >= 1024 * 1024
866
+ ? `${(bytes / 1024 / 1024).toFixed(1)} MB`
867
+ : `${Math.max(1, Math.round(bytes / 1024))} kB`;
868
+ }
852
869
  mail
853
870
  .command("draft")
854
- .description("Stage a mail concept in your own webmail; never sends it directly. --body is the message above the automatic signature; do not include the signature in the HTML.")
855
- .requiredOption("--to <email>", "Recipient email address")
856
- .option("--subject <text>", "Subject")
871
+ .description([
872
+ "Save a real draft in Concepten of your own mailbox; never sends it (that is `mail send`).",
873
+ "--body/--body-file is the message above your default signature, which is added automatically; do not put a closing or signature in it. HTML by default; Markdown (.md or --format markdown) and plain text work too.",
874
+ "Local images (<img src=\"shot.png\"> or ![](shot.png), relative to --body-file or the cwd) and --image files are embedded inline; --attach adds files as attachments.",
875
+ "--reply/--reply-all/--forward build the draft on an existing message (find its UID with `mail messages`): thread headers, Re:/Fwd: subject and the quoted original are added.",
876
+ ].join(" "))
877
+ .option("--to <emails...>", "Recipients (repeat or comma-separate)")
878
+ .option("--cc <emails...>", "Cc recipients")
879
+ .option("--bcc <emails...>", "Bcc recipients")
880
+ .option("--subject <text>", "Subject (default Re:/Fwd: of the original)")
857
881
  .option("--body <html>", "Body HTML placed above the automatic signature (never include the signature)")
858
- .option("--body-file <path>", "Read the HTML body from a file ('-' for stdin)")
859
- .option("--from <email>", "Preferred sender mailbox address")
860
- .option("--attach <path>", "Path to an image or PDF to attach (max 10 MB)")
861
- .option("--json", "Output the draft id/url as JSON")
882
+ .option("--body-file <path>", "Read the body from a file ('-' for stdin); .md is Markdown, .txt plain text")
883
+ .option("--format <format>", "Body format: html (default), markdown or text")
884
+ .option("--image <paths...>", "Images to show inline below the body, in this order (png, jpg, gif, webp)")
885
+ .option("--attach <paths...>", "Files to attach (PDF, images, docx, ...)")
886
+ .option("--from <email>", "Sender address (mailbox or alias) you have access to")
887
+ .option("--no-signature", "Do not add the default signature")
888
+ .option("--reply <uid>", "Reply to this message", parseUid)
889
+ .option("--reply-all <uid>", "Reply to all on this message", parseUid)
890
+ .option("--forward <uid>", "Forward this message, with its attachments", parseUid)
891
+ .option("--folder <path>", "Folder of the original message", "INBOX")
892
+ .option("--source-mailbox <id>", "Mailbox id or address of the original (default: the draft mailbox)")
893
+ .option("--no-forward-attachments", "Forward without the original attachments")
894
+ .option("--replace <uid>", "Replace this existing draft in Concepten", parseUid)
895
+ .option("--dry-run", "Check recipients, images and attachments without saving")
896
+ .option("--preview <file.html>", "Write the body (images inline) to an HTML file to look at; implies --dry-run")
897
+ .option("--no-inline-remote", "Keep https:// images as links instead of embedding them")
898
+ .option("--no-optimize-images", "Do not shrink large inline images")
899
+ .option("--json", "Output the result as JSON")
862
900
  .action(async (opts) => {
863
901
  try {
864
- const html = resolveDescription({
865
- description: opts.body,
866
- descriptionFile: opts.bodyFile,
867
- });
868
- const { id, url } = await createMailDraft({
902
+ const built = await buildDraft({
869
903
  to: opts.to,
904
+ cc: opts.cc,
905
+ bcc: opts.bcc,
870
906
  subject: opts.subject,
871
- html,
872
- fromAddress: opts.from,
873
- attachmentPath: opts.attach,
907
+ body: opts.body,
908
+ bodyFile: opts.bodyFile,
909
+ format: opts.format,
910
+ images: opts.image,
911
+ attach: opts.attach,
912
+ from: opts.from,
913
+ signature: opts.signature,
914
+ reply: opts.reply,
915
+ replyAll: opts.replyAll,
916
+ forward: opts.forward,
917
+ folder: opts.folder,
918
+ sourceMailbox: opts.sourceMailbox,
919
+ forwardAttachments: opts.forwardAttachments,
920
+ replace: opts.replace,
921
+ inlineRemote: opts.inlineRemote,
922
+ optimizeImages: opts.optimizeImages,
923
+ }, process.cwd());
924
+ for (const message of built.warnings)
925
+ warn(message);
926
+ if (opts.preview) {
927
+ writeFileSync(opts.preview, previewPage(built));
928
+ process.stderr.write(`Preview: ${resolvePath(opts.preview)}\n`);
929
+ }
930
+ if (opts.dryRun || opts.preview) {
931
+ process.stdout.write(`${JSON.stringify(draftSummary(built), null, 2)}\n`);
932
+ return;
933
+ }
934
+ const { baseUrl: _baseUrl, ...draft } = await createMailDraft(built.input);
935
+ if (opts.json) {
936
+ process.stdout.write(`${JSON.stringify(draft, null, 2)}\n`);
937
+ return;
938
+ }
939
+ printDraft(draft);
940
+ }
941
+ catch (err) {
942
+ fail(err instanceof Error ? err.message : String(err));
943
+ }
944
+ });
945
+ function printDraft(draft) {
946
+ ok(`Draft ${draft.replaced ? `replaced (was ${draft.replaced}) ` : ""}saved in ${draft.folder} of ${draft.mailbox} (from ${draft.from})`);
947
+ const lines = [
948
+ `To: ${draft.to.join(", ") || "-"}`,
949
+ draft.cc.length ? `Cc: ${draft.cc.join(", ")}` : "",
950
+ draft.bcc.length ? `Bcc: ${draft.bcc.join(", ")}` : "",
951
+ `Subject: ${draft.subject || "-"}`,
952
+ draft.inlineImages
953
+ ? `Images: ${draft.inlineImages} inline${draft.optimizedImages ? `, ${draft.optimizedImages} shrunk (-${formatBytes(draft.savedBytes ?? 0)})` : ""}`
954
+ : "",
955
+ draft.attachments.length
956
+ ? `Files: ${draft.attachments.map((a) => `${a.filename} (${formatBytes(a.size)})`).join(", ")}`
957
+ : "",
958
+ draft.signature ? "" : "Signature: none",
959
+ draft.url,
960
+ ].filter(Boolean);
961
+ process.stdout.write(lines.map((line) => ` ${line}\n`).join(""));
962
+ }
963
+ mail
964
+ .command("batch <file>")
965
+ .description([
966
+ "Save many drafts from a JSON file: an array of objects with the same fields as `mail draft`",
967
+ "(to, cc, bcc, subject, body or bodyFile, format, images, attach, from, signature, reply, replyAll, forward, folder, replace, ...).",
968
+ "Paths are relative to the JSON file. Every draft is checked first; nothing is saved if one is invalid. Never sends.",
969
+ "To redo a batch after editing, --replace-map replaces the drafts a previous run saved (--write-map) instead of adding copies.",
970
+ ].join(" "))
971
+ .option("--dry-run", "Check every draft without saving")
972
+ .option("--replace-map <file>", "JSON object of first recipient (or subject) to draft UID: each match replaces that draft")
973
+ .option("--write-map <file>", "Write the saved drafts as a replace map (first recipient to UID) for the next run")
974
+ .option("--json", "Output the results as JSON")
975
+ .action(async (file, opts) => {
976
+ try {
977
+ const path = resolvePath(file);
978
+ let specs;
979
+ try {
980
+ specs = JSON.parse(readFileSync(path, "utf8"));
981
+ }
982
+ catch (err) {
983
+ fail(`Cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`);
984
+ }
985
+ if (!Array.isArray(specs) || specs.length === 0) {
986
+ fail(`${path} must contain a non-empty JSON array of drafts`);
987
+ }
988
+ // Eerst alles opbouwen: een fout in concept 7 mag niet pas blijken nadat
989
+ // 1-6 al in Concepten staan.
990
+ const built = [];
991
+ const problems = [];
992
+ for (const [index, spec] of specs.entries()) {
993
+ const label = `#${index + 1}${spec?.subject ? ` (${spec.subject})` : ""}`;
994
+ try {
995
+ const draft = await buildDraft(spec, dirname(path));
996
+ for (const message of draft.warnings)
997
+ warn(`${label}: ${message}`);
998
+ built.push(draft);
999
+ }
1000
+ catch (err) {
1001
+ problems.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
1002
+ }
1003
+ }
1004
+ if (problems.length)
1005
+ fail(`Nothing saved.\n ${problems.join("\n ")}`);
1006
+ let replaceMap = {};
1007
+ if (opts.replaceMap) {
1008
+ try {
1009
+ replaceMap = parseReplaceMap(readFileSync(resolvePath(opts.replaceMap), "utf8"));
1010
+ }
1011
+ catch (err) {
1012
+ fail(`Cannot use ${opts.replaceMap}: ${err instanceof Error ? err.message : String(err)}`);
1013
+ }
1014
+ for (const draft of built)
1015
+ applyReplaceMap(draft.input, replaceMap);
1016
+ const unmatched = Object.keys(replaceMap).filter((key) => !built.some((d) => replaceKey(d.input) === key));
1017
+ if (unmatched.length) {
1018
+ warn(`${unmatched.length} replace-map entr${unmatched.length === 1 ? "y" : "ies"} matched no draft in this file: ${unmatched.join(", ")}`);
1019
+ }
1020
+ }
1021
+ if (opts.dryRun) {
1022
+ process.stdout.write(`${JSON.stringify(built.map(draftSummary), null, 2)}\n`);
1023
+ return;
1024
+ }
1025
+ const results = [];
1026
+ for (const draft of built) {
1027
+ try {
1028
+ const { baseUrl: _baseUrl, ...saved } = await createMailDraft(draft.input);
1029
+ results.push(saved);
1030
+ if (!opts.json)
1031
+ printDraft(saved);
1032
+ }
1033
+ catch (err) {
1034
+ const error = err instanceof Error ? err.message : String(err);
1035
+ results.push({ error, subject: draft.input.subject });
1036
+ if (!opts.json)
1037
+ warn(`${draft.input.subject ?? "draft"}: ${error}`);
1038
+ }
1039
+ }
1040
+ if (opts.writeMap) {
1041
+ const written = { ...replaceMap }; // a failed redo keeps its old UID
1042
+ for (const [index, result] of results.entries()) {
1043
+ const key = replaceKey(built[index].input);
1044
+ if (key && "uid" in result && result.uid)
1045
+ written[key] = result.uid;
1046
+ }
1047
+ writeFileSync(resolvePath(opts.writeMap), `${JSON.stringify(written, null, 2)}\n`);
1048
+ process.stderr.write(`Replace map: ${resolvePath(opts.writeMap)}\n`);
1049
+ }
1050
+ if (opts.json)
1051
+ process.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
1052
+ const failed = results.filter((r) => "error" in r).length;
1053
+ if (failed)
1054
+ fail(`${failed} of ${results.length} drafts failed; the rest are saved`);
1055
+ if (!opts.json)
1056
+ ok(`${results.length} drafts saved in Concepten`);
1057
+ }
1058
+ catch (err) {
1059
+ fail(err instanceof Error ? err.message : String(err));
1060
+ }
1061
+ });
1062
+ mail
1063
+ .command("mailboxes")
1064
+ .description("Your mailboxes, the addresses you can use with --from, and the default signature that `mail draft` adds")
1065
+ .option("--json", "Output as JSON")
1066
+ .action(async (opts) => {
1067
+ try {
1068
+ const info = await listMailboxes();
1069
+ if (opts.json) {
1070
+ process.stdout.write(`${JSON.stringify(info, null, 2)}\n`);
1071
+ return;
1072
+ }
1073
+ for (const m of info.mailboxes) {
1074
+ process.stdout.write(`${m.address}${m.default ? " (default)" : ""} id ${m.id}\n from: ${m.sendAs.join(", ")}\n`);
1075
+ }
1076
+ process.stdout.write(info.signature
1077
+ ? `\nSignature "${info.signature.name}" (added below every draft):\n${info.signature.text.replace(/^/gm, " ")}\n`
1078
+ : "\nNo default signature: end the body with your own closing.\n");
1079
+ }
1080
+ catch (err) {
1081
+ fail(err instanceof Error ? err.message : String(err));
1082
+ }
1083
+ });
1084
+ mail
1085
+ .command("drafts")
1086
+ .description("List the newest drafts in Concepten, with their UID and link")
1087
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1088
+ .option("--search <query>", "Only drafts matching this Mail search")
1089
+ .option("--limit <n>", "How many (max 100)", "20")
1090
+ .option("--json", "Output as JSON")
1091
+ .action(async (opts) => {
1092
+ try {
1093
+ const list = await listMailDrafts({
1094
+ mailbox: opts.mailbox,
1095
+ limit: Number(opts.limit) || 20,
1096
+ search: opts.search,
1097
+ });
1098
+ if (opts.json) {
1099
+ process.stdout.write(`${JSON.stringify(list, null, 2)}\n`);
1100
+ return;
1101
+ }
1102
+ process.stdout.write(`${list.folder} of ${list.mailbox}: ${list.total} draft(s)\n`);
1103
+ for (const d of list.drafts) {
1104
+ process.stdout.write(` ${String(d.uid).padStart(6)} ${d.date?.slice(0, 16).replace("T", " ") ?? ""} ${d.to || "-"} ${d.subject}${d.hasAttachments ? " [bijlage]" : ""}\n`);
1105
+ }
1106
+ }
1107
+ catch (err) {
1108
+ fail(err instanceof Error ? err.message : String(err));
1109
+ }
1110
+ });
1111
+ mail
1112
+ .command("delete-draft <uid>")
1113
+ .alias("draft-delete")
1114
+ .description("Delete one draft from Concepten (never from another folder)")
1115
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1116
+ .action(async (uid, opts) => {
1117
+ try {
1118
+ const result = await deleteMailDraft(parseUid(uid), opts.mailbox);
1119
+ ok(`Draft ${result.uid} deleted from ${result.folder} of ${result.mailbox}`);
1120
+ }
1121
+ catch (err) {
1122
+ fail(err instanceof Error ? err.message : String(err));
1123
+ }
1124
+ });
1125
+ mail
1126
+ .command("sent")
1127
+ .description("List the newest messages in Verzonden (to check that a mail really went out)")
1128
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1129
+ .option("--search <query>", "Search with the same syntax as Mail")
1130
+ .option("--limit <n>", "How many (max 50)", "20")
1131
+ .option("--json", "Output as JSON")
1132
+ .action(async (opts) => {
1133
+ try {
1134
+ const page = await listMailMessages({
1135
+ mailbox: opts.mailbox,
1136
+ kind: "sent",
1137
+ search: opts.search,
1138
+ limit: Number(opts.limit) || 20,
1139
+ });
1140
+ if (opts.json) {
1141
+ process.stdout.write(`${JSON.stringify(page, null, 2)}\n`);
1142
+ return;
1143
+ }
1144
+ process.stdout.write(`${page.folder} of ${page.mailbox}\n`);
1145
+ for (const m of page.messages) {
1146
+ process.stdout.write(` ${String(m.uid).padStart(6)} ${m.date?.slice(0, 16).replace("T", " ") ?? ""} ${m.to || "-"} ${m.subject}${m.hasAttachments ? " [bijlage]" : ""}\n`);
1147
+ }
1148
+ }
1149
+ catch (err) {
1150
+ fail(err instanceof Error ? err.message : String(err));
1151
+ }
1152
+ });
1153
+ mail
1154
+ .command("status <ref>")
1155
+ .description("Is this mail really in Verzonden? <ref> is a draft UID (also a Verzonden UID) or a Message-ID. Use it after a timeout or error, before sending again")
1156
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1157
+ .option("--json", "Output as JSON")
1158
+ .action(async (ref, opts) => {
1159
+ try {
1160
+ const messageId = ref.includes("@") ? ref : undefined;
1161
+ const status = await mailDraftStatus({ uid: messageId ? undefined : parseUid(ref), messageId }, opts.mailbox);
1162
+ if (opts.json) {
1163
+ process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
1164
+ return;
1165
+ }
1166
+ const where = status.state === "sent"
1167
+ ? `SENT: in ${status.sentFolder} of ${status.mailbox} as UID ${status.sent?.uid}${status.draft ? `, but draft ${status.draft.uid} is still in Concepten` : ""}`
1168
+ : status.state === "draft"
1169
+ ? `NOT SENT: still a draft (UID ${status.draft?.uid}) in Concepten of ${status.mailbox}`
1170
+ : `NOT FOUND: in neither Concepten nor ${status.sentFolder} of ${status.mailbox}`;
1171
+ const message = status.sent ?? status.draft;
1172
+ process.stdout.write(`${where}\n${message ? ` To: ${message.to || "-"}\n Subject: ${message.subject}\n Date: ${message.date ?? "-"}\n` : ""}${status.messageId ? ` Message-ID: ${status.messageId}\n` : ""}`);
1173
+ if (status.state === "missing")
1174
+ process.exitCode = 1;
1175
+ }
1176
+ catch (err) {
1177
+ fail(err instanceof Error ? err.message : String(err));
1178
+ }
1179
+ });
1180
+ mail
1181
+ .command("send [uids...]")
1182
+ .description([
1183
+ "SENDS existing drafts from Concepten, exactly as the Verzenden button does (SMTP, copy in Verzonden, draft removed). Run this only when the user explicitly asked to send.",
1184
+ "Nothing is sent without --yes; without it you get the dry-run overview and an error. Pass UIDs (from `mail drafts`) or --all-drafts [--filter query].",
1185
+ `Batches wait --delay seconds between mails (default 10), send at most ${MAX_SEND_PER_RUN} per run and stop at the first failure, listing what already went out. A draft that was already sent is skipped, never sent twice.`,
1186
+ ].join(" "))
1187
+ .option("--mailbox <id-or-address>", "Mailbox with the drafts (default: your first)")
1188
+ .option("--all-drafts", "Send every draft in Concepten (narrow with --filter)")
1189
+ .option("--filter <query>", "With --all-drafts: only drafts matching this Mail search")
1190
+ .option("--delay <seconds>", "Wait between mails of a batch (default 10, 0 for none)")
1191
+ .option("--max <n>", `Refuse to send more than n drafts (max ${MAX_SEND_PER_RUN})`)
1192
+ .option("--yes", "Really send; required")
1193
+ .option("--dry-run", "Show recipients, subject and attachments; send nothing")
1194
+ .option("--json", "Output the result as JSON")
1195
+ .action(async (uidArgs, opts) => {
1196
+ try {
1197
+ if (opts.filter && !opts.allDrafts)
1198
+ fail("--filter needs --all-drafts");
1199
+ if (opts.allDrafts && uidArgs.length)
1200
+ fail("Give UIDs or --all-drafts, not both");
1201
+ const max = parseMax(opts.max);
1202
+ let uids;
1203
+ if (opts.allDrafts) {
1204
+ const list = await listMailDrafts({
1205
+ mailbox: opts.mailbox,
1206
+ limit: MAX_SEND_PER_RUN,
1207
+ search: opts.filter,
1208
+ });
1209
+ if (list.total > list.drafts.length) {
1210
+ fail(`${list.total} drafts match but at most ${MAX_SEND_PER_RUN} are handled per run: narrow with --filter or pass UIDs`);
1211
+ }
1212
+ // Oudste concept eerst: de volgorde waarin ze zijn klaargezet.
1213
+ uids = list.drafts.map((d) => d.uid).sort((a, b) => a - b);
1214
+ }
1215
+ else {
1216
+ uids = parseUidList(uidArgs);
1217
+ }
1218
+ if (!uids.length)
1219
+ fail("No drafts to send: pass UIDs or --all-drafts");
1220
+ if (uids.length > max) {
1221
+ fail(`${uids.length} drafts is more than --max ${max}; send in smaller runs`);
1222
+ }
1223
+ const delay = parseDelay(opts.delay, uids.length);
1224
+ // Eerst alles controleren: een fout in concept 7 mag niet pas blijken
1225
+ // nadat 1-6 al zijn verstuurd.
1226
+ const overview = [];
1227
+ for (const uid of uids) {
1228
+ overview.push(await sendMailDraft({ uid, mailbox: opts.mailbox, dryRun: true }));
1229
+ }
1230
+ const blocked = overview.filter((r) => r.state === "blocked");
1231
+ const ready = overview.filter((r) => r.state === "ready");
1232
+ // Ook wat al verstuurd is gaat mee: dat verstuurt niets maar ruimt het
1233
+ // achtergebleven concept op.
1234
+ const todo = overview.filter((r) => r.state !== "blocked");
1235
+ if (!opts.json || opts.dryRun || !opts.yes) {
1236
+ for (const result of overview) {
1237
+ (opts.json ? process.stderr : process.stdout).write(`${describeSend(result)}\n`);
1238
+ }
1239
+ }
1240
+ if (opts.dryRun) {
1241
+ if (opts.json)
1242
+ process.stdout.write(`${JSON.stringify(overview, null, 2)}\n`);
1243
+ else
1244
+ process.stdout.write(`Dry run: ${ready.length} would be sent, nothing was.\n`);
1245
+ return;
1246
+ }
1247
+ if (blocked.length) {
1248
+ fail(`Nothing sent: ${blocked.length} draft(s) cannot be sent (see above)`);
1249
+ }
1250
+ if (!opts.yes) {
1251
+ fail(`Not sending ${ready.length} mail(s) without --yes. Only add it when the user explicitly asked you to send these.`);
1252
+ }
1253
+ const outcome = await sendBatch(todo.map((r) => r.uid), {
1254
+ send: (uid) => sendMailDraft({ uid, mailbox: opts.mailbox, confirm: true }),
1255
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
1256
+ isUnknown: (err) => err instanceof SendOutcomeUnknownError,
1257
+ onSent: (r) => {
1258
+ if (!opts.json) {
1259
+ ok(r.state === "sent"
1260
+ ? `Sent draft ${r.uid} to ${r.to.join(", ")}${r.sent?.uid ? ` (Verzonden UID ${r.sent.uid})` : ""}${r.sent?.filed === false ? " (no copy in Verzonden!)" : ""}${r.sent?.rejected.length ? ` (server rejected: ${r.sent.rejected.join(", ")})` : ""}`
1261
+ : `Draft ${r.uid} was already sent, skipped`);
1262
+ }
1263
+ },
1264
+ onWait: (seconds) => {
1265
+ if (!opts.json)
1266
+ process.stderr.write(` waiting ${seconds}s...\n`);
1267
+ },
1268
+ }, delay);
1269
+ const summary = {
1270
+ sent: outcome.sent.map((r) => ({ uid: r.uid, to: r.to, subject: r.subject, messageId: r.sent?.messageId, sentUid: r.sent?.uid })),
1271
+ alreadySent: outcome.alreadySent.map((r) => r.uid),
1272
+ failed: outcome.failed,
1273
+ notAttempted: outcome.notAttempted,
1274
+ };
1275
+ if (opts.json)
1276
+ process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
1277
+ if (outcome.failed) {
1278
+ process.stderr.write(`\nStopped at draft ${outcome.failed.uid}: ${outcome.failed.error}\n` +
1279
+ ` Already sent: ${summary.sent.map((s) => s.uid).join(", ") || "none"}\n` +
1280
+ ` Not attempted: ${outcome.notAttempted.join(", ") || "none"}\n` +
1281
+ (outcome.failed.unknown
1282
+ ? ` Draft ${outcome.failed.uid} may have been sent: run \`mail status ${outcome.failed.uid}\` first.\n`
1283
+ : ` Draft ${outcome.failed.uid} was not sent.\n`));
1284
+ process.exit(1);
1285
+ }
1286
+ if (!opts.json)
1287
+ ok(`${outcome.sent.length} mail(s) sent${summary.alreadySent.length ? `, ${summary.alreadySent.length} already sent` : ""}`);
1288
+ }
1289
+ catch (err) {
1290
+ fail(err instanceof Error ? err.message : String(err));
1291
+ }
1292
+ });
1293
+ mail
1294
+ .command("messages")
1295
+ .description("List or search messages in a folder to find the UID for --reply/--forward; never marks mail read")
1296
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1297
+ .option("--folder <path>", "Folder", "INBOX")
1298
+ .option("--sent", "List Verzonden instead of --folder")
1299
+ .option("--search <query>", "Search with the same syntax as Mail")
1300
+ .option("--limit <n>", "How many (max 50)", "20")
1301
+ .option("--json", "Output as JSON")
1302
+ .action(async (opts) => {
1303
+ try {
1304
+ const page = await listMailMessages({
1305
+ mailbox: opts.mailbox,
1306
+ folder: opts.folder,
1307
+ kind: opts.sent ? "sent" : undefined,
1308
+ search: opts.search,
1309
+ limit: Number(opts.limit) || 20,
1310
+ });
1311
+ if (opts.json) {
1312
+ process.stdout.write(`${JSON.stringify(page, null, 2)}\n`);
1313
+ return;
1314
+ }
1315
+ process.stdout.write(`${page.folder} of ${page.mailbox}\n`);
1316
+ for (const m of page.messages) {
1317
+ process.stdout.write(` ${String(m.uid).padStart(6)} ${m.date?.slice(0, 16).replace("T", " ") ?? ""} ${m.seen ? " " : "*"} ${m.from} ${m.subject}\n`);
1318
+ }
1319
+ }
1320
+ catch (err) {
1321
+ fail(err instanceof Error ? err.message : String(err));
1322
+ }
1323
+ });
1324
+ mail
1325
+ .command("read <uid>")
1326
+ .description("Show one message as text (headers, body, attachment names); never marks it read. Use --drafts to check a saved draft (with --json: recipients incl. Bcc, subject, body and how often the signature is in it)")
1327
+ .option("--mailbox <id-or-address>", "Mailbox (default: your first)")
1328
+ .option("--folder <path>", "Folder", "INBOX")
1329
+ .option("--drafts", "Read from Concepten (e.g. the uid `mail draft` returned)")
1330
+ .option("--sent", "Read from Verzonden")
1331
+ .option("--json", "Output as JSON")
1332
+ .action(async (uid, opts) => {
1333
+ try {
1334
+ const { message, ...where } = await readMailMessage(parseUid(uid), {
1335
+ mailbox: opts.mailbox,
1336
+ folder: opts.folder,
1337
+ kind: opts.drafts ? "drafts" : opts.sent ? "sent" : undefined,
874
1338
  });
875
1339
  if (opts.json) {
876
- process.stdout.write(`${JSON.stringify({ id, url }, null, 2)}\n`);
1340
+ process.stdout.write(`${JSON.stringify({ ...where, message }, null, 2)}\n`);
877
1341
  return;
878
1342
  }
879
- ok("Draft staged");
880
- process.stdout.write(` ${url}\n`);
1343
+ const head = [
1344
+ `From: ${message.from}`,
1345
+ `To: ${message.to}`,
1346
+ message.cc ? `Cc: ${message.cc}` : "",
1347
+ message.bcc ? `Bcc: ${message.bcc}` : "",
1348
+ `Date: ${message.date ?? "-"}`,
1349
+ `Subject: ${message.subject}`,
1350
+ message.signatureCount !== undefined
1351
+ ? `Signatures: ${message.signatureCount}`
1352
+ : "",
1353
+ message.attachments.length
1354
+ ? `Files: ${message.attachments.join(", ")}`
1355
+ : "",
1356
+ ].filter(Boolean);
1357
+ process.stdout.write(`${head.join("\n")}\n\n${message.body}\n`);
881
1358
  }
882
1359
  catch (err) {
883
1360
  fail(err instanceof Error ? err.message : String(err));