mdto-messages 0.3.0 → 0.4.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 CHANGED
@@ -15,6 +15,8 @@ npm install mdto-messages
15
15
  | Telegram Bot API | Text `Ship today` and a bold entity at offset 0, length 4 |
16
16
  | Plain text | `Ship today` |
17
17
 
18
+ Try the draft formatters for [WhatsApp](https://mdtochat.com/whatsapp) and [Google Chat](https://mdtochat.com/google-chat) in your browser.
19
+
18
20
  ## Choose an operation
19
21
 
20
22
  Use `convert(markdown, target)` for a **draft**. Targets are `plaintext`, `html`, `email`, `whatsapp`, `threema`, `signal`, `viber`, `google-chat`, `discord`, `telegram`, `teams` and `slack`. For email, use both the returned `text` and `html` to build a multipart message.
package/dist/api.d.ts CHANGED
@@ -15,9 +15,22 @@ export declare const Target: {
15
15
  };
16
16
  export type Target = (typeof Target)[keyof typeof Target];
17
17
  export type Policy = "readable" | "compact" | "strict";
18
+ export type TableMode = "auto" | "cards" | "code";
18
19
  export interface Options {
19
20
  policy?: Policy;
20
21
  maxInputLength?: number;
22
+ /**
23
+ * Opt-in readability pass for AI-generated drafts (math, citations, code
24
+ * fences, tracking parameters, quotes and lists). Supported by `convert`
25
+ * only; `toMessages` rejects `true` with INVALID_INPUT. Default `false`.
26
+ */
27
+ aiDraft?: boolean;
28
+ /**
29
+ * Table rendering: `auto` (native destination, default), `cards` (labeled
30
+ * fields) or `code` (pipe-separated columns in a code block). Supported by
31
+ * `convert` only; `toMessages` rejects values other than `auto`.
32
+ */
33
+ tableMode?: TableMode;
21
34
  }
22
35
  export type DiagnosticCode = keyof typeof diagnostics;
23
36
  export interface Diagnostic {
@@ -38,5 +51,9 @@ export interface Result {
38
51
  html?: string;
39
52
  format: "html" | "text" | "markers";
40
53
  diagnostics: Diagnostic[];
54
+ /** Present only when `aiDraft` or a non-`auto` `tableMode` was requested. */
55
+ hasTable?: boolean;
41
56
  }
42
57
  export declare function validate(markdown: string, options: Options): string;
58
+ /** Body APIs build platform payloads from the default rendering only. */
59
+ export declare function rejectDraftOptions(options: unknown): void;
package/dist/api.js CHANGED
@@ -13,6 +13,8 @@ export const Target = {
13
13
  Teams: "teams",
14
14
  Slack: "slack",
15
15
  };
16
+ const optionKeys = ["policy", "maxInputLength", "aiDraft", "tableMode"];
17
+ const tableModes = ["auto", "cards", "code"];
16
18
  export function describe(codes) {
17
19
  return Array.from(codes, (code) => ({ code, ...diagnostics[code] }));
18
20
  }
@@ -40,8 +42,13 @@ export function validate(markdown, options) {
40
42
  if (typeof markdown !== "string" || !options || typeof options !== "object")
41
43
  throw new ConversionError("INVALID_INPUT");
42
44
  if (Array.isArray(options) ||
43
- Object.keys(options).some((key) => key !== "policy" && key !== "maxInputLength"))
44
- throw new ConversionError("INVALID_INPUT", "Supported conversion options are policy and maxInputLength.");
45
+ Object.keys(options).some((key) => !optionKeys.includes(key)))
46
+ throw new ConversionError("INVALID_INPUT", "Supported conversion options are policy, maxInputLength, aiDraft and tableMode.");
47
+ if (options.aiDraft !== undefined && typeof options.aiDraft !== "boolean")
48
+ throw new ConversionError("INVALID_INPUT", "aiDraft must be a boolean.");
49
+ if (options.tableMode !== undefined &&
50
+ !tableModes.includes(options.tableMode))
51
+ throw new ConversionError("INVALID_INPUT", "tableMode must be auto, cards or code.");
45
52
  const limit = options.maxInputLength === undefined ? 32768 : options.maxInputLength;
46
53
  if (!Number.isInteger(limit) || limit < 1 || limit > 131072)
47
54
  throw new ConversionError("INVALID_INPUT", "maxInputLength must be an integer from 1 through 131072 UTF-16 units.");
@@ -54,3 +61,11 @@ export function validate(markdown, options) {
54
61
  throw new ConversionError("INVALID_INPUT", "policy must be readable, compact or strict.");
55
62
  return markdown.replace(/^\uFEFF/, "");
56
63
  }
64
+ /** Body APIs build platform payloads from the default rendering only. */
65
+ export function rejectDraftOptions(options) {
66
+ if (!options || typeof options !== "object")
67
+ return;
68
+ const { aiDraft, tableMode } = options;
69
+ if (aiDraft === true || (tableMode !== undefined && tableMode !== "auto"))
70
+ throw new ConversionError("INVALID_INPUT", "aiDraft and tableMode are supported by convert only, not by toMessages.");
71
+ }
@@ -0,0 +1,33 @@
1
+ import type { TokenizerExtension } from "marked";
2
+ /**
3
+ * Convert a simple math expression to Unicode text. Returns undefined for
4
+ * anything unknown or ambiguous so the caller can keep the source verbatim.
5
+ */
6
+ export declare function convertMath(body: string): string | undefined;
7
+ interface MathMatch {
8
+ raw: string;
9
+ body: string;
10
+ }
11
+ /** Match one paired math span at the start of `src`. */
12
+ export declare function matchMath(src: string): MathMatch | undefined;
13
+ /** Bare web URL at the start of `src`, without trailing sentence
14
+ * punctuation or an unmatched closing bracket. */
15
+ export declare function matchBareUrl(src: string): string | undefined;
16
+ /** Inline tokenizer extensions that only run when aiDraft is enabled. The URL
17
+ * rule is registered first so math delimiters inside a bare URL stay literal. */
18
+ export declare const draftExtensions: TokenizerExtension[];
19
+ /**
20
+ * Remove known utm_* parameters from an ordinary http(s) URL. The functional
21
+ * query keeps its original encoding and order, and the fragment is retained.
22
+ * Signed, authenticated or unrecognized queries are returned unchanged.
23
+ */
24
+ export declare function stripTracking(url: string): string;
25
+ /** Legacy assistant citations such as 【4†source】 become [4]. */
26
+ export declare function legacyCitations(text: string): string;
27
+ /** The readable label for a GitHub-style callout marker, if `raw` starts with one. */
28
+ export declare function calloutLabel(raw: string): string | undefined;
29
+ /** Count Markdown cells before a parser pads or drops mismatched cells. */
30
+ export declare function tableWidth(line: string): number;
31
+ /** Source number of an ordered list item, such as 10 in "10. text". */
32
+ export declare function listNumber(raw: string): number | undefined;
33
+ export {};
package/dist/draft.js ADDED
@@ -0,0 +1,296 @@
1
+ import { normalizeLink } from "./links.js";
2
+ /** Maximum UTF-8 bytes interpreted as math; longer pairs remain source text. */
3
+ const MATH_LIMIT = 1024;
4
+ const SUPERSCRIPT = {
5
+ "0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴",
6
+ "5": "⁵", "6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹",
7
+ "+": "⁺", "-": "⁻", "=": "⁼", "(": "⁽", ")": "⁾", n: "ⁿ", i: "ⁱ",
8
+ };
9
+ const SUBSCRIPT = {
10
+ "0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄",
11
+ "5": "₅", "6": "₆", "7": "₇", "8": "₈", "9": "₉",
12
+ "+": "₊", "-": "₋", "=": "₌", "(": "₍", ")": "₎",
13
+ a: "ₐ", e: "ₑ", h: "ₕ", i: "ᵢ", j: "ⱼ", k: "ₖ", l: "ₗ", m: "ₘ",
14
+ n: "ₙ", o: "ₒ", p: "ₚ", r: "ᵣ", s: "ₛ", t: "ₜ", u: "ᵤ", v: "ᵥ", x: "ₓ",
15
+ };
16
+ const COMMANDS = {
17
+ to: "→", rightarrow: "→", leftarrow: "←", Rightarrow: "⇒",
18
+ leftrightarrow: "↔", approx: "≈", times: "×", cdot: "·", pm: "±",
19
+ mp: "∓", le: "≤", leq: "≤", ge: "≥", geq: "≥", ne: "≠", neq: "≠",
20
+ infty: "∞", ldots: "…", cdots: "⋯", sum: "∑", partial: "∂", in: "∈",
21
+ alpha: "α", beta: "β", gamma: "γ", delta: "δ", epsilon: "ε",
22
+ theta: "θ", lambda: "λ", mu: "μ", pi: "π", sigma: "σ", tau: "τ",
23
+ phi: "φ", omega: "ω", Delta: "Δ", Sigma: "Σ", Omega: "Ω",
24
+ };
25
+ const mathWords = new Set(["sin", "cos", "tan", "log", "ln", "exp", "lim", "max", "min", "mod"]);
26
+ const utf8 = new TextEncoder();
27
+ const plainMath = /^[\p{L}\p{N}\s*+\-=<>()[\],.;:/|!'?]$/u;
28
+ /**
29
+ * Convert a simple math expression to Unicode text. Returns undefined for
30
+ * anything unknown or ambiguous so the caller can keep the source verbatim.
31
+ */
32
+ export function convertMath(body) {
33
+ if (body.length > MATH_LIMIT || utf8.encode(body).length > MATH_LIMIT)
34
+ return undefined;
35
+ const word = /\p{L}+/uy;
36
+ let out = "";
37
+ for (let i = 0; i < body.length;) {
38
+ const c = String.fromCodePoint(body.codePointAt(i));
39
+ if (c === "\\") {
40
+ const escaped = body[i + 1];
41
+ if (escaped === "%" || (escaped !== undefined && ",;: ".includes(escaped))) {
42
+ out += escaped === "%" ? "%" : " ";
43
+ i += 2;
44
+ continue;
45
+ }
46
+ const command = /^\\([A-Za-z]{1,24})(?![A-Za-z])/.exec(body.slice(i, i + 26));
47
+ if (!command || !Object.hasOwn(COMMANDS, command[1]))
48
+ return undefined;
49
+ out += COMMANDS[command[1]];
50
+ i += command[0].length;
51
+ continue;
52
+ }
53
+ if (c === "^" || c === "_") {
54
+ if (!out.trim())
55
+ return undefined;
56
+ const map = c === "^" ? SUPERSCRIPT : SUBSCRIPT;
57
+ let group;
58
+ if (body[i + 1] === "{") {
59
+ const close = body.indexOf("}", i + 2);
60
+ if (close < 0)
61
+ return undefined;
62
+ group = body.slice(i + 2, close);
63
+ i = close + 1;
64
+ }
65
+ else {
66
+ group = body[i + 1] ?? "";
67
+ i += 2;
68
+ }
69
+ if (!group)
70
+ return undefined;
71
+ for (const g of group) {
72
+ if (!Object.hasOwn(map, g))
73
+ return undefined;
74
+ out += map[g];
75
+ }
76
+ continue;
77
+ }
78
+ if (/\p{L}/u.test(c)) {
79
+ word.lastIndex = i;
80
+ const name = word.exec(body)[0];
81
+ if (Array.from(name).length > 2 && !mathWords.has(name))
82
+ return undefined;
83
+ out += name;
84
+ i += name.length;
85
+ continue;
86
+ }
87
+ if (!plainMath.test(c))
88
+ return undefined;
89
+ out += c;
90
+ i += c.length;
91
+ }
92
+ out = out.trim().replace(/\s+/gu, " ");
93
+ return out || undefined;
94
+ }
95
+ /** Match one paired math span at the start of `src`. */
96
+ export function matchMath(src) {
97
+ let open, close;
98
+ if (src.startsWith("$$"))
99
+ open = close = "$$";
100
+ else if (src[0] === "$")
101
+ open = close = "$";
102
+ else if (src.startsWith("\\("))
103
+ [open, close] = ["\\(", "\\)"];
104
+ else if (src.startsWith("\\["))
105
+ [open, close] = ["\\[", "\\]"];
106
+ else
107
+ return undefined;
108
+ // Stop at the next delimiter, nested bracket opener or code boundary.
109
+ // Long paired expressions can then be emitted verbatim without a second parse.
110
+ const markers = open === "$" || open === "$$"
111
+ ? (open === "$" ? /[$`\n]/g : /\$\$|`|\n\s*\n/g)
112
+ : (open === "\\(" ? /\\[()]|`|\n/g : /\\[\[\]]|`|\n\s*\n/g);
113
+ markers.lastIndex = open.length;
114
+ let marker = markers.exec(src);
115
+ while (marker?.[0] === close && open.startsWith("$") && src[marker.index - 1] === "\\")
116
+ marker = markers.exec(src);
117
+ const end = marker?.[0] === close ? marker.index : -1;
118
+ if (end < 0)
119
+ return undefined;
120
+ const body = src.slice(open.length, end);
121
+ if (!body.trim() || body.includes("\n\n"))
122
+ return undefined;
123
+ if (open === "$") {
124
+ // Pandoc's rule keeps ordinary currency such as "$5 and $10" literal.
125
+ if (/^[0-9.,]+$/.test(body))
126
+ return { raw: src.slice(0, end + 1), body: "" };
127
+ if (/\s/u.test(body[0]) || /\s/u.test(body[body.length - 1]))
128
+ return;
129
+ if (/[0-9$]/.test(src[end + 1] ?? ""))
130
+ return;
131
+ }
132
+ else if (open.startsWith("\\") && /^[A-Za-z]{2,}$/.test(body)) {
133
+ // An escaped bracket pair such as \[note\] is not mathematics.
134
+ return undefined;
135
+ }
136
+ return { raw: src.slice(0, end + close.length), body };
137
+ }
138
+ function mathOpener(src, i) {
139
+ if (src[i] === "\\")
140
+ return src[i + 1] === "(" || src[i + 1] === "[";
141
+ if (i > 0 && /[\p{L}\p{N}\\$]/u.test(src[i - 1]))
142
+ return false;
143
+ const next = src[i + 1];
144
+ return next !== undefined && !/\s/u.test(next);
145
+ }
146
+ /** Bare web URL at the start of `src`, without trailing sentence
147
+ * punctuation or an unmatched closing bracket. */
148
+ export function matchBareUrl(src) {
149
+ const match = /^(?:https?:\/\/|www\.)[^\s\u0085<>"`]+/i.exec(src);
150
+ if (!match)
151
+ return undefined;
152
+ const source = match[0];
153
+ const pairs = { ")": "(", "]": "[", "}": "{" };
154
+ const excess = new Map();
155
+ for (const [close, open] of Object.entries(pairs)) {
156
+ excess.set(close, source.split(close).length - source.split(open).length);
157
+ }
158
+ let end = source.length;
159
+ while (end) {
160
+ const last = source[end - 1];
161
+ if ((excess.get(last) ?? 0) > 0) {
162
+ excess.set(last, excess.get(last) - 1);
163
+ }
164
+ else if (!".,:;!?'".includes(last)) {
165
+ break;
166
+ }
167
+ end--;
168
+ }
169
+ const url = source.slice(0, end);
170
+ // A scheme-less web address stays literal, just as it did before this pass.
171
+ const destination = /^www\./i.test(url) ? "https://" + url : url;
172
+ return normalizeLink(destination) ? url : undefined;
173
+ }
174
+ /** Inline tokenizer extensions that only run when aiDraft is enabled. The URL
175
+ * rule is registered first so math delimiters inside a bare URL stay literal. */
176
+ export const draftExtensions = [
177
+ {
178
+ name: "draftUrl",
179
+ level: "inline",
180
+ start(src) {
181
+ const index = src.search(/https?:\/\/|\bwww\./i);
182
+ return index < 0 ? undefined : index;
183
+ },
184
+ tokenizer(src) {
185
+ const url = matchBareUrl(src);
186
+ return url ? { type: "draftUrl", raw: url, text: url } : undefined;
187
+ },
188
+ },
189
+ {
190
+ name: "draftMath",
191
+ level: "inline",
192
+ start(src) {
193
+ const candidate = /\$|\\[([]/g;
194
+ for (let m; (m = candidate.exec(src));)
195
+ if (mathOpener(src, m.index))
196
+ return m.index;
197
+ return undefined;
198
+ },
199
+ tokenizer(src, tokens) {
200
+ // Marked passes the unconsumed suffix here. Its start hint alone has
201
+ // no access to the character preceding a dollar at suffix index zero.
202
+ const previous = tokens.at(-1)?.raw;
203
+ if (src[0] === "$" && src[1] !== "$" && previous && /[\p{L}\p{N}$]$/u.test(previous))
204
+ return undefined;
205
+ const match = matchMath(src);
206
+ return match
207
+ ? { type: "draftMath", raw: match.raw, text: match.body }
208
+ : undefined;
209
+ },
210
+ },
211
+ ];
212
+ const trackingKeys = new Set([
213
+ "utm_source",
214
+ "utm_medium",
215
+ "utm_campaign",
216
+ "utm_term",
217
+ "utm_content",
218
+ "utm_id",
219
+ "utm_name",
220
+ "utm_source_platform",
221
+ "utm_creative_format",
222
+ "utm_marketing_tactic",
223
+ ]);
224
+ // Any key that may carry a signature or credential keeps the URL untouched.
225
+ const sensitiveKey = /^(?:x-amz-|x-goog-|x-ms-|x-cos-|x-oss-)|sig|token|auth|key|secret|credential|hmac|policy|expires|password|session|nonce|hash|^(?:code|state|jwt|sid|se|sp|sv|sr|st|skoid|ske)$/i;
226
+ /**
227
+ * Remove known utm_* parameters from an ordinary http(s) URL. The functional
228
+ * query keeps its original encoding and order, and the fragment is retained.
229
+ * Signed, authenticated or unrecognized queries are returned unchanged.
230
+ */
231
+ export function stripTracking(url) {
232
+ if (!/^https?:\/\//i.test(url) || url.length > 4096)
233
+ return url;
234
+ const hash = url.indexOf("#");
235
+ const beforeHash = hash < 0 ? url : url.slice(0, hash);
236
+ const fragment = hash < 0 ? "" : url.slice(hash);
237
+ const mark = beforeHash.indexOf("?");
238
+ if (mark < 0)
239
+ return url;
240
+ const query = beforeHash.slice(mark + 1);
241
+ if (!query || query.includes(";") || /%(?![0-9a-f]{2})/i.test(url))
242
+ return url;
243
+ const pairs = query.split("&");
244
+ if (pairs.length > 256)
245
+ return url;
246
+ const kept = [];
247
+ for (const pair of pairs) {
248
+ const match = /^([A-Za-z0-9_.\-[\]]+)(?:=[^=]*)?$/.exec(pair);
249
+ if (!match || sensitiveKey.test(match[1]))
250
+ return url;
251
+ const key = match[1];
252
+ if (!trackingKeys.has(key.toLowerCase()))
253
+ kept.push(pair);
254
+ }
255
+ if (kept.length === pairs.length)
256
+ return url;
257
+ return (beforeHash.slice(0, mark) +
258
+ (kept.length ? "?" + kept.join("&") : "") +
259
+ fragment);
260
+ }
261
+ /** Legacy assistant citations such as 【4†source】 become [4]. */
262
+ export function legacyCitations(text) {
263
+ return text.replace(/【(\d{1,4})(?:[†‡:][^【】\n]{0,200})?】/g, "[$1]");
264
+ }
265
+ const calloutLabels = {
266
+ NOTE: "Note",
267
+ TIP: "Tip",
268
+ IMPORTANT: "Important",
269
+ WARNING: "Warning",
270
+ CAUTION: "Caution",
271
+ };
272
+ const calloutMarker = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*(?=\s|$)/i;
273
+ /** The readable label for a GitHub-style callout marker, if `raw` starts with one. */
274
+ export function calloutLabel(raw) {
275
+ const match = calloutMarker.exec(raw);
276
+ return match ? calloutLabels[match[1].toUpperCase()] : undefined;
277
+ }
278
+ /** Count Markdown cells before a parser pads or drops mismatched cells. */
279
+ export function tableWidth(line) {
280
+ const row = line.trim();
281
+ let separators = 0;
282
+ let escaped = false;
283
+ let endsWithSeparator = false;
284
+ for (const char of row) {
285
+ endsWithSeparator = char === "|" && !escaped;
286
+ if (endsWithSeparator)
287
+ separators++;
288
+ escaped = char === "\\" && !escaped;
289
+ }
290
+ return separators + 1 - Number(row.startsWith("|")) - Number(endsWithSeparator);
291
+ }
292
+ /** Source number of an ordered list item, such as 10 in "10. text". */
293
+ export function listNumber(raw) {
294
+ const match = /^[ \t]{0,3}(\d{1,9})[.)]/.exec(raw);
295
+ return match ? Number(match[1]) : undefined;
296
+ }
@@ -3,17 +3,28 @@ export interface DocumentNode {
3
3
  text?: string;
4
4
  url?: string;
5
5
  start?: number;
6
+ /** A key into the fixed style table; never author-supplied CSS. */
7
+ style?: StyleName;
6
8
  children: DocumentNode[];
7
9
  }
10
+ declare const styles: {
11
+ readonly table: "border-collapse:collapse";
12
+ readonly cellLeft: "border:1px solid #d0d7de;padding:6px 10px;text-align:left";
13
+ readonly cellCenter: "border:1px solid #d0d7de;padding:6px 10px;text-align:center";
14
+ readonly cellRight: "border:1px solid #d0d7de;padding:6px 10px;text-align:right";
15
+ };
16
+ export type StyleName = keyof typeof styles;
8
17
  export interface Fragment {
9
18
  text: string;
10
19
  nodes: DocumentNode[];
11
20
  htmlSize: number;
12
- endsInWebLink?: boolean;
21
+ startsWithWebURL?: boolean;
22
+ webTailLength?: number;
13
23
  }
14
24
  export declare function html(nodes: DocumentNode[]): string;
15
25
  export declare function literal(text: string): Fragment;
16
- export declare function wrap(kind: string, part: Fragment, attributes?: Pick<DocumentNode, "url" | "start">): Fragment;
17
- export declare function linkBoundary(endsInWebLink: boolean | undefined, next: string): string;
26
+ export declare function wrap(kind: string, part: Fragment, attributes?: Pick<DocumentNode, "url" | "start" | "style">): Fragment;
27
+ export declare function markText(part: Fragment, delimiter: string): void;
18
28
  export declare function join(parts: Fragment[], sep?: string): Fragment;
19
29
  export declare function contains(nodes: DocumentNode[], kind: string): boolean;
30
+ export {};
package/dist/fragment.js CHANGED
@@ -1,3 +1,10 @@
1
+ // Inline styles for email tables. Only these constants can reach the output.
2
+ const styles = {
3
+ table: "border-collapse:collapse",
4
+ cellLeft: "border:1px solid #d0d7de;padding:6px 10px;text-align:left",
5
+ cellCenter: "border:1px solid #d0d7de;padding:6px 10px;text-align:center",
6
+ cellRight: "border:1px solid #d0d7de;padding:6px 10px;text-align:right",
7
+ };
1
8
  const escape = (s) => s
2
9
  .replace(/&/g, "&amp;")
3
10
  .replace(/</g, "&lt;")
@@ -9,7 +16,10 @@ function opening(n) {
9
16
  : n.kind === "ol" && n.start !== 1
10
17
  ? ' start="' + n.start + '"'
11
18
  : "";
12
- return "<" + n.kind + attr + ">";
19
+ const style = n.style && Object.hasOwn(styles, n.style)
20
+ ? ' style="' + escape(styles[n.style]) + '"'
21
+ : "";
22
+ return "<" + n.kind + attr + style + ">";
13
23
  }
14
24
  const voidElement = (kind) => kind === "br" || kind === "hr";
15
25
  export function html(nodes) {
@@ -31,29 +41,73 @@ export function wrap(kind, part, attributes = {}) {
31
41
  const node = { kind, ...attributes, children: part.nodes };
32
42
  return {
33
43
  text: part.text,
34
- endsInWebLink: part.endsInWebLink,
44
+ startsWithWebURL: part.startsWithWebURL,
45
+ webTailLength: part.webTailLength,
35
46
  nodes: [node],
36
47
  htmlSize: part.htmlSize +
37
48
  opening(node).length +
38
49
  (voidElement(kind) ? 0 : kind.length + 3),
39
50
  };
40
51
  }
41
- export function linkBoundary(endsInWebLink, next) {
42
- return endsInWebLink && /^[^\p{White_Space}\uFEFF]/u.test(next) ? " " : "";
52
+ const leadingPunctuation = /^[.,!?:;)\]}]*/;
53
+ const whitespace = /[\p{White_Space}\uFEFF]/u;
54
+ const leftDelimiter = /[\p{White_Space}\uFEFF(\[{]$/u;
55
+ export function markText(part, delimiter) {
56
+ if (!part.webTailLength) {
57
+ part.text = delimiter + part.text + delimiter;
58
+ part.startsWithWebURL = false;
59
+ return;
60
+ }
61
+ const prefix = part.text.slice(0, -part.webTailLength);
62
+ const content = prefix.replace(/[\p{White_Space}\uFEFF]+$/u, "");
63
+ if (content) {
64
+ const gap = prefix.slice(content.length) || " ";
65
+ part.text = delimiter + content + delimiter + gap + part.text.slice(prefix.length);
66
+ part.startsWithWebURL = false;
67
+ }
43
68
  }
44
69
  export function join(parts, sep = "") {
45
70
  const nodes = [];
46
71
  let htmlSize = 0;
47
72
  const text = [];
48
- let endsInWebLink = false;
73
+ let startsWithWebURL = false;
74
+ let webTailLength = 0;
75
+ // A punctuation-only sibling is terminal only if the following text permits it.
76
+ const punctuationLengths = [];
77
+ const canFollowURL = [];
78
+ if (parts.some(part => part.webTailLength)) {
79
+ let terminal = true;
80
+ for (let i = parts.length - 1; i >= 0; i--) {
81
+ const value = parts[i].text;
82
+ const count = leadingPunctuation.exec(value)[0].length;
83
+ if (count < value.length)
84
+ terminal = whitespace.test(value[count]);
85
+ else if (sep)
86
+ terminal = true;
87
+ punctuationLengths[i] = count;
88
+ canFollowURL[i] = terminal;
89
+ }
90
+ }
49
91
  for (const [i, part] of parts.entries()) {
50
92
  if (i && sep) {
51
- text.push(linkBoundary(endsInWebLink, sep), sep);
52
- endsInWebLink = false;
93
+ text.push(sep);
94
+ webTailLength = 0;
53
95
  }
54
96
  if (part.text) {
55
- text.push(linkBoundary(endsInWebLink, part.text), part.text);
56
- endsInWebLink = !!part.endsInWebLink;
97
+ const before = text[text.length - 1];
98
+ if (!before)
99
+ startsWithWebURL = !!part.startsWithWebURL;
100
+ const gap = (webTailLength && !canFollowURL[i]) ||
101
+ (before && part.startsWithWebURL && !leftDelimiter.test(before));
102
+ if (gap)
103
+ text.push(" ");
104
+ text.push(part.text);
105
+ if (webTailLength && !gap && punctuationLengths[i] === part.text.length) {
106
+ webTailLength += part.text.length;
107
+ }
108
+ else {
109
+ webTailLength = part.webTailLength ?? 0;
110
+ }
57
111
  }
58
112
  htmlSize += part.htmlSize;
59
113
  for (const node of part.nodes) {
@@ -64,7 +118,7 @@ export function join(parts, sep = "") {
64
118
  nodes.push(node);
65
119
  }
66
120
  }
67
- return { text: text.join(""), endsInWebLink, nodes, htmlSize };
121
+ return { text: text.join(""), startsWithWebURL, webTailLength, nodes, htmlSize };
68
122
  }
69
123
  export function contains(nodes, kind) {
70
124
  return nodes.some((n) => n.kind === kind || contains(n.children, kind));
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Target, ConversionError, type Diagnostic, type DiagnosticCode, type Options, type Policy, type Result, type ErrorCode, } from "./api.js";
1
+ export { Target, ConversionError, type Diagnostic, type DiagnosticCode, type Options, type Policy, type TableMode, type Result, type ErrorCode, } from "./api.js";
2
2
  export { convert } from "./render.js";
3
3
  export { toMessages, type ApiTarget, type MessageBodies, type MessageBatch, type TelegramBody, type DiscordBody, type SlackBody, type Entity, } from "./messages.js";
4
4
  export { diagnostics } from "./diagnostics.js";
package/dist/messages.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { chunks, flatten } from "./flatten.js";
2
2
  import { renderSlack } from "./slack.js";
3
3
  import { normalizeLink } from "./links.js";
4
- import { ConversionError, unknownTarget, describe, } from "./api.js";
4
+ import { ConversionError, unknownTarget, rejectDraftOptions, describe, } from "./api.js";
5
5
  import { convert, parseDocument } from "./render.js";
6
6
  const blankMessage = /^[\s\u0085]*$/u;
7
7
  const discordUrlPattern = /(https?:\/\/[^\s\u0085<>]+)/gi;
@@ -93,6 +93,7 @@ function singleMessage(input, target, options) {
93
93
  return { messages: [body], diagnostics: describe(warnings) };
94
94
  }
95
95
  export function toMessages(markdown, target, options = {}) {
96
+ rejectDraftOptions(options);
96
97
  if (target === "whatsapp" ||
97
98
  target === "viber" ||
98
99
  target === "threema" ||
package/dist/render.js CHANGED
@@ -1,12 +1,15 @@
1
1
  import { displayLink, normalizeLink } from "./links.js";
2
2
  import { Target, ConversionError, unknownTarget, describe, validate, } from "./api.js";
3
- import { contains, linkBoundary, html, join, literal, wrap, } from "./fragment.js";
3
+ import { contains, markText, html, join, literal, wrap, } from "./fragment.js";
4
+ import { calloutLabel, convertMath, draftExtensions, legacyCitations, listNumber, stripTracking, tableWidth, } from "./draft.js";
4
5
  import { MarkdownTokenizer, decodeReferences } from "./tokenizer.js";
5
6
  import markedFootnote from "marked-footnote";
6
7
  import { Marked } from "marked";
7
8
  class Renderer {
8
9
  target;
9
10
  policy;
11
+ draft;
12
+ tableMode;
10
13
  warnings = new Set();
11
14
  rich;
12
15
  mobileChat;
@@ -16,9 +19,13 @@ class Renderer {
16
19
  compact;
17
20
  nodes = 0;
18
21
  workUnits = 0;
19
- constructor(target, policy) {
22
+ /** Set when the parsed document contains a real Markdown table. */
23
+ sawTable = false;
24
+ constructor(target, policy, draft = false, tableMode = "auto") {
20
25
  this.target = target;
21
26
  this.policy = policy;
27
+ this.draft = draft;
28
+ this.tableMode = tableMode;
22
29
  this.rich = ["html", "email", "teams", "slack"].includes(target);
23
30
  this.mobileChat = target === "whatsapp" || target === "google-chat";
24
31
  this.doubled = target === "discord" || target === "telegram";
@@ -36,13 +43,19 @@ class Renderer {
36
43
  renderSiblings(tokens, depth) {
37
44
  const visible = tokens.filter((t) => t.type !== "space" && t.type !== "def");
38
45
  const isRawBlock = (t) => t?.type === "html" && t.block;
39
- return visible.map((token, i) => {
46
+ const numericInfix = (token, i) => token.type === "em" &&
47
+ /^\*[0-9]+\*$/.test(token.raw) &&
48
+ /[0-9]$/.test(visible[i - 1]?.raw ?? "") &&
49
+ /^[0-9]/.test(visible[i + 1]?.raw ?? "");
50
+ const parts = visible.map((token, i) => {
51
+ // A product such as 2*3*4 is arithmetic, not emphasis.
52
+ if (this.draft && numericInfix(token, i)) {
53
+ if (this.markers && this.target !== "whatsapp")
54
+ this.warn("AMBIGUOUS_MARKER");
55
+ return literal(token.raw);
56
+ }
40
57
  const part = this.visit(token, depth);
41
- if (this.target === "whatsapp" &&
42
- token.type === "em" &&
43
- /^\*[0-9]+\*$/.test(token.raw) &&
44
- /[0-9]$/.test(visible[i - 1]?.raw ?? "") &&
45
- /^[0-9]/.test(visible[i + 1]?.raw ?? "")) {
58
+ if (this.target === "whatsapp" && numericInfix(token, i)) {
46
59
  part.text = token.raw;
47
60
  }
48
61
  if (isRawBlock(token) &&
@@ -50,6 +63,48 @@ class Renderer {
50
63
  return wrap("p", part);
51
64
  return part;
52
65
  });
66
+ if (this.draft && !this.rich && !this.mobileChat)
67
+ this.flattenLinkParentheses(visible, parts);
68
+ return parts;
69
+ }
70
+ /** "([label](url))" reads as "label (url)" in plain text. Parentheses that
71
+ * also enclose other words are real grouping and remain. */
72
+ flattenLinkParentheses(tokens, parts) {
73
+ for (let i = 1; i + 1 < tokens.length; i++) {
74
+ if (tokens[i].type !== "link")
75
+ continue;
76
+ if (tokens[i - 1].type !== "text" || tokens[i + 1].type !== "text")
77
+ continue;
78
+ const before = parts[i - 1].text;
79
+ const after = parts[i + 1].text;
80
+ if (!/(?:^|\s)\($/u.test(before) || !after.startsWith(")"))
81
+ continue;
82
+ if (!/ \([^\s()]+\)$/.test(parts[i].text))
83
+ continue;
84
+ parts[i - 1] = { ...parts[i - 1], text: before.slice(0, -1) };
85
+ parts[i + 1] = { ...parts[i + 1], text: after.slice(1) };
86
+ }
87
+ }
88
+ /** Native chat code for a draft. A source that contains a triple fence
89
+ * cannot be fenced safely, so it stays literal (indented for blocks). */
90
+ draftCode(block, text) {
91
+ if (!text.includes("```")) {
92
+ if (block)
93
+ return "```\n" + text + "\n```";
94
+ if (!text.includes("`")) {
95
+ const fence = this.target === "viber" ? "```" : "`";
96
+ return fence + text + fence;
97
+ }
98
+ if (!text.startsWith("`") && !text.endsWith("`"))
99
+ return "```" + text + "```";
100
+ }
101
+ this.warn("FORMAT_AS_TEXT");
102
+ return block
103
+ ? text
104
+ .split("\n")
105
+ .map((line) => " " + line)
106
+ .join("\n")
107
+ : text;
53
108
  }
54
109
  render(tokens, depth, block = false) {
55
110
  return join(this.renderSiblings(tokens, depth), block ? (this.compact ? "\n" : "\n\n") : "");
@@ -65,6 +120,15 @@ class Renderer {
65
120
  if (++this.nodes > 8192 || depth > 48)
66
121
  throw new ConversionError("LIMIT");
67
122
  const children = (tokens, block = false) => this.render(tokens, depth + 1, block);
123
+ const custom = t;
124
+ if (custom.type === "draftMath") {
125
+ const text = convertMath(custom.text) ?? custom.raw;
126
+ if (this.markers && /[*_~`]/.test(text))
127
+ this.warn("AMBIGUOUS_MARKER");
128
+ return literal(text);
129
+ }
130
+ if (custom.type === "draftUrl")
131
+ return this.bareUrl(custom.raw);
68
132
  switch (t.type) {
69
133
  case "footnoteRef":
70
134
  return literal("[" + t.id + "]");
@@ -72,7 +136,9 @@ class Renderer {
72
136
  case "escape": {
73
137
  if (t.type === "text" && t.tokens)
74
138
  return children(t.tokens);
75
- const text = t.type === "escape" ? t.text : decodeReferences(t.text);
139
+ let text = t.type === "escape" ? t.text : decodeReferences(t.text);
140
+ if (this.draft && t.type === "text")
141
+ text = legacyCitations(text);
76
142
  if (this.markers && /[*_~`]/.test(text))
77
143
  this.warn("AMBIGUOUS_MARKER");
78
144
  return literal(text);
@@ -91,7 +157,10 @@ class Renderer {
91
157
  const value = wrap("code", literal(t.text));
92
158
  const part = t.type === "code" ? wrap("pre", value) : value;
93
159
  if (!this.rich) {
94
- if (this.markers &&
160
+ if (this.draft && this.markers && this.target !== "threema") {
161
+ part.text = this.draftCode(t.type === "code", t.text);
162
+ }
163
+ else if (this.markers &&
95
164
  this.target !== "threema" &&
96
165
  !t.text.includes("`")) {
97
166
  const fence = t.type === "code" || this.target === "viber" ? "```" : "`";
@@ -114,8 +183,7 @@ class Renderer {
114
183
  del: this.doubled ? "~~" : "~",
115
184
  strong: this.bold,
116
185
  }[t.type];
117
- value.text = delimiter + value.text + linkBoundary(value.endsInWebLink, delimiter) + delimiter;
118
- value.endsInWebLink = false;
186
+ markText(value, delimiter);
119
187
  }
120
188
  return value;
121
189
  }
@@ -124,23 +192,33 @@ class Renderer {
124
192
  this.warn("FORMAT_AS_TEXT");
125
193
  const value = wrap("h" + t.depth, children(t.tokens));
126
194
  if (this.markers &&
127
- !(t.tokens.length === 1 && t.tokens[0].type === "strong")) {
128
- value.text = this.bold + value.text + linkBoundary(value.endsInWebLink, this.bold) + this.bold;
129
- value.endsInWebLink = false;
195
+ !(t.tokens.length === 1 && t.tokens[0].type === "strong") &&
196
+ // Nested bold markers would cancel out in chat composers.
197
+ !(this.draft && contains(value.nodes, "strong"))) {
198
+ markText(value, this.bold);
130
199
  }
131
200
  return value;
132
201
  }
133
202
  case "paragraph":
134
203
  return wrap("p", children(t.tokens));
135
204
  case "blockquote": {
136
- const value = wrap("blockquote", children(t.tokens, true));
205
+ let value = wrap("blockquote", children(t.tokens, true));
206
+ if (this.draft)
207
+ value = this.callout(value, t.tokens);
137
208
  if (!this.rich) {
138
- if (["whatsapp", "google-chat", "discord", "telegram"].includes(this.target))
209
+ const quotes = [
210
+ "whatsapp",
211
+ "google-chat",
212
+ "discord",
213
+ "telegram",
214
+ ].includes(this.target);
215
+ // Drafts keep each nesting level visible as a "> " prefix.
216
+ if (quotes || this.draft)
139
217
  value.text = value.text
140
218
  .split("\n")
141
219
  .map((line) => "> " + line)
142
220
  .join("\n");
143
- else
221
+ if (!quotes)
144
222
  this.warn("FORMAT_AS_TEXT");
145
223
  }
146
224
  return value;
@@ -149,10 +227,16 @@ class Renderer {
149
227
  case "link": {
150
228
  const angleLink = t.type === "link" && t.autolink;
151
229
  let label = angleLink ? literal(t.text) : children(t.tokens);
152
- const authored = angleLink ? t.href : decodeReferences(t.href);
230
+ const original = angleLink ? t.href : decodeReferences(t.href);
231
+ const authored = this.draft && t.type === "link" ? stripTracking(original) : original;
153
232
  const href = normalizeLink(authored);
154
- if (contains(label.nodes, "a"))
155
- label = { ...literal(label.text), endsInWebLink: label.endsInWebLink };
233
+ if (contains(label.nodes, "a")) {
234
+ label = {
235
+ ...literal(label.text),
236
+ startsWithWebURL: label.startsWithWebURL,
237
+ webTailLength: label.webTailLength,
238
+ };
239
+ }
156
240
  if (t.type === "image")
157
241
  this.warn("IMAGE_AS_LINK");
158
242
  if (!href) {
@@ -160,22 +244,41 @@ class Renderer {
160
244
  return label;
161
245
  }
162
246
  const display = displayLink(authored, href);
163
- if (!label.text || label.text === authored)
247
+ if (!label.text || label.text === authored || label.text === original)
164
248
  label = literal(display);
165
249
  const result = wrap("a", label, { url: href });
166
- if (label.text !== display) {
167
- result.text = this.mobileChat && /^https?:/i.test(href)
168
- ? label.text + linkBoundary(label.endsInWebLink, ":") + ": " + display
169
- : label.text + " (" + display + ")";
250
+ const web = this.mobileChat && /^https?:/i.test(href);
251
+ if (web) {
252
+ const host = /^https?:\/\/([^/:?#]+)/i.exec(display)[1];
253
+ const asciiFold = (s) => s.replace(/[A-Z]/g, c => c.toLowerCase());
254
+ const hostLabel = label.nodes.length === 1 &&
255
+ label.nodes[0].kind === "text" &&
256
+ asciiFold(label.text) === asciiFold(host);
257
+ if (hostLabel || label.text === display) {
258
+ result.text = display;
259
+ result.startsWithWebURL = true;
260
+ }
261
+ else {
262
+ result.text = label.text + (label.webTailLength ? " : " : ": ") + display;
263
+ }
264
+ result.webTailLength = display.length;
265
+ }
266
+ else {
267
+ result.webTailLength = 0;
268
+ if (label.text !== display)
269
+ result.text = label.text + " (" + display + ")";
170
270
  }
171
- result.endsInWebLink = this.mobileChat && /^https?:/i.test(href);
172
271
  return result;
173
272
  }
174
273
  case "list": {
175
274
  const start = Number(t.start === "" ? 1 : t.start);
176
275
  const items = t.items.map((item, i) => {
177
276
  const value = this.visit(item, depth + 1);
178
- const prefix = t.ordered ? start + i + ". " : "- ";
277
+ // Drafts keep authored numbers, such as 1. followed by 10.
278
+ const number = this.draft
279
+ ? (listNumber(item.raw) ?? start + i)
280
+ : start + i;
281
+ const prefix = t.ordered ? number + ". " : "- ";
179
282
  return { ...value, text: prefix + value.text.replace(/\n/g, "\n ") };
180
283
  });
181
284
  const list = join(items, "\n");
@@ -215,42 +318,136 @@ class Renderer {
215
318
  });
216
319
  return wrap("li", join(parts));
217
320
  }
321
+ callout(value, tokens) {
322
+ const first = tokens.find((token) => token.type !== "space");
323
+ if (first?.type !== "paragraph")
324
+ return value;
325
+ const label = calloutLabel(first.raw);
326
+ if (!label)
327
+ return value;
328
+ const marker = /^\[![A-Za-z]+\][ \t]*(?:\r?\n)*/;
329
+ const replace = (text) => text.replace(marker, (found) => found.length === text.length ? label + ":" : label + ": ");
330
+ const quote = value.nodes[0];
331
+ const paragraph = quote?.children[0];
332
+ const node = paragraph?.kind === "p" ? paragraph.children[0] : undefined;
333
+ if (node?.kind === "text" && marker.test(node.text)) {
334
+ const children = [{ ...node, text: replace(node.text) }];
335
+ quote.children = [
336
+ { ...paragraph, children: [...children, ...paragraph.children.slice(1)] },
337
+ ...quote.children.slice(1),
338
+ ];
339
+ }
340
+ return { ...value, text: replace(value.text) };
341
+ }
342
+ bareUrl(raw) {
343
+ const cleaned = this.draft ? stripTracking(raw) : raw;
344
+ const href = normalizeLink(cleaned);
345
+ if (href && this.target === "email") {
346
+ const display = displayLink(cleaned, href);
347
+ return { ...wrap("a", literal(display), { url: href }), webTailLength: 0 };
348
+ }
349
+ if (this.markers && /[*_~`]/.test(cleaned))
350
+ this.warn("AMBIGUOUS_MARKER");
351
+ return literal(cleaned);
352
+ }
353
+ /** A pipe-separated table inside the destination's code block. */
354
+ codeTable(lines) {
355
+ const value = wrap("pre", wrap("code", literal(lines)));
356
+ if (!this.rich) {
357
+ if (this.markers && this.target !== "threema")
358
+ value.text = this.draftCode(true, lines);
359
+ else
360
+ this.warn("FORMAT_AS_TEXT");
361
+ }
362
+ return value;
363
+ }
218
364
  table(t, depth) {
219
365
  if (t.header.length > 32 || t.rows.length > 256)
220
366
  throw new ConversionError("LIMIT");
221
- if (!this.rich || this.target === "slack")
367
+ const mode = this.tableMode;
368
+ const enhanced = this.draft || mode !== "auto";
369
+ if (enhanced) {
370
+ const lines = t.raw.replace(/\n+$/, "").split("\n");
371
+ if (lines.slice(2).some((line) => tableWidth(line) !== t.header.length)) {
372
+ const parts = lines.flatMap((line, i) => [
373
+ ...(i ? [{ ...wrap("br", literal("")), text: "\n" }] : []),
374
+ literal(line),
375
+ ]);
376
+ if (this.markers && /[*_~`]/.test(t.raw))
377
+ this.warn("AMBIGUOUS_MARKER");
378
+ return wrap("p", join(parts));
379
+ }
380
+ }
381
+ this.sawTable = true;
382
+ const native = mode === "auto" && this.rich && this.target !== "slack";
383
+ if (!native)
222
384
  this.warn("TABLE_AS_ROWS");
223
- const header = t.header.map((cell) => this.render(cell.tokens, depth + 1));
224
- const rows = t.rows.map((row) => row.map((cell) => this.render(cell.tokens, depth + 1)));
225
- const tr = (cells, tag) => wrap("tr", join(cells.map((c) => wrap(tag, c))));
226
- const repeatedLabels = header.reduce((n, cell) => n + cell.text.length, 0) * rows.length;
385
+ const markers = this.markers;
386
+ if (mode === "code")
387
+ this.markers = false;
388
+ const renderRow = (cells) => cells.map((cell) => this.render(cell.tokens, depth + 1));
389
+ const header = renderRow(t.header);
390
+ const rows = t.rows.map(renderRow);
391
+ this.markers = markers;
392
+ const repeatedLabels = header.reduce((n, cell) => n + cell.text.length, 0) *
393
+ (enhanced ? Math.max(rows.length, 1) : rows.length);
227
394
  if (repeatedLabels > 262144)
228
395
  throw new ConversionError("LIMIT");
229
- const cards = rows.map((row) => {
230
- const fields = row.map((cell, i) => {
231
- const label = header[i]?.text || "Column " + (i + 1);
232
- return label + linkBoundary(header[i]?.endsInWebLink, ":") + ": " + (this.mobileChat && !cell.text ? "—" : cell.text);
233
- });
396
+ const dash = this.mobileChat || enhanced;
397
+ const value = (cell) => (dash && !cell.text ? "—" : cell.text);
398
+ if (mode === "code") {
399
+ const codeCell = (cell) => value(cell).replace(/[\\|]/g, "\\$&").replace(/\r?\n/g, " ");
400
+ const lines = [header, ...rows]
401
+ .map((row) => row.map(codeCell).join(" | "))
402
+ .join("\n");
403
+ return this.codeTable(lines);
404
+ }
405
+ const label = (i) => header[i]?.text || "Column " + (i + 1);
406
+ const separator = (i) => (header[i]?.webTailLength ? " : " : ": ");
407
+ // A header-only table still reads as one labeled row in drafts.
408
+ const fieldRows = rows.length || !enhanced ? rows : [header.map(() => literal(""))];
409
+ const cards = fieldRows.map((row) => {
410
+ const fields = row.map((cell, i) => label(i) + separator(i) + value(cell));
234
411
  return this.mobileChat ? "- " + fields.join(" · ") : fields.join("\n");
235
412
  });
236
413
  const text = cards.length
237
414
  ? cards.join(this.mobileChat ? "\n" : "\n\n")
238
415
  : header.map((h) => h.text).join(" | ");
416
+ if (mode === "cards" && this.rich) {
417
+ const blocks = fieldRows.map((row) => wrap("p", join(row.flatMap((cell, i) => [
418
+ ...(i ? [wrap("br", literal(""))] : []),
419
+ literal(label(i) + separator(i)),
420
+ cell.text ? cell : literal("—"),
421
+ ]))));
422
+ return { ...join(blocks), text };
423
+ }
239
424
  if (this.target === "slack") {
240
425
  const lines = text.split("\n");
241
426
  const parts = lines.flatMap((line, i) => i ? [wrap("br", literal("")), literal(line)] : [literal(line)]);
242
427
  return { ...wrap("p", join(parts)), text };
243
428
  }
429
+ // Email clients ignore stylesheets; drafts carry fixed inline styles and
430
+ // take alignment from the parsed delimiter row only.
431
+ const styled = this.draft && this.target === "email";
432
+ const alignStyle = {
433
+ left: "cellLeft",
434
+ center: "cellCenter",
435
+ right: "cellRight",
436
+ };
437
+ const cellStyle = (i) => alignStyle[t.align[i] ?? ""] ?? "cellLeft";
438
+ const tr = (cells, tag) => wrap("tr", join(cells.map((c, i) => wrap(tag, c, styled ? { style: cellStyle(i) } : {}))));
244
439
  const table = wrap("table", join([
245
440
  wrap("thead", tr(header, "th")),
246
441
  wrap("tbody", join(rows.map((r) => tr(r, "td")))),
247
- ]));
442
+ ]), styled ? { style: "table" } : {});
248
443
  return { ...table, text };
249
444
  }
250
445
  document(markdown) {
251
446
  let value;
252
447
  try {
253
- const parser = new Marked(markedFootnote());
448
+ const parser = this.draft
449
+ ? new Marked(markedFootnote(), { extensions: draftExtensions })
450
+ : new Marked(markedFootnote());
254
451
  parser.setOptions({ tokenizer: new MarkdownTokenizer() });
255
452
  const tokens = parser.lexer(markdown, parser.defaults);
256
453
  const definitions = tokens.filter((t) => t.type === "footnote");
@@ -262,7 +459,17 @@ class Renderer {
262
459
  for (const note of notes) {
263
460
  const label = "[" + (note.refs[0]?.id ?? nextNumber++) + "] ";
264
461
  const content = this.render(note.content, 1, true);
265
- sections.push(wrap("div", join([literal(label), content])));
462
+ const section = join([literal(label), content]);
463
+ const [first, ...rest] = content.nodes;
464
+ // Email drafts keep the label beside the opening line in mail clients.
465
+ if (this.draft && this.target === "email" && first?.kind === "p") {
466
+ const labelNode = { kind: "text", text: label, children: [] };
467
+ section.nodes = [
468
+ { ...first, children: [labelNode, ...first.children] },
469
+ ...rest,
470
+ ];
471
+ }
472
+ sections.push(wrap("div", section));
266
473
  }
267
474
  if (notes.length)
268
475
  value = join(sections, this.compact ? "\n" : "\n\n");
@@ -282,7 +489,9 @@ export function convert(input, target = "plaintext", options = {}) {
282
489
  if (!Object.values(Target).includes(target))
283
490
  throw unknownTarget(target, Object.values(Target));
284
491
  const markdown = validate(input, options);
285
- const renderer = new Renderer(target, options.policy ?? "readable");
492
+ const tableMode = options.tableMode ?? "auto";
493
+ const optedIn = options.aiDraft === true || tableMode !== "auto";
494
+ const renderer = new Renderer(target, options.policy ?? "readable", options.aiDraft === true, tableMode);
286
495
  const value = renderer.document(markdown);
287
496
  return {
288
497
  target,
@@ -290,6 +499,7 @@ export function convert(input, target = "plaintext", options = {}) {
290
499
  ...(renderer.rich ? { html: html(value.nodes) } : {}),
291
500
  format: renderer.rich ? "html" : renderer.markers ? "markers" : "text",
292
501
  diagnostics: describe([...renderer.warnings].sort()),
502
+ ...(optedIn ? { hasTable: renderer.sawTable } : {}),
293
503
  };
294
504
  }
295
505
  export function parseDocument(input, options = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdto-messages",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {