@cmodjs/core 5.9.0 → 5.11.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/runtime/web.js ADDED
@@ -0,0 +1,381 @@
1
+ import { fromMarkdown, gfm, gfmFromMarkdown } from '../vendor-markdown.js';
2
+ const elementKey = '$cmodElement';
3
+ const handlerKey = '$cmodHandler';
4
+ const themeKeys = new Set(['text', 'inverseText', 'inactive', 'subtle', 'suggestion', 'remember', 'success', 'error', 'warning', 'merged', 'claude', 'permission', 'planMode', 'autoAccept', 'promptBorder', 'bashBorder', 'ide', 'diffAdded', 'diffRemoved', 'diffAddedDimmed', 'diffRemovedDimmed', 'diffAddedWord', 'diffRemovedWord']);
5
+ const spaceSteps = { xs: 0.25, sm: 0.5, md: 1, lg: 1.5, xl: 2 };
6
+ const flexValues = {
7
+ flexDirection: new Set(['row', 'column', 'row-reverse', 'column-reverse']),
8
+ flexWrap: new Set(['nowrap', 'wrap', 'wrap-reverse']),
9
+ alignItems: new Set(['flex-start', 'center', 'flex-end', 'stretch']),
10
+ alignSelf: new Set(['flex-start', 'center', 'flex-end', 'auto']),
11
+ justifyContent: new Set(['flex-start', 'center', 'flex-end', 'space-between', 'space-around', 'space-evenly']),
12
+ };
13
+ const cssNames = { flexDirection: 'flex-direction', flexWrap: 'flex-wrap', alignItems: 'align-items', alignSelf: 'align-self', justifyContent: 'justify-content' };
14
+ const sides = [
15
+ ['Top', 'Y', 'down'],
16
+ ['Right', 'X', 'across'],
17
+ ['Bottom', 'Y', 'down'],
18
+ ['Left', 'X', 'across'],
19
+ ];
20
+ const linkSchemes = /^(https?:|mailto:|file:)/i;
21
+ const hotkeys = /^[0-9a-z]$/;
22
+ const base64 = /^[A-Za-z0-9+/]*={0,2}$/;
23
+ const markdownOptions = { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] };
24
+ export function htmlOf(tree) {
25
+ const drawing = { rules: [], groups: new Map(), scopes: 0, scope: undefined };
26
+ const body = nodeHtml(tree, drawing);
27
+ return drawing.rules.length === 0 ? body : `<style>${drawing.rules.join('')}</style>${body}`;
28
+ }
29
+ function nodeHtml(tree, drawing) {
30
+ if (tree === null || tree === undefined || typeof tree === 'boolean')
31
+ return '';
32
+ if (typeof tree === 'string')
33
+ return escaped(tree);
34
+ if (typeof tree === 'number')
35
+ return String(tree);
36
+ if (Array.isArray(tree))
37
+ return tree.map((each) => nodeHtml(each, drawing)).join('');
38
+ if (typeof tree !== 'object')
39
+ return '';
40
+ const fields = tree;
41
+ const name = fields[elementKey];
42
+ if (typeof name !== 'string')
43
+ return '';
44
+ const props = (typeof fields['props'] === 'object' && fields['props'] !== null ? fields['props'] : {});
45
+ const draw = elements[name];
46
+ return draw === undefined ? `<span class="gap">${escaped(`The browser draws no ${name}.`)}</span>` : draw(props, drawing);
47
+ }
48
+ const elements = {
49
+ Box: (props, drawing) => {
50
+ const key = keyOf(props);
51
+ const own = key === undefined ? undefined : `s${drawing.scopes++}`;
52
+ const outer = drawing.scope;
53
+ const hover = hoverClasses(props['hover'], boxHover(props), drawing, own ?? outer);
54
+ const classes = ['b', ...(typeof props['borderStyle'] === 'string' ? ['bordered'] : []), ...(own === undefined ? [] : [own]), ...hover];
55
+ drawing.scope = own ?? outer;
56
+ const children = nodeHtml(props['children'], drawing);
57
+ drawing.scope = outer;
58
+ return `<div class="${classes.join(' ')}"${attribute('data-key', key)}${attribute('style', boxStyle(props))}>${children}</div>`;
59
+ },
60
+ Text: (props, drawing) => {
61
+ const hover = hoverClasses(props['hover'], textHover(props), drawing, drawing.scope);
62
+ return `<span class="${['t', ...textClasses(props), ...hover].join(' ')}"${attribute('style', textStyle(props))}${attribute('dir', props['dir'] === 'rtl' || props['dir'] === 'ltr' ? props['dir'] : undefined)}>${nodeHtml(props['children'], drawing)}</span>`;
63
+ },
64
+ Button: (props, drawing) => {
65
+ const label = typeof props['label'] === 'string' ? props['label'] : undefined;
66
+ const drawn = nodeHtml(props['children'], drawing);
67
+ const shown = drawn === '' ? escaped(label ?? '') : drawn;
68
+ const hotkey = typeof props['hotkey'] === 'string' && hotkeys.test(props['hotkey']) ? props['hotkey'] : undefined;
69
+ const prefix = props['plain'] === true && hotkey !== undefined ? `<span class="hotkey">${hotkey}</span>: ` : '';
70
+ const hover = hoverClasses(props['hover'], textHover({}), drawing, drawing.scope);
71
+ const classes = ['button', ...(props['plain'] === true ? ['plain'] : props['variant'] === 'primary' ? ['primary'] : []), ...(props['dimColor'] === true ? ['dim'] : []), ...hover];
72
+ const key = keyOf(props) ?? label ?? (typeof props['children'] === 'string' ? props['children'] : undefined);
73
+ return `<button type="button" class="${classes.join(' ')}"${attribute('aria-label', drawn === '' ? undefined : label)}${attribute('data-key', key)}${handlerAttribute('data-press', props['onPress'])}${attribute('data-hotkey', hotkey)}${props['autoFocus'] === true ? ' autofocus' : ''}>${prefix}${shown}</button>`;
74
+ },
75
+ Link: (props, drawing) => {
76
+ const href = typeof props['href'] === 'string' ? props['href'] : '';
77
+ const drawn = nodeHtml(props['children'], drawing);
78
+ const text = drawn === '' ? escaped(typeof props['label'] === 'string' ? props['label'] : href) : drawn;
79
+ return linkSchemes.test(href) ? `<a class="link" href="${escaped(href)}" target="_blank" rel="noopener noreferrer">${text}</a>` : `<span class="t">${text}</span>`;
80
+ },
81
+ Code: (props) => codeHtml(typeof props['source'] === 'string' ? props['source'] : '', typeof props['startLine'] === 'number' ? props['startLine'] : undefined, props['format'] === 'diff', props['wrap'] === 'truncate-end'),
82
+ Markdown: (props) => {
83
+ const text = typeof props['text'] === 'string' ? props['text'] : '';
84
+ const pressable = Array.isArray(props['pressableLinks']) ? props['pressableLinks'].filter((href) => typeof href === 'string') : undefined;
85
+ const blocks = fromMarkdown(text, markdownOptions).children.map((node) => blockHtml(node, { link: handlerOf(props['onLinkPress']), pressable })).join('');
86
+ return `<div class="${props['dimColor'] === true ? 'markdown dim' : 'markdown'}"${attribute('data-key', keyOf(props))}>${blocks}</div>`;
87
+ },
88
+ Input: (props) => {
89
+ const value = typeof props['value'] === 'string' ? props['value'] : '';
90
+ const rows = typeof props['rows'] === 'number' && props['rows'] > 1 ? Math.floor(props['rows']) : 1;
91
+ const shared = `${attribute('data-key', keyOf(props))}${handlerAttribute('data-input', props['onInput'])}${handlerAttribute('data-submit', props['onSubmit'])}${attribute('data-value', value)}${attribute('placeholder', typeof props['placeholder'] === 'string' ? props['placeholder'] : undefined)}${props['autoFocus'] === true ? ' autofocus' : ''}`;
92
+ const field = rows > 1 ? `<textarea class="input" rows="${rows}"${shared}>${escaped(value)}</textarea>` : `<input type="text" class="input"${shared} value="${escaped(value)}">`;
93
+ const submitLabel = typeof props['submitLabel'] === 'string' ? props['submitLabel'] : 'submit';
94
+ return `<label class="field">${labelHtml(props['label'])}${field}<span class="hint">enter: ${escaped(submitLabel)}</span></label>`;
95
+ },
96
+ Select: (props) => {
97
+ const value = typeof props['value'] === 'string' ? props['value'] : undefined;
98
+ const options = (Array.isArray(props['options']) ? props['options'] : []).flatMap((option) => {
99
+ const each = option;
100
+ if (typeof each['value'] !== 'string')
101
+ return [];
102
+ const label = typeof each['label'] === 'string' ? each['label'] : each['value'];
103
+ return [`<option value="${escaped(each['value'])}"${each['value'] === value ? ' selected' : ''}>${escaped(label)}</option>`];
104
+ });
105
+ return `<label class="field">${labelHtml(props['label'])}<select class="select"${attribute('data-key', keyOf(props))}${handlerAttribute('data-select', props['onSelect'])}${attribute('data-value', value)}${props['autoFocus'] === true ? ' autofocus' : ''}>${options.join('')}</select></label>`;
106
+ },
107
+ Image: (props) => {
108
+ const source = props['source'];
109
+ const alt = typeof props['alt'] === 'string' ? props['alt'] : '';
110
+ const size = attribute('style', `width:${across(numberOr(props['columns'], 1))};height:${down(numberOr(props['rows'], 1))}`);
111
+ if (typeof source?.['png'] === 'string' && base64.test(source['png']))
112
+ return `<img class="image" alt="${escaped(alt)}" src="data:image/png;base64,${source['png']}"${size}>`;
113
+ const [width, height] = [source?.['width'], source?.['height']];
114
+ if (typeof source?.['rgba'] === 'string' && base64.test(source['rgba']) && Number.isInteger(width) && Number.isInteger(height))
115
+ return `<canvas class="image" width="${width}" height="${height}" data-rgba="${source['rgba']}"${attribute('aria-label', alt)}${size}></canvas>`;
116
+ return `<span class="t dim"${size}>${escaped(alt)}</span>`;
117
+ },
118
+ Svg: (props) => {
119
+ const source = typeof props['source'] === 'string' ? props['source'] : '';
120
+ const size = [typeof props['width'] === 'number' ? `width:${props['width']}px` : '', typeof props['height'] === 'number' ? `height:${props['height']}px` : ''].filter((each) => each !== '').join(';');
121
+ return `<img class="svg" alt="${escaped(typeof props['alt'] === 'string' ? props['alt'] : '')}" src="data:image/svg+xml,${encodeURIComponent(source)}"${attribute('style', size === '' ? undefined : size)}>`;
122
+ },
123
+ Raster: (props) => rasterHtml(typeof props['cells'] === 'string' ? props['cells'] : '', numberOr(props['columns'], 1)),
124
+ };
125
+ function escaped(text) {
126
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
127
+ }
128
+ function attribute(name, value) {
129
+ return value === undefined || value === '' ? '' : ` ${name}="${escaped(value)}"`;
130
+ }
131
+ function handlerOf(value) {
132
+ const marker = typeof value === 'object' && value !== null ? value[handlerKey] : undefined;
133
+ return typeof marker === 'number' ? marker : undefined;
134
+ }
135
+ function handlerAttribute(name, value) {
136
+ const handler = handlerOf(value);
137
+ return handler === undefined ? '' : ` ${name}="${handler}"`;
138
+ }
139
+ function keyOf(props) {
140
+ return typeof props['key'] === 'string' ? props['key'] : undefined;
141
+ }
142
+ function numberOr(value, fallback) {
143
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
144
+ }
145
+ function across(cells) {
146
+ return `${cells}ch`;
147
+ }
148
+ function down(cells) {
149
+ return `calc(${cells} * var(--row))`;
150
+ }
151
+ function cellsOf(value) {
152
+ if (typeof value === 'number' && Number.isFinite(value))
153
+ return value;
154
+ return typeof value === 'string' ? spaceSteps[value] : undefined;
155
+ }
156
+ function sizeOf(value, axis) {
157
+ if (typeof value === 'string' && /^\d+(\.\d+)?%$/.test(value))
158
+ return value;
159
+ const cells = typeof value === 'number' && Number.isFinite(value) ? value : undefined;
160
+ return cells === undefined ? undefined : axis === 'across' ? across(cells) : down(cells);
161
+ }
162
+ function colorOf(value) {
163
+ if (typeof value !== 'string')
164
+ return undefined;
165
+ if (themeKeys.has(value) || /^[a-z]+[A-Z][A-Za-z]*$/.test(value))
166
+ return `var(--${value})`;
167
+ return /^#[0-9a-f]{3,8}$/i.test(value) || /^(rgb|hsl)a?\([\d\s.,%]+\)$/i.test(value) || /^[a-z]+$/.test(value) ? value : undefined;
168
+ }
169
+ function dimmed(color) {
170
+ return `color-mix(in srgb, ${color} 55%, transparent)`;
171
+ }
172
+ function css(declarations, suffix = '') {
173
+ return declarations.flatMap(([name, value]) => (value === undefined ? [] : [`${name}:${value}${suffix}`])).join(';');
174
+ }
175
+ function hoverClasses(hover, declarations, drawing, scope) {
176
+ if (typeof hover !== 'object' || hover === null)
177
+ return [];
178
+ const lit = hover;
179
+ const rule = css(declarations(lit), ' !important');
180
+ const group = typeof lit['scope'] === 'string' ? (drawing.groups.get(lit['scope']) ?? `g${drawing.groups.size}`) : undefined;
181
+ if (rule === '' || (group === undefined && scope === undefined))
182
+ return [];
183
+ const name = `h${drawing.rules.length}`;
184
+ if (group === undefined) {
185
+ drawing.rules.push(`.${scope}:hover .${name},.${scope}.${name}:hover{${rule}}`);
186
+ return [name];
187
+ }
188
+ drawing.groups.set(lit['scope'], group);
189
+ drawing.rules.push(`:root:has(.${group}:hover) .${name}{${rule}}`);
190
+ return [name, group];
191
+ }
192
+ function boxHover(props) {
193
+ return (hover) => {
194
+ const offset = (side, axis) => (props['position'] === 'absolute' ? sizeOf(hover[side], axis) : undefined);
195
+ const color = colorOf(hover['borderColor'] ?? props['borderColor']) ?? 'currentColor';
196
+ const isBorderLit = typeof props['borderStyle'] === 'string' && (hover['borderColor'] !== undefined || hover['borderDimColor'] !== undefined);
197
+ return [
198
+ ['display', hover['display'] === 'flex' ? 'flex' : undefined],
199
+ ['background', colorOf(hover['backgroundColor'])],
200
+ ['--border-color', isBorderLit ? ((hover['borderDimColor'] ?? props['borderDimColor']) === true ? dimmed(color) : color) : undefined],
201
+ ['top', offset('top', 'down')],
202
+ ['left', offset('left', 'across')],
203
+ ['right', offset('right', 'across')],
204
+ ['bottom', offset('bottom', 'down')],
205
+ ];
206
+ };
207
+ }
208
+ function textHover(props) {
209
+ return (hover) => textDeclarations({ ...props, ...hover });
210
+ }
211
+ function boxStyle(props) {
212
+ const style = [];
213
+ const add = (name, value) => void style.push([name, value]);
214
+ for (const [prop, allowed] of Object.entries(flexValues))
215
+ add(cssNames[prop] ?? prop, typeof props[prop] === 'string' && allowed.has(props[prop]) ? props[prop] : undefined);
216
+ add('flex-grow', typeof props['flexGrow'] === 'number' ? String(props['flexGrow']) : undefined);
217
+ add('flex-shrink', typeof props['flexShrink'] === 'number' ? String(props['flexShrink']) : undefined);
218
+ const columnGap = cellsOf(props['columnGap'] ?? props['gap']);
219
+ const rowGap = cellsOf(props['rowGap'] ?? props['gap']);
220
+ add('column-gap', columnGap === undefined ? undefined : across(columnGap));
221
+ add('row-gap', rowGap === undefined ? undefined : down(rowGap));
222
+ add('width', sizeOf(props['width'], 'across'));
223
+ add('height', sizeOf(props['height'], 'down'));
224
+ add('min-width', sizeOf(props['minWidth'], 'across'));
225
+ add('min-height', sizeOf(props['minHeight'], 'down'));
226
+ const hasBorder = typeof props['borderStyle'] === 'string';
227
+ for (const [side, axis, unit] of sides) {
228
+ const margin = cellsOf(props[`margin${side}`] ?? props[`margin${axis}`] ?? props['margin']);
229
+ const padding = (cellsOf(props[`padding${side}`] ?? props[`padding${axis}`] ?? props['padding']) ?? 0) + (hasBorder ? 1 : 0);
230
+ add(`margin-${side.toLowerCase()}`, margin === undefined ? undefined : unit === 'across' ? across(margin) : down(margin));
231
+ if (padding > 0)
232
+ add(`padding-${side.toLowerCase()}`, unit === 'across' ? across(padding) : down(padding));
233
+ }
234
+ if (hasBorder) {
235
+ const color = colorOf(props['borderColor']) ?? 'currentColor';
236
+ add('--border-color', props['borderDimColor'] === true ? dimmed(color) : color);
237
+ add('--border-style', props['borderStyle'] === 'double' ? 'double' : props['borderStyle'] === 'classic' || props['borderStyle'] === 'dashed' ? 'dashed' : 'solid');
238
+ add('--border-radius', props['borderStyle'] === 'round' ? '0.5ch' : '0');
239
+ add('--border-width', props['borderStyle'] === 'bold' || props['borderStyle'] === 'double' ? '3px' : '1px');
240
+ }
241
+ add('background', colorOf(props['backgroundColor']));
242
+ add('overflow', props['overflow'] === 'hidden' ? 'hidden' : undefined);
243
+ add('display', props['display'] === 'none' ? 'none' : undefined);
244
+ if (props['position'] === 'absolute') {
245
+ add('position', 'absolute');
246
+ add('top', sizeOf(props['top'], 'down'));
247
+ add('bottom', sizeOf(props['bottom'], 'down'));
248
+ add('left', sizeOf(props['left'], 'across'));
249
+ add('right', sizeOf(props['right'], 'across'));
250
+ }
251
+ return css(style);
252
+ }
253
+ function textClasses(props) {
254
+ const wrap = props['wrap'];
255
+ const isCut = typeof wrap === 'string' && wrap !== 'wrap';
256
+ const size = props['size'];
257
+ return [...(isCut ? ['cut'] : []), ...(typeof size === 'string' && ['caption', 'footnote', 'heading', 'title'].includes(size) ? [`size-${size}`] : [])];
258
+ }
259
+ function textDeclarations(props) {
260
+ const color = colorOf(props['color']);
261
+ const background = colorOf(props['backgroundColor']);
262
+ const isDim = props['dimColor'] === true;
263
+ const foreground = color === undefined && !isDim ? undefined : isDim ? dimmed(color ?? 'var(--text)') : color;
264
+ const isInverse = props['inverse'] === true;
265
+ const weight = props['weight'];
266
+ const weights = { regular: '400', medium: '500', semibold: '600', bold: '700' };
267
+ const lines = [props['underline'] === true ? 'underline' : '', props['strikethrough'] === true ? 'line-through' : ''].filter((line) => line !== '');
268
+ return [
269
+ ['color', isInverse ? (background ?? 'var(--background)') : foreground],
270
+ ['background', isInverse ? (foreground ?? 'var(--text)') : background],
271
+ ['font-weight', typeof weight === 'string' && weights[weight] !== undefined ? weights[weight] : props['bold'] === true ? '700' : undefined],
272
+ ['font-style', props['italic'] === true ? 'italic' : undefined],
273
+ ['text-decoration', lines.length === 0 ? undefined : lines.join(' ')],
274
+ ['font-variant-numeric', props['tabular'] === true ? 'tabular-nums' : undefined],
275
+ ];
276
+ }
277
+ function textStyle(props) {
278
+ return css(textDeclarations(props));
279
+ }
280
+ function labelHtml(label) {
281
+ return typeof label === 'string' ? `<span class="label">${escaped(label)}</span>` : '';
282
+ }
283
+ function codeHtml(source, startLine, isDiff, isCut) {
284
+ const lines = source.split('\n');
285
+ const width = String((startLine ?? 1) + lines.length - 1).length;
286
+ const rows = lines.map((line, index) => {
287
+ const kind = !isDiff ? '' : line.startsWith('+') ? ' added' : line.startsWith('-') ? ' removed' : line.startsWith('@@') ? ' hunk' : '';
288
+ const gutter = startLine === undefined || isDiff ? '' : `<span class="gutter">${String(startLine + index).padStart(width)} </span>`;
289
+ return `<span class="line${kind}">${gutter}${escaped(line)}</span>`;
290
+ });
291
+ return `<pre class="${isCut ? 'code cut' : 'code'}">${rows.join('\n')}</pre>`;
292
+ }
293
+ function rasterHtml(cells, columns) {
294
+ if (cells.length % 4 !== 0 || !base64.test(cells))
295
+ return '<span class="gap">The browser draws no Raster whose cells are not base64.</span>';
296
+ const bytes = Uint8Array.from(atob(cells), (character) => character.charCodeAt(0));
297
+ const words = new DataView(bytes.buffer);
298
+ const colorFrom = (word) => (word === 0x01000000 ? undefined : `#${(word & 0xffffff).toString(16).padStart(6, '0')}`);
299
+ const rows = [];
300
+ let row = '';
301
+ for (let offset = 0, index = 0; offset + 12 <= bytes.length; offset += 12, index += 1) {
302
+ const glyph = String.fromCodePoint(words.getUint32(offset, true));
303
+ const style = [colorFrom(words.getUint32(offset + 4, true)), colorFrom(words.getUint32(offset + 8, true))];
304
+ const painted = [style[0] === undefined ? '' : `color:${style[0]}`, style[1] === undefined ? '' : `background:${style[1]}`].filter((each) => each !== '').join(';');
305
+ row += painted === '' ? escaped(glyph) : `<span style="${painted}">${escaped(glyph)}</span>`;
306
+ if ((index + 1) % Math.max(Math.floor(columns), 1) === 0) {
307
+ rows.push(row);
308
+ row = '';
309
+ }
310
+ }
311
+ if (row !== '')
312
+ rows.push(row);
313
+ return `<pre class="raster">${rows.join('\n')}</pre>`;
314
+ }
315
+ function linkHtml(href, inner, markdown) {
316
+ const isPressed = markdown.link !== undefined && (markdown.pressable === undefined || markdown.pressable.includes(href));
317
+ if (isPressed)
318
+ return `<a class="link" href="${escaped(href)}" data-link="${markdown.link}">${inner}</a>`;
319
+ return linkSchemes.test(href) ? `<a class="link" href="${escaped(href)}" target="_blank" rel="noopener noreferrer">${inner}</a>` : inner;
320
+ }
321
+ function inlineHtml(node, markdown) {
322
+ const inner = () => ('children' in node ? node.children.map((child) => inlineHtml(child, markdown)).join('') : '');
323
+ switch (node.type) {
324
+ case 'text':
325
+ return escaped(node.value);
326
+ case 'emphasis':
327
+ return `<em>${inner()}</em>`;
328
+ case 'strong':
329
+ return `<strong>${inner()}</strong>`;
330
+ case 'delete':
331
+ return `<del>${inner()}</del>`;
332
+ case 'inlineCode':
333
+ return `<code>${escaped(node.value)}</code>`;
334
+ case 'break':
335
+ return '<br>';
336
+ case 'link':
337
+ return linkHtml(node.url, inner(), markdown);
338
+ case 'image':
339
+ return linkHtml(node.url, escaped(node.alt ?? node.url), markdown);
340
+ case 'html':
341
+ return escaped(node.value);
342
+ default:
343
+ return inner();
344
+ }
345
+ }
346
+ function itemHtml(item, markdown) {
347
+ const check = item.checked === true ? '☑ ' : item.checked === false ? '☐ ' : '';
348
+ return `<li>${check}${item.children.map((child) => blockHtml(child, markdown)).join('')}</li>`;
349
+ }
350
+ function cellHtml(cell, tag, align, markdown) {
351
+ return `<${tag}${align === null || align === undefined ? '' : ` style="text-align:${align}"`}>${cell.children.map((child) => inlineHtml(child, markdown)).join('')}</${tag}>`;
352
+ }
353
+ function blockHtml(node, markdown) {
354
+ switch (node.type) {
355
+ case 'heading':
356
+ return `<h${node.depth}>${node.children.map((child) => inlineHtml(child, markdown)).join('')}</h${node.depth}>`;
357
+ case 'paragraph':
358
+ return `<p>${node.children.map((child) => inlineHtml(child, markdown)).join('')}</p>`;
359
+ case 'code':
360
+ return codeHtml(node.value, undefined, node.lang === 'diff', false);
361
+ case 'blockquote':
362
+ return `<blockquote>${node.children.map((child) => blockHtml(child, markdown)).join('')}</blockquote>`;
363
+ case 'list': {
364
+ const items = node.children.map((item) => itemHtml(item, markdown)).join('');
365
+ return node.ordered === true ? `<ol${node.start === null || node.start === undefined || node.start === 1 ? '' : ` start="${node.start}"`}>${items}</ol>` : `<ul>${items}</ul>`;
366
+ }
367
+ case 'table': {
368
+ const [head, ...body] = node.children;
369
+ const row = (cells, tag) => `<tr>${cells.map((cell, index) => cellHtml(cell, tag, node.align?.[index], markdown)).join('')}</tr>`;
370
+ return `<table>${head === undefined ? '' : `<thead>${row(head.children, 'th')}</thead>`}<tbody>${body.map((each) => row(each.children, 'td')).join('')}</tbody></table>`;
371
+ }
372
+ case 'thematicBreak':
373
+ return '<hr>';
374
+ case 'html':
375
+ return `<p>${escaped(node.value)}</p>`;
376
+ case 'listItem':
377
+ return itemHtml(node, markdown);
378
+ default:
379
+ return 'children' in node ? node.children.map((child) => blockHtml(child, markdown)).join('') : 'value' in node ? `<p>${escaped(String(node.value))}</p>` : '';
380
+ }
381
+ }
@@ -27,7 +27,7 @@ export function program(options: { readonly command: readonly string[]; readonly
27
27
  const { claude, report, spawnCmod, watches } = engineOf(mod)
28
28
  const [executable] = command
29
29
  if (executable === undefined) throw new Error(`${mod.name}: the program has no command. Name the program on PATH and its arguments, such as ['preview-server', '--port', '0'].`)
30
- if (isService) reserveName('program', basename(executable), `${mod.name}: the service ${executable} is already added. Give each isService program its own executable.`)
30
+ if (isService) for (const type of ['program', 'service']) reserveName(type, basename(executable), `${mod.name}: the service ${executable} is already added. Give each isService program its own executable.`)
31
31
  else if (singleInstance) reserveName('program', basename(executable), `${mod.name}: the single instance of ${executable} is already added. Give each singleInstance program its own executable.`)
32
32
  const isElected = singleInstance || isService
33
33
  const request = { argv: command, ...(environment === undefined ? {} : { env: environment }) }
package/src/records.ts CHANGED
@@ -272,6 +272,10 @@ export function servicePath(store: string, mod: string, executable: string): str
272
272
  return `${serviceFolder(store, mod)}/${checkedName(executable)}.json`
273
273
  }
274
274
 
275
+ export function serviceLogPath(store: string, mod: string, executable: string): string {
276
+ return `${serviceFolder(store, mod)}/${checkedName(executable)}.log`
277
+ }
278
+
275
279
  export type Links = { readonly marketplaces: Readonly<Record<string, string>>; readonly turnedOff: Readonly<Record<string, readonly string[]>> }
276
280
 
277
281
  export function parseLinks(value: unknown, path: string): Links {
@@ -300,12 +304,26 @@ export function preferencesPath(store: string): string {
300
304
  return `${store}/preferences.json`
301
305
  }
302
306
 
303
- export type Preferences = { readonly showsInstalledModErrors: boolean }
307
+ export type Preferences = { readonly showsInstalledModErrors: boolean; readonly servesWebUi: boolean }
308
+
309
+ const preferenceKeys = ['showsInstalledModErrors', 'servesWebUi'] as const satisfies readonly (keyof Preferences)[]
304
310
 
305
311
  export function parsePreferences(value: unknown, path: string): Preferences {
306
- if (value === undefined) return { showsInstalledModErrors: false }
307
- if (!isObject(value) || (value['showsInstalledModErrors'] !== undefined && typeof value['showsInstalledModErrors'] !== 'boolean')) throw new Error(`${path} is not a map of cmod's preferences to true or false. Delete it, and cmod uses its defaults.`)
308
- return { showsInstalledModErrors: value['showsInstalledModErrors'] === true }
312
+ if (value !== undefined && (!isObject(value) || preferenceKeys.some((key) => value[key] !== undefined && typeof value[key] !== 'boolean'))) throw new Error(`${path} is not a map of cmod's preferences to true or false. Delete it, and cmod uses its defaults.`)
313
+ const saved = isObject(value) ? value : {}
314
+ return { showsInstalledModErrors: saved['showsInstalledModErrors'] === true, servesWebUi: saved['servesWebUi'] === true }
315
+ }
316
+
317
+ export function webPath(store: string): string {
318
+ return `${store}/web.json`
319
+ }
320
+
321
+ export type WebUi = { readonly port: number }
322
+
323
+ export function parseWebUi(value: unknown, path: string): WebUi | undefined {
324
+ if (value === undefined) return undefined
325
+ if (!isObject(value) || !Number.isInteger(value['port'])) throw new Error(`${path} is not the web UI's port. Delete it, and cmod web serve writes it again.`)
326
+ return { port: value['port'] as number }
309
327
  }
310
328
 
311
329
  export type Contact = { readonly kind: 'github'; readonly repository: string } | { readonly kind: 'email'; readonly address: string }
@@ -377,9 +395,9 @@ function readHotkeys(hotkeys: unknown): Steps {
377
395
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
378
396
  }
379
397
 
380
- export const coreVersion = '5.9.0'
398
+ export const coreVersion = '5.11.0'
381
399
 
382
- export const oldestCmodVersion = '5.9.0'
400
+ export const oldestCmodVersion = '5.10.0'
383
401
 
384
402
  export function hotkeyCommand(mod: string, hotkey: string): string {
385
403
  return `${mod}--${hotkey}`
@@ -2,6 +2,7 @@ import type { HookStream, ProcessSpawnChunk, ProcessSpawnResult } from 'claude-c
2
2
  import type { Claude } from './claude.js'
3
3
  import type { Pages } from './pages.js'
4
4
  import type { Router } from './router.js'
5
+ import type { Subscription } from '../utils/subscription.js'
5
6
  import type { Failure } from './toaster.js'
6
7
  import type { ToolCalls } from './tool-calls.js'
7
8
  import type { Watches } from './watches.js'
@@ -16,6 +17,7 @@ export type Engine = {
16
17
  readonly answerInput: <Answer>(run: () => Promise<Answer>, passOn: () => Promise<unknown>) => Promise<Answer>
17
18
  readonly spawnCmod: (args: readonly string[], env?: Readonly<Record<string, string>>) => HookStream<ProcessSpawnChunk, ProcessSpawnResult>
18
19
  readonly watches: Watches
20
+ readonly onRedraw: (listener: () => void) => Subscription
19
21
  readonly widgets?: Widgets
20
22
  readonly pages?: Pages
21
23
  }
@@ -3,7 +3,7 @@ import type { Step } from '../installer.js'
3
3
 
4
4
  import type { Imports, Mod, ModDefinition, Reservation, SettingsFile, SettingsFileChange, SettingsFileChangeListener, Subscription, Timer as ModTimer } from '../mod.js'
5
5
  import type { Options, OptionValues } from '../options.js'
6
- import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVersion, pendingStepsMethod, parseEvent, programPath, readRecord, readSteps, recordPath, scriptsSha256, storeFolder, type ReadFile, type RunnerEvent, type Steps } from '../records.js'
6
+ import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVersion, pendingStepsMethod, parseEvent, programPath, readRecord, readSteps, recordPath, scriptsSha256, serviceFolder, storeFolder, type ReadFile, type RunnerEvent, type Steps } from '../records.js'
7
7
  import { homePrefix, ifMissing, relativePath } from '../utils/paths.js'
8
8
  import { firstLine, formatExit, messageOf } from '../utils/text.js'
9
9
  import type { Claude } from './claude.js'
@@ -16,7 +16,7 @@ import type { Device } from '../session/context/turn/device.js'
16
16
  import { keepEngine } from './engine.js'
17
17
  import { classicFailure, classicHook, userSkillHook, type Hook, type HookFields, type HookListener, type RoutedEvent } from './hooks.js'
18
18
  import type { PermissionRoutes } from './permission-check.js'
19
- import { cmodError, locatingPrograms, newestCmodVersion, readLines, spawnCmod, type Programs } from './programs.js'
19
+ import { cmodError, locatingPrograms, newestCmodVersion, readLines, runCmod, spawnCmod, type Programs } from './programs.js'
20
20
  import { createModFiles, resolvedPath, type Places } from './metadata.js'
21
21
  import { fitsOption } from '../options.js'
22
22
  import { createInstaller } from './installer.js'
@@ -733,7 +733,13 @@ export function createLifecycle<State extends object, Declared extends Options =
733
733
  async function createMod<State extends object, Declared extends Options>(definition: ModDefinition<State, string, Declared>, runtime: ModRuntime): Promise<ActiveMod<State, Declared>> {
734
734
  const { router, toaster } = runtime
735
735
  const report = (failure: Failure) => void toaster.fail(failure)
736
- const claude = answeringOwnCalls(withBareRefusals(runtime.claude), router)
736
+ const redraws = new Set<() => void>()
737
+ const calling = answeringOwnCalls(withBareRefusals(runtime.claude), router)
738
+ const invalidate: Claude['ui']['invalidate'] = (event) => {
739
+ calling.ui.invalidate(event)
740
+ if (event === 'ui.render') for (const redraw of redraws) redraw()
741
+ }
742
+ const claude: Claude = { ...calling, ui: { ...calling.ui, invalidate } }
737
743
  const added: string[] = []
738
744
  const announce = (feature: string) => {
739
745
  added.push(feature)
@@ -1090,6 +1096,10 @@ async function createMod<State extends object, Declared extends Options>(definit
1090
1096
  answerInput: area.answerInput,
1091
1097
  spawnCmod: (args, env) => spawnCmod(claude, args, session, env),
1092
1098
  watches,
1099
+ onRedraw(listener) {
1100
+ redraws.add(listener)
1101
+ return { remove: () => void redraws.delete(listener) }
1102
+ },
1093
1103
  ...(widgets === undefined ? {} : { widgets }),
1094
1104
  ...(pages === undefined ? {} : { pages }),
1095
1105
  })
@@ -1100,6 +1110,12 @@ async function createMod<State extends object, Declared extends Options>(definit
1100
1110
  names.add(key)
1101
1111
  return { remove: () => void names.delete(key) }
1102
1112
  }
1113
+ const removeUndeclaredServices = async () => {
1114
+ for (const { name } of await claude.fs.list(serviceFolder(runtime.store, definition.name)).catch(ifMissing([]))) {
1115
+ const program = name.endsWith('.json') ? name.slice(0, -'.json'.length) : undefined
1116
+ if (program !== undefined && !names.has(`service:${program}`)) await runCmod(claude, ['program', definition.name, '--remove-service', '--', program], session)
1117
+ }
1118
+ }
1103
1119
  await failsAs('its state did not load', () => modState.load())
1104
1120
  await failsAs('its options did not load', () => modOptions.load(root))
1105
1121
  const missing = modOptions.missing
@@ -1109,6 +1125,7 @@ async function createMod<State extends object, Declared extends Options>(definit
1109
1125
  api = apiOf(definition.name, returned)
1110
1126
  await failsAs('its open panes did not load', () => area.restorePanes())
1111
1127
  area.started()
1128
+ void removeUndeclaredServices().catch((error: unknown) => report({ id: 'program:services', message: 'Could not stop a service it no longer runs', error }))
1112
1129
  return { mod, added, imports, raise: client.raise, area }
1113
1130
  }
1114
1131