limmat 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daan Rosendal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # limmat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Streaming markdown for LLM chat. Half-typed syntax like `[docs](https://example` or `# Titl` renders cleanly instead of showing raw text.
4
+
5
+ <p align="center">
6
+ <a href="https://limmat.daanrosendal.com">
7
+ <picture>
8
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/DaanRosendal/limmat/master/docs/demo-dark.gif">
9
+ <img src="https://raw.githubusercontent.com/DaanRosendal/limmat/master/docs/demo-light.gif" width="720" alt="The limmat demo streaming a reply about itself: the raw text from the model on the left, limmat's rendered output on the right.">
10
+ </picture>
11
+ </a>
12
+ </p>
13
+
14
+ **[Try the demo](https://limmat.daanrosendal.com)**
15
+
16
+ - **No raw markers.** Unfinished markdown shows as clean text until it is complete.
17
+ - **Predictable.** However the text is cut into chunks, the page ends up the same as rendering it all at once.
18
+ - **Safe.** It builds DOM nodes, never HTML strings, so hostile input shows up as plain text. Images load unless you limit them, see [Safety](#safety).
19
+ - **Any framework.** Give it any DOM element: React, Vue, Svelte, or plain JavaScript.
20
+ - **Small and fast.** 9.5 kB gzip, no dependencies. A 100 KB reply streamed in small chunks takes about 20 ms in total in Chromium.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ npm install limmat
26
+ ```
27
+
28
+ ```ts
29
+ import { createRenderer } from 'limmat';
30
+ import 'limmat/style.css'; // optional
31
+
32
+ const md = createRenderer(document.querySelector('#answer')!);
33
+ for await (const chunk of stream) md.write(chunk); // any source of text chunks
34
+ md.end();
35
+ ```
36
+
37
+ `createRenderer(el)` returns `write(chunk)` (only the new text), `end()` (call it when the stream is over), `reset()` (clear it for a new message), and `destroy()`. Use one renderer per message. Creating a renderer empties the element, and options are read once, at creation. limmat is an ES module and renders in the browser, so on a server the element stays empty until the client runs. Options are listed [below](#options).
38
+
39
+ In React, create the renderer in an effect and destroy it in the cleanup:
40
+
41
+ ```tsx
42
+ useEffect(() => {
43
+ const md = createRenderer(ref.current!);
44
+ const ctrl = new AbortController();
45
+ fetch('/chat', { signal: ctrl.signal })
46
+ .then(async (res) => {
47
+ const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
48
+ for (let r = await reader.read(); !r.done; r = await reader.read()) md.write(r.value);
49
+ md.end();
50
+ })
51
+ .catch(() => {});
52
+ return () => {
53
+ ctrl.abort();
54
+ md.destroy();
55
+ };
56
+ }, []);
57
+ ```
58
+
59
+ For colored code, add the optional highlighter (it needs `@speed-highlight/core`, plus one of its theme stylesheets):
60
+
61
+ ```ts
62
+ import { speedHighlight } from 'limmat/highlight';
63
+ createRenderer(el, { highlight: speedHighlight() });
64
+ ```
65
+
66
+ ## Browser support
67
+
68
+ | Chrome, Edge, and other Chromium browsers | Firefox | Safari (macOS and iOS) |
69
+ |:---:|:---:|:---:|
70
+ | ✅ | ✅ | ✅ |
71
+
72
+ Tested in Chromium, Firefox, and WebKit.
73
+
74
+ ## Safety
75
+
76
+ Raw HTML shows as text, except attribute-free tags like `<kbd>` and `<sub>`, and collapsible `<details>`. Links must be http, https, mailto, or a site path (every path unless `isInternalPath` says otherwise). The optional highlighter passes code to `@speed-highlight/core`, which builds HTML itself. Images load without a click, so a hostile reply can send data to its own server: pass `images: ['https://your-cdn.example']` or `images: false` to limit that. More in [SECURITY.md](https://github.com/DaanRosendal/limmat/blob/master/SECURITY.md).
77
+
78
+ ## What is supported
79
+
80
+ limmat follows the [CommonMark spec](https://spec.commonmark.org/0.31.2/) where it can. Anything it does not support falls back to plain text or a simpler element, never to raw HTML. The demo's "What's supported" tab shows how many CommonMark examples each feature passes.
81
+
82
+ <!-- support:start (generated by scripts/gen-support.mjs from docs/support.json, do not edit) -->
83
+ | Feature | Status | Note |
84
+ |---|---|---|
85
+ | Headings (`# Title`) | 🟢&nbsp;Supported | |
86
+ | Horizontal rules (`---`) | 🟢&nbsp;Supported | |
87
+ | Code blocks (fenced) | 🟢&nbsp;Supported | Language label, Copy button, optional highlighting. |
88
+ | Block quotes | 🟢&nbsp;Supported | |
89
+ | Task lists | 🟢&nbsp;Supported | Checkboxes are read-only. |
90
+ | Tables | 🟢&nbsp;Supported | |
91
+ | Bold and italic | 🟢&nbsp;Supported | `snake_case_words` stay text. |
92
+ | Strikethrough (`~~text~~`) | 🟢&nbsp;Supported | Needs two tildes. |
93
+ | Inline code | 🟢&nbsp;Supported | |
94
+ | Collapsible sections (`<details>`) | 🟢&nbsp;Supported | Each tag alone on its line. |
95
+ | Line breaks | 🟢&nbsp;Supported | |
96
+ | Half-typed markers hidden while streaming | 🟢&nbsp;Supported | A few exceptions, see Known limits. |
97
+ | Same output however the text is chunked | 🟢&nbsp;Supported | |
98
+ | Lists | 🟡&nbsp;Partial | Nesting works. Blank lines between items are ignored. |
99
+ | Links | 🟡&nbsp;Partial | `[text](url)` only. A title is dropped, and unsafe URLs show as text. |
100
+ | Autolinks (bare URLs, `www.`, emails) | 🟡&nbsp;Partial | Only http, https, and mailto. |
101
+ | Images | 🟡&nbsp;Partial | On by default and loaded without a click, so limit them with `images`. No titles. |
102
+ | Raw HTML | 🟡&nbsp;Partial | Shown as text, except a few tags like `<kbd>` and `<sub>`. |
103
+ | Backslash escapes | 🟡&nbsp;Partial | A few edge cases differ. |
104
+ | Underlined headings (`Title` over `---`) | ⚪&nbsp;Not&nbsp;yet | The underline shows as a rule or as text. |
105
+ | Indented code blocks | ⚪&nbsp;Not&nbsp;yet | Use fences. |
106
+ | Reference links (`[a][1]`) | ⚪&nbsp;Not&nbsp;yet | Shown as text. |
107
+ | HTML entities (`&amp;`) | ⚪&nbsp;Not&nbsp;yet | Shown literally. |
108
+ | Tab indentation | ⚪&nbsp;Not&nbsp;yet | |
109
+ | Math (`$x$`) | ⚪&nbsp;Not&nbsp;yet | Planned as an opt-in hook you supply. |
110
+ | Footnotes | ⚪&nbsp;Not&nbsp;yet | Shown as text. Will be opt-in. |
111
+ | Alerts (`> [!NOTE]`) | ⚪&nbsp;Not&nbsp;yet | Shown as a plain block quote. |
112
+ | Citations (`[1]`) and emoji codes | ⚪&nbsp;Not&nbsp;yet | Shown literally. Will be opt-in. |
113
+ <!-- support:end -->
114
+
115
+ ## Options
116
+
117
+ Pass options as the second argument to `createRenderer`. All are optional.
118
+
119
+ | Option | Default | What it does |
120
+ |---|---|---|
121
+ | `throttleMs` | `50` | Minimum ms between re-renders of the open block. `0` renders on every write. |
122
+ | `images` | `true` | Allowed image origins, like `['https://cdn.example.com']`, or `false` for alt text only. See [Safety](#safety). |
123
+ | `html` | `true` | Which safe tags become elements, like `<kbd>` and `<details>`. A list keeps only those, `false` shows them as text, except `<br>`. |
124
+ | `highlight` | none | `(el, code, lang) => void`, called for each finished code block. `limmat/highlight` provides one. |
125
+ | `onLinkClick` | none | `(href, event) => boolean`. Return `true` to handle the click yourself. |
126
+ | `isInternalPath` | every path | `(path) => boolean`. Site paths like `/docs/x` become links only if this returns `true`. Check the whole path. |
127
+ | `allowedProtocols` | `['https', 'http', 'mailto']` | Protocols that become links. Others show as text. |
128
+ | `externalLinksNewTab` | `true` | `false` opens links in the same tab. |
129
+ | `classPrefix` | `'limmat'` | Prefix for generated classes. The bundled CSS only styles the default. |
130
+ | `labels` | English | Text for the Copy button and screen readers: `copy`, `copied`, `table`, `done`, `todo`. |
131
+
132
+ ```ts
133
+ createRenderer(el, {
134
+ images: ['https://cdn.example.com'],
135
+ html: ['kbd', 'sub', 'sup'], // no <details>
136
+ highlight: speedHighlight(),
137
+ onLinkClick: (href) => {
138
+ if (!href.startsWith('/docs/')) return false;
139
+ router.push(href); // your router
140
+ return true;
141
+ },
142
+ labels: { copy: 'Kopieren', copied: 'Kopiert' },
143
+ });
144
+ ```
145
+
146
+ ## Known limits
147
+
148
+ - `[1]` shows as `1` until its closing bracket arrives, and the `<` of an `<email@example.com>` autolink shows until the `@` arrives.
149
+ - `#anchor` links and relative links without a leading slash show as plain text.
150
+ - A different bullet or delimiter (`+` after `-`, `3)` after `2.`) does not start a new list, and any number can interrupt a paragraph.
151
+
152
+ ---
153
+
154
+ [AGENTS.md](https://github.com/DaanRosendal/limmat/blob/master/AGENTS.md) for working on limmat, [SECURITY.md](https://github.com/DaanRosendal/limmat/blob/master/SECURITY.md) to report a problem, and [CHANGELOG.md](https://github.com/DaanRosendal/limmat/blob/master/CHANGELOG.md). Licensed under the [MIT License](https://github.com/DaanRosendal/limmat/blob/master/LICENSE).
155
+
156
+ *Named after the [Limmat](https://en.wikipedia.org/wiki/Limmat), the river through Zurich.*
@@ -0,0 +1,16 @@
1
+ import type { Options } from './index.js';
2
+ /**
3
+ * Adapter for @speed-highlight/core. Each language loads as its own small chunk the first time it is needed,
4
+ * so a reply without code never downloads the highlighter. Install the peer dependency yourself.
5
+ * Very large blocks and very long lines are left as plain text, because the highlighter is slow on very long
6
+ * lines (seconds for a single 16 KB line), which would freeze the page. Tune the limits with `speedHighlight({ maxChars, maxLine })`.
7
+ *
8
+ * Also load one of the highlighter's theme stylesheets, for example `@speed-highlight/core/themes/default.css`: without a
9
+ * theme the code stays uncolored, and the theme only adds token colors (limmat keeps its own frame when `limmat/style.css` is loaded).
10
+ * @example
11
+ * createRenderer(el, { highlight: speedHighlight() });
12
+ */
13
+ export declare function speedHighlight({ maxChars, maxLine }?: {
14
+ maxChars?: number | undefined;
15
+ maxLine?: number | undefined;
16
+ }): NonNullable<Options['highlight']>;
@@ -0,0 +1,12 @@
1
+ // src/highlight.ts
2
+ function speedHighlight({ maxChars = 4096, maxLine = 300 } = {}) {
3
+ return async (el, code, lang) => {
4
+ if (code.length > maxChars || new RegExp(`[^\\n]{${maxLine + 1}}`).test(code)) return;
5
+ if (lang && !/^[\w+#-]{1,20}$/.test(lang)) return;
6
+ const { highlightElement } = await import("@speed-highlight/core");
7
+ await highlightElement(el, lang || void 0);
8
+ };
9
+ }
10
+ export {
11
+ speedHighlight
12
+ };
@@ -0,0 +1,59 @@
1
+ export interface Options {
2
+ /** Called when a rendered link is clicked. Return true if you handled it: limmat then calls preventDefault. If it throws, the error reaches window.onerror and the link behaves normally. */
3
+ onLinkClick?: (href: string, event: MouseEvent) => boolean | void;
4
+ /** Site-relative paths ('/research/x/') become links only if this returns true. Default: every path is a link. A throw counts as false. It gets the raw path including any query and hash, and may be called more than once per link while the reply streams. Check the whole path, not just a prefix: '/research/../admin' starts with '/research/'. */
5
+ isInternalPath?: (path: string) => boolean;
6
+ /** Protocols that may become links, with or without the colon and in any case. Default ['https', 'http', 'mailto']. Everything else renders as plain text. */
7
+ allowedProtocols?: string[];
8
+ /** Open http and https links in a new tab with rel="noopener noreferrer". Default true. false adds neither attribute, so links open in the same tab. */
9
+ externalLinksNewTab?: boolean;
10
+ /**
11
+ * Safe HTML tags written without attributes (b, strong, i, em, u, s, del, ins, mark, small, kbd, sub, sup) become elements. Default true.
12
+ * false shows them as text. An array narrows the list, and names outside the built-in list are ignored. A tag with any attribute, and every other tag, stays text. <br> always works.
13
+ * The list also holds `details`, which turns on collapsible blocks (<details>, an optional <summary> line, content, </details>, each tag alone on its line). Leave it out of an array to turn them off.
14
+ */
15
+ html?: boolean | string[];
16
+ /**
17
+ * Images. Default true: `![alt](url)` becomes an <img> when the URL passes the same checks as a link, limited to http, https, and site paths.
18
+ * An array of origins ('https://cdn.example.com') loads only from those, and site paths still work. false renders the alt text only.
19
+ * An image loads as soon as it renders, with no click, so a hostile reply can use one to send data to a server it controls. If that matters, pass an origin list or false, or set a CSP img-src.
20
+ */
21
+ images?: boolean | string[];
22
+ /** Called once when a code fence closes (or at end()). Receives the <code> element, its text, and the language. A throw or rejection is ignored and the plain text stays. */
23
+ highlight?: (el: HTMLElement, code: string, lang: string) => void | Promise<void>;
24
+ /** Minimum ms between re-renders of the open block. Default 50. 0 renders on every write. Non-finite values use the default. */
25
+ throttleMs?: number;
26
+ /** Prefix for every generated class. Default 'limmat'. The bundled style.css only styles the default prefix. */
27
+ classPrefix?: string;
28
+ /** Visible and accessible text, for translation. Defaults: copy 'Copy', copied 'Copied', table 'Table', done 'Completed', todo 'Not completed'. */
29
+ labels?: {
30
+ copy?: string;
31
+ copied?: string;
32
+ table?: string;
33
+ done?: string;
34
+ todo?: string;
35
+ };
36
+ }
37
+ /** The type of the `highlight` option, for adapters. */
38
+ export type Highlighter = NonNullable<Options['highlight']>;
39
+ export interface Renderer {
40
+ /** Append markdown. Chunks may split anywhere. Ignored after end() until reset(), and after destroy(). */
41
+ write(chunk: string): void;
42
+ /** Finish the message: unfinished constructs become literal text, code blocks are highlighted. Safe to call twice. */
43
+ end(): void;
44
+ /** Clear the container and start a new message with the same options. */
45
+ reset(): void;
46
+ /** Stop timers and remove the click listener. The rendered DOM stays. A pending throttled render is dropped. */
47
+ destroy(): void;
48
+ }
49
+ /**
50
+ * Render streaming markdown into `container`, which is emptied first. Use one renderer per message, and call `destroy()` when the element goes away.
51
+ * The container has no live region, because announcing every chunk is noisy: to have the finished reply announced, set
52
+ * `aria-busy` on your own element while streaming, or announce once after `end()`. The Copy button names the language,
53
+ * tables and code blocks are keyboard-scrollable, task checkboxes have names, and the copy result goes to a polite status element.
54
+ * @example
55
+ * const r = createRenderer(el);
56
+ * for await (const chunk of stream) r.write(chunk);
57
+ * r.end();
58
+ */
59
+ export declare function createRenderer(container: HTMLElement, options?: Options): Renderer;