@dawnlit/outlook-bridge 1.1.0 → 2.0.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.
Files changed (139) hide show
  1. package/README.md +150 -183
  2. package/dist/backend.d.ts +151 -0
  3. package/dist/backend.js +3 -0
  4. package/dist/backend.js.map +1 -0
  5. package/dist/bridge.d.ts +56 -0
  6. package/dist/bridge.js +507 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/errors.d.ts +81 -43
  9. package/dist/errors.js +98 -52
  10. package/dist/errors.js.map +1 -1
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +25 -52
  13. package/dist/index.js.map +1 -1
  14. package/dist/mac/accounts.d.ts +7 -2
  15. package/dist/mac/accounts.js +23 -6
  16. package/dist/mac/accounts.js.map +1 -1
  17. package/dist/mac/attachments.d.ts +5 -25
  18. package/dist/mac/attachments.js +40 -99
  19. package/dist/mac/attachments.js.map +1 -1
  20. package/dist/mac/bounces.d.ts +12 -27
  21. package/dist/mac/bounces.js +95 -112
  22. package/dist/mac/bounces.js.map +1 -1
  23. package/dist/mac/cleanup.d.ts +11 -25
  24. package/dist/mac/cleanup.js +50 -76
  25. package/dist/mac/cleanup.js.map +1 -1
  26. package/dist/mac/drafts.d.ts +13 -34
  27. package/dist/mac/drafts.js +95 -169
  28. package/dist/mac/drafts.js.map +1 -1
  29. package/dist/mac/folders.d.ts +10 -21
  30. package/dist/mac/folders.js +33 -47
  31. package/dist/mac/folders.js.map +1 -1
  32. package/dist/mac/index.d.ts +2 -22
  33. package/dist/mac/index.js +19 -81
  34. package/dist/mac/index.js.map +1 -1
  35. package/dist/mac/profile.d.ts +13 -0
  36. package/dist/mac/profile.js +149 -0
  37. package/dist/mac/profile.js.map +1 -0
  38. package/dist/mac/read.d.ts +18 -36
  39. package/dist/mac/read.js +154 -208
  40. package/dist/mac/read.js.map +1 -1
  41. package/dist/mac/run.d.ts +35 -39
  42. package/dist/mac/run.js +97 -102
  43. package/dist/mac/run.js.map +1 -1
  44. package/dist/mac/scripts.d.ts +78 -86
  45. package/dist/mac/scripts.js +125 -115
  46. package/dist/mac/scripts.js.map +1 -1
  47. package/dist/mac/send.d.ts +10 -20
  48. package/dist/mac/send.js +64 -86
  49. package/dist/mac/send.js.map +1 -1
  50. package/dist/mac/signatures.d.ts +2 -2
  51. package/dist/mac/signatures.js +9 -11
  52. package/dist/mac/signatures.js.map +1 -1
  53. package/dist/mac/templates.d.ts +14 -26
  54. package/dist/mac/templates.js +75 -113
  55. package/dist/mac/templates.js.map +1 -1
  56. package/dist/mail.d.ts +77 -45
  57. package/dist/mail.js +166 -73
  58. package/dist/mail.js.map +1 -1
  59. package/dist/runtime.d.ts +76 -43
  60. package/dist/runtime.js +103 -48
  61. package/dist/runtime.js.map +1 -1
  62. package/dist/shared/args.d.ts +48 -0
  63. package/dist/shared/args.js +216 -0
  64. package/dist/shared/args.js.map +1 -0
  65. package/dist/shared/attachmentMatch.d.ts +28 -16
  66. package/dist/shared/attachmentMatch.js +60 -22
  67. package/dist/shared/attachmentMatch.js.map +1 -1
  68. package/dist/shared/bounceReport.d.ts +11 -0
  69. package/dist/shared/bounceReport.js +45 -0
  70. package/dist/shared/bounceReport.js.map +1 -0
  71. package/dist/shared/bounceRules.d.ts +38 -10
  72. package/dist/shared/bounceRules.js +50 -32
  73. package/dist/shared/bounceRules.js.map +1 -1
  74. package/dist/shared/exec.d.ts +21 -0
  75. package/dist/shared/exec.js +47 -0
  76. package/dist/shared/exec.js.map +1 -0
  77. package/dist/shared/json.d.ts +12 -6
  78. package/dist/shared/json.js +29 -23
  79. package/dist/shared/json.js.map +1 -1
  80. package/dist/shared/locate.d.ts +39 -0
  81. package/dist/shared/locate.js +129 -0
  82. package/dist/shared/locate.js.map +1 -0
  83. package/dist/shared/replyBody.d.ts +42 -32
  84. package/dist/shared/replyBody.js +84 -71
  85. package/dist/shared/replyBody.js.map +1 -1
  86. package/dist/templateBody.d.ts +63 -0
  87. package/dist/{outlookTemplateSections.js → templateBody.js} +72 -72
  88. package/dist/templateBody.js.map +1 -0
  89. package/dist/types.d.ts +360 -165
  90. package/dist/types.js +8 -9
  91. package/dist/types.js.map +1 -1
  92. package/dist/windows/accounts.d.ts +10 -1
  93. package/dist/windows/accounts.js +25 -13
  94. package/dist/windows/accounts.js.map +1 -1
  95. package/dist/windows/attachments.d.ts +9 -24
  96. package/dist/windows/attachments.js +94 -119
  97. package/dist/windows/attachments.js.map +1 -1
  98. package/dist/windows/bounces.d.ts +13 -26
  99. package/dist/windows/bounces.js +169 -200
  100. package/dist/windows/bounces.js.map +1 -1
  101. package/dist/windows/cleanup.d.ts +19 -23
  102. package/dist/windows/cleanup.js +93 -111
  103. package/dist/windows/cleanup.js.map +1 -1
  104. package/dist/windows/drafts.d.ts +16 -35
  105. package/dist/windows/drafts.js +167 -253
  106. package/dist/windows/drafts.js.map +1 -1
  107. package/dist/windows/folders.d.ts +8 -13
  108. package/dist/windows/folders.js +45 -52
  109. package/dist/windows/folders.js.map +1 -1
  110. package/dist/windows/index.d.ts +2 -27
  111. package/dist/windows/index.js +11 -65
  112. package/dist/windows/index.js.map +1 -1
  113. package/dist/windows/read.d.ts +24 -45
  114. package/dist/windows/read.js +266 -279
  115. package/dist/windows/read.js.map +1 -1
  116. package/dist/windows/run.d.ts +39 -39
  117. package/dist/windows/run.js +151 -111
  118. package/dist/windows/run.js.map +1 -1
  119. package/dist/windows/scripts.d.ts +71 -38
  120. package/dist/windows/scripts.js +123 -71
  121. package/dist/windows/scripts.js.map +1 -1
  122. package/dist/windows/send.d.ts +6 -11
  123. package/dist/windows/send.js +70 -79
  124. package/dist/windows/send.js.map +1 -1
  125. package/dist/windows/signatures.d.ts +4 -10
  126. package/dist/windows/signatures.js +30 -37
  127. package/dist/windows/signatures.js.map +1 -1
  128. package/dist/windows/templates.d.ts +12 -18
  129. package/dist/windows/templates.js +126 -151
  130. package/dist/windows/templates.js.map +1 -1
  131. package/package.json +5 -4
  132. package/dist/OutlookService.d.ts +0 -43
  133. package/dist/OutlookService.js +0 -137
  134. package/dist/OutlookService.js.map +0 -1
  135. package/dist/outlookTemplateSections.d.ts +0 -62
  136. package/dist/outlookTemplateSections.js.map +0 -1
  137. package/dist/shared/capabilities.d.ts +0 -3
  138. package/dist/shared/capabilities.js +0 -9
  139. package/dist/shared/capabilities.js.map +0 -1
package/dist/types.js CHANGED
@@ -1,13 +1,12 @@
1
1
  "use strict";
2
- // The package's data contract, and the interface both platform implementations
3
- // answer to.
2
+ // The public contract: what the package returns, what it takes, and the
3
+ // OutlookBridge interface every entry point answers to.
4
4
  //
