@lightblues/jig 0.0.8 → 0.0.10

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.
@@ -0,0 +1,169 @@
1
+ // One markdown-it configuration for server and client: the same HTML while streaming and when finished, safe for
2
+ // innerHTML. Only `markdown-it` is imported; KaTeX, texmath, the CJK rule and a highlighter are injected by the host,
3
+ // so a host that does not use one does not install it, and no bundler has to resolve a missing optional peer.
4
+ import MarkdownIt from 'markdown-it';
5
+ import { closeOpenMarkdown } from "./close.js";
6
+ export { closeOpenMarkdown };
7
+ /** Longest inline `$…$` read as math. texmath's own rule has no bound, so a long line of `$a ` is quadratic. */
8
+ export const MAX_INLINE_MATH = 1000;
9
+ export const DEFAULT_REL = 'noopener noreferrer nofollow';
10
+ const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
11
+ const NEVER = new Set(['javascript', 'vbscript', 'file', 'data']);
12
+ const RASTER = /^data:image\/(?:png|gif|jpe?g|webp);/i;
13
+ /** Is `url` (as markdown-it normalized it) allowed as a link or an image source? */
14
+ export function urlAllowed(url, kind, allow) {
15
+ // As the URL parser reads it: leading/trailing C0 controls and spaces dropped, tabs and newlines removed anywhere.
16
+ const u = url.replace(/^[\x00-\x20]+|[\x00-\x20]+$/g, '').replace(/[\t\n\r]/g, '');
17
+ const scheme = SCHEME.exec(u)?.[1]?.toLowerCase();
18
+ if (scheme && NEVER.has(scheme) && !(kind === 'image' && scheme === 'data' && RASTER.test(u) && allow?.(u, kind) === true))
19
+ return false;
20
+ const host = allow?.(u, kind);
21
+ if (host !== undefined)
22
+ return host;
23
+ if (!scheme)
24
+ return true;
25
+ return scheme === 'http' || scheme === 'https' || (kind === 'link' && scheme === 'mailto');
26
+ }
27
+ /** An absolute URL, or one a browser reads as another host (`//x`, `/\x`, `\\x`). */
28
+ const external = (url) => SCHEME.test(url) || /^[/\\]{2}/.test(url.trim());
29
+ export function createMarkdown(opts = {}) {
30
+ const md = new MarkdownIt({
31
+ html: opts.trustedHtml === true,
32
+ linkify: opts.linkify ?? true,
33
+ breaks: opts.breaks ?? true,
34
+ typographer: false,
35
+ });
36
+ const allow = opts.links?.allow;
37
+ const images = opts.images === true;
38
+ const rel = opts.links?.rel ?? DEFAULT_REL;
39
+ const target = opts.links?.target;
40
+ // Parse time: a refused URL is not a link at all (its source stays as text).
41
+ md.validateLink = (url) => urlAllowed(url, 'link', allow) || (images && urlAllowed(url, 'image', allow));
42
+ if (opts.cjk)
43
+ md.use(opts.cjk);
44
+ if (opts.math)
45
+ useMath(md, opts.math);
46
+ if (opts.highlight) {
47
+ const hl = opts.highlight;
48
+ md.set({ highlight: (code, lang) => { try {
49
+ return lang ? hl(code, lang) || '' : '';
50
+ }
51
+ catch {
52
+ return '';
53
+ } } });
54
+ }
55
+ // Render time, again: a token a plugin made, or an href a plugin rewrote, meets the same rules.
56
+ const linkOpen = md.renderer.rules.link_open;
57
+ md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
58
+ const t = tokens[idx];
59
+ const a = t.attrGet('href');
60
+ const href = a === null ? null : String(a);
61
+ if (href === null || !urlAllowed(href, 'link', allow))
62
+ dropAttr(t, 'href');
63
+ else if (external(href)) {
64
+ if (target)
65
+ t.attrSet('target', target);
66
+ if (rel)
67
+ t.attrSet('rel', rel);
68
+ }
69
+ return linkOpen ? linkOpen(tokens, idx, options, env, self) : self.renderToken(tokens, idx, options);
70
+ };
71
+ const image = md.renderer.rules.image;
72
+ md.renderer.rules.image = (tokens, idx, options, env, self) => {
73
+ const t = tokens[idx];
74
+ const src = String(t.attrGet('src') ?? '');
75
+ if (!images || !urlAllowed(src, 'image', allow))
76
+ return md.utils.escapeHtml(self.renderInlineAsText(t.children ?? [], options, env));
77
+ return image(tokens, idx, options, env, self);
78
+ };
79
+ for (const p of opts.plugins ?? []) {
80
+ if (Array.isArray(p)) {
81
+ const [plugin, ...params] = p;
82
+ md.use(plugin, ...params);
83
+ }
84
+ else
85
+ md.use(p);
86
+ }
87
+ const strip = opts.streamingStrip;
88
+ return {
89
+ md,
90
+ render: (text, r = {}) => md.render(r.streaming ? closeOpenMarkdown(text, strip ? { strip } : {}) : text),
91
+ };
92
+ }
93
+ /** Formulas kept per instance. While streaming, every frame re-renders the same formulas; KaTeX is ~80% of the cost. */
94
+ export const MATH_CACHE_SIZE = 500;
95
+ /** Default `math.maxLength`. */
96
+ export const MAX_MATH_LENGTH = 5000;
97
+ /**
98
+ * texmath parses `$…$` / `$$…$$`; the HTML is ours. texmath keeps its KaTeX engine module-wide (the first `use` wins),
99
+ * so another instance's options (a host's `trust: true`) would reach ours, and it puts KaTeX's output through
100
+ * `String.replace`, where a `$&` in it is a replacement pattern. Our rules render with this instance's KaTeX and options.
101
+ */
102
+ function useMath(md, math) {
103
+ const { katex, texmath } = math;
104
+ const host = math.katexOptions ?? {};
105
+ const maxExpand = Number(host.maxExpand);
106
+ const maxSize = Number(host.maxSize);
107
+ const maxLength = math.maxLength ?? MAX_MATH_LENGTH;
108
+ // `strict: "ignore"`: KaTeX's default warns on the console for every non-LaTeX input, which is user-controlled.
109
+ const base = {
110
+ throwOnError: false, strict: 'ignore', ...host,
111
+ trust: false,
112
+ maxExpand: maxExpand >= 0 && maxExpand < 1000 ? maxExpand : 1000,
113
+ maxSize: maxSize >= 0 && maxSize < 50 ? maxSize : 50,
114
+ };
115
+ const macros = (host.macros ?? {});
116
+ const cache = new Map();
117
+ const tex = (src, displayMode) => {
118
+ const key = (displayMode ? 'D' : 'I') + src;
119
+ if (src.length > maxLength)
120
+ return `<code class="math-source">${md.utils.escapeHtml(src)}</code>`;
121
+ let html = cache.get(key);
122
+ if (html !== undefined) {
123
+ cache.delete(key);
124
+ cache.set(key, html);
125
+ return html;
126
+ }
127
+ try {
128
+ // A fresh copy of the macros each time: `\gdef` in one formula must not reach the next render (or another user).
129
+ html = katex.renderToString(src, { ...base, macros: { ...macros }, displayMode });
130
+ }
131
+ catch (err) {
132
+ html = md.utils.escapeHtml(`${src}:${err?.message ?? err}`);
133
+ }
134
+ cache.set(key, html);
135
+ if (cache.size > MATH_CACHE_SIZE)
136
+ cache.delete(cache.keys().next().value);
137
+ return html;
138
+ };
139
+ md.use(texmath, { engine: katex, delimiters: 'dollars', katexOptions: { ...base } });
140
+ boundInlineMath(md, texmath);
141
+ const r = md.renderer.rules;
142
+ r.math_inline = (t, i) => `<eq>${tex(t[i].content, false)}</eq>`;
143
+ r.math_inline_double = (t, i) => `<section><eqn>${tex(t[i].content, true)}</eqn></section>`;
144
+ r.math_block = (t, i) => `<section><eqn>${tex(t[i].content, true)}</eqn></section>`;
145
+ r.math_block_eqno = (t, i) => `<section class="eqno"><eqn>${tex(t[i].content, true)}</eqn><span>(${md.utils.escapeHtml(t[i].info)})</span></section>`;
146
+ }
147
+ /**
148
+ * Replace texmath's `math_inline` rule with the same rule on a bounded pattern: `\S.*?[^\s\\]` scans to the end of
149
+ * the line for every `$` that does not close, so 90k characters of `$a ` took 1.3 s; bounded, 300k take ~0.3 s.
150
+ */
151
+ function boundInlineMath(md, texmath) {
152
+ const rule = texmath.rules?.dollars?.inline.find((r) => r.name === 'math_inline');
153
+ if (!rule || !texmath.inline || rule.rex.source !== '\\$((?:[^\\s\\\\])|(?:\\S.*?[^\\s\\\\]))\\$') {
154
+ throw new Error('markdown-it-texmath: unexpected version; jig/markdown is tested with 1.0.0');
155
+ }
156
+ const rex = new RegExp(`\\$((?:[^\\s\\\\])|(?:\\S.{0,${MAX_INLINE_MATH - 2}}?[^\\s\\\\]))\\$`, 'gy');
157
+ md.inline.ruler.at('math_inline', texmath.inline({ ...rule, rex }));
158
+ }
159
+ function dropAttr(t, name) {
160
+ if (t.attrs)
161
+ t.attrs = t.attrs.filter(([k]) => k !== name);
162
+ }
163
+ /**
164
+ * A `highlight` function from highlight.js (pass `highlight.js/lib/core` with the languages you register; the full
165
+ * bundle is ~314 KB gzipped). An unknown language stays escaped plain code.
166
+ */
167
+ export function hljsHighlighter(hljs) {
168
+ return (code, lang) => (hljs.getLanguage(lang) ? hljs.highlight(code, { language: lang, ignoreIllegals: true }).value : '');
169
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lightblues/jig",
3
- "version": "0.0.8",
4
- "description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, and more as they prove reusable.",
3
+ "version": "0.0.10",
4
+ "description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, one markdown renderer, and more as they prove reusable.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Lightblues",
@@ -40,6 +40,10 @@
40
40
  "types": "./dist/agent-pi/index.d.ts",
41
41
  "default": "./dist/agent-pi/index.js"
42
42
  },
