@dawnlit/outlook-bridge 1.1.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +152 -183
  2. package/dist/backend.d.ts +151 -0
  3. package/dist/backend.js +3 -0
  4. package/dist/backend.js.map +1 -0
  5. package/dist/bridge.d.ts +56 -0
  6. package/dist/bridge.js +507 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/errors.d.ts +79 -43
  9. package/dist/errors.js +93 -52
  10. package/dist/errors.js.map +1 -1
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +25 -52
  13. package/dist/index.js.map +1 -1
  14. package/dist/mac/accounts.d.ts +7 -2
  15. package/dist/mac/accounts.js +23 -6
  16. package/dist/mac/accounts.js.map +1 -1
  17. package/dist/mac/attachments.d.ts +5 -25
  18. package/dist/mac/attachments.js +40 -99
  19. package/dist/mac/attachments.js.map +1 -1
  20. package/dist/mac/bounces.d.ts +12 -27
  21. package/dist/mac/bounces.js +96 -117
  22. package/dist/mac/bounces.js.map +1 -1
  23. package/dist/mac/cleanup.d.ts +11 -25
  24. package/dist/mac/cleanup.js +44 -107
  25. package/dist/mac/cleanup.js.map +1 -1
  26. package/dist/mac/drafts.d.ts +15 -34
  27. package/dist/mac/drafts.js +113 -186
  28. package/dist/mac/drafts.js.map +1 -1
  29. package/dist/mac/folders.d.ts +12 -21
  30. package/dist/mac/folders.js +44 -59
  31. package/dist/mac/folders.js.map +1 -1
  32. package/dist/mac/index.d.ts +2 -22
  33. package/dist/mac/index.js +19 -81
  34. package/dist/mac/index.js.map +1 -1
  35. package/dist/mac/profile.d.ts +13 -0
  36. package/dist/mac/profile.js +149 -0
  37. package/dist/mac/profile.js.map +1 -0
  38. package/dist/mac/read.d.ts +21 -37
  39. package/dist/mac/read.js +198 -216
  40. package/dist/mac/read.js.map +1 -1
  41. package/dist/mac/run.d.ts +51 -38
  42. package/dist/mac/run.js +138 -103
  43. package/dist/mac/run.js.map +1 -1
  44. package/dist/mac/scripts.d.ts +90 -91
  45. package/dist/mac/scripts.js +167 -126
  46. package/dist/mac/scripts.js.map +1 -1
  47. package/dist/mac/send.d.ts +10 -20
  48. package/dist/mac/send.js +99 -89
  49. package/dist/mac/send.js.map +1 -1
  50. package/dist/mac/signatures.d.ts +2 -2
  51. package/dist/mac/signatures.js +9 -11
  52. package/dist/mac/signatures.js.map +1 -1
  53. package/dist/mac/templates.d.ts +14 -26
  54. package/dist/mac/templates.js +79 -120
  55. package/dist/mac/templates.js.map +1 -1
  56. package/dist/mail.d.ts +80 -46
  57. package/dist/mail.js +179 -73
  58. package/dist/mail.js.map +1 -1
  59. package/dist/runtime.d.ts +76 -43
  60. package/dist/runtime.js +103 -48
  61. package/dist/runtime.js.map +1 -1
  62. package/dist/shared/args.d.ts +48 -0
  63. package/dist/shared/args.js +216 -0
  64. package/dist/shared/args.js.map +1 -0
  65. package/dist/shared/attachmentMatch.d.ts +26 -20
  66. package/dist/shared/attachmentMatch.js +60 -23
  67. package/dist/shared/attachmentMatch.js.map +1 -1
  68. package/dist/shared/bounceReport.d.ts +11 -0
  69. package/dist/shared/bounceReport.js +45 -0
  70. package/dist/shared/bounceReport.js.map +1 -0
  71. package/dist/shared/bounceRules.d.ts +38 -10
  72. package/dist/shared/bounceRules.js +50 -32
  73. package/dist/shared/bounceRules.js.map +1 -1
  74. package/dist/shared/exec.d.ts +21 -0
  75. package/dist/shared/exec.js +47 -0
  76. package/dist/shared/exec.js.map +1 -0
  77. package/dist/shared/json.d.ts +17 -6
  78. package/dist/shared/json.js +35 -24
  79. package/dist/shared/json.js.map +1 -1
  80. package/dist/shared/locate.d.ts +31 -0
  81. package/dist/shared/locate.js +128 -0
  82. package/dist/shared/locate.js.map +1 -0
  83. package/dist/shared/replyBody.d.ts +31 -36
  84. package/dist/shared/replyBody.js +83 -72
  85. package/dist/shared/replyBody.js.map +1 -1
  86. package/dist/shared/templateLimits.d.ts +14 -0
  87. package/dist/shared/templateLimits.js +21 -0
  88. package/dist/shared/templateLimits.js.map +1 -0
  89. package/dist/templateBody.d.ts +69 -0
  90. package/dist/{outlookTemplateSections.js → templateBody.js} +80 -73
  91. package/dist/templateBody.js.map +1 -0
  92. package/dist/types.d.ts +381 -168
  93. package/dist/types.js +8 -9
  94. package/dist/types.js.map +1 -1
  95. package/dist/windows/accounts.d.ts +7 -12
  96. package/dist/windows/accounts.js +19 -34
  97. package/dist/windows/accounts.js.map +1 -1
  98. package/dist/windows/attachments.d.ts +9 -24
  99. package/dist/windows/attachments.js +94 -119
  100. package/dist/windows/attachments.js.map +1 -1
  101. package/dist/windows/bounces.d.ts +13 -26
  102. package/dist/windows/bounces.js +168 -200
  103. package/dist/windows/bounces.js.map +1 -1
  104. package/dist/windows/cleanup.d.ts +23 -23
  105. package/dist/windows/cleanup.js +99 -113
  106. package/dist/windows/cleanup.js.map +1 -1
  107. package/dist/windows/drafts.d.ts +16 -35
  108. package/dist/windows/drafts.js +156 -253
  109. package/dist/windows/drafts.js.map +1 -1
  110. package/dist/windows/folders.d.ts +8 -13
  111. package/dist/windows/folders.js +44 -52
  112. package/dist/windows/folders.js.map +1 -1
  113. package/dist/windows/index.d.ts +2 -27
  114. package/dist/windows/index.js +11 -66
  115. package/dist/windows/index.js.map +1 -1
  116. package/dist/windows/read.d.ts +24 -60
  117. package/dist/windows/read.js +265 -306
  118. package/dist/windows/read.js.map +1 -1
  119. package/dist/windows/run.d.ts +38 -40
  120. package/dist/windows/run.js +151 -112
  121. package/dist/windows/run.js.map +1 -1
  122. package/dist/windows/scripts.d.ts +65 -55
  123. package/dist/windows/scripts.js +109 -85
  124. package/dist/windows/scripts.js.map +1 -1
  125. package/dist/windows/send.d.ts +9 -9
  126. package/dist/windows/send.js +76 -88
  127. package/dist/windows/send.js.map +1 -1
  128. package/dist/windows/signatures.d.ts +4 -10
  129. package/dist/windows/signatures.js +30 -37
  130. package/dist/windows/signatures.js.map +1 -1
  131. package/dist/windows/templates.d.ts +12 -18
  132. package/dist/windows/templates.js +117 -150
  133. package/dist/windows/templates.js.map +1 -1
  134. package/package.json +5 -4
  135. package/dist/OutlookService.d.ts +0 -43
  136. package/dist/OutlookService.js +0 -137
  137. package/dist/OutlookService.js.map +0 -1
  138. package/dist/outlookTemplateSections.d.ts +0 -62
  139. package/dist/outlookTemplateSections.js.map +0 -1
  140. package/dist/shared/capabilities.d.ts +0 -3
  141. package/dist/shared/capabilities.js +0 -9
  142. package/dist/shared/capabilities.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/shared/json.ts"],"names":[],"mappings":";AAAA,6DAA6D;AAC7D,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,wEAAwE;;AAGxE,kCAGC;AAGD,gCAGC;AAGD,0BAEC;AAGD,wBAEC;AAED,kBAEC;AAED,kBAEC;AAED,0BAEC;AAhCD,gFAAgF;AAChF,SAAgB,WAAW,CAAC,GAAW;IACnC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IAC5D,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAA4B,CAAC;AAC7D,CAAC;AAED,gFAAgF;AAChF,SAAgB,UAAU,CAAC,GAAW;IAClC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IAC5D,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,oFAAoF;AACpF,SAAgB,OAAO,CAAC,KAAc;IAClC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAA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AK,CAAC,EAAE,CAAC;IACrF,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Coercing the JSON a PowerShell script prints into the package's types.\n//\n// ConvertTo-Json has two habits a caller must never see: it unwraps a\n// single-element array into a bare object, and it renders an empty one as\n// nothing at all. Every list crossing that boundary goes through `toArray`, and\n// every scalar through a coercion that survives a missing property.\nimport type { ItemFailure } from '../types';\n\n/** One value as a list: an array stays, null and undefined become empty, anything else wraps. */\nexport function toArray(value: unknown): unknown[] {\n return Array.isArray(value) ? value : value == null ? [] : [value];\n}\n\n/** A value as a plain object, for reading fields off one row. */\nexport function record(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n}\n\nexport function str(value: unknown): string {\n return value == null ? '' : String(value);\n}\n\nexport function num(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nexport function bool(value: unknown): boolean {\n return value === true;\n}\n\n/** A list of non-empty strings. */\nexport function strList(value: unknown): string[] {\n return toArray(value).map(str).filter(Boolean);\n}\n\n/** A base64 field decoded as UTF-8 — how scripts pass bodies that must survive intact. */\nexport function base64Text(value: unknown): string {\n return Buffer.from(str(value), 'base64').toString('utf8');\n}\n\n/**\n * The PowerShell that appends one item's failure to `$failed`, inside the\n * `catch` of a per-item loop: the row `itemFailures` reads back, written once\n * so no script can name its fields differently. `idVariable` holds the item's\n * id. `$subject` must be reset before each item's `try`, or a failure reports\n * the previous item's subject.\n */\nexport function itemFailurePs(idVariable: '$id' | '$entryId'): string {\n return `$failed += [PSCustomObject]@{ entryId = ${idVariable}; subject = $subject; error = $_.Exception.Message }`;\n}\n\n/** A list of per-item failures, as `itemFailurePs` writes them. */\nexport function itemFailures(value: unknown): ItemFailure[] {\n return toArray(value).map(row => {\n const e = record(row);\n return { entryId: str(e.entryId), subject: str(e.subject), error: str(e.error) };\n });\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import type { InboxSearchMatch } from '../types';