5
- // These types used to live in the Windows implementation, so macOS imported its
6
- // own return shapes from it and its stubs re-declared them structurally. The two
7
- // drifted, and because OutlookService dispatches by picking one implementation or
8
- // the other, every drift surfaced in the PUBLIC types as a union — `matched:
9
- // UndeliverableEmail[] | unknown[]` and the like. Both now implement
10
- // `OutlookBridge` from here, so a drift is a compile error in the package rather
11
- // than a union in the consumer's editor.
5
+ // Two conventions hold throughout:
6
+ // - Timestamps are local time as 'yyyy-MM-dd HH:mm', which sorts correctly as
7
+ // a plain string and is what both platforms can produce without a timezone
8
+ // table.
9
+ // - Ids are platform-specific (see EmailLocator). Don't persist one and look it
10
+ // up on the other platform.
12
11
  Object.defineProperty(exports, "__esModule", { value: true });
13
12
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA,+EAA+E;AAC/E,aAAa;AACb,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,kFAAkF;AAClF,6EAA6E;AAC7E,qEAAqE;AACrE,iFAAiF;AACjF,yCAAyC"}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wDAAwD;AACxD,EAAE;AACF,mCAAmC;AACnC,+EAA+E;AAC/E,8EAA8E;AAC9E,YAAY;AACZ,iFAAiF;AACjF,+BAA+B","sourcesContent":["// The public contract: what the package returns, what it takes, and the\n// OutlookBridge interface every entry point answers to.\n//\n// Two conventions hold throughout:\n// - Timestamps are local time as 'yyyy-MM-dd HH:mm', which sorts correctly as\n// a plain string and is what both platforms can produce without a timezone\n// table.\n// - Ids are platform-specific (see EmailLocator). Don't persist one and look it\n// up on the other platform.\n\n// ── Identifying an email ─────────────────────────────────────────────────\n/**\n * Where an email lives, as a listing reported it.\n *\n * Every listing row (`InboxEmail`, `InboxSearchMatch`, `SelectedEmail`, …)\n * carries both fields, so a row can be passed straight back in wherever an\n * `EmailRef` is accepted — which is also the reliable way to keep the two ids\n * from different rows apart.\n */\nexport interface EmailLocator {\n /** Windows: the MAPI EntryID. macOS: Outlook for Mac's integer message id. */\n readonly entryId: string;\n /**\n * Windows: the StoreID the email was listed from, which lets it resolve in\n * any mounted mailbox rather than only the default one. macOS has no\n * equivalent and ignores it.\n */\n readonly storeId?: string;\n}\n\n/** An email to act on: its entry id alone, or anything carrying a locator. */\nexport type EmailRef = string | EmailLocator;\n\n/**\n * Recipients: one address, a comma- or semicolon-separated list, or an array.\n * Display-name forms such as `\"Doe, Jo\" <jo@example.com>` are kept whole.\n */\nexport type Recipients = string | readonly string[];\n\n// ── Sending and replying ─────────────────────────────────────────────────\nexport interface SendEmailParams {\n /** SMTP address of the mailbox to send from. Never falls back to the\n * default account — an address that doesn't resolve is an error. */\n emailAccount: string;\n to?: Recipients;\n cc?: Recipients;\n bcc?: Recipients;\n subject: string;\n htmlBody: string;\n /** Absolute paths of files to attach. Each has to exist. */\n attachments?: readonly string[];\n /**\n * An Outlook signature, by the name listOutlookSignatures reports, added to\n * the body: in its `{{SIGNATURE}}` placeholder when it has one, otherwise\n * at the end. Outlook adds no signature of its own to a body set this way,\n * so this is how a composed email gets one.\n */\n signatureName?: string;\n /** Send now. Default false: the email is staged as a draft instead. */\n sendImmediately?: boolean;\n /**\n * Drafts only. True (the default) opens an Outlook compose window; false\n * files the draft silently into Drafts — the workable choice for batches.\n */\n openDraftWindow?: boolean;\n}\n\nexport interface ReplyEmailParams extends EmailLocator {\n /** SMTP address of the mailbox to reply from. */\n emailAccount: string;\n /**\n * HTML inserted above the quoted original (a full document is reduced to\n * its <body> content). Optional when `templateSubject` is given.\n */\n htmlBody?: string;\n /**\n * Reply with a template email saved in the mailbox, found by subject, so\n * the caller never carries a large template's HTML itself.\n */\n templateSubject?: string;\n /** Folder holding the template. Default 'Templates'. */\n templateFolder?: string;\n /**\n * The [[SECTION]] of the template to keep, when one template holds several\n * reply variants (see composeTemplateBody). Required if it has sections.\n */\n templateSection?: string;\n /** `{{PLACEHOLDER}}` → HTML substituted into the composed body. */\n templatePlaceholders?: Readonly<Record<string, string>>;\n /**\n * An Outlook signature (by the name listOutlookSignatures reports), put in\n * the body's `{{SIGNATURE}}` placeholder, or below the new text when there\n * is none. Resolved here, so the signature's HTML never crosses the\n * caller's boundary.\n */\n signatureName?: string;\n /**\n * Answer every recipient of the original instead of only its sender.\n * Default false: widening a reply cannot be taken back, so it is opt-in.\n */\n replyAll?: boolean;\n /** Send now. Default false. */\n sendImmediately?: boolean;\n /** Drafts only: open a compose window (the default) or file silently. */\n openDraftWindow?: boolean;\n}\n\nexport interface ReplyEmailResult {\n /** Who the reply is addressed to. Windows reports Outlook's To line\n * (display names); macOS the resolved addresses. */\n to: string;\n subject: string;\n /** The original email's sender — check it is who you meant to answer. */\n repliedToSender: string;\n}\n\n// ── Per-item outcomes ────────────────────────────────────────────────────\n/** One item a batch operation could not handle, and why. */\nexport interface ItemFailure {\n entryId: string;\n /** The item's subject when it could be read, else ''. */\n subject: string;\n error: string;\n}\n\n// ── Drafts ───────────────────────────────────────────────────────────────\n/** One mail draft belonging to an account. */\nexport interface OutlookDraft {\n entryId: string;\n subject: string;\n /** The To line as Outlook renders it. */\n to: string;\n /** Recipient addresses, best effort — an unresolved Exchange entry falls back to its name. */\n toEmails: string[];\n /** Short plain-text preview, enough to tell similar drafts apart. */\n bodyPreview: string;\n hasAttachments: boolean;\n lastModified: string;\n /** The Drafts folder it sits in; one account's drafts can span two. */\n folderPath: string;\n}\n\nexport interface ListDraftsOptions {\n /** Newest-first cap on the drafts returned. Default 100. */\n limit?: number;\n /** Characters of body preview per draft. Default 300; 0 omits it. */\n previewChars?: number;\n}\n\nexport interface ListDraftsResult {\n account: string;\n /** The Drafts folders scanned, in scan order. */\n foldersScanned: string[];\n /** Matching drafts found, before `limit` was applied. */\n count: number;\n truncated: boolean;\n drafts: OutlookDraft[];\n}\n\nexport interface SendDraftsResult {\n sent: number;\n failed: ItemFailure[];\n}\n\nexport interface DeleteDraftsResult {\n deleted: number;\n failed: ItemFailure[];\n}\n\n// ── Deleting mail ────────────────────────────────────────────────────────\nexport interface DeleteMailOptions {\n /** Lift the refusal to touch Inbox and Sent Items (and their subfolders). */\n allowProtected?: boolean;\n /** Resolve and report every id without deleting anything. */\n dryRun?: boolean;\n}\n\n/** What happened to one id in a deleteOutlookEmails call. */\nexport interface DeleteMailOutcome {\n entryId: string;\n subject: string;\n /** The folder the item was actually in — the audit trail for a wrong id. */\n folderPath: string;\n status: 'deleted' | 'would-delete' | 'refused' | 'failed';\n reason: string;\n}\n\nexport interface DeleteMailResult {\n dryRun: boolean;\n deleted: number;\n refused: number;\n failed: number;\n items: DeleteMailOutcome[];\n}\n\nexport interface PurgeDeletedItemsOptions {\n /** Keep items newer than this many days. Default 0: purge everything. */\n olderThanDays?: number;\n /** Count what would be purged without destroying anything. */\n dryRun?: boolean;\n}\n\nexport interface PurgeDeletedItemsResult {\n folderPath: string;\n dryRun: boolean;\n /** Items old enough to qualify. */\n matched: number;\n purged: number;\n /** Items left because they were newer than `olderThanDays`. */\n kept: number;\n failed: number;\n}\n\n// ── Bounces ──────────────────────────────────────────────────────────────\n/** One bounce-back / non-delivery message found in a mailbox. */\nexport interface UndeliverableEmail {\n entryId: string;\n subject: string;\n senderName: string;\n senderEmail: string;\n receivedTime: string;\n /** Which rule flagged it: an NDR message class, a mail-daemon sender, or a bounce subject phrase. */\n matchedReason: string;\n /** Best-effort addresses parsed from the bounce body — the sends that failed. */\n failedRecipients: string[];\n}\n\nexport interface CleanUndeliverableOptions {\n /** How far back to scan. Default 30. */\n daysBack?: number;\n /** Report without deleting. Default TRUE — deleting has to be asked for. */\n dryRun?: boolean;\n}\n\nexport interface CleanUndeliverableResult {\n account: string;\n scannedDays: number;\n dryRun: boolean;\n matchedCount: number;\n deletedCount: number;\n matched: UndeliverableEmail[];\n /** Matched items that could not be deleted (a delete run only). */\n failed: ItemFailure[];\n}\n\nexport interface CollectBouncedRecipientsOptions {\n /** How far back to scan. Default 30. */\n daysBack?: number;\n /** Scan Deleted Items too, so bounces already cleaned away still count. Default true. */\n includeDeletedItems?: boolean;\n}\n\nexport interface SentRecipientGroupsOptions {\n /** How far back to read Sent Items. Default 30. */\n daysBack?: number;\n /** Newest-first cap on messages. Default 3000. */\n limit?: number;\n}\n\n/** One sent message and every SMTP address it went to (To, CC and BCC). */\nexport interface SentRecipientGroup {\n entryId: string;\n subject: string;\n sentOn: string;\n recipients: string[];\n}\n\nexport interface BounceReportOptions {\n /** How far back to read bounce-backs and Sent Items. Default 30. */\n daysBack?: number;\n /** Count bounces already moved to Deleted Items too. Default true. */\n includeDeletedItems?: boolean;\n}\n\n/** A sent message that at least one of its recipients bounced back from. */\nexport interface BouncedSend {\n entryId: string;\n subject: string;\n sentOn: string;\n /** Every address it went to, lower-cased and deduplicated. */\n recipients: string[];\n /** The recipients a bounce-back reported as failed. */\n failedRecipients: string[];\n /** True when every recipient failed: the message reached nobody. */\n allFailed: boolean;\n}\n\nexport interface BounceReport {\n account: string;\n scannedDays: number;\n /** Every distinct address the bounce-backs reported, lower-cased. */\n bouncedAddresses: string[];\n /** The sent messages with a bounced recipient, newest first. */\n sends: BouncedSend[];\n /**\n * Bounced addresses no sent message in the window went to: an alias the\n * server expanded, or a send older than the window.\n */\n unmatchedAddresses: string[];\n}\n\n// ── Reading ──────────────────────────────────────────────────────────────\nexport interface ReadInboxOptions {\n /**\n * Read this folder instead of the Inbox root: a folder under the Inbox by\n * name or path, a well-known folder ('Sent Items', 'Drafts', …), or a full\n * folder path — see mailFolderRef. Only that folder is read, not its\n * subfolders.\n */\n folder?: string;\n /** Only mail from the last this-many days. Default 60. */\n daysBack?: number;\n /** Newest-first cap on rows. Default 50. */\n limit?: number;\n /** Characters of plain-text body per row. Default 600; 0 skips reading bodies. */\n previewChars?: number;\n}\n\nexport interface InboxEmail extends EmailLocator {\n entryId: string;\n storeId: string;\n subject: string;\n /** For outgoing folders (Sent Items, Outbox, Drafts) these carry the\n * RECIPIENT, since a folder of mail \"from\" its own owner says nothing. */\n senderName: string;\n senderEmail: string;\n receivedTime: string;\n bodyPreview: string;\n attachmentNames: string[];\n attachmentCount: number;\n /** The folder the email was read from. */\n folderPath: string;\n}\n\nexport interface InboxSearchFilter {\n /** Only mail from the last this-many days. Default 60 — a scan has no\n * unbounded mode; ask for 365 to reach back a year. */\n daysBack?: number;\n /** Glob-style subject pattern: `*` matches any run, `?` one character,\n * case-insensitive, e.g. '*invoice*'. */\n subjectLike?: string;\n /**\n * Regular expression tested against each subject, case-insensitively\n * whatever the RegExp's own flags. On Windows the pattern runs in .NET's\n * regex engine, so keep to syntax JavaScript and .NET share.\n */\n subjectPattern?: RegExp;\n /** Drop subjects carrying a reply or forward prefix (RE:, FW:, AW:, 回复:, …). */\n excludeReplies?: boolean;\n /** Only return mail with at least one attachment. */\n requireAttachment?: boolean;\n /**\n * Folders under the Inbox to leave out, by full folder path or bare name,\n * case-insensitively. An excluded folder takes its whole subtree with it.\n * Sent, Drafts, Deleted and Junk are always skipped, even where the profile\n * nests them under the Inbox. macOS matches the leaf name only.\n */\n excludeFolders?: readonly string[];\n /**\n * Scan only these folders, given the same way. Matched exactly: naming a\n * folder does not bring its children, and the Inbox root is included only\n * when named. Exclusion wins where the two overlap.\n */\n includeFolders?: readonly string[];\n /** Return each match's full plain-text body. Default true; false makes a\n * scan much lighter when only the metadata is needed. */\n includeBody?: boolean;\n}\n\nexport interface InboxSearchMatch extends EmailLocator {\n entryId: string;\n storeId: string;\n subject: string;\n senderName: string;\n /** SMTP address, resolved from the Exchange DN where the sender is an Exchange user. */\n senderEmail: string;\n receivedTime: string;\n /** The plain-text body; '' when the search asked for no bodies. */\n body: string;\n /** Not saved to disk — pass the ones you want to saveEmailAttachments. */\n attachmentNames: string[];\n folderPath: string;\n}\n\n/**\n * What was kept about an email besides its id, for finding it again once the\n * id no longer resolves: Outlook rewrites an email's id whenever it moves, and\n * an id from one platform means nothing on the other.\n *\n * At least two of `subject`, `sender` and `receivedTime` are needed, since a\n * subject alone names every message in a thread.\n */\nexport interface EmailDescription {\n /** Compared without reply and forward prefixes, spacing or case. */\n subject?: string;\n /**\n * An address, a display name, or both (`Jo Doe <jo@example.com>`). An\n * address is compared as an address; a bare name only against the\n * sender's display name.\n */\n sender?: string;\n /** `yyyy-MM-dd HH:mm` as a listing reported it, or just the day. */\n receivedTime?: string;\n /** The mailbox to search. Default: every account, the one `folderPath` names first. */\n emailAccount?: string;\n /**\n * The folderPath a listing reported (`\\\\team@example.com\\Inbox\\Invoices`).\n * Only decides which mailbox is searched first.\n */\n folderPath?: string;\n}\n\nexport interface LocateEmailOptions {\n /** How far back to search when the description has no receivedTime. Default 60. */\n daysBack?: number;\n}\n\nexport interface SelectedEmail extends EmailLocator {\n entryId: string;\n storeId: string;\n subject: string;\n senderName: string;\n senderEmail: string;\n receivedTime: string;\n body: string;\n /** Not saved to disk — pass the ones you want to saveEmailAttachments. */\n attachmentNames: string[];\n}\n\nexport interface ReadEmailBodyOptions {\n /** Cap on the returned body. Default 8000. */\n maxChars?: number;\n /** Also return the quoted thread below the reply. Default false. */\n includeQuoted?: boolean;\n /** Cap on the quoted thread when it is returned. Default 4000. */\n maxQuotedChars?: number;\n}\n\nexport interface EmailBodyResult {\n entryId: string;\n subject: string;\n senderName: string;\n senderEmail: string;\n receivedTime: string;\n /** The sender's own new text — everything above the quoted thread. */\n body: string;\n /** True when `body` was cut at maxChars. */\n truncated: boolean;\n /** Length of the sender's new text before any cut. */\n bodyLength: number;\n /** What the quoted thread was split on; '' when none was found. */\n quoteSeparator: string;\n /** Length of the quoted thread, reported even when it isn't returned. */\n quotedLength: number;\n /** The quoted thread — only when asked for. */\n quotedOriginal: string;\n attachmentNames: string[];\n attachmentCount: number;\n}\n\n// ── Folders ──────────────────────────────────────────────────────────────\nexport interface MailFolderRef {\n /** olDefaultFolders id of the well-known root the path starts from. */\n rootId: number;\n /** That root as the caller spelled it, for messages. */\n rootLabel: string;\n /** Path segments below the root. */\n segments: string[];\n}\n\nexport interface ListFoldersOptions {\n /** How many levels below the Inbox to list, 1–10. Default 2. */\n maxDepth?: number;\n}\n\nexport interface InboxFolderInfo {\n name: string;\n /** Outlook folder path, e.g. `\\\\mailbox\\Inbox\\Invoices`. */\n folderPath: string;\n itemCount: number;\n /** 1 = direct child of the Inbox, 2 = grandchild, … */\n depth: number;\n}\n\nexport interface MoveEmailsOptions {\n /** Create the destination — the whole missing chain — when absent. Default false. */\n createIfMissing?: boolean;\n}\n\nexport interface MoveEmailsResult {\n folderPath: string;\n folderCreated: boolean;\n moved: number;\n failed: ItemFailure[];\n}\n\n// ── Attachments ──────────────────────────────────────────────────────────\nexport interface SaveAttachmentOptions {\n /**\n * Directory to save into, created if absent. Without one, each call saves\n * into a fresh private directory, so two emails that both carry\n * 'invoice.pdf' can never overwrite each other.\n */\n destDir?: string;\n}\n\nexport interface SavedAttachment {\n /** Where the file was written. A name already taken in the directory gets\n * a numbered suffix rather than overwriting what is there. */\n path: string;\n /** The attachment's name as the email carries it. */\n fileName: string;\n /** Who the email was from — confirm it is the email you meant. */\n subject: string;\n senderName: string;\n senderEmail: string;\n receivedTime: string;\n}\n\n// ── Template emails ──────────────────────────────────────────────────────\nexport interface ReadTemplatesOptions {\n /** Mailbox folder holding the templates, searched up to 3 levels deep. Default 'Templates'. */\n folder?: string;\n /** Return only the template with this subject (case-insensitive). */\n subject?: string;\n /** Return each full HTML body. Default true; false returns previews. */\n includeBody?: boolean;\n /** Newest-first cap on templates, 1–200. Default 20. */\n limit?: number;\n}\n\n/** One template email stored in a mailbox folder. */\nexport interface TemplateEmail {\n entryId: string;\n subject: string;\n /** Full HTML body with embedded (cid:) images removed; '' without includeBody. */\n htmlBody: string;\n /** Short plain-text preview; '' with includeBody. */\n bodyPreview: string;\n /** [[SECTION]] names, returned with or without the body. */\n sections: string[];\n /** `{{PLACEHOLDER}}` names the template expects filled. */\n placeholders: string[];\n lastModified: string;\n}\n\nexport interface TemplateFolderResult {\n folderFound: boolean;\n /** The folder's path when found. */\n folderPath: string;\n templates: TemplateEmail[];\n /** When the folder wasn't found: the mailbox's top-level folder names. */\n availableFolders: string[];\n}\n\nexport interface SaveTemplateParams {\n subject: string;\n htmlBody: string;\n /** Folder to save into, created at the mailbox root if absent. Default 'Templates'. */\n folder?: string;\n}\n\nexport interface SaveTemplateResult {\n folderPath: string;\n folderCreated: boolean;\n}\n\n// ── The contract ─────────────────────────────────────────────────────────\n/**\n * Everything the package does, under one signature per operation whatever the\n * platform. A platform that cannot do something says so at run time — see\n * `CapabilityMap` — rather than through a narrower type.\n */\nexport interface OutlookBridge {\n /** Every mailbox this Outlook profile can reach, as SMTP addresses. */\n getOutlookAccounts(): Promise<string[]>;\n\n /** Send an email, or stage it as a draft. */\n sendOutlookEmail(params: SendEmailParams): Promise<void>;\n\n /** Reply to an email, with the new text above the quoted original. */\n replyOutlookEmail(params: ReplyEmailParams): Promise<ReplyEmailResult>;\n\n /** Recent mail from the Inbox root or one named folder, newest first. */\n readInboxEmails(emailAccount: string, options?: ReadInboxOptions): Promise<InboxEmail[]>;\n\n /** Walk every folder under the Inbox for the mail matching `filter`. */\n searchInboxByFilter(emailAccount: string, filter?: InboxSearchFilter): Promise<InboxSearchMatch[]>;\n\n /** The email currently selected, or open, in Outlook. */\n readSelectedEmail(): Promise<SelectedEmail>;\n\n /** One email's plain-text body, split from the thread it quotes. */\n readEmailBody(email: EmailRef, options?: ReadEmailBodyOptions): Promise<EmailBodyResult>;\n\n /** Open an email in Outlook. */\n openOutlookEmail(email: EmailRef): Promise<void>;\n\n /**\n * Find an email again from what was kept about it, when its id no longer\n * resolves. Searches the Inbox and its subfolders, and returns null rather\n * than a guess: every field the description gives has to agree.\n */\n locateEmail(description: EmailDescription, options?: LocateEmailOptions): Promise<InboxSearchMatch | null>;\n\n /** The folders under an account's Inbox. */\n listInboxFolders(emailAccount: string, options?: ListFoldersOptions): Promise<InboxFolderInfo[]>;\n\n /** File emails into a folder. Moving rewrites each email's entry id. */\n moveOutlookEmails(\n emailAccount: string,\n entryIds: readonly string[],\n folder: string,\n options?: MoveEmailsOptions,\n ): Promise<MoveEmailsResult>;\n\n /** The mail drafts bound to an account, newest first. */\n listOutlookDrafts(emailAccount: string, options?: ListDraftsOptions): Promise<ListDraftsResult>;\n\n /** Send the named drafts — each has to be one of this account's drafts. */\n sendDrafts(emailAccount: string, entryIds: readonly string[]): Promise<SendDraftsResult>;\n\n /** Send every draft bound to an account. */\n sendAllDrafts(emailAccount: string): Promise<SendDraftsResult>;\n\n /** Delete the named drafts (into Deleted Items) — each has to be one of this account's drafts. */\n deleteOutlookDrafts(emailAccount: string, entryIds: readonly string[]): Promise<DeleteDraftsResult>;\n\n /** Delete mail by id into Deleted Items, refusing received and sent mail unless allowed. */\n deleteOutlookEmails(\n emailAccount: string,\n entryIds: readonly string[],\n options?: DeleteMailOptions,\n ): Promise<DeleteMailResult>;\n\n /** Permanently empty an account's Deleted Items. The one irreversible operation. */\n purgeDeletedItems(emailAccount: string, options?: PurgeDeletedItemsOptions): Promise<PurgeDeletedItemsResult>;\n\n /** Save one attachment to disk. */\n saveEmailAttachment(email: EmailRef, fileName: string, options?: SaveAttachmentOptions): Promise<SavedAttachment>;\n\n /** Save several attachments from one email, in the order named. */\n saveEmailAttachments(\n email: EmailRef,\n fileNames: readonly string[],\n options?: SaveAttachmentOptions,\n ): Promise<SavedAttachment[]>;\n\n /** Find bounce-backs in the Inbox and, unless dry-running, delete them. */\n cleanUndeliverableEmails(\n emailAccount: string,\n options?: CleanUndeliverableOptions,\n ): Promise<CleanUndeliverableResult>;\n\n /** The addresses bounce-backs report as having failed, deduplicated. */\n collectBouncedRecipients(emailAccount: string, options?: CollectBouncedRecipientsOptions): Promise<string[]>;\n\n /** Sent Items, each message with the full set of addresses it went to. */\n readSentRecipientGroups(emailAccount: string, options?: SentRecipientGroupsOptions): Promise<SentRecipientGroup[]>;\n\n /** Which sent messages bounced, and for which of their recipients. */\n readBounceReport(emailAccount: string, options?: BounceReportOptions): Promise<BounceReport>;\n\n /** The names of the Outlook signatures on this machine. */\n listOutlookSignatures(): Promise<string[]>;\n\n /** A signature's HTML, or '' when there is no signature by that name. */\n readOutlookSignatureHtml(name: string): Promise<string>;\n\n /** The template emails saved in a mailbox folder. */\n readTemplateEmails(emailAccount: string, options?: ReadTemplatesOptions): Promise<TemplateFolderResult>;\n\n /** Save a new template email. Always adds; never overwrites. */\n saveTemplateEmail(emailAccount: string, template: SaveTemplateParams): Promise<SaveTemplateResult>;\n\n /**\n * Open HTML in an Outlook compose window, wait for the person editing it to\n * save and close, and return what they saved. Has no timeout; cancel it\n * with an AbortSignal.\n */\n editEmailTemplate(label: string, currentHtml: string): Promise<string>;\n}\n\n// ── Capability discovery ─────────────────────────────────────────────────\n/** Every operation whose availability can be asked about. */\nexport type BridgeCapability = keyof OutlookBridge;\n\n/**\n * Which operations work on this machine: all of them on Windows and macOS,\n * none anywhere else. Lets a UI disable what it cannot back instead of\n * discovering the gap when a user clicks.\n */\nexport type CapabilityMap = Readonly<Record<BridgeCapability, boolean>>;\n"]}
@@ -1,2 +1,11 @@
1
- /** Retrieve all Outlook email accounts (SMTP addresses). */
1
+ /**
2
+ * Every mailbox this profile can reach, as SMTP addresses.
3
+ *
4
+ * Walks Accounts AND the top-level store folders, because they are not the same
5
+ * set: a mailbox mounted as a secondary store has no Account object, and an
6
+ * Accounts-only walk would report a profile missing exactly the mailboxes an
7
+ * operator added on purpose. A store contributes only when its name is an
8
+ * address; a data file's store is named whatever it was called ("Archive") and
9
+ * names no mailbox a caller could pass back in.
10
+ */
2
11
  export declare function getOutlookAccounts(): Promise<string[]>;
