@wirecat/mail-cli 0.40.0 → 0.42.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.
@@ -6,7 +6,7 @@ import {
6
6
  PACKAGE,
7
7
  SKILL,
8
8
  __name
9
- } from "./chunk-VI5G3S4Y.js";
9
+ } from "./chunk-XHLSJ7JE.js";
10
10
 
11
11
  // dist/program.js
12
12
  import { join as join8 } from "node:path";
@@ -14,12 +14,12 @@ import { resolvePaths as resolvePaths9 } from "@wirecat/cli-base";
14
14
  import { appDoctorCommand, appMcpCommand, appUpdate, baseContext as baseContext14, commandsCommand, configCommand, createProgram as createSharedProgram, environmentOf as environmentOf9, notLocalPaths as notLocalPaths4, outputFor as outputFor18, run as runShared, runsCommand, scheduleCommandFor, skillCommand, upgradeCommand } from "@wirecat/cli-core";
15
15
 
16
16
  // dist/commands/account.js
17
- import { CliError as CliError14 } from "@wirecat/cli-base";
18
- import { annotate as annotate2 } from "@wirecat/cli-base/commands";
17
+ import { CliError as CliError16 } from "@wirecat/cli-base";
18
+ import { annotate as annotate3 } from "@wirecat/cli-base/commands";
19
19
  import { timezoneOf as timezoneOf2 } from "@wirecat/cli-base/query";
20
- import { answerEntity as answerEntity2, baseContext as baseContext2, itemOf as itemOf2, LOCAL_READ, outputFor as outputFor2, positiveCount as positiveCount2, REMOTE_READ, renderAnswer } from "@wirecat/cli-core";
20
+ import { answerEntity as answerEntity3, baseContext as baseContext3, itemOf as itemOf3, LOCAL_READ as LOCAL_READ2, outputFor as outputFor3, positiveCount as positiveCount2, REMOTE_READ as REMOTE_READ2, renderAnswer as renderAnswer2 } from "@wirecat/cli-core";
21
21
  import { domainsToAge, FREE_MAIL, probeMail, SCORE_RULE, SUGGEST_RULE } from "@wirecat/cli-core/mail";
22
- import { Command as Command2 } from "commander";
22
+ import { Command as Command3 } from "commander";
23
23
 
24
24
  // node_modules/.pnpm/valibot@1.5.0_typescript@7.0.2/node_modules/valibot/dist/index.mjs
25
25
  var store$4;
@@ -6466,186 +6466,606 @@ var removal = {
6466
6466
  };
6467
6467
  var removeCommand = /* @__PURE__ */ __name(() => accountRemoveCommand(IDENTITY, removal, { resolveSettings: configuration.resolveSettings }), "removeCommand");
6468
6468
 
6469
- // dist/commands/sync.js
6469
+ // dist/commands/folders.js
6470
6470
  import { CliError as CliError13 } from "@wirecat/cli-base";
6471
6471
  import { annotate } from "@wirecat/cli-base/commands";
6472
- import { timezoneOf, zonedMoment } from "@wirecat/cli-base/query";
6473
- import { answerEntity, answerLocally, baseContext, environmentOf as environmentOf2, FETCH, itemOf, outputFor, positiveCount, runBudgetOf } from "@wirecat/cli-core";
6474
- import { mailAccountKey, SEARCH_REFUSED as SEARCH_REFUSED2, scoreSenders, storedMailRuleSet, syncMail } from "@wirecat/cli-core/mail";
6472
+ import { answerEntity, baseContext, guardedWrite as guardedWrite2, guardFor, itemOf, LOCAL_READ, listOf, newOperationId as newOperationId2, outputFor, ownerOnlyOption, REMOTE_READ, REMOTE_WRITE, renderAnswer, terminalAsker } from "@wirecat/cli-core";
6475
6473
  import { Command } from "commander";
6476
6474
 
6477
- // dist/mail/rethread.js
6475
+ // dist/mail/organise.js
6478
6476
  import { CliError as CliError12 } from "@wirecat/cli-base";