2
+ /** The fields a match is judged on, trimmed; blank means not given. */
3
+ export interface WantedEmail {
4
+ readonly subject?: string;
5
+ readonly sender?: string;
6
+ readonly receivedTime?: string;
7
+ }
8
+ /** INVALID_REQUEST unless the description gives enough to tell one email from its thread. */
9
+ export declare function requireDescribed(wanted: WantedEmail): void;
10
+ /**
11
+ * The subject glob to prefilter a search with: the longest run of plain
12
+ * characters in the subject, or undefined when there's no run of four.
13
+ *
14
+ * A subject can hold an apostrophe or a `*`, and the prefilter becomes a query
15
+ * on some stores; it only has to be selective, since every result is judged on
16
+ * the whole subject afterwards.
17
+ */
18
+ export declare function subjectPrefilter(subject: string | undefined): string | undefined;
19
+ /**
20
+ * How far back a search has to reach to cover the day the email arrived, or
21
+ * `fallback` when no day is known. Two days of slack cover whichever timezone
22
+ * the stamp was written in, and a search started either side of midnight.
23
+ */
24
+ export declare function daysBackFor(receivedTime: string | undefined, fallback: number, now?: number): number;
25
+ /** The best match, or null when nothing agrees with the description. */
26
+ export declare function bestMatch(wanted: WantedEmail, matches: readonly InboxSearchMatch[]): InboxSearchMatch | null;
27
+ /**
28
+ * Accounts in the order to search them: the one a listing's folderPath names
29
+ * first (`\\team@example.com\Inbox\…`), then the rest as given.
30
+ */
31
+ export declare function accountSearchOrder(accounts: readonly string[], folderPath: string | undefined): string[];
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireDescribed = requireDescribed;
4
+ exports.subjectPrefilter = subjectPrefilter;
5
+ exports.daysBackFor = daysBackFor;
6
+ exports.bestMatch = bestMatch;
7
+ exports.accountSearchOrder = accountSearchOrder;
8
+ // Finding an email again from what was kept about it: the rules, as pure
9
+ // functions. The search itself is an ordinary searchInboxByFilter per mailbox;
10
+ // what lives here is how narrow that search can be made, and which of its
11
+ // results is the email.
12
+ //
13
+ // The rules never guess. Every field the description gives has to agree, and at
14
+ // least two have to be given, because a subject alone names every message in a
15
+ // thread. A miss stays a miss rather than returning somebody else's email.
16
+ const mail_1 = require("../mail");
17
+ const errors_1 = require("../errors");
18
+ /** `yyyy-MM-dd`, optionally followed by ` HH:mm` — how both platforms stamp a received time. */
19
+ const STAMP = /^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2})?/;
20
+ /** An address inside a sender string, which may be a name, an address, or both. */
21
+ const ADDRESS = /[^\s<>,;"']+@[^\s<>,;"']+/;
22
+ const DAY_MS = 86_400_000;
23
+ const subjectKey = (subject) => (0, mail_1.threadSubject)(subject).toLowerCase();
24
+ /**
25
+ * The stamp in the listings' own form (`yyyy-MM-dd HH:mm`), or '' when it isn't
26
+ * a stamp at all — which is then treated as not given, since it can't disagree
27
+ * with anything.
28
+ */
29
+ function stampOf(receivedTime) {
30
+ const match = STAMP.exec((receivedTime ?? '').trim());
31
+ return match ? match[0].replace('T', ' ') : '';
32
+ }
33
+ /** How many of the three fields the description actually gives. */
34
+ function recordedCount(wanted) {
35
+ return (wanted.subject ? 1 : 0) + (wanted.sender ? 1 : 0) + (stampOf(wanted.receivedTime) ? 1 : 0);
36
+ }
37
+ /** INVALID_REQUEST unless the description gives enough to tell one email from its thread. */
38
+ function requireDescribed(wanted) {
39
+ if (recordedCount(wanted) < 2) {
40
+ throw new errors_1.InvalidRequestError('Describe the email by at least two of subject, sender and receivedTime (as yyyy-MM-dd HH:mm): '
41
+ + 'a subject alone names every message in its thread.');
42
+ }
43
+ }
44
+ /**
45
+ * The subject glob to prefilter a search with: the longest run of plain
46
+ * characters in the subject, or undefined when there's no run of four.
47
+ *
48
+ * A subject can hold an apostrophe or a `*`, and the prefilter becomes a query
49
+ * on some stores; it only has to be selective, since every result is judged on
50
+ * the whole subject afterwards.
51
+ */
52
+ function subjectPrefilter(subject) {
53
+ const longest = ((0, mail_1.threadSubject)(subject ?? '').match(/[A-Za-z0-9 ._-]+/g) ?? [])
54
+ .map(run => run.trim())
55
+ .sort((a, b) => b.length - a.length)[0] ?? '';
56
+ return longest.length >= 4 ? `*${longest}*` : undefined;
57
+ }
58
+ /**
59
+ * How far back a search has to reach to cover the day the email arrived, or
60
+ * `fallback` when no day is known. Two days of slack cover whichever timezone
61
+ * the stamp was written in, and a search started either side of midnight.
62
+ */
63
+ function daysBackFor(receivedTime, fallback, now = Date.now()) {
64
+ const stamp = stampOf(receivedTime);
65
+ if (!stamp)
66
+ return fallback;
67
+ const day = Date.parse(`${stamp.slice(0, 10)}T00:00:00Z`);
68
+ if (Number.isNaN(day))
69
+ return fallback;
70
+ return Math.max(1, Math.floor((now - day) / DAY_MS) + 2);
71
+ }
72
+ /** Whether a found email came from the sender described. */
73
+ function senderMatches(wanted, match) {
74
+ const want = wanted.toLowerCase();
75
+ const address = ADDRESS.exec(want)?.[0];
76
+ if (address)
77
+ return address === match.senderEmail.trim().toLowerCase();
78
+ const name = match.senderName.trim().toLowerCase();
79
+ return name !== '' && (want.includes(name) || name.includes(want));
80
+ }
81
+ /**
82
+ * How well a found email answers the description, or 0 for "not this one".
83
+ *
84
+ * Disagreement on any given field disqualifies outright. Agreement is then
85
+ * ranked, so an exact minute beats the same day: a sender who wrote twice in
86
+ * one afternoon still resolves to the email described.
87
+ */
88
+ function matchScore(wanted, match) {
89
+ if (recordedCount(wanted) < 2)
90
+ return 0;
91
+ const wantSubject = wanted.subject ? subjectKey(wanted.subject) : '';
92
+ if (wantSubject && subjectKey(match.subject) !== wantSubject)
93
+ return 0;
94
+ if (wanted.sender && !senderMatches(wanted.sender, match))
95
+ return 0;
96
+ const stamp = stampOf(wanted.receivedTime);
97
+ const found = match.receivedTime.trim();
98
+ const sameDay = stamp !== '' && stamp.slice(0, 10) === found.slice(0, 10);
99
+ const sameMinute = sameDay && stamp.length >= 16 && stamp.slice(0, 16) === found.slice(0, 16);
100
+ if (stamp && !sameDay)
101
+ return 0;
102
+ return (wantSubject ? 1 : 0) + (wanted.sender ? 2 : 0) + (sameMinute ? 3 : sameDay ? 1 : 0);
103
+ }
104
+ /** The best match, or null when nothing agrees with the description. */
105
+ function bestMatch(wanted, matches) {
106
+ let best = null;
107
+ let bestScore = 0;
108
+ for (const match of matches) {
109
+ const score = matchScore(wanted, match);
110
+ if (score > bestScore) {
111
+ best = match;
112
+ bestScore = score;
113
+ }
114
+ }
115
+ return best;
116
+ }
117
+ /**
118
+ * Accounts in the order to search them: the one a listing's folderPath names
119
+ * first (`\\team@example.com\Inbox\…`), then the rest as given.
120
+ */
121
+ function accountSearchOrder(accounts, folderPath) {
122
+ const path = (folderPath ?? '').toLowerCase();
123
+ if (!path)
124
+ return [...accounts];
125
+ const named = accounts.filter(account => path.includes(account.toLowerCase()));
126
+ return [...named, ...accounts.filter(account => !named.includes(account))];
127
+ }
128
+ //# sourceMappingURL=locate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locate.js","sourceRoot":"","sources":["../../src/shared/locate.ts"],"names":[],"mappings":";;AA6CA,4CAOC;AAUD,4CAKC;AAOD,kCAMC;AAmCD,8BAWC;AAMD,gDAKC;AAzID,yEAAyE;AACzE,+EAA+E;AAC/E,0EAA0E;AAC1E,wBAAwB;AACxB,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,2EAA2E;AAC3E,kCAAwC;AACxC,sCAAgD;AAUhD,gGAAgG;AAChG,MAAM,KAAK,GAAG,sCAAsC,CAAC;AAErD,mFAAmF;AACnF,MAAM,OAAO,GAAG,2BAA2B,CAAC;AAE5C,MAAM,MAAM,GAAG,UAAU,CAAC;AAE1B,MAAM,UAAU,GAAG,CAAC,OAAe,EAAU,EAAE,CAAC,IAAA,oBAAa,EAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;AAErF;;;;GAIG;AACH,SAAS,OAAO,CAAC,YAAgC;IAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACtD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE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AC1B,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACxC,IAAI,KAAK,GAAG,SAAS,EAAE,CAAC;YACpB,IAAI,GAAG,KAAK,CAAC;YACb,SAAS,GAAG,KAAK,CAAC;QACtB,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,QAA2B,EAAE,UAA8B;IAC1F,MAAM,IAAI,GAAG,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAC9C,IAAI,CAAC,IAAI;QAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;IAChC,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;IAC/E,OAAO,CAAC,GAAG,KAAK,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["// Finding an email again from what was kept about it: the rules, as pure\n// functions. The search itself is an ordinary searchInboxByFilter per mailbox;\n// what lives here is how narrow that search can be made, and which of its\n// results is the email.\n//\n// The rules never guess. Every field the description gives has to agree, and at\n// least two have to be given, because a subject alone names every message in a\n// thread. A miss stays a miss rather than returning somebody else's email.\nimport { threadSubject } from '../mail';\nimport { InvalidRequestError } from '../errors';\nimport type { InboxSearchMatch } from '../types';\n\n/** The fields a match is judged on, trimmed; blank means not given. */\nexport interface WantedEmail {\n readonly subject?: string;\n readonly sender?: string;\n readonly receivedTime?: string;\n}\n\n/** `yyyy-MM-dd`, optionally followed by ` HH:mm` — how both platforms stamp a received time. */\nconst STAMP = /^\\d{4}-\\d{2}-\\d{2}([ T]\\d{2}:\\d{2})?/;\n\n/** An address inside a sender string, which may be a name, an address, or both. */\nconst ADDRESS = /[^\\s<>,;\"']+@[^\\s<>,;\"']+/;\n\nconst DAY_MS = 86_400_000;\n\nconst subjectKey = (subject: string): string => threadSubject(subject).toLowerCase();\n\n/**\n * The stamp in the listings' own form (`yyyy-MM-dd HH:mm`), or '' when it isn't\n * a stamp at all — which is then treated as not given, since it can't disagree\n * with anything.\n */\nfunction stampOf(receivedTime: string | undefined): string {\n const match = STAMP.exec((receivedTime ?? '').trim());\n return match ? match[0].replace('T', ' ') : '';\n}\n\n/** How many of the three fields the description actually gives. */\nfunction recordedCount(wanted: WantedEmail): number {\n return (wanted.subject ? 1 : 0) + (wanted.sender ? 1 : 0) + (stampOf(wanted.receivedTime) ? 1 : 0);\n}\n\n/** INVALID_REQUEST unless the description gives enough to tell one email from its thread. */\nexport function requireDescribed(wanted: WantedEmail): void {\n if (recordedCount(wanted) < 2) {\n throw new InvalidRequestError(\n 'Describe the email by at least two of subject, sender and receivedTime (as yyyy-MM-dd HH:mm): '\n + 'a subject alone names every message in its thread.',\n );\n }\n}\n\n/**\n * The subject glob to prefilter a search with: the longest run of plain\n * characters in the subject, or undefined when there's no run of four.\n *\n * A subject can hold an apostrophe or a `*`, and the prefilter becomes a query\n * on some stores; it only has to be selective, since every result is judged on\n * the whole subject afterwards.\n */\nexport function subjectPrefilter(subject: string | undefined): string | undefined {\n const longest = (threadSubject(subject ?? '').match(/[A-Za-z0-9 ._-]+/g) ?? [])\n .map(run => run.trim())\n .sort((a, b) => b.length - a.length)[0] ?? '';\n return longest.length >= 4 ? `*${longest}*` : undefined;\n}\n\n/**\n * How far back a search has to reach to cover the day the email arrived, or\n * `fallback` when no day is known. Two days of slack cover whichever timezone\n * the stamp was written in, and a search started either side of midnight.\n */\nexport function daysBackFor(receivedTime: string | undefined, fallback: number, now = Date.now()): number {\n const stamp = stampOf(receivedTime);\n if (!stamp) return fallback;\n const day = Date.parse(`${stamp.slice(0, 10)}T00:00:00Z`);\n if (Number.isNaN(day)) return fallback;\n return Math.max(1, Math.floor((now - day) / DAY_MS) + 2);\n}\n\n/** Whether a found email came from the sender described. */\nfunction senderMatches(wanted: string, match: InboxSearchMatch): boolean {\n const want = wanted.toLowerCase();\n const address = ADDRESS.exec(want)?.[0];\n if (address) return address === match.senderEmail.trim().toLowerCase();\n const name = match.senderName.trim().toLowerCase();\n return name !== '' && (want.includes(name) || name.includes(want));\n}\n\n/**\n * How well a found email answers the description, or 0 for \"not this one\".\n *\n * Disagreement on any given field disqualifies outright. Agreement is then\n * ranked, so an exact minute beats the same day: a sender who wrote twice in\n * one afternoon still resolves to the email described.\n */\nfunction matchScore(wanted: WantedEmail, match: InboxSearchMatch): number {\n if (recordedCount(wanted) < 2) return 0;\n\n const wantSubject = wanted.subject ? subjectKey(wanted.subject) : '';\n if (wantSubject && subjectKey(match.subject) !== wantSubject) return 0;\n if (wanted.sender && !senderMatches(wanted.sender, match)) return 0;\n\n const stamp = stampOf(wanted.receivedTime);\n const found = match.receivedTime.trim();\n const sameDay = stamp !== '' && stamp.slice(0, 10) === found.slice(0, 10);\n const sameMinute = sameDay && stamp.length >= 16 && stamp.slice(0, 16) === found.slice(0, 16);\n if (stamp && !sameDay) return 0;\n\n return (wantSubject ? 1 : 0) + (wanted.sender ? 2 : 0) + (sameMinute ? 3 : sameDay ? 1 : 0);\n}\n\n/** The best match, or null when nothing agrees with the description. */\nexport function bestMatch(wanted: WantedEmail, matches: readonly InboxSearchMatch[]): InboxSearchMatch | null {\n let best: InboxSearchMatch | null = null;\n let bestScore = 0;\n for (const match of matches) {\n const score = matchScore(wanted, match);\n if (score > bestScore) {\n best = match;\n bestScore = score;\n }\n }\n return best;\n}\n\n/**\n * Accounts in the order to search them: the one a listing's folderPath names\n * first (`\\\\team@example.com\\Inbox\\…`), then the rest as given.\n */\nexport function accountSearchOrder(accounts: readonly string[], folderPath: string | undefined): string[] {\n const path = (folderPath ?? '').toLowerCase();\n if (!path) return [...accounts];\n const named = accounts.filter(account => path.includes(account.toLowerCase()));\n return [...named, ...accounts.filter(account => !named.includes(account))];\n}\n"]}
@@ -1,49 +1,44 @@
1
- import type { ReplyEmailParams, TemplateFolderResult } from '../types';
2
- /** The reads a platform must supply for a template- or signature-backed reply. */
1
+ import type { ReadTemplatesRequest } from '../backend';
2
+ import type { TemplateFolderResult } from '../types';
3
+ /** The reads a template- or signature-backed reply needs. */
3
4
  export interface ReplyBodyDeps {
4
- readTemplateEmails(emailAccount: string, folderName?: string, limit?: number, includeBody?: boolean, subject?: string): Promise<TemplateFolderResult>;
5
+ readTemplateEmails(request: ReadTemplatesRequest): Promise<TemplateFolderResult>;
5
6
  readOutlookSignatureHtml(name: string): Promise<string>;
6
7
  listOutlookSignatures(): Promise<string[]>;
7
8
  }
9
+ /** A reply's content, as the caller described it — already validated. */
10
+ export interface ReplyContent {
11
+ readonly account: string;
12
+ readonly htmlBody?: string;
13
+ readonly templateSubject?: string;
14
+ readonly templateFolder: string;
15
+ readonly templateSection?: string;
16
+ readonly templatePlaceholders?: Readonly<Record<string, string>>;
17
+ readonly signatureName?: string;
18
+ }
19
+ /** A named signature's HTML, ready to insert into a body; NOT_FOUND naming the ones there are. */
20
+ export declare function resolveSignatureHtml(deps: Pick<ReplyBodyDeps, 'readOutlookSignatureHtml' | 'listOutlookSignatures'>, name: string): Promise<string>;
8
21
  /**
9
- * The content of an HTML document's `<body>`, or the input when there is no
10
- * document around it.
11
- *
12
- * Both things this is used on — a signature file and a saved template — are whole
13
- * HTML documents, and neither may nest its `<html>`/`<body>` inside the reply's.
22
+ * Sign a body: in its `{{SIGNATURE}}` placeholder when it has one, otherwise at
23
+ * the end, where Outlook itself would put a signature. In a whole document the
24
+ * end is just inside `</body>`, since anything after `</html>` is outside the
25
+ * email.
14
26
  */
15
- export declare function innerBodyHtml(html: string): string;
16
- /**
17
- * Resolve a saved template's HTML by subject, so a reply can name a template
18
- * instead of carrying its (often large, Word-generated) HTML.
19
- *
20
- * The read is filtered by subject in the platform layer rather than here:
21
- * unfiltered, EVERY template's full body crosses the interpreter's stdout on
22
- * every reply, and a folder of Word-sized templates overruns the buffer outright
23
- * — turning a growing Templates folder into a failure on a call that never
24
- * needed more than one body.
25
- */
26
- export declare function resolveTemplateHtmlBySubject(deps: ReplyBodyDeps, emailAccount: string, folderName: string, subject: string): Promise<string>;
27
+ export declare function placeSignature(html: string, signature: string): string;
27
28
  /**
28
29
  * The HTML to insert above the quoted original: template resolved, section
29
- * chosen, placeholders and signature filled, document wrapper removed.
30
+ * kept, placeholders and signature filled, document wrapper removed.
30
31
  *
31
- * Composition also runs (with no options) on any body taken straight from a
32
- * template, so a stray [[SECTION]] marker is caught here rather than mailed to a
33
- * customer.
32
+ * A body taken from a template is always put through composition, even with
33
+ * nothing to fill, so a stray [[SECTION]] marker is caught here rather than
34
+ * mailed out.
34
35
  */
35
- export declare function composeReplyHtml(params: ReplyEmailParams, deps: ReplyBodyDeps): Promise<string>;
36
+ export declare function composeReplyHtml(content: ReplyContent, deps: ReplyBodyDeps): Promise<string>;
36
37
  /**
37
- * Where the new text goes in an Outlook-built reply.
38
- *
39
- * Outlook builds the reply body as a Word document whose own (empty) paragraph
40
- * sits inside `WordSection1`; inserting straight after that div's opening tag is
41
- * what puts the new text where the user's cursor would have been. A reply
42
- * Outlook did not build that way falls back to just inside `<body>`.
43
- *
44
- * The insertion itself cannot live here — the reply HTML never leaves Outlook,
45
- * so each platform splices it in its own language (`windows/send.ts`, and the
46
- * `insertAboveQuoted` handler in `mac/run.ts`). The anchor both of them look for
47
- * is the one part they must agree on, so it is stated once, here.
38
+ * Where the new text goes in an Outlook-built reply: straight after the opening
39
+ * of `WordSection1`, the div holding the empty paragraph where a person's cursor
40
+ * would be. A reply Outlook didn't build that way falls back to just inside
41
+ * `<body>`. The insertion itself happens in each platform's own language, since
42
+ * the reply HTML never leaves Outlook; this anchor is the part both must agree on.
48
43
  */
49
44
  export declare const WORD_SECTION_ANCHOR = "WordSection1>";
@@ -1,113 +1,124 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WORD_SECTION_ANCHOR = void 0;
4
- exports.innerBodyHtml = innerBodyHtml;
5
- exports.resolveTemplateHtmlBySubject = resolveTemplateHtmlBySubject;
4
+ exports.resolveSignatureHtml = resolveSignatureHtml;
5
+ exports.placeSignature = placeSignature;
6
6
  exports.composeReplyHtml = composeReplyHtml;
7
- // Everything replyOutlookEmail does BEFORE it touches Outlook.
8
- //
9
- // Resolving a named template, filling {{PLACEHOLDER}}s, substituting a named
10
- // signature and reducing the result to insertable HTML is identical work on both
11
- // platforms — it is string handling plus two reads that each platform already
12
- // implements. Keeping it here is what lets macOS answer the same
13
- // ReplyEmailParams contract Windows does instead of a subset of it.
14
- const outlookTemplateSections_1 = require("../outlookTemplateSections");
7
+ // Everything a reply needs before it touches Outlook: resolving a named
8
+ // template, keeping its section, filling placeholders and a named signature,
9
+ // and reducing the result to HTML that can be inserted into another document.
10
+ // Signing a new email uses the signature half of it. String work plus three
11
+ // reads each platform already provides, so it is done once here for both.
12
+ const templateBody_1 = require("../templateBody");
15
13
  const errors_1 = require("../errors");
16
14
  /**
17
- * The content of an HTML document's `<body>`, or the input when there is no
18
- * document around it.
19
- *
20
- * Both things this is used on — a signature file and a saved template — are whole
21
- * HTML documents, and neither may nest its `<html>`/`<body>` inside the reply's.
15
+ * The content of an HTML document's `<body>`, or the input when it isn't a
16
+ * whole document. Signature files and saved templates are both whole documents,
17
+ * and neither may nest its `<html>`/`<body>` inside another email's.
22
18
  */
23
19
  function innerBodyHtml(html) {
24
20
  const match = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html);
25
21
  return (match ? match[1] : html).trim();
26
22
  }