@@ -1,22 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getOutlookAccounts = getOutlookAccounts;
4
+ // The mailboxes a Windows Outlook profile can reach.
4
5
  const run_1 = require("./run");
5
- /** Retrieve all Outlook email accounts (SMTP addresses). */
6
+ const scripts_1 = require("./scripts");
7
+ const json_1 = require("../shared/json");
8
+ /**
9
+ * Every mailbox this profile can reach, as SMTP addresses.
10
+ *
11
+ * Walks Accounts AND the top-level store folders, because they are not the same
12
+ * set: a mailbox mounted as a secondary store has no Account object, and an
13
+ * Accounts-only walk would report a profile missing exactly the mailboxes an
14
+ * operator added on purpose. A store contributes only when its name is an
15
+ * address; a data file's store is named whatever it was called ("Archive") and
16
+ * names no mailbox a caller could pass back in.
17
+ */
6
18
  async function getOutlookAccounts() {
7
- if (process.platform !== 'win32')
8
- return [];
9
- const script = `
10
- $outlook = New-Object -ComObject Outlook.Application
19
+ const output = await (0, run_1.runPowerShellJson)(`${scripts_1.SESSION_PS}
20
+ $seen = @{}
11
21
  $accounts = @()
12
- foreach ($a in $outlook.Session.Accounts) {
13
- $accounts += $a.SmtpAddress
22
+ foreach ($a in $ns.Accounts) {
23
+ $address = [string]$a.SmtpAddress
24
+ if ($address -and -not $seen.ContainsKey($address.ToLower())) { $seen[$address.ToLower()] = $true; $accounts += $address }
14
25
  }
15
- $accounts -join '|'
16
- `;
17
- const result = await (0, run_1.runPowerShell)(script);
18
- if (!result)
19
- return [];
20
- return result.split('|').filter(Boolean);
26
+ foreach ($f in $ns.Folders) {
27
+ $name = [string]$f.Name
28
+ if ($name -match '@' -and -not $seen.ContainsKey($name.ToLower())) { $seen[$name.ToLower()] = $true; $accounts += $name }
29
+ }
30
+ ConvertTo-Json -Compress -InputObject @($accounts)
31
+ `, 'quick');
32
+ return (0, json_1.strList)(output);
21
33
  }
