// Words drops raw HTML, so markdown.ts writes tag-shaped text as `<`
// first; a mistake there either loses text a model wrote or lets markup
// through. Render generated Markdown through the real Words build and check
// both, and that splitting a document into blocks changes nothing else.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { stripTypeScriptTypes } from 'node:module';
import test from 'node:test';
import { createHtmlRenderer } from '@pierre/words/html';
import { check, fc } from './property.mjs';
const source = stripTypeScriptTypes(
await readFile(new URL('../src/lib/markdown.ts', import.meta.url), 'utf8'),
).replace(
/from '(@pierre\/words\/[\w-]+)'/g,
(_, name) => `from '${import.meta.resolve(name)}'`,
);
const { prepareMarkdown, preparer, markdownOptions, documentHtml } =
await import(
`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`
);
function words(prepared, text, streaming = false) {
const formatter = createHtmlRenderer(markdownOptions(text, 't-'));
const html = formatter.render(prepared, streaming, streaming).html;
formatter.dispose();
return html;
}
const render = (text, streaming = false) =>
words(prepareMarkdown(text, streaming), text, streaming);
const decode = (text) =>
text.replace(
/&(lt|gt|quot|#39|amp);/g,
(_, name) => ({ lt: '<', gt: '>', quot: '"', '#39': "'", amp: '&' })[name],
);
// The code header's language label is hidden (Markdown.svelte).
const visible = (html) =>
decode(
html
.replace(/
.*?<\/div>/g, '')
.replace(/<[^>]*>/g, ''),
);
// What Words and the hooks in markdown.ts make; anything else came from the text.
const TAGS = new Set(
'p h1 h2 h3 h4 h5 h6 em strong del code pre span div a ul ol li input table thead tbody tr th td blockquote hr br sup section button svg g text rect path line polyline polygon'.split(
' ',
),
);
const ATTRIBUTES = new Set(
'data-markdown data-incomplete data-markdown-incomplete data-streaming data-language data-code data-meta data-code-action data-footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx class id href target rel type checked disabled readonly start style dir aria-label aria-hidden role xmlns width height viewbox fill color font-family font-size font-style font-weight x y x1 y1 x2 y2 d points stroke stroke-width transform'.split(
' ',
),
);
function markup(html) {
const problems = [];
for (const [, name, attributes] of html.matchAll(
/<([A-Za-z][\w-]*)([^>]*)>/g,
)) {
if (!TAGS.has(name.toLowerCase())) problems.push(`<${name}>`);
for (const [, attribute, value = ''] of attributes.matchAll(
/([^\s=]+)(?:="([^"]*)")?/g,
)) {
if (!ATTRIBUTES.has(attribute.toLowerCase()))
problems.push(`${name} ${attribute}`);
if (attribute === 'href' && !/^(?:https?:|mailto:|#)/.test(decode(value)))
problems.push(`href ${value}`);
}
}
return problems;
}
// Pieces models write: prose, tags in and out of code and maths, fences and
// both maths delimiters. No brackets or colons, so no link or autolink takes
// a `<` into an address; single spaces, so nothing turns into indented code;
// and a fence ends its line, since its info string is never shown.
const piece = fc.constantFrom(
'word',
'Vec
',
'',
'',
'bold',
'',
'',
'',
'

',
'
',
'',
'x`',
'$',
'$$',
'$x ',
'# ',
'| a | b |',
'|---|---|',
'**',
'_',
'1. ',
' ',
'\n',
'\n\n',
);
const markdown = fc
.array(piece, { maxLength: 40 })
.map((pieces) => pieces.join(''))
.filter((text) => !/^[\s>\d.*+-]*(?:`{3,}|~{3,})[^\n]*',
'www.a.example',
'me@a.example',
'[x][r]',
'\n\n[r]: data:text/html,hi\n',
'note[^1]',
'\n\n[^1]: the note\n',
),
),
{ maxLength: 30 },
)
.map((pieces) => pieces.join(''));
test('rendered text holds only markup Words makes, safe links and no images', () => {
check(
fc.property(linked, fc.boolean(), (text, streaming) => {
const html = render(text, streaming);
assert.deepEqual(markup(html), []);
for (const [link] of html.matchAll(/]*href="(?!#)[^>]*>/g))
assert.match(link, /target="_blank" rel="noopener noreferrer"/);
}),
300,
);
});
test('every tag-shaped character a model wrote still shows', () => {
check(
fc.property(markdown, (text) => {
const count = (value) => value.split('<').length - 1;
assert.equal(count(visible(render(text))), count(text), render(text));
}),
300,
);
});
test('a reply prepared delta by delta ends as the whole reply prepared at once', () => {
check(
fc.property(
markdown,
fc.array(fc.integer({ min: 1, max: 40 }), {
minLength: 1,
maxLength: 20,
}),
(text, steps) => {
const prepare = preparer();
for (
let at = 0, step = 0;
at < text.length;
at += steps[step++ % steps.length]
)
prepare(text.slice(0, at), true);
assert.equal(words(prepare(text, false), text), render(text));
},
),
);
});
// Documents of blocks separated by blank lines, some of them lists and fences.
const block = fc.oneof(
fc.constantFrom(
'a paragraph\nthat wraps',
'# heading',
'> a quote',
'| a | b |\n|---|---|\n| 1 | 2 |',
'$$\nx^2\n$$',
'see [the docs][d]',
),
fc
.integer({ min: 1, max: 3 })
.map((n) => Array.from({ length: n }, (_, i) => `- item ${i}`).join('\n')),
fc
.integer({ min: 1, max: 3 })
.map(
(n) =>
'```\n' +
Array.from({ length: n }, () => 'code\n\nmore').join('\n') +
'\n```',
),
);
const document = fc
.array(block, { minLength: 1, maxLength: 8 })
.map((blocks) => blocks.join('\n\n') + '\n\n[d]: https://example.com\n');
test('a document split into blocks renders as the whole document does', () => {
check(
fc.property(document, (text) => {
const blocks = documentHtml(text, new Set(), 't-');
const unwrapped = blocks.replace(
/|<\/div>(?=
m[1])
.map((m) => `${m[2]}-${m[3]}`);
assert.deepEqual(marked(1), ['1-1']);
assert.deepEqual(marked(3), ['3-3']);
assert.deepEqual(marked(6), ['5-6']);
assert.deepEqual(marked(10), ['8-12']);
assert.deepEqual(marked(2), []);
});