@dawnlit/outlook-bridge 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -9
- package/dist/backend.d.ts +2 -2
- package/dist/backend.js.map +1 -1
- package/dist/bridge.js +3 -3
- package/dist/bridge.js.map +1 -1
- package/dist/errors.d.ts +17 -8
- package/dist/errors.js +17 -13
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/mac/accounts.d.ts +4 -0
- package/dist/mac/accounts.js +10 -0
- package/dist/mac/accounts.js.map +1 -1
- package/dist/mac/attachments.js +1 -1
- package/dist/mac/attachments.js.map +1 -1
- package/dist/mac/bounces.js +18 -31
- package/dist/mac/bounces.js.map +1 -1
- package/dist/mac/cleanup.d.ts +11 -3
- package/dist/mac/cleanup.js +30 -58
- package/dist/mac/cleanup.js.map +1 -1
- package/dist/mac/drafts.d.ts +3 -1
- package/dist/mac/drafts.js +37 -49
- package/dist/mac/drafts.js.map +1 -1
- package/dist/mac/folders.d.ts +10 -3
- package/dist/mac/folders.js +31 -23
- package/dist/mac/folders.js.map +1 -1
- package/dist/mac/profile.d.ts +12 -0
- package/dist/mac/profile.js +75 -1
- package/dist/mac/profile.js.map +1 -1
- package/dist/mac/read.d.ts +4 -0
- package/dist/mac/read.js +68 -42
- package/dist/mac/read.js.map +1 -1
- package/dist/mac/run.d.ts +19 -5
- package/dist/mac/run.js +49 -9
- package/dist/mac/run.js.map +1 -1
- package/dist/mac/scripts.d.ts +67 -14
- package/dist/mac/scripts.js +150 -31
- package/dist/mac/scripts.js.map +1 -1
- package/dist/mac/send.d.ts +5 -4
- package/dist/mac/send.js +52 -14
- package/dist/mac/send.js.map +1 -1
- package/dist/mac/templates.js +16 -22
- package/dist/mac/templates.js.map +1 -1
- package/dist/mail.d.ts +11 -3
- package/dist/mail.js +25 -6
- package/dist/mail.js.map +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/shared/args.js.map +1 -1
- package/dist/shared/attachmentMatch.d.ts +0 -6
- package/dist/shared/attachmentMatch.js +0 -1
- package/dist/shared/attachmentMatch.js.map +1 -1
- package/dist/shared/exec.js.map +1 -1
- package/dist/shared/locate.d.ts +0 -8
- package/dist/shared/locate.js +0 -1
- package/dist/shared/locate.js.map +1 -1
- package/dist/shared/replyBody.d.ts +0 -15
- package/dist/shared/replyBody.js +0 -2
- package/dist/shared/replyBody.js.map +1 -1
- package/dist/shared/templateLimits.d.ts +14 -0
- package/dist/shared/templateLimits.js +21 -0
- package/dist/shared/templateLimits.js.map +1 -0
- package/dist/templateBody.d.ts +6 -0
- package/dist/templateBody.js +8 -1
- package/dist/templateBody.js.map +1 -1
- package/dist/types.d.ts +43 -7
- package/dist/types.js.map +1 -1
- package/dist/windows/accounts.js +1 -1
- package/dist/windows/accounts.js.map +1 -1
- package/dist/windows/attachments.js +2 -2
- package/dist/windows/attachments.js.map +1 -1
- package/dist/windows/bounces.js +7 -7
- package/dist/windows/bounces.js.map +1 -1
- package/dist/windows/cleanup.d.ts +5 -1
- package/dist/windows/cleanup.js +18 -15
- package/dist/windows/cleanup.js.map +1 -1
- package/dist/windows/drafts.d.ts +4 -4
- package/dist/windows/drafts.js +22 -33
- package/dist/windows/drafts.js.map +1 -1
- package/dist/windows/folders.js +2 -2
- package/dist/windows/folders.js.map +1 -1
- package/dist/{shared → windows}/json.d.ts +11 -6
- package/dist/{shared → windows}/json.js +12 -7
- package/dist/windows/json.js.map +1 -0
- package/dist/windows/read.js +23 -16
- package/dist/windows/read.js.map +1 -1
- package/dist/windows/run.d.ts +0 -2
- package/dist/windows/run.js +1 -2
- package/dist/windows/run.js.map +1 -1
- package/dist/windows/scripts.d.ts +10 -4
- package/dist/windows/scripts.js +21 -12
- package/dist/windows/scripts.js.map +1 -1
- package/dist/windows/send.d.ts +13 -4
- package/dist/windows/send.js +24 -6
- package/dist/windows/send.js.map +1 -1
- package/dist/windows/templates.js +11 -17
- package/dist/windows/templates.js.map +1 -1
- package/package.json +2 -2
- package/dist/shared/json.js.map +0 -1
package/dist/templateBody.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templateBody.js","sourceRoot":"","sources":["../src/templateBody.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;AAqEH,kDAuBC;AAmFD,oCASC;AAQD,0CAQC;AAsBD,gCAGC;AAQD,gDAUC;AAiBD,kDAkEC;AApUD,qCAA+C;AAE/C,kFAAkF;AAClF,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,GAAG,GAAG,kDAAkD,CAAC;AAE/D,uFAAuF;AACvF,MAAM,UAAU,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAEtC;;;;;;;;;;GAUG;AACH,MAAM,SAAS,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAEpC,SAAS,QAAQ,CAAC,CAAS;IACvB,OAAO,CAAC,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEnD,SAAS,WAAW,CAAC,KAAa;IAC9B,IAAI,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,IAAI,CAAC,KAAK,EAAE,CAAC;QACT,KAAK,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;QACjE,gBAAgB,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,sFAAsF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C,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1F,CAAC;IAED,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QAClB,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChD,CAAC,CAAC,sCAAsC;YACxC,CAAC,CAAC,gEAAgE,CAAC;QACvE,MAAM,IAAI,4BAAmB,CACzB,GAAG,KAAK,uDAAuD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,uBAAuB,CACrH,CAAC;IACN,CAAC;IACD,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["/**\n * Sections and placeholders in HTML email templates.\n *\n * A template email is an ordinary saved mail its owner edits in Outlook, so the\n * greeting, closing and signature stay theirs. Where one template serves several\n * kinds of reply, the variants live inside it between markers:\n *\n * Hello,\n * [[ACCEPT]] Thank you — we accept... [[/ACCEPT]]\n * [[DECLINE]] Thank you for letting us know... [[/DECLINE]]\n * [[CLARIFY]] {{QUESTIONS}} [[/CLARIFY]]\n * Best regards, {{SIGNATURE}}\n *\n * Composing keeps the requested section, drops the others, and substitutes the\n * `{{PLACEHOLDER}}`s — so shared wording is written once and a caller names a\n * section instead of carrying the whole body.\n *\n * Everything works on the raw HTML string rather than a parsed tree: Word's\n * markup carries conditional comments and namespaced tags a parser round-trip\n * would rewrite, and the composed body must stay byte-identical to what was\n * written.\n */\n\nimport { InvalidRequestError } from './errors';\n\n/** Marker and placeholder names: what a person can reasonably type in Outlook. */\nconst NAME = '[A-Za-z0-9_-]{1,40}';\n\n/**\n * What Word may inject *between two characters of a marker*: tags (it splits\n * runs across <span>s freely), comments, non-breaking spaces, and the newlines\n * it wraps long lines with — sometimes mid-word. So `[[ACCEPT]]` is matched\n * character by character with this between, never as a literal string.\n */\nconst GAP = '(?:<!--[\\\\s\\\\S]*?-->|<[^>]*>| | |\\\\s)*';\n\n/** Block elements a marker can sit alone inside; the whole block goes when it does. */\nconst BLOCK_TAGS = ['p', 'div', 'li'];\n\n/**\n * Block elements that make up one *line* of a template, for a token whose\n * empty value takes its whole line out (see `removeTokenLine`). Outermost\n * first: Word puts a <p> inside every table cell, so a token in a details table\n * has to drop the <tr> — dropping the <p> would leave the row's label beside a\n * blank cell.\n *\n * <div> is deliberately absent: it is rarely a line and often the wrapper around\n * the entire body, so a token directly inside one would take the whole email\n * with it. Deleting just the token is the safer miss.\n */\nconst LINE_TAGS = ['tr', 'li', 'p'];\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Tag-tolerant matcher for one literal token, e.g. `[[/ACCEPT]]` or `{{QUESTIONS}}`.\n *\n * Memoized: the pattern interleaves `GAP` between every character, so a short\n * token compiles to hundreds of characters, and the replace loops ask for the\n * same token repeatedly while walking a template.\n */\nconst markerRegexCache = new Map<string, RegExp>();\n\nfunction markerRegex(token: string): RegExp {\n let regex = markerRegexCache.get(token);\n if (!regex) {\n regex = new RegExp(token.split('').map(escapeRe).join(GAP), 'i');\n markerRegexCache.set(token, regex);\n }\n return regex;\n}\n\n/** HTML → rough plain text, enough to spot markers and test a block for emptiness. */\nfunction stripToText(html: string): string {\n return html\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/<[^>]*>/g, '')\n .replace(/ | /gi, ' ');\n}\n\nexport interface TemplateMarkers {\n /** Section names with both an opening and a closing marker, in document order. */\n sections: string[];\n /** `{{NAME}}` placeholders found anywhere in the template. */\n placeholders: string[];\n}\n\n/** Find the markers in a template body (HTML, or the plain text Outlook derives from it). */\nexport function findTemplateMarkers(body: string): TemplateMarkers {\n const text = stripToText(body || '');\n const opened: string[] = [];\n const closed = new Set<string>();\n const seen = new Set<string>();\n const sectionRe = new RegExp(`\\\\[\\\\[\\\\s*(/?)\\\\s*(${NAME})\\\\s*\\\\]\\\\]`, 'g');\n let m: RegExpExecArray | null;\n while ((m = sectionRe.exec(text)) !== null) {\n const name = m[2].toUpperCase();\n if (m[1]) {\n closed.add(name);\n } else if (!seen.has(name)) {\n seen.add(name);\n opened.push(name);\n }\n }\n const placeholders: string[] = [];\n const placeholderRe = new RegExp(`\\\\{\\\\{\\\\s*(${NAME})\\\\s*\\\\}\\\\}`, 'g');\n while ((m = placeholderRe.exec(text)) !== null) {\n const name = m[1].toUpperCase();\n if (!placeholders.includes(name)) placeholders.push(name);\n }\n return {sections: opened.filter(n => closed.has(n)), placeholders};\n}\n\n/**\n * Every `[[...]]` / `{{...}}` token still in a body, paired or not — the last\n * check before a composed body goes out, so a half-deleted marker stops the\n * send instead of reaching a recipient.\n */\nfunction markerTokens(body: string): string[] {\n const text = stripToText(body || '');\n const re = new RegExp(`\\\\[\\\\[\\\\s*/?\\\\s*${NAME}\\\\s*\\\\]\\\\]|\\\\{\\\\{\\\\s*${NAME}\\\\s*\\\\}\\\\}`, 'g');\n const found: string[] = [];\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n const token = m[0].replace(/\\s+/g, '');\n if (!found.includes(token)) found.push(token);\n }\n return found;\n}\n\ninterface Span {\n start: number;\n end: number;\n}\n\n/**\n * The nearest enclosing block element of [start, end), or null when the marker\n * isn't inside one. The closing tag is the first of the same name after the\n * marker — Word doesn't nest <p>, and where that guess is wrong the emptiness\n * test simply fails and the caller falls back to the marker's own span.\n */\nfunction enclosingBlock(html: string, start: number, end: number, tags: string[] = BLOCK_TAGS): {\n block: Span;\n contentStart: number;\n contentEnd: number;\n} | null {\n let best: { idx: number; contentStart: number; tag: string } | null = null;\n for (const tag of tags) {\n const openRe = new RegExp(`<${tag}(?:\\\\s[^>]*)?>`, 'gi');\n let m: RegExpExecArray | null;\n while ((m = openRe.exec(html)) !== null) {\n if (m.index >= start) break;\n if (!best || m.index > best.idx) {\n best = {idx: m.index, contentStart: m.index + m[0].length, tag};\n }\n }\n }\n if (!best) return null;\n const closeRe = new RegExp(`</${best.tag}\\\\s*>`, 'gi');\n closeRe.lastIndex = end;\n const close = closeRe.exec(html);\n if (!close) return null;\n return {\n block: {start: best.idx, end: close.index + close[0].length},\n contentStart: best.contentStart,\n contentEnd: close.index,\n };\n}\n\n/**\n * What to delete for a marker: its whole paragraph when the marker is alone in\n * it (removing only the text would leave a blank line), else just the marker.\n */\nfunction markerSpan(html: string, start: number, end: number): Span {\n const found = enclosingBlock(html, start, end);\n if (!found || found.contentStart > start || found.contentEnd < end) return {start, end};\n const rest = html.slice(found.contentStart, start) + html.slice(end, found.contentEnd);\n return stripToText(rest).trim() === '' ? found.block : {start, end};\n}\n\nfunction locate(html: string, token: string): Span | null {\n const m = markerRegex(token).exec(html);\n return m ? {start: m.index, end: m.index + m[0].length} : null;\n}\n\n// ── Single-token fill ───────────────────────────────────────────────────\n//\n// The section machinery above is for templates holding several variants of\n// one email. These are for the simpler case: fixed wording with details typed\n// elsewhere and dropped into tokens of the caller's own choosing (`{Name}`,\n// `%NAME%`, …). Same tag-tolerant matching, since these templates are edited in\n// Outlook too.\n\n/** Replace every occurrence of `token` with `value`, which is never rescanned. */\nexport function replaceToken(html: string, token: string, value: string): string {\n let done = '';\n let rest = html;\n for (; ;) {\n const at = locate(rest, token);\n if (!at) return done + rest;\n done += rest.slice(0, at.start) + value;\n rest = rest.slice(at.end);\n }\n}\n\n/**\n * Remove `token` together with the line it sits on — the table row or\n * paragraph, label included. For an optional detail this is the difference\n * between the email not mentioning it and a heading with nothing under it.\n * Falls back to deleting just the token when it isn't inside a line element.\n */\nexport function removeTokenLine(html: string, token: string): string {\n let out = html;\n for (; ;) {\n const at = locate(out, token);\n if (!at) return out;\n const cut = lineSpan(out, at);\n out = out.slice(0, cut.start) + out.slice(cut.end);\n }\n}\n\n/**\n * The line to delete for a token at `at`: its enclosing row or paragraph, or\n * the token's own span when it isn't in one.\n *\n * `enclosingBlock` returns the *nearest* opening tag before the token, which is\n * only the enclosing one if it hasn't been closed already — a token in a\n * paragraph after a table has a `<tr>` before it and a `</tr>` after it without\n * being inside a row, and taking that span would delete the table.\n */\nfunction lineSpan(html: string, at: Span): Span {\n for (const tag of LINE_TAGS) {\n const found = enclosingBlock(html, at.start, at.end, [tag]);\n if (!found) continue;\n const closedBefore = new RegExp(`</${tag}\\\\s*>`, 'i').test(html.slice(found.contentStart, at.start));\n if (!closedBefore) return found.block;\n }\n return at;\n}\n\n/** Which of `tokens` the template actually uses — what the caller has to supply. */\nexport function findTokens(html: string, tokens: readonly string[]): string[] {\n const text = stripToText(html || '');\n return tokens.filter(token => markerRegex(token).test(text));\n}\n\n/**\n * `{Token}`-shaped text still in a filled-in body: a placeholder misspelled\n * while editing, or one nothing supplied. Reads visible text only, so the\n * braces of a <style> block are not mistaken for placeholders. Catches a\n * leftover `{{TOKEN}}` too, reported by its inner `{TOKEN}`.\n */\nexport function findUnfilledTokens(html: string): string[] {\n const text = stripToText((html || '').replace(/<(style|script)\\b[^>]*>[\\s\\S]*?<\\/\\1>/gi, ''));\n const found: string[] = [];\n const re = /\\{\\s*([A-Za-z][A-Za-z0-9 _-]{0,30})\\s*\\}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n const token = `{${m[1].trim()}}`;\n if (!found.includes(token)) found.push(token);\n }\n return found;\n}\n\nexport interface ComposeOptions {\n /** Section to keep; the other sections are dropped with their markers. */\n section?: string;\n /** `{{NAME}}` → HTML to substitute. Names match case-insensitively. */\n placeholders?: Readonly<Record<string, string>>;\n /** The template's name, for error messages. */\n label?: string;\n}\n\n/**\n * Reduce a template body to the one email that goes out: keep `section`, drop\n * the rest, fill the placeholders. Throws INVALID_REQUEST rather than guessing —\n * a template edited into an unusable state has to stop the send, not deliver a\n * body with `[[ACCEPT]]` or an unfilled placeholder in it.\n */\nexport function composeTemplateBody(html: string, options: ComposeOptions = {}): string {\n const label = options.label ? `Template '${options.label}'` : 'The template';\n const wanted = (options.section || '').trim().toUpperCase();\n const {sections, placeholders: available} = findTemplateMarkers(html);\n\n if (wanted && !sections.includes(wanted)) {\n throw new InvalidRequestError(\n sections.length\n ? `${label} has no [[${wanted}]] section. Sections found: ${sections.join(', ')}.`\n : `${label} has no [[${wanted}]]...[[/${wanted}]] markers — it holds a single body, so name no section (or add the markers to the template).`,\n );\n }\n if (!wanted && sections.length) {\n throw new InvalidRequestError(\n `${label} is split into sections (${sections.join(', ')}); name the one to send, `\n + 'otherwise the email would go out with every variant and the markers in it.',\n );\n }\n\n // Deletions are collected first and applied right to left, so each span's\n // offsets still refer to the string they were measured against.\n const cuts: Span[] = [];\n for (const name of sections) {\n const open = locate(html, `[[${name}]]`);\n const close = locate(html, `[[/${name}]]`);\n if (!open || !close || close.start < open.end) {\n throw new InvalidRequestError(`${label} has a malformed [[${name}]] section — expected [[${name}]] ... [[/${name}]] in that order.`);\n }\n const openSpan = markerSpan(html, open.start, open.end);\n const closeSpan = markerSpan(html, close.start, close.end);\n if (name === wanted) {\n cuts.push(openSpan, closeSpan); // keep the content, shed the markers\n } else {\n cuts.push({start: openSpan.start, end: closeSpan.end});\n }\n }\n let out = html;\n for (const cut of cuts.sort((a, b) => b.start - a.start)) {\n out = out.slice(0, cut.start) + out.slice(cut.end);\n }\n\n for (const [rawKey, value] of Object.entries(options.placeholders || {})) {\n const key = rawKey.trim().toUpperCase();\n if (!available.includes(key)) {\n throw new InvalidRequestError(\n `${label} has no {{${key}}} placeholder`\n + (available.length ? ` (found: ${available.map(p => `{{${p}}}`).join(', ')}).` : '.')\n + ' It may have been removed when the template was last edited.',\n );\n }\n const m = markerRegex(`{{${key}}}`).exec(out);\n // In the template but gone from `out` means it lived in a dropped\n // section: the caller supplying more than one variant needs, not an error.\n if (m) out = out.slice(0, m.index) + (value ?? '') + out.slice(m.index + m[0].length);\n }\n\n const leftover = markerTokens(out);\n if (leftover.length) {\n const hint = leftover.every(t => t.startsWith('{{'))\n ? 'Supply a value for each placeholder.'\n : 'Check the template — every [[SECTION]] needs its [[/SECTION]].';\n throw new InvalidRequestError(\n `${label} still contains unresolved markers after composing: ${leftover.join(', ')}. ${hint} Nothing was created.`,\n );\n }\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"templateBody.js","sourceRoot":"","sources":["../src/templateBody.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;AAqEH,kDAuBC;AA0FD,oCASC;AAQD,0CAQC;AAsBD,gCAGC;AAQD,gDAUC;AAiBD,kDAkEC;AA3UD,qCAA+C;AAE/C,kFAAkF;AAClF,MAAM,IAAI,GAAG,qBAAqB,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,GAAG,GAAG,kDAAkD,CAAC;AAE/D,uFAAuF;AACvF,MAAM,UAAU,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAEtC;;;;;;;;;;GAUG;AACH,MAAM,SAAS,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAEpC,SAAS,QAAQ,CAAC,CAAS;IACvB,OAAO,CAAC,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEnD,SAAS,WAAW,CAAC,KAAa;IAC9B,IAAI,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,IAAI,CAAC,KAAK,EAAE,CAAC;QACT,KAAK,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAA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,MAAM,CAAC,GAAG,WAAW,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC9C,kEAAkE;QAClE,2EAA2E;QAC3E,IAAI,CAAC;YAAE,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1F,CAAC;IAED,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QAClB,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChD,CAAC,CAAC,sCAAsC;YACxC,CAAC,CAAC,gEAAgE,CAAC;QACvE,MAAM,IAAI,4BAAmB,CACzB,GAAG,KAAK,uDAAuD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,uBAAuB,CACrH,CAAC;IACN,CAAC;IACD,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["/**\n * Sections and placeholders in HTML email templates.\n *\n * A template email is an ordinary saved mail its owner edits in Outlook, so the\n * greeting, closing and signature stay theirs. Where one template serves several\n * kinds of reply, the variants live inside it between markers:\n *\n * Hello,\n * [[ACCEPT]] Thank you — we accept... [[/ACCEPT]]\n * [[DECLINE]] Thank you for letting us know... [[/DECLINE]]\n * [[CLARIFY]] {{QUESTIONS}} [[/CLARIFY]]\n * Best regards, {{SIGNATURE}}\n *\n * Composing keeps the requested section, drops the others, and substitutes the\n * `{{PLACEHOLDER}}`s — so shared wording is written once and a caller names a\n * section instead of carrying the whole body.\n *\n * Everything works on the raw HTML string rather than a parsed tree: Word's\n * markup carries conditional comments and namespaced tags a parser round-trip\n * would rewrite, and the composed body must stay byte-identical to what was\n * written.\n */\n\nimport { InvalidRequestError } from './errors';\n\n/** Marker and placeholder names: what a person can reasonably type in Outlook. */\nconst NAME = '[A-Za-z0-9_-]{1,40}';\n\n/**\n * What Word may inject *between two characters of a marker*: tags (it splits\n * runs across <span>s freely), comments, non-breaking spaces, and the newlines\n * it wraps long lines with — sometimes mid-word. So `[[ACCEPT]]` is matched\n * character by character with this between, never as a literal string.\n */\nconst GAP = '(?:<!--[\\\\s\\\\S]*?-->|<[^>]*>| | |\\\\s)*';\n\n/** Block elements a marker can sit alone inside; the whole block goes when it does. */\nconst BLOCK_TAGS = ['p', 'div', 'li'];\n\n/**\n * Block elements that make up one *line* of a template, for a token whose\n * empty value takes its whole line out (see `removeTokenLine`). Outermost\n * first: Word puts a <p> inside every table cell, so a token in a details table\n * has to drop the <tr> — dropping the <p> would leave the row's label beside a\n * blank cell.\n *\n * <div> is deliberately absent: it is rarely a line and often the wrapper around\n * the entire body, so a token directly inside one would take the whole email\n * with it. Deleting just the token is the safer miss.\n */\nconst LINE_TAGS = ['tr', 'li', 'p'];\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Tag-tolerant matcher for one literal token, e.g. `[[/ACCEPT]]` or `{{QUESTIONS}}`.\n *\n * Memoized: the pattern interleaves `GAP` between every character, so a short\n * token compiles to hundreds of characters, and the replace loops ask for the\n * same token repeatedly while walking a template.\n */\nconst markerRegexCache = new Map<string, RegExp>();\n\nfunction markerRegex(token: string): RegExp {\n let regex = markerRegexCache.get(token);\n if (!regex) {\n regex = new RegExp(token.split('').map(escapeRe).join(GAP), 'i');\n markerRegexCache.set(token, regex);\n }\n return regex;\n}\n\n/** HTML → rough plain text, enough to spot markers and test a block for emptiness. */\nfunction stripToText(html: string): string {\n return html\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/<[^>]*>/g, '')\n .replace(/ | /gi, ' ');\n}\n\nexport interface TemplateMarkers {\n /** Section names with both an opening and a closing marker, in document order. */\n sections: string[];\n /** `{{NAME}}` placeholders found anywhere in the template. */\n placeholders: string[];\n}\n\n/** Find the markers in a template body (HTML, or the plain text Outlook derives from it). */\nexport function findTemplateMarkers(body: string): TemplateMarkers {\n const text = stripToText(body || '');\n const opened: string[] = [];\n const closed = new Set<string>();\n const seen = new Set<string>();\n const sectionRe = new RegExp(`\\\\[\\\\[\\\\s*(/?)\\\\s*(${NAME})\\\\s*\\\\]\\\\]`, 'g');\n let m: RegExpExecArray | null;\n while ((m = sectionRe.exec(text)) !== null) {\n const name = m[2].toUpperCase();\n if (m[1]) {\n closed.add(name);\n } else if (!seen.has(name)) {\n seen.add(name);\n opened.push(name);\n }\n }\n const placeholders: string[] = [];\n const placeholderRe = new RegExp(`\\\\{\\\\{\\\\s*(${NAME})\\\\s*\\\\}\\\\}`, 'g');\n while ((m = placeholderRe.exec(text)) !== null) {\n const name = m[1].toUpperCase();\n if (!placeholders.includes(name)) placeholders.push(name);\n }\n return { sections: opened.filter(n => closed.has(n)), placeholders };\n}\n\n/**\n * Any `[[SECTION]]`, `[[/SECTION]]` or `{{PLACEHOLDER}}` token, paired or not, as\n * a pattern source JavaScript and .NET read the same way: Windows scans a\n * template's plain text with it inside PowerShell.\n */\nexport const MARKER_TOKEN_SOURCE = `\\\\[\\\\[\\\\s*/?\\\\s*${NAME}\\\\s*\\\\]\\\\]|\\\\{\\\\{\\\\s*${NAME}\\\\s*\\\\}\\\\}`;\n\n/**\n * Every `[[...]]` / `{{...}}` token still in a body, paired or not — the last\n * check before a composed body goes out, so a half-deleted marker stops the\n * send instead of reaching a recipient.\n */\nfunction markerTokens(body: string): string[] {\n const text = stripToText(body || '');\n const re = new RegExp(MARKER_TOKEN_SOURCE, 'g');\n const found: string[] = [];\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n const token = m[0].replace(/\\s+/g, '');\n if (!found.includes(token)) found.push(token);\n }\n return found;\n}\n\ninterface Span {\n start: number;\n end: number;\n}\n\n/**\n * The nearest enclosing block element of [start, end), or null when the marker\n * isn't inside one. The closing tag is the first of the same name after the\n * marker — Word doesn't nest <p>, and where that guess is wrong the emptiness\n * test simply fails and the caller falls back to the marker's own span.\n */\nfunction enclosingBlock(html: string, start: number, end: number, tags: string[] = BLOCK_TAGS): {\n block: Span;\n contentStart: number;\n contentEnd: number;\n} | null {\n let best: { idx: number; contentStart: number; tag: string } | null = null;\n for (const tag of tags) {\n const openRe = new RegExp(`<${tag}(?:\\\\s[^>]*)?>`, 'gi');\n let m: RegExpExecArray | null;\n while ((m = openRe.exec(html)) !== null) {\n if (m.index >= start) break;\n if (!best || m.index > best.idx) {\n best = { idx: m.index, contentStart: m.index + m[0].length, tag };\n }\n }\n }\n if (!best) return null;\n const closeRe = new RegExp(`</${best.tag}\\\\s*>`, 'gi');\n closeRe.lastIndex = end;\n const close = closeRe.exec(html);\n if (!close) return null;\n return {\n block: { start: best.idx, end: close.index + close[0].length },\n contentStart: best.contentStart,\n contentEnd: close.index,\n };\n}\n\n/**\n * What to delete for a marker: its whole paragraph when the marker is alone in\n * it (removing only the text would leave a blank line), else just the marker.\n */\nfunction markerSpan(html: string, start: number, end: number): Span {\n const found = enclosingBlock(html, start, end);\n if (!found || found.contentStart > start || found.contentEnd < end) return { start, end };\n const rest = html.slice(found.contentStart, start) + html.slice(end, found.contentEnd);\n return stripToText(rest).trim() === '' ? found.block : { start, end };\n}\n\nfunction locate(html: string, token: string): Span | null {\n const m = markerRegex(token).exec(html);\n return m ? { start: m.index, end: m.index + m[0].length } : null;\n}\n\n// ── Single-token fill ───────────────────────────────────────────────────\n//\n// The section machinery above is for templates holding several variants of\n// one email. These are for the simpler case: fixed wording with details typed\n// elsewhere and dropped into tokens of the caller's own choosing (`{Name}`,\n// `%NAME%`, …). Same tag-tolerant matching, since these templates are edited in\n// Outlook too.\n\n/** Replace every occurrence of `token` with `value`, which is never rescanned. */\nexport function replaceToken(html: string, token: string, value: string): string {\n let done = '';\n let rest = html;\n for (; ;) {\n const at = locate(rest, token);\n if (!at) return done + rest;\n done += rest.slice(0, at.start) + value;\n rest = rest.slice(at.end);\n }\n}\n\n/**\n * Remove `token` together with the line it sits on — the table row or\n * paragraph, label included. For an optional detail this is the difference\n * between the email not mentioning it and a heading with nothing under it.\n * Falls back to deleting just the token when it isn't inside a line element.\n */\nexport function removeTokenLine(html: string, token: string): string {\n let out = html;\n for (; ;) {\n const at = locate(out, token);\n if (!at) return out;\n const cut = lineSpan(out, at);\n out = out.slice(0, cut.start) + out.slice(cut.end);\n }\n}\n\n/**\n * The line to delete for a token at `at`: its enclosing row or paragraph, or\n * the token's own span when it isn't in one.\n *\n * `enclosingBlock` returns the *nearest* opening tag before the token, which is\n * only the enclosing one if it hasn't been closed already — a token in a\n * paragraph after a table has a `<tr>` before it and a `</tr>` after it without\n * being inside a row, and taking that span would delete the table.\n */\nfunction lineSpan(html: string, at: Span): Span {\n for (const tag of LINE_TAGS) {\n const found = enclosingBlock(html, at.start, at.end, [tag]);\n if (!found) continue;\n const closedBefore = new RegExp(`</${tag}\\\\s*>`, 'i').test(html.slice(found.contentStart, at.start));\n if (!closedBefore) return found.block;\n }\n return at;\n}\n\n/** Which of `tokens` the template actually uses — what the caller has to supply. */\nexport function findTokens(html: string, tokens: readonly string[]): string[] {\n const text = stripToText(html || '');\n return tokens.filter(token => markerRegex(token).test(text));\n}\n\n/**\n * `{Token}`-shaped text still in a filled-in body: a placeholder misspelled\n * while editing, or one nothing supplied. Reads visible text only, so the\n * braces of a <style> block are not mistaken for placeholders. Catches a\n * leftover `{{TOKEN}}` too, reported by its inner `{TOKEN}`.\n */\nexport function findUnfilledTokens(html: string): string[] {\n const text = stripToText((html || '').replace(/<(style|script)\\b[^>]*>[\\s\\S]*?<\\/\\1>/gi, ''));\n const found: string[] = [];\n const re = /\\{\\s*([A-Za-z][A-Za-z0-9 _-]{0,30})\\s*\\}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n const token = `{${m[1].trim()}}`;\n if (!found.includes(token)) found.push(token);\n }\n return found;\n}\n\nexport interface ComposeOptions {\n /** Section to keep; the other sections are dropped with their markers. */\n section?: string;\n /** `{{NAME}}` → HTML to substitute. Names match case-insensitively. */\n placeholders?: Readonly<Record<string, string>>;\n /** The template's name, for error messages. */\n label?: string;\n}\n\n/**\n * Reduce a template body to the one email that goes out: keep `section`, drop\n * the rest, fill the placeholders. Throws INVALID_REQUEST rather than guessing —\n * a template edited into an unusable state has to stop the send, not deliver a\n * body with `[[ACCEPT]]` or an unfilled placeholder in it.\n */\nexport function composeTemplateBody(html: string, options: ComposeOptions = {}): string {\n const label = options.label ? `Template '${options.label}'` : 'The template';\n const wanted = (options.section || '').trim().toUpperCase();\n const { sections, placeholders: available } = findTemplateMarkers(html);\n\n if (wanted && !sections.includes(wanted)) {\n throw new InvalidRequestError(\n sections.length\n ? `${label} has no [[${wanted}]] section. Sections found: ${sections.join(', ')}.`\n : `${label} has no [[${wanted}]]...[[/${wanted}]] markers — it holds a single body, so name no section (or add the markers to the template).`,\n );\n }\n if (!wanted && sections.length) {\n throw new InvalidRequestError(\n `${label} is split into sections (${sections.join(', ')}); name the one to send, `\n + 'otherwise the email would go out with every variant and the markers in it.',\n );\n }\n\n // Deletions are collected first and applied right to left, so each span's\n // offsets still refer to the string they were measured against.\n const cuts: Span[] = [];\n for (const name of sections) {\n const open = locate(html, `[[${name}]]`);\n const close = locate(html, `[[/${name}]]`);\n if (!open || !close || close.start < open.end) {\n throw new InvalidRequestError(`${label} has a malformed [[${name}]] section — expected [[${name}]] ... [[/${name}]] in that order.`);\n }\n const openSpan = markerSpan(html, open.start, open.end);\n const closeSpan = markerSpan(html, close.start, close.end);\n if (name === wanted) {\n cuts.push(openSpan, closeSpan); // keep the content, shed the markers\n } else {\n cuts.push({ start: openSpan.start, end: closeSpan.end });\n }\n }\n let out = html;\n for (const cut of cuts.sort((a, b) => b.start - a.start)) {\n out = out.slice(0, cut.start) + out.slice(cut.end);\n }\n\n for (const [rawKey, value] of Object.entries(options.placeholders || {})) {\n const key = rawKey.trim().toUpperCase();\n if (!available.includes(key)) {\n throw new InvalidRequestError(\n `${label} has no {{${key}}} placeholder`\n + (available.length ? ` (found: ${available.map(p => `{{${p}}}`).join(', ')}).` : '.')\n + ' It may have been removed when the template was last edited.',\n );\n }\n const m = markerRegex(`{{${key}}}`).exec(out);\n // In the template but gone from `out` means it lived in a dropped\n // section: the caller supplying more than one variant needs, not an error.\n if (m) out = out.slice(0, m.index) + (value ?? '') + out.slice(m.index + m[0].length);\n }\n\n const leftover = markerTokens(out);\n if (leftover.length) {\n const hint = leftover.every(t => t.startsWith('{{'))\n ? 'Supply a value for each placeholder.'\n : 'Check the template — every [[SECTION]] needs its [[/SECTION]].';\n throw new InvalidRequestError(\n `${label} still contains unresolved markers after composing: ${leftover.join(', ')}. ${hint} Nothing was created.`,\n );\n }\n return out;\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -49,6 +49,18 @@ export interface SendEmailParams {
|
|
|
49
49
|
*/
|
|
50
50
|
openDraftWindow?: boolean;
|
|
51
51
|
}
|
|
52
|
+
export interface SendEmailResult {
|
|
53
|
+
/**
|
|
54
|
+
* The draft's entry id when the email was filed silently into Drafts
|
|
55
|
+
* (`openDraftWindow: false`) — the id `listOutlookDrafts` reports for it,
|
|
56
|
+
* so a caller can keep it and later send or delete exactly the drafts it
|
|
57
|
+
* made. '' when the email was sent, or opened in a compose window, which
|
|
58
|
+
* files nothing yet; and on macOS in the rare case Drafts gained another
|
|
59
|
+
* draft with the same subject in the same moment, so this one could not be
|
|
60
|
+
* told apart.
|
|
61
|
+
*/
|
|
62
|
+
draftEntryId: string;
|
|
63
|
+
}
|
|
52
64
|
export interface ReplyEmailParams extends EmailLocator {
|
|
53
65
|
/** SMTP address of the mailbox to reply from. */
|
|
54
66
|
emailAccount: string;
|
|
@@ -95,6 +107,15 @@ export interface ReplyEmailResult {
|
|
|
95
107
|
subject: string;
|
|
96
108
|
/** The original email's sender — check it is who you meant to answer. */
|
|
97
109
|
repliedToSender: string;
|
|
110
|
+
/**
|
|
111
|
+
* The draft's entry id when the reply was filed silently into Drafts
|
|
112
|
+
* (`openDraftWindow: false`), as `SendEmailResult.draftEntryId` reports a
|
|
113
|
+
* new email's: the id `listOutlookDrafts` gives it, so a caller can later
|
|
114
|
+
* send or delete exactly the replies it drafted. '' when the reply was
|
|
115
|
+
* sent or opened in a compose window, and on macOS when Drafts gained
|
|
116
|
+
* another draft with the same subject in the same moment.
|
|
117
|
+
*/
|
|
118
|
+
draftEntryId: string;
|
|
98
119
|
}
|
|
99
120
|
/** One item a batch operation could not handle, and why. */
|
|
100
121
|
export interface ItemFailure {
|
|
@@ -296,8 +317,9 @@ export interface InboxSearchFilter {
|
|
|
296
317
|
subjectLike?: string;
|
|
297
318
|
/**
|
|
298
319
|
* Regular expression tested against each subject, case-insensitively
|
|
299
|
-
* whatever the RegExp's own flags
|
|
300
|
-
*
|
|
320
|
+
* whatever the RegExp's own flags; on macOS a `u` or `v` flag is kept,
|
|
321
|
+
* since it decides how the pattern parses. On Windows the pattern runs in
|
|
322
|
+
* .NET's regex engine, so keep to syntax JavaScript and .NET share.
|
|
301
323
|
*/
|
|
302
324
|
subjectPattern?: RegExp;
|
|
303
325
|
/** Drop subjects carrying a reply or forward prefix (RE:, FW:, AW:, 回复:, …). */
|
|
@@ -307,8 +329,8 @@ export interface InboxSearchFilter {
|
|
|
307
329
|
/**
|
|
308
330
|
* Folders under the Inbox to leave out, by full folder path or bare name,
|
|
309
331
|
* case-insensitively. An excluded folder takes its whole subtree with it.
|
|
310
|
-
* Sent, Drafts, Deleted and
|
|
311
|
-
* nests them under the Inbox. macOS matches the leaf name only.
|
|
332
|
+
* Sent, Drafts, Deleted, Junk and the Outbox are always skipped, even where
|
|
333
|
+
* the profile nests them under the Inbox. macOS matches the leaf name only.
|
|
312
334
|
*/
|
|
313
335
|
excludeFolders?: readonly string[];
|
|
314
336
|
/**
|
|
@@ -376,6 +398,13 @@ export interface SelectedEmail extends EmailLocator {
|
|
|
376
398
|
body: string;
|
|
377
399
|
/** Not saved to disk — pass the ones you want to saveEmailAttachments. */
|
|
378
400
|
attachmentNames: string[];
|
|
401
|
+
/**
|
|
402
|
+
* The folder it sits in, in the form the listings report
|
|
403
|
+
* (`\\team@example.com\[Gmail]\Drafts`) and so naming its mailbox. '' when
|
|
404
|
+
* Outlook can't say: an email opened from a file, or on macOS one whose
|
|
405
|
+
* mailbox neither AppleScript nor the profile database names.
|
|
406
|
+
*/
|
|
407
|
+
folderPath: string;
|
|
379
408
|
}
|
|
380
409
|
export interface ReadEmailBodyOptions {
|
|
381
410
|
/** Cap on the returned body. Default 8000. */
|
|
@@ -507,7 +536,7 @@ export interface OutlookBridge {
|
|
|
507
536
|
/** Every mailbox this Outlook profile can reach, as SMTP addresses. */
|
|
508
537
|
getOutlookAccounts(): Promise<string[]>;
|
|
509
538
|
/** Send an email, or stage it as a draft. */
|
|
510
|
-
sendOutlookEmail(params: SendEmailParams): Promise<
|
|
539
|
+
sendOutlookEmail(params: SendEmailParams): Promise<SendEmailResult>;
|
|
511
540
|
/** Reply to an email, with the new text above the quoted original. */
|
|
512
541
|
replyOutlookEmail(params: ReplyEmailParams): Promise<ReplyEmailResult>;
|
|
513
542
|
/** Recent mail from the Inbox root or one named folder, newest first. */
|
|
@@ -528,7 +557,11 @@ export interface OutlookBridge {
|
|
|
528
557
|
locateEmail(description: EmailDescription, options?: LocateEmailOptions): Promise<InboxSearchMatch | null>;
|
|
529
558
|
/** The folders under an account's Inbox. */
|
|
530
559
|
listInboxFolders(emailAccount: string, options?: ListFoldersOptions): Promise<InboxFolderInfo[]>;
|
|
531
|
-
/**
|
|
560
|
+
/**
|
|
561
|
+
* File emails into a folder. Moving rewrites each email's entry id. Only the
|
|
562
|
+
* account's own mail is moved: an id that resolves in another mailbox fails
|
|
563
|
+
* as that item.
|
|
564
|
+
*/
|
|
532
565
|
moveOutlookEmails(emailAccount: string, entryIds: readonly string[], folder: string, options?: MoveEmailsOptions): Promise<MoveEmailsResult>;
|
|
533
566
|
/** The mail drafts bound to an account, newest first. */
|
|
534
567
|
listOutlookDrafts(emailAccount: string, options?: ListDraftsOptions): Promise<ListDraftsResult>;
|
|
@@ -538,7 +571,10 @@ export interface OutlookBridge {
|
|
|
538
571
|
sendAllDrafts(emailAccount: string): Promise<SendDraftsResult>;
|
|
539
572
|
/** Delete the named drafts (into Deleted Items) — each has to be one of this account's drafts. */
|
|
540
573
|
deleteOutlookDrafts(emailAccount: string, entryIds: readonly string[]): Promise<DeleteDraftsResult>;
|
|
541
|
-
/**
|
|
574
|
+
/**
|
|
575
|
+
* Delete mail by id into Deleted Items, refusing received and sent mail
|
|
576
|
+
* unless allowed — and mail in any other mailbox whatever is allowed.
|
|
577
|
+
*/
|
|
542
578
|
deleteOutlookEmails(emailAccount: string, entryIds: readonly string[], options?: DeleteMailOptions): Promise<DeleteMailResult>;
|
|
543
579
|
/** Permanently empty an account's Deleted Items. The one irreversible operation. */
|
|
544
580
|
purgeDeletedItems(emailAccount: string, options?: PurgeDeletedItemsOptions): Promise<PurgeDeletedItemsResult>;
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
+
{"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 SendEmailResult {\n /**\n * The draft's entry id when the email was filed silently into Drafts\n * (`openDraftWindow: false`) — the id `listOutlookDrafts` reports for it,\n * so a caller can keep it and later send or delete exactly the drafts it\n * made. '' when the email was sent, or opened in a compose window, which\n * files nothing yet; and on macOS in the rare case Drafts gained another\n * draft with the same subject in the same moment, so this one could not be\n * told apart.\n */\n draftEntryId: string;\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 * The draft's entry id when the reply was filed silently into Drafts\n * (`openDraftWindow: false`), as `SendEmailResult.draftEntryId` reports a\n * new email's: the id `listOutlookDrafts` gives it, so a caller can later\n * send or delete exactly the replies it drafted. '' when the reply was\n * sent or opened in a compose window, and on macOS when Drafts gained\n * another draft with the same subject in the same moment.\n */\n draftEntryId: 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 macOS a `u` or `v` flag is kept,\n * since it decides how the pattern parses. On Windows the pattern runs in\n * .NET's 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, Junk and the Outbox are always skipped, even where\n * the profile 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 * The folder it sits in, in the form the listings report\n * (`\\\\team@example.com\\[Gmail]\\Drafts`) and so naming its mailbox. '' when\n * Outlook can't say: an email opened from a file, or on macOS one whose\n * mailbox neither AppleScript nor the profile database names.\n */\n folderPath: 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<SendEmailResult>;\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 /**\n * File emails into a folder. Moving rewrites each email's entry id. Only the\n * account's own mail is moved: an id that resolves in another mailbox fails\n * as that item.\n */\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 /**\n * Delete mail by id into Deleted Items, refusing received and sent mail\n * unless allowed — and mail in any other mailbox whatever is allowed.\n */\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"]}
|
package/dist/windows/accounts.js
CHANGED
|
@@ -4,7 +4,7 @@ exports.getOutlookAccounts = getOutlookAccounts;
|
|
|
4
4
|
// The mailboxes a Windows Outlook profile can reach.
|
|
5
5
|
const run_1 = require("./run");
|
|
6
6
|
const scripts_1 = require("./scripts");
|
|
7
|
-
const json_1 = require("
|
|
7
|
+
const json_1 = require("./json");
|
|
8
8
|
/**
|
|
9
9
|
* Every mailbox this profile can reach, as SMTP addresses.
|
|
10
10
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/windows/accounts.ts"],"names":[],"mappings":";;AAeA,gDAeC;AA9BD,qDAAqD;AACrD,+BAA0C;AAC1C,uCAAuC;AACvC,
|
|
1
|
+
{"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/windows/accounts.ts"],"names":[],"mappings":";;AAeA,gDAeC;AA9BD,qDAAqD;AACrD,+BAA0C;AAC1C,uCAAuC;AACvC,iCAAiC;AAEjC;;;;;;;;;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 './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"]}
|
|
@@ -4,7 +4,7 @@ exports.saveEmailAttachments = saveEmailAttachments;
|
|
|
4
4
|
// Saving attachments off an email.
|
|
5
5
|
const run_1 = require("./run");
|
|
6
6
|
const scripts_1 = require("./scripts");
|
|
7
|
-
const json_1 = require("
|
|
7
|
+
const json_1 = require("./json");
|
|
8
8
|
const attachmentMatch_1 = require("../shared/attachmentMatch");
|
|
9
9
|
const errors_1 = require("../errors");
|
|
10
10
|
/**
|
|
@@ -65,7 +65,7 @@ try { $subject = [string]$item.Subject } catch {}
|
|
|
65
65
|
$senderName = ''
|
|
66
66
|
try { $senderName = [string]$item.SenderName } catch {}
|
|
67
67
|
$received = ''
|
|
68
|
-
try { $received = $item.ReceivedTime
|
|
68
|
+
try { $received = ${(0, scripts_1.stampPs)('$item.ReceivedTime')} } catch {}
|
|
69
69
|
$attachments = @()
|
|
70
70
|
foreach ($att in $item.Attachments) { $attachments += $att }
|
|
71
71
|
$picks = @()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["../../src/windows/attachments.ts"],"names":[],"mappings":";;AAuDA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C;QACtB,OAAO;YACH,IAAI,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,IAAI,CAAC;YACjB,QAAQ,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,QAAQ,CAAC;YACzB,OAAO,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,OAAO,CAAC;YACvB,UAAU,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,UAAU,CAAC;YAC7B,WAAW,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,WAAW,CAAC;YAC/B,YAAY,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,YAAY,CAAC;SACpC,CAAC;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, stampPs } from './scripts';\nimport { record, str, toArray } from './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 = ${stampPs('$item.ReceivedTime')} } 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"]}
|
package/dist/windows/bounces.js
CHANGED
|
@@ -7,7 +7,7 @@ exports.readSentRecipientGroups = readSentRecipientGroups;
|
|
|
7
7
|
// addresses that failed.
|
|
8
8
|
const run_1 = require("./run");
|
|
9
9
|
const scripts_1 = require("./scripts");
|
|
10
|
-
const json_1 = require("
|
|
10
|
+
const json_1 = require("./json");
|
|
11
11
|
const bounceRules_1 = require("../shared/bounceRules");
|
|
12
12
|
const mail_1 = require("../mail");
|
|
13
13
|
/**
|
|
@@ -59,7 +59,7 @@ function Get-BounceReport($item) {
|
|
|
59
59
|
if ($failedRecipients.Count -ge $maxFailed) { break }
|
|
60
60
|
}
|
|
61
61
|
$received = ''
|
|
62
|
-
try { $received = $item.ReceivedTime
|
|
62
|
+
try { $received = ${(0, scripts_1.stampPs)('$item.ReceivedTime')} } catch {}
|
|
63
63
|
return [PSCustomObject]@{
|
|
64
64
|
entryId = [string]$item.EntryID
|
|
65
65
|
subject = $subject.Trim()
|
|
@@ -86,7 +86,7 @@ ${bounceClassifierScript()}
|
|
|
86
86
|
$dryRun = ${(0, run_1.psBool)(request.dryRun)}
|
|
87
87
|
$inbox = $store.GetDefaultFolder(${(0, run_1.psInt)(mail_1.FolderId.Inbox)})
|
|
88
88
|
${(0, scripts_1.cutoffScript)(request.daysBack)}
|
|
89
|
-
${(0, scripts_1.itemsSinceScript)('inbox', 'ReceivedTime'
|
|
89
|
+
${(0, scripts_1.itemsSinceScript)('inbox', 'ReceivedTime')}
|
|
90
90
|
$reports = @()
|
|
91
91
|
$matchedItems = @()
|
|
92
92
|
$count = $filtered.Count
|
|
@@ -111,7 +111,7 @@ if (-not $dryRun) {
|
|
|
111
111
|
try { $entryId = [string]$m.EntryID } catch {}
|
|
112
112
|
try { $subject = [string]$m.Subject } catch {}
|
|
113
113
|
try { $m.Delete(); $deleted++ }
|
|
114
|
-
catch { $
|
|
114
|
+
catch { ${(0, json_1.itemFailurePs)('$entryId')} }
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
ConvertTo-Json -Depth 4 -InputObject ([PSCustomObject]@{
|
|
@@ -159,7 +159,7 @@ foreach ($role in @(${roles.map(run_1.psInt).join(', ')})) {
|
|
|
159
159
|
$scanFolder = $null
|
|
160
160
|
try { $scanFolder = $store.GetDefaultFolder($role) } catch {}
|
|
161
161
|
if ($scanFolder -eq $null) { continue }
|
|
162
|
-
${(0, scripts_1.itemsSinceScript)('scanFolder', 'ReceivedTime'
|
|
162
|
+
${(0, scripts_1.itemsSinceScript)('scanFolder', 'ReceivedTime').trim()}
|
|
163
163
|
$count = $filtered.Count
|
|
164
164
|
for ($i = 1; $i -le $count; $i++) {
|
|
165
165
|
$item = $null
|
|
@@ -186,7 +186,7 @@ async function readSentRecipientGroups(request) {
|
|
|
186
186
|
${scripts_1.DELIVERY_STORE_PS}
|
|
187
187
|
$sentFolder = $store.GetDefaultFolder(${(0, run_1.psInt)(mail_1.FolderId.SentMail)})
|
|
188
188
|
${(0, scripts_1.cutoffScript)(request.daysBack)}
|
|
189
|
-
${(0, scripts_1.itemsSinceScript)('sentFolder', 'SentOn'
|
|
189
|
+
${(0, scripts_1.itemsSinceScript)('sentFolder', 'SentOn')}
|
|
190
190
|
$filtered.Sort('[SentOn]', $true)
|
|
191
191
|
$limit = ${(0, run_1.psInt)(request.limit)}
|
|
192
192
|
$rows = @()
|
|
@@ -217,7 +217,7 @@ for ($i = 1; $i -le $count -and $rows.Count -lt $limit; $i++) {
|
|
|
217
217
|
$rows += [PSCustomObject]@{
|
|
218
218
|
entryId = [string]$m.EntryID
|
|
219
219
|
subject = ([string]$m.Subject).Trim()
|
|
220
|
-
sentOn = if ($sentOn -ne $null) { $
|
|
220
|
+
sentOn = if ($sentOn -ne $null) { ${(0, scripts_1.stampPs)('$sentOn')} } else { '' }
|
|
221
221
|
recipients = @($addresses)
|
|
222
222
|
}
|
|
223
223
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bounces.js","sourceRoot":"","sources":["../../src/windows/bounces.ts"],"names":[],"mappings":";;AAyFA,4DA+DC;AAOD,4DA4BC;AAMD,0DAmDC;AApPD,0EAA0E;AAC1E,yBAAyB;AACzB,+BAA4E;AAC5E,uCAA6G;AAC7G,yCAAkF;AAClF,uDAS+B;AAC/B,kCAAmC;AAInC;;;;;;;GAOG;AACH,SAAS,sBAAsB;IAC3B,OAAO;mBACQ,IAAA,aAAO,EAAC,oCAAsB,CAAC;qBAC7B,IAAA,aAAO,EAAC,qCAAuB,CAAC;iBACpC,IAAA,aAAO,EAAC,iCAAmB,CAAC;gBAC7B,IAAA,aAAO,EAAC,mCAAqB,CAAC;eAC/B,IAAA,cAAQ,EAAC,sCAAwB,CAAC;oBAC7B,IAAA,cAAQ,EAAC,kCAAoB,CAAC;eACnC,IAAA,WAAK,EAAC,mCAAqB,CAAC;;;;;;;;;;;;;;;mGAewD,IAAA,cAAQ,EAAC,2BAAa,CAAC,GAAG,CAAC;kHACZ,IAAA,cAAQ,EAAC,2BAAa,CAAC,MAAM,CAAC;6GACnC,IAAA,cAAQ,EAAC,2BAAa,CAAC,MAAM,CAAC;6GAC9B,2BAAa,CAAC,aAAa,CAAC,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0B7I,CAAC;AACF,CAAC;AAED;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E,QAAQ,EAAE,UAAU,CAAC;;WAE3C,IAAA,WAAK,EAAC,OAAO,CAAC,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkC9B,EAAE,MAAM,CAAC,CAAC;IACP,OAAO,IAAA,cAAO,EAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;QAC7B,MAAM,CAAC,GAAG,IAAA,aAAM,EAAC,GAAG,CAAC,CAAC;QACtB,OAAO;YACH,OAAO,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,OAAO,CAAC;YACvB,OAAO,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,OAAO,CAAC;YACvB,MAAM,EAAE,IAAA,UAAG,EAAC,CAAC,CAAC,MAAM,CAAC;YACrB,UAAU,EAAE,IAAA,cAAO,EAAC,CAAC,CAAC,UAAU,CAAC;SACpC,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Bounce-backs: finding them, clearing them away, and mining them for the\n// addresses that failed.\nimport { psArray, psBool, psInt, psString, runPowerShellJson } from './run';\nimport { accountScript, cutoffScript, DELIVERY_STORE_PS, itemsSinceScript, NAMED_STORE_PS } from './scripts';\nimport { itemFailures, num, record, str, strList, toArray } from '../shared/json';\nimport {\n BODY_ADDRESS_PATTERN,\n BOUNCE_DAEMON_ADDRESSES,\n BOUNCE_DAEMON_NAMES,\n BOUNCE_REASON,\n BOUNCE_SUBJECT_PHRASES,\n DAEMON_SELF_ADDRESSES,\n MAX_FAILED_RECIPIENTS,\n NDR_MESSAGE_CLASS_PREFIX,\n} from '../shared/bounceRules';\nimport { FolderId } from '../mail';\nimport type { CleanUndeliverableRequest, CollectBouncesRequest, SentGroupsRequest } from '../backend';\nimport type { CleanUndeliverableResult, SentRecipientGroup } from '../types';\n\n/**\n * The classifier, generated from the shared rules so Windows and macOS can't\n * disagree about what a bounce is. Defines `Get-BounceReport`, which returns\n * null for an item that isn't a bounce and a report row for one that is.\n *\n * The body is read only after a cheaper signal (class, sender, subject) has\n * matched — that ordering is what keeps a large-inbox scan affordable.\n */\nfunction bounceClassifierScript(): string {\n return `\n$bouncePhrases = ${psArray(BOUNCE_SUBJECT_PHRASES)}\n$daemonAddresses = ${psArray(BOUNCE_DAEMON_ADDRESSES)}\n$daemonNames = ${psArray(BOUNCE_DAEMON_NAMES)}\n$daemonSelf = ${psArray(DAEMON_SELF_ADDRESSES)}\n$ndrPrefix = ${psString(NDR_MESSAGE_CLASS_PREFIX)}\n$addressPattern = ${psString(BODY_ADDRESS_PATTERN)}\n$maxFailed = ${psInt(MAX_FAILED_RECIPIENTS)}\n$accountLower = $target.ToLower()\nfunction Get-BounceReport($item) {\n $class = 0\n try { $class = [int]$item.Class } catch {}\n if ($class -ne 43 -and $class -ne 46) { return $null }\n $subject = ''\n try { $subject = [string]$item.Subject } catch {}\n $senderName = ''\n try { $senderName = [string]$item.SenderName } catch {}\n $senderEmail = ''\n try { $senderEmail = [string]$item.SenderEmailAddress } catch {}\n $messageClass = ''\n try { $messageClass = [string]$item.MessageClass } catch {}\n $reason = ''\n if ($messageClass.StartsWith($ndrPrefix, [StringComparison]::OrdinalIgnoreCase)) { $reason = ${psString(BOUNCE_REASON.ndr)} }\n if (-not $reason) { foreach ($d in $daemonAddresses) { if ($senderEmail.ToLower().Contains($d)) { $reason = ${psString(BOUNCE_REASON.daemon)}; break } } }\n if (-not $reason) { foreach ($d in $daemonNames) { if ($senderName.ToLower().Contains($d)) { $reason = ${psString(BOUNCE_REASON.daemon)}; break } } }\n if (-not $reason) { foreach ($p in $bouncePhrases) { if ($subject.ToLower().Contains($p)) { $reason = \"${BOUNCE_REASON.subjectPhrase('$p')}\"; break } } }\n if (-not $reason) { return $null }\n $failedRecipients = @()\n $body = ''\n try { $body = [string]$item.Body } catch {}\n foreach ($m in [regex]::Matches($body, $addressPattern)) {\n $address = $m.Value.ToLower().TrimEnd('.')\n if ($address -eq $accountLower) { continue }\n $isDaemon = $false\n foreach ($d in $daemonSelf) { if ($address.Contains($d)) { $isDaemon = $true; break } }\n if ($isDaemon -or $failedRecipients -contains $address) { continue }\n $failedRecipients += $address\n if ($failedRecipients.Count -ge $maxFailed) { break }\n }\n $received = ''\n try { $received = $item.ReceivedTime.ToString('yyyy-MM-dd HH:mm') } catch {}\n return [PSCustomObject]@{\n entryId = [string]$item.EntryID\n subject = $subject.Trim()\n senderName = $senderName\n senderEmail = $senderEmail\n receivedTime = $received\n matchedReason = $reason\n failedRecipients = @($failedRecipients)\n }\n}\n`;\n}\n\n/**\n * Scan an account's Inbox for bounce-backs and, unless dry-running, move each to\n * Deleted Items (recoverable).\n *\n * Matched items are collected before the first Delete(): deleting shifts the\n * collection, and deleting mid-enumeration would skip items.\n */\nexport async function cleanUndeliverableEmails(request: CleanUndeliverableRequest): Promise<CleanUndeliverableResult> {\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${NAMED_STORE_PS}\n${bounceClassifierScript()}\n$dryRun = ${psBool(request.dryRun)}\n$inbox = $store.GetDefaultFolder(${psInt(FolderId.Inbox)})\n${cutoffScript(request.daysBack)}\n${itemsSinceScript('inbox', 'ReceivedTime', 'filtered')}\n$reports = @()\n$matchedItems = @()\n$count = $filtered.Count\nfor ($i = 1; $i -le $count; $i++) {\n $item = $null\n try { $item = $filtered.Item($i) } catch { continue }\n if ($item -eq $null) { continue }\n $received = $null\n try { $received = $item.ReceivedTime } catch {}\n if ($received -ne $null -and $received -lt $cutoff) { continue }\n $report = Get-BounceReport $item\n if ($report -eq $null) { continue }\n $reports += $report\n $matchedItems += $item\n}\n$deleted = 0\n$failed = @()\nif (-not $dryRun) {\n foreach ($m in $matchedItems) {\n $entryId = ''\n $subject = ''\n try { $entryId = [string]$m.EntryID } catch {}\n try { $subject = [string]$m.Subject } catch {}\n try { $m.Delete(); $deleted++ }\n catch { $failed += [PSCustomObject]@{ entryId = $entryId; subject = $subject; error = $_.Exception.Message } }\n }\n}\nConvertTo-Json -Depth 4 -InputObject ([PSCustomObject]@{\n deletedCount = $deleted\n matched = @($reports)\n failed = @($failed)\n})\n`, 'scan');\n const e = record(output);\n const matched = toArray(e.matched).map(row => {\n const m = record(row);\n return {\n entryId: str(m.entryId),\n subject: str(m.subject),\n senderName: str(m.senderName),\n senderEmail: str(m.senderEmail),\n receivedTime: str(m.receivedTime),\n matchedReason: str(m.matchedReason),\n failedRecipients: strList(m.failedRecipients),\n };\n });\n return {\n account: request.account,\n scannedDays: request.daysBack,\n dryRun: request.dryRun,\n matchedCount: matched.length,\n deletedCount: num(e.deletedCount),\n matched,\n failed: itemFailures(e.failed),\n };\n}\n\n/**\n * The deduplicated addresses bounce-backs report as failed, from the Inbox and,\n * optionally, Deleted Items — so it still works after the bounces were cleaned\n * away. Never deletes anything.\n */\nexport async function collectBouncedRecipients(request: CollectBouncesRequest): Promise<string[]> {\n const roles = request.includeDeletedItems ? [FolderId.Inbox, FolderId.DeletedItems] : [FolderId.Inbox];\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${DELIVERY_STORE_PS}\n${bounceClassifierScript()}\n${cutoffScript(request.daysBack)}\n$found = [ordered]@{}\nforeach ($role in @(${roles.map(psInt).join(', ')})) {\n $scanFolder = $null\n try { $scanFolder = $store.GetDefaultFolder($role) } catch {}\n if ($scanFolder -eq $null) { continue }\n ${itemsSinceScript('scanFolder', 'ReceivedTime', 'filtered').trim()}\n $count = $filtered.Count\n for ($i = 1; $i -le $count; $i++) {\n $item = $null\n try { $item = $filtered.Item($i) } catch { continue }\n if ($item -eq $null) { continue }\n $received = $null\n try { $received = $item.ReceivedTime } catch {}\n if ($received -ne $null -and $received -lt $cutoff) { continue }\n $report = Get-BounceReport $item\n if ($report -eq $null) { continue }\n foreach ($address in $report.failedRecipients) { $found[$address] = $true }\n }\n}\nConvertTo-Json -Compress -InputObject @($found.Keys)\n`, 'scan');\n return strList(output);\n}\n\n/**\n * Sent Items within the window, each message with the full SMTP address set it\n * went to (To + CC + BCC), newest first.\n */\nexport async function readSentRecipientGroups(request: SentGroupsRequest): Promise<SentRecipientGroup[]> {\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${DELIVERY_STORE_PS}\n$sentFolder = $store.GetDefaultFolder(${psInt(FolderId.SentMail)})\n${cutoffScript(request.daysBack)}\n${itemsSinceScript('sentFolder', 'SentOn', 'filtered')}\n$filtered.Sort('[SentOn]', $true)\n$limit = ${psInt(request.limit)}\n$rows = @()\n$count = $filtered.Count\nfor ($i = 1; $i -le $count -and $rows.Count -lt $limit; $i++) {\n $m = $null\n try { $m = $filtered.Item($i) } catch { continue }\n if ($m -eq $null) { continue }\n $sentOn = $null\n try { $sentOn = $m.SentOn } catch {}\n if ($sentOn -ne $null -and $sentOn -lt $cutoff) { break }\n $class = 0\n try { $class = [int]$m.Class } catch {}\n if ($class -ne 43) { continue }\n $addresses = @()\n try {\n foreach ($r in $m.Recipients) {\n $address = ''\n try { $address = [string]$r.Address } catch {}\n # An internal recipient resolves to an Exchange DN; recover its SMTP address.\n if ($address -notlike '*@*') {\n try { $address = [string]$r.AddressEntry.GetExchangeUser().PrimarySmtpAddress } catch {}\n }\n if ($address -like '*@*') { $addresses += $address.ToLower() }\n }\n } catch {}\n if ($addresses.Count -eq 0) { continue }\n $rows += [PSCustomObject]@{\n entryId = [string]$m.EntryID\n subject = ([string]$m.Subject).Trim()\n sentOn = if ($sentOn -ne $null) { $sentOn.ToString('yyyy-MM-dd HH:mm') } else { '' }\n recipients = @($addresses)\n }\n}\nConvertTo-Json -Depth 4 -InputObject @($rows)\n`, 'scan');\n return toArray(output).map(row => {\n const e = record(row);\n return {\n entryId: str(e.entryId),\n subject: str(e.subject),\n sentOn: str(e.sentOn),\n recipients: strList(e.recipients),\n };\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bounces.js","sourceRoot":"","sources":["../../src/windows/bounces.ts"],"names":[],"mappings":";;AAyFA,4DA+DC;AAOD,4DA4BC;AAMD,0DAmDC;AApPD,0EAA0E;AAC1E,yBAAyB;AACzB,+BAA4E;AAC5E,uC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AAU,EAAE,IAAA,cAAO,EAAC,CAAC,CAAC,UAAU,CAAC;SACpC,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Bounce-backs: finding them, clearing them away, and mining them for the\n// addresses that failed.\nimport { psArray, psBool, psInt, psString, runPowerShellJson } from './run';\nimport { accountScript, cutoffScript, DELIVERY_STORE_PS, itemsSinceScript, NAMED_STORE_PS, stampPs } from './scripts';\nimport { itemFailurePs, itemFailures, num, record, str, strList, toArray } from './json';\nimport {\n BODY_ADDRESS_PATTERN,\n BOUNCE_DAEMON_ADDRESSES,\n BOUNCE_DAEMON_NAMES,\n BOUNCE_REASON,\n BOUNCE_SUBJECT_PHRASES,\n DAEMON_SELF_ADDRESSES,\n MAX_FAILED_RECIPIENTS,\n NDR_MESSAGE_CLASS_PREFIX,\n} from '../shared/bounceRules';\nimport { FolderId } from '../mail';\nimport type { CleanUndeliverableRequest, CollectBouncesRequest, SentGroupsRequest } from '../backend';\nimport type { CleanUndeliverableResult, SentRecipientGroup } from '../types';\n\n/**\n * The classifier, generated from the shared rules so Windows and macOS can't\n * disagree about what a bounce is. Defines `Get-BounceReport`, which returns\n * null for an item that isn't a bounce and a report row for one that is.\n *\n * The body is read only after a cheaper signal (class, sender, subject) has\n * matched — that ordering is what keeps a large-inbox scan affordable.\n */\nfunction bounceClassifierScript(): string {\n return `\n$bouncePhrases = ${psArray(BOUNCE_SUBJECT_PHRASES)}\n$daemonAddresses = ${psArray(BOUNCE_DAEMON_ADDRESSES)}\n$daemonNames = ${psArray(BOUNCE_DAEMON_NAMES)}\n$daemonSelf = ${psArray(DAEMON_SELF_ADDRESSES)}\n$ndrPrefix = ${psString(NDR_MESSAGE_CLASS_PREFIX)}\n$addressPattern = ${psString(BODY_ADDRESS_PATTERN)}\n$maxFailed = ${psInt(MAX_FAILED_RECIPIENTS)}\n$accountLower = $target.ToLower()\nfunction Get-BounceReport($item) {\n $class = 0\n try { $class = [int]$item.Class } catch {}\n if ($class -ne 43 -and $class -ne 46) { return $null }\n $subject = ''\n try { $subject = [string]$item.Subject } catch {}\n $senderName = ''\n try { $senderName = [string]$item.SenderName } catch {}\n $senderEmail = ''\n try { $senderEmail = [string]$item.SenderEmailAddress } catch {}\n $messageClass = ''\n try { $messageClass = [string]$item.MessageClass } catch {}\n $reason = ''\n if ($messageClass.StartsWith($ndrPrefix, [StringComparison]::OrdinalIgnoreCase)) { $reason = ${psString(BOUNCE_REASON.ndr)} }\n if (-not $reason) { foreach ($d in $daemonAddresses) { if ($senderEmail.ToLower().Contains($d)) { $reason = ${psString(BOUNCE_REASON.daemon)}; break } } }\n if (-not $reason) { foreach ($d in $daemonNames) { if ($senderName.ToLower().Contains($d)) { $reason = ${psString(BOUNCE_REASON.daemon)}; break } } }\n if (-not $reason) { foreach ($p in $bouncePhrases) { if ($subject.ToLower().Contains($p)) { $reason = \"${BOUNCE_REASON.subjectPhrase('$p')}\"; break } } }\n if (-not $reason) { return $null }\n $failedRecipients = @()\n $body = ''\n try { $body = [string]$item.Body } catch {}\n foreach ($m in [regex]::Matches($body, $addressPattern)) {\n $address = $m.Value.ToLower().TrimEnd('.')\n if ($address -eq $accountLower) { continue }\n $isDaemon = $false\n foreach ($d in $daemonSelf) { if ($address.Contains($d)) { $isDaemon = $true; break } }\n if ($isDaemon -or $failedRecipients -contains $address) { continue }\n $failedRecipients += $address\n if ($failedRecipients.Count -ge $maxFailed) { break }\n }\n $received = ''\n try { $received = ${stampPs('$item.ReceivedTime')} } catch {}\n return [PSCustomObject]@{\n entryId = [string]$item.EntryID\n subject = $subject.Trim()\n senderName = $senderName\n senderEmail = $senderEmail\n receivedTime = $received\n matchedReason = $reason\n failedRecipients = @($failedRecipients)\n }\n}\n`;\n}\n\n/**\n * Scan an account's Inbox for bounce-backs and, unless dry-running, move each to\n * Deleted Items (recoverable).\n *\n * Matched items are collected before the first Delete(): deleting shifts the\n * collection, and deleting mid-enumeration would skip items.\n */\nexport async function cleanUndeliverableEmails(request: CleanUndeliverableRequest): Promise<CleanUndeliverableResult> {\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${NAMED_STORE_PS}\n${bounceClassifierScript()}\n$dryRun = ${psBool(request.dryRun)}\n$inbox = $store.GetDefaultFolder(${psInt(FolderId.Inbox)})\n${cutoffScript(request.daysBack)}\n${itemsSinceScript('inbox', 'ReceivedTime')}\n$reports = @()\n$matchedItems = @()\n$count = $filtered.Count\nfor ($i = 1; $i -le $count; $i++) {\n $item = $null\n try { $item = $filtered.Item($i) } catch { continue }\n if ($item -eq $null) { continue }\n $received = $null\n try { $received = $item.ReceivedTime } catch {}\n if ($received -ne $null -and $received -lt $cutoff) { continue }\n $report = Get-BounceReport $item\n if ($report -eq $null) { continue }\n $reports += $report\n $matchedItems += $item\n}\n$deleted = 0\n$failed = @()\nif (-not $dryRun) {\n foreach ($m in $matchedItems) {\n $entryId = ''\n $subject = ''\n try { $entryId = [string]$m.EntryID } catch {}\n try { $subject = [string]$m.Subject } catch {}\n try { $m.Delete(); $deleted++ }\n catch { ${itemFailurePs('$entryId')} }\n }\n}\nConvertTo-Json -Depth 4 -InputObject ([PSCustomObject]@{\n deletedCount = $deleted\n matched = @($reports)\n failed = @($failed)\n})\n`, 'scan');\n const e = record(output);\n const matched = toArray(e.matched).map(row => {\n const m = record(row);\n return {\n entryId: str(m.entryId),\n subject: str(m.subject),\n senderName: str(m.senderName),\n senderEmail: str(m.senderEmail),\n receivedTime: str(m.receivedTime),\n matchedReason: str(m.matchedReason),\n failedRecipients: strList(m.failedRecipients),\n };\n });\n return {\n account: request.account,\n scannedDays: request.daysBack,\n dryRun: request.dryRun,\n matchedCount: matched.length,\n deletedCount: num(e.deletedCount),\n matched,\n failed: itemFailures(e.failed),\n };\n}\n\n/**\n * The deduplicated addresses bounce-backs report as failed, from the Inbox and,\n * optionally, Deleted Items — so it still works after the bounces were cleaned\n * away. Never deletes anything.\n */\nexport async function collectBouncedRecipients(request: CollectBouncesRequest): Promise<string[]> {\n const roles = request.includeDeletedItems ? [FolderId.Inbox, FolderId.DeletedItems] : [FolderId.Inbox];\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${DELIVERY_STORE_PS}\n${bounceClassifierScript()}\n${cutoffScript(request.daysBack)}\n$found = [ordered]@{}\nforeach ($role in @(${roles.map(psInt).join(', ')})) {\n $scanFolder = $null\n try { $scanFolder = $store.GetDefaultFolder($role) } catch {}\n if ($scanFolder -eq $null) { continue }\n ${itemsSinceScript('scanFolder', 'ReceivedTime').trim()}\n $count = $filtered.Count\n for ($i = 1; $i -le $count; $i++) {\n $item = $null\n try { $item = $filtered.Item($i) } catch { continue }\n if ($item -eq $null) { continue }\n $received = $null\n try { $received = $item.ReceivedTime } catch {}\n if ($received -ne $null -and $received -lt $cutoff) { continue }\n $report = Get-BounceReport $item\n if ($report -eq $null) { continue }\n foreach ($address in $report.failedRecipients) { $found[$address] = $true }\n }\n}\nConvertTo-Json -Compress -InputObject @($found.Keys)\n`, 'scan');\n return strList(output);\n}\n\n/**\n * Sent Items within the window, each message with the full SMTP address set it\n * went to (To + CC + BCC), newest first.\n */\nexport async function readSentRecipientGroups(request: SentGroupsRequest): Promise<SentRecipientGroup[]> {\n const output = await runPowerShellJson(`${accountScript(request.account)}\n${DELIVERY_STORE_PS}\n$sentFolder = $store.GetDefaultFolder(${psInt(FolderId.SentMail)})\n${cutoffScript(request.daysBack)}\n${itemsSinceScript('sentFolder', 'SentOn')}\n$filtered.Sort('[SentOn]', $true)\n$limit = ${psInt(request.limit)}\n$rows = @()\n$count = $filtered.Count\nfor ($i = 1; $i -le $count -and $rows.Count -lt $limit; $i++) {\n $m = $null\n try { $m = $filtered.Item($i) } catch { continue }\n if ($m -eq $null) { continue }\n $sentOn = $null\n try { $sentOn = $m.SentOn } catch {}\n if ($sentOn -ne $null -and $sentOn -lt $cutoff) { break }\n $class = 0\n try { $class = [int]$m.Class } catch {}\n if ($class -ne 43) { continue }\n $addresses = @()\n try {\n foreach ($r in $m.Recipients) {\n $address = ''\n try { $address = [string]$r.Address } catch {}\n # An internal recipient resolves to an Exchange DN; recover its SMTP address.\n if ($address -notlike '*@*') {\n try { $address = [string]$r.AddressEntry.GetExchangeUser().PrimarySmtpAddress } catch {}\n }\n if ($address -like '*@*') { $addresses += $address.ToLower() }\n }\n } catch {}\n if ($addresses.Count -eq 0) { continue }\n $rows += [PSCustomObject]@{\n entryId = [string]$m.EntryID\n subject = ([string]$m.Subject).Trim()\n sentOn = if ($sentOn -ne $null) { ${stampPs('$sentOn')} } else { '' }\n recipients = @($addresses)\n }\n}\nConvertTo-Json -Depth 4 -InputObject @($rows)\n`, 'scan');\n return toArray(output).map(row => {\n const e = record(row);\n return {\n entryId: str(e.entryId),\n subject: str(e.subject),\n sentOn: str(e.sentOn),\n recipients: strList(e.recipients),\n };\n });\n}\n"]}
|
|
@@ -6,7 +6,11 @@ import type { DeleteMailResult, PurgeDeletedItemsResult } from '../types';
|
|
|
6
6
|
*
|
|
7
7
|
* This is the one operation that can reach received mail, and an entry id is an
|
|
8
8
|
* unsafe key for it: a stale or wrong id can resolve to a DIFFERENT message.
|
|
9
|
-
*
|
|
9
|
+
* Four things hold the line:
|
|
10
|
+
* - An id that resolves outside this account's store is refused. The bare
|
|
11
|
+
* lookup falls back to the default store, and the Inbox/Sent check below
|
|
12
|
+
* only knows this account's folders, so another mailbox's received mail
|
|
13
|
+
* would otherwise pass it.
|
|
10
14
|
* - Inbox and Sent Items are refused, INCLUDING their subfolders (a filed
|
|
11
15
|
* folder is still received mail), unless `allowProtected`.
|
|
12
16
|
* - `dryRun` resolves and reports without deleting, so the exact subjects and
|