22
34
  //# sourceMappingURL=accounts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/windows/accounts.ts"],"names":[],"mappings":";;AAGA,gDAaC;AAhBD,+BAAsC;AAEtC,4DAA4D;AACrD,KAAK,UAAU,kBAAkB;IACpC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;QAAE,OAAO,EAAE,CAAC;IAC5C,MAAM,MAAM,GAAG;;;;;;;CAOlB,CAAC;IACE,MAAM,MAAM,GAAG,MAAM,IAAA,mBAAa,EAAC,MAAM,CAAC,CAAC;IAC3C,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,OAAO,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAC7C,CAAC"}
1
+ {"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/windows/accounts.ts"],"names":[],"mappings":";;AAeA,gDAeC;AA9BD,qDAAqD;AACrD,+BAA0C;AAC1C,uCAAuC;AACvC,yCAAyC;AAEzC;;;;;;;;;GASG;AACI,KAAK,UAAU,kBAAkB;IACpC,MAAM,MAAM,GAAG,MAAM,IAAA,uBAAiB,EAAC,GAAG,oBAAU;;;;;;;;;;;;CAYvD,EAAE,OAAO,CAAC,CAAC;IACR,OAAO,IAAA,cAAO,EAAC,MAAM,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["// The mailboxes a Windows Outlook profile can reach.\nimport { runPowerShellJson } from './run';\nimport { SESSION_PS } from './scripts';\nimport { strList } from '../shared/json';\n\n/**\n * Every mailbox this profile can reach, as SMTP addresses.\n *\n * Walks Accounts AND the top-level store folders, because they are not the same\n * set: a mailbox mounted as a secondary store has no Account object, and an\n * Accounts-only walk would report a profile missing exactly the mailboxes an\n * operator added on purpose. A store contributes only when its name is an\n * address; a data file's store is named whatever it was called (\"Archive\") and\n * names no mailbox a caller could pass back in.\n */\nexport async function getOutlookAccounts(): Promise<string[]> {\n const output = await runPowerShellJson(`${SESSION_PS}\n$seen = @{}\n$accounts = @()\nforeach ($a in $ns.Accounts) {\n $address = [string]$a.SmtpAddress\n if ($address -and -not $seen.ContainsKey($address.ToLower())) { $seen[$address.ToLower()] = $true; $accounts += $address }\n}\nforeach ($f in $ns.Folders) {\n $name = [string]$f.Name\n if ($name -match '@' -and -not $seen.ContainsKey($name.ToLower())) { $seen[$name.ToLower()] = $true; $accounts += $name }\n}\nConvertTo-Json -Compress -InputObject @($accounts)\n`, 'quick');\n return strList(output);\n}\n"]}
@@ -1,28 +1,13 @@
1
+ import type { SaveAttachmentsRequest } from '../backend';
1
2
  import type { SavedAttachment } from '../types';
