Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

adf.ts

454 lines16.1 KB

1/**
2 * Jira Cloud's rich text (Atlassian Document Format) to and from the markdown every client edits.
3 * Reading keeps what markdown can say and names the rest; writing produces only nodes Jira's
4 * schema accepts where markdown put them, since Jira refuses a whole document over one bad node.
5 */
6import * as DateTime from "effect/DateTime";
7import * as Option from "effect/Option";
8import remarkGfm from "remark-gfm";
9import remarkParse from "remark-parse";
10import { unified } from "unified";
11​
12export interface AdfNode {
13 readonly type: string;
14 readonly text?: string;
15 readonly attrs?: Readonly<Record<string, unknown>>;
16 readonly marks?: ReadonlyArray<{
17 readonly type: string;
18 readonly attrs?: Readonly<Record<string, unknown>>;
19 }>;
20 readonly content?: ReadonlyArray<AdfNode>;
22​
23function isNode(value: unknown): value is AdfNode {
24 return typeof value === "object" && value !== null && typeof (value as AdfNode).type === "string";
26​
27const children = (node: AdfNode): ReadonlyArray<AdfNode> =>
28 Array.isArray(node.content) ? node.content.filter(isNode) : [];
29​
30const attr = (node: AdfNode, key: string): string | null => {
31 const value = node.attrs?.[key];
32 return typeof value === "string" && value.length > 0 ? value : null;
33};
34​
35/** Jira's literal characters that markdown would read as syntax; `_` inside a word is inert. */
36const escape = (text: string) =>
37 text.replace(/[\\`*~[\]<&]|(?<![\p{L}\p{N}])_|_(?![\p{L}\p{N}])/gu, "\\$&");
38​
39/** Line openers that would make a paragraph a heading, quote, list or setext underline. */
40const escapeLineStarts = (text: string) =>
41 text.replace(/^([ \t]*)([#>+=-])/gm, "$1\\$2").replace(/^([ \t]*\d+)([.)])/gm, "$1\\$2");
42​
43/** A backtick run longer than any inside `code`, so the code cannot close its own fence. */
44const fence = (code: string, least: number) =>
45 "`".repeat(Math.max(least, ...(code.match(/`+/g) ?? []).map((run) => run.length + 1)));
46​
47function codeSpan(code: string): string {
48 // A space keeps an edge backtick off the fence; markdown strips one from each end.
49 const pad = /^`|`$|^ .*[^ ].* $/s.test(code) ? " " : "";
50 const ticks = fence(code, 1);
51 return `${ticks}${pad}${code}${pad}${ticks}`;
53​
54const ATTACHMENT = "_(attachment, open in Jira to view)_";
55​
56/** A link destination markdown reads back whole: parentheses escaped, spaces in angle brackets. */
57function linked(text: string, marks: NonNullable<AdfNode["marks"]>): string {
58 const href = marks.find((mark) => mark.type === "link")?.attrs?.["href"];
59 if (typeof href !== "string") return text;
60 const escaped = href.replace(/[\\()]/g, "\\$&");
61 return `[${text}](${/\s/u.test(href) ? `<${href.replace(/[\\<>]/g, "\\$&")}>` : escaped})`;
63​
64function inline(node: AdfNode): string {
65 switch (node.type) {
66 case "text": {
67 const marks = node.marks ?? [];
68 const raw = node.text ?? "";
69 if (marks.some((mark) => mark.type === "code")) {
70 return linked(codeSpan(raw), marks);
71 }
72 // A delimiter beside whitespace does not close, so edge spaces stay outside the marks.
73 const [, before = "", core = "", after = ""] = /^(\s*)(.*?)(\s*)$/su.exec(raw) ?? [];
74 if (core.length === 0) return raw;
75 let text = escape(core);
76 for (const mark of marks) {
77 if (mark.type === "strong") text = `**${text}**`;
78 else if (mark.type === "em") text = `*${text}*`;
79 else if (mark.type === "strike") text = `~~${text}~~`;
80 }
81 return `${before}${linked(text, marks)}${after}`;
82 }
83 case "hardBreak":
84 return "\\\n";
85 case "mention":
86 return attr(node, "text") ?? "@someone";
87 case "emoji":
88 return attr(node, "text") ?? attr(node, "shortName") ?? "";
89 case "inlineCard":
90 return attr(node, "url") ?? "";
91 case "status":
92 return attr(node, "text") ?? "";
93 case "date": {
94 const at = Number(node.attrs?.["timestamp"]);
95 return Option.match(DateTime.make(at), {
96 onNone: () => "",
97 onSome: (date) => DateTime.formatIso(date).slice(0, 10),
98 });
99 }
100 case "mediaInline":
101 return ATTACHMENT;
102 default:
103 return children(node).map(inline).join("");
104 }
106​
107const inlines = (node: AdfNode) => children(node).map(inline).join("");
108​
109const indent = (text: string, prefix: string) =>
110 text
111 .split("\n")
112 .map((line) => (line.length === 0 ? prefix.trimEnd() : prefix + line))
113 .join("\n");
114​
115function list(node: AdfNode, marker: (index: number) => string): string {
116 return children(node)
117 .map((item, index) => {
118 const lead = marker(index);
119 // Paragraphs keep a blank line between them, or they read back as one; so does a nested
120 // ordered list not starting at 1, which markdown would read as the paragraph's next line.
121 const body = children(item)
122 .map((child, at, all) => {
123 const text = block(child);
124 const next = all[at + 1];
125 if (next === undefined) return text;
126 const loose =
127 next.type === "paragraph" ||
128 (next.type === "orderedList" && (Number(next.attrs?.["order"]) || 1) !== 1);
129 return `${text}${loose ? "\n\n" : "\n"}`;
130 })
131 .join("");
132 return lead + indent(body, " ".repeat(lead.length)).slice(lead.length);
133 })
134 .join("\n");
136​
137function table(node: AdfNode): string {
138 const rows = children(node).map((row) =>
139 children(row).map((cell) =>
140 blocks(children(cell), " ")
141 .replaceAll("\\\n", " ")
142 .replaceAll("\n", " ")
143 .replaceAll("|", "\\|"),
144 ),
145 );
146 // Merged cells leave rows of different lengths; the widest row sets the column count.
147 const width = Math.max(0, ...rows.map((row) => row.length));
148 const [head, ...rest] = rows;
149 if (head === undefined || width === 0) return "";
150 const line = (cells: ReadonlyArray<string>) =>
151 `| ${[...cells, ...Array<string>(width - cells.length).fill("")].join(" | ")} |`;
152 return [line(head), line(Array<string>(width).fill("---")), ...rest.map(line)].join("\n");
154​
155function block(node: AdfNode): string {
156 switch (node.type) {
157 case "paragraph":
158 return escapeLineStarts(inlines(node));
159 case "heading": {
160 const level = Math.min(6, Math.max(1, Number(node.attrs?.["level"]) || 1));
161 // A trailing `#` would read as the heading's closing sequence.
162 return `${"#".repeat(level)} ${inlines(node).replace(/#+$/, "\\$&")}`;
163 }
164 case "bulletList":
165 return list(node, () => "- ");
166 case "orderedList": {
167 const start = Number(node.attrs?.["order"]) || 1;
168 return list(node, (index) => `${start + index}. `);
169 }
170 case "taskList":
171 return children(node)
172 .map((item) => `- [${item.attrs?.["state"] === "DONE" ? "x" : " "}] ${inlines(item)}`)
173 .join("\n");
174 case "codeBlock": {
175 const code = children(node)
176 .map((child) => child.text ?? "")
177 .join("");
178 const ticks = fence(code, 3);
179 return `${ticks}${attr(node, "language") ?? ""}\n${code}\n${ticks}`;
180 }
181 case "blockquote":
182 case "panel":
183 return indent(blocks(children(node)), "> ");
184 case "rule":
185 return "---";
186 case "expand":
187 case "nestedExpand": {
188 const title = attr(node, "title");
189 return [...(title === null ? [] : [`**${title}**`]), blocks(children(node))].join("\n\n");
190 }
191 case "table":
192 return table(node);
193 case "mediaSingle":
194 case "mediaGroup":
195 return ATTACHMENT;
196 case "blockCard":
197 case "embedCard":
198 return attr(node, "url") ?? "";
199 default:
200 return node.content === undefined ? inline(node) : blocks(children(node));
201 }
203​
204const blocks = (nodes: ReadonlyArray<AdfNode>, separator = "\n\n") =>
205 nodes
206 .map(block)
207 .filter((text) => text.length > 0)
208 .join(separator);
209​
210/** Markdown for a description or comment body; empty for none. Jira sends null for no text. */
211export function adfToMarkdown(document: unknown): string {
212 if (typeof document === "string") return document;
213 return isNode(document) ? blocks(children(document)) : "";
215​
216/** What `markdownToAdf` cannot write back, so rewriting the text would drop it from Jira. */
217const UNWRITABLE = new Set([
218 "media",
219 "mediaSingle",
220 "mediaGroup",
221 "mediaInline",
222 "extension",
223 "bodiedExtension",
224 "inlineExtension",
225 "layoutSection",
226 "decisionList",
227 "mention",
228 "emoji",
229 "status",
230 "date",
231 "expand",
232 "nestedExpand",
233 "panel",
234 "inlineCard",
235 "blockCard",
236 "embedCard",
237]);
238​
239const WRITABLE_MARKS = new Set(["link", "code", "strong", "em", "strike"]);
240​
241const merged = (node: AdfNode) =>
242 Number(node.attrs?.["colspan"] ?? 1) > 1 || Number(node.attrs?.["rowspan"] ?? 1) > 1;
243​
244export function hasUnwritableContent(document: unknown): boolean {
245 if (!isNode(document)) return false;
246 return (
247 UNWRITABLE.has(document.type) ||
248 merged(document) ||
249 // A table cell is written back as one paragraph.
250 ((document.type === "tableCell" || document.type === "tableHeader") &&
251 (children(document).length > 1 ||
252 children(document).some((child) => child.type !== "paragraph") ||
253 // A line break in a cell is written back as a space.
254 children(document).some((child) =>
255 children(child).some((leaf) => leaf.type === "hardBreak"),
256 ))) ||
257 // A checklist is written back flat, so one nested in another would be lost.
258 (document.type === "taskList" &&
259 children(document).some((child) => child.type === "taskList")) ||
260 (document.marks ?? []).some((mark) => !WRITABLE_MARKS.has(mark.type)) ||
261 children(document).some(hasUnwritableContent)
262 );
264​
265interface Mdast {
266 readonly type: string;
267 readonly value?: string;
268 readonly depth?: number;
269 readonly ordered?: boolean | null;
270 readonly start?: number | null;
271 readonly checked?: boolean | null;
272 readonly position?: { readonly start: { readonly offset?: number } };
273 readonly lang?: string | null;
274 readonly url?: string;
275 readonly alt?: string | null;
276 readonly identifier?: string;
277 readonly children?: ReadonlyArray<Mdast>;
279​
280type Mark = NonNullable<AdfNode["marks"]>[number];
281​
282/** Jira takes one mark of each type, and code beside nothing but a link; the outer mark wins. */
283function text(value: string, marks: ReadonlyArray<Mark>): AdfNode[] {
284 if (value.length === 0) return [];
285 const code = marks.some((mark) => mark.type === "code");
286 const kept = marks.filter(
287 (mark, index) =>
288 marks.findIndex((other) => other.type === mark.type) === index &&
289 (!code || mark.type === "code" || mark.type === "link"),
290 );
291 return [{ type: "text", text: value, ...(kept.length === 0 ? {} : { marks: kept }) }];
293​
294function toInline(node: Mdast, marks: ReadonlyArray<Mark>): AdfNode[] {
295 const within = (mark: Mark) =>
296 (node.children ?? []).flatMap((child) => toInline(child, [...marks, mark]));
297 switch (node.type) {
298 case "text":
299 case "html":
300 return text(node.value ?? "", marks);
301 case "inlineCode":
302 return text(node.value ?? "", [...marks, { type: "code" }]);
303 case "strong":
304 return within({ type: "strong" });
305 case "emphasis":
306 return within({ type: "em" });
307 case "delete":
308 return within({ type: "strike" });
309 case "link":
310 return within({ type: "link", attrs: { href: node.url ?? "" } });
311 case "image":
312 return text(node.alt || node.url || "", [
313 ...marks,
314 { type: "link", attrs: { href: node.url ?? "" } },
315 ]);
316 case "break":
317 return [{ type: "hardBreak" }];
318 default:
319 return (node.children ?? []).flatMap((child) => toInline(child, marks));
320 }
322​
323const paragraph = (node: Mdast, lead = ""): AdfNode => ({
324 type: "paragraph",
325 content: [...text(lead, []), ...(node.children ?? []).flatMap((child) => toInline(child, []))],
326});
327​
328/** Where the node starts in the markdown: unique within the document, as Jira asks of task ids. */
329const localId = (node: Mdast) => `task-${node.position?.start.offset ?? 0}`;
330​
331/** Every item a box with a single line of text: what a Jira task list holds. */
332function isChecklist(node: Mdast): boolean {
333 const items = node.children ?? [];
334 return (
335 !node.ordered &&
336 items.length > 0 &&
337 items.every(
338 (item) =>
339 item.checked != null &&
340 item.children?.length === 1 &&
341 item.children[0]!.type === "paragraph",
342 )
343 );
345​
346/** `nested` is inside a list item or quote, where Jira takes only text, lists and code. */
347function toBlocks(node: Mdast, nested: boolean): AdfNode[] {
348 switch (node.type) {
349 case "paragraph":
350 return [paragraph(node)];
351 case "heading":
352 return nested
353 ? [paragraph(node)]
354 : [{ ...paragraph(node), type: "heading", attrs: { level: node.depth ?? 1 } }];
355 case "code":
356 return [
357 {
358 type: "codeBlock",
359 ...(node.lang ? { attrs: { language: node.lang } } : {}),
360 content: text(node.value ?? "", []),
361 },
362 ];
363 case "thematicBreak":
364 return nested ? [] : [{ type: "rule" }];
365 case "blockquote": {
366 const content = (node.children ?? []).flatMap((child) => toBlocks(child, true));
367 return nested ? content : [{ type: "blockquote", content }];
368 }
369 case "list":
370 if (!nested && isChecklist(node)) {
371 return [
372 {
373 type: "taskList",
374 attrs: { localId: localId(node) },
375 content: (node.children ?? []).map((item): AdfNode => ({
376 type: "taskItem",
377 attrs: { localId: localId(item), state: item.checked ? "DONE" : "TODO" },
378 content: paragraph(item.children![0]!).content ?? [],
379 })),
380 },
381 ];
382 }
383 return [
384 {
385 type: node.ordered ? "orderedList" : "bulletList",
386 ...(node.ordered && node.start != null && node.start !== 1
387 ? { attrs: { order: node.start } }
388 : {}),
389 content: (node.children ?? []).map((item) => {
390 // A box Jira's task nodes cannot hold (nested content, a mixed list) stays as text.
391 const lead = item.checked == null ? "" : item.checked ? "[x] " : "[ ] ";
392 const [first, ...rest] = item.children ?? [];
393 const body =
394 first?.type === "paragraph"
395 ? [paragraph(first, lead), ...rest.flatMap((child) => toBlocks(child, true))]
396 : [
397 { type: "paragraph", content: text(lead, []) },
398 ...(item.children ?? []).flatMap((child) => toBlocks(child, true)),
399 ];
400 return { type: "listItem", content: body };
401 }),
402 },
403 ];
404 case "table": {
405 const rows = (node.children ?? []).map((row, index) => ({
406 type: "tableRow",
407 content: (row.children ?? []).map((cell) => ({
408 type: index === 0 ? "tableHeader" : "tableCell",
409 content: [paragraph(cell)],
410 })),
411 }));
412 return nested
413 ? rows.flatMap((row) => row.content.flatMap((cell) => cell.content))
414 : [{ type: "table", content: rows }];
415 }
416 case "html":
417 return [{ type: "paragraph", content: text(node.value ?? "", []) }];
418 default:
419 return (node.children ?? []).flatMap((child) => toBlocks(child, nested));
420 }
422​
423/** ADF has no link definitions, so a reference becomes the link it names; the first one wins. */
424function inlineReferences(root: Mdast): Mdast {
425 const urls = new Map<string, string>();
426 const collect = (node: Mdast): void => {
427 if (node.type === "definition" && node.identifier !== undefined && !urls.has(node.identifier))
428 urls.set(node.identifier, node.url ?? "");
429 node.children?.forEach(collect);
430 };
431 const resolve = (node: Mdast): Mdast => {
432 const url = node.identifier === undefined ? undefined : urls.get(node.identifier);
433 const type =
434 node.type === "linkReference" ? "link" : node.type === "imageReference" ? "image" : null;
435 return {
436 ...node,
437 ...(type !== null && url !== undefined ? { type, url } : {}),
438 ...(node.children === undefined ? {} : { children: node.children.map(resolve) }),
439 };
440 };
441 collect(root);
442 return resolve(root);
444​
445const parser = unified().use(remarkParse).use(remarkGfm);
446​
447export function markdownToAdf(markdown: string): AdfNode & { readonly version: 1 } {
448 const root = inlineReferences(parser.parse(markdown) as Mdast);
449 return {
450 version: 1,
451 type: "doc",
452 content: (root.children ?? []).flatMap((child) => toBlocks(child, false)),
453 };