@writedocs/generator 0.20.0 â 0.21.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/bin/writedocs.js +23 -7
- package/package.json +1 -1
- package/src/cli/convert.js +120 -15
- package/src/lib/readme-convert.js +325 -0
- package/src/lib/readme-fetch.js +336 -0
- package/src/lib/readme-html.js +201 -0
- package/src/lib/readme-mdx.js +569 -0
- package/src/lib/readme-recipes.js +135 -0
- package/src/pages/[...slug].astro +60 -1
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
// Turns the body of a ReadMe page - its raw source, ReadMe's own flavor of
|
|
2
|
+
// MDX - into writedocs MDX. Used by lib/readme-convert.js for every guide,
|
|
3
|
+
// reference and recipe page.
|
|
4
|
+
//
|
|
5
|
+
// The body is split into fenced code blocks, <HTMLBlock>s, and the text
|
|
6
|
+
// between them; only the text is rewritten, so nothing inside a code block
|
|
7
|
+
// changes. What changes:
|
|
8
|
+
//
|
|
9
|
+
// - Callouts: `<Callout icon="đ" theme="info">` with a leading `### Title`,
|
|
10
|
+
// and the blockquote form `> đ Title`, become `<Callout type title>`.
|
|
11
|
+
// - ReadMe components: `<Cards columns>`/`<Card>` -> `<CardGroup cols>`/
|
|
12
|
+
// `<Card>` (Font Awesome `fa-` icon names lose the prefix), `<Image>` ->
|
|
13
|
+
// a Markdown image, or `<Image>`/`<Frame>` for a width or a caption,
|
|
14
|
+
// `<TutorialTile>`/`<Recipe>` -> a `<Card>` to the recipe, `<Embed>` -> a
|
|
15
|
+
// `<Card>` to the URL, `<Glossary>`/`<<glossary:term>>` -> `<Hint>`,
|
|
16
|
+
// `<Anchor>` -> a link, `<Table>`/`<Tr>`/... -> HTML table elements, and
|
|
17
|
+
// `<HTMLBlock>` -> the HTML written as JSX (lib/readme-html.js).
|
|
18
|
+
// - Links: `doc:slug`, `ref:slug`, `recipe:slug`, `changelog:slug`,
|
|
19
|
+
// `page:slug` and absolute links to the site itself (with or without a
|
|
20
|
+
// `/v1.0` version prefix) become root paths - in Markdown links and in
|
|
21
|
+
// href/src attributes.
|
|
22
|
+
// - Images on files.readme.io are pointed at their local copies (the
|
|
23
|
+
// caller decides the path and downloads them).
|
|
24
|
+
// - Code: adjacent fences (no blank line between them, ReadMe's code tabs)
|
|
25
|
+
// go in a `<CodeGroup>`; language names ReadMe accepts that the
|
|
26
|
+
// highlighter doesn't (`curl`, `node`, `sh`, ...) are mapped.
|
|
27
|
+
// - Raw HTML in the text: `class` -> `className`, `style` strings -> style
|
|
28
|
+
// objects, void elements self-closed, `<!-- -->` -> `{/* */}`; a `<`
|
|
29
|
+
// that doesn't start a known element or component (`<YOUR_API_KEY>`,
|
|
30
|
+
// `a < b`) is escaped, and `<https://...>` autolinks become links - MDX
|
|
31
|
+
// reads all of these as JSX.
|
|
32
|
+
// - `<<variable>>` -> `[[variable]]`, writedocs' variable syntax.
|
|
33
|
+
//
|
|
34
|
+
// Inline code is left alone everywhere.
|
|
35
|
+
|
|
36
|
+
import { htmlToMdx, styleToJsx, mdxJsString } from './readme-html.js';
|
|
37
|
+
import { BUILTIN_COMPONENT_NAMES } from './mdx-inject-builtins.js';
|
|
38
|
+
|
|
39
|
+
const LANG_ALIASES = {
|
|
40
|
+
curl: 'bash', sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',
|
|
41
|
+
node: 'javascript', nodejs: 'javascript', js: 'javascript', jsx: 'jsx',
|
|
42
|
+
ts: 'typescript', py: 'python', rb: 'ruby', 'c#': 'csharp', cs: 'csharp', 'objective-c': 'objc',
|
|
43
|
+
kt: 'kotlin', yml: 'yaml', plaintext: 'text', txt: 'text', http: 'http',
|
|
44
|
+
};
|
|
45
|
+
const LANG_LABELS = {
|
|
46
|
+
curl: 'cURL', bash: 'Bash', sh: 'Shell', shell: 'Shell', node: 'Node', nodejs: 'Node', javascript: 'JavaScript', js: 'JavaScript',
|
|
47
|
+
typescript: 'TypeScript', ts: 'TypeScript', python: 'Python', py: 'Python', ruby: 'Ruby', rb: 'Ruby', php: 'PHP', java: 'Java',
|
|
48
|
+
csharp: 'C#', 'c#': 'C#', cs: 'C#', go: 'Go', swift: 'Swift', kotlin: 'Kotlin', json: 'JSON', xml: 'XML', html: 'HTML',
|
|
49
|
+
yaml: 'YAML', text: 'Text', http: 'HTTP', sql: 'SQL', powershell: 'PowerShell', objc: 'Objective-C',
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Callout types by ReadMe theme, and by the emoji ReadMe puts first.
|
|
53
|
+
const THEME_TYPES = { info: 'info', okay: 'check', success: 'check', warn: 'warning', warning: 'warning', error: 'danger', danger: 'danger', default: 'note' };
|
|
54
|
+
const EMOJI_TYPES = [
|
|
55
|
+
['đ', 'info'], ['âšī¸', 'info'], ['đ', 'check'], ['â
', 'check'], ['đ§', 'warning'], ['â ī¸', 'warning'],
|
|
56
|
+
['âī¸', 'danger'], ['â', 'danger'], ['đ', 'danger'], ['đ', 'note'], ['đĄ', 'tip'],
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
// HTML elements a page may use as they are; any other lower-case `<name>`
|
|
60
|
+
// in the text is taken for a placeholder and escaped.
|
|
61
|
+
const HTML_ELEMENTS = new Set(`a abbr address area article aside audio b bdi bdo blockquote br button canvas caption cite code col
|
|
62
|
+
colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6
|
|
63
|
+
header hgroup hr i iframe img input ins kbd label legend li main map mark menu meter nav noscript object ol optgroup option
|
|
64
|
+
output p picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup svg
|
|
65
|
+
table tbody td template textarea tfoot th thead time tr track u ul var video wbr path g rect circle line polyline polygon
|
|
66
|
+
ellipse defs use symbol clipPath mask filter linearGradient radialGradient stop text tspan center font`.split(/\s+/));
|
|
67
|
+
const VOID = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'source', 'track', 'wbr']);
|
|
68
|
+
// Upper-case table components ReadMe's editor writes for a table with
|
|
69
|
+
// formatting - the plain HTML elements render the same.
|
|
70
|
+
const TABLE_COMPONENTS = { Table: 'table', Thead: 'thead', Tbody: 'tbody', Tr: 'tr', Th: 'th', Td: 'td' };
|
|
71
|
+
// Components this conversion writes, and the ones writedocs has.
|
|
72
|
+
const KNOWN_COMPONENTS = new Set([...BUILTIN_COMPONENT_NAMES, 'Fragment']);
|
|
73
|
+
|
|
74
|
+
/** Parses JSX-ish attributes: name="v", name='v', name={v}, bare name. */
|
|
75
|
+
export function parseAttributes(text) {
|
|
76
|
+
const attrs = {};
|
|
77
|
+
const re = /([A-Za-z_:][\w:.-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}|([^\s"'>/{}]+)))?/g;
|
|
78
|
+
let m;
|
|
79
|
+
while ((m = re.exec(text))) {
|
|
80
|
+
const [, name, dq, sq, expr, bare] = m;
|
|
81
|
+
if (dq !== undefined) attrs[name] = dq;
|
|
82
|
+
else if (sq !== undefined) attrs[name] = sq;
|
|
83
|
+
else if (expr !== undefined) attrs[name] = { expression: expr.trim() };
|
|
84
|
+
else if (bare !== undefined) attrs[name] = bare;
|
|
85
|
+
else attrs[name] = true;
|
|
86
|
+
}
|
|
87
|
+
return attrs;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** An attribute's plain value: strings as they are, `{3}`/`{"x"}` unwrapped. */
|
|
91
|
+
function plain(value) {
|
|
92
|
+
if (value === undefined || value === null || value === true) return undefined;
|
|
93
|
+
if (typeof value === 'string') return value;
|
|
94
|
+
const e = value.expression;
|
|
95
|
+
if (/^-?\d+(\.\d+)?$/.test(e)) return e;
|
|
96
|
+
const q = /^(["'`])([\s\S]*)\1$/.exec(e);
|
|
97
|
+
return q ? q[2] : undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `name="value"`, or `name={"..."}` when the value needs escaping. */
|
|
101
|
+
export function jsxAttr(name, value) {
|
|
102
|
+
const v = String(value);
|
|
103
|
+
return /^[^"\\{}<>\n\r&]*$/.test(v) ? `${name}="${v}"` : `${name}={${mdxJsString(v)}}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** `fa-solid fa-arrow-right` / `fa-arrow-right` -> `arrow-right`; an emoji
|
|
107
|
+
* or another library's name -> undefined (writedocs looks bare names up
|
|
108
|
+
* in Lucide, then Font Awesome). */
|
|
109
|
+
export function convertIcon(icon) {
|
|
110
|
+
if (typeof icon !== 'string') return undefined;
|
|
111
|
+
const names = icon.split(/\s+/).filter((t) => /^fa-[a-z0-9-]+$/.test(t) && !/^fa-(solid|regular|light|thin|duotone|brands|sharp|kit)$/.test(t));
|
|
112
|
+
if (names.length) return names[names.length - 1].slice(3);
|
|
113
|
+
// Already a bare icon name ("book-open"); an emoji isn't one.
|
|
114
|
+
return /^[a-z0-9]+(-[a-z0-9]+)*$/.test(icon.trim()) ? icon.trim() : undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** ReadMe's link schemes and the site's own absolute URLs, as root paths. */
|
|
118
|
+
export function makeLinkRewriter({ baseUrl, subdomain } = {}) {
|
|
119
|
+
const origins = new Set();
|
|
120
|
+
if (baseUrl) origins.add(new URL(baseUrl).origin);
|
|
121
|
+
if (subdomain) origins.add(`https://${subdomain}.readme.io`);
|
|
122
|
+
const SCHEMES = { doc: '/docs/', ref: '/reference/', recipe: '/recipes/', recipes: '/recipes/', changelog: '/changelog/', page: '/page/' };
|
|
123
|
+
const stripVersion = (p) => p.replace(/^\/v\d+(?:\.\d+)*(?:-[\w-]+)?(?=\/)/, '');
|
|
124
|
+
// `from` is the id of the page the link is on ("docs/webhooks"). A
|
|
125
|
+
// relative link resolves the way it did on ReadMe, whose page addresses
|
|
126
|
+
// have no trailing slash: `events#x` on /docs/webhooks is /docs/events#x.
|
|
127
|
+
// writedocs' addresses end in a slash, so it's written as a root path.
|
|
128
|
+
return (url, from) => {
|
|
129
|
+
if (typeof url !== 'string') return url;
|
|
130
|
+
const s = url.trim();
|
|
131
|
+
if (from && s && !/^([a-z][a-z0-9+.-]*:|\/|#|\?|\{)/i.test(s)) {
|
|
132
|
+
try {
|
|
133
|
+
const u = new URL(s, `https://readme.invalid/${from}`);
|
|
134
|
+
return `${u.pathname}${u.search}${u.hash}`;
|
|
135
|
+
} catch {
|
|
136
|
+
return url;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const scheme = /^(doc|ref|recipes?|changelog|page):(?!\/\/)([^#?\s]*)([?#].*)?$/i.exec(s);
|
|
140
|
+
if (scheme) return `${SCHEMES[scheme[1].toLowerCase()]}${scheme[2]}${scheme[3] ?? ''}`;
|
|
141
|
+
if (/^https?:\/\//i.test(s)) {
|
|
142
|
+
let u;
|
|
143
|
+
try {
|
|
144
|
+
u = new URL(s);
|
|
145
|
+
} catch {
|
|
146
|
+
return url;
|
|
147
|
+
}
|
|
148
|
+
if (!origins.has(u.origin)) return url;
|
|
149
|
+
const p = stripVersion(u.pathname);
|
|
150
|
+
return `${p === '' ? '/' : p}${u.search}${u.hash}`;
|
|
151
|
+
}
|
|
152
|
+
if (s.startsWith('/')) return stripVersion(s);
|
|
153
|
+
return url;
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---------------------------------------------------------------------
|
|
158
|
+
// Splitting the body
|
|
159
|
+
// ---------------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
/** The body as segments: { kind: 'text' | 'code' | 'html', lines | text }.
|
|
162
|
+
* A code segment is one fence; an html segment is an <HTMLBlock>'s HTML. */
|
|
163
|
+
export function splitBody(body) {
|
|
164
|
+
const lines = String(body ?? '').replace(/\r\n?/g, '\n').split('\n');
|
|
165
|
+
const segments = [];
|
|
166
|
+
let text = [];
|
|
167
|
+
const flushText = () => {
|
|
168
|
+
if (text.length) segments.push({ kind: 'text', lines: text });
|
|
169
|
+
text = [];
|
|
170
|
+
};
|
|
171
|
+
for (let i = 0; i < lines.length; i++) {
|
|
172
|
+
const line = lines[i];
|
|
173
|
+
const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line);
|
|
174
|
+
if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
|
|
175
|
+
const [, indent, marks, info] = fence;
|
|
176
|
+
const close = new RegExp(`^\\s*${marks[0] === '`' ? '`' : '~'}{${marks.length},}\\s*$`);
|
|
177
|
+
const body = [];
|
|
178
|
+
let j = i + 1;
|
|
179
|
+
while (j < lines.length && !close.test(lines[j])) body.push(lines[j++]);
|
|
180
|
+
flushText();
|
|
181
|
+
segments.push({ kind: 'code', indent, marks, info: info.trim(), body });
|
|
182
|
+
i = j; // the closing fence (or the end)
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const start = line.indexOf('<HTMLBlock');
|
|
186
|
+
if (start !== -1) {
|
|
187
|
+
let j = i;
|
|
188
|
+
let joined = line.slice(start);
|
|
189
|
+
while (!joined.includes('</HTMLBlock>') && j + 1 < lines.length) joined += `\n${lines[++j]}`;
|
|
190
|
+
const end = joined.indexOf('</HTMLBlock>');
|
|
191
|
+
if (end !== -1) {
|
|
192
|
+
if (line.slice(0, start).trim()) text.push(line.slice(0, start));
|
|
193
|
+
flushText();
|
|
194
|
+
const inner = joined.slice(joined.indexOf('>') + 1, end);
|
|
195
|
+
const tpl = /^\s*\{\s*`([\s\S]*)`\s*\}\s*$/.exec(inner);
|
|
196
|
+
segments.push({ kind: 'html', html: tpl ? tpl[1].replace(/\\`/g, '`').replace(/\\\$\{/g, '${') : inner });
|
|
197
|
+
const rest = joined.slice(end + '</HTMLBlock>'.length);
|
|
198
|
+
if (rest.trim()) text.push(rest);
|
|
199
|
+
i = j;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
text.push(line);
|
|
204
|
+
}
|
|
205
|
+
flushText();
|
|
206
|
+
return segments;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------
|
|
210
|
+
// Code
|
|
211
|
+
// ---------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
/** A fence's info string with ReadMe's language names mapped, and - in a
|
|
214
|
+
* code group, where the title is the tab's label - a title when it has none. */
|
|
215
|
+
export function normalizeFenceInfo(info, { inGroup = false } = {}) {
|
|
216
|
+
if (!info) return '';
|
|
217
|
+
const [lang, ...rest] = info.split(/\s+/);
|
|
218
|
+
const lower = lang.toLowerCase();
|
|
219
|
+
const mapped = LANG_ALIASES[lower] ?? lang;
|
|
220
|
+
let title = rest.join(' ').trim();
|
|
221
|
+
if (!title && inGroup) title = LANG_LABELS[lower] ?? lang;
|
|
222
|
+
return title ? `${mapped} ${title}` : mapped;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function renderCode(seg, inGroup) {
|
|
226
|
+
const info = normalizeFenceInfo(seg.info, { inGroup });
|
|
227
|
+
return [`${seg.indent}${seg.marks}${info}`, ...seg.body, `${seg.indent}${seg.marks}`];
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---------------------------------------------------------------------
|
|
231
|
+
// Text
|
|
232
|
+
// ---------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
function protectInlineCode(text) {
|
|
235
|
+
const saved = [];
|
|
236
|
+
// One line at most: a span reaching across lines is far more often two
|
|
237
|
+
// stray backticks (or a fence) than real inline code.
|
|
238
|
+
const out = text.replace(/(`+)(?!`)([^\n]*?[^`\n])\1(?!`)/g, (m) => {
|
|
239
|
+
saved.push(m);
|
|
240
|
+
return `\u0000${saved.length - 1}\u0000`;
|
|
241
|
+
});
|
|
242
|
+
return { text: out, restore: (s) => s.replace(/\u0000(\d+)\u0000/g, (_, i) => saved[Number(i)]) };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function stripInlineMarkup(s) {
|
|
246
|
+
return s.replace(/\*\*([^*]+)\*\*/g, '$1').replace(/__([^_]+)__/g, '$1').replace(/^\*([^*]+)\*$/, '$1').trim();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function calloutOpen(type, title) {
|
|
250
|
+
return title ? `<Callout type="${type}" ${jsxAttr('title', title)}>` : `<Callout type="${type}">`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** `<Callout icon theme>` + a leading heading -> `<Callout type title>`. */
|
|
254
|
+
function convertCalloutTags(text, unwrap) {
|
|
255
|
+
return text.replace(/<Callout\b([^>]*)>([ \t]*\n(?:[ \t]*\n)*([ \t]*)(#{1,6})[ \t]+([^\n]+)\n(?:[ \t]*\n)*)?/g, (m, attrs, headingBlock, indent, hashes, heading) => {
|
|
256
|
+
const a = parseAttributes(attrs);
|
|
257
|
+
// Already writedocs' form - a blockquote callout converted earlier.
|
|
258
|
+
if (a.type !== undefined) return m;
|
|
259
|
+
const theme = plain(a.theme);
|
|
260
|
+
const icon = plain(a.icon);
|
|
261
|
+
let type = theme ? THEME_TYPES[theme] : undefined;
|
|
262
|
+
if (!type && icon) type = EMOJI_TYPES.find(([e]) => icon.startsWith(e))?.[1];
|
|
263
|
+
type ??= 'note';
|
|
264
|
+
const title = heading ? stripInlineMarkup(unwrap(heading.replace(/\s*#+\s*$/, ''))) : undefined;
|
|
265
|
+
return calloutOpen(type, title) + (headingBlock ? '\n' : '');
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** `> đ Title` + `> body` lines -> a Callout. Runs on the raw body, before
|
|
270
|
+
* it's split, so a code fence inside the quote (`> ```js`) comes out as a
|
|
271
|
+
* real fence; lines inside a fence outside any quote are left alone. */
|
|
272
|
+
export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^`]*)`/g, '$1')) {
|
|
273
|
+
const out = [];
|
|
274
|
+
let fence = null;
|
|
275
|
+
for (let i = 0; i < lines.length; i++) {
|
|
276
|
+
const f = /^\s*(`{3,}|~{3,})/.exec(lines[i]);
|
|
277
|
+
if (f && (!fence || (f[1][0] === fence[0] && f[1].length >= fence.length))) fence = fence ? null : f[1];
|
|
278
|
+
const m = !fence && !f && /^(\s*)>\s?(.*)$/.exec(lines[i]);
|
|
279
|
+
const emoji = m && EMOJI_TYPES.find(([e]) => m[2].startsWith(e));
|
|
280
|
+
if (!emoji) {
|
|
281
|
+
out.push(lines[i]);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const indent = m[1];
|
|
285
|
+
const title = stripInlineMarkup(unwrap(m[2].slice(emoji[0].length).replace(/^\uFE0F/, '')));
|
|
286
|
+
const body = [];
|
|
287
|
+
let j = i + 1;
|
|
288
|
+
while (j < lines.length) {
|
|
289
|
+
const b = new RegExp(`^${indent}>\\s?(.*)$`).exec(lines[j]);
|
|
290
|
+
if (!b) break;
|
|
291
|
+
body.push(b[1]);
|
|
292
|
+
j++;
|
|
293
|
+
}
|
|
294
|
+
while (body.length && !body[0].trim()) body.shift();
|
|
295
|
+
while (body.length && !body[body.length - 1].trim()) body.pop();
|
|
296
|
+
out.push(`${indent}${calloutOpen(emoji[1], title || undefined)}`);
|
|
297
|
+
for (const b of body) out.push(b.trim() ? `${indent} ${b}` : '');
|
|
298
|
+
out.push(`${indent}</Callout>`);
|
|
299
|
+
i = j - 1;
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The class every converted HTML block is wrapped in - see READMEHTML_CSS. */
|
|
305
|
+
export const README_HTML_CLASS = 'readme-html';
|
|
306
|
+
|
|
307
|
+
/** Hand-written HTML from ReadMe sets its own colors on a container and
|
|
308
|
+
* lets the headings inside inherit them; writedocs' article heading color
|
|
309
|
+
* (a light one in dark mode) would win over that inheritance, leaving
|
|
310
|
+
* light headings on the HTML's own white cards. Written to the project as
|
|
311
|
+
* readme-html.css when a page has converted HTML. */
|
|
312
|
+
export const README_HTML_CSS = `/* Written by writedocs convert --readme. The HTML converted from ReadMe
|
|
313
|
+
(its HTMLBlocks and landing page) sets its own colors - its headings
|
|
314
|
+
inherit them, instead of the site's heading color. */
|
|
315
|
+
.${README_HTML_CLASS} :where(h1, h2, h3, h4, h5, h6, strong, b) {
|
|
316
|
+
color: inherit;
|
|
317
|
+
}
|
|
318
|
+
`;
|
|
319
|
+
|
|
320
|
+
export function wrapHtml(mdx) {
|
|
321
|
+
return `<div className="${README_HTML_CLASS}">\n${mdx}\n</div>`;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Converts a ReadMe page body.
|
|
326
|
+
*
|
|
327
|
+
* @param {string} body
|
|
328
|
+
* @param {object} ctx
|
|
329
|
+
* @param {(url: string) => string} ctx.rewriteLink
|
|
330
|
+
* @param {(url: string) => string} ctx.localImage the local path for an image URL (or the URL, to keep it)
|
|
331
|
+
* @param {Set<string>} [ctx.recipes] recipe slugs that exist
|
|
332
|
+
* @param {Map<string, string>} [ctx.glossary] term (lower case) -> definition
|
|
333
|
+
* @param {(key: string, message: string) => void} [ctx.note]
|
|
334
|
+
* @returns {string}
|
|
335
|
+
*/
|
|
336
|
+
export function convertReadmeBody(body, ctx) {
|
|
337
|
+
const note = ctx.note ?? (() => {});
|
|
338
|
+
const glossary = ctx.glossary ?? new Map();
|
|
339
|
+
const recipes = ctx.recipes ?? new Set();
|
|
340
|
+
let source = String(body ?? '').replace(/\r\n?/g, '\n');
|
|
341
|
+
// ReadMe's older [block:type]{json}[/block] syntax isn't converted: each
|
|
342
|
+
// block goes in a code fence, so the page builds (its JSON is not MDX)
|
|
343
|
+
// and the author sees what to rewrite.
|
|
344
|
+
if (/^\[block:[\w-]+\]/m.test(source)) {
|
|
345
|
+
note('legacy-blocks', "The page uses ReadMe's older [block:...] syntax, which isn't converted - each block is shown as a code block. Rewrite them with components.");
|
|
346
|
+
source = source.replace(/^\[block:([\w-]+)\]\n([\s\S]*?)\n\[\/block\]$/gm, (m, type, json) => `\`\`\`json block:${type}\n${json}\n\`\`\``);
|
|
347
|
+
}
|
|
348
|
+
const lines = source.split('\n');
|
|
349
|
+
const segments = splitBody(convertBlockquoteCallouts(lines).join('\n'));
|
|
350
|
+
const out = [];
|
|
351
|
+
|
|
352
|
+
for (let s = 0; s < segments.length; s++) {
|
|
353
|
+
const seg = segments[s];
|
|
354
|
+
if (seg.kind === 'code') {
|
|
355
|
+
// Fences with nothing between them are ReadMe code tabs.
|
|
356
|
+
const group = [seg];
|
|
357
|
+
while (segments[s + 1]?.kind === 'code') group.push(segments[++s]);
|
|
358
|
+
if (group.length === 1) out.push(...renderCode(seg, false));
|
|
359
|
+
else {
|
|
360
|
+
const indent = group[0].indent;
|
|
361
|
+
out.push(`${indent}<CodeGroup>`);
|
|
362
|
+
for (const g of group) out.push(...renderCode(g, true));
|
|
363
|
+
out.push(`${indent}</CodeGroup>`);
|
|
364
|
+
}
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (seg.kind === 'html') {
|
|
368
|
+
const mdx = htmlToMdx(seg.html, {
|
|
369
|
+
rewriteUrl: (url, name) => (name === 'src' ? ctx.localImage(url) : ctx.rewriteLink(url)),
|
|
370
|
+
});
|
|
371
|
+
if (mdx) out.push('', wrapHtml(mdx), '');
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
out.push(convertText(seg.lines.join('\n'), { ...ctx, note, glossary, recipes }));
|
|
375
|
+
}
|
|
376
|
+
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function convertText(source, ctx) {
|
|
380
|
+
const { text: protectedText, restore } = protectInlineCode(source);
|
|
381
|
+
const unwrap = (s) => restore(s).replace(/`([^`]*)`/g, '$1');
|
|
382
|
+
let t = protectedText;
|
|
383
|
+
|
|
384
|
+
t = convertCalloutTags(t, unwrap);
|
|
385
|
+
|
|
386
|
+
// <TutorialTile> / <tutorial-tile> / <Recipe>: a card to the recipe.
|
|
387
|
+
t = t.replace(/<(TutorialTile|tutorial-tile|Recipe)\b((?:[^>"']|"[^"]*"|'[^']*')*?)(?:\/>|>\s*<\/\1>)/g, (m, name, attrs) => {
|
|
388
|
+
const a = parseAttributes(attrs);
|
|
389
|
+
const slug = plain(a.slug);
|
|
390
|
+
const title = plain(a.title) ?? slug;
|
|
391
|
+
if (!slug || !ctx.recipes.has(slug)) {
|
|
392
|
+
ctx.note('missing-recipe', "A recipe card (TutorialTile) links to a recipe that isn't on the site any more - the card is left out.");
|
|
393
|
+
return '';
|
|
394
|
+
}
|
|
395
|
+
return `<Card ${jsxAttr('title', title)} icon="book-open" href="/recipes/${slug}" />`;
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
// <Cards columns> / <Card>.
|
|
399
|
+
t = t.replace(/<Cards\b([^>]*)>/g, (m, attrs) => {
|
|
400
|
+
const cols = plain(parseAttributes(attrs).columns);
|
|
401
|
+
return /^\d+$/.test(cols ?? '') ? `<CardGroup cols={${cols}}>` : '<CardGroup>';
|
|
402
|
+
});
|
|
403
|
+
t = t.replace(/<\/Cards>/g, '</CardGroup>');
|
|
404
|
+
t = t.replace(/<Card\b([^>]*?)(\/?)>/g, (m, attrs, selfClose) => {
|
|
405
|
+
const a = parseAttributes(attrs);
|
|
406
|
+
const parts = [];
|
|
407
|
+
const title = plain(a.title);
|
|
408
|
+
if (title !== undefined) parts.push(jsxAttr('title', unwrap(title)));
|
|
409
|
+
const icon = convertIcon(plain(a.icon));
|
|
410
|
+
if (icon) parts.push(jsxAttr('icon', icon));
|
|
411
|
+
const href = plain(a.href);
|
|
412
|
+
if (href) parts.push(jsxAttr('href', ctx.rewriteLink(href)));
|
|
413
|
+
return `<Card${parts.length ? ` ${parts.join(' ')}` : ''}${selfClose ? ' />' : '>'}`;
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
// <Image>.
|
|
417
|
+
const image = (attrs, child) => {
|
|
418
|
+
const a = parseAttributes(attrs);
|
|
419
|
+
const src = plain(a.src);
|
|
420
|
+
if (!src) return '';
|
|
421
|
+
const local = ctx.localImage(src);
|
|
422
|
+
const alt = plain(a.alt) ?? plain(a.title) ?? '';
|
|
423
|
+
const caption = (plain(a.caption) ?? child ?? '').trim();
|
|
424
|
+
const width = plain(a.width);
|
|
425
|
+
const size = width && width !== 'smart' && width !== 'auto' ? (/^\d+$/.test(width) ? `${width}px` : width) : undefined;
|
|
426
|
+
if (size || caption) {
|
|
427
|
+
const parts = [jsxAttr('src', local)];
|
|
428
|
+
if (size) parts.push(jsxAttr('size', size));
|
|
429
|
+
if (alt) parts.push(jsxAttr('alt', alt));
|
|
430
|
+
if (caption) parts.push(jsxAttr('caption', unwrap(caption)));
|
|
431
|
+
return `<Image ${parts.join(' ')} />`;
|
|
432
|
+
}
|
|
433
|
+
return `![${alt.replace(/[[\]]/g, '')}](${local})`;
|
|
434
|
+
};
|
|
435
|
+
t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)\/>/g, (m, attrs) => image(attrs));
|
|
436
|
+
t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)>([\s\S]*?)<\/Image>/g, (m, attrs, child) => image(attrs, child));
|
|
437
|
+
|
|
438
|
+
// <Embed>: a card to what it embedded.
|
|
439
|
+
t = t.replace(/<Embed\b([\s\S]*?)\/>/g, (m, attrs) => {
|
|
440
|
+
const a = parseAttributes(attrs);
|
|
441
|
+
const url = plain(a.url) ?? plain(a.href);
|
|
442
|
+
if (!url) return '';
|
|
443
|
+
ctx.note('embed', 'An <Embed> became a card linking to what it embedded.');
|
|
444
|
+
return `<Card ${jsxAttr('title', plain(a.title) || url)} icon="external-link" href="${url}" />`;
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
// Glossary terms.
|
|
448
|
+
const tooltip = (term) => {
|
|
449
|
+
const def = ctx.glossary.get(term.trim().toLowerCase());
|
|
450
|
+
if (!def) {
|
|
451
|
+
ctx.note('glossary', `The glossary term "${term}" isn't in the project's glossary - left as plain text.`);
|
|
452
|
+
return term;
|
|
453
|
+
}
|
|
454
|
+
return `<Hint ${jsxAttr('tip', def)}>${term}</Hint>`;
|
|
455
|
+
};
|
|
456
|
+
t = t.replace(/<<glossary:([^>]+)>>/g, (m, term) => tooltip(term));
|
|
457
|
+
t = t.replace(/<Glossary>([\s\S]*?)<\/Glossary>/g, (m, term) => tooltip(term));
|
|
458
|
+
t = t.replace(/<<([A-Za-z_][\w.-]*)>>/g, (m, name) => `[[${name}]]`);
|
|
459
|
+
|
|
460
|
+
// <Anchor label target href>.
|
|
461
|
+
t = t.replace(/<Anchor\b([^>]*)>([\s\S]*?)<\/Anchor>/g, (m, attrs, label) => {
|
|
462
|
+
const href = plain(parseAttributes(attrs).href);
|
|
463
|
+
return href ? `[${label.trim()}](${ctx.rewriteLink(href)})` : label;
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
// Autolinks MDX would read as JSX.
|
|
467
|
+
t = t.replace(/<((?:https?|mailto):[^\s<>]+)>/g, (m, url) => `[${url}](${ctx.rewriteLink(url)})`);
|
|
468
|
+
|
|
469
|
+
// Markdown links and images.
|
|
470
|
+
t = t.replace(/(!?)\[((?:[^[\]]|\[[^\]]*\])*)\]\(\s*<?([^)\s>]+)>?((?:\s+"[^"]*")?)\s*\)/g, (m, bang, label, url, title) =>
|
|
471
|
+
bang ? `}${title})` : `[${label}](${ctx.rewriteLink(url)}${title})`
|
|
472
|
+
);
|
|
473
|
+
|
|
474
|
+
t = fixRawHtml(t, ctx);
|
|
475
|
+
return restore(t);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Raw HTML and stray `<` in the text, made valid MDX - see the header. */
|
|
479
|
+
function fixRawHtml(text, ctx) {
|
|
480
|
+
let out = '';
|
|
481
|
+
let i = 0;
|
|
482
|
+
while (i < text.length) {
|
|
483
|
+
const lt = text.indexOf('<', i);
|
|
484
|
+
if (lt === -1) {
|
|
485
|
+
out += text.slice(i);
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
488
|
+
out += text.slice(i, lt);
|
|
489
|
+
if (text.startsWith('<!--', lt)) {
|
|
490
|
+
const end = text.indexOf('-->', lt + 4);
|
|
491
|
+
const body = text.slice(lt + 4, end === -1 ? text.length : end).trim().replace(/\*\//g, '* /');
|
|
492
|
+
out += body ? `{/* ${body} */}` : '';
|
|
493
|
+
i = end === -1 ? text.length : end + 3;
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
const tag = /^<(\/?)([A-Za-z][\w.:-]*)/.exec(text.slice(lt));
|
|
497
|
+
const end = tag ? tagEnd(text, lt + tag[0].length) : -1;
|
|
498
|
+
if (!tag || end === -1) {
|
|
499
|
+
out += '<';
|
|
500
|
+
i = lt + 1;
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
const [, closing, rawName] = tag;
|
|
504
|
+
const inner = text.slice(lt + tag[0].length, end); // attributes, and a trailing "/"
|
|
505
|
+
const name = TABLE_COMPONENTS[rawName] ?? rawName;
|
|
506
|
+
if (KNOWN_COMPONENTS.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
|
|
507
|
+
// A component: writedocs' own, or one it will report as unknown.
|
|
508
|
+
out += text.slice(lt, end + 1);
|
|
509
|
+
} else if (HTML_ELEMENTS.has(name) || name.includes('-') && /^[a-z]/.test(name) && /=/.test(inner)) {
|
|
510
|
+
out += closing ? `</${name}>` : htmlOpenTag(name, inner, ctx);
|
|
511
|
+
} else {
|
|
512
|
+
// `<YOUR_API_KEY>`, `<username>`: a placeholder, not an element.
|
|
513
|
+
out += `<${text.slice(lt + 1, end)}>`;
|
|
514
|
+
}
|
|
515
|
+
i = end + 1;
|
|
516
|
+
}
|
|
517
|
+
return out;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** A PascalCase tag that isn't writedocs': kept (the build shows its
|
|
521
|
+
* content and warns) when it's written like a component - self-closed, or
|
|
522
|
+
* closed later. `<YOUR_API_KEY>` or a lone `<Method>` is a placeholder. */
|
|
523
|
+
function isUnknownComponent(name, closing, inner, text, end) {
|
|
524
|
+
if (TABLE_COMPONENTS[name] || !/^[A-Z][A-Za-z0-9]*(\.[A-Z][A-Za-z0-9]*)?$/.test(name) || !/[a-z]/.test(name)) return false;
|
|
525
|
+
if (closing || /\/\s*$/.test(inner)) return true;
|
|
526
|
+
return text.indexOf(`</${name}>`, end) !== -1;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** The index of the `>` that ends a tag, skipping quoted values and {...}. */
|
|
530
|
+
function tagEnd(text, from) {
|
|
531
|
+
let depth = 0;
|
|
532
|
+
let quote = null;
|
|
533
|
+
for (let j = from; j < text.length; j++) {
|
|
534
|
+
const c = text[j];
|
|
535
|
+
if (quote) {
|
|
536
|
+
if (c === quote) quote = null;
|
|
537
|
+
} else if (depth > 0) {
|
|
538
|
+
if (c === '{') depth++;
|
|
539
|
+
else if (c === '}') depth--;
|
|
540
|
+
else if (c === '"' || c === "'" || c === '`') {
|
|
541
|
+
const close = text.indexOf(c, j + 1);
|
|
542
|
+
if (close === -1) return -1;
|
|
543
|
+
j = close;
|
|
544
|
+
}
|
|
545
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
546
|
+
else if (c === '{') depth++;
|
|
547
|
+
else if (c === '>') return j;
|
|
548
|
+
else if (c === '<' || c === '\n' && text[j + 1] === '\n') return -1;
|
|
549
|
+
}
|
|
550
|
+
return -1;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function htmlOpenTag(name, inner, ctx) {
|
|
554
|
+
const selfClosing = /\/\s*$/.test(inner);
|
|
555
|
+
const a = parseAttributes(inner.replace(/\/\s*$/, ''));
|
|
556
|
+
const parts = [];
|
|
557
|
+
for (const [key, value] of Object.entries(a)) {
|
|
558
|
+
if (key === 'align' && typeof value === 'object') continue; // <Table align={[...]}>
|
|
559
|
+
const jsxKey = key === 'class' ? 'className' : key === 'for' ? 'htmlFor' : key;
|
|
560
|
+
if (value === true) parts.push(jsxKey);
|
|
561
|
+
else if (typeof value === 'object') parts.push(`${jsxKey}={${value.expression}}`);
|
|
562
|
+
else if (key === 'style') parts.push(`style=${styleToJsx(value)}`);
|
|
563
|
+
else if (key === 'href') parts.push(jsxAttr(jsxKey, ctx.rewriteLink(value)));
|
|
564
|
+
else if (key === 'src') parts.push(jsxAttr(jsxKey, ctx.localImage(value)));
|
|
565
|
+
else parts.push(jsxAttr(jsxKey, value));
|
|
566
|
+
}
|
|
567
|
+
const attrs = parts.length ? ` ${parts.join(' ')}` : '';
|
|
568
|
+
return VOID.has(name) || selfClosing ? `<${name}${attrs} />` : `<${name}${attrs}>`;
|
|
569
|
+
}
|