3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-19 06:35:44 +01:00

Write ADF as lossless Jira wiki markup, carrying in Jira's {adf} macro what wiki markup cannot spell

This commit is contained in:
2026-11-17 01:33:31 +01:00
committed by Lillem4n
parent addcf453c2
commit 973c2a4480
11 changed files with 894 additions and 12 deletions
+22
View File
@@ -0,0 +1,22 @@
import type { AdfNode } from '../adf/document.ts'
import { carriedJson } from '../adf/carried-json.ts'
import { largestNesting } from '../nesting.ts'
import { success, type ConvertErrorPath, type Result } from '../result.ts'
// spec/wiki.md, The carry: `depth` is the nesting of the block list holding the node.
export function blockCarry(node: AdfNode, path: ConvertErrorPath, depth: number): Result<string> {
const json = carriedJson(node, node, 'compact', path, largestNesting - depth)
return json.ok ? success(`{adf:display=block}\n${closingMacroEscaped(json.value.json)}\n{adf}`) : json
}
// One node is carried as its JSON, a run of several as an array.
export function inlineCarry(nodes: readonly AdfNode[], path: ConvertErrorPath): Result<string> {
const carried = nodes.length === 1 && nodes[0] !== undefined ? nodes[0] : nodes
const json = carriedJson(carried, carried, 'compact', path, largestNesting)
return json.ok ? success(`{adf:display=inline}${closingMacroEscaped(json.value.json)}{adf}`) : json
}
// A `{` inside a JSON string is `\u007b`, so the closing `{adf}` is the only one the macro holds.
function closingMacroEscaped(json: string): string {
return json.replace(/"(?:[^"\\]|\\.)*"/g, (string) => string.replaceAll('{', '\\u007b'))
}
+329
View File
@@ -0,0 +1,329 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { AdfAttributes, AdfDocument, AdfMark, AdfNode } from '../../adf/document.ts'
import type { Result } from '../../result.ts'
import { adfToLosslessJiraWiki } from '../../index.ts'
import { largestNesting } from '../../nesting.ts'
function document(...content: AdfNode[]): AdfDocument {
return { content, type: 'doc', version: 1 }
}
function wiki(...content: AdfNode[]): string {
const result = adfToLosslessJiraWiki(document(...content))
return result.ok ? result.value : `${result.error.code}: ${result.error.message}`
}
function refusal(result: Result<unknown>): string {
return result.ok ? 'written' : `${result.error.code} at /${result.error.path.join('/')}`
}
function paragraph(...content: AdfNode[]): AdfNode {
return content.length === 0 ? { type: 'paragraph' } : { content, type: 'paragraph' }
}
function text(value: string, ...marks: AdfMark[]): AdfNode {
return marks.length === 0 ? { text: value, type: 'text' } : { marks, text: value, type: 'text' }
}
function line(value: string): string {
return wiki(paragraph(text(value)))
}
function marked(...marks: AdfMark[]): string {
return wiki(paragraph(text('a '), text('b', ...marks), text(' c')))
}
function block(json: string): string {
return `{adf:display=block}\n${json}\n{adf}`
}
function inline(json: string): string {
return `{adf:display=inline}${json}{adf}`
}
function item(...content: AdfNode[]): AdfNode {
return { content, type: 'listItem' }
}
function list(type: string, ...items: AdfNode[]): AdfNode {
return type === 'orderedList' ? { attrs: { order: 1 }, content: items, type } : { content: items, type }
}
function cell(type: string, ...content: AdfNode[]): AdfNode {
return { content: [paragraph(...content)], type }
}
function table(attrs: AdfAttributes, ...rows: AdfNode[][]): AdfNode {
return { attrs, content: rows.map((cells) => ({ content: cells, type: 'tableRow' })), type: 'table' }
}
function code(language: string | undefined, value: string): AdfNode {
return language === undefined ? { content: [text(value)], type: 'codeBlock' } : { attrs: { language }, content: [text(value)], type: 'codeBlock' }
}
function image(attrs: AdfAttributes, layout = 'center'): AdfNode {
return { attrs: { layout }, content: [{ attrs, type: 'media' }], type: 'mediaSingle' }
}
function quote(...content: AdfNode[]): AdfNode {
return { content, type: 'blockquote' }
}
function panel(panelType: string, ...content: AdfNode[]): AdfNode {
return { attrs: { panelType }, content, type: 'panel' }
}
const plainTable = { isNumberColumnEnabled: false, layout: 'default' }
test('writes an empty document as the empty string', () => {
assert.equal(wiki(), '')
})
test('carries a document holding no content key as its JSON', () => {
const result = adfToLosslessJiraWiki({ type: 'doc', version: 1 })
assert.equal(result.ok ? result.value : result.error.code, block('{"type":"doc","version":1}'))
})
test('parts blocks by one blank line', () => {
assert.equal(wiki(paragraph(text('a')), paragraph(text('b'))), 'a\n\nb')
})
test('writes a heading by its level', () => {
assert.equal(wiki({ attrs: { level: 2 }, content: [text('Title')], type: 'heading' }), 'h2. Title')
})
test('writes a blockquote of one paragraph as bq.', () => {
assert.equal(wiki(quote(paragraph(text('Quoted')))), 'bq. Quoted')
})
test('writes any other blockquote as a quote macro', () => {
assert.equal(wiki(quote(paragraph(text('a')), paragraph(text('b')))), '{quote}\na\n\nb\n{quote}')
})
test('writes a bullet list with an ordered list nested in an item', () => {
assert.equal(wiki(list('bulletList', item(paragraph(text('a')), list('orderedList', item(paragraph(text('b'))))), item(paragraph(text('c'))))), '* a\n*# b\n* c')
})
test('writes an ordered list of order 1 with # markers', () => {
assert.equal(wiki(list('orderedList', item(paragraph(text('a'))), item(paragraph(text('b'))))), '# a\n# b')
})
test('writes a code block of a listed language as a code macro', () => {
assert.equal(wiki(code('java', 'x = 1;\ny()')), '{code:java}\nx = 1;\ny()\n{code}')
})
test('writes a code block of language "" as a noformat macro', () => {
assert.equal(wiki(code('', '*x*')), '{noformat}\n*x*\n{noformat}')
})
test('writes a centred external image, with its alt where it holds one', () => {
assert.equal(wiki(image({ type: 'external', url: 'https://example.com/a.png' })), '!https://example.com/a.png!')
assert.equal(wiki(image({ alt: 'A cat', type: 'external', url: 'https://example.com/a.png' })), '!https://example.com/a.png|alt=A cat!')
})
test('writes a panel of each of the five types with its colour', () => {
assert.equal(wiki(panel('info', paragraph(text('Note this')))), '{panel:bgColor=#deebff}\nNote this\n{panel}')
assert.equal(wiki(panel('error', paragraph(text('x')))), '{panel:bgColor=#ffebe6}\nx\n{panel}')
})
test('writes a rule as four dashes', () => {
assert.equal(wiki({ type: 'rule' }), '----')
})
test('writes a table a row per line, an empty paragraph as a space', () => {
const header = [cell('tableHeader', text('H1')), cell('tableHeader', text('H2'))]
assert.equal(wiki(table(plainTable, header, [cell('tableCell', text('a')), cell('tableCell')])), '||H1||H2||\n|a| |')
})
test('carries a whitespace-only text in a table cell inline, and its paragraph stands', () => {
assert.equal(wiki(table(plainTable, [cell('tableCell', text(' '))])), `|${inline('{"text":" ","type":"text"}')}|`)
})
test('carries a block wiki markup cannot spell', () => {
assert.equal(wiki({ attrs: { title: 'More' }, content: [paragraph(text('x'))], type: 'expand' }), block('{"attrs":{"title":"More"},"content":[{"content":[{"text":"x","type":"text"}],"type":"paragraph"}],"type":"expand"}'))
})
test('carries a paragraph holding no content or only whitespace outside a table cell', () => {
assert.equal(wiki(paragraph()), block('{"type":"paragraph"}'))
assert.equal(wiki(paragraph(text(' '))), block('{"content":[{"text":" ","type":"text"}],"type":"paragraph"}'))
})
test('carries a block holding an attribute value no spelling stands for', () => {
assert.equal(wiki({ attrs: { order: 3 }, content: [item(paragraph(text('a')))], type: 'orderedList' }), block('{"attrs":{"order":3},"content":[{"content":[{"content":[{"text":"a","type":"text"}],"type":"paragraph"}],"type":"listItem"}],"type":"orderedList"}'))
assert.equal(wiki({ attrs: { localId: 'p1' }, content: [text('a')], type: 'paragraph' }), block('{"attrs":{"localId":"p1"},"content":[{"text":"a","type":"text"}],"type":"paragraph"}'))
assert.equal(wiki(code('foo', 'x')), block('{"attrs":{"language":"foo"},"content":[{"text":"x","type":"text"}],"type":"codeBlock"}'))
assert.equal(wiki(code(undefined, 'x')), block('{"content":[{"text":"x","type":"text"}],"type":"codeBlock"}'))
assert.equal(wiki(code('java', 'a {code} b')), block('{"attrs":{"language":"java"},"content":[{"text":"a \\u007bcode} b","type":"text"}],"type":"codeBlock"}'))
assert.equal(wiki(panel('tip', paragraph(text('x')))).startsWith('{adf:display=block}'), true)
assert.equal(wiki(table({ isNumberColumnEnabled: true, layout: 'default' }, [cell('tableCell', text('a'))])).startsWith('{adf:display=block}'), true)
assert.equal(wiki(image({ type: 'external', url: 'https://example.com/a.png' }, 'wide')).startsWith('{adf:display=block}'), true)
assert.equal(wiki(image({ alt: 'a|b', type: 'external', url: 'https://example.com/a.png' })).startsWith('{adf:display=block}'), true)
assert.equal(wiki(image({ id: 'f1', type: 'file' })).startsWith('{adf:display=block}'), true)
})
test('carries a list or a table where a block it holds rides', () => {
const riding = list('bulletList', item(paragraph(text('a')), code('foo', 'x')))
assert.equal(wiki(riding).startsWith('{adf:display=block}\n{"content":[{"content":[{"content"'), true)
assert.equal(wiki(list('bulletList', item(paragraph()))).startsWith('{adf:display=block}'), true)
assert.equal(wiki(table(plainTable, [{ content: [paragraph(text('a')), paragraph(text('b'))], type: 'tableCell' }])).startsWith('{adf:display=block}'), true)
})
test('carries a list item holding two lists of one kind in a row, which would read as one', () => {
const nested = list('bulletList', item(paragraph(text('b'))))
assert.equal(wiki(list('bulletList', item(paragraph(text('a')), nested, nested))).startsWith('{adf:display=block}'), true)
})
test('carries a quote macro holding another, and a panel holding another, since the macros cannot nest', () => {
assert.equal(wiki(quote(paragraph(text('a')), quote(paragraph(text('b')), paragraph(text('c'))))).startsWith('{adf:display=block}'), true)
assert.equal(wiki(panel('info', panel('note', paragraph(text('a'))))).startsWith('{adf:display=block}'), true)
assert.equal(wiki(quote(paragraph(text('a')), quote(paragraph(text('b'))))), '{quote}\na\n\nbq. b\n{quote}')
assert.equal(wiki(panel('info', quote(paragraph(text('a')), paragraph(text('b'))))), '{panel:bgColor=#deebff}\n{quote}\na\n\nb\n{quote}\n{panel}')
})
test('carries a heading holding a node that rides', () => {
assert.equal(wiki({ attrs: { level: 1 }, content: [{ attrs: { text: 'x' }, type: 'status' }], type: 'heading' }).startsWith('{adf:display=block}'), true)
})
test('writes a hard break as two backslashes', () => {
assert.equal(wiki(paragraph(text('a'), { type: 'hardBreak' }, text('b'))), 'a\\\\b')
})
test('writes a mention by account id, and carries one holding any other attribute', () => {
assert.equal(wiki(paragraph({ attrs: { accessLevel: '', id: '5b10' }, type: 'mention' })), '[~accountid:5b10]')
assert.equal(wiki(paragraph({ attrs: { accessLevel: '', id: '5b10', text: '@Ann' }, type: 'mention' })), inline('{"attrs":{"accessLevel":"","id":"5b10","text":"@Ann"},"type":"mention"}'))
})
test('carries an inline node wiki markup cannot spell as its JSON', () => {
assert.equal(wiki(paragraph(text('a '), { attrs: { text: 'DONE' }, type: 'status' }, text(' b'))), `a ${inline('{"attrs":{"text":"DONE"},"type":"status"}')} b`)
})
test('escapes a character wiki markup would read as markup where it stands', () => {
assert.equal(line('*not bold*'), '\\*not bold\\*')
assert.equal(line('a [b] {c} | d'), 'a \\[b\\] \\{c\\} \\| d')
assert.equal(line('# not a list'), '\\# not a list')
assert.equal(line('- not a list'), '\\- not a list')
assert.equal(line('h1. not a heading'), '\\h1. not a heading')
assert.equal(line('bq. not a quote'), '\\bq. not a quote')
assert.equal(line('a -- b'), 'a \\-\\- b')
assert.equal(line('what?? ok'), 'what\\?? ok')
assert.equal(line('Wow!!'), 'Wow\\!!')
assert.equal(line('Wow! (y) f(x) x:)'), 'Wow! \\(y) f\\(x) x\\:)')
})
test('leaves a character that reads as itself where it stands', () => {
assert.equal(line('well-known a - b 2*3 snake_case Hello!'), 'well-known a - b 2*3 snake_case Hello!')
assert.equal(line('a:Pb (on)x'), 'a:Pb (on)x')
})
test('carries a text no backslash protects', () => {
assert.equal(line('C:\\temp'), inline('{"text":"C:\\\\temp","type":"text"}'))
assert.equal(line('see https://example.com'), inline('{"text":"see https://example.com","type":"text"}'))
assert.equal(line('a\nb'), inline('{"text":"a\\nb","type":"text"}'))
assert.equal(wiki(paragraph(text(' a'), text('b', { type: 'strong' }))), `${inline('{"text":" a","type":"text"}')}*b*`)
})
test('carries the second of two texts the reader would read as one', () => {
assert.equal(wiki(paragraph(text('a'), text('b'))), `a${inline('{"text":"b","type":"text"}')}`)
})
test('writes each spelled mark with its delimiters', () => {
assert.equal(marked({ type: 'strong' }), 'a *b* c')
assert.equal(marked({ type: 'em' }), 'a _b_ c')
assert.equal(marked({ type: 'strike' }), 'a -b- c')
assert.equal(marked({ type: 'underline' }), 'a +b+ c')
assert.equal(marked({ type: 'code' }), 'a {{b}} c')
assert.equal(marked({ attrs: { type: 'sup' }, type: 'subsup' }), 'a ^b^ c')
assert.equal(marked({ attrs: { type: 'sub' }, type: 'subsup' }), 'a ~b~ c')
assert.equal(marked({ attrs: { color: '#ff0000' }, type: 'textColor' }), 'a {color:#ff0000}b{color} c')
})
test('writes a link with its text, its title, or as its href alone', () => {
assert.equal(marked({ attrs: { href: 'https://example.com' }, type: 'link' }), 'a [b|https://example.com] c')
assert.equal(marked({ attrs: { href: 'https://example.com', title: 'Home page' }, type: 'link' }), 'a [b|https://example.com|Home page] c')
assert.equal(wiki(paragraph(text('https://example.com', { attrs: { href: 'https://example.com' }, type: 'link' }))), '[https://example.com]')
})
test('nests marks in the order the array holds, outermost first', () => {
assert.equal(marked({ type: 'strong' }, { type: 'em' }), 'a *_b_* c')
assert.equal(marked({ type: 'em' }, { type: 'strong' }), 'a _*b*_ c')
assert.equal(wiki(paragraph(text('a ', { type: 'strong' }), text('b', { type: 'strong' }, { type: 'em' }))), '*a _b_*')
})
test('carries a run whose delimiters would not read', () => {
assert.equal(wiki(paragraph(text('a'), text('b', { type: 'strong' }), text('c'))), `a${inline('{"marks":[{"type":"strong"}],"text":"b","type":"text"}')}c`)
assert.equal(wiki(paragraph(text('a '), text(' b', { type: 'em' }))), `a ${inline('{"marks":[{"type":"em"}],"text":" b","type":"text"}')}`)
})
test('carries the run of nodes under a mark with no spelling as an array', () => {
const background = { attrs: { color: '#ffff00' }, type: 'backgroundColor' }
assert.equal(wiki(paragraph(text('a', background), text('b', background, { type: 'strong' }))), inline('[{"marks":[{"attrs":{"color":"#ffff00"},"type":"backgroundColor"}],"text":"a","type":"text"},{"marks":[{"attrs":{"color":"#ffff00"},"type":"backgroundColor"},{"type":"strong"}],"text":"b","type":"text"}]'))
})
test('carries a mark holding an attribute value no spelling stands for', () => {
assert.equal(marked({ attrs: {}, type: 'strong' }), `a ${inline('{"marks":[{"attrs":{},"type":"strong"}],"text":"b","type":"text"}')} c`)
assert.equal(marked({ attrs: { color: 'red' }, type: 'textColor' }).includes('{adf:display=inline}'), true)
assert.equal(marked({ attrs: { type: 'mid' }, type: 'subsup' }).includes('{adf:display=inline}'), true)
assert.equal(marked({ attrs: { href: 'a b' }, type: 'link' }).includes('{adf:display=inline}'), true)
assert.equal(marked({ attrs: { href: 'https://example.com', title: 'a|b' }, type: 'link' }).includes('{adf:display=inline}'), true)
assert.equal(marked({ type: 'strong' }, { type: 'strong' }).includes('{adf:display=inline}'), true)
})
test('escapes a { inside a carried JSON string, so the closing macro is the only one', () => {
assert.equal(wiki(paragraph({ attrs: { text: '{adf}' }, type: 'status' })), inline('{"attrs":{"text":"\\u007badf}"},"type":"status"}'))
})
test('refuses a carry whose JSON nests past 500 levels', () => {
let value: AdfAttributes[string] = 1
for (let level = 0; level < largestNesting - 2; level += 1) value = [value]
assert.equal(refusal(adfToLosslessJiraWiki(document(paragraph({ attrs: { a: value }, type: 'unknownInline' })))), 'written')
assert.equal(refusal(adfToLosslessJiraWiki(document(paragraph({ attrs: { a: [value] }, type: 'unknownInline' })))), 'unsupported-nesting-depth at /content/0/content/0')
assert.equal(refusal(adfToLosslessJiraWiki(document({ attrs: { a: value }, type: 'unknownBlock' }))), 'written')
assert.equal(refusal(adfToLosslessJiraWiki(document({ attrs: { a: [value] }, type: 'unknownBlock' }))), 'unsupported-nesting-depth at /content/0')
})
test('refuses what every writer refuses before writing', () => {
assert.equal(refusal(adfToLosslessJiraWiki({ content: [], type: 'doc', version: 2 })), 'unsupported-document-version at /')
assert.equal(refusal(adfToLosslessJiraWiki(JSON.parse('{"type":"doc"}'))), 'not-an-adf-document at /')
})
test('carries a heading of no level 1 to 6, or of no content', () => {
assert.equal(wiki({ attrs: { level: 7 }, content: [text('a')], type: 'heading' }), block('{"attrs":{"level":7},"content":[{"text":"a","type":"text"}],"type":"heading"}'))
assert.equal(wiki({ attrs: { level: 1 }, type: 'heading' }), block('{"attrs":{"level":1},"type":"heading"}'))
})
test('carries a rule holding attributes, and an image whose URL wiki markup cannot hold', () => {
assert.equal(wiki({ attrs: { a: 1 }, type: 'rule' }), block('{"attrs":{"a":1},"type":"rule"}'))
assert.equal(wiki(image({ type: 'external', url: 'a b' })).startsWith('{adf:display=block}'), true)
})
test('carries a marked hard break, and a mention whose id wiki markup cannot hold', () => {
assert.equal(wiki(paragraph(text('a'), { marks: [{ type: 'strong' }], type: 'hardBreak' })), `a${inline('{"marks":[{"type":"strong"}],"type":"hardBreak"}')}`)
assert.equal(wiki(paragraph({ attrs: { accessLevel: '', id: 'a b' }, type: 'mention' })), inline('{"attrs":{"accessLevel":"","id":"a b"},"type":"mention"}'))
})
test('carries a code mark holding attributes', () => {
assert.equal(marked({ attrs: { a: 1 }, type: 'code' }), `a ${inline('{"marks":[{"attrs":{"a":1},"type":"code"}],"text":"b","type":"text"}')} c`)
})
test('writes a link text equal to its href with its text where the link marks a neighbour too', () => {
const link = { attrs: { href: 'mailto:a@example.com' }, type: 'link' }
assert.equal(wiki(paragraph(text('mailto:a@example.com', link), text('b', { type: 'strong' }, link))), '[mailto:a@example.com|mailto:a@example.com]*[b|mailto:a@example.com]*')
assert.equal(wiki(paragraph(text('b', { type: 'strong' }, link), text('mailto:a@example.com', link))), '*[b|mailto:a@example.com]*[mailto:a@example.com|mailto:a@example.com]')
})
test('closes an inner mark where the next node leaves it', () => {
assert.equal(wiki(paragraph(text('a', { type: 'strong' }, { type: 'em' }), text(' b', { type: 'strong' }))), '*_a_ b*')
})
test('escapes a smiley the node edge cuts, unless the line ends there', () => {
assert.equal(wiki(paragraph(text('a ('), { attrs: { accessLevel: '', id: '5b10' }, type: 'mention' })), 'a \\([~accountid:5b10]')
assert.equal(line('a ('), 'a (')
})
test('refuses a heading holding a carry past 500 levels', () => {
let value: AdfAttributes[string] = 1
for (let level = 0; level < largestNesting - 1; level += 1) value = [value]
assert.equal(refusal(adfToLosslessJiraWiki(document({ attrs: { level: 1 }, content: [{ attrs: { a: value }, type: 'unknownInline' }], type: 'heading' }))), 'unsupported-nesting-depth at /content/0/content/0')
})
+82
View File
@@ -0,0 +1,82 @@
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
import type { Result } from '../../result.ts'
import { blockCarry } from '../carry.ts'
import { joinedWithin, withinEngineLimits } from '../../length-bound.ts'
import { nodeAttrs, nodeContent, readAdfDocument, writableContent } from '../../adf/document.ts'
import { panelColours } from '../spellings.ts'
import { spelledBlocks, type Spelling } from './spelled-blocks.ts'
// `prefix`: the markers of the lists holding the block, one character per level.
type Pending = string | { node: AdfNode; prefix: string }
const listMarkers: Readonly<Record<string, string>> = { bulletList: '*', orderedList: '#' }
export function adfToLosslessJiraWiki(document: AdfDocument): Result<string> {
return withinEngineLimits(() => {
const read = readAdfDocument(document)
if (!read.ok) return read
const content = writableContent(read.value)
if (!content.ok) return content
return content.value === undefined ? blockCarry(read.value, [], 0) : writeWiki(content.value)
})
}
// Every block a spelled block holds is spelled too, so only the document's own blocks ride. A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded).
function writeWiki(content: readonly AdfNode[]): Result<string> {
const found = spelledBlocks(content)
if (!found.ok) return found
const spelled = found.value
const pieces: string[] = []
for (const [index, node] of content.entries()) {
if (index > 0) pieces.push('\n\n')
const spelling = spelled.get(node)
if (spelling === undefined || spelling.blank) {
const carry = blockCarry(node, ['content', index], 0)
if (!carry.ok) return carry
pieces.push(carry.value)
} else writeSpelled(node, spelled, pieces)
}
return joinedWithin(pieces)
}
function writeSpelled(root: AdfNode, spelled: ReadonlyMap<AdfNode, Spelling>, pieces: string[]): void {
const pending: Pending[] = [{ node: root, prefix: '' }]
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
if (typeof next === 'string') pieces.push(next)
else for (const piece of blockPieces(next.node, next.prefix, spelled).reverse()) pending.push(piece)
}
}
function blockPieces(node: AdfNode, prefix: string, spelled: ReadonlyMap<AdfNode, Spelling>): Pending[] {
const text = spelled.get(node)?.text
if (text !== undefined) return [text]
const content = nodeContent(node)
const marker = listMarkers[node.type]
if (marker !== undefined) return listPieces(content, `${prefix}${marker}`)
if (node.type === 'table') return tablePieces(content)
const [only] = content
if (node.type === 'blockquote' && content.length === 1 && only?.type === 'paragraph') return ['bq. ', { node: only, prefix: '' }]
const colour = node.type === 'panel' ? panelColours[String(nodeAttrs(node)['panelType'])] : undefined
const [open, close] = colour === undefined ? ['{quote}', '{quote}'] : [`{panel:bgColor=${colour}}`, '{panel}']
const blocks = content.flatMap((child, index): Pending[] => [...(index > 0 ? ['\n\n'] : []), { node: child, prefix: '' }])
return [`${open}\n`, ...blocks, `\n${close}`]
}
// An item's paragraph stands on its marker's line, and each list it holds follows on the lines below, one marker deeper.
function listPieces(items: readonly AdfNode[], prefix: string): Pending[] {
return items.flatMap((item, index): Pending[] =>
nodeContent(item).flatMap((child, position): Pending[] => (position === 0 ? [`${index > 0 ? '\n' : ''}${prefix} `, { node: child, prefix }] : ['\n', { node: child, prefix }])),
)
}
// A row closes with its last cell's delimiter.
function tablePieces(rows: readonly AdfNode[]): Pending[] {
return rows.flatMap((row, index): Pending[] => {
let delimiter = ''
const cells = nodeContent(row).flatMap((cell): Pending[] => {
delimiter = cell.type === 'tableHeader' ? '||' : '|'
return [delimiter, ...nodeContent(cell).map((paragraph) => ({ node: paragraph, prefix: '' }))]
})
return [...(index > 0 ? ['\n'] : []), ...cells, delimiter]
})
}
+161
View File
@@ -0,0 +1,161 @@
import type { AdfMark, AdfNode } from '../../adf/document.ts'
import { escapedText } from './text-escaping.ts'
import { holdsOnlyAttributes, identicalMark, identicalMarks, isSpellableText, nodeAttrs, nodeMarks } from '../../adf/document.ts'
import { inlineCarry } from '../carry.ts'
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
// `carried`: whether any node of the line rides the carry.
export type Line = { carried: boolean; line: string }
// `checked`: a delimiter that reads only beside whitespace, punctuation or the line's edge.
type Delimiters = { checked: boolean; close: string; open: string }
// `marks`: those that group the node with its neighbours; `spelled`: the node's spelling and the delimiters of those marks, `undefined` where it rides.
type Atom = { marks: readonly AdfMark[]; spelled: { marks: readonly SpelledMark[]; text: string } | undefined }
type SpelledMark = { delimiters: Delimiters; mark: AdfMark }
type Token = { checked: boolean; kind: 'atom' | 'close' | 'open'; text: string }
const characterDelimiters: Readonly<Record<string, string>> = { em: '_', strike: '-', strong: '*', underline: '+' }
const spellableUrl = /^[^\s[\]{}|\\]+$/
const spellableColour = /^#[0-9a-f]{6}$/i
// spec/wiki.md, Inline and Marks: the nodes, each run of marked nodes, and the carry around what wiki markup cannot spell.
export function inlineLine(nodes: readonly AdfNode[], path: ConvertErrorPath): Result<Line> {
const atoms = nodes.map((node, index) => atom(node, nodes, index))
const groups = markedGroups(atoms)
let line = ''
let carried = false
for (const [position, { first, last }] of groups.entries()) {
const next = groups[position + 1]
const following = next === undefined ? undefined : atoms[next.first]
const after = following === undefined ? undefined : following.marks.length > 0 ? '{' : (following.spelled?.text ?? '{')
const written = groupSpelling(atoms.slice(first, last + 1), line.at(-1), after?.[0])
if (written === undefined) {
const carry = inlineCarry(nodes.slice(first, last + 1), [...path, 'content', first])
if (!carry.ok) return carry
line += carry.value
carried = true
} else line += written
}
return success({ carried, line })
}
function atom(node: AdfNode, nodes: readonly AdfNode[], index: number): Atom {
const { text } = node
if (node.type !== 'text' || text === undefined) {
const leaf = leafSpelling(node)
return { marks: [], spelled: leaf === undefined ? undefined : { marks: [], text: leaf } }
}
const marks = nodeMarks(node)
const spelled = spelledMarks(marks)
const previous = nodes[index - 1]
const joinsPrevious = previous?.type === 'text' && identicalMarks(nodeMarks(previous), marks)
if (!isSpellableText(node) || joinsPrevious || spelled === undefined) return { marks, spelled: undefined }
const href = hrefSpelling(node, nodes, index)
if (href !== undefined) return { marks: marks.slice(0, -1), spelled: { marks: spelled.slice(0, -1), text: href } }
const escaped = escapedText(text, index === 0, index === nodes.length - 1)
return { marks, spelled: escaped === undefined ? undefined : { marks: spelled, text: escaped } }
}
// `undefined` where a mark has no spelling, or two marks share a type.
function spelledMarks(marks: readonly AdfMark[]): SpelledMark[] | undefined {
const spelled: SpelledMark[] = []
for (const [position, mark] of marks.entries()) {
const delimiters = markDelimiters(mark)
if (delimiters === undefined || marks.findIndex((other) => other.type === mark.type) !== position) return undefined
spelled.push({ delimiters, mark })
}
return spelled
}
function leafSpelling(node: AdfNode): string | undefined {
if (node.type === 'hardBreak') return holdsOnlyAttributes(node, []) && node.content === undefined ? '\\\\' : undefined
if (node.type !== 'mention' || !holdsOnlyAttributes(node, ['accessLevel', 'id'])) return undefined
const { accessLevel, id } = nodeAttrs(node)
return accessLevel === '' && typeof id === 'string' && spellableUrl.test(id) ? `[~accountid:${id}]` : undefined
}
// `[<href>]`: the text is the href of the link that is its innermost mark, a link marking no node beside it.
function hrefSpelling(node: AdfNode, nodes: readonly AdfNode[], index: number): string | undefined {
const link = nodeMarks(node).at(-1)
if (link?.type !== 'link') return undefined
const { href, ...others } = nodeAttrs(link)
if (typeof href !== 'string' || href !== node.text || Object.keys(others).length > 0 || href.startsWith('~') || !spellableUrl.test(href)) return undefined
const sharesLink = (neighbour: AdfNode | undefined): boolean => neighbour !== undefined && nodeMarks(neighbour).some((mark) => identicalMark(mark, link))
return sharesLink(nodes[index - 1]) || sharesLink(nodes[index + 1]) ? undefined : `[${href}]`
}
// `undefined` where wiki markup has no spelling for the mark.
function markDelimiters(mark: AdfMark): Delimiters | undefined {
const attrs = nodeAttrs(mark)
const character = characterDelimiters[mark.type]
if (character !== undefined) return mark.attrs === undefined ? { checked: true, close: character, open: character } : undefined
if (mark.type === 'code') return mark.attrs === undefined ? { checked: true, close: '}}', open: '{{' } : undefined
if (mark.type === 'subsup') {
const delimiter = attrs['type'] === 'sub' ? '~' : attrs['type'] === 'sup' ? '^' : undefined
return delimiter !== undefined && Object.keys(attrs).length === 1 ? { checked: true, close: delimiter, open: delimiter } : undefined
}
if (mark.type === 'textColor') {
const { color } = attrs
return typeof color === 'string' && spellableColour.test(color) && Object.keys(attrs).length === 1 ? { checked: false, close: '{color}', open: `{color:${color}}` } : undefined
}
return mark.type === 'link' ? linkDelimiters(attrs) : undefined
}
function linkDelimiters(attrs: Readonly<Record<string, unknown>>): Delimiters | undefined {
const { href, title, ...others } = attrs
if (Object.keys(others).length > 0 || typeof href !== 'string' || !spellableUrl.test(href)) return undefined
if (title === undefined) return { checked: false, close: `|${href}]`, open: '[' }
return typeof title === 'string' && /^[^\s[\]{}|\\](?:[^[\]{}|\\\r\n]*[^\s[\]{}|\\])?$/.test(title) ? { checked: false, close: `|${href}|${title}]`, open: '[' } : undefined
}
// Runs of nodes sharing at least their outermost mark, each spelled or carried as a whole.
function markedGroups(atoms: readonly Atom[]): { first: number; last: number }[] {
const groups: { first: number; last: number }[] = []
for (const [index, current] of atoms.entries()) {
const group = groups.at(-1)
const previous = atoms[index - 1]
if (group !== undefined && previous !== undefined && sharedMarks(previous.marks, current.marks) > 0) group.last = index
else groups.push({ first: index, last: index })
}
return groups
}
function sharedMarks(left: readonly AdfMark[], right: readonly AdfMark[]): number {
const shared = left.findIndex((mark, index) => {
const other = right[index]
return other === undefined || !identicalMark(mark, other)
})
return shared === -1 ? left.length : shared
}
// Marks nest in the order the array holds, outermost first; `undefined` where a node or a delimiter fails.
function groupSpelling(atoms: readonly Atom[], before: string | undefined, after: string | undefined): string | undefined {
const tokens: Token[] = []
let open: readonly SpelledMark[] = []
for (const { spelled } of atoms) {
if (spelled === undefined) return undefined
const { marks, text } = spelled
const shared = sharedMarks(open.map(({ mark }) => mark), marks.map(({ mark }) => mark))
for (const mark of open.slice(shared).reverse()) tokens.push(delimiterToken(mark, 'close'))
for (const mark of marks.slice(shared)) tokens.push(delimiterToken(mark, 'open'))
tokens.push({ checked: false, kind: 'atom', text })
open = marks
}
for (const mark of open.slice().reverse()) tokens.push(delimiterToken(mark, 'close'))
return tokens.every((token, index) => delimiterReads(token, tokens[index - 1]?.text.at(-1) ?? before, tokens[index + 1]?.text[0] ?? after)) ? tokens.map(({ text }) => text).join('') : undefined
}
function delimiterToken({ delimiters: { checked, close, open } }: SpelledMark, kind: 'close' | 'open'): Token {
return { checked, kind, text: kind === 'open' ? open : close }
}
// spec/wiki.md, Marks: a delimiter sits beside whitespace, punctuation or the line's edge, and its run neither starts nor ends with whitespace.
function delimiterReads({ checked, kind }: Token, before: string | undefined, after: string | undefined): boolean {
if (!checked) return true
const outside = kind === 'open' ? before : after
const inside = kind === 'open' ? after : before
return (outside === undefined || !/[\p{L}\p{N}]/u.test(outside)) && inside !== undefined && !/\s/u.test(inside)
}
+141
View File
@@ -0,0 +1,141 @@
import type { AdfNode } from '../../adf/document.ts'
import type { JsonValue } from '../../json-value.ts'
import { codeLanguages, panelColours } from '../spellings.ts'
import { holdsOnlyAttributes, isUnmarkedSpellableText, nodeAttrs, nodeContent } from '../../adf/document.ts'
import { inlineLine } from './inline-line.ts'
import { isHeadingLevel } from '../../adf/block-nodes.ts'
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
// `blank`: a paragraph holding no content or only whitespace, which only a table cell holds, written as a space; `macros`: the `{quote}` and `{panel}` the block writes, which can't nest in their own kind; `text`: the block's spelling, where no container composes it.
export type Spelling = { blank: boolean; macros: number; text: string | undefined }
type Step = { exit: boolean; node: AdfNode; path: ConvertErrorPath }
const quoteMacro = 1
const panelMacro = 2
const lists = ['bulletList', 'orderedList']
const spellableAlt = /^[^\s!|,\\[\]{}](?:[^!|,\\[\]{}\r\n]*[^\s!|,\\[\]{}])?$/
const spellableImageUrl = /^[^\s!|\\[\]{}]+$/
// spec/wiki.md, Blocks: each block wiki markup spells, found after its children, since a block holding one that rides rides too. A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded).
export function spelledBlocks(content: readonly AdfNode[]): Result<Map<AdfNode, Spelling>> {
const spelled = new Map<AdfNode, Spelling>()
const pending: Step[] = content.map((node, index) => ({ exit: false, node, path: ['content', index] })).reverse()
for (let step = pending.pop(); step !== undefined; step = pending.pop()) {
const { exit, node, path } = step
if (exit) {
const spelling = containerSpelling(node, spelled)
if (spelling !== undefined) spelled.set(node, spelling)
} else if (containerHolds(node)) {
pending.push({ exit: true, node, path })
for (const [index, child] of nodeContent(node).entries()) pending.push({ exit: false, node: child, path: [...path, 'content', index] })
} else {
const spelling = leafSpelling(node, path)
if (!spelling.ok) return spelling
if (spelling.value !== undefined) spelled.set(node, spelling.value)
}
}
return success(spelled)
}
// Whether a container's own attributes and the types of its children have a spelling.
function containerHolds(node: AdfNode): boolean {
const content = nodeContent(node)
if (content.length === 0) return false
switch (node.type) {
case 'blockquote':
return holdsExactly(node, {})
case 'bulletList':
case 'orderedList':
return holdsExactly(node, node.type === 'orderedList' ? { order: 1 } : {}) && content.every((child) => child.type === 'listItem')
case 'listItem':
return holdsExactly(node, {}) && content[0]?.type === 'paragraph' && content.slice(1).every((child, index) => lists.includes(child.type) && child.type !== content[index]?.type)
case 'panel': {
const { panelType } = nodeAttrs(node)
return holdsOnlyAttributes(node, ['panelType']) && typeof panelType === 'string' && Object.hasOwn(panelColours, panelType)
}
case 'table':
return holdsExactly(node, { isNumberColumnEnabled: false, layout: 'default' }) && content.every((child) => child.type === 'tableRow')
case 'tableCell':
case 'tableHeader':
return holdsExactly(node, {}) && content.length === 1 && content[0]?.type === 'paragraph'
case 'tableRow':
return holdsExactly(node, {}) && content.every((child) => child.type === 'tableCell' || child.type === 'tableHeader')
default:
return false
}
}
// Called once the children are found: `undefined` where one rides.
function containerSpelling(node: AdfNode, spelled: ReadonlyMap<AdfNode, Spelling>): Spelling | undefined {
const content = nodeContent(node)
const cell = node.type === 'tableCell' || node.type === 'tableHeader'
const children = content.map((child) => spelled.get(child)).filter((child): child is Spelling => child !== undefined && (cell || !child.blank))
if (children.length < content.length) return undefined
const macros = children.reduce((held, child) => held | child.macros, 0)
if (node.type === 'blockquote') {
// A blockquote of one paragraph is written `bq. `, no macro.
if (content.length === 1 && content[0]?.type === 'paragraph') return { blank: false, macros, text: undefined }
return (macros & quoteMacro) === 0 ? { blank: false, macros: macros | quoteMacro, text: undefined } : undefined
}
if (node.type === 'panel') return (macros & panelMacro) === 0 ? { blank: false, macros: macros | panelMacro, text: undefined } : undefined
return { blank: false, macros, text: undefined }
}
function leafSpelling(node: AdfNode, path: ConvertErrorPath): Result<Spelling | undefined> {
if (node.type === 'paragraph') return paragraphSpelling(node, path)
if (node.type === 'heading') return headingSpelling(node, path)
return success(spelledText(simpleLeafText(node)))
}
function paragraphSpelling(node: AdfNode, path: ConvertErrorPath): Result<Spelling | undefined> {
if (!holdsExactly(node, {})) return success(undefined)
if (node.content === undefined) return success({ blank: true, macros: 0, text: ' ' })
const line = inlineLine(node.content, path)
if (!line.ok) return line
return success({ blank: node.content.every((child) => child.type === 'text') && /^\s*$/u.test(node.content.map(({ text }) => text).join('')), macros: 0, text: line.value.line })
}
function headingSpelling(node: AdfNode, path: ConvertErrorPath): Result<Spelling | undefined> {
const { level } = nodeAttrs(node)
if (!holdsOnlyAttributes(node, ['level']) || !isHeadingLevel(level) || node.content === undefined) return success(undefined)
const line = inlineLine(node.content, path)
if (!line.ok) return line
return success(line.value.carried ? undefined : spelledText(`h${level}. ${line.value.line}`))
}
function simpleLeafText(node: AdfNode): string | undefined {
if (node.type === 'rule') return holdsExactly(node, {}) && node.content === undefined ? '----' : undefined
if (node.type === 'codeBlock') return codeText(node)
return node.type === 'mediaSingle' && holdsExactly(node, { layout: 'center' }) ? imageText(nodeContent(node)) : undefined
}
function codeText(node: AdfNode): string | undefined {
const { language } = nodeAttrs(node)
const [text, ...others] = nodeContent(node)
const code = text?.text
if (!holdsOnlyAttributes(node, ['language']) || typeof language !== 'string' || text === undefined || code === undefined || others.length > 0 || !isUnmarkedSpellableText(text)) return undefined
if (code.includes('{code}') || code.includes('{noformat}')) return undefined
if (language === '') return `{noformat}\n${code}\n{noformat}`
return codeLanguages.includes(language) ? `{code:${language}}\n${code}\n{code}` : undefined
}
function imageText(content: readonly AdfNode[]): string | undefined {
const [media, ...others] = content
if (media?.type !== 'media' || others.length > 0 || media.content !== undefined || !holdsOnlyAttributes(media, ['alt', 'type', 'url'])) return undefined
const { alt, type, url } = nodeAttrs(media)
if (type !== 'external' || typeof url !== 'string' || !spellableImageUrl.test(url)) return undefined
if (alt === undefined) return `!${url}!`
return typeof alt === 'string' && spellableAlt.test(alt) ? `!${url}|alt=${alt}!` : undefined
}
function spelledText(text: string | undefined): Spelling | undefined {
return text === undefined ? undefined : { blank: false, macros: 0, text }
}
// The node holds exactly these attributes with these values, and no marks.
function holdsExactly(node: AdfNode, values: Readonly<Record<string, JsonValue>>): boolean {
const attrs = nodeAttrs(node)
return holdsOnlyAttributes(node, Object.keys(values)) && Object.entries(values).every(([key, value]) => attrs[key] === value)
}
+51
View File
@@ -0,0 +1,51 @@
import { smileys } from '../spellings.ts'
// What stands beside a character: a node's edge inside a line may meet a delimiter, so it counts as punctuation.
type Side = 'punctuation' | 'space' | 'word'
const alwaysEscaped = '[]{}|'
const delimiters = '*+-^_~'
const lineStartMarkers = '#*-'
const lineStartWords = /^(?:bq|h[1-6])\./i
const smileyOpeners = '(:;'
const smileyCharacters = smileys.map((smiley) => Array.from(smiley))
const unprotectable = /[\\\r\n]|https?:\/\//i
// spec/wiki.md, Inline: `undefined` where no backslash protects the text, so it rides the carry.
export function escapedText(text: string, lineStart: boolean, lineEnd: boolean): string | undefined {
if (unprotectable.test(text)) return undefined
if ((lineStart && /^\s/u.test(text)) || (lineEnd && /\s$/u.test(text))) return undefined
const characters = Array.from(text)
const edges: { end: Side; start: Side } = { end: lineEnd ? 'space' : 'punctuation', start: lineStart ? 'space' : 'punctuation' }
return characters.map((character, index) => (escapes(character, characters, index, edges, lineStart) ? `\\${character}` : character)).join('')
}
function escapes(character: string, characters: readonly string[], index: number, edges: { end: Side; start: Side }, lineStart: boolean): boolean {
const previous = characters[index - 1]
const next = characters[index + 1]
const before = previous === undefined ? edges.start : side(previous)
const after = next === undefined ? edges.end : side(next)
if (alwaysEscaped.includes(character)) return true
if (lineStart && index === 0 && (lineStartMarkers.includes(character) || lineStartWords.test(characters.join('')))) return true
// A delimiter both of whose neighbours are words, or both spaces, neither opens nor closes a run.
if (delimiters.includes(character) && !(before === after && before !== 'punctuation')) return true
if (character === '?' && next === '?') return true
if (character === '!' && after !== 'space') return true
return smileyOpeners.includes(character) && opensSmiley(characters, index, edges.end)
}
// A smiley reads wherever no letter or digit follows it; one the node's edge cuts may close in the next node's spelling.
function opensSmiley(characters: readonly string[], index: number, end: Side): boolean {
return smileyCharacters.some((spelled) => {
const held = characters.slice(index, index + spelled.length)
if (held.some((character, offset) => character !== spelled[offset])) return false
if (held.length < spelled.length) return end !== 'space'
const next = characters[index + spelled.length]
return (next === undefined ? end : side(next)) !== 'word'
})
}
function side(character: string): Side {
if (/\s/u.test(character)) return 'space'
return /[\p{L}\p{N}]/u.test(character) ? 'word' : 'punctuation'
}
+69
View File
@@ -0,0 +1,69 @@
// spec/wiki.md, Blocks: the names Atlassian's text formatting notation help lists for `{code}`.
export const codeLanguages: readonly string[] = [
'actionscript',
'ada',
'applescript',
'bash',
'c',
'c#',
'c++',
'css',
'erlang',
'go',
'groovy',
'haskell',
'html',
'java',
'javascript',
'json',
'lua',
'nyan',
'objc',
'perl',
'php',
'python',
'r',
'ruby',
'scala',
'sql',
'swift',
'visualbasic',
'xml',
'yaml',
]
// spec/wiki.md, Blocks: the `bgColor` Jira writes for each panel type it reads back.
export const panelColours: Readonly<Record<string, string>> = {
error: '#ffebe6',
info: '#deebff',
note: '#eae6ff',
success: '#e3fcef',
warning: '#fffae6',
}
// spec/wiki.md, What only the reader reads: each smiley Jira reads as an emoji.
export const smileys: readonly string[] = [
'(!)',
'(*)',
'(*b)',
'(*g)',
'(*r)',
'(*y)',
'(+)',
'(-)',
'(/)',
'(?)',
'(flag)',
'(flagoff)',
'(i)',
'(n)',
'(off)',
'(on)',
'(x)',
'(y)',
':(',
':)',
':D',
':P',
';)',
]