2
3
  /**
3
- * Save an email attachment by entryId and filename, returning the saved path
4
- * together with the resolved email's subject/sender so the caller can confirm the
5
- * file came from the email it intended.
4
+ * Save the named attachments of one email, in the order named.
6
5
  *
7
- * `destDir` is created if absent. Without one the file lands in a fresh directory
8
- * of its own, because attachments keep the name the sender gave them: a single
9
- * shared folder means two emails carrying "invoice.pdf" silently overwrite each
10
- * other. Pass `destDir` whenever you want the files somewhere you control.
11
- *
12
- * When the attachment isn't found, throws an error that names the email actually
13
- * resolved (from/subject/received) and the attachments it does carry. Because
14
- * GetItemFromID happily returns a *different* message when handed a stale or wrong
15
- * EntryID (common when many replies share one subject), a bare "not found" is
16
- * misleading — this surfaces which email you're really looking at.
17
- */
18
- export declare function saveEmailAttachmentDetailed(entryId: string, fileName: string, storeId?: string, destDir?: string): Promise<SavedAttachment>;
19
- /** Save an attachment and return just the saved file path. */
20
- export declare function saveEmailAttachment(entryId: string, fileName: string, storeId?: string, destDir?: string): Promise<string>;
21
- /**
22
- * Save several attachments from one email in a single COM round trip — what a
23
- * caller working through searchInboxByFilter/readSelectedEmail results wants,
24
- * rather than paying a PowerShell process spawn per attachment. Destination,
25
- * matching and the not-found error follow saveEmailAttachmentDetailed's rules
26
- * exactly, applied per name; results come back in the same order as `fileNames`.
6
+ * Every name is matched before anything is written — exact first, then ignoring
7
+ * case and whitespace runs — so a batch with one bad name fails without having
8
+ * saved half its files. A name that matches nothing fails as NOT_FOUND naming
9
+ * the email that actually resolved and the attachments it does carry: an id can
10
+ * resolve to a different email than the caller meant, and a bare "not found"
11
+ * would point at the wrong problem.
27
12
  */
