Render Markdown and highlight code
Turn the Markdown a model writes into formatted text and coloured code, while the reply streams and once it is done.
<aparte-chat-bubble message-id="a1" data-role="assistant" streaming></aparte-chat-bubble>
<script>
// The streaming parser appends what each chunk adds instead of re-parsing the whole
// reply, so a list grows item by item.
const bubble = document.querySelector('aparte-chat-bubble');
bubble.setSegments([{ id: 's1', type: 'text', content: '' }]);
const text = 'Three steps:\n\n1. Register a provider.\n2. Set a transport.\n3. Start the client.\n\nThat is **the whole wiring**.';
let i = 0;
const tick = setInterval(() => {
bubble.appendToSegment('s1', text.slice(i, i + 6));
i += 6;
if (i >= text.length) { clearInterval(tick); bubble.removeAttribute('streaming'); }
}, 60);
</script>Install and register
Section titled “Install and register”npm install @aparte/plugin-streaming-markdown @aparte/plugin-marked marked @aparte/plugin-shiki shikiimport { setupStreamingMarkdownProvider } from '@aparte/plugin-streaming-markdown';
import { setupMarkedProvider } from '@aparte/plugin-marked';
import { setupShikiProvider } from '@aparte/plugin-shiki';
setupStreamingMarkdownProvider();
setupMarkedProvider();
setupShikiProvider({ theme: { light: 'github-light', dark: 'github-dark' } });Core has no Markdown of its own: with no renderer set, a reply shows its text as written, escaped.
The marked and Shiki plugins need their library installed beside them — marked, shiki — and
none of it reaches a page that does not install the plugin; the streaming plugin brings its parser
with it. Register them before the chat renders: a message drawn earlier shows its plain text until
they arrive, then is drawn again.
Which one formats what
Section titled “Which one formats what”@aparte/plugin-streaming-markdownformats the reply while it streams, adding what each chunk brings instead of formatting the whole reply again. Alone, it formats finished and restored messages too. Its parser is@paulrichez/streaming-markdown, a maintained fork ofstreaming-markdown.@aparte/plugin-markedformats a finished or restored message at full fidelity. Beside the streaming plugin, it formats a reply again once it finishes; alone, it formats a streaming reply too, from the start at each chunk. Its/streamingentry formats the streaming reply with marked as well — see Stream with marked.@aparte/plugin-shikicolours code: the code blocks of a reply — the stream parser makes each fence its own block — the fences in a message given as plain content, in reasoning and in atextsegment you build yourself, and the JSON a tool call shows.
To pass marked its options, give them to the setup: setupMarkedProvider({ gfm: true, breaks: true }).
With options it uses a marked of its own, so two configurations can format differently. Another
parser plugs into the same place: aparteGlobalConfig.setMarkdownProvider((markdown) => html),
a synchronous function from the Markdown to its HTML.
Stream with marked
Section titled “Stream with marked”import { setupMarkedStreamingProvider } from '@aparte/plugin-marked/streaming';
setupMarkedStreamingProvider();This one call replaces setupStreamingMarkdownProvider() and setupMarkedProvider() from the first
step: marked formats the reply while it streams and once it is done, so a finished reply looks
exactly as it did at its last chunk. While it streams, the block being written is completed by
Vercel’s remend before marked reads it: **bold shows
bold before its closing ** arrives, a link shows as a link from its first character and becomes
clickable once its URL is complete, and an image that may load appears once its URL is
(which ones may). remend installs with the
plugin, and only this entry imports it. The options are marked’s, as for setupMarkedProvider.
Pick by what the reply should keep while it streams:
@aparte/plugin-streaming-markdownonly adds to the page. Nothing already written is drawn again, so a selection holds anywhere in the reply. Beside@aparte/plugin-marked, the reply is formatted once more by marked when it finishes, and a construct the two parsers read differently moves at that moment.@aparte/plugin-marked/streamingdraws the block being written again at each chunk, so a selection inside that block does not hold until it is done; the blocks above it stay as they are. What streams is marked’s output — tables, nested lists, and nothing moves when the reply finishes.
Light and dark code
Section titled “Light and dark code”The theme pair above follows the nearest data-aparte-theme around the code, so a chat set light
inside a dark page gets light code; with no attribute anywhere it follows the system, and a
color-scheme the page sets changes nothing. A single theme name, such as { theme: 'github-dark' }, keeps that look in both,
and with no theme at all code uses github-dark in both. A language shiki does not know shows as
plain text.
Ship only the grammars you need
Section titled “Ship only the grammars you need”npm install @shikijs/langs @shikijs/themesimport { createHighlighterCore } from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import ts from '@shikijs/langs/typescript';
import bash from '@shikijs/langs/bash';
import githubDark from '@shikijs/themes/github-dark';
import { setupShikiProviderFromHighlighter } from '@aparte/plugin-shiki/core';
createHighlighterCore({
themes: [githubDark],
langs: [ts, bash],
engine: createJavaScriptRegexEngine(),
}).then((highlighter) => setupShikiProviderFromHighlighter(highlighter, { theme: 'github-dark' }));This replaces the setupShikiProvider call of the first step: an import of @aparte/plugin-shiki
anywhere in your app brings every grammar back. That entry loads each grammar the first time a
reply needs it, but your bundler cannot know which ones that will be, so it emits a file for every
language shiki knows. The /core entry takes a highlighter you build with the grammars you choose,
and your build carries those alone; a language it lacks shows as plain text. For a light and dark
pair, load both themes into it: themes: [githubLight, githubDark].
The options are typed: ShikiProviderOptions for setupShikiProvider, ShikiCoreProviderOptions
for the /core entry, ShikiThemePair for a light and a dark theme. A highlighter of your own
passed to /core is a ShikiHighlighterLike, called with ShikiRenderOptions.
Use another highlighter
Section titled “Use another highlighter”import { aparteGlobalConfig } from '@aparte/core';
declare const myHighlighter: { toHtml(code: string, lang: string): Promise<string> };
aparteGlobalConfig.setHighlightProvider((code, lang) => myHighlighter.toHtml(code, lang));The provider gets the code and its language, and returns the whole block as HTML, <pre> included,
as a string or a promise of one.
Keep it safe
Section titled “Keep it safe”import DOMPurify from 'dompurify';
import { aparteGlobalConfig, defaultSanitizer } from '@aparte/core';
aparteGlobalConfig.setHtmlSanitizer((html) => defaultSanitizer(DOMPurify.sanitize(html)));What marked and a highlighter return goes through the chat’s HTML sanitizer before it reaches the page, and so does a streamed reply once it finishes, so the Markdown a model writes cannot run script. While a reply streams, a link or an image with an unsafe address is dropped, and a link to another site opens in a new tab. The built-in sanitizer needs no dependency.
To add DOMPurify, chain it in front of the built-in sanitizer, as above, rather than in its place.
setHtmlSanitizer replaces the sanitizer, and
DOMPurify’s defaults are written for any page, not for a chat: on their own they keep inline layout
styles (a reply can cover the screen), core’s aparte- classes (a reply can draw a button that looks
like an approval), form controls, ids, roles that make text a control, the data-aparte-*
attributes core reads as commands (a reply can open a dialog), and they leave a link to another site opening in the
chat’s own frame.
Pictures a reply can load
Section titled “Pictures a reply can load”Pictures a model or a tool chose do not load by themselves. A data: or blob: picture does;
any other is shown as a small link that names where it would load from, and it loads in place when
the reader clicks it (a click with a modifier key or the middle button is left to the browser, as
for any link: a new tab, a new window or a download). A card shows one “Show images” button in
place of the links. A held picture is not fetched while a reply streams either.
A picture fetches its address the moment it is shown, and a prompt-injected model — one that read
a web page, a document or a tool result written to steer it — can write the conversation into that
address:  sends it, with the reader’s IP address, to that
host without a click, and nobody sees anything happen. The page’s own address is not trusted by
default either. It carries the reader’s cookies, and an open redirect on your site turns a picture
from your site into a picture from anywhere.
The assistants this was done to closed it the same way: Gemini no longer shows external pictures in a reply, ChatGPT loads only addresses it has checked, and GitHub Copilot Chat stopped showing them, each after the attack was reported.
Name what you trust with setImagePolicy:
import { aparteGlobalConfig } from '@aparte/core';
// Your own site and one CDN load; everything else waits for a click.
aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
// Every picture loads, as before 1.0.
aparteGlobalConfig.setImagePolicy(['*']);
// Anything else: 'load' it, 'hold' it behind a click, or 'drop' it with no trace.
aparteGlobalConfig.setImagePolicy((url) =>
url.startsWith('https://images.example.com/') ? 'load' : 'hold');Which one to choose:
- Your pictures come from places you know — your site, a CDN, a product catalogue: list them. List hosts that serve only your own files: one where anyone can upload, or that redirects anywhere, gives the hole back.
- Every picture should load — an internal tool whose model never reads content you do not
control:
['*'], as 0.x did. - No picture should load by itself — keep the default.
setImagePolicy([])says so, and silences the note below.
The first picture held on a page also writes a note in the browser console, with its host and the line to add, so a picture waiting for a click is not mistaken for a broken one. Naming any policy, the default included, silences it.
A list takes 'self', '*' and origins; a function gets the address resolved against the page.
An answer that is none of the three holds the picture. Every picture that loads goes with
referrerpolicy="no-referrer", so the host does not learn which page showed it.
A plugin, or an app that draws pictures itself, asks the same rule before it sets a src, because
setting it is the request:
import { aparteGlobalConfig } from '@aparte/core';
declare const url: string;
declare const frame: HTMLElement;
if (aparteGlobalConfig.decideImage(url) === 'load') {
const img = document.createElement('img');
img.referrerPolicy = 'no-referrer'; // before `src`, which starts the request
img.src = url;
frame.append(img);
}
// The reader chose to see it: it loads from now on where the policy would only have held it.
aparteGlobalConfig.showImage(url);For a card of your own, ctx.image(src, props) returns an <img> that loads, or null when the
policy does not let it, and ctx.loads(url) says whether a video, a sound or a poster may load
now (cards).
Beside a Content-Security-Policy
Section titled “Beside a Content-Security-Policy”The policy is what the library can do on its own. An img-src header is the stronger rule beside
it, because it also checks where a redirect leads, which no script on the page can see:
Content-Security-Policy: img-src 'self' data: blob: https://cdn.example.comOr proxy third-party pictures through your own server and allow that origin in the policy and in
the header. A <video> or an <audio> cannot be told to send no referrer; a page that cares sets
its own Referrer-Policy header.
What it does not cover
Section titled “What it does not cover”- It runs after whichever sanitizer is set, DOMPurify included, and covers
<img>and<source>. A sanitizer of your own that keeps<video>,<audio>, an SVG<image>or astylewithurl()lets those load: chain it in front ofdefaultSanitizer, as above. - With no page, as in a server render, a relative address cannot be resolved, so a list other than
'*'holds it. - The map tiles you configure (
mapTiles) and the pictures your own code draws, such as avatars, attachments and a tool renderer that returns its own markup, are yours, not the policy’s.
Maths and diagrams
Section titled “Maths and diagrams”import { aparteGlobalConfig, escapeHtml } from '@aparte/core';
// A ```csv fence drawn as a table, in any reply.
aparteGlobalConfig.registerCodeLanguageRenderer({
languages: ['csv'],
render: ({ source }) =>
`<table>${source.trim().split('\n').map((row) =>
`<tr>${row.split(',').map((cell) => `<td>${escapeHtml(cell)}</td>`).join('')}</tr>`).join('')}</table>`,
});A fence or a formula is drawn by the renderer registered for its language — math by
@aparte/plugin-katex, mermaid by @aparte/plugin-mermaid,
or one of your own — whichever Markdown provider is installed. A provider hands a source over by
marking it: <pre><code class="language-X"> for a fence, which every provider already writes, and
<code class="language-math math-inline"> or math-display for maths, which marked and
streaming-markdown write once a math renderer is registered. While a reply streams the renderer is
also asked about a source still arriving, and may draw it or wait. To draw them inside an element of
your own, call renderCodeLanguages(element) after writing its HTML.
A drawing goes beside its source, which stays in the page hidden: copying, and the history the model
reads, still use the source. What render returns is inserted as it is, not through the sanitizer,
which would strip the SVG, MathML and positioning a drawing is made of; it has the standing of a
segment renderer’s output — code you installed — so escape anything from the source you put in it.
Route the links a model writes
Section titled “Route the links a model writes”declare const router: { push(path: string): void }; // your app's router
const chat = document.querySelector('aparte-chat');
chat?.addEventListener('aparte-link-click', (event) => {
const url = new URL(event.detail.href, location.href);
if (url.origin !== location.origin) return; // another site: let the browser open it
event.preventDefault(); // this one is yours
router.push(url.pathname + url.search);
});Before the browser follows a link in a reply, the message fires aparte-link-click. It bubbles, so
one listener on the chat covers every message, and it can be cancelled: call preventDefault() and
the navigation is yours — your router, a webview, a question first. The detail is
{ href, anchor, messageId }.
Two chats, two setups
Section titled “Two chats, two setups”import { AparteConfig, attachConfig } from '@aparte/core';
import { setupStreamingMarkdownProvider } from '@aparte/plugin-streaming-markdown';
import { setupMarkedProvider } from '@aparte/plugin-marked';
import { setupShikiProvider } from '@aparte/plugin-shiki';
const support = new AparteConfig();
setupStreamingMarkdownProvider(support);
setupMarkedProvider({ breaks: true }, support);
setupShikiProvider({ theme: 'github-dark' }, support);
const chat = document.querySelector<HTMLElement>('#support-chat');
if (chat) attachConfig(chat, support);Every setup takes a configuration as its last argument, the page-wide one by default. A
configuration of your own starts from the built-in defaults and reads nothing the page-wide one
registered, so set up on it every formatter that chat uses; attached to a chat, it formats that chat
alone. The framework packages take it as their config prop.