askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
markdown.py · 9.0 KB · 213 lines
| 1 | """Shared markdown renderer, served as one object at /markdown. |
| 2 | |
| 3 | Any page includes <script src="/markdown"></script> and gets |
| 4 | `window.dbbasicMarkdown(text)` — defined once, reused everywhere. As of |
| 5 | this pass that's the shell/Talk captions, view_render.py's standalone |
| 6 | `markdown` view block, and /form's read-only rendering of any `textarea` |
| 7 | field (articles, notes, anything long-form) — three call sites that used |
| 8 | to each carry their own copy of a *lighter* transform (bold/italic/links/ |
| 9 | line-breaks only) before converging here. Rendering markdown is a shared |
| 10 | UI utility, so it lives in the design system alongside /style and /nav, |
| 11 | never copied into each page — see 2026-08's incident: two of those three |
| 12 | copies were written in the same session before this one was noticed. |
| 13 | |
| 14 | Real block-level markdown now, not just inline transforms: headings (# - |
| 15 | ######), fenced code blocks (```lang ... ```), blockquotes (>), ordered |
| 16 | and unordered lists (no nesting -- see below), horizontal rules, and GFM |
| 17 | tables, on top of the inline set (bold, italic, inline code, bracket |
| 18 | links with an http(s)/relative/#/mailto href allowlist, autolinked bare |
| 19 | URLs). Hard-wrapped continuation lines inside a list item rejoin their |
| 20 | bullet, matching how paragraphs already rejoin their own wrapped lines. This codebase's stated posture (see object_reader.py) is stdlib/ |
| 21 | no-new-dependency on the server; the client-side JS here is unbundled |
| 22 | vanilla JS with no npm/build step at all, so a hand-rolled parser matches |
| 23 | how every other renderer in this codebase is built (forms, lists, detail |
| 24 | pages), not a gap to fill with a vendored library. |
| 25 | |
| 26 | Deliberately NOT attempted: nested lists (one level only -- a nested `- ` |
| 27 | line is treated as its own top-level bullet, which is wrong but never |
| 28 | silently drops content), tables with column alignment markers (`:---:` |
| 29 | parses as a plain separator, alignment is ignored), and fenced-block |
| 30 | diagram languages (a ```mermaid block renders as a plain code block here, |
| 31 | not a live-rendered diagram -- honestly worse than nothing for diagrams |
| 32 | specifically, but never worse than escaping the raw text). All three are |
| 33 | real, scoped follow-ups, not oversights to silently paper over. |
| 34 | |
| 35 | Escapes the input FIRST, so untrusted text (an AI reply, a user note) can |
| 36 | never inject HTML -- markdown SYNTAX characters (#, *, `, -, >, |) survive |
| 37 | HTML-escaping unchanged, so escaping the whole raw line before recognizing |
| 38 | its block type is safe and is what every regex below assumes. |
| 39 | """ |
| 40 | |
| 41 | _JS = r""" |
| 42 | (function () { |
| 43 | const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, |
| 44 | (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); |
| 45 | |
| 46 | // Inline transforms only -- applied to one line/cell's worth of text |
| 47 | // that has ALREADY been through block-level recognition. Order matters: |
| 48 | // inline code first (so `**not bold**` inside backticks is not touched |
| 49 | // by the bold/italic passes that run after it). |
| 50 | // Only these href shapes may become real links -- everything else (most |
| 51 | // importantly javascript:) stays inert escaped text. The input was |
| 52 | // escaped first, so quotes in an href arrive as " and cannot break |
| 53 | // out of the attribute. |
| 54 | const SAFE_HREF_RE = /^(https?:\/\/|\/|#|mailto:)/i; |
| 55 | |
| 56 | function renderInline(text) { |
| 57 | let html = esc(text); |
| 58 | html = html.replace(/`([^`\n]+)`/g, "<code>$1</code>"); |
| 59 | html = html.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>"); |
| 60 | html = html.replace(/\*([^*\n]+)\*/g, "<em>$1</em>"); |
| 61 | // [text](href) before the bare-URL pass, so the pass below never eats |
| 62 | // the href out of a bracket link's parentheses first. |
| 63 | html = html.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (match, label, href) => { |
| 64 | if (!SAFE_HREF_RE.test(href)) return match; |
| 65 | const external = /^https?:\/\//i.test(href); |
| 66 | const extra = external ? ' target="_blank" rel="noopener"' : ""; |
| 67 | return '<a href="' + href + '"' + extra + ">" + label + "</a>"; |
| 68 | }); |
| 69 | // Bare URLs -- but not one already sitting inside an href="..." |
| 70 | // attribute or an anchor's text from the pass above (preceded by " or |
| 71 | // >). Written as capture-and-restore, not lookbehind, so the whole |
| 72 | // script still parses on older WebKit (pre-16.4 Safari has no |
| 73 | // lookbehind, and one bad regex literal kills the file at load). |
| 74 | html = html.replace(/(^|[^">])(https?:\/\/[^\s<]+)/g, |
| 75 | (match, pre, url) => pre + '<a href="' + url + '" target="_blank" rel="noopener">' + url + "</a>"); |
| 76 | return html; |
| 77 | } |
| 78 | |
| 79 | function parseTableRow(line) { |
| 80 | const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, ""); |
| 81 | return trimmed.split("|").map((c) => c.trim()); |
| 82 | } |
| 83 | const TABLE_SEPARATOR_RE = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/; |
| 84 | |
| 85 | window.dbbasicMarkdown = function (text) { |
| 86 | const lines = String(text == null ? "" : text).replace(/\r\n/g, "\n").split("\n"); |
| 87 | const out = []; |
| 88 | let paragraph = []; |
| 89 | let listType = null; // "ul" | "ol" | null |
| 90 | let listItems = []; |
| 91 | let blockquote = []; |
| 92 | |
| 93 | function flushParagraph() { |
| 94 | if (paragraph.length) { out.push("<p>" + renderInline(paragraph.join(" ")) + "</p>"); paragraph = []; } |
| 95 | } |
| 96 | function flushList() { |
| 97 | if (listType) { |
| 98 | out.push("<" + listType + ">" + listItems.map((it) => "<li>" + renderInline(it) + "</li>").join("") + "</" + listType + ">"); |
| 99 | listType = null; listItems = []; |
| 100 | } |
| 101 | } |
| 102 | function flushBlockquote() { |
| 103 | if (blockquote.length) { out.push("<blockquote>" + renderInline(blockquote.join(" ")) + "</blockquote>"); blockquote = []; } |
| 104 | } |
| 105 | function flushAll() { flushParagraph(); flushList(); flushBlockquote(); } |
| 106 | |
| 107 | let i = 0; |
| 108 | while (i < lines.length) { |
| 109 | const line = lines[i]; |
| 110 | |
| 111 | const fence = line.match(/^```\s*([a-zA-Z0-9_+-]*)\s*$/); |
| 112 | if (fence) { |
| 113 | flushAll(); |
| 114 | const lang = fence[1]; |
| 115 | const codeLines = []; |
| 116 | i++; |
| 117 | while (i < lines.length && !/^```\s*$/.test(lines[i])) { codeLines.push(lines[i]); i++; } |
| 118 | i++; // skip the closing fence (or run off the end if unterminated) |
| 119 | const cls = lang ? ' class="language-' + esc(lang) + '"' : ""; |
| 120 | out.push("<pre><code" + cls + ">" + esc(codeLines.join("\n")) + "</code></pre>"); |
| 121 | continue; |
| 122 | } |
| 123 | |
| 124 | const heading = line.match(/^(#{1,6})\s+(.*)$/); |
| 125 | if (heading) { |
| 126 | flushAll(); |
| 127 | const level = heading[1].length; |
| 128 | out.push("<h" + level + ">" + renderInline(heading[2].trim()) + "</h" + level + ">"); |
| 129 | i++; |
| 130 | continue; |
| 131 | } |
| 132 | |
| 133 | if (/^(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) { |
| 134 | flushAll(); |
| 135 | out.push("<hr>"); |
| 136 | i++; |
| 137 | continue; |
| 138 | } |
| 139 | |
| 140 | // GFM table: a "| a | b |" row immediately followed by a |
| 141 | // "|---|---|"-shaped separator row. |
| 142 | if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && TABLE_SEPARATOR_RE.test(lines[i + 1])) { |
| 143 | flushAll(); |
| 144 | const headerCells = parseTableRow(line); |
| 145 | i += 2; |
| 146 | const bodyRows = []; |
| 147 | while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { bodyRows.push(parseTableRow(lines[i])); i++; } |
| 148 | let table = "<table><thead><tr>" + headerCells.map((c) => "<th>" + renderInline(c) + "</th>").join("") + "</tr></thead>"; |
| 149 | if (bodyRows.length) { |
| 150 | table += "<tbody>" + bodyRows.map((row) => |
| 151 | "<tr>" + row.map((c) => "<td>" + renderInline(c) + "</td>").join("") + "</tr>" |
| 152 | ).join("") + "</tbody>"; |
| 153 | } |
| 154 | out.push(table + "</table>"); |
| 155 | continue; |
| 156 | } |
| 157 | |
| 158 | const quote = line.match(/^>\s?(.*)$/); |
| 159 | if (quote) { |
| 160 | flushParagraph(); flushList(); |
| 161 | blockquote.push(quote[1]); |
| 162 | i++; |
| 163 | continue; |
| 164 | } |
| 165 | if (blockquote.length) flushBlockquote(); |
| 166 | |
| 167 | // Leading whitespace tolerated on markers: a nested " - " line |
| 168 | // becomes its own top-level bullet (the documented wrong-but-lossless |
| 169 | // behavior), instead of falling through to the continuation branch. |
| 170 | const ul = line.match(/^\s*[-*+]\s+(.*)$/); |
| 171 | if (ul) { |
| 172 | flushParagraph(); flushBlockquote(); |
| 173 | if (listType && listType !== "ul") flushList(); |
| 174 | listType = "ul"; |
| 175 | listItems.push(ul[1]); |
| 176 | i++; |
| 177 | continue; |
| 178 | } |
| 179 | |
| 180 | const ol = line.match(/^\s*\d+\.\s+(.*)$/); |
| 181 | if (ol) { |
| 182 | flushParagraph(); flushBlockquote(); |
| 183 | if (listType && listType !== "ol") flushList(); |
| 184 | listType = "ol"; |
| 185 | listItems.push(ol[1]); |
| 186 | i++; |
| 187 | continue; |
| 188 | } |
| 189 | // A hard-wrapped continuation of the previous bullet: indented, |
| 190 | // non-empty, not itself a marker (checked above). Without this, a |
| 191 | // source wrapped at a fixed column breaks every long bullet into a |
| 192 | // bullet plus a stray paragraph. |
| 193 | if (listType && /^\s+\S/.test(line)) { |
| 194 | listItems[listItems.length - 1] += " " + line.trim(); |
| 195 | i++; |
| 196 | continue; |
| 197 | } |
| 198 | if (listType) flushList(); |
| 199 | |
| 200 | if (line.trim() === "") { flushParagraph(); i++; continue; } |
| 201 | |
| 202 | paragraph.push(line.trim()); |
| 203 | i++; |
| 204 | } |
| 205 | flushAll(); |
| 206 | return out.join(""); |
| 207 | }; |
| 208 | })(); |
| 209 | """ |
| 210 | |
| 211 | |
| 212 | def GET(request): |
| 213 | return {"content_type": "application/javascript; charset=utf-8", "body": _JS} |