main
ply4 git calls32 ms49 KiB2 cachedprotocol v2
669 lines26 KiBRaw
1// GitHub-flavoured markdown for README and .md files: headings, paragraphs with hard breaks, emphasis, strikethrough,
2// inline and fenced code (with a language label), block quotes, nested and task lists, tables with alignment, rules,
3// inline/reference/auto links, and images. Safety model: the source is only ever escaped as text; tags and class names
4// come from fixed sets in safehtml.ts; a link becomes an anchor only when its URL passes classifyHref (or a
5// repository-relative path that the caller resolves to a viewer URL). Raw HTML is shown as text. Images are links, not
6// <img>: the viewer's CSP is img-src 'none', and a README must not make visitors' browsers fetch third-party pixels.
7import { atIndex, captureGroup, mapGet, recordGet, textAt } from '../absent.ts';
8import { find, unwrapOr } from '../option.ts';
9import { anchor, concatHtml, escapeHtml, heading, orderedList, tag, voidTag, type MdClass, type SafeHtml } from './safehtml.ts';
11function chAt(text: string, index: number): string {
12 return unwrapOr(textAt(text, index), '');
15function lineAt(lines: readonly string[], index: number): string {
16 return unwrapOr(atIndex(lines, index), '');
19function group(match: RegExpMatchArray | null, index: number, fallback = ''): string {
20 return unwrapOr(captureGroup(match, index), fallback);
23const NAMED: Record<string, string> = {
24 quot: '"', amp: '&', lt: '<', gt: '>', apos: "'", colon: ':', tab: '\t', newline: '\n',
25};
27function decodeEntities(value: string): string {
28 return value.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]+);/gi, (all, body: string) => {
29 if (body.startsWith('#x') || body.startsWith('#X')) {
30 const cp = Number.parseInt(body.slice(2), 16);
31 if (!Number.isFinite(cp) || cp < 0 || cp > 0x10ffff) return all;
32 return String.fromCodePoint(cp);
33 }
34 if (body.startsWith('#')) {
35 const cp = Number.parseInt(body.slice(1), 10);
36 if (!Number.isFinite(cp) || cp < 0 || cp > 0x10ffff) return all;
37 return String.fromCodePoint(cp);
38 }
39 return unwrapOr(recordGet(NAMED, body.toLowerCase()), all);
40 });
43function obscured(value: string): boolean {
44 // oxlint-disable-next-line no-control-regex -- controls and whitespace are scheme-obfuscation, not a URL
45 if (/[\u0000-\u001f\u007f\s<>"'`\\]/.test(value)) return true;
46 if (/[\u200b-\u200f\u202a-\u202e\ufeff]/.test(value)) return true;
47 if (/%0[0-9a-f]|%1[0-9a-f]|%7f/i.test(value)) return true;
48 return false;
51function schemeOf(value: string): 'http' | 'https' | 'mailto' | 'relative' | 'bad' {
52 if (value.startsWith('//') || value.startsWith('\\') || value.includes('\\')) return 'bad';
53 const colon = value.indexOf(':');
54 if (colon === -1) {
55 if (value.startsWith('#') || value.startsWith('/') || value.startsWith('./') || value.startsWith('../') || /^[A-Za-z0-9]/.test(value)) return 'relative';
56 return 'bad';
57 }
58 const scheme = value.slice(0, colon).toLowerCase();
59 if (!/^[a-z][a-z0-9+.-]*$/.test(scheme)) return 'bad';
60 if (scheme === 'http' || scheme === 'https') {
61 if (!value.slice(colon + 1).startsWith('//')) return 'bad';
62 return scheme;
63 }
64 if (scheme === 'mailto') return 'mailto';
65 return 'bad';
68/** http, https, mailto, or a same-document relative URL. javascript:, data:, vbscript:, and obfuscations are null. */
69export function classifyHref(raw: string): string | null {
70 if (typeof raw !== 'string' || raw.length === 0 || raw.length > 2048) return null;
71 if (obscured(raw)) return null;
72 const decoded = decodeEntities(raw);
73 if (decoded !== raw && (obscured(decoded) || schemeOf(decoded) === 'bad')) return null;
74 const kind = schemeOf(raw);
75 if (kind === 'bad') return null;
76 if (kind === 'http' || kind === 'https') {
77 let url: URL;
78 try { url = new URL(raw); }
79 catch { return null; }
80 if (url.username || url.password) return null;
81 if (url.protocol !== `${kind}:`) return null;
82 }
83 return raw;
87export type MarkdownOptions = {
88 /**
89 * Resolve a repository-relative link (`docs/x.md`, `./a.png`, `../b`) to a viewer URL. The path is already joined
90 * and normalised against the document's directory; null leaves the link as text. `image` asks for raw bytes.
91 */
92 readonly resolve: ((path: string, kind: 'link' | 'image') => string | null) | null;
93 /** The document's directory inside the repository. Empty for the root. */
94 readonly base: string;
95};
97const ROOT_OPTIONS: MarkdownOptions = { resolve: null, base: '' };
99type Ctx = { opts: MarkdownOptions; refs: Map<string, string>; slugs: Map<string, number> };
101const MAX_DEPTH = 8;
102const PUNCT = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;
104// ── links ────────────────────────────────────────────────────────────────────────────────────────────────────────
106function joinRepoPath(base: string, rel: string): string | null {
107 const parts = base ? base.split('/') : [];
108 for (const seg of rel.split('/')) {
109 if (seg === '' || seg === '.') continue;
110 if (seg === '..') { if (!parts.length) return null; parts.pop(); continue; }
111 parts.push(seg);
112 }
113 return parts.join('/');
116function hrefFor(raw: string, kind: 'link' | 'image', ctx: Ctx): string | null {
117 const dest = raw.trim();
118 const safe = classifyHref(dest);
119 if (!safe) return null;
120 const relative = !dest.startsWith('#') && !dest.startsWith('/') && !/^[a-z][a-z0-9+.-]*:/i.test(dest);
121 if (!relative || ctx.opts.resolve === null) return safe;
122 const hash = dest.indexOf('#');
123 const pathPart = unwrapOr(atIndex((hash === -1 ? dest : dest.slice(0, hash)).split('?'), 0), '');
124 let decoded: string;
125 try { decoded = decodeURIComponent(pathPart); } catch { return null; }
126 const joined = joinRepoPath(ctx.opts.base, decoded);
127 if (joined === null) return null;
128 const resolved = ctx.opts.resolve(joined, kind);
129 if (!resolved) return null;
130 const frag = hash === -1 ? '' : dest.slice(hash);
131 return classifyHref(frag && /^#[A-Za-z0-9_-]{1,80}$/.test(frag) ? `${resolved}${frag}` : resolved);
134/** `(dest "title")` after `]`. Returns the destination and how many characters it used, or null. */
135function linkTail(src: string, at: number): { dest: string; end: number } | null {
136 if (src[at] !== '(') return null;
137 let i = at + 1;
138 while (src[i] === ' ') i++;
139 let dest = '';
140 if (src[i] === '<') {
141 const close = src.indexOf('>', i);
142 if (close === -1) return null;
143 dest = src.slice(i + 1, close);
144 i = close + 1;
145 } else {
146 let depth = 0;
147 const start = i;
148 while (i < src.length) {
149 const ch = src[i];
150 if (ch === '\\' && i + 1 < src.length) { i += 2; continue; }
151 if (ch === ' ' || ch === '\t') break;
152 if (ch === '(') depth++;
153 if (ch === ')') { if (depth === 0) break; depth--; }
154 i++;
155 }
156 dest = src.slice(start, i);
157 }
158 while (src[i] === ' ') i++;
159 const q = src[i];
160 if (q === '"' || q === "'") {
161 const close = src.indexOf(q, i + 1);
162 if (close === -1) return null;
163 i = close + 1;
164 while (src[i] === ' ') i++;
165 }
166 if (src[i] !== ')') return null;
167 return { dest, end: i + 1 };
170/** Index of the `]` that closes the `[` at `at`, honouring nesting, escapes and code spans. */
171// Link labels longer than this are left as text, so a run of unclosed brackets stays linear.
172const MAX_LABEL = 1_000;
173const MAX_EMPHASIS = 4_000;
175function closeBracket(src: string, at: number): number {
176 let depth = 0;
177 const stop = Math.min(src.length, at + MAX_LABEL);
178 for (let i = at; i < stop; i++) {
179 const ch = src[i];
180 if (ch === '\\') { i++; continue; }
181 if (ch === '`') { const end = codeSpanEnd(src, i); if (end > 0) { i = end - 1; continue; } }
182 if (ch === '[') depth++;
183 if (ch === ']') { depth--; if (depth === 0) return i; }
184 }
185 return -1;
188function codeSpanEnd(src: string, at: number): number {
189 let n = 0;
190 while (src[at + n] === '`') n++;
191 const fence = '`'.repeat(n);
192 let from = at + n;
193 for (;;) {
194 const hit = src.indexOf(fence, from);
195 if (hit === -1) return -1;
196 if (src[hit + n] !== '`' && src[hit - 1] !== '`') return hit + n;
197 from = hit + 1;
198 }
201function refKey(label: string): string {
202 return label.trim().replace(/\s+/g, ' ').toLowerCase();
205// ── inline ───────────────────────────────────────────────────────────────────────────────────────────────────────
207function isWordChar(ch: string): boolean {
208 return ch !== '' && /[\p{L}\p{N}]/u.test(ch);
211function findCloser(src: string, from: number, delim: string): number {
212 const stop = Math.min(src.length, from + MAX_EMPHASIS);
213 for (let i = from; i < stop; i++) {
214 const ch = src[i];
215 if (ch === '\\') { i++; continue; }
216 if (ch === '`') { const end = codeSpanEnd(src, i); if (end > 0) { i = end - 1; continue; } }
217 if (src.startsWith(delim, i) && i > from && !/\s/.test(unwrapOr(textAt(src, i - 1), ' '))) {
218 if (delim.length === 1 && src[i + 1] === delim) { i++; continue; }
219 if (delim[0] === '_' && isWordChar(chAt(src, i + delim.length))) continue;
220 return i;
221 }
222 }
223 return -1;
226// Every character `inline` acts on; anything else is literal text.
227const INLINE_SPECIAL = new Set(['\\', '\n', '`', '!', '[', '<', 'h', 'H', '*', '_', '~']);
228const PLAIN_RUN = /[^\\\n`![<hH*_~]+/y;
230function inline(src: string, ctx: Ctx, inLink = false, depth = 0): SafeHtml {
231 const out: SafeHtml[] = [];
232 let text = '';
233 const flush = () => { if (text) { out.push(escapeHtml(text)); text = ''; } };
234 let i = 0;
235 while (i < src.length) {
236 const ch = chAt(src, i);
237 if (!INLINE_SPECIAL.has(ch)) {
238 // A run of plain characters is copied at once (it was one `text += ch` per character).
239 PLAIN_RUN.lastIndex = i;
240 const run = PLAIN_RUN.exec(src);
241 const end = run === null ? i + 1 : i + run[0].length;
242 text += src.slice(i, end);
243 i = end;
244 continue;
245 }
246 if (ch === '\\' && PUNCT.test(chAt(src, i + 1))) { text += src[i + 1]; i += 2; continue; }
247 if (ch === '\\' && src[i + 1] === '\n') { flush(); out.push(voidTag('br')); i += 2; continue; }
248 if (ch === '\n') {
249 const hard = / {2,}$/.test(text);
250 text = text.replace(/ +$/, '');
251 flush();
252 out.push(hard ? voidTag('br') : escapeHtml(' '));
253 i++;
254 while (src[i] === ' ') i++;
255 continue;
256 }
257 if (ch === '`') {
258 const end = codeSpanEnd(src, i);
259 if (end > 0) {
260 let n = 0;
261 while (src[i + n] === '`') n++;
262 let code = src.slice(i + n, end - n).replace(/\n/g, ' ');
263 if (/^ .* $/.test(code) && code.trim()) code = code.slice(1, -1);
264 flush();
265 out.push(tag('code', escapeHtml(code), null));
266 i = end;
267 continue;
268 }
269 let n = 0;
270 while (src[i + n] === '`') n++;
271 text += src.slice(i, i + n);
272 i += n;
273 continue;
274 }
275 const image = ch === '!' && src[i + 1] === '[';
276 if ((ch === '[' || image) && !inLink && depth < MAX_DEPTH) {
277 const open = image ? i + 1 : i;
278 const close = closeBracket(src, open);
279 if (close > open) {
280 const label = src.slice(open + 1, close);
281 let dest: string | null = null;
282 let end = close + 1;
283 const tail = linkTail(src, close + 1);
284 if (tail) { dest = tail.dest; end = tail.end; }
285 else if (src[close + 1] === '[') {
286 const refClose = src.indexOf(']', close + 2);
287 if (refClose !== -1) {
288 const key = refKey(src.slice(close + 2, refClose) || label);
289 const hit = mapGet(ctx.refs, key);
290 if (hit.tag === 'some') { dest = hit.value; end = refClose + 1; }
291 }
292 } else {
293 const hit = mapGet(ctx.refs, refKey(label));
294 if (hit.tag === 'some') dest = hit.value;
295 }
296 if (dest !== null) {
297 flush();
298 const href = hrefFor(dest.replace(/\\(.)/g, '$1'), image ? 'image' : 'link', ctx);
299 if (image) {
300 const alt = escapeHtml(label.replace(/[*_`[\]]/g, '') || 'image');
301 out.push(href ? anchor(href, tag('span', alt, 'md-img')) : tag('span', alt, 'md-img'));
302 } else {
303 // A refused destination stays visible as text, so the reader sees what the README tried to link.
304 out.push(href ? anchor(href, inline(label, ctx, true, depth + 1)) : escapeHtml(src.slice(i, end)));
305 }
306 i = end;
307 continue;
308 }
309 }
310 }
311 if (ch === '<' && !inLink) {
312 // The rest of the line is sliced only at a `<` or an `h` (it was sliced at every character).
313 const auto = /^<(https:[^\s<>]+|http:[^\s<>]+|mailto:[^\s<>]+)>/i.exec(src.slice(i));
314 const autoUrl = captureGroup(auto, 1);
315 if (autoUrl.tag === 'some' && autoUrl.value !== '') {
316 const href = classifyHref(autoUrl.value);
317 flush();
318 out.push(href ? anchor(href, escapeHtml(autoUrl.value)) : escapeHtml(group(auto, 0)));
319 i += group(auto, 0).length;
320 continue;
321 }
322 }
323 if ((ch === 'h' || ch === 'H') && !inLink && !isWordChar(chAt(src, i - 1))) {
324 const bare = /^https:\/\/[^\s<>"'`]+|^http:\/\/[^\s<>"'`]+/i.exec(src.slice(i));
325 if (bare) {
326 let url = bare[0];
327 while (/[.,:;!?)\]*_~]$/.test(url)) {
328 const opens = url.match(/\(/g);
329 const closes = url.match(/\)/g);
330 const openCount = opens === null ? 0 : opens.length;
331 const closeCount = closes === null ? 0 : closes.length;
332 if (url.endsWith(')') && openCount >= closeCount) break;
333 url = url.slice(0, -1);
334 }
335 const href = classifyHref(url);
336 if (href) {
337 flush();
338 out.push(anchor(href, escapeHtml(url)));
339 i += url.length;
340 continue;
341 }
342 }
343 }
344 if ((ch === '*' || ch === '_' || ch === '~') && depth < MAX_DEPTH) {
345 const two = src[i + 1] === ch;
346 if (ch === '~' && !two) { text += ch; i++; continue; }
347 const delim = two ? ch + ch : ch;
348 const leftOk = !/\s/.test(unwrapOr(textAt(src, i + delim.length), ' ')) && !(ch === '_' && isWordChar(chAt(src, i - 1)));
349 if (leftOk) {
350 const close = findCloser(src, i + delim.length, delim);
351 if (close > i + delim.length - 1) {
352 const inner = src.slice(i + delim.length, close);
353 if (inner.length) {
354 flush();
355 const name = ch === '~' ? 'del' : two ? 'strong' : 'em';
356 out.push(tag(name, inline(inner, ctx, inLink, depth + 1), null));
357 i = close + delim.length;
358 continue;
359 }
360 }
361 }
362 text += delim;
363 i += delim.length;
364 continue;
365 }
366 text += ch;
367 i++;
368 }
369 flush();
370 return concatHtml(out);
373// ── blocks ───────────────────────────────────────────────────────────────────────────────────────────────────────
375const FENCE = /^( {0,3})(`{3,}|~{3,})\s*([^`\s]*)[^`]*$/;
376const ATX = /^ {0,3}(#{1,6})([ \t]+(.*?))?([ \t]+#+)?[ \t]*$/;
377const HR = /^ {0,3}([-*_])([ \t]*\1){2,}[ \t]*$/;
378const QUOTE = /^ {0,3}> ?(.*)$/;
379const LIST = /^( {0,12})([-*+]|\d{1,9}[.)])([ \t]+(.*))?$/;
380const DELIM_ROW = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
381const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
382const REF_DEF = /^ {0,3}\[([^\]]{1,200})\]:[ \t]*<?([^\s>]+)>?([ \t]+"[^"]*"|[ \t]+'[^']*'|[ \t]+\([^)]*\))?[ \t]*$/;
384function slugify(text: string, ctx: Ctx): string {
385 const base = text.toLowerCase().replace(/<[^>]*>/g, '').replace(/[^\p{L}\p{N}\s-]/gu, '').trim().replace(/\s/g, '-')
386 .normalize('NFKD').replace(/[^a-z0-9-]/g, '').slice(0, 64);
387 if (!base) return '';
388 const seen = unwrapOr(mapGet(ctx.slugs, base), 0);
389 ctx.slugs.set(base, seen + 1);
390 return seen ? `${base}-${seen}` : base;
393function headingText(raw: string): string {
394 return raw.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[`*_~]/g, '');
397function splitRow(line: string): string[] {
398 let s = line.trim();
399 if (s.startsWith('|')) s = s.slice(1);
400 if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1);
401 const cells: string[] = [];
402 let cur = '';
403 for (let i = 0; i < s.length; i++) {
404 const ch = s[i];
405 if (ch === '\\' && s[i + 1] === '|') { cur += '|'; i++; continue; }
406 if (ch === '`') {
407 const end = codeSpanEnd(s, i);
408 if (end > 0) { cur += s.slice(i, end); i = end - 1; continue; }
409 }
410 if (ch === '|') { cells.push(cur.trim()); cur = ''; continue; }
411 cur += ch;
412 }
413 cells.push(cur.trim());
414 return cells;
417function alignOf(cell: string): MdClass | null {
418 const c = cell.trim();
419 const left = c.startsWith(':');
420 const right = c.endsWith(':');
421 if (left && right) return 'al-c';
422 if (right) return 'al-r';
423 if (left) return 'al-l';
424 return null;
427function startsBlock(line: string, inParagraph: boolean): boolean {
428 if (FENCE.test(line) || ATX.test(line) || HR.test(line) || QUOTE.test(line)) return true;
429 const item = LIST.exec(line);
430 const itemText = captureGroup(item, 4);
431 if (itemText.tag === 'some' && itemText.value.trim() !== '') {
432 // A paragraph is only interrupted by a bullet or by an ordered list that starts at 1 (CommonMark).
433 if (!inParagraph) return true;
434 const marker = group(item, 2);
435 return /^[-*+]$/.test(marker) || /^1[.)]$/.test(marker);
436 }
437 return /^ {0,3}<!--/.test(line);
440function indentOf(line: string): number {
441 let n = 0;
442 for (const ch of line) { if (ch === ' ') n++; else if (ch === '\t') n += 4 - (n % 4); else break; }
443 return n;
446function dedent(line: string, n: number): string {
447 let col = 0;
448 let i = 0;
449 while (i < line.length && col < n) {
450 if (line[i] === ' ') col++;
451 else if (line[i] === '\t') col += 4 - (col % 4);
452 else break;
453 i++;
454 }
455 return line.slice(i);
458function codeBlock(lang: string, text: string): SafeHtml {
459 const pre = tag('pre', tag('code', escapeHtml(text), null), null);
460 const label = lang ? tag('div', escapeHtml(lang.slice(0, 32)), 'md-code-lang') : escapeHtml('');
461 return tag('div', concatHtml([label, pre]), 'md-code');
464function renderBlocks(lines: string[], ctx: Ctx, depth: number, tight = false): SafeHtml {
465 const out: SafeHtml[] = [];
466 let i = 0;
467 while (i < lines.length) {
468 const line = lineAt(lines, i);
469 if (!line.trim()) { i++; continue; }
471 const fence = FENCE.exec(line);
472 if (fence) {
473 const indent = group(fence, 1).length;
474 const marker = group(fence, 2, '```');
475 const body: string[] = [];
476 i++;
477 // Built once per fence (it was built per line inside the fence).
478 const closing = new RegExp(`^ {0,3}${marker[0] === '`' ? '`' : '~'}{${marker.length},}[ \\t]*$`);
479 while (i < lines.length) {
480 const l = lineAt(lines, i);
481 if (closing.test(l)) { i++; break; }
482 body.push(dedent(l, indent));
483 i++;
484 }
485 out.push(codeBlock(group(fence, 3), body.join('\n')));
486 continue;
487 }
489 if (indentOf(line) >= 4) {
490 const body: string[] = [];
491 while (i < lines.length && (indentOf(lineAt(lines, i)) >= 4 || !lineAt(lines, i).trim())) { body.push(dedent(lineAt(lines, i), 4)); i++; }
492 while (body.length > 0) {
493 const last = atIndex(body, body.length - 1);
494 if (last.tag === 'none' || last.value.trim() !== '') break;
495 body.pop();
496 }
497 out.push(codeBlock('', body.join('\n')));
498 continue;
499 }
501 if (/^ {0,3}<!--/.test(line)) {
502 while (i < lines.length && !lineAt(lines, i).includes('-->')) i++;
503 i++;
504 continue;
505 }
507 const atx = ATX.exec(line);
508 if (atx) {
509 const hashes = captureGroup(atx, 1);
510 const level = Math.min(6, (hashes.tag === 'none' ? 1 : hashes.value.length) + 1) as 2 | 3 | 4 | 5 | 6;
511 const text = group(atx, 3);
512 out.push(heading(level, slugify(headingText(text), ctx), inline(text, ctx)));
513 i++;
514 continue;
515 }
517 if (HR.test(line)) { out.push(voidTag('hr')); i++; continue; }
519 if (QUOTE.test(line)) {
520 const inner: string[] = [];
521 while (i < lines.length) {
522 const l = lineAt(lines, i);
523 const q = QUOTE.exec(l);
524 if (q) { inner.push(group(q, 1)); i++; continue; }
525 if (!l.trim() || startsBlock(l, true)) break;
526 inner.push(l);
527 i++;
528 }
529 out.push(tag('blockquote', depth < MAX_DEPTH ? renderBlocks(inner, ctx, depth + 1) : escapeHtml(inner.join('\n')), null));
530 continue;
531 }
533 const next = lineAt(lines, i + 1);
534 if (line.includes('|') && DELIM_ROW.test(next) && next.includes('-')) {
535 const head = splitRow(line);
536 const aligns = splitRow(next).map(alignOf);
537 if (aligns.length === head.length || (aligns.length > 0 && head.length > 0)) {
538 const cols = head.length;
539 const row = (cells: string[], cell: 'th' | 'td') => tag('tr', concatHtml(
540 Array.from({ length: cols }, (_, c) => {
541 const align = atIndex(aligns, c);
542 const cls = align.tag === 'some' ? align.value : null;
543 return tag(cell, inline(unwrapOr(atIndex(cells, c), ''), ctx), cls);
544 }),
545 ), null);
546 const body: SafeHtml[] = [];
547 i += 2;
548 while (i < lines.length) {
549 const l = lineAt(lines, i);
550 if (!l.trim() || (!l.includes('|') && startsBlock(l, true))) break;
551 body.push(row(splitRow(l), 'td'));
552 i++;
553 }
554 const table = tag('table', concatHtml([tag('thead', row(head, 'th'), null), body.length ? tag('tbody', concatHtml(body), null) : escapeHtml('')]), null);
555 out.push(tag('div', table, 'md-table'));
556 continue;
557 }
558 }
560 const item = LIST.exec(line);
561 const itemBody = captureGroup(item, 4);
562 if (itemBody.tag === 'some' && itemBody.value.trim() !== '' && depth < MAX_DEPTH) {
563 const itemMarker = group(item, 2);
564 const ordered = /\d/.test(itemMarker);
565 const bullet = ordered ? itemMarker.slice(-1) : itemMarker;
566 const items: string[][] = [];
567 let looseList = false;
568 while (i < lines.length) {
569 const m = LIST.exec(lineAt(lines, i));
570 const mBody = captureGroup(m, 4);
571 if (m === null || mBody.tag === 'none' || mBody.value.trim() === '') break;
572 const mMarker = group(m, 2);
573 const sameKind = ordered ? /\d/.test(mMarker) && mMarker.endsWith(bullet) : mMarker === bullet;
574 if (!sameKind || indentOf(group(m, 1)) > indentOf(group(item, 1)) + 3) break;
575 const spacer = group(m, 3, ' ');
576 const contentIndent = group(m, 1).length + mMarker.length + Math.min(4, Math.max(1, spacer.length - mBody.value.length));
577 const body = [mBody.value];
578 i++;
579 let sawBlank = false;
580 while (i < lines.length) {
581 const l = lineAt(lines, i);
582 if (!l.trim()) {
583 const after = find(lines.slice(i + 1), (row) => row.trim() !== '');
584 if (after.tag === 'some' && indentOf(after.value) >= contentIndent) { body.push(''); sawBlank = true; i++; continue; }
585 break;
586 }
587 if (indentOf(l) >= contentIndent) { body.push(dedent(l, contentIndent)); i++; continue; }
588 if (sawBlank || startsBlock(l, true) || LIST.test(l)) break;
589 body.push(l.trim());
590 i++;
591 }
592 if (sawBlank) looseList = true;
593 items.push(body);
594 if (i < lines.length && !lineAt(lines, i).trim()) {
595 const after = find(lines.slice(i), (row) => row.trim() !== '');
596 const am = after.tag === 'some' ? LIST.exec(after.value) : null;
597 const amMarker = group(am, 2);
598 const amKind = am !== null && (ordered ? /\d/.test(amMarker) && amMarker.endsWith(bullet) : amMarker === bullet);
599 if (am !== null && amKind && indentOf(group(am, 1)) <= indentOf(group(item, 1)) + 3) {
600 looseList = true;
601 while (i < lines.length && !lineAt(lines, i).trim()) i++;
602 }
603 }
604 }
605 const lis = items.map(body => {
606 const first = unwrapOr(atIndex(body, 0), '');
607 const task = /^\[([ xX])\][ \t]+/.exec(first);
608 if (task) body[0] = first.slice(task[0].length);
609 const content = renderBlocks(body, ctx, depth + 1, !looseList);
610 if (!task) return tag('li', content, null);
611 const box = tag('span', escapeHtml(task[1] === ' ' ? '' : '✓'), task[1] === ' ' ? 'task' : 'task done');
612 return tag('li', concatHtml([box, content]), 'task-item');
613 });
614 const start = ordered ? Number.parseInt(group(item, 2, '1'), 10) : 1;
615 out.push(ordered ? orderedList(start, concatHtml(lis)) : tag('ul', concatHtml(lis), null));
616 continue;
617 }
619 const para: string[] = [];
620 while (i < lines.length) {
621 const l = lineAt(lines, i);
622 if (!l.trim()) break;
623 if (para.length && SETEXT.test(l)) {
624 const level = (l.trim()[0] === '=' ? 2 : 3) as 2 | 3;
625 const text = para.join('\n');
626 out.push(heading(level, slugify(headingText(text), ctx), inline(text, ctx)));
627 para.length = 0;
628 i++;
629 break;
630 }
631 if (para.length && startsBlock(l, true)) break;
632 if (para.length && line.includes('|') && DELIM_ROW.test(lineAt(lines, i + 1))) break;
633 para.push(l.replace(/^ {1,3}/, ''));
634 i++;
635 }
636 if (para.length) {
637 const html = inline(para.join('\n').replace(/[ \t]+$/, ''), ctx);
638 out.push(tight ? html : tag('p', html, null));
639 }
640 }
641 return concatHtml(out);
644function stripFrontMatter(lines: string[]): string[] {
645 const first = atIndex(lines, 0);
646 if (first.tag === 'none' || first.value.trim() !== '---') return lines;
647 const end = lines.findIndex((l, n) => n > 0 && (l.trim() === '---' || l.trim() === '...'));
648 return end > 0 ? lines.slice(end + 1) : lines;
651export function renderMarkdown(source: string, opts: MarkdownOptions = ROOT_OPTIONS): SafeHtml {
652 const ctx: Ctx = { opts, refs: new Map(), slugs: new Map() };
653 const lines: string[] = [];
654 let inFence = false;
655 for (const line of stripFrontMatter(source.replace(/\r\n?/g, '\n').split('\n'))) {
656 if (FENCE.test(line) && !inFence) inFence = true;
657 else if (inFence && /^ {0,3}(`{3,}|~{3,})[ \t]*$/.test(line)) inFence = false;
658 const def = inFence ? null : REF_DEF.exec(line);
659 const label = captureGroup(def, 1);
660 const dest = captureGroup(def, 2);
661 if (label.tag === 'some' && label.value !== '' && dest.tag === 'some' && dest.value !== '') {
662 const key = refKey(label.value);
663 if (!ctx.refs.has(key)) ctx.refs.set(key, dest.value);
664 continue;
665 }
666 lines.push(line);
667 }
668 return renderBlocks(lines, ctx, 0);
Diagnostics4 git calls · 32 ms
CallStatusSizeTime032 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=UPDATING
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=41349
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=41349
git.pkt.payload.max=41254
git.sideband.band1.bytes=41253
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=61
git.pack.bytes=41253
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c
git.pack.full=61
Open pack map
fetch2007.9 KiB · hit27 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=27
git.response.bytes=8110
git.response.cache=HIT
git.response.duration_ms=27
git.fetch.wants=87d057ab16b1cc4f30207cd3c5c4704704a684ec
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=8110
git.pkt.payload.max=8089
git.sideband.band1.bytes=8088
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
Ref
refs/heads/main
Commit
526b305930b8ef382f2d7a1f9c0238730a585921
cf-ray
a5e2ff8b1da9f3c9
Request
39ea9583…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format