28
- export declare function saveEmailAttachments(entryId: string, fileNames: string[], storeId?: string, destDir?: string): Promise<SavedAttachment[]>;
13
+ export declare function saveEmailAttachments(request: SaveAttachmentsRequest): Promise<SavedAttachment[]>;
@@ -1,141 +1,116 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.saveEmailAttachmentDetailed = saveEmailAttachmentDetailed;
4
- exports.saveEmailAttachment = saveEmailAttachment;
5
3
  exports.saveEmailAttachments = saveEmailAttachments;
6
- // Saving attachments off an email, one at a time or in a batch.
4
+ // Saving attachments off an email.
7
5
  const run_1 = require("./run");
8
6
  const scripts_1 = require("./scripts");
9
7
  const json_1 = require("../shared/json");
10
8
  const attachmentMatch_1 = require("../shared/attachmentMatch");
11
- const runtime_1 = require("../runtime");
12
9
  const errors_1 = require("../errors");
13
10
  /**
14
- * The "not found" throw, built from the shared wording with PowerShell
15
- * interpolations in place of the values — so the sentence a Windows caller sees
16
- * is literally the same one macOS composes.
11
+ * The file-name rules from shared/attachmentMatch.ts, as PowerShell: the same
12
+ * sanitizing `safeFileName` does, and the same never-overwrite numbering as
13
+ * `uniqueSavePath`.
17
14
  */
18
- const NOT_FOUND_THROW = `throw "${(0, attachmentMatch_1.attachmentNotFoundMessage)({
19
- fileName: '$target',
20
- senderEmail: '$($item.SenderEmailAddress)',
21
- subject: '$($item.Subject)',
22
- receivedTime: '$($item.ReceivedTime)',
23
- present: '$haveStr',
24
- idLabel: 'EntryID',
25
- })}"`;
15
+ const SAVE_PATH_PS = `
16
+ $unsafeChars = ${(0, run_1.psString)(attachmentMatch_1.UNSAFE_FILE_NAME_CHARS)}
17
+ $reservedName = ${(0, run_1.psString)(attachmentMatch_1.RESERVED_FILE_NAME)}
18
+ $maxStem = ${(0, run_1.psInt)(attachmentMatch_1.MAX_FILE_STEM)}
19
+ function Get-SafeFileName([string]$name) {
20
+ $safe = [regex]::Replace($name, $unsafeChars, '_').TrimEnd([char[]]'. ')
21
+ if ($safe -match $reservedName) { $safe = '_' + $safe }
22
+ $ext = [IO.Path]::GetExtension($safe)
23
+ $stem = $safe.Substring(0, $safe.Length - $ext.Length)
24
+ if ($stem.Length -gt $maxStem) { $safe = $stem.Substring(0, $maxStem) + $ext }
25
+ if (-not $safe) { $safe = 'attachment' }
26
+ return $safe
27
+ }
28
+ function Get-UniqueSavePath([string]$dir, [string]$name) {
29
+ $ext = [IO.Path]::GetExtension($name)
30
+ $stem = $name.Substring(0, $name.Length - $ext.Length)
31
+ $candidate = [IO.Path]::Combine($dir, $name)
32
+ $n = 1
33
+ while (Test-Path -LiteralPath $candidate) {
34
+ $candidate = [IO.Path]::Combine($dir, "$stem ($n)$ext")
35
+ $n++
36
+ }
37
+ return $candidate
38
+ }
39
+ `;
26
40
  /**
27
- * Locate one attachment by name into `$found`, or throw naming the email that
28
- * actually resolved. Matching is exact first, then whitespace-normalized (trim +
29
- * collapse runs, incl. non-breaking spaces) so a trivially reformatted filename
30
- * still resolves.
41
+ * Save the named attachments of one email, in the order named.
42
+ *
43
+ * Every name is matched before anything is written — exact first, then ignoring
44
+ * case and whitespace runs — so a batch with one bad name fails without having
45
+ * saved half its files. A name that matches nothing fails as NOT_FOUND naming
46
+ * the email that actually resolved and the attachments it does carry: an id can
47
+ * resolve to a different email than the caller meant, and a bare "not found"
48
+ * would point at the wrong problem.
31
49
  */