6479
- var rethreadStored = /* @__PURE__ */ __name(async (backend, store, key, folders, since, mayGoOn) => {
6480
- const account = await store.accounts.storedAccount(key).catch((error2) => {
6481
- if (error2 instanceof CliError12 && error2.code === "not_found")
6482
- return null;
6483
- throw error2;
6484
- });
6485
- if (account === null || backend.search === void 0)
6486
- return { moved: 0, complete: true };
6487
- let moved = 0;
6488
- for (const folder of folders) {
6489
- const searched = await backend.search(since, folder);
6490
- if (!searched.quick)
6491
- continue;
6492
- const slice = backend.listBatch ?? 200;
6493
- for (let start = 0; start < searched.uids.length; start += slice) {
6494
- if (!mayGoOn())
6495
- return { moved, complete: false };
6496
- const listed2 = await backend.list(since, folder, {
6497
- searched: { ...searched, uids: searched.uids.slice(start, start + slice) }
6477
+ import { guardedWrite, newOperationId } from "@wirecat/cli-core";
6478
+ import { decodedLabelName as decodedLabelName2 } from "@wirecat/cli-core/mail";
6479
+ var FILTER_LIMIT = 500;
6480
+ var MAX_LIMIT = 5e3;
6481
+ var BULK = 20;
6482
+ var SYSTEM_FLAGS = {
6483
+ read: "\\Seen",
6484
+ seen: "\\Seen",
6485
+ flagged: "\\Flagged",
6486
+ starred: "\\Flagged",
6487
+ answered: "\\Answered",
6488
+ draft: "\\Draft"
6489
+ };
6490
+ var KEYWORD = /^\$?[A-Za-z0-9_.-]+$/;
6491
+ var flagOf = /* @__PURE__ */ __name((given) => {
6492
+ const word = given.trim();
6493
+ const system = SYSTEM_FLAGS[word.toLowerCase().replace(/^\\/, "")];
6494
+ if (system)
6495
+ return system;
6496
+ if (/^\\deleted$/i.test(word) || word.toLowerCase() === "deleted")
6497
+ throw new CliError12("validation_error", "\\Deleted is how a server expunges mail", {
6498
+ param: "flag",
6499
+ reason: "mail.flag-deleted"
6500
+ });
6501
+ if (!KEYWORD.test(word))
6502
+ throw new CliError12("validation_error", `"${given}" is no flag: give read, flagged, answered, draft, or a keyword of letters, digits and $._-`, { param: "flag" });
6503
+ return word;
6504
+ }, "flagOf");
6505
+ var folderNamed = /* @__PURE__ */ __name((folders, given) => {
6506
+ const word = given.trim();
6507
+ return folders.find(({ path: path2 }) => path2 === word) ?? folders.find(({ role }) => role === word.toLowerCase()) ?? folders.find(({ path: path2, name }) => path2.toLowerCase() === word.toLowerCase() || name.toLowerCase() === word.toLowerCase());
6508
+ }, "folderNamed");
6509
+ var trashOf = /* @__PURE__ */ __name(async (mailbox) => {
6510
+ const folders = await mailbox.folders();
6511
+ const found2 = folders.find(({ role }) => role === "trash") ?? folders.find(({ path: path2 }) => mailbox.organise.trash.includes(path2));
6512
+ if (!found2)
6513
+ throw new CliError12("provider_unavailable", "the mailbox has no Trash folder this tool can find, so nothing is deleted; folders list shows the folders", { reason: "mail.no-trash" });
6514
+ return found2.path;
6515
+ }, "trashOf");
6516
+ var allMailOf = /* @__PURE__ */ __name(async (mailbox) => {
6517
+ const found2 = (await mailbox.folders()).find(({ role }) => role === "all");
6518
+ if (!found2)
6519
+ throw new CliError12("provider_unavailable", "Gmail's All Mail folder is not listed", { reason: "mail.no-all-mail" });
6520
+ return found2.path;
6521
+ }, "allMailOf");
6522
+ var targetOf = /* @__PURE__ */ __name(async (mailbox, given, copy) => {
6523
+ const folders = await mailbox.folders();
6524
+ const found2 = folderNamed(folders, given);
6525
+ if (found2?.role === "trash")
6526
+ throw new CliError12("validation_error", "moving to Trash is a deletion", {
6527
+ param: "folder",
6528
+ reason: "mail.move-to-trash"
6529
+ });
6530
+ if (!mailbox.organise.labels) {
6531
+ if (!found2)
6532
+ throw new CliError12("not_found", `no folder "${given}"; folders list shows them, folders create makes one`, {
6533
+ param: "folder"
6498
6534
  });
6499
- const wanted = new Map(listed2.map(({ messageId, threadId }) => [messageId, threadId]));
6500
- const placed = await store.mail.inThreads(account.id, [...wanted.keys()]);
6501
- const astray = placed.filter(({ externalId, threadExternalId }) => wanted.get(externalId) !== threadExternalId);
6502
- const now = Date.now();
6503
- for (const { externalId } of astray) {
6504
- const email2 = await store.mail.email(account.id, externalId);
6505
- const threadId = wanted.get(externalId);
6506
- if (email2 === null || threadId === void 0)
6507
- continue;
6508
- await store.mail.saveThread({
6509
- accountId: account.id,
6510
- externalId: threadId,
6511
- now,
6512
- emails: [
6513
- {
6514
- externalId,
6515
- subject: email2.subject,
6516
- from: email2.fromAddress === null ? null : { address: email2.fromAddress, name: email2.fromName },
6517
- sentAt: email2.sentAt,
6518
- bodyText: email2.bodyText
6519
- }
6520
- ]
6521
- });
6522
- moved++;
6523
- }
6524
- }
6535
+ return { kind: "folder", path: found2.path };
6525
6536
  }
6526
- return { moved, complete: true };
6527
- }, "rethreadStored");
6528
-
6529
- // dist/mail/send-as.js
6530
- var SEND_AS_KEY = "mail_send_as";
6531
- var SEND_AS_URL = "https://gmail.googleapis.com/gmail/v1/users/me/settings/sendAs";
6532
- var SendAsList = object({
6533
- sendAs: optional(array(object({
6534
- sendAsEmail: string(),
6535
- isPrimary: optional(boolean()),
6536
- verificationStatus: optional(string())
6537
- })))
6538
- });
6539
- var readSendAs = /* @__PURE__ */ __name(async (accessToken, fetcher, signal) => {
6540
- const response = await signInFetch(fetcher)(SEND_AS_URL, {
6541
- headers: { authorization: `Bearer ${accessToken}`, accept: "application/json" },
6542
- ...signal ? { signal } : {},
6543
- redirect: "error"
6544
- });
6545
- if (!response.ok)
6546
- throw new Error(`Gmail answered HTTP ${response.status}`);
6547
- const list2 = safeParse(SendAsList, await response.json().catch(() => void 0));
6548
- if (!list2.success)
6549
- throw new Error("Gmail's answer is not a sendAs list");
6550
- return [
6551
- ...new Set((list2.output.sendAs ?? []).filter(({ isPrimary, verificationStatus }) => !isPrimary && verificationStatus === "accepted").map(({ sendAsEmail }) => sendAsEmail.trim().toLowerCase()))
6552
- ].sort();
6553
- }, "readSendAs");
6554
- var savedOf = /* @__PURE__ */ __name((value) => {
6555
- if (value === void 0)
6556
- return [];
6557
- try {
6558
- const parsed2 = JSON.parse(value);
6559
- return Array.isArray(parsed2) ? parsed2.filter((item) => typeof item === "string") : [];
6560
- } catch {
6561
- return [];
6537
+ if (found2?.role === "junk")
6538
+ return { kind: "folder", path: found2.path };
6539
+ if (found2?.role === "inbox")
6540
+ return { kind: "labels", add: ["\\Inbox"], remove: [], name: "INBOX" };
6541
+ if (found2?.role === "all" || given.trim().toLowerCase() === "archive") {
6542
+ if (copy)
6543
+ throw new CliError12("validation_error", "on Gmail, all mail is in All Mail already", { param: "folder" });
6544
+ return { kind: "labels", add: [], remove: ["\\Inbox"], name: found2?.path ?? "All Mail" };
6562
6545
  }
6563
- }, "savedOf");
6564
- var savedSendAs = /* @__PURE__ */ __name(async (store, key) => savedOf((await store.sync.syncState(key, SEND_AS_KEY))?.value), "savedSendAs");
6565
- var gmailAliases = /* @__PURE__ */ __name(async (store, key, read) => {
6566
- const saved2 = await savedSendAs(store, key);
6567
- let aliases;
6568
- try {
6569
- aliases = await read();
6570
- } catch (error2) {
6571
- return { aliases: saved2, unread: error2 instanceof Error ? error2.message : String(error2) };
6546
+ if (found2?.role)
6547
+ throw new CliError12("validation_error", `on Gmail, ${found2.path} is not a label to move mail to`);
6548
+ const name = found2?.path ?? given.trim();
6549
+ return { kind: "labels", add: [name], remove: copy ? [] : ["\\Inbox"], name };
6550
+ }, "targetOf");
6551
+ var storeBox = /* @__PURE__ */ __name((folder) => ({ externalId: folder, name: folder, kind: null }), "storeBox");
6552
+ var labelBox = /* @__PURE__ */ __name((raw) => {
6553
+ const name = decodedLabelName2(raw);
6554
+ return { externalId: `label:${name}`, name, kind: "label" };
6555
+ }, "labelBox");
6556
+ var Changer = class {
6557
+ static {
6558
+ __name(this, "Changer");
6572
6559
  }
6573
- if (JSON.stringify(aliases) !== JSON.stringify(saved2))
6574
- await store.sync.setSyncState(key, SEND_AS_KEY, JSON.stringify(aliases));
6575
- return { aliases };
6576
- }, "gmailAliases");
6577
-
6578
- // dist/store.js
6579
- import { openAppStore } from "@wirecat/cli-core";
6580
- var PROVIDER = { name: "email", kind: "mail", aliases: [], command: IDENTITY.command };
6581
- var openMailStore = /* @__PURE__ */ __name((env, { readOnly = false } = {}) => openAppStore(env, { app: IDENTITY, provider: PROVIDER, readOnly }), "openMailStore");
6582
-
6583
- // dist/commands/sync.js
6584
- var DAY_MS = 864e5;
6585
- var WINDOW_DAYS = { d: 1, w: 7, y: 365 };
6586
- var MB = 1024 * 1024;
6587
- var stoppedText = /* @__PURE__ */ __name((stopped, budget) => (stopped === "requests" || stopped === "deadline") && budget.limit !== null ? `the run stopped at its cap of ${budget.limit} requests (--timeout sets it, --max-pages only lowers it); ` : "", "stoppedText");
6588
- var sinceOf = /* @__PURE__ */ __name((value, zone, now, setting = DEFAULT_SYNC_SINCE) => {
6589
- if (value !== void 0)
6590
- return momentOf(value, zone, now, "--since-time");
6591
- const window = SYNC_WINDOW.exec(setting);
6592
- if (!window)
6593
- return momentOf(setting, zone, now, "sync_since");
6594
- return new Date(now - Number(window[1]) * (WINDOW_DAYS[window[2]] ?? 1) * DAY_MS);
6595
- }, "sinceOf");
6596
- var momentOf = /* @__PURE__ */ __name((value, zone, now, name) => {
6597
- const refuse = /* @__PURE__ */ __name(() => new CliError13("validation_error", `${name} takes an ISO date or timestamp in the past`, {
6598
- param: name === "--since-time" ? "since-time" : "sync_since"
6599
- }), "refuse");
6600
- let since;
6601
- try {
6602
- since = zonedMoment(value, zone, { start: 0, end: value.length });
6603
- } catch (error2) {
6604
- if (error2 instanceof CliError13)
6605
- throw refuse();
6606
- throw error2;
6560
+ mailbox;
6561
+ guard;
6562
+ log;
6563
+ key;
6564
+ action;
6565
+ writes = [];
6566
+ constructor(mailbox, guard, log, key, action) {
6567
+ this.mailbox = mailbox;
6568
+ this.guard = guard;
6569
+ this.log = log;
6570
+ this.key = key;
6571
+ this.action = action;
6607
6572
  }
6608
- if (since > now)
6609
- throw refuse();
6610
- return new Date(since);
6611
- }, "momentOf");
6612
- var BUDGET_CODES = { requests: "rate_limited", deadline: "timeout", cancelled: "cancelled" };
6613
- var issuesOf = /* @__PURE__ */ __name((report) => [
6614
- ...report.unreadable?.length ? [{ code: "invalid_response", reason: "mail.unreadable", source: "sync" }] : [],
6615
- ...report.deletionsSkipped ? [{ code: "outcome_unknown", reason: "mail.deletions-skipped", source: "sync" }] : [],
6616
- ...report.stopped ? [{ code: BUDGET_CODES[report.stopped], reason: `budget.${report.stopped}`, source: "sync" }] : [],
6617
- ...report.refusedFolders?.length ? [{ code: "provider_error", reason: SEARCH_REFUSED2, source: "sync" }] : []
6618
- ], "issuesOf");
6619
- var sendAsOf = /* @__PURE__ */ __name(async (context, store, address) => {
6620
- const { mailbox } = context.settings;
6621
- if (mailbox.auth !== "oauth" || oauthKindOf(mailbox) !== "google")
6622
- return void 0;
6623
- const { credential } = await credentialOf(context);
6624
- return gmailAliases(store, mailAccountKey(address), async () => {
6625
- const login = await credential.login();
6626
- if (!("accessToken" in login))
6627
- return [];
6628
- return readSendAs(login.accessToken, context.environment.fetch, context.environment.signal);
6629
- });
6630
- }, "sendAsOf");
6631
- var foldersFor = /* @__PURE__ */ __name(async (explicit, configured, defaults, list2) => {
6632
- if (explicit?.length)
6633
- return explicit;
6634
- if (configured?.length)
6635
- return configured;
6636
- const found2 = await list2();
6637
- const chosen2 = found2.filter((folder) => folder.role && defaults.roles.includes(folder.role)).map(({ path: path2 }) => path2);
6638
- return chosen2.length ? chosen2 : [defaults.otherwise];
6639
- }, "foldersFor");
6640
- var mailSync = strictObject({
6641
- address: string(),
6642
- since: string(),
6643
- timezone: string(),
6644
- folders: array(string()),
6645
- state: picklist(["partial", "complete"]),
6646
- stopped: optional(picklist(["requests", "deadline", "cancelled", "limit"])),
6647
- requests: number(),
6648
- listed: number(),
6573
+ async step(line, act, moved) {
6574
+ const request = {
6575
+ chatId: null,
6576
+ kind: "account",
6577
+ action: this.action,
6578
+ key: this.key,
6579
+ count: line.items.length,
6580
+ operationId: newOperationId()
6581
+ };
6582
+ const step = this.log.begin({ ...line, operation_id: request.operationId });
6583
+ const done = await guardedWrite(this.guard, request, act);
6584
+ this.log.done(step, line.items.map(({ id }) => id), moved?.(done));
6585
+ this.writes.push({
6586
+ operation_id: request.operationId,
6587
+ op: line.op,
6588
+ folder: line.folder,
6589
+ ...line.to ? { to: line.to } : {},
6590
+ messages: line.items.length,
6591
+ ...line.undoes ? { undoes: line.undoes } : {}
6592
+ });
6593
+ return done;
6594
+ }
6595
+ };
6596
+ var statesOf = /* @__PURE__ */ __name(async (mailbox, { folder, validity, items }) => mailbox.writes.state(folder, validity, items.map(({ uid }) => uid)), "statesOf");
6597
+ var groupBy = /* @__PURE__ */ __name((items, keyOf2) => {
6598
+ const groups = /* @__PURE__ */ new Map();
6599
+ for (const item of items) {
6600
+ const group = groups.get(keyOf2(item));
6601
+ if (group)
6602
+ group.push(item);
6603
+ else
6604
+ groups.set(keyOf2(item), [item]);
6605
+ }
6606
+ return groups;
6607
+ }, "groupBy");
6608
+ var valuesOf = /* @__PURE__ */ __name((map2, keys) => keys.flatMap((key) => {
6609
+ const value = map2.get(key);
6610
+ return value === void 0 ? [] : [value];
6611
+ }), "valuesOf");
6612
+ var byId = /* @__PURE__ */ __name((uids, idOf) => new Map([...uids].flatMap(([uid, value]) => {
6613
+ const id = idOf.get(uid);
6614
+ return id === void 0 ? [] : [[id, value]];
6615
+ })), "byId");
6616
+ var flagChanges = /* @__PURE__ */ __name((change2) => ({
6617
+ ...change2.add.includes("\\Seen") ? { read: true } : change2.remove.includes("\\Seen") ? { read: false } : {},
6618
+ ...change2.add.includes("\\Flagged") ? { flagged: true } : change2.remove.includes("\\Flagged") ? { flagged: false } : {}
6619
+ }), "flagChanges");
6620
+ var SETTABLE = /* @__PURE__ */ __name((flag2) => flag2 !== "\\Recent" && flag2 !== "\\Deleted", "SETTABLE");
6621
+ var changeFlags = /* @__PURE__ */ __name(async (changer, located, change2) => {
6622
+ const { mailbox } = changer;
6623
+ const changed = [];
6624
+ for (const place of located) {
6625
+ const states = await statesOf(mailbox, place);
6626
+ const items = place.items.flatMap((item) => {
6627
+ const state = states.get(item.uid);
6628
+ if (!state)
6629
+ return [];
6630
+ const now = state.flags.filter(SETTABLE);
6631
+ const add = change2.add.filter((flag2) => !now.includes(flag2));
6632
+ const remove = change2.replace ? now.filter((flag2) => !change2.add.includes(flag2)) : change2.remove.filter((flag2) => now.includes(flag2));
6633
+ return add.length || remove.length ? [{ item: { ...item, had: now.filter((f) => remove.includes(f)) }, add, remove }] : [];
6634
+ });
6635
+ for (const group of groupBy(items, ({ add, remove }) => JSON.stringify([add, remove])).values()) {
6636
+ const [{ add, remove }] = group;
6637
+ const line = {
6638
+ op: "flag",
6639
+ folder: place.folder,
6640
+ validity: place.validity,
6641
+ change: { add, remove },
6642
+ items: group.map(({ item }) => item)
6643
+ };
6644
+ await changer.step(line, () => mailbox.writes.flag(place.folder, place.validity, line.items.map(({ uid }) => uid), { add, remove }));
6645
+ const flags = flagChanges({ add, remove });
6646
+ if (Object.keys(flags).length)
6647
+ await mailbox.store.mail.setFlags(mailbox.accountId, new Map(line.items.map(({ id }) => [id, flags])), mailbox.now());
6648
+ for (const { id } of line.items)
6649
+ changed.push(id);
6650
+ }
6651
+ }
6652
+ return changed;
6653
+ }, "changeFlags");
6654
+ var changeLabels = /* @__PURE__ */ __name(async (changer, place, add, remove) => {
6655
+ const { mailbox } = changer;
6656
+ const states = await statesOf(mailbox, place);
6657
+ const items = place.items.flatMap((item) => {
6658
+ const labels = states.get(item.uid)?.labels;
6659
+ if (labels === void 0)
6660
+ return [];
6661
+ const adds = add.filter((label) => !labels.includes(label));
6662
+ const removes = remove.filter((label) => labels.includes(label));
6663
+ return adds.length || removes.length ? [{ ...item, had: labels.filter((label) => removes.includes(label)) }] : [];
6664
+ });
6665
+ if (items.length === 0)
6666
+ return [];
6667
+ const uids = items.map(({ uid }) => uid);
6668
+ await changer.step({ op: "label", folder: place.folder, validity: place.validity, change: { add, remove }, items }, () => mailbox.writes.label(place.folder, place.validity, uids, { add, remove }));
6669
+ await relabel(mailbox, items.map(({ id }) => id), add, remove);
6670
+ return items.map(({ id }) => id);
6671
+ }, "changeLabels");
6672
+ var relabel = /* @__PURE__ */ __name(async (mailbox, ids, add, remove) => {
6673
+ const scanned = [...add, ...remove].map(labelBox);
6674
+ const kept = add.map(labelBox).map(({ externalId }) => externalId);
6675
+ if (scanned.length === 0)
6676
+ return;
6677
+ await mailbox.store.mail.setMailboxes(mailbox.accountId, scanned, new Map(ids.map((id) => [id, kept])), mailbox.now());
6678
+ }, "relabel");
6679
+ var moveFolder = /* @__PURE__ */ __name(async (changer, place, to, op) => {
6680
+ const { mailbox } = changer;
6681
+ const states = await statesOf(mailbox, place);
6682
+ const items = place.items.flatMap((item) => {
6683
+ const state = states.get(item.uid);
6684
+ return state ? [{ ...item, ...state.messageId ? { mid: state.messageId } : {} }] : [];
6685
+ });
6686
+ if (items.length === 0)
6687
+ return [];
6688
+ const uids = items.map(({ uid }) => uid);
6689
+ const idOf = new Map(items.map(({ id, uid }) => [uid, id]));
6690
+ const moved = await changer.step({ op, folder: place.folder, validity: place.validity, to, items }, () => (op === "move" ? mailbox.writes.move : mailbox.writes.copy)(place.folder, place.validity, uids, to), (done) => ({
6691
+ uids: byId(done.uids, idOf),
6692
+ ...done.validity ? { validity: done.validity } : {}
6693
+ }));
6694
+ const ids = items.map(({ id }) => id);
6695
+ const now = mailbox.now();
6696
+ await mailbox.store.mail.setMailboxes(mailbox.accountId, op === "move" ? [storeBox(place.folder), storeBox(to)] : [storeBox(to)], new Map(ids.map((id) => [id, [to]])), now);
6697
+ if (op === "move")
6698
+ await mailbox.store.mail.forgetLocations(mailbox.accountId, place.folder, place.validity, uids);
6699
+ if (moved.validity && moved.uids.size)
6700
+ await mailbox.store.mail.setLocations(mailbox.accountId, to, moved.validity, new Map([...byId(moved.uids, idOf)].map(([id, uid]) => [id, [uid]])));
6701
+ return ids;
6702
+ }, "moveFolder");
6703
+ var moveMessages = /* @__PURE__ */ __name(async (changer, located, target, op) => {
6704
+ const changed = [];
6705
+ for (const place of located) {
6706
+ const ids = target.kind === "labels" ? await changeLabels(changer, place, target.add, target.remove) : await moveFolder(changer, place, target.path, op);
6707
+ for (const id of ids)
6708
+ changed.push(id);
6709
+ }
6710
+ return changed;
6711
+ }, "moveMessages");
6712
+ var trashMessages = /* @__PURE__ */ __name(async (changer, located, trash, keep = () => void 0) => {
6713
+ const { mailbox } = changer;
6714
+ const changed = [];
6715
+ const kept = {};
6716
+ for (const place of located) {
6717
+ const states = await statesOf(mailbox, place);
6718
+ const items = place.items.flatMap((item) => {
6719
+ const state = states.get(item.uid);
6720
+ if (!state)
6721
+ return [];
6722
+ const reason = keep(item.id, state);
6723
+ if (reason !== void 0) {
6724
+ kept[reason] = (kept[reason] ?? 0) + 1;
6725
+ return [];
6726
+ }
6727
+ return [
6728
+ {
6729
+ ...item,
6730
+ ...state.labels ? { labels: state.labels } : {},
6731
+ ...state.messageId ? { mid: state.messageId } : {}
6732
+ }
6733
+ ];
6734
+ });
6735
+ if (items.length === 0)
6736
+ continue;
6737
+ const idOf = new Map(items.map(({ id, uid }) => [uid, id]));
6738
+ await changer.step({ op: "trash", folder: place.folder, validity: place.validity, to: trash, items }, () => mailbox.writes.move(place.folder, place.validity, items.map(({ uid }) => uid), trash), (done) => ({
6739
+ uids: byId(done.uids, idOf),
6740
+ ...done.validity ? { validity: done.validity } : {}
6741
+ }));
6742
+ const ids = items.map(({ id }) => id);
6743
+ await mailbox.store.mail.markDeleted(mailbox.accountId, ids, mailbox.now());
6744
+ for (const id of ids)
6745
+ changed.push(id);
6746
+ }
6747
+ return { changed, kept };
6748
+ }, "trashMessages");
6749
+
6750
+ // dist/commands/folders.js
6751
+ var mailFolder = strictObject({
6752
+ path: string(),
6753
+ name: string(),
6754
+ role: nullable(string()),
6755
+ messages: nullable(number()),
6756
+ unseen: nullable(number())
6757
+ });
6758
+ var listCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command("list"), {
6759
+ effects: REMOTE_READ,
6760
+ examples: [`${IDENTITY.command} personal folders list`, `${IDENTITY.command} personal folders list --json`]
6761
+ }), "mail_folder", mailFolder).summary("the folders with their role and message counts").description("the folders of the mailbox with their role (inbox, sent, trash, ...) and message counts").action(async function() {
6762
+ const context = contextOf(this);
6763
+ refuseOffline(context.flags);
6764
+ const { backend } = await openMail(context);
6765
+ const folders = await closing(backend, () => baseContext(this, configuration.resolveSettings).run(() => backend.folderList()));
6766
+ renderAnswer(this, outputFor(this), listOf("folders list", { items: folders, limit: Math.max(1, folders.length), has_more: false }));
6767
+ }), "listCommand");
6768
+ var folderChange = strictObject({
6769
+ action: picklist(["create", "rename", "delete"]),
6770
+ folder: string(),
6771
+ to: optional(string()),
6772
+ messages: optional(nullable(number())),
6773
+ applied: optional(boolean()),
6774
+ operation_id: optional(string()),
6775
+ hint: optional(string())
6776
+ });
6777
+ var ACTIONS = { create: "folder-create", rename: "folder-update", delete: "folder-delete" };
6778
+ var changeFolder = /* @__PURE__ */ __name(async (command, action, work, preview) => {
6779
+ const context = contextOf(command);
6780
+ refuseOffline(context.flags);
6781
+ const { backend } = await openMail(context);
6782
+ const base2 = baseContext(command, configuration.resolveSettings);
6783
+ const done = await closing(backend, () => base2.run(async () => {
6784
+ const writes = backend.writes;
6785
+ if (!writes)
6786
+ throw new CliError13("provider_unavailable", "this mailbox cannot be changed from here");
6787
+ const guard = guardFor(IDENTITY, { ...base2.settings, permissionDefaults: configuration.permissions?.defaults ?? {} }, (message) => outputFor(command).renderer.warn(message), context.env, terminalAsker(command));
6788
+ const folders = await backend.folderList();
6789
+ const shown4 = preview?.(folders);
6790
+ if (shown4)
6791
+ return { ...shown4, applied: false, hint: "a preview: nothing changed; add --yes to delete it" };
6792
+ const operationId = newOperationId2();
6793
+ const changed = await guardedWrite2(guard, { chatId: null, kind: "account", action: ACTIONS[action], key: `folders.${action}`, operationId }, () => work(writes, folders));
6794
+ return { ...changed, operation_id: operationId };
6795
+ }));
6796
+ renderAnswer(command, outputFor(command), itemOf({ action, ...done }));
6797
+ }, "changeFolder");
6798
+ var existing = /* @__PURE__ */ __name((folders, given) => {
6799
+ const found2 = folderNamed(folders, given);
6800
+ if (!found2)
6801
+ throw new CliError13("not_found", `no folder "${given}"; folders list shows them`, { param: "folder" });
6802
+ return found2;
6803
+ }, "existing");
6804
+ var createCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command("create"), {
6805
+ effects: REMOTE_WRITE,
6806
+ examples: [
6807
+ `${IDENTITY.command} personal folders create Receipts`,
6808
+ `${IDENTITY.command} personal folders create Work/2026`
6809
+ ]
6810
+ }), "mail_folder_change", folderChange).summary("make a folder").description("make a folder on the server; on Gmail it is a label").argument("<folder>", "the folder's path; the server's separator (usually / or .) makes a subfolder").action(async function(folder) {
6811
+ await changeFolder(this, "create", async (writes, folders) => {
6812
+ if (folders.some(({ path: path2 }) => path2 === folder))
6813
+ throw new CliError13("validation_error", `folder "${folder}" already exists`, { param: "folder" });
6814
+ await writes.createFolder(folder);
6815
+ return { folder };
6816
+ });
6817
+ }), "createCommand");
6818
+ var renameCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command("rename"), {
6819
+ effects: REMOTE_WRITE,
6820
+ examples: [`${IDENTITY.command} personal folders rename Receipts Invoices`]
6821
+ }), "mail_folder_change", folderChange).summary("rename a folder").description("rename a folder of your own on the server; the inbox and the special folders keep their names").argument("<folder>", "the folder, by path or name").argument("<name>", "its new path").action(async function(folder, name) {
6822
+ await changeFolder(this, "rename", async (writes, folders) => {
6823
+ const found2 = existing(folders, folder);
6824
+ if (found2.role)
6825
+ throw new CliError13("validation_error", `${found2.path} is the ${found2.role} folder; it keeps its name`);
6826
+ await writes.renameFolder(found2.path, name);
6827
+ return { folder: found2.path, to: name };
6828
+ });
6829
+ }), "renameCommand");
6830
+ var deleteFolderCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command("delete"), {
6831
+ effects: REMOTE_WRITE,
6832
+ examples: [`${IDENTITY.command} personal folders delete Old --yes`]
6833
+ }), "mail_folder_change", folderChange).summary("delete an empty folder").description("delete a folder of your own; it must be empty (move or delete its mail first), unless --allow-dangerous, which loses that mail for good; a preview without --yes").argument("<folder>", "the folder, by path or name").option("--yes", "delete it; without it, only a preview").option("--dry-run", "only preview, even with --yes").addOption(ownerOnlyOption("--allow-dangerous", "delete a folder that still holds mail: that mail is gone for good, no restore")).action(async function(folder, options) {
6834
+ const given = this.optsWithGlobals();
6835
+ const dangerous = given.allowDangerous === true;
6836
+ const emptyOrAllowed = /* @__PURE__ */ __name((folders) => {
6837
+ const found2 = existing(folders, folder);
6838
+ if (found2.role)
6839
+ throw new CliError13("validation_error", `${found2.path} is the ${found2.role} folder; it stays`);
6840
+ if (found2.messages !== 0 && !dangerous)
6841
+ throw new CliError13("validation_error", `${found2.path} holds ${found2.messages ?? "an unknown number of"} messages; move them out first (messages move --filter 'mailbox:"${found2.path}"' --folder \u2026), or the owner adds --allow-dangerous to lose them`, { reason: "mail.folder-not-empty" });
6842
+ return found2;
6843
+ }, "emptyOrAllowed");
6844
+ const preview = options.dryRun === true || given.yes !== true;
6845
+ await changeFolder(this, "delete", async (writes, folders) => {
6846
+ const found2 = emptyOrAllowed(folders);
6847
+ await writes.deleteFolder(found2.path);
6848
+ return { folder: found2.path, messages: found2.messages, applied: true };
6849
+ }, preview ? (folders) => {
6850
+ const found2 = emptyOrAllowed(folders);
6851
+ return { folder: found2.path, messages: found2.messages };
6852
+ } : void 0);
6853
+ }), "deleteFolderCommand");
6854
+ var foldersCommand = /* @__PURE__ */ __name(() => annotate(new Command("folders"), { effects: LOCAL_READ }).description("the folders of this profile's mailbox").addCommand(listCommand()).addCommand(createCommand()).addCommand(renameCommand()).addCommand(deleteFolderCommand()), "foldersCommand");
6855
+ var foldersFor = /* @__PURE__ */ __name(async (explicit, configured, defaults, list2) => {
6856
+ if (explicit?.length)
6857
+ return explicit;
6858
+ if (configured?.length)
6859
+ return configured;
6860
+ const found2 = await list2();
6861
+ const chosen2 = found2.filter((folder) => folder.role && defaults.roles.includes(folder.role)).map(({ path: path2 }) => path2);
6862
+ return chosen2.length ? chosen2 : [defaults.otherwise];
6863
+ }, "foldersFor");
6864
+
6865
+ // dist/commands/sync.js
6866
+ import { CliError as CliError15 } from "@wirecat/cli-base";
6867
+ import { annotate as annotate2 } from "@wirecat/cli-base/commands";
6868
+ import { timezoneOf, zonedMoment } from "@wirecat/cli-base/query";
6869
+ import { answerEntity as answerEntity2, answerLocally, baseContext as baseContext2, environmentOf as environmentOf2, FETCH, itemOf as itemOf2, outputFor as outputFor2, positiveCount, runBudgetOf } from "@wirecat/cli-core";
6870
+ import { mailAccountKey, SEARCH_REFUSED as SEARCH_REFUSED2, scoreSenders, storedMailRuleSet, syncMail, syncMailServer } from "@wirecat/cli-core/mail";
6871
+ import { Command as Command2 } from "commander";
6872
+
6873
+ // dist/mail/rethread.js
6874
+ import { CliError as CliError14 } from "@wirecat/cli-base";
6875
+ var rethreadStored = /* @__PURE__ */ __name(async (backend, store, key, folders, since, mayGoOn) => {
6876
+ const account = await store.accounts.storedAccount(key).catch((error2) => {
6877
+ if (error2 instanceof CliError14 && error2.code === "not_found")
6878
+ return null;
6879
+ throw error2;
6880
+ });
6881
+ if (account === null || backend.search === void 0)
6882
+ return { moved: 0, complete: true };
6883
+ let moved = 0;
6884
+ for (const folder of folders) {
6885
+ const searched = await backend.search(since, folder);
6886
+ if (!searched.quick)
6887
+ continue;
6888
+ const slice = backend.listBatch ?? 200;
6889
+ for (let start = 0; start < searched.uids.length; start += slice) {
6890
+ if (!mayGoOn())
6891
+ return { moved, complete: false };
6892
+ const listed2 = await backend.list(since, folder, {
6893
+ searched: { ...searched, uids: searched.uids.slice(start, start + slice) }
6894
+ });
6895
+ const wanted = new Map(listed2.map(({ messageId, threadId }) => [messageId, threadId]));
6896
+ const placed = await store.mail.inThreads(account.id, [...wanted.keys()]);
6897
+ const astray = placed.filter(({ externalId, threadExternalId }) => wanted.get(externalId) !== threadExternalId);
6898
+ const now = Date.now();
6899
+ for (const { externalId } of astray) {
6900
+ const email2 = await store.mail.email(account.id, externalId);
6901
+ const threadId = wanted.get(externalId);
6902
+ if (email2 === null || threadId === void 0)
6903
+ continue;
6904
+ await store.mail.saveThread({
6905
+ accountId: account.id,
6906
+ externalId: threadId,
6907
+ now,
6908
+ emails: [
6909
+ {
6910
+ externalId,
6911
+ subject: email2.subject,
6912
+ from: email2.fromAddress === null ? null : { address: email2.fromAddress, name: email2.fromName },
6913
+ sentAt: email2.sentAt,
6914
+ bodyText: email2.bodyText
6915
+ }
6916
+ ]
6917
+ });
6918
+ moved++;
6919
+ }
6920
+ }
6921
+ }
6922
+ return { moved, complete: true };
6923
+ }, "rethreadStored");
6924
+
6925
+ // dist/mail/send-as.js
6926
+ var SEND_AS_KEY = "mail_send_as";
6927
+ var SEND_AS_URL = "https://gmail.googleapis.com/gmail/v1/users/me/settings/sendAs";
6928
+ var SendAsList = object({
6929
+ sendAs: optional(array(object({
6930
+ sendAsEmail: string(),
6931
+ isPrimary: optional(boolean()),
6932
+ verificationStatus: optional(string())
6933
+ })))
6934
+ });
6935
+ var readSendAs = /* @__PURE__ */ __name(async (accessToken, fetcher, signal) => {
6936
+ const response = await signInFetch(fetcher)(SEND_AS_URL, {
6937
+ headers: { authorization: `Bearer ${accessToken}`, accept: "application/json" },
6938
+ ...signal ? { signal } : {},
6939
+ redirect: "error"
6940
+ });
6941
+ if (!response.ok)
6942
+ throw new Error(`Gmail answered HTTP ${response.status}`);
6943
+ const list2 = safeParse(SendAsList, await response.json().catch(() => void 0));
6944
+ if (!list2.success)
6945
+ throw new Error("Gmail's answer is not a sendAs list");
6946
+ return [
6947
+ ...new Set((list2.output.sendAs ?? []).filter(({ isPrimary, verificationStatus }) => !isPrimary && verificationStatus === "accepted").map(({ sendAsEmail }) => sendAsEmail.trim().toLowerCase()))
6948
+ ].sort();
6949
+ }, "readSendAs");
6950
+ var savedOf = /* @__PURE__ */ __name((value) => {
6951
+ if (value === void 0)
6952
+ return [];
6953
+ try {
6954
+ const parsed2 = JSON.parse(value);
6955
+ return Array.isArray(parsed2) ? parsed2.filter((item) => typeof item === "string") : [];
6956
+ } catch {
6957
+ return [];
6958
+ }
6959
+ }, "savedOf");
6960
+ var savedSendAs = /* @__PURE__ */ __name(async (store, key) => savedOf((await store.sync.syncState(key, SEND_AS_KEY))?.value), "savedSendAs");
6961
+ var gmailAliases = /* @__PURE__ */ __name(async (store, key, read) => {
6962
+ const saved2 = await savedSendAs(store, key);
6963
+ let aliases;
6964
+ try {
6965
+ aliases = await read();
6966
+ } catch (error2) {
6967
+ return { aliases: saved2, unread: error2 instanceof Error ? error2.message : String(error2) };
6968
+ }
6969
+ if (JSON.stringify(aliases) !== JSON.stringify(saved2))
6970
+ await store.sync.setSyncState(key, SEND_AS_KEY, JSON.stringify(aliases));
6971
+ return { aliases };
6972
+ }, "gmailAliases");
6973
+
6974
+ // dist/store.js
6975
+ import { openAppStore } from "@wirecat/cli-core";
6976
+ var PROVIDER = { name: "email", kind: "mail", aliases: [], command: IDENTITY.command };
6977
+ var openMailStore = /* @__PURE__ */ __name((env, { readOnly = false } = {}) => openAppStore(env, { app: IDENTITY, provider: PROVIDER, readOnly }), "openMailStore");
6978
+
6979
+ // dist/commands/server-search.js
6980
+ var serverAccess = /* @__PURE__ */ __name((command) => {
6981
+ const context = contextOf(command);
6982
+ const { settings } = context;
6983
+ const { address, host, folders: configured } = settings.mailbox;
6984
+ const search = providerFor(address ?? "", host)?.search ?? DEFAULT_SEARCH;
6985
+ return {
6986
+ ...search.timeMs === void 0 ? {} : { timeMs: search.timeMs },
6987
+ offline: context.flags.offline === true,
6988
+ permissions: settings.permissions,
6989
+ open: /* @__PURE__ */ __name(async () => {
6990
+ const { backend } = await openMail(context);
6991
+ const serverQuery = backend.serverQuery;
6992
+ try {
6993
+ const folders = await foldersFor(void 0, configured, search, () => backend.folderList());
6994
+ return {
6995
+ source: {
6996
+ ...backend,
6997
+ ...serverQuery ? { query: /* @__PURE__ */ __name((criteria, folder) => serverQuery(criteria, folder, search.syntax), "query") } : {}
6998
+ },
6999
+ folders,
7000
+ close: backend.close
7001
+ };
7002
+ } catch (error2) {
7003
+ await backend.close();
7004
+ throw error2;
7005
+ }
7006
+ }, "open")
7007
+ };
7008
+ }, "serverAccess");
7009
+
7010
+ // dist/commands/sync.js
7011
+ var DAY_MS = 864e5;
7012
+ var WINDOW_DAYS = { d: 1, w: 7, y: 365 };
7013
+ var MB = 1024 * 1024;
7014
+ var stoppedText = /* @__PURE__ */ __name((stopped, budget) => (stopped === "requests" || stopped === "deadline") && budget.limit !== null ? `the run stopped at its cap of ${budget.limit} requests (--timeout sets it, --max-pages only lowers it); ` : "", "stoppedText");
7015
+ var sinceOf = /* @__PURE__ */ __name((value, zone, now, setting = DEFAULT_SYNC_SINCE) => {
7016
+ if (value !== void 0)
7017
+ return momentOf(value, zone, now, "--since-time");
7018
+ const window = SYNC_WINDOW.exec(setting);
7019
+ if (!window)
7020
+ return momentOf(setting, zone, now, "sync_since");
7021
+ return new Date(now - Number(window[1]) * (WINDOW_DAYS[window[2]] ?? 1) * DAY_MS);
7022
+ }, "sinceOf");
7023
+ var momentOf = /* @__PURE__ */ __name((value, zone, now, name) => {
7024
+ const refuse = /* @__PURE__ */ __name(() => new CliError15("validation_error", `${name} takes an ISO date or timestamp in the past`, {
7025
+ param: name === "--since-time" ? "since-time" : "sync_since"
7026
+ }), "refuse");
7027
+ let since;
7028
+ try {
7029
+ since = zonedMoment(value, zone, { start: 0, end: value.length });
7030
+ } catch (error2) {
7031
+ if (error2 instanceof CliError15)
7032
+ throw refuse();
7033
+ throw error2;
7034
+ }
7035
+ if (since > now)
7036
+ throw refuse();
7037
+ return new Date(since);
7038
+ }, "momentOf");
7039
+ var BUDGET_CODES = { requests: "rate_limited", deadline: "timeout", cancelled: "cancelled" };
7040
+ var issuesOf = /* @__PURE__ */ __name((report) => [
7041
+ ...report.unreadable?.length ? [{ code: "invalid_response", reason: "mail.unreadable", source: "sync" }] : [],
7042
+ ...report.deletionsSkipped ? [{ code: "outcome_unknown", reason: "mail.deletions-skipped", source: "sync" }] : [],
7043
+ ...report.stopped ? [{ code: BUDGET_CODES[report.stopped], reason: `budget.${report.stopped}`, source: "sync" }] : [],
7044
+ ...report.refusedFolders?.length ? [{ code: "provider_error", reason: SEARCH_REFUSED2, source: "sync" }] : []
7045
+ ], "issuesOf");
7046
+ var sendAsOf = /* @__PURE__ */ __name(async (context, store, address) => {
7047
+ const { mailbox } = context.settings;
7048
+ if (mailbox.auth !== "oauth" || oauthKindOf(mailbox) !== "google")
7049
+ return void 0;
7050
+ const { credential } = await credentialOf(context);
7051
+ return gmailAliases(store, mailAccountKey(address), async () => {
7052
+ const login = await credential.login();
7053
+ if (!("accessToken" in login))
7054
+ return [];
7055
+ return readSendAs(login.accessToken, context.environment.fetch, context.environment.signal);
7056
+ });
7057
+ }, "sendAsOf");
7058
+ var mailSync = strictObject({
7059
+ address: string(),
7060
+ /** With --query: what the server was asked. Such a run reads no window and no folder list of its own. */
7061
+ query: optional(string()),
7062
+ since: optional(string()),
7063
+ timezone: string(),
7064
+ folders: optional(array(string())),
7065
+ state: picklist(["partial", "complete"]),
7066
+ stopped: optional(picklist(["requests", "deadline", "cancelled", "limit"])),
7067
+ requests: number(),
7068
+ listed: number(),
6649
7069
  saved: number(),
6650
7070
  already_stored: number(),
6651
7071
  deleted: number(),
@@ -6675,7 +7095,7 @@ var mailSync = strictObject({
6675
7095
  send_as: optional(strictObject({ aliases: number(), unread: optional(string()) })),
6676
7096
  hint: optional(string())
6677
7097
  });
6678
- var syncCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command("sync"), {
7098
+ var syncCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Command2("sync"), {
6679
7099
  effects: FETCH,
6680
7100
  // The run stops on its own before its deadline, keeps what it read and says how to go on (WC-LIFE-16).
6681
7101
  cooperative: true,
@@ -6683,20 +7103,22 @@ var syncCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command
6683
7103
  examples: [
6684
7104
  `${IDENTITY.command} personal sync`,
6685
7105
  `${IDENTITY.command} personal sync --since-time 2026-10-01 --max-messages 200`,
6686
- `${IDENTITY.command} personal sync --folder INBOX`
7106
+ `${IDENTITY.command} personal sync --query 'invoice from:ann@example.com'`
6687
7107
  ]
6688
- }), "mail_sync", mailSync).description("read mail from the server into the shared store; mail already stored is skipped").option("--since-time <time>", "only mail received since this date or time; a date alone starts at local midnight, a time without a zone is local (default: the profile's sync_since, else 30d)").option("--max-messages <n>", "save at most this many new emails in this run, newest first", positiveCount("--max-messages")).option("--max-pages <pages>", "at most this many requests to the mail server in this run; as many as fit the deadline if not given", positiveCount("--max-pages")).addOption(repeatable("--folder <folder>", "a folder to read; repeat it for more (default: the profile's folders, else INBOX and Sent; All Mail on Gmail)")).option("--attachments", "read attachments into the search index this run, whatever the profile's read_attachments").option("--no-attachments", "read no attachment this run; each is stored with its name and size, without text").option("--max-attachment-mb <mb>", "the largest attachment to read this run, in MB (default: the profile's max_attachment_mb, else 10)", positiveCount("--max-attachment-mb")).option("--rescan", "list the whole window again; also moves stored replies into their thread where the server has no thread ids").action(async function(args) {
7108
+ }), "mail_sync", mailSync).description("read mail from the server into the shared store; mail already stored is skipped").option("--query <query>", "store only what the server finds for this search query, as search messages shows it; takes no other option").option("--since-time <time>", "only mail received since this date or time; a date alone starts at local midnight, a time without a zone is local (default: the profile's sync_since, else 30d)").option("--max-messages <n>", "save at most this many new emails in this run, newest first", positiveCount("--max-messages")).option("--max-pages <pages>", "at most this many requests to the mail server in this run; as many as fit the deadline if not given", positiveCount("--max-pages")).addOption(repeatable("--folder <folder>", "a folder to read; repeat it for more (default: the profile's folders, else INBOX and Sent; All Mail on Gmail)")).option("--attachments", "read attachments into the search index this run, whatever the profile's read_attachments").option("--no-attachments", "read no attachment this run; each is stored with its name and size, without text").option("--max-attachment-mb <mb>", "the largest attachment to read this run, in MB (default: the profile's max_attachment_mb, else 10)", positiveCount("--max-attachment-mb")).option("--rescan", "list the whole window again; also moves stored replies into their thread where the server has no thread ids").action(async function(args) {
7109
+ if (args.query !== void 0)
7110
+ return syncByQuery(this, args.query);
6689
7111
  const context = contextOf(this);
6690
7112
  refuseOffline(context.flags);
6691
7113
  const address = context.settings.mailbox.address;
6692
7114
  if (!address)
6693
- throw new CliError13("configuration_error", `profile ${context.profile} has no address`);
7115
+ throw new CliError15("configuration_error", `profile ${context.profile} has no address`);
6694
7116
  const zone = timezoneOf();
6695
7117
  const since = sinceOf(args.sinceTime, zone, Date.now(), context.settings.mailbox.syncSince);
6696
7118
  const { signal } = environmentOf2(this);
6697
7119
  const budget = runBudgetOf(this, args.maxPages);
6698
7120
  const { backend } = await openMail(context, { canRetry: /* @__PURE__ */ __name(() => budget.take() === null, "canRetry") });
6699
- const { report, rethreaded, unreadable, senders, sendAs } = await closing(backend, () => baseContext(this, configuration.resolveSettings).run(async () => {
7121
+ const { report, rethreaded, unreadable, senders, sendAs } = await closing(backend, () => baseContext2(this, configuration.resolveSettings).run(async () => {
6700
7122
  const { mailbox } = context.settings;
6701
7123
  const defaults = providerFor(address, mailbox.host)?.sync ?? DEFAULT_SYNC;
6702
7124
  const folders = await foldersFor(args.folder, mailbox.folders, defaults, () => backend.folderList());
@@ -6765,7 +7187,7 @@ var syncCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command
6765
7187
  }
6766
7188
  ] : [];
6767
7189
  const hint = !partial ? void 0 : refused2.length ? `the server refused to search ${refused2.join(", ")}; nothing there was read or marked deleted \u2014 run sync again later, or name the other folders with --folder` : limited ? `${report.remaining ?? 0} new emails are left; run sync again to save the next ${args.maxMessages}` : moved ? `${stoppedText(stopped, budget)}${args.rescan ? "run sync again WITHOUT --rescan to continue: --rescan starts over from the newest mail" : "run sync again to continue"}; ${IDENTITY.command} ${context.profile} status shows how far it is` : "this run moved nothing on: raise --timeout or --max-pages, then run sync again";
6768
- answerLocally(this, outputFor(this), itemOf({
7190
+ answerLocally(this, outputFor2(this), itemOf2({
6769
7191
  address: report.account,
6770
7192
  since: report.since,
6771
7193
  timezone: zone,
@@ -6808,6 +7230,76 @@ var syncCommand = /* @__PURE__ */ __name(() => answerEntity(annotate(new Command
6808
7230
  }
6809
7231
  }));
6810
7232
  }), "syncCommand");
7233
+ var FAILED = {
7234
+ rate_limited: { code: "rate_limited", reason: "search.server-rate-limited" },
7235
+ search_failed: { code: "provider_unavailable", reason: "search.server-failed" },
7236
+ time_or_abort_bound: { code: "timeout", reason: "search.server-timeout" }
7237
+ };
7238
+ var syncByQuery = /* @__PURE__ */ __name(async (command, query) => {
7239
+ const typed = command.options.filter((option) => command.getOptionValueSource(option.attributeName()) === "cli");
7240
+ if (typed.some((option) => option.attributeName() !== "query"))
7241
+ throw new CliError15("validation_error", "--query takes no other sync option", { param: "query" });
7242
+ if (!query.trim())
7243
+ throw new CliError15("validation_error", "--query needs a search query", { param: "query" });
7244
+ const context = contextOf(command);
7245
+ refuseOffline(context.flags);
7246
+ const address = context.settings.mailbox.address;
7247
+ if (!address)
7248
+ throw new CliError15("configuration_error", `profile ${context.profile} has no address`);
7249
+ const zone = timezoneOf();
7250
+ const { signal } = environmentOf2(command);
7251
+ const deadline = context.environment.deadline?.();
7252
+ const { report } = await baseContext2(command, configuration.resolveSettings).run(async () => {
7253
+ const store = await openMailStore(context.env);
7254
+ environmentOf2(command).trackCloseable?.(store);
7255
+ try {
7256
+ return await syncMailServer(store, mailAccountKey(address), serverAccess(command), {
7257
+ text: query,
7258
+ timeMs: 6e4,
7259
+ ...deadline ? { deadline } : {},
7260
+ ...signal ? { signal } : {}
7261
+ });
7262
+ } finally {
7263
+ await store.close();
7264
+ }
7265
+ });
7266
+ const issues = [
7267
+ ...[...new Set(report.failed.map(({ reason }) => reason))].map((reason) => ({ ...FAILED[reason], source: "sync" })),
7268
+ ...report.partial ? [{ code: "outcome_unknown", reason: "search.server-partial", source: "sync" }] : []
7269
+ ];
7270
+ const next = report.partial ? [
7271
+ {
7272
+ kind: "command",
7273
+ step: "mail.sync",
7274
+ command: "sync",
7275
+ args: {},
7276
+ why: `${report.partial} big emails were stored from their first bytes; a full sync reads them whole`,
7277
+ safe_to_auto_execute: true
7278
+ }
7279
+ ] : [];
7280
+ answerLocally(command, outputFor2(command), itemOf2({
7281
+ address,
7282
+ query,
7283
+ timezone: zone,
7284
+ state: report.complete ? "complete" : "partial",
7285
+ requests: report.calls,
7286
+ listed: report.returned,
7287
+ saved: report.new,
7288
+ already_stored: report.returned - report.new,
7289
+ deleted: 0,
7290
+ complete: report.complete,
7291
+ remaining: 0,
7292
+ unreadable: 0,
7293
+ ...report.complete ? {} : { hint: "the server answered in part; run the same sync --query again, or a full sync" }
7294
+ }, {
7295
+ next,
7296
+ meta: {
7297
+ complete: report.complete && issues.length === 0,
7298
+ ...issues.length ? { issues } : {},
7299
+ timezone: zone
7300
+ }
7301
+ }));
7302
+ }, "syncByQuery");
6811
7303
 
6812
7304
  // dist/commands/account.js
6813
7305
  var mailAccountCheck = strictObject({
@@ -6821,15 +7313,15 @@ var mailAccountCheck = strictObject({
6821
7313
  features: record(string(), boolean()),
6822
7314
  folders: number()
6823
7315
  });
6824
- var checkCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Command2("check"), {
6825
- effects: REMOTE_READ,
7316
+ var checkCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new Command3("check"), {
7317
+ effects: REMOTE_READ2,
6826
7318
  examples: [`${IDENTITY.command} personal account check`, `${IDENTITY.command} personal account check --json`]
6827
7319
  }), "mail_account_check", mailAccountCheck).summary("log in and list what the server supports").description("log in to the server and list what it supports (IDLE, CONDSTORE, MOVE, Gmail extensions)").action(async function() {
6828
7320
  const context = contextOf(this);
6829
7321
  refuseOffline(context.flags);
6830
7322
  const { backend, endpoint, passwordFrom: passwordFrom2 } = await openMail(context);
6831
- const checked = await closing(backend, () => baseContext2(this, configuration.resolveSettings).run(() => backend.check()));
6832
- renderAnswer(this, outputFor2(this), itemOf2({
7323
+ const checked = await closing(backend, () => baseContext3(this, configuration.resolveSettings).run(() => backend.check()));
7324
+ renderAnswer2(this, outputFor3(this), itemOf3({
6833
7325
  profile: context.profile,
6834
7326
  host: endpoint.host,
6835
7327
  port: endpoint.port,
@@ -6895,8 +7387,8 @@ var probeText = /* @__PURE__ */ __name((probe, seconds, zone) => {
6895
7387
  ].join("\n")}
6896
7388
  `;
6897
7389
  }, "probeText");
6898
- var inspectCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Command2("inspect"), {
6899
- effects: REMOTE_READ,
7390
+ var inspectCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new Command3("inspect"), {
7391
+ effects: REMOTE_READ2,
6900
7392
  examples: [
6901
7393
  `${IDENTITY.command} gm account inspect`,
6902
7394
  `${IDENTITY.command} gm account inspect --since-time 2025-01-01 --limit 20 --domain-age`
@@ -6906,12 +7398,12 @@ var inspectCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Co
6906
7398
  refuseOffline(context.flags);
6907
7399
  const { address, host, folders: configured } = context.settings.mailbox;
6908
7400
  if (!address)
6909
- throw new CliError14("configuration_error", `profile ${context.profile} has no address`);
7401
+ throw new CliError16("configuration_error", `profile ${context.profile} has no address`);
6910
7402
  const zone = args.sinceTime === void 0 ? void 0 : timezoneOf2();
6911
7403
  const since = zone === void 0 ? /* @__PURE__ */ new Date(0) : sinceOf(args.sinceTime, zone, Date.now());
6912
7404
  const started = Date.now();
6913
7405
  const { backend } = await openMail(context);
6914
- const { folders, items } = await closing(backend, () => baseContext2(this, configuration.resolveSettings).run(async () => {
7406
+ const { folders, items } = await closing(backend, () => baseContext3(this, configuration.resolveSettings).run(async () => {
6915
7407
  const defaults = providerFor(address, host)?.sync ?? DEFAULT_SYNC;
6916
7408
  const folders2 = await foldersFor(args.folder, configured, defaults, () => backend.folderList());
6917
7409
  const listed2 = /* @__PURE__ */ new Map();
@@ -6927,7 +7419,7 @@ var inspectCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Co
6927
7419
  probe = probeMail(items, args.limit, knownAges(context.env));
6928
7420
  }
6929
7421
  const seconds = Math.round((Date.now() - started) / 100) / 10;
6930
- renderAnswer(this, outputFor2(this), itemOf2({
7422
+ renderAnswer2(this, outputFor3(this), itemOf3({
6931
7423
  address,
6932
7424
  folders,
6933
7425
  emails: probe.emails,
@@ -6955,22 +7447,22 @@ var inspectCommand = /* @__PURE__ */ __name(() => answerEntity2(annotate2(new Co
6955
7447
  seconds
6956
7448
  }, zone === void 0 ? {} : { meta: { timezone: zone, window: { since: since.toISOString() } } }), () => probeText(probe, seconds, zone));
6957
7449
  }), "inspectCommand");
6958
- var accountCommand = /* @__PURE__ */ __name(() => annotate2(new Command2("account"), { effects: LOCAL_READ }).description("the mailbox behind this profile").addCommand(checkCommand()).addCommand(inspectCommand()).addCommand(removeCommand()), "accountCommand");
7450
+ var accountCommand = /* @__PURE__ */ __name(() => annotate3(new Command3("account"), { effects: LOCAL_READ2 }).description("the mailbox behind this profile").addCommand(checkCommand()).addCommand(inspectCommand()).addCommand(removeCommand()), "accountCommand");
6959
7451
 
6960
7452
  // dist/commands/attachments.js
6961
7453
  import { resolve as resolve3 } from "node:path";
6962
- import { CliError as CliError21 } from "@wirecat/cli-base";
6963
- import { annotate as annotate3 } from "@wirecat/cli-base/commands";
6964
- import { answerEntity as answerEntity3, FETCH as FETCH2, itemOf as itemOf4, listOf, outputFor as outputFor4, REMOTE_READ as REMOTE_READ2, refusedPlace, renderAnswer as renderAnswer3 } from "@wirecat/cli-core";
7454
+ import { CliError as CliError22 } from "@wirecat/cli-base";
7455
+ import { annotate as annotate4 } from "@wirecat/cli-base/commands";
7456
+ import { answerEntity as answerEntity4, FETCH as FETCH2, itemOf as itemOf5, listOf as listOf2, outputFor as outputFor5, REMOTE_READ as REMOTE_READ3, refusedPlace, renderAnswer as renderAnswer4 } from "@wirecat/cli-core";
6965
7457
  import { parseMail as parseMail2 } from "@wirecat/cli-core/mail";
6966
- import { Command as Command3 } from "commander";
7458
+ import { Command as Command4 } from "commander";
6967
7459
 
6968
7460
  // dist/mail/save.js
6969
7461
  import { lstatSync, mkdirSync as mkdirSync4 } from "node:fs";
6970
7462
  import { dirname as dirname2, extname } from "node:path";
6971
- import { CliError as CliError15 } from "@wirecat/cli-base";
7463
+ import { CliError as CliError17 } from "@wirecat/cli-base";
6972
7464
  import { safeName as plainName, writeFileAtomic as writeFileAtomic2 } from "@wirecat/cli-core";
6973
- var exists = /* @__PURE__ */ __name((path2) => new CliError15("validation_error", `${path2} already exists`, {
7465
+ var exists = /* @__PURE__ */ __name((path2) => new CliError17("validation_error", `${path2} already exists`, {
6974
7466
  reason: "download.exists",
6975
7467
  param: "output-dir"
6976
7468
  }), "exists");
@@ -7013,12 +7505,12 @@ var distinctNames = /* @__PURE__ */ __name((names) => {
7013
7505
  }, "distinctNames");
7014
7506
 
7015
7507
  // dist/mail/send.js
7016
- import { CliError as CliError19, realSleep as realSleep2 } from "@wirecat/cli-base";
7017
- import { DEFAULT_PACE, guardedWrite as guardedWrite2, newOperationId as newOperationId2, Pacer, pacePathFor } from "@wirecat/cli-core";
7508
+ import { CliError as CliError20, realSleep as realSleep2 } from "@wirecat/cli-base";
7509
+ import { DEFAULT_PACE, guardedWrite as guardedWrite3, newOperationId as newOperationId3, Pacer, pacePathFor } from "@wirecat/cli-core";
7018
7510
  import { mailIds as mailIds2, storedMailRules, syncMail as syncMail2 } from "@wirecat/cli-core/mail";
7019
7511
 
7020
7512
  // dist/mail/compose.js
7021
- import { CliError as CliError16 } from "@wirecat/cli-base";
7513
+ import { CliError as CliError18 } from "@wirecat/cli-base";
7022
7514
  import { parseMail } from "@wirecat/cli-core/mail";
7023
7515
 
7024
7516
  // node_modules/.pnpm/nodemailer@10.1.7/node_modules/nodemailer/dist/esm/addressparser/index.js
@@ -12366,562 +12858,285 @@ var MailComposer = class {
12366
12858
  if (this._useAlternative) {
12367
12859
  this._createAlternative(node);
12368
12860
  } else if (this._useRelated) {
12369
- this._createRelated(node);
12370
- }
12371
- [].concat(!this._useAlternative && this._alternatives || []).concat(this._attachments.attached || []).forEach((element) => {
12372
- if (!this._useRelated || element !== this._htmlNode) {
12373
- this._createContentNode(node, element);
12374
- }
12375
- });
12376
- return node;
12377
- }
12378
- /**
12379
- * Builds multipart/alternative node. It should always contain same type of elements on the same level
12380
- * eg. text + html view of the same data
12381
- *
12382
- * @param parentNode Parent for this note. If it does not exist, a root node is created
12383
- * @returns MimeNode node element
12384
- * @internal
12385
- */
12386
- _createAlternative(parentNode) {
12387
- const node = parentNode ? parentNode.createChild("multipart/alternative", {
12388
- disableUrlAccess: this.mail.disableUrlAccess,
12389
- disableFileAccess: this.mail.disableFileAccess,
12390
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12391
- newline: this.mail.newline
12392
- }) : new mime_node_default("multipart/alternative", {
12393
- baseBoundary: this.mail.baseBoundary,
12394
- textEncoding: this.mail.textEncoding,
12395
- boundaryPrefix: this.mail.boundaryPrefix,
12396
- disableUrlAccess: this.mail.disableUrlAccess,
12397
- disableFileAccess: this.mail.disableFileAccess,
12398
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12399
- newline: this.mail.newline
12400
- });
12401
- this._alternatives.forEach((alternative) => {
12402
- if (this._useRelated && this._htmlNode === alternative) {
12403
- this._createRelated(node);
12404
- } else {
12405
- this._createContentNode(node, alternative);
12406
- }
12407
- });
12408
- return node;
12409
- }
12410
- /**
12411
- * Builds multipart/related node. It should always contain html node with related attachments
12412
- *
12413
- * @param parentNode Parent for this note. If it does not exist, a root node is created
12414
- * @returns MimeNode node element
12415
- * @internal
12416
- */
12417
- _createRelated(parentNode) {
12418
- const node = parentNode ? parentNode.createChild('multipart/related; type="text/html"', {
12419
- disableUrlAccess: this.mail.disableUrlAccess,
12420
- disableFileAccess: this.mail.disableFileAccess,
12421
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12422
- newline: this.mail.newline
12423
- }) : new mime_node_default('multipart/related; type="text/html"', {
12424
- baseBoundary: this.mail.baseBoundary,
12425
- textEncoding: this.mail.textEncoding,
12426
- boundaryPrefix: this.mail.boundaryPrefix,
12427
- disableUrlAccess: this.mail.disableUrlAccess,
12428
- disableFileAccess: this.mail.disableFileAccess,
12429
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12430
- newline: this.mail.newline
12431
- });
12432
- this._createContentNode(node, this._htmlNode);
12433
- this._attachments.related.forEach((alternative) => this._createContentNode(node, alternative));
12434
- return node;
12435
- }
12436
- /**
12437
- * Creates a regular node with contents
12438
- *
12439
- * @param parentNode Parent for this note. If it does not exist, a root node is created
12440
- * @param element Node data
12441
- * @returns MimeNode node element
12442
- * @internal
12443
- */
12444
- _createContentNode(parentNode, element) {
12445
- element = element || {};
12446
- element.content = element.content || "";
12447
- const encoding = (element.encoding || "utf8").toString().toLowerCase().replace(/[-_\s]/g, "");
12448
- const node = parentNode ? parentNode.createChild(element.contentType, {
12449
- filename: element.filename,
12450
- textEncoding: this.mail.textEncoding,
12451
- disableUrlAccess: this.mail.disableUrlAccess,
12452
- disableFileAccess: this.mail.disableFileAccess,
12453
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12454
- newline: this.mail.newline
12455
- }) : new mime_node_default(element.contentType, {
12456
- filename: element.filename,
12457
- baseBoundary: this.mail.baseBoundary,
12458
- textEncoding: this.mail.textEncoding,
12459
- boundaryPrefix: this.mail.boundaryPrefix,
12460
- disableUrlAccess: this.mail.disableUrlAccess,
12461
- disableFileAccess: this.mail.disableFileAccess,
12462
- normalizeHeaderKey: this.mail.normalizeHeaderKey,
12463
- newline: this.mail.newline
12464
- });
12465
- if (element.headers) {
12466
- node.addHeader(element.headers);
12467
- }
12468
- if (element.cid) {
12469
- node.setHeader("Content-Id", "<" + element.cid.replace(/[<>]/g, "") + ">");
12470
- }
12471
- if (element.contentTransferEncoding) {
12472
- node.setHeader("Content-Transfer-Encoding", element.contentTransferEncoding);
12473
- } else if (this.mail.encoding && /^text\//i.test(element.contentType)) {
12474
- node.setHeader("Content-Transfer-Encoding", this.mail.encoding);
12475
- }
12476
- if (!/^text\//i.test(element.contentType) || element.contentDisposition) {
12477
- node.setHeader("Content-Disposition", element.contentDisposition || (element.cid && /^image\//i.test(element.contentType) ? "inline" : "attachment"));
12478
- }
12479
- if (typeof element.content === "string" && !["utf8", "usascii", "ascii"].includes(encoding)) {
12480
- element.content = Buffer.from(element.content, encoding);
12481
- }
12482
- if (element.raw) {
12483
- node.setRaw(element.raw);
12484
- } else {
12485
- node.setContent(element.content);
12486
- }
12487
- return node;
12488
- }
12489
- /**
12490
- * Parses data uri and converts it to a Buffer
12491
- *
12492
- * @param element Content element
12493
- * @return Parsed element
12494
- * @internal
12495
- */
12496
- _processDataUrl(element) {
12497
- const dataUrl = element.path || element.href;
12498
- if (!dataUrl || typeof dataUrl !== "string") {
12499
- return element;
12500
- }
12501
- if (!dataUrl.startsWith("data:")) {
12502
- return element;
12503
- }
12504
- if (dataUrl.length > 52428800) {
12505
- let detectedType = "application/octet-stream";
12506
- const commaPos = dataUrl.indexOf(",");
12507
- if (commaPos > 0 && commaPos < 200) {
12508
- const header2 = dataUrl.substring(5, commaPos);
12509
- const parts = header2.split(";");
12510
- if (parts[0] && parts[0].includes("/")) {
12511
- detectedType = parts[0].trim();
12512
- }
12513
- }
12514
- return Object.assign(copyOwnKeys({}, element), {
12515
- path: false,
12516
- href: false,
12517
- content: Buffer.alloc(0),
12518
- contentType: element.contentType || detectedType
12519
- });
12520
- }
12521
- let parsedDataUri;
12522
- try {
12523
- parsedDataUri = parseDataURI(dataUrl);
12524
- } catch (_err) {
12525
- return element;
12526
- }
12527
- if (!parsedDataUri) {
12528
- return element;
12529
- }
12530
- element.content = parsedDataUri.data;
12531
- element.contentType = element.contentType || parsedDataUri.contentType;
12532
- if ("path" in element) {
12533
- element.path = false;
12534
- }
12535
- if ("href" in element) {
12536
- element.href = false;
12861
+ this._createRelated(node);
12537
12862
  }
12538
- return element;
12539
- }
12540
- };
12541
- var mail_composer_default = MailComposer;
12542
-
12543
- // dist/mail/compose.js
12544
- var EMAIL = /^[^\s@<>()",;:]+@[^\s@<>()",;:]+\.[^\s@<>()",;:]+$/u;
12545
- var peopleOf = /* @__PURE__ */ __name((given, flag2) => given.flatMap((one) => addressparser_default(one, { flatten: true }).map(({ name, address }) => {
12546
- const clean = address.trim().toLowerCase();
12547
- if (!EMAIL.test(clean))
12548
- throw new CliError16("validation_error", `${flag2} takes email addresses; ${JSON.stringify(one)} holds none`, {
12549
- param: flag2.replace(/^--/, "")
12863
+ [].concat(!this._useAlternative && this._alternatives || []).concat(this._attachments.attached || []).forEach((element) => {
12864
+ if (!this._useRelated || element !== this._htmlNode) {
12865
+ this._createContentNode(node, element);
12866
+ }
12550
12867
  });
12551
- return { address: clean, ...name.trim() ? { name: name.trim() } : {} };
12552
- })), "peopleOf");
12553
- var unique = /* @__PURE__ */ __name((people, without = /* @__PURE__ */ new Set()) => {
12554
- const seen = new Set(without);
12555
- return people.filter(({ address }) => !seen.has(address) && seen.add(address) !== void 0);
12556
- }, "unique");
12557
- var personOf = /* @__PURE__ */ __name(({ email: email2, name }) => ({ address: email2, ...name ? { name } : {} }), "personOf");
12558
- var originalOf = /* @__PURE__ */ __name(async (raw) => {
12559
- let mail;
12560
- try {
12561
- mail = await parseMail(raw, void 0, 0);
12562
- } catch {
12563
- throw new CliError16("invalid_response", "the original message on the server cannot be read");
12868
+ return node;
12564
12869
  }
12565
- return {
12566
- ...mail.messageId ? { messageId: mail.messageId } : {},
12567
- references: mail.references,
12568
- subject: mail.subject ?? "",
12569
- ...mail.date ? { date: mail.date } : {},
12570
- ...mail.from ? { from: personOf(mail.from) } : {},
12571
- replyTo: mail.replyTo.map(personOf),
12572
- to: mail.to.map(personOf),
12573
- cc: mail.cc.map(personOf),
12574
- text: mail.text
12575
- };
12576
- }, "originalOf");
12577
- var replyPeople = /* @__PURE__ */ __name((original, owner, all) => {
12578
- const mine = original.from !== void 0 && owner.has(original.from.address);
12579
- const first = mine ? original.to : original.replyTo.length ? original.replyTo : original.from ? [original.from] : [];
12580
- return unique([...first, ...all ? [...original.to, ...original.cc] : []], owner);
12581
- }, "replyPeople");
12582
- var replyCopies = /* @__PURE__ */ __name((original, owner, to) => unique([...original.to, ...original.cc], /* @__PURE__ */ new Set([...owner, ...to.map(({ address }) => address)])), "replyCopies");
12583
- var prefixed = /* @__PURE__ */ __name((subject, prefix, already) => already.test(subject.trim()) ? subject.trim() : `${prefix} ${subject.trim()}`.trim(), "prefixed");
12584
- var replySubject = /* @__PURE__ */ __name((subject) => prefixed(subject, "Re:", /^(re|ha|aw|sv)\s*:/iu), "replySubject");
12585
- var forwardSubject = /* @__PURE__ */ __name((subject) => prefixed(subject, "Fwd:", /^(fwd?|fw)\s*:/iu), "forwardSubject");
12586
- var referencesOf = /* @__PURE__ */ __name((original) => [...original.references, ...original.messageId ? [original.messageId] : []].slice(-20), "referencesOf");
12587
- var shown = /* @__PURE__ */ __name((person) => person === void 0 ? "someone" : person.name ? `${person.name} <${person.address}>` : person.address, "shown");
12588
- var quoted2 = /* @__PURE__ */ __name((text3, original) => {
12589
- const when = original.date ? `On ${original.date}, ` : "";
12590
- const lines = original.text.split("\n").map((line) => line.startsWith(">") ? `>${line}` : `> ${line}`);
12591
- return `${text3.trimEnd()}
12592
-
12593
- ${when}${shown(original.from)} wrote:
12594
- ${lines.join("\n")}
12595
- `;
12596
- }, "quoted");
12597
- var header = /* @__PURE__ */ __name((person) => person.name ? { name: person.name, address: person.address } : person.address, "header");
12598
- var build = /* @__PURE__ */ __name(async (draft) => {
12599
- const options = {
12600
- from: header(draft.from),
12601
- to: draft.to.map(header),
12602
- ...draft.cc.length ? { cc: draft.cc.map(header) } : {},
12603
- ...draft.bcc.length ? { bcc: draft.bcc.map(header) } : {},
12604
- subject: draft.subject,
12605
- text: draft.text,
12606
- ...draft.html === void 0 ? {} : { html: draft.html },
12607
- messageId: draft.messageId,
12608
- date: draft.date,
12609
- ...draft.inReplyTo ? { inReplyTo: draft.inReplyTo } : {},
12610
- ...draft.references?.length ? { references: draft.references } : {},
12611
- attachments: [
12612
- ...draft.files.map(({ name, path: path2 }) => ({ filename: name, path: path2 })),
12613
- ...(draft.parts ?? []).map(({ name, mime, bytes }) => ({
12614
- filename: name,
12615
- content: Buffer.from(bytes),
12616
- ...mime ? { contentType: mime } : {}
12617
- })),
12618
- ...draft.message ? [
12619
- {
12620
- filename: draft.message.name,
12621
- content: Buffer.from(draft.message.raw),
12622
- contentType: "message/rfc822",
12623
- contentDisposition: "attachment"
12624
- }
12625
- ] : []
12626
- ],
12627
- disableUrlAccess: true,
12628
- newline: "\r\n"
12629
- };
12630
- const sent = new mail_composer_default(options).compile();
12631
- const copy = new mail_composer_default(options).compile();
12632
- copy.keepBcc = true;
12633
- return { raw: new Uint8Array(await sent.build()), copy: new Uint8Array(await copy.build()) };
12634
- }, "build");
12635
- var messageIdFor = /* @__PURE__ */ __name((operationId, from) => `<${operationId.replace(/[^\w.-]/g, "")}@${from.split("@")[1] ?? "localhost"}>`, "messageIdFor");
12636
- var forgotAttachment = /* @__PURE__ */ __name((text3, attached) => !attached && /\battach(ed|ment|ing)?\b|влож(ени|ил|ен)|прилага|прикреп/iu.test(text3), "forgotAttachment");
12637
-
12638
- // dist/mail/locate.js
12639
- import { CliError as CliError18 } from "@wirecat/cli-base";
12640
- import { parseReference } from "@wirecat/cli-core";
12641
- import { searchMail } from "@wirecat/cli-core/mail";
12642
-
12643
- // dist/mail/organise.js
12644
- import { CliError as CliError17 } from "@wirecat/cli-base";
12645
- import { guardedWrite, newOperationId } from "@wirecat/cli-core";
12646
- import { decodedLabelName as decodedLabelName2 } from "@wirecat/cli-core/mail";
12647
- var FILTER_LIMIT = 500;
12648
- var MAX_LIMIT = 5e3;
12649
- var BULK = 20;
12650
- var SYSTEM_FLAGS = {
12651
- read: "\\Seen",
12652
- seen: "\\Seen",
12653
- flagged: "\\Flagged",
12654
- starred: "\\Flagged",
12655
- answered: "\\Answered",
12656
- draft: "\\Draft"
12657
- };
12658
- var KEYWORD = /^\$?[A-Za-z0-9_.-]+$/;
12659
- var flagOf = /* @__PURE__ */ __name((given) => {
12660
- const word = given.trim();
12661
- const system = SYSTEM_FLAGS[word.toLowerCase().replace(/^\\/, "")];
12662
- if (system)
12663
- return system;
12664
- if (/^\\deleted$/i.test(word) || word.toLowerCase() === "deleted")
12665
- throw new CliError17("validation_error", "\\Deleted is how a server expunges mail", {
12666
- param: "flag",
12667
- reason: "mail.flag-deleted"
12870
+ /**
12871
+ * Builds multipart/alternative node. It should always contain same type of elements on the same level
12872
+ * eg. text + html view of the same data
12873
+ *
12874
+ * @param parentNode Parent for this note. If it does not exist, a root node is created
12875
+ * @returns MimeNode node element
12876
+ * @internal
12877
+ */
12878
+ _createAlternative(parentNode) {
12879
+ const node = parentNode ? parentNode.createChild("multipart/alternative", {
12880
+ disableUrlAccess: this.mail.disableUrlAccess,
12881
+ disableFileAccess: this.mail.disableFileAccess,
12882
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12883
+ newline: this.mail.newline
12884
+ }) : new mime_node_default("multipart/alternative", {
12885
+ baseBoundary: this.mail.baseBoundary,
12886
+ textEncoding: this.mail.textEncoding,
12887
+ boundaryPrefix: this.mail.boundaryPrefix,
12888
+ disableUrlAccess: this.mail.disableUrlAccess,
12889
+ disableFileAccess: this.mail.disableFileAccess,
12890
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12891
+ newline: this.mail.newline
12668
12892
  });
12669
- if (!KEYWORD.test(word))
12670
- throw new CliError17("validation_error", `"${given}" is no flag: give read, flagged, answered, draft, or a keyword of letters, digits and $._-`, { param: "flag" });
12671
- return word;
12672
- }, "flagOf");
12673
- var folderNamed = /* @__PURE__ */ __name((folders, given) => {
12674
- const word = given.trim();
12675
- return folders.find(({ path: path2 }) => path2 === word) ?? folders.find(({ role }) => role === word.toLowerCase()) ?? folders.find(({ path: path2, name }) => path2.toLowerCase() === word.toLowerCase() || name.toLowerCase() === word.toLowerCase());
12676
- }, "folderNamed");
12677
- var trashOf = /* @__PURE__ */ __name(async (mailbox) => {
12678
- const folders = await mailbox.folders();
12679
- const found2 = folders.find(({ role }) => role === "trash") ?? folders.find(({ path: path2 }) => mailbox.organise.trash.includes(path2));
12680
- if (!found2)
12681
- throw new CliError17("provider_unavailable", "the mailbox has no Trash folder this tool can find, so nothing is deleted; folders list shows the folders", { reason: "mail.no-trash" });
12682
- return found2.path;
12683
- }, "trashOf");
12684
- var allMailOf = /* @__PURE__ */ __name(async (mailbox) => {
12685
- const found2 = (await mailbox.folders()).find(({ role }) => role === "all");
12686
- if (!found2)
12687
- throw new CliError17("provider_unavailable", "Gmail's All Mail folder is not listed", { reason: "mail.no-all-mail" });
12688
- return found2.path;
12689
- }, "allMailOf");
12690
- var targetOf = /* @__PURE__ */ __name(async (mailbox, given, copy) => {
12691
- const folders = await mailbox.folders();
12692
- const found2 = folderNamed(folders, given);
12693
- if (found2?.role === "trash")
12694
- throw new CliError17("validation_error", "moving to Trash is a deletion", {
12695
- param: "folder",
12696
- reason: "mail.move-to-trash"
12893
+ this._alternatives.forEach((alternative) => {
12894
+ if (this._useRelated && this._htmlNode === alternative) {
12895
+ this._createRelated(node);
12896
+ } else {
12897
+ this._createContentNode(node, alternative);
12898
+ }
12697
12899
  });
12698
- if (!mailbox.organise.labels) {
12699
- if (!found2)
12700
- throw new CliError17("not_found", `no folder "${given}"; folders list shows them, folders create makes one`, {
12701
- param: "folder"
12702
- });
12703
- return { kind: "folder", path: found2.path };
12704
- }
12705
- if (found2?.role === "junk")
12706
- return { kind: "folder", path: found2.path };
12707
- if (found2?.role === "inbox")
12708
- return { kind: "labels", add: ["\\Inbox"], remove: [], name: "INBOX" };
12709
- if (found2?.role === "all" || given.trim().toLowerCase() === "archive") {
12710
- if (copy)
12711
- throw new CliError17("validation_error", "on Gmail, all mail is in All Mail already", { param: "folder" });
12712
- return { kind: "labels", add: [], remove: ["\\Inbox"], name: found2?.path ?? "All Mail" };
12713
- }
12714
- if (found2?.role)
12715
- throw new CliError17("validation_error", `on Gmail, ${found2.path} is not a label to move mail to`);
12716
- const name = found2?.path ?? given.trim();
12717
- return { kind: "labels", add: [name], remove: copy ? [] : ["\\Inbox"], name };
12718
- }, "targetOf");
12719
- var storeBox = /* @__PURE__ */ __name((folder) => ({ externalId: folder, name: folder, kind: null }), "storeBox");
12720
- var labelBox = /* @__PURE__ */ __name((raw) => {
12721
- const name = decodedLabelName2(raw);
12722
- return { externalId: `label:${name}`, name, kind: "label" };
12723
- }, "labelBox");
12724
- var Changer = class {
12725
- static {
12726
- __name(this, "Changer");
12727
- }
12728
- mailbox;
12729
- guard;
12730
- log;
12731
- key;
12732
- action;
12733
- writes = [];
12734
- constructor(mailbox, guard, log, key, action) {
12735
- this.mailbox = mailbox;
12736
- this.guard = guard;
12737
- this.log = log;
12738
- this.key = key;
12739
- this.action = action;
12900
+ return node;
12740
12901
  }
12741
- async step(line, act, moved) {
12742
- const request = {
12743
- chatId: null,
12744
- kind: "account",
12745
- action: this.action,
12746
- key: this.key,
12747
- count: line.items.length,
12748
- operationId: newOperationId()
12749
- };
12750
- const step = this.log.begin({ ...line, operation_id: request.operationId });
12751
- const done = await guardedWrite(this.guard, request, act);
12752
- this.log.done(step, line.items.map(({ id }) => id), moved?.(done));
12753
- this.writes.push({
12754
- operation_id: request.operationId,
12755
- op: line.op,
12756
- folder: line.folder,
12757
- ...line.to ? { to: line.to } : {},
12758
- messages: line.items.length,
12759
- ...line.undoes ? { undoes: line.undoes } : {}
12902
+ /**
12903
+ * Builds multipart/related node. It should always contain html node with related attachments
12904
+ *
12905
+ * @param parentNode Parent for this note. If it does not exist, a root node is created
12906
+ * @returns MimeNode node element
12907
+ * @internal
12908
+ */
12909
+ _createRelated(parentNode) {
12910
+ const node = parentNode ? parentNode.createChild('multipart/related; type="text/html"', {
12911
+ disableUrlAccess: this.mail.disableUrlAccess,
12912
+ disableFileAccess: this.mail.disableFileAccess,
12913
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12914
+ newline: this.mail.newline
12915
+ }) : new mime_node_default('multipart/related; type="text/html"', {
12916
+ baseBoundary: this.mail.baseBoundary,
12917
+ textEncoding: this.mail.textEncoding,
12918
+ boundaryPrefix: this.mail.boundaryPrefix,
12919
+ disableUrlAccess: this.mail.disableUrlAccess,
12920
+ disableFileAccess: this.mail.disableFileAccess,
12921
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12922
+ newline: this.mail.newline
12760
12923
  });
12761
- return done;
12762
- }
12763
- };
12764
- var statesOf = /* @__PURE__ */ __name(async (mailbox, { folder, validity, items }) => mailbox.writes.state(folder, validity, items.map(({ uid }) => uid)), "statesOf");
12765
- var groupBy = /* @__PURE__ */ __name((items, keyOf2) => {
12766
- const groups = /* @__PURE__ */ new Map();
12767
- for (const item of items) {
12768
- const group = groups.get(keyOf2(item));
12769
- if (group)
12770
- group.push(item);
12771
- else
12772
- groups.set(keyOf2(item), [item]);
12924
+ this._createContentNode(node, this._htmlNode);
12925
+ this._attachments.related.forEach((alternative) => this._createContentNode(node, alternative));
12926
+ return node;
12773
12927
  }
12774
- return groups;
12775
- }, "groupBy");
12776
- var valuesOf = /* @__PURE__ */ __name((map2, keys) => keys.flatMap((key) => {
12777
- const value = map2.get(key);
12778
- return value === void 0 ? [] : [value];
12779
- }), "valuesOf");
12780
- var byId = /* @__PURE__ */ __name((uids, idOf) => new Map([...uids].flatMap(([uid, value]) => {
12781
- const id = idOf.get(uid);
12782
- return id === void 0 ? [] : [[id, value]];
12783
- })), "byId");
12784
- var flagChanges = /* @__PURE__ */ __name((change2) => ({
12785
- ...change2.add.includes("\\Seen") ? { read: true } : change2.remove.includes("\\Seen") ? { read: false } : {},
12786
- ...change2.add.includes("\\Flagged") ? { flagged: true } : change2.remove.includes("\\Flagged") ? { flagged: false } : {}
12787
- }), "flagChanges");
12788
- var SETTABLE = /* @__PURE__ */ __name((flag2) => flag2 !== "\\Recent" && flag2 !== "\\Deleted", "SETTABLE");
12789
- var changeFlags = /* @__PURE__ */ __name(async (changer, located, change2) => {
12790
- const { mailbox } = changer;
12791
- const changed = [];
12792
- for (const place of located) {
12793
- const states = await statesOf(mailbox, place);
12794
- const items = place.items.flatMap((item) => {
12795
- const state = states.get(item.uid);
12796
- if (!state)
12797
- return [];
12798
- const now = state.flags.filter(SETTABLE);
12799
- const add = change2.add.filter((flag2) => !now.includes(flag2));
12800
- const remove = change2.replace ? now.filter((flag2) => !change2.add.includes(flag2)) : change2.remove.filter((flag2) => now.includes(flag2));
12801
- return add.length || remove.length ? [{ item: { ...item, had: now.filter((f) => remove.includes(f)) }, add, remove }] : [];
12928
+ /**
12929
+ * Creates a regular node with contents
12930
+ *
12931
+ * @param parentNode Parent for this note. If it does not exist, a root node is created
12932
+ * @param element Node data
12933
+ * @returns MimeNode node element
12934
+ * @internal
12935
+ */
12936
+ _createContentNode(parentNode, element) {
12937
+ element = element || {};
12938
+ element.content = element.content || "";
12939
+ const encoding = (element.encoding || "utf8").toString().toLowerCase().replace(/[-_\s]/g, "");
12940
+ const node = parentNode ? parentNode.createChild(element.contentType, {
12941
+ filename: element.filename,
12942
+ textEncoding: this.mail.textEncoding,
12943
+ disableUrlAccess: this.mail.disableUrlAccess,
12944
+ disableFileAccess: this.mail.disableFileAccess,
12945
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12946
+ newline: this.mail.newline
12947
+ }) : new mime_node_default(element.contentType, {
12948
+ filename: element.filename,
12949
+ baseBoundary: this.mail.baseBoundary,
12950
+ textEncoding: this.mail.textEncoding,
12951
+ boundaryPrefix: this.mail.boundaryPrefix,
12952
+ disableUrlAccess: this.mail.disableUrlAccess,
12953
+ disableFileAccess: this.mail.disableFileAccess,
12954
+ normalizeHeaderKey: this.mail.normalizeHeaderKey,
12955
+ newline: this.mail.newline
12802
12956
  });
12803
- for (const group of groupBy(items, ({ add, remove }) => JSON.stringify([add, remove])).values()) {
12804
- const [{ add, remove }] = group;
12805
- const line = {
12806
- op: "flag",
12807
- folder: place.folder,
12808
- validity: place.validity,
12809
- change: { add, remove },
12810
- items: group.map(({ item }) => item)
12811
- };
12812
- await changer.step(line, () => mailbox.writes.flag(place.folder, place.validity, line.items.map(({ uid }) => uid), { add, remove }));
12813
- const flags = flagChanges({ add, remove });
12814
- if (Object.keys(flags).length)
12815
- await mailbox.store.mail.setFlags(mailbox.accountId, new Map(line.items.map(({ id }) => [id, flags])), mailbox.now());
12816
- for (const { id } of line.items)
12817
- changed.push(id);
12957
+ if (element.headers) {
12958
+ node.addHeader(element.headers);
12818
12959
  }
12960
+ if (element.cid) {
12961
+ node.setHeader("Content-Id", "<" + element.cid.replace(/[<>]/g, "") + ">");
12962
+ }
12963
+ if (element.contentTransferEncoding) {
12964
+ node.setHeader("Content-Transfer-Encoding", element.contentTransferEncoding);
12965
+ } else if (this.mail.encoding && /^text\//i.test(element.contentType)) {
12966
+ node.setHeader("Content-Transfer-Encoding", this.mail.encoding);
12967
+ }
12968
+ if (!/^text\//i.test(element.contentType) || element.contentDisposition) {
12969
+ node.setHeader("Content-Disposition", element.contentDisposition || (element.cid && /^image\//i.test(element.contentType) ? "inline" : "attachment"));
12970
+ }
12971
+ if (typeof element.content === "string" && !["utf8", "usascii", "ascii"].includes(encoding)) {
12972
+ element.content = Buffer.from(element.content, encoding);
12973
+ }
12974
+ if (element.raw) {
12975
+ node.setRaw(element.raw);
12976
+ } else {
12977
+ node.setContent(element.content);
12978
+ }
12979
+ return node;
12819
12980
  }
12820
- return changed;
12821
- }, "changeFlags");
12822
- var changeLabels = /* @__PURE__ */ __name(async (changer, place, add, remove) => {
12823
- const { mailbox } = changer;
12824
- const states = await statesOf(mailbox, place);
12825
- const items = place.items.flatMap((item) => {
12826
- const labels = states.get(item.uid)?.labels;
12827
- if (labels === void 0)
12828
- return [];
12829
- const adds = add.filter((label) => !labels.includes(label));
12830
- const removes = remove.filter((label) => labels.includes(label));
12831
- return adds.length || removes.length ? [{ ...item, had: labels.filter((label) => removes.includes(label)) }] : [];
12832
- });
12833
- if (items.length === 0)
12834
- return [];
12835
- const uids = items.map(({ uid }) => uid);
12836
- await changer.step({ op: "label", folder: place.folder, validity: place.validity, change: { add, remove }, items }, () => mailbox.writes.label(place.folder, place.validity, uids, { add, remove }));
12837
- await relabel(mailbox, items.map(({ id }) => id), add, remove);
12838
- return items.map(({ id }) => id);
12839
- }, "changeLabels");
12840
- var relabel = /* @__PURE__ */ __name(async (mailbox, ids, add, remove) => {
12841
- const scanned = [...add, ...remove].map(labelBox);
12842
- const kept = add.map(labelBox).map(({ externalId }) => externalId);
12843
- if (scanned.length === 0)
12844
- return;
12845
- await mailbox.store.mail.setMailboxes(mailbox.accountId, scanned, new Map(ids.map((id) => [id, kept])), mailbox.now());
12846
- }, "relabel");
12847
- var moveFolder = /* @__PURE__ */ __name(async (changer, place, to, op) => {
12848
- const { mailbox } = changer;
12849
- const states = await statesOf(mailbox, place);
12850
- const items = place.items.flatMap((item) => {
12851
- const state = states.get(item.uid);
12852
- return state ? [{ ...item, ...state.messageId ? { mid: state.messageId } : {} }] : [];
12853
- });
12854
- if (items.length === 0)
12855
- return [];
12856
- const uids = items.map(({ uid }) => uid);
12857
- const idOf = new Map(items.map(({ id, uid }) => [uid, id]));
12858
- const moved = await changer.step({ op, folder: place.folder, validity: place.validity, to, items }, () => (op === "move" ? mailbox.writes.move : mailbox.writes.copy)(place.folder, place.validity, uids, to), (done) => ({
12859
- uids: byId(done.uids, idOf),
12860
- ...done.validity ? { validity: done.validity } : {}
12861
- }));
12862
- const ids = items.map(({ id }) => id);
12863
- const now = mailbox.now();
12864
- await mailbox.store.mail.setMailboxes(mailbox.accountId, op === "move" ? [storeBox(place.folder), storeBox(to)] : [storeBox(to)], new Map(ids.map((id) => [id, [to]])), now);
12865
- if (op === "move")
12866
- await mailbox.store.mail.forgetLocations(mailbox.accountId, place.folder, place.validity, uids);
12867
- if (moved.validity && moved.uids.size)
12868
- await mailbox.store.mail.setLocations(mailbox.accountId, to, moved.validity, new Map([...byId(moved.uids, idOf)].map(([id, uid]) => [id, [uid]])));
12869
- return ids;
12870
- }, "moveFolder");
12871
- var moveMessages = /* @__PURE__ */ __name(async (changer, located, target, op) => {
12872
- const changed = [];
12873
- for (const place of located) {
12874
- const ids = target.kind === "labels" ? await changeLabels(changer, place, target.add, target.remove) : await moveFolder(changer, place, target.path, op);
12875
- for (const id of ids)
12876
- changed.push(id);
12877
- }
12878
- return changed;
12879
- }, "moveMessages");
12880
- var trashMessages = /* @__PURE__ */ __name(async (changer, located, trash, keep = () => void 0) => {
12881
- const { mailbox } = changer;
12882
- const changed = [];
12883
- const kept = {};
12884
- for (const place of located) {
12885
- const states = await statesOf(mailbox, place);
12886
- const items = place.items.flatMap((item) => {
12887
- const state = states.get(item.uid);
12888
- if (!state)
12889
- return [];
12890
- const reason = keep(item.id, state);
12891
- if (reason !== void 0) {
12892
- kept[reason] = (kept[reason] ?? 0) + 1;
12893
- return [];
12981
+ /**
12982
+ * Parses data uri and converts it to a Buffer
12983
+ *
12984
+ * @param element Content element
12985
+ * @return Parsed element
12986
+ * @internal
12987
+ */
12988
+ _processDataUrl(element) {
12989
+ const dataUrl = element.path || element.href;
12990
+ if (!dataUrl || typeof dataUrl !== "string") {
12991
+ return element;
12992
+ }
12993
+ if (!dataUrl.startsWith("data:")) {
12994
+ return element;
12995
+ }
12996
+ if (dataUrl.length > 52428800) {
12997
+ let detectedType = "application/octet-stream";
12998
+ const commaPos = dataUrl.indexOf(",");
12999
+ if (commaPos > 0 && commaPos < 200) {
13000
+ const header2 = dataUrl.substring(5, commaPos);
13001
+ const parts = header2.split(";");
13002
+ if (parts[0] && parts[0].includes("/")) {
13003
+ detectedType = parts[0].trim();
13004
+ }
12894
13005
  }
12895
- return [
13006
+ return Object.assign(copyOwnKeys({}, element), {
13007
+ path: false,
13008
+ href: false,
13009
+ content: Buffer.alloc(0),
13010
+ contentType: element.contentType || detectedType
13011
+ });
13012
+ }
13013
+ let parsedDataUri;
13014
+ try {
13015
+ parsedDataUri = parseDataURI(dataUrl);
13016
+ } catch (_err) {
13017
+ return element;
13018
+ }
13019
+ if (!parsedDataUri) {
13020
+ return element;
13021
+ }
13022
+ element.content = parsedDataUri.data;
13023
+ element.contentType = element.contentType || parsedDataUri.contentType;
13024
+ if ("path" in element) {
13025
+ element.path = false;
13026
+ }
13027
+ if ("href" in element) {
13028
+ element.href = false;
13029
+ }
13030
+ return element;
13031
+ }
13032
+ };
13033
+ var mail_composer_default = MailComposer;
13034
+
13035
+ // dist/mail/compose.js
13036
+ var EMAIL = /^[^\s@<>()",;:]+@[^\s@<>()",;:]+\.[^\s@<>()",;:]+$/u;
13037
+ var peopleOf = /* @__PURE__ */ __name((given, flag2) => given.flatMap((one) => addressparser_default(one, { flatten: true }).map(({ name, address }) => {
13038
+ const clean = address.trim().toLowerCase();
13039
+ if (!EMAIL.test(clean))
13040
+ throw new CliError18("validation_error", `${flag2} takes email addresses; ${JSON.stringify(one)} holds none`, {
13041
+ param: flag2.replace(/^--/, "")
13042
+ });
13043
+ return { address: clean, ...name.trim() ? { name: name.trim() } : {} };
13044
+ })), "peopleOf");
13045
+ var unique = /* @__PURE__ */ __name((people, without = /* @__PURE__ */ new Set()) => {
13046
+ const seen = new Set(without);
13047
+ return people.filter(({ address }) => !seen.has(address) && seen.add(address) !== void 0);
13048
+ }, "unique");
13049
+ var personOf = /* @__PURE__ */ __name(({ email: email2, name }) => ({ address: email2, ...name ? { name } : {} }), "personOf");
13050
+ var originalOf = /* @__PURE__ */ __name(async (raw) => {
13051
+ let mail;
13052
+ try {
13053
+ mail = await parseMail(raw, void 0, 0);
13054
+ } catch {
13055
+ throw new CliError18("invalid_response", "the original message on the server cannot be read");
13056
+ }
13057
+ return {
13058
+ ...mail.messageId ? { messageId: mail.messageId } : {},
13059
+ references: mail.references,
13060
+ subject: mail.subject ?? "",
13061
+ ...mail.date ? { date: mail.date } : {},
13062
+ ...mail.from ? { from: personOf(mail.from) } : {},
13063
+ replyTo: mail.replyTo.map(personOf),
13064
+ to: mail.to.map(personOf),
13065
+ cc: mail.cc.map(personOf),
13066
+ text: mail.text
13067
+ };
13068
+ }, "originalOf");
13069
+ var replyPeople = /* @__PURE__ */ __name((original, owner, all) => {
13070
+ const mine = original.from !== void 0 && owner.has(original.from.address);
13071
+ const first = mine ? original.to : original.replyTo.length ? original.replyTo : original.from ? [original.from] : [];
13072
+ return unique([...first, ...all ? [...original.to, ...original.cc] : []], owner);
13073
+ }, "replyPeople");
13074
+ var replyCopies = /* @__PURE__ */ __name((original, owner, to) => unique([...original.to, ...original.cc], /* @__PURE__ */ new Set([...owner, ...to.map(({ address }) => address)])), "replyCopies");
13075
+ var prefixed = /* @__PURE__ */ __name((subject, prefix, already) => already.test(subject.trim()) ? subject.trim() : `${prefix} ${subject.trim()}`.trim(), "prefixed");
13076
+ var replySubject = /* @__PURE__ */ __name((subject) => prefixed(subject, "Re:", /^(re|ha|aw|sv)\s*:/iu), "replySubject");
13077
+ var forwardSubject = /* @__PURE__ */ __name((subject) => prefixed(subject, "Fwd:", /^(fwd?|fw)\s*:/iu), "forwardSubject");
13078
+ var referencesOf = /* @__PURE__ */ __name((original) => [...original.references, ...original.messageId ? [original.messageId] : []].slice(-20), "referencesOf");
13079
+ var shown = /* @__PURE__ */ __name((person) => person === void 0 ? "someone" : person.name ? `${person.name} <${person.address}>` : person.address, "shown");
13080
+ var quoted2 = /* @__PURE__ */ __name((text3, original) => {
13081
+ const when = original.date ? `On ${original.date}, ` : "";
13082
+ const lines = original.text.split("\n").map((line) => line.startsWith(">") ? `>${line}` : `> ${line}`);
13083
+ return `${text3.trimEnd()}
13084
+
13085
+ ${when}${shown(original.from)} wrote:
13086
+ ${lines.join("\n")}
13087
+ `;
13088
+ }, "quoted");
13089
+ var header = /* @__PURE__ */ __name((person) => person.name ? { name: person.name, address: person.address } : person.address, "header");
13090
+ var build = /* @__PURE__ */ __name(async (draft) => {
13091
+ const options = {
13092
+ from: header(draft.from),
13093
+ to: draft.to.map(header),
13094
+ ...draft.cc.length ? { cc: draft.cc.map(header) } : {},
13095
+ ...draft.bcc.length ? { bcc: draft.bcc.map(header) } : {},
13096
+ subject: draft.subject,
13097
+ text: draft.text,
13098
+ ...draft.html === void 0 ? {} : { html: draft.html },
13099
+ messageId: draft.messageId,
13100
+ date: draft.date,
13101
+ ...draft.inReplyTo ? { inReplyTo: draft.inReplyTo } : {},
13102
+ ...draft.references?.length ? { references: draft.references } : {},
13103
+ attachments: [
13104
+ ...draft.files.map(({ name, path: path2 }) => ({ filename: name, path: path2 })),
13105
+ ...(draft.parts ?? []).map(({ name, mime, bytes }) => ({
13106
+ filename: name,
13107
+ content: Buffer.from(bytes),
13108
+ ...mime ? { contentType: mime } : {}
13109
+ })),
13110
+ ...draft.message ? [
12896
13111
  {
12897
- ...item,
12898
- ...state.labels ? { labels: state.labels } : {},
12899
- ...state.messageId ? { mid: state.messageId } : {}
13112
+ filename: draft.message.name,
13113
+ content: Buffer.from(draft.message.raw),
13114
+ contentType: "message/rfc822",
13115
+ contentDisposition: "attachment"
12900
13116
  }
12901
- ];
12902
- });
12903
- if (items.length === 0)
12904
- continue;
12905
- const idOf = new Map(items.map(({ id, uid }) => [uid, id]));
12906
- await changer.step({ op: "trash", folder: place.folder, validity: place.validity, to: trash, items }, () => mailbox.writes.move(place.folder, place.validity, items.map(({ uid }) => uid), trash), (done) => ({
12907
- uids: byId(done.uids, idOf),
12908
- ...done.validity ? { validity: done.validity } : {}
12909
- }));
12910
- const ids = items.map(({ id }) => id);
12911
- await mailbox.store.mail.markDeleted(mailbox.accountId, ids, mailbox.now());
12912
- for (const id of ids)
12913
- changed.push(id);
12914
- }
12915
- return { changed, kept };
12916
- }, "trashMessages");
13117
+ ] : []
13118
+ ],
13119
+ disableUrlAccess: true,
13120
+ newline: "\r\n"
13121
+ };
13122
+ const sent = new mail_composer_default(options).compile();
13123
+ const copy = new mail_composer_default(options).compile();
13124
+ copy.keepBcc = true;
13125
+ return { raw: new Uint8Array(await sent.build()), copy: new Uint8Array(await copy.build()) };
13126
+ }, "build");
13127
+ var messageIdFor = /* @__PURE__ */ __name((operationId, from) => `<${operationId.replace(/[^\w.-]/g, "")}@${from.split("@")[1] ?? "localhost"}>`, "messageIdFor");
13128
+ var forgotAttachment = /* @__PURE__ */ __name((text3, attached) => !attached && /\battach(ed|ment|ing)?\b|влож(ени|ил|ен)|прилага|прикреп/iu.test(text3), "forgotAttachment");
12917
13129
 
12918
13130
  // dist/mail/locate.js
13131
+ import { CliError as CliError19 } from "@wirecat/cli-base";
13132
+ import { parseReference } from "@wirecat/cli-core";
13133
+ import { searchMail } from "@wirecat/cli-core/mail";
12919
13134
  var PAGE = 100;
12920
13135
  var selectIds = /* @__PURE__ */ __name(async (mailbox, { refs = [], filter, limit = FILTER_LIMIT }) => {
12921
13136
  if (refs.length === 0 && filter === void 0)
12922
- throw new CliError18("validation_error", "name the messages", { reason: "mail.no-selection" });
13137
+ throw new CliError19("validation_error", "name the messages", { reason: "mail.no-selection" });
12923
13138
  if (refs.length > 0 && filter !== void 0)
12924
- throw new CliError18("validation_error", "give message references or a query, not both", {
13139
+ throw new CliError19("validation_error", "give message references or a query, not both", {
12925
13140
  param: "filter",
12926
13141
  reason: "mail.refs-and-filter"
12927
13142
  });
@@ -12929,9 +13144,9 @@ var selectIds = /* @__PURE__ */ __name(async (mailbox, { refs = [], filter, limi
12929
13144
  for (const ref of refs) {
12930
13145
  const place = parseReference(ref);
12931
13146
  if (place.type !== "message")
12932
- throw new CliError18("validation_error", `${ref} names no email \u2014 give the msg:email/\u2026 reference search shows`);
13147
+ throw new CliError19("validation_error", `${ref} names no email \u2014 give the msg:email/\u2026 reference search shows`);
12933
13148
  if (place.provider !== mailbox.key.provider || place.account !== mailbox.key.account)
12934
- throw new CliError18("not_found", `${ref} is not mail of this profile's mailbox ${mailbox.key.account}`);
13149
+ throw new CliError19("not_found", `${ref} is not mail of this profile's mailbox ${mailbox.key.account}`);
12935
13150
  ids.add(place.message);
12936
13151
  }
12937
13152
  if (filter === void 0)
@@ -13016,12 +13231,12 @@ var fetchOriginal = /* @__PURE__ */ __name(async (mailbox, backend, ref) => {
13016
13231
  const place = located[0];
13017
13232
  const item = place?.items[0];
13018
13233
  if (!place || !item)
13019
- throw new CliError19("not_found", `${ref} is not on the server any more, or not where the store last saw it`, {
13234
+ throw new CliError20("not_found", `${ref} is not on the server any more, or not where the store last saw it`, {
13020
13235
  reason: "mail.original-gone"
13021
13236
  });
13022
13237
  const [raw] = await backend.fetchRaw([{ uid: String(item.uid), folder: place.folder, receivedAt: "" }]);
13023
13238
  if (!(raw instanceof Uint8Array))
13024
- throw new CliError19("provider_error", "the server did not give the original message");
13239
+ throw new CliError20("provider_error", "the server did not give the original message");
13025
13240
  return { folder: place.folder, validity: place.validity, uid: item.uid, raw };
13026
13241
  }, "fetchOriginal");
13027
13242
  var sentFolder = /* @__PURE__ */ __name(async (mailbox) => (await mailbox.folders()).find(({ role }) => role === "sent")?.path, "sentFolder");
@@ -13089,10 +13304,10 @@ var markOriginal = /* @__PURE__ */ __name(async (sending2, original, flag2) => {
13089
13304
  action: "message-flag",
13090
13305
  key: "messages.update",
13091
13306
  count: 1,
13092
- operationId: newOperationId2()
13307
+ operationId: newOperationId3()
13093
13308
  };
13094
13309
  try {
13095
- await guardedWrite2(sending2.guard, request, () => sending2.mailbox.writes.flag(original.folder, original.validity, [original.uid], { add: [flag2] }));
13310
+ await guardedWrite3(sending2.guard, request, () => sending2.mailbox.writes.flag(original.folder, original.validity, [original.uid], { add: [flag2] }));
13096
13311
  return true;
13097
13312
  } catch {
13098
13313
  sending2.warn(`the message was sent; the original was not marked ${flag2}`);
@@ -13121,14 +13336,14 @@ var sendOut = /* @__PURE__ */ __name(async (sending2, outgoing) => {
13121
13336
  const probe = { chatId: null, kind: "read", key: SEND_OTHERS_KEY };
13122
13337
  try {
13123
13338
  if (sending2.agentWithoutOthers)
13124
- throw new CliError19("permission_error", `over MCP, profile ${sending2.profile} mails only its owner: permissions.${SEND_OTHERS_KEY} is readonly for an agent until the owner sets it in the config`, { permission: SEND_OTHERS_KEY, reason: "mail.others-for-agent" });
13339
+ throw new CliError20("permission_error", `over MCP, profile ${sending2.profile} mails only its owner: permissions.${SEND_OTHERS_KEY} is readonly for an agent until the owner sets it in the config`, { permission: SEND_OTHERS_KEY, reason: "mail.others-for-agent" });
13125
13340
  await sending2.guard.ask?.(probe);
13126
13341
  sending2.guard.check(probe, { reserve: false });
13127
13342
  } catch (error2) {
13128
13343
  sending2.guard.record({
13129
13344
  ...attempt,
13130
13345
  outcome: "refused",
13131
- errorCode: error2 instanceof CliError19 ? error2.code : "unknown"
13346
+ errorCode: error2 instanceof CliError20 ? error2.code : "unknown"
13132
13347
  });
13133
13348
  throw error2;
13134
13349
  }
@@ -13146,11 +13361,11 @@ var sendOut = /* @__PURE__ */ __name(async (sending2, outgoing) => {
13146
13361
  };
13147
13362
  const submit = sending2.backend.submit;
13148
13363
  if (!submit)
13149
- throw new CliError19("configuration_error", `profile ${sending2.profile} names no submission server; set smtp_host, smtp_port and smtp_security`, { sent: false, reason: "mail.no-submission" });
13364
+ throw new CliError20("configuration_error", `profile ${sending2.profile} names no submission server; set smtp_host, smtp_port and smtp_security`, { sent: false, reason: "mail.no-submission" });
13150
13365
  const { raw, copy } = await build(draft);
13151
13366
  const clock = sending2.clock ?? REAL_CLOCK;
13152
13367
  const pacer = new Pacer(pacePathFor(IDENTITY, sending2.profile, sending2.env), DEFAULT_PACE, clock.now);
13153
- const submitted = await guardedWrite2(sending2.guard, attempt, () => submit.send({ from: draft.from.address, recipients: recipients2.map(({ address }) => address), raw }), () => ({}), async () => {
13368
+ const submitted = await guardedWrite3(sending2.guard, attempt, () => submit.send({ from: draft.from.address, recipients: recipients2.map(({ address }) => address), raw }), () => ({}), async () => {
13154
13369
  const at = await pacer.reserve();
13155
13370
  const now = clock.now();
13156
13371
  if (at > now)
@@ -13172,8 +13387,8 @@ var sendOut = /* @__PURE__ */ __name(async (sending2, outgoing) => {
13172
13387
  }, "sendOut");
13173
13388
 
13174
13389
  // dist/commands/organising.js
13175
- import { CliError as CliError20 } from "@wirecat/cli-base";
13176
- import { baseContext as baseContext3, currentRun, guardFor, itemOf as itemOf3, outputFor as outputFor3, renderAnswer as renderAnswer2, terminalAsker } from "@wirecat/cli-core";
13390
+ import { CliError as CliError21 } from "@wirecat/cli-base";
13391
+ import { baseContext as baseContext4, currentRun, guardFor as guardFor2, itemOf as itemOf4, outputFor as outputFor4, renderAnswer as renderAnswer3, terminalAsker as terminalAsker2 } from "@wirecat/cli-core";
13177
13392
  var BULK_KEY = "messages.bulk";
13178
13393
  var writeSchema = strictObject({
13179
13394
  operation_id: string(),
@@ -13202,7 +13417,7 @@ var mailChange = looseObject({
13202
13417
  });
13203
13418
  var limitOf = /* @__PURE__ */ __name((value) => {
13204
13419
  if (!/^\d+$/.test(value.trim()) || Number(value) < 1 || Number(value) > MAX_LIMIT)
13205
- throw new CliError20("validation_error", `--limit takes a whole number from 1 to ${MAX_LIMIT}`, { param: "limit" });
13420
+ throw new CliError21("validation_error", `--limit takes a whole number from 1 to ${MAX_LIMIT}`, { param: "limit" });
13206
13421
  return Number(value);
13207
13422
  }, "limitOf");
13208
13423
  var askingOnce = /* @__PURE__ */ __name((ask2) => {
@@ -13229,22 +13444,22 @@ var commandLine = /* @__PURE__ */ __name((command, profile) => {
13229
13444
  return { path: path2.join(" "), line: `${IDENTITY.command} ${profile} ${path2.join(" ")}` };
13230
13445
  }, "commandLine");
13231
13446
  var stringsOf = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.filter((one) => typeof one === "string") : [], "stringsOf");
13232
- var closedAfterSending = /* @__PURE__ */ __name((operationId, error2) => new CliError20("outcome_unknown", `the message was probably sent, but the store did not close (${error2 instanceof Error ? error2.message : String(error2)}); repeat the command with --operation-id ${operationId}: it looks in Sent first and does not send it twice`, { operation_id: operationId, retryable: false }), "closedAfterSending");
13447
+ var closedAfterSending = /* @__PURE__ */ __name((operationId, error2) => new CliError21("outcome_unknown", `the message was probably sent, but the store did not close (${error2 instanceof Error ? error2.message : String(error2)}); repeat the command with --operation-id ${operationId}: it looks in Sent first and does not send it twice`, { operation_id: operationId, retryable: false }), "closedAfterSending");
13233
13448
  var organising = /* @__PURE__ */ __name(async (command, work) => {
13234
13449
  const context = contextOf(command);
13235
13450
  refuseOffline(context.flags);
13236
13451
  const address = context.settings.mailbox.address;
13237
13452
  if (!address)
13238
- throw new CliError20("configuration_error", `profile ${context.profile} has no address`);
13453
+ throw new CliError21("configuration_error", `profile ${context.profile} has no address`);
13239
13454
  const { backend } = await openMail(context);
13240
13455
  let shown4;
13241
13456
  let sent;
13242
13457
  let result;
13243
13458
  try {
13244
- result = await worded(context.profile, () => baseContext3(command, configuration.resolveSettings).run(async () => {
13459
+ result = await worded(context.profile, () => baseContext4(command, configuration.resolveSettings).run(async () => {
13245
13460
  const writes = backend.writes;
13246
13461
  if (!writes)
13247
- throw new CliError20("provider_unavailable", "this mailbox cannot be changed from here");
13462
+ throw new CliError21("provider_unavailable", "this mailbox cannot be changed from here");
13248
13463
  const store = await openMailStore(context.env);
13249
13464
  context.environment.trackCloseable?.(store);
13250
13465
  let worked = false;
@@ -13252,7 +13467,7 @@ var organising = /* @__PURE__ */ __name(async (command, work) => {
13252
13467
  const key = { provider: "email", account: address.toLowerCase() };
13253
13468
  const stored = await store.accounts.storedAccount(key).catch(() => null);
13254
13469
  if (stored === null)
13255
- throw new CliError20("not_found", `no mail of ${address} is stored yet; run \`${IDENTITY.command} ${context.profile} sync\` first`);
13470
+ throw new CliError21("not_found", `no mail of ${address} is stored yet; run \`${IDENTITY.command} ${context.profile} sync\` first`);
13256
13471
  let folders;
13257
13472
  const mailbox = {
13258
13473
  app: IDENTITY,
@@ -13267,8 +13482,8 @@ var organising = /* @__PURE__ */ __name(async (command, work) => {
13267
13482
  organise: providerFor(address, context.settings.mailbox.host)?.organise ?? DEFAULT_ORGANISE,
13268
13483
  now: Date.now
13269
13484
  };
13270
- const { settings } = baseContext3(command, configuration.resolveSettings);
13271
- const guard = guardFor(IDENTITY, { ...settings, permissionDefaults: configuration.permissions?.defaults ?? {} }, (message) => outputFor3(command).renderer.warn(message), context.env, askingOnce(askedByMailFlags(command, terminalAsker(command))));
13485
+ const { settings } = baseContext4(command, configuration.resolveSettings);
13486
+ const guard = guardFor2(IDENTITY, { ...settings, permissionDefaults: configuration.permissions?.defaults ?? {} }, (message) => outputFor4(command).renderer.warn(message), context.env, askingOnce(askedByMailFlags(command, terminalAsker2(command))));
13272
13487
  const { path: path2, line } = commandLine(command, context.profile);
13273
13488
  const done = await work({
13274
13489
  mailbox,
@@ -13339,7 +13554,7 @@ var answerChange = /* @__PURE__ */ __name((command, opened, plan, outcome, given
13339
13554
  safe_to_auto_execute: false
13340
13555
  }
13341
13556
  ] : [];
13342
- opened.answer(() => renderAnswer2(command, outputFor3(command), itemOf3({
13557
+ opened.answer(() => renderAnswer3(command, outputFor4(command), itemOf4({
13343
13558
  action: plan.action,
13344
13559
  applied: outcome !== null,
13345
13560
  run_id: outcome?.run ?? null,
@@ -13390,23 +13605,23 @@ var attachmentsOf = /* @__PURE__ */ __name(async (opened, reference) => {
13390
13605
  content: one.bytes ?? new Uint8Array()
13391
13606
  }));
13392
13607
  }, "attachmentsOf");
13393
- var listCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new Command3("list"), {
13394
- effects: REMOTE_READ2,
13608
+ var listCommand2 = /* @__PURE__ */ __name(() => answerEntity4(annotate4(new Command4("list"), {
13609
+ effects: REMOTE_READ3,
13395
13610
  examples: [`${IDENTITY.command} personal attachments list ${REF_EXAMPLE}`]
13396
13611
  }), "mail_attachment", attachment).summary("the files attached to one email, read from the server").description("the attachments of one stored email, numbered as attachments download takes them; reads the message from the server").argument("<message>", "the msg:email/\u2026 reference search messages shows").action(async function(reference) {
13397
13612
  const found2 = await organising(this, (opened) => attachmentsOf(opened, reference));
13398
13613
  const items = found2.map(({ content: _, ...one }) => one);
13399
- renderAnswer3(this, outputFor4(this), listOf("attachments list", { items, limit: Math.max(1, items.length), has_more: false }), () => items.length ? items.map(({ number: number2, name, bytes }) => `${number2} ${name} ${bytes} bytes
13614
+ renderAnswer4(this, outputFor5(this), listOf2("attachments list", { items, limit: Math.max(1, items.length), has_more: false }), () => items.length ? items.map(({ number: number2, name, bytes }) => `${number2} ${name} ${bytes} bytes
13400
13615
  `).join("") : "no attachments\n");
13401
13616
  }), "listCommand");
13402
13617
  var numbersOf = /* @__PURE__ */ __name((given) => given.map((value) => {
13403
13618
  if (!/^\d+$/.test(value.trim()) || Number(value) < 1)
13404
- throw new CliError21("validation_error", "an attachment is given by its number in attachments list", {
13619
+ throw new CliError22("validation_error", "an attachment is given by its number in attachments list", {
13405
13620
  param: "attachment"
13406
13621
  });
13407
13622
  return Number(value);
13408
13623
  }), "numbersOf");
13409
- var downloadCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new Command3("download"), {
13624
+ var downloadCommand = /* @__PURE__ */ __name(() => answerEntity4(annotate4(new Command4("download"), {
13410
13625
  effects: FETCH2,
13411
13626
  examples: [
13412
13627
  `${IDENTITY.command} personal attachments download ${REF_EXAMPLE} --output-dir ./invoices`,
@@ -13416,12 +13631,12 @@ var downloadCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new C
13416
13631
  const numbers = numbersOf(given);
13417
13632
  const folder = resolve3(flags.outputDir);
13418
13633
  if (refusedPlace(folder, IDENTITY, contextOf(this).env))
13419
- throw new CliError21("validation_error", `will not save into ${flags.outputDir}: credential folders and the WireCat apps' folders are not written to`, { param: "output-dir" });
13634
+ throw new CliError22("validation_error", `will not save into ${flags.outputDir}: credential folders and the WireCat apps' folders are not written to`, { param: "output-dir" });
13420
13635
  const found2 = await organising(this, (opened) => attachmentsOf(opened, reference));
13421
13636
  const wanted = numbers.length ? found2.filter(({ number: number2 }) => numbers.includes(number2)) : found2;
13422
13637
  const missing = numbers.filter((number2) => !found2.some((one) => one.number === number2));
13423
13638
  if (missing.length)
13424
- throw new CliError21("not_found", `the message has no attachment ${missing.join(", ")}; it has ${found2.length}`, {
13639
+ throw new CliError22("not_found", `the message has no attachment ${missing.join(", ")}; it has ${found2.length}`, {
13425
13640
  param: "attachment"
13426
13641
  });
13427
13642
  const files = wanted.map((one) => ({ ...one, path: resolve3(folder, one.name) }));
@@ -13432,10 +13647,10 @@ var downloadCommand = /* @__PURE__ */ __name(() => answerEntity3(annotate3(new C
13432
13647
  for (const { path: path2, content } of files)
13433
13648
  await savePrivately(path2, content, flags.replace === true);
13434
13649
  });
13435
- renderAnswer3(this, outputFor4(this), itemOf4({ folder, files: files.map(({ number: number2, name, path: path2, bytes }) => ({ number: number2, name, path: path2, bytes })) }), () => files.length ? files.map(({ path: path2, bytes }) => `${path2} ${bytes} bytes
13650
+ renderAnswer4(this, outputFor5(this), itemOf5({ folder, files: files.map(({ number: number2, name, path: path2, bytes }) => ({ number: number2, name, path: path2, bytes })) }), () => files.length ? files.map(({ path: path2, bytes }) => `${path2} ${bytes} bytes
13436
13651
  `).join("") : "no attachments\n");
13437
13652
  }), "downloadCommand");
13438
- var attachmentsCommand = /* @__PURE__ */ __name(() => new Command3("attachments").summary("list and save the files attached to an email").addCommand(listCommand()).addCommand(downloadCommand()), "attachmentsCommand");
13653
+ var attachmentsCommand = /* @__PURE__ */ __name(() => new Command4("attachments").summary("list and save the files attached to an email").addCommand(listCommand2()).addCommand(downloadCommand()), "attachmentsCommand");
13439
13654
 
13440
13655
  // dist/commands/doctor.js
13441
13656
  import { oauthClientReport } from "@wirecat/cli-core";
@@ -13522,25 +13737,25 @@ var localChecks = /* @__PURE__ */ __name((env) => {
13522
13737
 
13523
13738
  // dist/commands/drafts.js
13524
13739
  import { randomUUID } from "node:crypto";
13525
- import { CliError as CliError24 } from "@wirecat/cli-base";
13526
- import { annotate as annotate6 } from "@wirecat/cli-base/commands";
13527
- import { answerEntity as answerEntity6, bufferedInput as bufferedInput2, environmentOf as environmentOf4, guardedWrite as guardedWrite4, itemOf as itemOf6, LOCAL_READ as LOCAL_READ2, listOf as listOf2, newOperationId as newOperationId5, outputFor as outputFor7, ownerOnlyOption as ownerOnlyOption2, REMOTE_READ as REMOTE_READ3, REMOTE_WRITE as REMOTE_WRITE3, renderAnswer as renderAnswer5 } from "@wirecat/cli-core";
13528
- import { Command as Command6 } from "commander";
13740
+ import { CliError as CliError25 } from "@wirecat/cli-base";
13741
+ import { annotate as annotate7 } from "@wirecat/cli-base/commands";
13742
+ import { answerEntity as answerEntity7, bufferedInput as bufferedInput2, environmentOf as environmentOf4, guardedWrite as guardedWrite5, itemOf as itemOf7, LOCAL_READ as LOCAL_READ3, listOf as listOf3, newOperationId as newOperationId6, outputFor as outputFor8, ownerOnlyOption as ownerOnlyOption3, REMOTE_READ as REMOTE_READ4, REMOTE_WRITE as REMOTE_WRITE4, renderAnswer as renderAnswer6 } from "@wirecat/cli-core";
13743
+ import { Command as Command7 } from "commander";
13529
13744
 
13530
13745
  // dist/mail/drafts.js
13531
- import { CliError as CliError22 } from "@wirecat/cli-base";
13746
+ import { CliError as CliError23 } from "@wirecat/cli-base";
13532
13747
  import { parseMail as parseMail3 } from "@wirecat/cli-core/mail";
13533
13748
  var DRAFT_FLAGS = ["\\Draft", "\\Seen"];
13534
13749
  var draftsFolderOf = /* @__PURE__ */ __name((folders, organise) => {
13535
13750
  const found2 = folders.find(({ role }) => role === "drafts") ?? folders.find(({ path: path2 }) => organise.drafts.includes(path2));
13536
13751
  if (!found2)
13537
- throw new CliError22("provider_unavailable", "the mailbox has no Drafts folder this tool can find; folders list shows the folders", { reason: "mail.no-drafts" });
13752
+ throw new CliError23("provider_unavailable", "the mailbox has no Drafts folder this tool can find; folders list shows the folders", { reason: "mail.no-drafts" });
13538
13753
  return found2.path;
13539
13754
  }, "draftsFolderOf");
13540
13755
  var draftIdOf = /* @__PURE__ */ __name((given) => {
13541
13756
  const bare = given.trim().replace(/^<|>$/g, "");
13542
13757
  if (!/^[^\s<>]+@[^\s<>]+$/.test(bare))
13543
- throw new CliError22("validation_error", `"${given}" is no draft id \u2014 drafts list shows them`, { param: "draft" });
13758
+ throw new CliError23("validation_error", `"${given}" is no draft id \u2014 drafts list shows them`, { param: "draft" });
13544
13759
  return `<${bare}>`;
13545
13760
  }, "draftIdOf");
13546
13761
  var dateOf = /* @__PURE__ */ __name((raw) => {
@@ -13581,7 +13796,7 @@ var rawOf = /* @__PURE__ */ __name(async (backend, folder, uids) => {
13581
13796
  }, "rawOf");
13582
13797
  var listDrafts = /* @__PURE__ */ __name(async (backend, folder, limit) => {
13583
13798
  if (!backend.search)
13584
- throw new CliError22("provider_unavailable", "this mailbox cannot list a folder");
13799
+ throw new CliError23("provider_unavailable", "this mailbox cannot list a folder");
13585
13800
  const { uids } = await backend.search(/* @__PURE__ */ new Date(0), folder);
13586
13801
  const newest = uids.map(Number).sort((a, b) => b - a).slice(0, limit);
13587
13802
  const raws = newest.length ? await rawOf(backend, folder, newest) : [];
@@ -13591,16 +13806,16 @@ var listDrafts = /* @__PURE__ */ __name(async (backend, folder, limit) => {
13591
13806
  var findDraft = /* @__PURE__ */ __name(async (backend, folder, id) => {
13592
13807
  const writes = backend.writes;
13593
13808
  if (!writes)
13594
- throw new CliError22("provider_unavailable", "this mailbox cannot be changed from here");
13809
+ throw new CliError23("provider_unavailable", "this mailbox cannot be changed from here");
13595
13810
  const { validity, uids } = await writes.locate(folder, { messageIds: [id] });
13596
13811
  const uid = uids.get(id);
13597
13812
  if (uid === void 0)
13598
- throw new CliError22("not_found", `no draft ${id.replace(/^<|>$/g, "")} in ${folder}; drafts list shows them`, {
13813
+ throw new CliError23("not_found", `no draft ${id.replace(/^<|>$/g, "")} in ${folder}; drafts list shows them`, {
13599
13814
  reason: "mail.draft-unknown"
13600
13815
  });
13601
13816
  const [raw] = await rawOf(backend, folder, [uid]);
13602
13817
  if (!raw)
13603
- throw new CliError22("not_found", `email ${uid} was not returned`, { reason: "mail.not-returned" });
13818
+ throw new CliError23("not_found", `email ${uid} was not returned`, { reason: "mail.not-returned" });
13604
13819
  return { uid, validity, read: await readDraft(raw, uid) };
13605
13820
  }, "findDraft");
13606
13821
  var nextVersion = /* @__PURE__ */ __name(({ draft, references, parts }, given, owner) => {
@@ -13622,16 +13837,16 @@ var nextVersion = /* @__PURE__ */ __name(({ draft, references, parts }, given, o
13622
13837
  }, "nextVersion");
13623
13838
 
13624
13839
  // dist/commands/drafts-send.js
13625
- import { annotate as annotate5 } from "@wirecat/cli-base/commands";
13626
- import { answerEntity as answerEntity5, guardedWrite as guardedWrite3, newOperationId as newOperationId4, outputFor as outputFor6, REMOTE_WRITE as REMOTE_WRITE2 } from "@wirecat/cli-core";
13627
- import { Command as Command5 } from "commander";
13840
+ import { annotate as annotate6 } from "@wirecat/cli-base/commands";
13841
+ import { answerEntity as answerEntity6, guardedWrite as guardedWrite4, newOperationId as newOperationId5, outputFor as outputFor7, REMOTE_WRITE as REMOTE_WRITE3 } from "@wirecat/cli-core";
13842
+ import { Command as Command6 } from "commander";
13628
13843
 
13629
13844
  // dist/commands/send.js
13630
- import { CliError as CliError23 } from "@wirecat/cli-base";
13631
- import { annotate as annotate4 } from "@wirecat/cli-base/commands";
13632
- import { answerEntity as answerEntity4, baseContext as baseContext4, bufferedInput, environmentOf as environmentOf3, itemOf as itemOf5, levelFor, newOperationId as newOperationId3, outputFor as outputFor5, ownerOnlyOption, REMOTE_WRITE, readUpload, renderAnswer as renderAnswer4 } from "@wirecat/cli-core";
13845
+ import { CliError as CliError24 } from "@wirecat/cli-base";
13846
+ import { annotate as annotate5 } from "@wirecat/cli-base/commands";
13847
+ import { answerEntity as answerEntity5, baseContext as baseContext5, bufferedInput, environmentOf as environmentOf3, itemOf as itemOf6, levelFor, newOperationId as newOperationId4, outputFor as outputFor6, ownerOnlyOption as ownerOnlyOption2, REMOTE_WRITE as REMOTE_WRITE2, readUpload, renderAnswer as renderAnswer5 } from "@wirecat/cli-core";
13633
13848
  import { htmlToText } from "@wirecat/cli-core/mail";
13634
- import { Command as Command4 } from "commander";
13849
+ import { Command as Command5 } from "commander";
13635
13850
  var OPERATION_ID = /^-?[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
13636
13851
  var mailSend = looseObject({
13637
13852
  sent: boolean(),
@@ -13656,9 +13871,9 @@ var mailSend = looseObject({
13656
13871
  });
13657
13872
  var operationIdOf = /* @__PURE__ */ __name((given) => {
13658
13873
  if (given === void 0)
13659
- return newOperationId3();
13874
+ return newOperationId4();
13660
13875
  if (!OPERATION_ID.test(given))
13661
- throw new CliError23("validation_error", "--operation-id is the operation_id an outcome_unknown answer named", {
13876
+ throw new CliError24("validation_error", "--operation-id is the operation_id an outcome_unknown answer named", {
13662
13877
  param: "operation-id"
13663
13878
  });
13664
13879
  return given;
@@ -13685,13 +13900,13 @@ var sendingOf = /* @__PURE__ */ __name((opened, command) => {
13685
13900
  const folders = await foldersFor(void 0, settings.mailbox.folders, defaults, () => opened.mailbox.folders());
13686
13901
  return { folders, mode: defaults.mode ?? "imap" };
13687
13902
  }, "syncFolders"),
13688
- warn: /* @__PURE__ */ __name((message, stores) => outputFor5(command).renderer.warn(stores ? `${message}; \`${IDENTITY.command} ${opened.profile} ${stores}\` stores it` : message), "warn"),
13903
+ warn: /* @__PURE__ */ __name((message, stores) => outputFor6(command).renderer.warn(stores ? `${message}; \`${IDENTITY.command} ${opened.profile} ${stores}\` stores it` : message), "warn"),
13689
13904
  agentWithoutOthers: environmentOf3(command).agent !== void 0 && !othersSetInConfig(command),
13690
13905
  ...environment.sendClock ? { clock: environment.sendClock } : {}
13691
13906
  };
13692
13907
  }, "sendingOf");
13693
13908
  var othersSetInConfig = /* @__PURE__ */ __name((command) => {
13694
- const { settings } = baseContext4(command, configuration.resolveSettings);
13909
+ const { settings } = baseContext5(command, configuration.resolveSettings);
13695
13910
  const { key } = levelFor(settings.permissions, SEND_OTHERS_KEY, configuration.permissions?.defaults ?? {});
13696
13911
  const from = key ? settings.permissionSources[key] : void 0;
13697
13912
  return key !== void 0 && key !== null && key.startsWith(SEND_OTHERS_KEY) && from !== void 0 && from !== "flag";
@@ -13746,17 +13961,17 @@ var showBeforeAsking = /* @__PURE__ */ __name((command, draft, key, owner) => {
13746
13961
  const defaults = configuration.permissions?.defaults ?? {};
13747
13962
  const asks = [key, ...othersOf(draft, owner).length ? [SEND_OTHERS_KEY] : []].some((one) => levelFor(settings.permissions, one, defaults).level === "ask");
13748
13963
  if (asks)
13749
- outputFor5(command).streams.diagnostic(summaryText(draft));
13964
+ outputFor6(command).streams.diagnostic(summaryText(draft));
13750
13965
  }, "showBeforeAsking");
13751
- var answer = /* @__PURE__ */ __name((command, opened, draft, outcome) => opened.answer(() => renderAnswer4(command, outputFor5(command), itemOf5({ ...outcome, message_id: draft.messageId, ...summaryOf2(draft) }), () => outcome.sent ? `sent to ${everyone(draft).length} ${everyone(draft).length === 1 ? "recipient" : "recipients"}: ${draft.subject}
13966
+ var answer = /* @__PURE__ */ __name((command, opened, draft, outcome) => opened.answer(() => renderAnswer5(command, outputFor6(command), itemOf6({ ...outcome, message_id: draft.messageId, ...summaryOf2(draft) }), () => outcome.sent ? `sent to ${everyone(draft).length} ${everyone(draft).length === 1 ? "recipient" : "recipients"}: ${draft.subject}
13752
13967
  ` : `${String(outcome.hint ?? "not sent")}
13753
13968
  `)), "answer");
13754
13969
  var go = /* @__PURE__ */ __name(async (command, opened, outgoing, dryRun, after) => {
13755
13970
  const { draft } = outgoing;
13756
13971
  if (everyone(draft).length === 0)
13757
- throw new CliError23("validation_error", "the message has nobody to go to; give --to", { param: "to" });
13972
+ throw new CliError24("validation_error", "the message has nobody to go to; give --to", { param: "to" });
13758
13973
  if (forgotAttachment(draft.text, draft.files.length > 0 || draft.message !== void 0))
13759
- outputFor5(command).renderer.warn("the text speaks of an attachment, and nothing is attached (--file)");
13974
+ outputFor6(command).renderer.warn("the text speaks of an attachment, and nothing is attached (--file)");
13760
13975
  if (dryRun) {
13761
13976
  answer(command, opened, draft, {
13762
13977
  sent: false,
@@ -13786,17 +14001,17 @@ var go = /* @__PURE__ */ __name(async (command, opened, outgoing, dryRun, after)
13786
14001
  }, "go");
13787
14002
  var sendAction = /* @__PURE__ */ __name(async function(text3, flags) {
13788
14003
  if (flags.replyAll && flags.replyTo === void 0)
13789
- throw new CliError23("validation_error", "--reply-all answers the message --reply-to names", { param: "reply-all" });
14004
+ throw new CliError24("validation_error", "--reply-all answers the message --reply-to names", { param: "reply-all" });
13790
14005
  if (flags.replyTo === void 0 && flags.subject === void 0)
13791
- throw new CliError23("validation_error", "a new message needs --subject", { param: "subject" });
14006
+ throw new CliError24("validation_error", "a new message needs --subject", { param: "subject" });
13792
14007
  if (flags.html && flags.replyTo !== void 0)
13793
- throw new CliError23("validation_error", "--html sends a new message; a reply quotes its original as plain text", {
14008
+ throw new CliError24("validation_error", "--html sends a new message; a reply quotes its original as plain text", {
13794
14009
  param: "html"
13795
14010
  });
13796
14011
  const operationId = operationIdOf(flags.operationId);
13797
14012
  const body = text3 ?? await readText(this);
13798
14013
  if (!body.trim() && !flags.file?.length)
13799
- throw new CliError23("validation_error", "the message has no text: give it, or pipe it on stdin", { param: "text" });
14014
+ throw new CliError24("validation_error", "the message has no text: give it, or pipe it on stdin", { param: "text" });
13800
14015
  const files = await filesOf(this, flags.file ?? [], flags.allowAnyFile === true);
13801
14016
  await organising(this, async (opened) => {
13802
14017
  const from = { address: opened.mailbox.key.account };
@@ -13854,9 +14069,9 @@ var readText = /* @__PURE__ */ __name(async (command) => {
13854
14069
  return (await bufferedInput(input)).toString("utf8");
13855
14070
  }, "readText");
13856
14071
  var recipients = /* @__PURE__ */ __name((command) => command.addOption(repeatable("--to <address>", "who it goes to: an address, or several split by commas; repeat it for more (a reply: instead of its sender)")).addOption(repeatable("--cc <address>", "a copy to this address; repeat it for more")).addOption(repeatable("--bcc <address>", "a hidden copy to this address; repeat it for more")), "recipients");
13857
- var sending = /* @__PURE__ */ __name((command) => command.addOption(repeatable("--file <file>", "attach this file, as named, never a pattern; repeat it for more")).addOption(ownerOnlyOption("--allow-any-file", "attach a file even from credential folders or this CLI's own folders")).option("--operation-id <id>", "repeat a send whose outcome was unknown; Sent is checked first, so it goes once").option("--yes", "answer the question before sending to anyone but you").option("--dry-run", "build the message and show what would go; send nothing"), "sending");
13858
- var sendCommand = /* @__PURE__ */ __name(() => answerEntity4(sending(recipients(annotate4(new Command4("send"), {
13859
- effects: REMOTE_WRITE,
14072
+ var sending = /* @__PURE__ */ __name((command) => command.addOption(repeatable("--file <file>", "attach this file, as named, never a pattern; repeat it for more")).addOption(ownerOnlyOption2("--allow-any-file", "attach a file even from credential folders or this CLI's own folders")).option("--operation-id <id>", "repeat a send whose outcome was unknown; Sent is checked first, so it goes once").option("--yes", "answer the question before sending to anyone but you").option("--dry-run", "build the message and show what would go; send nothing"), "sending");
14073
+ var sendCommand = /* @__PURE__ */ __name(() => answerEntity5(sending(recipients(annotate5(new Command5("send"), {
14074
+ effects: REMOTE_WRITE2,
13860
14075
  examples: [
13861
14076
  `${IDENTITY.command} personal messages send --to ann@example.com --subject "Lunch" --html "<p>See you at <b>noon</b>.</p>"`,
13862
14077
  `${IDENTITY.command} personal messages send --reply-to 'msg:email/me%40example.com/thread-1/1001' "Thanks, done."`,
@@ -13896,8 +14111,8 @@ var forwardAction = /* @__PURE__ */ __name(async function(reference, text3, flag
13896
14111
  }, flags.dryRun === true);
13897
14112
  });
13898
14113
  }, "forwardAction");
13899
- var forwardCommand = /* @__PURE__ */ __name(() => answerEntity4(sending(recipients(annotate4(new Command4("forward"), {
13900
- effects: REMOTE_WRITE,
14114
+ var forwardCommand = /* @__PURE__ */ __name(() => answerEntity5(sending(recipients(annotate5(new Command5("forward"), {
14115
+ effects: REMOTE_WRITE2,
13901
14116
  examples: [
13902
14117
  `${IDENTITY.command} personal messages forward 'msg:email/me%40example.com/thread-1/1001' --to bob@example.com`,
13903
14118
  `${IDENTITY.command} personal messages forward 'msg:email/me%40example.com/thread-1/1001' --to bob@example.com "FYI"`
@@ -13905,8 +14120,8 @@ var forwardCommand = /* @__PURE__ */ __name(() => answerEntity4(sending(recipien
13905
14120
  }))), "mail_send", mailSend).summary("forward an email, attached whole, over SMTP").description("forward a stored email to other people: the original goes as an attached message with its own attachments, Fwd: before its subject. Mail to anyone but you asks first (permissions.messages.send.others)").argument("<message>", "the msg:email/\u2026 reference search messages shows").argument("[text]", "a few words above the forwarded message").option("--subject <text>", "the subject instead of the original's with Fwd:").action(forwardAction), "forwardCommand");
13906
14121
 
13907
14122
  // dist/commands/drafts-send.js
13908
- var draftSendCommand = /* @__PURE__ */ __name(() => answerEntity5(annotate5(new Command5("send"), {
13909
- effects: REMOTE_WRITE2,
14123
+ var draftSendCommand = /* @__PURE__ */ __name(() => answerEntity6(annotate6(new Command6("send"), {
14124
+ effects: REMOTE_WRITE3,
13910
14125
  examples: [`${IDENTITY.command} personal drafts send 5b0e1c2a@example.com`]
13911
14126
  }), "mail_send", mailSend).summary("send a saved draft, then remove it from Drafts").description("send a draft as it is saved, over SMTP, as messages send does: mail to anyone but you asks first (permissions.messages.send.others); once it went, the draft leaves the Drafts folder").argument("<draft>", "the draft's id, as drafts list shows it").option("--operation-id <id>", "repeat a send whose outcome was unknown; Sent is checked first, so it goes once").option("--yes", "answer the question before sending to anyone but you").option("--dry-run", "show what would go; send nothing").action(async function(given, flags) {
13912
14127
  const id = draftIdOf(given);
@@ -13931,11 +14146,11 @@ var draftSendCommand = /* @__PURE__ */ __name(() => answerEntity5(annotate5(new
13931
14146
  parts
13932
14147
  };
13933
14148
  await go(this, opened, { draft, kind: "message", key: "messages.send", operationId, retry: flags.operationId !== void 0 }, flags.dryRun === true, async () => {
13934
- const removal2 = newOperationId4();
14149
+ const removal2 = newOperationId5();
13935
14150
  try {
13936
- await guardedWrite3(opened.guard, { chatId: null, kind: "account", key: "drafts.send", operationId: removal2 }, () => opened.mailbox.writes.expunge(folder, found2.validity, [found2.uid]));
14151
+ await guardedWrite4(opened.guard, { chatId: null, kind: "account", key: "drafts.send", operationId: removal2 }, () => opened.mailbox.writes.expunge(folder, found2.validity, [found2.uid]));
13937
14152
  } catch {
13938
- outputFor6(this).renderer.warn(`the draft was sent and is still in ${folder}; drafts delete removes it`);
14153
+ outputFor7(this).renderer.warn(`the draft was sent and is still in ${folder}; drafts delete removes it`);
13939
14154
  return {};
13940
14155
  }
13941
14156
  return { writes: [{ operation_id: removal2, op: "delete", folder, messages: 1 }] };
@@ -13977,7 +14192,7 @@ var REF = "msg:email/me%40example.com/t1/m1";
13977
14192
  var ID = "5b0e1c2a@example.com";
13978
14193
  var limitOf2 = /* @__PURE__ */ __name((value) => {
13979
14194
  if (!/^\d+$/.test(value.trim()) || Number(value) < 1 || Number(value) > MAX_LIST)
13980
- throw new CliError24("validation_error", `--limit takes a whole number from 1 to ${MAX_LIST}`, { param: "limit" });
14195
+ throw new CliError25("validation_error", `--limit takes a whole number from 1 to ${MAX_LIST}`, { param: "limit" });
13981
14196
  return Number(value);
13982
14197
  }, "limitOf");
13983
14198
  var addressing = /* @__PURE__ */ __name((command) => command.addOption(repeatable("--to <address>", "who it goes to: an address, or several split by commas; repeat it for more")).addOption(repeatable("--cc <address>", "a copy to; repeat it for more")).addOption(repeatable("--bcc <address>", "a blind copy to; repeat it for more")).option("--subject <text>", "the subject line").option("--dry-run", "build the draft and show it; store nothing"), "addressing");
@@ -13988,26 +14203,26 @@ var textOf = /* @__PURE__ */ __name(async (command, text3) => {
13988
14203
  return text3;
13989
14204
  const input = environmentOf4(command).stdin ?? process.stdin;
13990
14205
  if ("isTTY" in input && input.isTTY === true)
13991
- throw new CliError24("validation_error", "- reads the text from a pipe");
14206
+ throw new CliError25("validation_error", "- reads the text from a pipe");
13992
14207
  return (await bufferedInput2(input)).toString("utf8");
13993
14208
  }, "textOf");
13994
14209
  var ownAddress = /* @__PURE__ */ __name((opened) => opened.mailbox.key.account, "ownAddress");
13995
14210
  var draftsFolder = /* @__PURE__ */ __name(async (opened) => draftsFolderOf(await opened.mailbox.folders(), opened.mailbox.organise), "draftsFolder");
13996
14211
  var guarded = /* @__PURE__ */ __name(async (opened, key, act) => {
13997
- const operationId = newOperationId5();
14212
+ const operationId = newOperationId6();
13998
14213
  return {
13999
- done: await guardedWrite4(opened.guard, { chatId: null, kind: "account", key, operationId }, act),
14214
+ done: await guardedWrite5(opened.guard, { chatId: null, kind: "account", key, operationId }, act),
14000
14215
  operationId
14001
14216
  };
14002
14217
  }, "guarded");
14003
- var answer2 = /* @__PURE__ */ __name((command, opened, change2) => opened.answer(() => renderAnswer5(command, outputFor7(command), itemOf6(change2), () => change2.applied ? `${change2.action === "delete" ? "deleted" : "saved"} draft ${change2.id} in ${change2.folder}
14218
+ var answer2 = /* @__PURE__ */ __name((command, opened, change2) => opened.answer(() => renderAnswer6(command, outputFor8(command), itemOf7(change2), () => change2.applied ? `${change2.action === "delete" ? "deleted" : "saved"} draft ${change2.id} in ${change2.folder}
14004
14219
  ` : `${change2.hint ?? "a preview: nothing changed"}
14005
14220
  `)), "answer");
14006
14221
  var replyTo = /* @__PURE__ */ __name(async (command, opened, ref, all) => {
14007
14222
  const { raw } = await fetchOriginal(opened.mailbox, opened.backend, ref);
14008
14223
  const original = await originalOf(raw);
14009
14224
  if (!original.messageId)
14010
- throw new CliError24("invalid_response", `${ref} has no Message-ID, so a reply cannot name what it answers`);
14225
+ throw new CliError25("invalid_response", `${ref} has no Message-ID, so a reply cannot name what it answers`);
14011
14226
  const owner = ownerOf(opened, command);
14012
14227
  const to = replyPeople(original, owner, false);
14013
14228
  return {
@@ -14018,8 +14233,8 @@ var replyTo = /* @__PURE__ */ __name(async (command, opened, ref, all) => {
14018
14233
  references: referencesOf(original)
14019
14234
  };
14020
14235
  }, "replyTo");
14021
- var listCommand2 = /* @__PURE__ */ __name(() => answerEntity6(annotate6(new Command6("list"), {
14022
- effects: REMOTE_READ3,
14236
+ var listCommand3 = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("list"), {
14237
+ effects: REMOTE_READ4,
14023
14238
  examples: [
14024
14239
  `${IDENTITY.command} personal drafts list`,
14025
14240
  `${IDENTITY.command} personal drafts list --limit 5 --json`
@@ -14028,19 +14243,19 @@ var listCommand2 = /* @__PURE__ */ __name(() => answerEntity6(annotate6(new Comm
14028
14243
  await organising(this, async (opened) => {
14029
14244
  const limit = options.limit ?? LIST_LIMIT;
14030
14245
  const found2 = await listDrafts(opened.backend, await draftsFolder(opened), limit);
14031
- opened.answer(() => renderAnswer5(this, outputFor7(this), listOf2("drafts list", { items: found2.items, limit, has_more: found2.more }), () => found2.items.length === 0 ? "no drafts\n" : `${found2.items.map((one) => `${one.id} ${one.subject || "(no subject)"} to ${one.to.join(", ") || "nobody yet"}`).join("\n")}
14246
+ opened.answer(() => renderAnswer6(this, outputFor8(this), listOf3("drafts list", { items: found2.items, limit, has_more: found2.more }), () => found2.items.length === 0 ? "no drafts\n" : `${found2.items.map((one) => `${one.id} ${one.subject || "(no subject)"} to ${one.to.join(", ") || "nobody yet"}`).join("\n")}
14032
14247
  `));
14033
14248
  });
14034
14249
  }), "listCommand");
14035
- var createCommand = /* @__PURE__ */ __name(() => answerEntity6(addressing(annotate6(new Command6("create"), {
14036
- effects: REMOTE_WRITE3,
14250
+ var createCommand2 = /* @__PURE__ */ __name(() => answerEntity7(addressing(annotate7(new Command7("create"), {
14251
+ effects: REMOTE_WRITE4,
14037
14252
  examples: [
14038
14253
  `${IDENTITY.command} personal drafts create --to anna@example.com --subject 'Monday' 'Shall we meet at ten?'`,
14039
14254
  `${IDENTITY.command} personal drafts create --reply-to ${REF} --reply-all 'Thanks, agreed.'`
14040
14255
  ]
14041
14256
  })), "mail_draft_change", draftChange).summary("save a new draft for the owner to check and send").description("save a new message in the Drafts folder; nothing is sent, and the owner sends it from any mail app. --reply-to answers a stored message in its thread").argument("[text]", "the text; - reads it from stdin").option("--reply-to <message>", "answer this stored message: its sender, its subject with Re:, in its thread").option("--reply-all", "with --reply-to, also everyone it went to, but you").action(async function(given, options) {
14042
14257
  if (options.replyAll && !options.replyTo)
14043
- throw new CliError24("validation_error", "--reply-all goes with --reply-to", { param: "reply-all" });
14258
+ throw new CliError25("validation_error", "--reply-all goes with --reply-to", { param: "reply-all" });
14044
14259
  const body = await textOf(this, given) ?? "";
14045
14260
  await organising(this, async (opened) => {
14046
14261
  const reply = options.replyTo ? await replyTo(this, opened, options.replyTo, options.replyAll === true) : void 0;
@@ -14091,8 +14306,8 @@ var saveDraft = /* @__PURE__ */ __name(async (command, opened, action, message,
14091
14306
  operation_id: operationId
14092
14307
  });
14093
14308
  }, "saveDraft");
14094
- var updateCommand = /* @__PURE__ */ __name(() => answerEntity6(addressing(annotate6(new Command6("update"), {
14095
- effects: REMOTE_WRITE3,
14309
+ var updateCommand = /* @__PURE__ */ __name(() => answerEntity7(addressing(annotate7(new Command7("update"), {
14310
+ effects: REMOTE_WRITE4,
14096
14311
  examples: [
14097
14312
  `${IDENTITY.command} personal drafts update ${ID} 'New text, the rest kept'`,
14098
14313
  `${IDENTITY.command} personal drafts update ${ID} --to anna@example.com --to boris@example.com`
@@ -14111,14 +14326,14 @@ var updateCommand = /* @__PURE__ */ __name(() => answerEntity6(addressing(annota
14111
14326
  ...body === void 0 ? {} : { text: body }
14112
14327
  };
14113
14328
  if (Object.keys(fields).length === 0)
14114
- throw new CliError24("validation_error", "give what changes: the text, --to, --cc, --bcc or --subject");
14329
+ throw new CliError25("validation_error", "give what changes: the text, --to, --cc, --bcc or --subject");
14115
14330
  await saveDraft(this, opened, "update", nextVersion(found2.read, fields, ownAddress(opened)), options.dryRun === true, { uid: found2.uid, validity: found2.validity });
14116
14331
  });
14117
14332
  }), "updateCommand");
14118
- var deleteCommand = /* @__PURE__ */ __name(() => answerEntity6(annotate6(new Command6("delete"), {
14119
- effects: REMOTE_WRITE3,
14333
+ var deleteCommand = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("delete"), {
14334
+ effects: REMOTE_WRITE4,
14120
14335
  examples: [`${IDENTITY.command} personal drafts delete ${ID} --allow-dangerous`]
14121
- }), "mail_draft_change", draftChange).summary("delete a draft for good").description("delete a draft from the Drafts folder for good, with no restore; the owner adds --allow-dangerous to do it, without it a preview").argument("<draft>", "the draft's id, as drafts list shows it").addOption(ownerOnlyOption2("--allow-dangerous", "delete it for good, no restore; without it, only a preview")).option("--dry-run", "only preview, even with --allow-dangerous").action(async function(draft, options) {
14336
+ }), "mail_draft_change", draftChange).summary("delete a draft for good").description("delete a draft from the Drafts folder for good, with no restore; the owner adds --allow-dangerous to do it, without it a preview").argument("<draft>", "the draft's id, as drafts list shows it").addOption(ownerOnlyOption3("--allow-dangerous", "delete it for good, no restore; without it, only a preview")).option("--dry-run", "only preview, even with --allow-dangerous").action(async function(draft, options) {
14122
14337
  const id = draftIdOf(draft);
14123
14338
  const dangerous = this.optsWithGlobals().allowDangerous === true;
14124
14339
  await organising(this, async (opened) => {
@@ -14142,117 +14357,7 @@ var deleteCommand = /* @__PURE__ */ __name(() => answerEntity6(annotate6(new Com
14142
14357
  answer2(this, opened, { ...shown4, applied: true, operation_id: operationId });
14143
14358
  });
14144
14359
  }), "deleteCommand");
14145
- var draftsCommand = /* @__PURE__ */ __name(() => annotate6(new Command6("drafts"), { effects: LOCAL_READ2 }).summary("drafts on the server: an agent writes them, the owner sends them").description("drafts in the mailbox's Drafts folder: an agent writes them, the owner checks and sends them").addCommand(listCommand2()).addCommand(createCommand()).addCommand(updateCommand()).addCommand(deleteCommand()).addCommand(draftSendCommand()), "draftsCommand");
14146
-
14147
- // dist/commands/folders.js
14148
- import { CliError as CliError25 } from "@wirecat/cli-base";
14149
- import { annotate as annotate7 } from "@wirecat/cli-base/commands";
14150
- import { answerEntity as answerEntity7, baseContext as baseContext5, guardedWrite as guardedWrite5, guardFor as guardFor2, itemOf as itemOf7, LOCAL_READ as LOCAL_READ3, listOf as listOf3, newOperationId as newOperationId6, outputFor as outputFor8, ownerOnlyOption as ownerOnlyOption3, REMOTE_READ as REMOTE_READ4, REMOTE_WRITE as REMOTE_WRITE4, renderAnswer as renderAnswer6, terminalAsker as terminalAsker2 } from "@wirecat/cli-core";
14151
- import { Command as Command7 } from "commander";
14152
- var mailFolder = strictObject({
14153
- path: string(),
14154
- name: string(),
14155
- role: nullable(string()),
14156
- messages: nullable(number()),
14157
- unseen: nullable(number())
14158
- });
14159
- var listCommand3 = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("list"), {
14160
- effects: REMOTE_READ4,
14161
- examples: [`${IDENTITY.command} personal folders list`, `${IDENTITY.command} personal folders list --json`]
14162
- }), "mail_folder", mailFolder).summary("the folders with their role and message counts").description("the folders of the mailbox with their role (inbox, sent, trash, ...) and message counts").action(async function() {
14163
- const context = contextOf(this);
14164
- refuseOffline(context.flags);
14165
- const { backend } = await openMail(context);
14166
- const folders = await closing(backend, () => baseContext5(this, configuration.resolveSettings).run(() => backend.folderList()));
14167
- renderAnswer6(this, outputFor8(this), listOf3("folders list", { items: folders, limit: Math.max(1, folders.length), has_more: false }));
14168
- }), "listCommand");
14169
- var folderChange = strictObject({
14170
- action: picklist(["create", "rename", "delete"]),
14171
- folder: string(),
14172
- to: optional(string()),
14173
- messages: optional(nullable(number())),
14174
- applied: optional(boolean()),
14175
- operation_id: optional(string()),
14176
- hint: optional(string())
14177
- });
14178
- var ACTIONS = { create: "folder-create", rename: "folder-update", delete: "folder-delete" };
14179
- var changeFolder = /* @__PURE__ */ __name(async (command, action, work, preview) => {
14180
- const context = contextOf(command);
14181
- refuseOffline(context.flags);
14182
- const { backend } = await openMail(context);
14183
- const base2 = baseContext5(command, configuration.resolveSettings);
14184
- const done = await closing(backend, () => base2.run(async () => {
14185
- const writes = backend.writes;
14186
- if (!writes)
14187
- throw new CliError25("provider_unavailable", "this mailbox cannot be changed from here");
14188
- const guard = guardFor2(IDENTITY, { ...base2.settings, permissionDefaults: configuration.permissions?.defaults ?? {} }, (message) => outputFor8(command).renderer.warn(message), context.env, terminalAsker2(command));
14189
- const folders = await backend.folderList();
14190
- const shown4 = preview?.(folders);
14191
- if (shown4)
14192
- return { ...shown4, applied: false, hint: "a preview: nothing changed; add --yes to delete it" };
14193
- const operationId = newOperationId6();
14194
- const changed = await guardedWrite5(guard, { chatId: null, kind: "account", action: ACTIONS[action], key: `folders.${action}`, operationId }, () => work(writes, folders));
14195
- return { ...changed, operation_id: operationId };
14196
- }));
14197
- renderAnswer6(command, outputFor8(command), itemOf7({ action, ...done }));
14198
- }, "changeFolder");
14199
- var existing = /* @__PURE__ */ __name((folders, given) => {
14200
- const found2 = folderNamed(folders, given);
14201
- if (!found2)
14202
- throw new CliError25("not_found", `no folder "${given}"; folders list shows them`, { param: "folder" });
14203
- return found2;
14204
- }, "existing");
14205
- var createCommand2 = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("create"), {
14206
- effects: REMOTE_WRITE4,
14207
- examples: [
14208
- `${IDENTITY.command} personal folders create Receipts`,
14209
- `${IDENTITY.command} personal folders create Work/2026`
14210
- ]
14211
- }), "mail_folder_change", folderChange).summary("make a folder").description("make a folder on the server; on Gmail it is a label").argument("<folder>", "the folder's path; the server's separator (usually / or .) makes a subfolder").action(async function(folder) {
14212
- await changeFolder(this, "create", async (writes, folders) => {
14213
- if (folders.some(({ path: path2 }) => path2 === folder))
14214
- throw new CliError25("validation_error", `folder "${folder}" already exists`, { param: "folder" });
14215
- await writes.createFolder(folder);
14216
- return { folder };
14217
- });
14218
- }), "createCommand");
14219
- var renameCommand = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("rename"), {
14220
- effects: REMOTE_WRITE4,
14221
- examples: [`${IDENTITY.command} personal folders rename Receipts Invoices`]
14222
- }), "mail_folder_change", folderChange).summary("rename a folder").description("rename a folder of your own on the server; the inbox and the special folders keep their names").argument("<folder>", "the folder, by path or name").argument("<name>", "its new path").action(async function(folder, name) {
14223
- await changeFolder(this, "rename", async (writes, folders) => {
14224
- const found2 = existing(folders, folder);
14225
- if (found2.role)
14226
- throw new CliError25("validation_error", `${found2.path} is the ${found2.role} folder; it keeps its name`);
14227
- await writes.renameFolder(found2.path, name);
14228
- return { folder: found2.path, to: name };
14229
- });
14230
- }), "renameCommand");
14231
- var deleteFolderCommand = /* @__PURE__ */ __name(() => answerEntity7(annotate7(new Command7("delete"), {
14232
- effects: REMOTE_WRITE4,
14233
- examples: [`${IDENTITY.command} personal folders delete Old --yes`]
14234
- }), "mail_folder_change", folderChange).summary("delete an empty folder").description("delete a folder of your own; it must be empty (move or delete its mail first), unless --allow-dangerous, which loses that mail for good; a preview without --yes").argument("<folder>", "the folder, by path or name").option("--yes", "delete it; without it, only a preview").option("--dry-run", "only preview, even with --yes").addOption(ownerOnlyOption3("--allow-dangerous", "delete a folder that still holds mail: that mail is gone for good, no restore")).action(async function(folder, options) {
14235
- const given = this.optsWithGlobals();
14236
- const dangerous = given.allowDangerous === true;
14237
- const emptyOrAllowed = /* @__PURE__ */ __name((folders) => {
14238
- const found2 = existing(folders, folder);
14239
- if (found2.role)
14240
- throw new CliError25("validation_error", `${found2.path} is the ${found2.role} folder; it stays`);
14241
- if (found2.messages !== 0 && !dangerous)
14242
- throw new CliError25("validation_error", `${found2.path} holds ${found2.messages ?? "an unknown number of"} messages; move them out first (messages move --filter 'mailbox:"${found2.path}"' --folder \u2026), or the owner adds --allow-dangerous to lose them`, { reason: "mail.folder-not-empty" });
14243
- return found2;
14244
- }, "emptyOrAllowed");
14245
- const preview = options.dryRun === true || given.yes !== true;
14246
- await changeFolder(this, "delete", async (writes, folders) => {
14247
- const found2 = emptyOrAllowed(folders);
14248
- await writes.deleteFolder(found2.path);
14249
- return { folder: found2.path, messages: found2.messages, applied: true };
14250
- }, preview ? (folders) => {
14251
- const found2 = emptyOrAllowed(folders);
14252
- return { folder: found2.path, messages: found2.messages };
14253
- } : void 0);
14254
- }), "deleteFolderCommand");
14255
- var foldersCommand = /* @__PURE__ */ __name(() => annotate7(new Command7("folders"), { effects: LOCAL_READ3 }).description("the folders of this profile's mailbox").addCommand(listCommand3()).addCommand(createCommand2()).addCommand(renameCommand()).addCommand(deleteFolderCommand()), "foldersCommand");
14360
+ var draftsCommand = /* @__PURE__ */ __name(() => annotate7(new Command7("drafts"), { effects: LOCAL_READ3 }).summary("drafts on the server: an agent writes them, the owner sends them").description("drafts in the mailbox's Drafts folder: an agent writes them, the owner checks and sends them").addCommand(listCommand3()).addCommand(createCommand2()).addCommand(updateCommand()).addCommand(deleteCommand()).addCommand(draftSendCommand()), "draftsCommand");
14256
14361
 
14257
14362
  // dist/commands/messages.js
14258
14363
  import { CliError as CliError27 } from "@wirecat/cli-base";
@@ -15501,38 +15606,6 @@ var importLeaf = /* @__PURE__ */ __name(() => answerEntity11(annotate11(new Comm
15501
15606
  }, { meta: { complete: report.complete, timezone: zone, window: { since: since.toISOString() } } }));
15502
15607
  }), "importLeaf");
15503
15608
 
15504
- // dist/commands/server-search.js
15505
- var serverAccess = /* @__PURE__ */ __name((command) => {
15506
- const context = contextOf(command);
15507
- const { settings } = context;
15508
- const { address, host, folders: configured } = settings.mailbox;
15509
- const search = providerFor(address ?? "", host)?.search ?? DEFAULT_SEARCH;
15510
- return {
15511
- ...search.timeMs === void 0 ? {} : { timeMs: search.timeMs },
15512
- offline: context.flags.offline === true,
15513
- permissions: settings.permissions,
15514
- readOnly: settings.readOnlyLock !== void 0,
15515
- open: /* @__PURE__ */ __name(async () => {
15516
- const { backend } = await openMail(context);
15517
- const serverQuery = backend.serverQuery;
15518
- try {
15519
- const folders = await foldersFor(void 0, configured, search, () => backend.folderList());
15520
- return {
15521
- source: {
15522
- ...backend,
15523
- ...serverQuery ? { query: /* @__PURE__ */ __name((criteria, folder) => serverQuery(criteria, folder, search.syntax), "query") } : {}
15524
- },
15525
- folders,
15526
- close: backend.close
15527
- };
15528
- } catch (error2) {
15529
- await backend.close();
15530
- throw error2;
15531
- }
15532
- }, "open")
15533
- };
15534
- }, "serverAccess");
15535
-
15536
15609
  // dist/commands/read.js
15537
15610
  var reads = {
15538
15611
  app: IDENTITY,