43
+ "./markdown": {
44
+ "types": "./dist/markdown/index.d.ts",
45
+ "default": "./dist/markdown/index.js"
46
+ },
43
47
  "./package.json": "./package.json"
44
48
  },
45
49
  "scripts": {
@@ -56,14 +60,19 @@
56
60
  "@earendil-works/pi-coding-agent": "1.4.0",
57
61
  "@getpaseo/client": "0.16.1",
58
62
  "@types/node": "^24.0.0",
63
+ "@types/pg": "8.23.1",
59
64
  "@types/react": "19.3.0",
60
65
  "@types/react-test-renderer": "19.3.1",
61
66
  "esbuild": "0.28.2",
62
- "react": "19.3.1",
63
- "react-test-renderer": "19.3.1",
64
- "@types/pg": "8.23.1",
67
+ "highlight.js": "11.12.0",
68
+ "katex": "0.19.1",
69
+ "markdown-it": "15.0.3",
70
+ "markdown-it-cjk-friendly": "3.0.0",
71
+ "markdown-it-texmath": "1.0.0",
65
72
  "pg": "8.23.1",
66
73
  "postgres": "3.4.9",
74
+ "react": "19.3.1",
75
+ "react-test-renderer": "19.3.1",
67
76
  "typescript": "^5.9.0"
68
77
  },
69
78
  "peerDependencies": {
@@ -72,6 +81,11 @@
72
81
  "@earendil-works/pi-ai": "~1.4.0",
73
82
  "@earendil-works/pi-coding-agent": "~1.4.0",
74
83
  "@getpaseo/client": "0.16.1",
84
+ "highlight.js": "^11.0.0",
85
+ "katex": ">=0.16.21",
86
+ "markdown-it": "^15.0.0",
87
+ "markdown-it-cjk-friendly": "^3.0.0",
88
+ "markdown-it-texmath": "~1.0.0",
75
89
  "react": ">=18"
76
90
  },
77
91
  "peerDependenciesMeta": {
@@ -90,6 +104,21 @@
90
104
  "@getpaseo/client": {
91
105
  "optional": true
92
106
  },
107
+ "highlight.js": {
108
+ "optional": true
109
+ },
110
+ "katex": {
111
+ "optional": true
112
+ },
113
+ "markdown-it": {
114
+ "optional": true
115
+ },
116
+ "markdown-it-cjk-friendly": {
117
+ "optional": true
118
+ },
119
+ "markdown-it-texmath": {
120
+ "optional": true
121
+ },
93
122
  "react": {
94
123
  "optional": true
95
124
  }