27
23
  /**
28
- * Resolve a saved template's HTML by subject, so a reply can name a template
29
- * instead of carrying its (often large, Word-generated) HTML.
24
+ * A saved template's HTML, found by subject.
30
25
  *
31
- * The read is filtered by subject in the platform layer rather than here:
32
- * unfiltered, EVERY template's full body crosses the interpreter's stdout on
33
- * every reply, and a folder of Word-sized templates overruns the buffer outright
34
- * — turning a growing Templates folder into a failure on a call that never
35
- * needed more than one body.
26
+ * The read is filtered by subject in the platform script: unfiltered, EVERY
27
+ * template's full body would cross the interpreter's stdout on every reply, and
28
+ * a folder of Word-sized templates overruns the output limit on a call that
29
+ * only ever needed one of them.
36
30
  */
37
- async function resolveTemplateHtmlBySubject(deps, emailAccount, folderName, subject) {
38
- const result = await deps.readTemplateEmails(emailAccount, folderName, 50, true, subject);
31
+ async function resolveTemplateHtml(deps, account, folder, subject) {
32
+ const result = await deps.readTemplateEmails({ account, folder, limit: 50, includeBody: true, subject });
39
33
  if (!result.folderFound) {
40
34
  const folders = result.availableFolders.join(', ') || '(none)';
41
- throw new errors_1.NotFoundError('folder', `Template folder '${folderName}' not found in ${emailAccount}. Available folders: ${folders}.`);
35
+ throw new errors_1.NotFoundError('folder', `Template folder '${folder}' not found in ${account}. Top-level folders: ${folders}.`);
42
36
  }
43
- const want = subject.trim().toLowerCase();
44
- const match = result.templates.find(t => t.subject.trim().toLowerCase() === want);
37
+ const wanted = subject.trim().toLowerCase();
38
+ const match = result.templates.find(t => t.subject.trim().toLowerCase() === wanted);
45
39
  if (!match) {
46
- // The read above was filtered, so it can't name the alternatives. List them
47
- // in a second pass with bodies omitted — which is what makes reading the
48
- // whole folder safe here, and keeps the error as useful as it was before
49
- // the filter.
50
- const all = await deps.readTemplateEmails(emailAccount, folderName, 50, false);
40
+ // The read above was filtered, so it can't name the alternatives. A
41
+ // second read without bodies can, cheaply.
42
+ const all = await deps.readTemplateEmails({ account, folder, limit: 200, includeBody: false });
51
43
  const names = all.templates.map(t => t.subject).filter(Boolean).join(', ') || '(none)';
52
- throw new errors_1.NotFoundError('template', `Template '${subject}' not found in '${folderName}'. Available templates: ${names}.`);
44
+ throw new errors_1.NotFoundError('template', `Template '${subject}' not found in '${folder}'. Templates there: ${names}.`);
53
45
  }
54
- if (!match.htmlBody || match.htmlBody.trim() === '') {
46
+ if (match.htmlBody.trim() === '') {
55
47
  throw new errors_1.NotFoundError('template', `Template '${subject}' has an empty HTML body.`);
56
48
  }
57
49
  return match.htmlBody;
58
50
  }
51
+ /** Where a template asks for the signature. */
52
+ const SIGNATURE_TOKEN = '{{SIGNATURE}}';
53
+ /** A named signature's HTML, ready to insert into a body; NOT_FOUND naming the ones there are. */
54
+ async function resolveSignatureHtml(deps, name) {
55
+ const signatureHtml = await deps.readOutlookSignatureHtml(name);
56
+ if (signatureHtml.trim() === '') {
57
+ const available = (await deps.listOutlookSignatures()).join(', ') || '(none)';
58
+ throw new errors_1.NotFoundError('signature', `Outlook signature '${name}' not found. Signatures on this machine: ${available}.`);
59
+ }
60
+ return innerBodyHtml(signatureHtml);
61
+ }
62
+ /** Whether a body says where its signature goes. */
63
+ function asksForSignature(html) {
64
+ return (0, templateBody_1.findTokens)(html, [SIGNATURE_TOKEN]).length > 0;
65
+ }
66
+ /**
67
+ * Sign a body: in its `{{SIGNATURE}}` placeholder when it has one, otherwise at
68
+ * the end, where Outlook itself would put a signature. In a whole document the
69
+ * end is just inside `</body>`, since anything after `</html>` is outside the
70
+ * email.
71
+ */
72
+ function placeSignature(html, signature) {
73
+ if (asksForSignature(html))
74
+ return (0, templateBody_1.replaceToken)(html, SIGNATURE_TOKEN, signature);
75
+ const block = `<br>${signature}`;
76
+ const close = html.toLowerCase().lastIndexOf('</body');
77
+ return close === -1 ? html + block : html.slice(0, close) + block + html.slice(close);
78
+ }
59
79
  /**
60
80
  * The HTML to insert above the quoted original: template resolved, section
61
- * chosen, placeholders and signature filled, document wrapper removed.
81
+ * kept, placeholders and signature filled, document wrapper removed.
62
82
  *
63
- * Composition also runs (with no options) on any body taken straight from a
64
- * template, so a stray [[SECTION]] marker is caught here rather than mailed to a
65
- * customer.
83
+ * A body taken from a template is always put through composition, even with
84
+ * nothing to fill, so a stray [[SECTION]] marker is caught here rather than
85
+ * mailed out.
66
86
  */
67
- async function composeReplyHtml(params, deps) {
68
- let htmlBody = params.htmlBody;
87
+ async function composeReplyHtml(content, deps) {
88
+ let html = content.htmlBody;
69
89
  let fromTemplate = false;
70
- if ((!htmlBody || htmlBody.trim() === '') && params.templateSubject) {
71
- htmlBody = await resolveTemplateHtmlBySubject(deps, params.emailAccount, params.templateFolder || 'Templates', params.templateSubject);
90
+ if ((!html || html.trim() === '') && content.templateSubject) {
91
+ html = await resolveTemplateHtml(deps, content.account, content.templateFolder, content.templateSubject);
72
92
  fromTemplate = true;
73
93
  }
74
- if (!htmlBody || htmlBody.trim() === '') {
75
- throw new errors_1.InvalidRequestError('replyOutlookEmail needs either htmlBody or a resolvable templateSubject.');
76
- }
77
- // A named signature fills {{SIGNATURE}} like any other placeholder, but is
78
- // read here so the caller never carries the signature HTML — images and all —
79
- // across the wire.
80
- let placeholders = params.templatePlaceholders;
81
- if (params.signatureName) {
82
- const signatureHtml = await deps.readOutlookSignatureHtml(params.signatureName);
83
- if (signatureHtml.trim() === '') {
84
- const available = (await deps.listOutlookSignatures()).join(', ') || '(none)';
85
- throw new errors_1.NotFoundError('signature', `Outlook signature '${params.signatureName}' not found. Available signatures: ${available}.`);
86
- }
87
- placeholders = { ...placeholders, SIGNATURE: innerBodyHtml(signatureHtml) };
94
+ if (!html || html.trim() === '') {
95
+ throw new errors_1.InvalidRequestError('A reply needs either htmlBody or templateSubject.');
88
96
  }
97
+ // A signature with a placeholder to go in is filled with the others, so
98
+ // one that sat in a dropped section goes with it. Without one it is added
99
+ // below the new text once everything else is composed.
100
+ let placeholders = content.templatePlaceholders;
101
+ const signature = content.signatureName ? await resolveSignatureHtml(deps, content.signatureName) : '';
102
+ const signatureInPlace = signature !== '' && asksForSignature(html);
103
+ if (signatureInPlace)
104
+ placeholders = { ...placeholders, SIGNATURE: signature };
89
105
  const hasPlaceholders = !!placeholders && Object.keys(placeholders).length > 0;
90
- if (fromTemplate || params.templateSection || hasPlaceholders) {
91
- htmlBody = (0, outlookTemplateSections_1.composeTemplateBody)(htmlBody, {
92
- section: params.templateSection,
106
+ if (fromTemplate || content.templateSection || hasPlaceholders) {
107
+ html = (0, templateBody_1.composeTemplateBody)(html, {
108
+ section: content.templateSection,
93
109
  placeholders,
94
- label: params.templateSubject,
110
+ label: content.templateSubject,
95
111
  });
96
112
  }
97
- return innerBodyHtml(htmlBody);
113
+ const body = innerBodyHtml(html);
114
+ return signature !== '' && !signatureInPlace ? placeSignature(body, signature) : body;
98
115
  }
99
116
  /**
100
- * Where the new text goes in an Outlook-built reply.
101
- *
102
- * Outlook builds the reply body as a Word document whose own (empty) paragraph
103
- * sits inside `WordSection1`; inserting straight after that div's opening tag is
104
- * what puts the new text where the user's cursor would have been. A reply
105
- * Outlook did not build that way falls back to just inside `<body>`.
106
- *
107
- * The insertion itself cannot live here — the reply HTML never leaves Outlook,
108
- * so each platform splices it in its own language (`windows/send.ts`, and the
109
- * `insertAboveQuoted` handler in `mac/run.ts`). The anchor both of them look for
110
- * is the one part they must agree on, so it is stated once, here.
117
+ * Where the new text goes in an Outlook-built reply: straight after the opening
118
+ * of `WordSection1`, the div holding the empty paragraph where a person's cursor
119
+ * would be. A reply Outlook didn't build that way falls back to just inside
120
+ * `<body>`. The insertion itself happens in each platform's own language, since
121
+ * the reply HTML never leaves Outlook; this anchor is the part both must agree on.
111
122
  */
112
123
  exports.WORD_SECTION_ANCHOR = 'WordSection1>';
113
124
  //# sourceMappingURL=replyBody.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"replyBody.js","sourceRoot":"","sources":["../../src/shared/replyBody.ts"],"names":[],"mappings":";;;AAiCA,sCAGC;AAYD,oEAgCC;AAUD,4CA8CC;AAxID,+DAA+D;AAC/D,EAAE;AACF,6EAA6E;AAC7E,iFAAiF;AACjF,8EAA8E;AAC9E,iEAAiE;AACjE,oEAAoE;AACpE,wEAAiE;AACjE,sCAA+D;AAkB/D;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,IAAY;IACtC,MAAM,KAAK,GAAG,+BAA+B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,C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,SAAS,EAAE,SAAS,EAAE,CAAC;IAE/E,MAAM,eAAe,GAAG,CAAC,CAAC,YAAY,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAC/E,IAAI,YAAY,IAAI,OAAO,CAAC,eAAe,IAAI,eAAe,EAAE,CAAC;QAC7D,IAAI,GAAG,IAAA,kCAAmB,EAAC,IAAI,EAAE;YAC7B,OAAO,EAAE,OAAO,CAAC,eAAe;YAChC,YAAY;YACZ,KAAK,EAAE,OAAO,CAAC,eAAe;SACjC,CAAC,CAAC;IACP,CAAC;IACD,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IACjC,OAAO,SAAS,KAAK,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1F,CAAC;AAED;;;;;;GAMG;AACU,QAAA,mBAAmB,GAAG,eAAe,CAAC","sourcesContent":["// Everything a reply needs before it touches Outlook: resolving a named\n// template, keeping its section, filling placeholders and a named signature,\n// and reducing the result to HTML that can be inserted into another document.\n// Signing a new email uses the signature half of it. String work plus three\n// reads each platform already provides, so it is done once here for both.\nimport { composeTemplateBody, findTokens, replaceToken } from '../templateBody';\nimport { InvalidRequestError, NotFoundError } from '../errors';\nimport type { ReadTemplatesRequest } from '../backend';\nimport type { TemplateFolderResult } from '../types';\n\n/** The reads a template- or signature-backed reply needs. */\nexport interface ReplyBodyDeps {\n readTemplateEmails(request: ReadTemplatesRequest): Promise<TemplateFolderResult>;\n\n readOutlookSignatureHtml(name: string): Promise<string>;\n\n listOutlookSignatures(): Promise<string[]>;\n}\n\n/** A reply's content, as the caller described it — already validated. */\nexport interface ReplyContent {\n readonly account: string;\n readonly htmlBody?: string;\n readonly templateSubject?: string;\n readonly templateFolder: string;\n readonly templateSection?: string;\n readonly templatePlaceholders?: Readonly<Record<string, string>>;\n readonly signatureName?: string;\n}\n\n/**\n * The content of an HTML document's `<body>`, or the input when it isn't a\n * whole document. Signature files and saved templates are both whole documents,\n * and neither may nest its `<html>`/`<body>` inside another email's.\n */\nfunction innerBodyHtml(html: string): string {\n const match = /<body[^>]*>([\\s\\S]*)<\\/body>/i.exec(html);\n return (match ? match[1] : html).trim();\n}\n\n/**\n * A saved template's HTML, found by subject.\n *\n * The read is filtered by subject in the platform script: unfiltered, EVERY\n * template's full body would cross the interpreter's stdout on every reply, and\n * a folder of Word-sized templates overruns the output limit on a call that\n * only ever needed one of them.\n */\nasync function resolveTemplateHtml(\n deps: ReplyBodyDeps,\n account: string,\n folder: string,\n subject: string,\n): Promise<string> {\n const result = await deps.readTemplateEmails({ account, folder, limit: 50, includeBody: true, subject });\n if (!result.folderFound) {\n const folders = result.availableFolders.join(', ') || '(none)';\n throw new NotFoundError('folder', `Template folder '${folder}' not found in ${account}. Top-level folders: ${folders}.`);\n }\n const wanted = subject.trim().toLowerCase();\n const match = result.templates.find(t => t.subject.trim().toLowerCase() === wanted);\n if (!match) {\n // The read above was filtered, so it can't name the alternatives. A\n // second read without bodies can, cheaply.\n const all = await deps.readTemplateEmails({ account, folder, limit: 200, includeBody: false });\n const names = all.templates.map(t => t.subject).filter(Boolean).join(', ') || '(none)';\n throw new NotFoundError('template', `Template '${subject}' not found in '${folder}'. Templates there: ${names}.`);\n }\n if (match.htmlBody.trim() === '') {\n throw new NotFoundError('template', `Template '${subject}' has an empty HTML body.`);\n }\n return match.htmlBody;\n}\n\n/** Where a template asks for the signature. */\nconst SIGNATURE_TOKEN = '{{SIGNATURE}}';\n\n/** A named signature's HTML, ready to insert into a body; NOT_FOUND naming the ones there are. */\nexport async function resolveSignatureHtml(\n deps: Pick<ReplyBodyDeps, 'readOutlookSignatureHtml' | 'listOutlookSignatures'>,\n name: string,\n): Promise<string> {\n const signatureHtml = await deps.readOutlookSignatureHtml(name);\n if (signatureHtml.trim() === '') {\n const available = (await deps.listOutlookSignatures()).join(', ') || '(none)';\n throw new NotFoundError('signature', `Outlook signature '${name}' not found. Signatures on this machine: ${available}.`);\n }\n return innerBodyHtml(signatureHtml);\n}\n\n/** Whether a body says where its signature goes. */\nfunction asksForSignature(html: string): boolean {\n return findTokens(html, [SIGNATURE_TOKEN]).length > 0;\n}\n\n/**\n * Sign a body: in its `{{SIGNATURE}}` placeholder when it has one, otherwise at\n * the end, where Outlook itself would put a signature. In a whole document the\n * end is just inside `</body>`, since anything after `</html>` is outside the\n * email.\n */\nexport function placeSignature(html: string, signature: string): string {\n if (asksForSignature(html)) return replaceToken(html, SIGNATURE_TOKEN, signature);\n const block = `<br>${signature}`;\n const close = html.toLowerCase().lastIndexOf('</body');\n return close === -1 ? html + block : html.slice(0, close) + block + html.slice(close);\n}\n\n/**\n * The HTML to insert above the quoted original: template resolved, section\n * kept, placeholders and signature filled, document wrapper removed.\n *\n * A body taken from a template is always put through composition, even with\n * nothing to fill, so a stray [[SECTION]] marker is caught here rather than\n * mailed out.\n */\nexport async function composeReplyHtml(content: ReplyContent, deps: ReplyBodyDeps): Promise<string> {\n let html = content.htmlBody;\n let fromTemplate = false;\n if ((!html || html.trim() === '') && content.templateSubject) {\n html = await resolveTemplateHtml(deps, content.account, content.templateFolder, content.templateSubject);\n fromTemplate = true;\n }\n if (!html || html.trim() === '') {\n throw new InvalidRequestError('A reply needs either htmlBody or templateSubject.');\n }\n\n // A signature with a placeholder to go in is filled with the others, so\n // one that sat in a dropped section goes with it. Without one it is added\n // below the new text once everything else is composed.\n let placeholders = content.templatePlaceholders;\n const signature = content.signatureName ? await resolveSignatureHtml(deps, content.signatureName) : '';\n const signatureInPlace = signature !== '' && asksForSignature(html);\n if (signatureInPlace) placeholders = { ...placeholders, SIGNATURE: signature };\n\n const hasPlaceholders = !!placeholders && Object.keys(placeholders).length > 0;\n if (fromTemplate || content.templateSection || hasPlaceholders) {\n html = composeTemplateBody(html, {\n section: content.templateSection,\n placeholders,\n label: content.templateSubject,\n });\n }\n const body = innerBodyHtml(html);\n return signature !== '' && !signatureInPlace ? placeSignature(body, signature) : body;\n}\n\n/**\n * Where the new text goes in an Outlook-built reply: straight after the opening\n * of `WordSection1`, the div holding the empty paragraph where a person's cursor\n * would be. A reply Outlook didn't build that way falls back to just inside\n * `<body>`. The insertion itself happens in each platform's own language, since\n * the reply HTML never leaves Outlook; this anchor is the part both must agree on.\n */\nexport const WORD_SECTION_ANCHOR = 'WordSection1>';\n"]}
@@ -0,0 +1,14 @@
1
+ /** How deep under the mailbox root a template folder is searched for. */
2
+ export declare const TEMPLATE_SEARCH_DEPTH = 3;
3
+ /** Cap on one template body; a Word-generated one is large, and a runaway one shouldn't sink the call. */
4
+ export declare const MAX_TEMPLATE_HTML = 100000;
5
+ /** Characters of plain text standing in for a body that wasn't asked for. */
6
+ export declare const TEMPLATE_PREVIEW_CHARS = 200;
7
+ /**
8
+ * An embedded (cid:) image tag, removed from a template body as it is read.
9
+ * Those images live as attachments on the TEMPLATE item, so its HTML reused
10
+ * elsewhere would show broken-image placeholders; template emails are text and
11
+ * markup only. Matched ignoring case on both platforms, since editors write
12
+ * both `<img src=` and `<IMG SRC=`.
13
+ */
14
+ export declare const EMBEDDED_IMAGE_SOURCE = "<img[^>]*src=\"cid:[^\"]*\"[^>]*>";
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ // How far both platforms go when reading a folder of template emails, and what
3
+ // they strip from a body, stated once so a template that reads one way on
4
+ // Windows can't read another on macOS.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EMBEDDED_IMAGE_SOURCE = exports.TEMPLATE_PREVIEW_CHARS = exports.MAX_TEMPLATE_HTML = exports.TEMPLATE_SEARCH_DEPTH = void 0;
7
+ /** How deep under the mailbox root a template folder is searched for. */
8
+ exports.TEMPLATE_SEARCH_DEPTH = 3;
9
+ /** Cap on one template body; a Word-generated one is large, and a runaway one shouldn't sink the call. */
10
+ exports.MAX_TEMPLATE_HTML = 100_000;
11
+ /** Characters of plain text standing in for a body that wasn't asked for. */
12
+ exports.TEMPLATE_PREVIEW_CHARS = 200;
13
+ /**
14
+ * An embedded (cid:) image tag, removed from a template body as it is read.
15
+ * Those images live as attachments on the TEMPLATE item, so its HTML reused
16
+ * elsewhere would show broken-image placeholders; template emails are text and
17
+ * markup only. Matched ignoring case on both platforms, since editors write
18
+ * both `<img src=` and `<IMG SRC=`.
19
+ */
20
+ exports.EMBEDDED_IMAGE_SOURCE = '<img[^>]*src="cid:[^"]*"[^>]*>';
21
+ //# sourceMappingURL=templateLimits.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templateLimits.js","sourceRoot":"","sources":["../../src/shared/templateLimits.ts"],"names":[],"mappings":";AAAA,+EAA+E;AAC/E,0EAA0E;AAC1E,uCAAuC;;;AAEvC,yEAAyE;AAC5D,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAEvC,0GAA0G;AAC7F,QAAA,iBAAiB,GAAG,OAAO,CAAC;AAEzC,6EAA6E;AAChE,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAE1C;;;;;;GAMG;AACU,QAAA,qBAAqB,GAAG,gCAAgC,CAAC","sourcesContent":["// How far both platforms go when reading a folder of template emails, and what\n// they strip from a body, stated once so a template that reads one way on\n// Windows can't read another on macOS.\n\n/** How deep under the mailbox root a template folder is searched for. */\nexport const TEMPLATE_SEARCH_DEPTH = 3;\n\n/** Cap on one template body; a Word-generated one is large, and a runaway one shouldn't sink the call. */\nexport const MAX_TEMPLATE_HTML = 100_000;\n\n/** Characters of plain text standing in for a body that wasn't asked for. */\nexport const TEMPLATE_PREVIEW_CHARS = 200;\n\n/**\n * An embedded (cid:) image tag, removed from a template body as it is read.\n * Those images live as attachments on the TEMPLATE item, so its HTML reused\n * elsewhere would show broken-image placeholders; template emails are text and\n * markup only. Matched ignoring case on both platforms, since editors write\n * both `<img src=` and `<IMG SRC=`.\n */\nexport const EMBEDDED_IMAGE_SOURCE = '<img[^>]*src=\"cid:[^\"]*\"[^>]*>';\n"]}