32
- const FIND_ATTACHMENT_PS = `
50
+ async function saveEmailAttachments(request) {
51
+ const notFound = (0, attachmentMatch_1.attachmentNotFoundMessage)({
52
+ fileName: '$wanted',
53
+ senderEmail: '$senderSmtp',
54
+ subject: '$subject',
55
+ receivedTime: '$received',
56
+ present: '$present',
57
+ });
58
+ const output = await (0, run_1.runPowerShellJson)(`${scripts_1.SESSION_PS}
59
+ ${(0, scripts_1.itemLookupScript)(request.email)}
60
+ ${scripts_1.SENDER_SMTP_PS}
61
+ ${SAVE_PATH_PS}
62
+ $destDir = ${(0, run_1.psString)(request.destDir)}
63
+ $subject = ''
64
+ try { $subject = [string]$item.Subject } catch {}
65
+ $senderName = ''
66
+ try { $senderName = [string]$item.SenderName } catch {}
67
+ $received = ''
68
+ try { $received = $item.ReceivedTime.ToString('yyyy-MM-dd HH:mm') } catch {}
69
+ $attachments = @()
70
+ foreach ($att in $item.Attachments) { $attachments += $att }
71
+ $picks = @()
72
+ foreach ($wanted in ${(0, run_1.psArray)(request.fileNames)}) {
33
73
  $found = $null
34
- foreach ($att in $item.Attachments) {
35
- if ($att.FileName -eq $target) { $found = $att; break }
36
- }
74
+ foreach ($att in $attachments) { if ([string]$att.FileName -ceq $wanted) { $found = $att; break } }
37
75
  if ($found -eq $null) {
38
- $tnorm = ($target -replace '\\s+', ' ').Trim()
39
- foreach ($att in $item.Attachments) {
40
- if ((($att.FileName -replace '\\s+', ' ').Trim()) -ieq $tnorm) { $found = $att; break }
76
+ $normalized = ($wanted -replace '\\s+', ' ').Trim()
77
+ foreach ($att in $attachments) {
78
+ if ((([string]$att.FileName) -replace '\\s+', ' ').Trim() -ieq $normalized) { $found = $att; break }
41
79
  }
42
80
  }
43
81
  if ($found -eq $null) {
44
- $have = @(); foreach ($a in $item.Attachments) { $have += $a.FileName }
45
- $haveStr = if ($have.Count -gt 0) { $have -join ', ' } else { '(none)' }
46
- ${NOT_FOUND_THROW}
82
+ $present = (@($attachments | ForEach-Object { [string]$_.FileName }) -join ', ')
83
+ if (-not $present) { $present = '(none)' }
84
+ throw "${(0, errors_1.failureTag)('NOT_FOUND', 'attachment')}${notFound}"
47
85
  }
48
- `;
49
- /** The row every saver returns: the file, plus who the email was really from. */
50
- const SAVED_ROW_PS = `[PSCustomObject]@{
51
- path = $savePath
52
- subject = if ($item.Subject) { $item.Subject } else { '' }
53
- senderName = if ($item.SenderName) { $item.SenderName } else { '' }
54
- senderEmail = if ($item.SenderEmailAddress) { $item.SenderEmailAddress } else { '' }
55
- receivedTime = if ($item.ReceivedTime) { $item.ReceivedTime.ToString('yyyy-MM-dd HH:mm') } else { '' }
56
- }`;
57
- function savedAttachment(value) {
58
- const e = (0, json_1.record)(value);
59
- return {
60
- path: (0, json_1.str)(e.path),
61
- subject: (0, json_1.str)(e.subject),
62
- senderName: (0, json_1.str)(e.senderName),
63
- senderEmail: (0, json_1.str)(e.senderEmail),
64
- receivedTime: (0, json_1.str)(e.receivedTime),
65
- };
66
- }
67
- /**
68
- * Save an email attachment by entryId and filename, returning the saved path
69
- * together with the resolved email's subject/sender so the caller can confirm the
70
- * file came from the email it intended.
71
- *
72
- * `destDir` is created if absent. Without one the file lands in a fresh directory
73
- * of its own, because attachments keep the name the sender gave them: a single
74
- * shared folder means two emails carrying "invoice.pdf" silently overwrite each
75
- * other. Pass `destDir` whenever you want the files somewhere you control.
76
- *
77
- * When the attachment isn't found, throws an error that names the email actually
78
- * resolved (from/subject/received) and the attachments it does carry. Because
79
- * GetItemFromID happily returns a *different* message when handed a stale or wrong
80
- * EntryID (common when many replies share one subject), a bare "not found" is
81
- * misleading — this surfaces which email you're really looking at.
82
- */
83
- async function saveEmailAttachmentDetailed(entryId, fileName, storeId, destDir) {
84
- (0, run_1.requireWindows)();
85
- const outDir = (0, runtime_1.resolveDestDir)(destDir);
86
- const script = `
87
- $outlook = New-Object -ComObject Outlook.Application
88
- $ns = $outlook.GetNamespace('mapi')
89
- $ns.Logon()
90
- ${(0, scripts_1.getItemScript)(entryId, storeId)}
91
- if ($item -eq $null) { throw "Email not found for EntryID '${(0, run_1.psEscape)(entryId)}'" }
92
- $target = '${(0, run_1.psEscape)(fileName)}'
93
- ${FIND_ATTACHMENT_PS}
94
- $savePath = [IO.Path]::Combine('${(0, run_1.psEscape)(outDir)}', $found.FileName)
95
- $found.SaveAsFile($savePath)
96
- $out = ${SAVED_ROW_PS}
97
- ConvertTo-Json $out -Compress
98
- `;
99
- const raw = await (0, run_1.runPowerShell)(script, 15000);
100
- if (!raw || !raw.trim())
101
- throw new errors_1.NotFoundError('attachment', 'Failed to save attachment.');
102
- return savedAttachment((0, json_1.parseObject)(raw));
103
- }
104
- /** Save an attachment and return just the saved file path. */
105
- async function saveEmailAttachment(entryId, fileName, storeId, destDir) {
106
- return (await saveEmailAttachmentDetailed(entryId, fileName, storeId, destDir)).path;
86
+ $picks += $found
107
87
  }
108
- /**
109
- * Save several attachments from one email in a single COM round trip — what a
110
- * caller working through searchInboxByFilter/readSelectedEmail results wants,
111
- * rather than paying a PowerShell process spawn per attachment. Destination,
112
- * matching and the not-found error follow saveEmailAttachmentDetailed's rules
113
- * exactly, applied per name; results come back in the same order as `fileNames`.
114
- */
115
- async function saveEmailAttachments(entryId, fileNames, storeId, destDir) {
116
- (0, run_1.requireWindows)();
117
- if (fileNames.length === 0)
118
- return [];
119
- const outDir = (0, runtime_1.resolveDestDir)(destDir);
120
- const script = `
121
- $outlook = New-Object -ComObject Outlook.Application
122
- $ns = $outlook.GetNamespace('mapi')
123
- $ns.Logon()
124
- ${(0, scripts_1.getItemScript)(entryId, storeId)}
125
- if ($item -eq $null) { throw "Email not found for EntryID '${(0, run_1.psEscape)(entryId)}'" }
126
- $targets = @(${(0, run_1.psList)(fileNames)})
127
- $results = @()
128
- foreach ($target in $targets) {
129
- ${FIND_ATTACHMENT_PS}
130
- $savePath = [IO.Path]::Combine('${(0, run_1.psEscape)(outDir)}', $found.FileName)
131
- $found.SaveAsFile($savePath)
132
- $results += ${SAVED_ROW_PS}
88
+ $rows = @()
89
+ foreach ($att in $picks) {
90
+ $fileName = [string]$att.FileName
91
+ $savePath = Get-UniqueSavePath $destDir (Get-SafeFileName $fileName)
92
+ $att.SaveAsFile($savePath)
93
+ $rows += [PSCustomObject]@{
94
+ path = $savePath
95
+ fileName = $fileName
96
+ subject = $subject.Trim()
97
+ senderName = $senderName
98
+ senderEmail = $senderSmtp
99
+ receivedTime = $received
100
+ }
133
101
  }
134
- ConvertTo-Json $results -Depth 3 -Compress
135
- `;
136
- const raw = await (0, run_1.runPowerShell)(script, 15000);
137
- if (!raw || !raw.trim())
138
- throw new errors_1.NotFoundError('attachment', 'Failed to save attachments.');
139
- return (0, json_1.parseArray)(raw).map(savedAttachment);
102
+ ConvertTo-Json -Compress -Depth 3 -InputObject @($rows)
103
+ `, 'standard');
104
+ return (0, json_1.toArray)(output).map(row => {
105
+ const e = (0, json_1.record)(row);
106
+ return {
107
+ path: (0, json_1.str)(e.path),
108
+ fileName: (0, json_1.str)(e.fileName),
109
+ subject: (0, json_1.str)(e.subject),
110
+ senderName: (0, json_1.str)(e.senderName),
111
+ senderEmail: (0, json_1.str)(e.senderEmail),
112
+ receivedTime: (0, json_1.str)(e.receivedTime),
113
+ };
114
+ });
140
115
  }
141
116
  //# sourceMappingURL=attachments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"attachments.js","sourceRoot":"","sources":["../../src/windows/attachments.ts"],"names":[],"mappings":";;AAmFA,kEAwBC;AAGD,kDAOC;AASD,oDA4BC;AA1JD,gEAAgE;AAChE,+BAAwE;AACxE,uCAA0C;AAC1C,yCAAsE;AACtE,+DAAsE;AACtE,wCAA4C;AAC5C,sCAA0C;AAG1C;;;;GAIG;AACH,MAAM,eAAe,GAAG,UAAU,IAAA,2CAAyB,EAAC;IACxD,QAAQ,EAAE,SAAS;IACnB,WAAW,EAAE,6BAA6B;IAC1C,OAAO,EAAE,kBAAkB;IAC3B,YAAY,EAAE,uBAAuB;IACrC,OAAO,EAAE,UAAU;IACnB,OAAO,EAAE,SAAS;CACrB,CAAC,GAAG,CAAC;AAEN;;;;;GAKG;AACH,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;UAcjB,eAAe;;CAExB,CAAC;AAEF,iFAAiF;AACjF,MAAM,YAAY,GAAG;;;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AAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Saving attachments off an email.\nimport { psArray, psInt, psString, runPowerShellJson } from './run';\nimport { itemLookupScript, SENDER_SMTP_PS, SESSION_PS } from './scripts';\nimport { record, str, toArray } from '../shared/json';\nimport {\n attachmentNotFoundMessage,\n MAX_FILE_STEM,\n RESERVED_FILE_NAME,\n UNSAFE_FILE_NAME_CHARS,\n} from '../shared/attachmentMatch';\nimport { failureTag } from '../errors';\nimport type { SaveAttachmentsRequest } from '../backend';\nimport type { SavedAttachment } from '../types';\n\n/**\n * The file-name rules from shared/attachmentMatch.ts, as PowerShell: the same\n * sanitizing `safeFileName` does, and the same never-overwrite numbering as\n * `uniqueSavePath`.\n */\nconst SAVE_PATH_PS = `\n$unsafeChars = ${psString(UNSAFE_FILE_NAME_CHARS)}\n$reservedName = ${psString(RESERVED_FILE_NAME)}\n$maxStem = ${psInt(MAX_FILE_STEM)}\nfunction Get-SafeFileName([string]$name) {\n $safe = [regex]::Replace($name, $unsafeChars, '_').TrimEnd([char[]]'. ')\n if ($safe -match $reservedName) { $safe = '_' + $safe }\n $ext = [IO.Path]::GetExtension($safe)\n $stem = $safe.Substring(0, $safe.Length - $ext.Length)\n if ($stem.Length -gt $maxStem) { $safe = $stem.Substring(0, $maxStem) + $ext }\n if (-not $safe) { $safe = 'attachment' }\n return $safe\n}\nfunction Get-UniqueSavePath([string]$dir, [string]$name) {\n $ext = [IO.Path]::GetExtension($name)\n $stem = $name.Substring(0, $name.Length - $ext.Length)\n $candidate = [IO.Path]::Combine($dir, $name)\n $n = 1\n while (Test-Path -LiteralPath $candidate) {\n $candidate = [IO.Path]::Combine($dir, \"$stem ($n)$ext\")\n $n++\n }\n return $candidate\n}\n`;\n\n/**\n * Save the named attachments of one email, in the order named.\n *\n * Every name is matched before anything is written — exact first, then ignoring\n * case and whitespace runs — so a batch with one bad name fails without having\n * saved half its files. A name that matches nothing fails as NOT_FOUND naming\n * the email that actually resolved and the attachments it does carry: an id can\n * resolve to a different email than the caller meant, and a bare \"not found\"\n * would point at the wrong problem.\n */\nexport async function saveEmailAttachments(request: SaveAttachmentsRequest): Promise<SavedAttachment[]> {\n const notFound = attachmentNotFoundMessage({\n fileName: '$wanted',\n senderEmail: '$senderSmtp',\n subject: '$subject',\n receivedTime: '$received',\n present: '$present',\n });\n const output = await runPowerShellJson(`${SESSION_PS}\n${itemLookupScript(request.email)}\n${SENDER_SMTP_PS}\n${SAVE_PATH_PS}\n$destDir = ${psString(request.destDir)}\n$subject = ''\ntry { $subject = [string]$item.Subject } catch {}\n$senderName = ''\ntry { $senderName = [string]$item.SenderName } catch {}\n$received = ''\ntry { $received = $item.ReceivedTime.ToString('yyyy-MM-dd HH:mm') } catch {}\n$attachments = @()\nforeach ($att in $item.Attachments) { $attachments += $att }\n$picks = @()\nforeach ($wanted in ${psArray(request.fileNames)}) {\n $found = $null\n foreach ($att in $attachments) { if ([string]$att.FileName -ceq $wanted) { $found = $att; break } }\n if ($found -eq $null) {\n $normalized = ($wanted -replace '\\\\s+', ' ').Trim()\n foreach ($att in $attachments) {\n if ((([string]$att.FileName) -replace '\\\\s+', ' ').Trim() -ieq $normalized) { $found = $att; break }\n }\n }\n if ($found -eq $null) {\n $present = (@($attachments | ForEach-Object { [string]$_.FileName }) -join ', ')\n if (-not $present) { $present = '(none)' }\n throw \"${failureTag('NOT_FOUND', 'attachment')}${notFound}\"\n }\n $picks += $found\n}\n$rows = @()\nforeach ($att in $picks) {\n $fileName = [string]$att.FileName\n $savePath = Get-UniqueSavePath $destDir (Get-SafeFileName $fileName)\n $att.SaveAsFile($savePath)\n $rows += [PSCustomObject]@{\n path = $savePath\n fileName = $fileName\n subject = $subject.Trim()\n senderName = $senderName\n senderEmail = $senderSmtp\n receivedTime = $received\n }\n}\nConvertTo-Json -Compress -Depth 3 -InputObject @($rows)\n`, 'standard');\n return toArray(output).map(row => {\n const e = record(row);\n return {\n path: str(e.path),\n fileName: str(e.fileName),\n subject: str(e.subject),\n senderName: str(e.senderName),\n senderEmail: str(e.senderEmail),\n receivedTime: str(e.receivedTime),\n };\n });\n}\n"]}
@@ -1,34 +1,21 @@
1
+ import type { CleanUndeliverableRequest, CollectBouncesRequest, SentGroupsRequest } from '../backend';
1
2
  import type { CleanUndeliverableResult, SentRecipientGroup } from '../types';
2
3
  /**
3
- * Scan an account's inbox for bounce-back / non-delivery messages — Outlook NDRs,
4
- * mail-daemon/postmaster rejections, and "Message blocked"-style Google/O365
5
- * failure notices — and, unless previewing, move each to Deleted Items (recoverable).
4
+ * Scan an account's Inbox for bounce-backs and, unless dry-running, move each to
5
+ * Deleted Items (recoverable).
6
6
  *
7
- * Classification is deliberately conservative so ordinary mail that merely
8
- * mentions "delivery" is never caught: an item matches only when its
9
- * MessageClass is an NDR report, its sender fingerprints as a mail-delivery
10
- * daemon/postmaster, or its subject contains a specific bounce phrase.
11
- *
12
- * Matched item references are snapshotted before any Delete() call — deleting
13
- * mutates the folder collection, so deleting mid-enumeration would skip items
14
- * (same pattern as sendAllDrafts).
7
+ * Matched items are collected before the first Delete(): deleting shifts the
8
+ * collection, and deleting mid-enumeration would skip items.
15
9
  */
16
- export declare function cleanUndeliverableEmails(emailAccount: string, daysBack?: number, dryRun?: boolean): Promise<CleanUndeliverableResult>;
10
+ export declare function cleanUndeliverableEmails(request: CleanUndeliverableRequest): Promise<CleanUndeliverableResult>;
17
11
  /**
18
- * Read-only scan of an account's Inbox (and, when scanDeleted, its Deleted Items)
19
- * for bounce messages, returning just the deduped set of failed recipient
20
- * addresses. Uses the same conservative classifier as cleanUndeliverableEmails.
21
- *
22
- * Deleted Items is included so this still works after cleanUndeliverableEmails has
23
- * already filed the bounces there — the blacklist step doesn't depend on running
24
- * before the cleanup. This never deletes anything.
12
+ * The deduplicated addresses bounce-backs report as failed, from the Inbox and,
13
+ * optionally, Deleted Items — so it still works after the bounces were cleaned
14
+ * away. Never deletes anything.
25
15
  */
26
- export declare function collectBouncedRecipients(emailAccount: string, daysBack?: number, scanDeleted?: boolean): Promise<string[]>;
16
+ export declare function collectBouncedRecipients(request: CollectBouncesRequest): Promise<string[]>;
27
17
  /**
28
- * Read the account's Sent Items within the window, returning each mail with the
29
- * full SMTP address set it was sent to (To + CC + BCC), newest first. This is how
30
- * the "was every address for this contact tried?" question gets answered: where a
31
- * blast sends one email per organization addressed to all of its addresses, a sent
32
- * message's recipient set IS that organization's full address set.
18
+ * Sent Items within the window, each message with the full SMTP address set it
19
+ * went to (To + CC + BCC), newest first.
33
20
  */
34
- export declare function readSentRecipientGroups(emailAccount: string, daysBack?: number, limit?: number): Promise<SentRecipientGroup[]>;
21
+ export declare function readSentRecipientGroups(request: SentGroupsRequest): Promise<SentRecipientGroup[]>;