@aqian0/dsh-renderer 0.0.0-stage → 0.2.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/cordis.patch.yml +4 -0
  4. package/icon.svg +5 -0
  5. package/lib/client.js +789 -0
  6. package/lib/config.js +96 -0
  7. package/lib/host/artifact-skill.js +55 -0
  8. package/lib/host/artifact-tool.js +177 -0
  9. package/lib/host/media-bridge.js +102 -0
  10. package/lib/index.js +120 -0
  11. package/lib/shared/artifact-stream.js +293 -0
  12. package/lib/shared/config-defaults.js +92 -0
  13. package/lib/shared/content-complexity.js +812 -0
  14. package/lib/shared/media-extractor.js +154 -0
  15. package/lib/shared/sandbox-core.js +286 -0
  16. package/lib/shared/sanitize.js +539 -0
  17. package/lib/types/client/artifact-node.d.ts +62 -0
  18. package/lib/types/client/artifact-resource.d.ts +30 -0
  19. package/lib/types/client/artifact-toolview.d.ts +17 -0
  20. package/lib/types/client/code-view.d.ts +22 -0
  21. package/lib/types/client/document-card.d.ts +33 -0
  22. package/lib/types/client/fence-layer.d.ts +26 -0
  23. package/lib/types/client/highlight.d.ts +24 -0
  24. package/lib/types/client/icons.d.ts +10 -0
  25. package/lib/types/client/locales.d.ts +57 -0
  26. package/lib/types/client/sandbox.d.ts +23 -0
  27. package/lib/types/client/styles.d.ts +20 -0
  28. package/lib/types/client/svg-view.d.ts +19 -0
  29. package/lib/types/client/theme.d.ts +20 -0
  30. package/lib/types/client/turn-media.d.ts +10 -0
  31. package/lib/types/client/types.d.ts +293 -0
  32. package/lib/types/client/workbench.d.ts +24 -0
  33. package/lib/types/client.d.ts +10 -0
  34. package/lib/types/config.d.ts +50 -0
  35. package/lib/types/host/artifact-skill.d.ts +39 -0
  36. package/lib/types/host/artifact-tool.d.ts +82 -0
  37. package/lib/types/host/media-bridge.d.ts +47 -0
  38. package/lib/types/index.d.ts +29 -0
  39. package/lib/types/shared/artifact-stream.d.ts +52 -0
  40. package/lib/types/shared/config-defaults.d.ts +56 -0
  41. package/lib/types/shared/content-complexity.d.ts +94 -0
  42. package/lib/types/shared/media-extractor.d.ts +42 -0
  43. package/lib/types/shared/sandbox-core.d.ts +128 -0
  44. package/lib/types/shared/sanitize.d.ts +97 -0
  45. package/locale/en.json +6 -0
  46. package/locale/zh.json +6 -0
  47. package/package.json +95 -4
@@ -0,0 +1,539 @@
1
+ /**
2
+ * Zero-dependency HTML/SVG sanitizer, CSP builder, and sandbox document generator.
3
+ *
4
+ * Security is layered:
5
+ * 1. A character-level HTML tag/attribute scanner strips dangerous elements, event
6
+ * handlers, unsafe URI schemes, declarative shadow roots, and unsafe CSS constructs.
7
+ * 2. Every generated static or interactive document prepends a strict
8
+ * Content-Security-Policy `<meta>` element before any author markup.
9
+ * 3. Callers mount static previews inside `<iframe sandbox="">` and interactive
10
+ * previews inside a Blob URL `<iframe sandbox="allow-scripts">` (never
11
+ * `allow-same-origin`).
12
+ *
13
+ * @module dsh-renderer/shared/sanitize
14
+ */
15
+ /** Container elements whose opening tag, body, and closing tag are dropped in static mode. */
16
+ const STATIC_DROP_CONTAINERS = new Set([
17
+ 'script',
18
+ 'noscript',
19
+ 'iframe',
20
+ 'frame',
21
+ 'frameset',
22
+ 'object',
23
+ 'applet',
24
+ 'template',
25
+ 'foreignobject',
26
+ 'animate',
27
+ 'animatemotion',
28
+ 'animatetransform',
29
+ 'set',
30
+ ]);
31
+ /** Standalone void/header elements dropped in static mode. */
32
+ const STATIC_DROP_SINGLETONS = new Set(['base', 'meta', 'link', 'import', 'embed']);
33
+ /** Elements whose closing tag is matched literally without parsing nested tags inside. */
34
+ const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'noscript', 'iframe', 'textarea', 'title', 'xmp']);
35
+ /** Attributes that are always forbidden in static mode regardless of value. */
36
+ const FORBIDDEN_STATIC_ATTRS = new Set([
37
+ 'srcdoc',
38
+ 'formaction',
39
+ 'xlink:href',
40
+ 'shadowrootmode',
41
+ 'shadowroot',
42
+ 'shadowrootdelegatesfocus',
43
+ 'ping',
44
+ 'autofocus',
45
+ 'nonce',
46
+ ]);
47
+ /** Attributes whose values carry URLs and must pass protocol validation. */
48
+ const URL_ATTRS = new Set(['src', 'href', 'action', 'poster', 'background', 'cite', 'data', 'srcset']);
49
+ /** Allowed `data:` image MIME prefixes for safe raster/static-SVG images. */
50
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpeg|jpg|gif|webp|bmp|x-icon|vnd\.microsoft\.icon|svg\+xml)(?:;[^,]*)?,/i;
51
+ /** Allowed HTTP(S) URL pattern. */
52
+ const SAFE_HTTP_URL_RE = /^https?:\/\//i;
53
+ /** Measure exact UTF-8 byte length without requiring Node's `Buffer` or a global `TextEncoder`. */
54
+ export function utf8ByteLength(text) {
55
+ if (typeof TextEncoder !== 'undefined') {
56
+ return new TextEncoder().encode(text).byteLength;
57
+ }
58
+ let bytes = 0;
59
+ for (let i = 0; i < text.length; i += 1) {
60
+ const code = text.charCodeAt(i);
61
+ if (code < 0x80) {
62
+ bytes += 1;
63
+ }
64
+ else if (code < 0x800) {
65
+ bytes += 2;
66
+ }
67
+ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
68
+ const next = text.charCodeAt(i + 1);
69
+ if (next >= 0xdc00 && next <= 0xdfff) {
70
+ bytes += 4;
71
+ i += 1;
72
+ }
73
+ else {
74
+ bytes += 3;
75
+ }
76
+ }
77
+ else {
78
+ bytes += 3;
79
+ }
80
+ }
81
+ return bytes;
82
+ }
83
+ /** Escape text for safe inclusion inside HTML text nodes or double-quoted attributes. */
84
+ export function escapeHtml(value) {
85
+ return value
86
+ .replaceAll('&', '&amp;')
87
+ .replaceAll('<', '&lt;')
88
+ .replaceAll('>', '&gt;')
89
+ .replaceAll('"', '&quot;')
90
+ .replaceAll("'", '&#39;');
91
+ }
92
+ /**
93
+ * Decode numeric/named HTML entities enough to inspect protocol prefixes in URL attributes.
94
+ * Strips ASCII whitespace and control characters that browsers ignore before scheme names.
95
+ */
96
+ function normalizeUrlForCheck(raw) {
97
+ const decoded = raw
98
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex) => {
99
+ const code = Number.parseInt(hex, 16);
100
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '';
101
+ })
102
+ .replace(/&#(\d+);?/g, (_, dec) => {
103
+ const code = Number.parseInt(dec, 10);
104
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '';
105
+ })
106
+ .replace(/&colon;/gi, ':')
107
+ .replace(/&tab;|&newline;/gi, '');
108
+ let cleaned = '';
109
+ for (let i = 0; i < decoded.length; i += 1) {
110
+ const code = decoded.charCodeAt(i);
111
+ if (code > 0x20 && code !== 0x7f) {
112
+ cleaned += decoded[i];
113
+ }
114
+ }
115
+ return cleaned;
116
+ }
117
+ /**
118
+ * Validate whether an authored URL is safe for the given HTML attribute in static mode.
119
+ *
120
+ * @param attr - lowercased attribute name.
121
+ * @param value - raw attribute value.
122
+ * @param allowExternalResources - whether external `http(s):` media URLs are permitted.
123
+ */
124
+ export function isSafeStaticUrl(attr, value, allowExternalResources) {
125
+ const normalized = normalizeUrlForCheck(value);
126
+ if (normalized.length === 0)
127
+ return false;
128
+ // Fragment-only links (`#section`) stay internal to the sandbox document.
129
+ if (normalized.startsWith('#')) {
130
+ return attr === 'href';
131
+ }
132
+ if (SAFE_DATA_IMAGE_RE.test(normalized)) {
133
+ return attr === 'src' || attr === 'poster';
134
+ }
135
+ if (allowExternalResources && SAFE_HTTP_URL_RE.test(normalized)) {
136
+ return attr === 'src' || attr === 'poster' || attr === 'href';
137
+ }
138
+ return false;
139
+ }
140
+ /**
141
+ * Sanitize CSS text (inline `style` attributes or `<style>` block bodies) by removing
142
+ * `@import`, legacy script expressions, and unsafe `url(...)` references.
143
+ */
144
+ export function sanitizeCss(css, allowExternalResources) {
145
+ let out = css.replaceAll('\0', '');
146
+ // Remove CSS comments so obfuscated `@/* */import` or `exp/* */ression` cannot slip through.
147
+ out = out.replace(/\/\*[\s\S]*?\*\//g, '');
148
+ // Drop @import rules (including optional layer/media queries up to semicolon or newline).
149
+ out = out.replace(/@import\b[^;\n]*(?:;|$)/gi, '');
150
+ // Neutralize legacy IE/Firefox script-in-CSS vectors.
151
+ out = out.replace(/expression\s*\(/gi, 'invalid-expr(');
152
+ out = out.replace(/(?:-moz-binding|behavior)\s*:/gi, 'x-blocked:');
153
+ // Filter url(...) references strictly.
154
+ out = out.replace(/url\(\s*(['"]?)([\s\S]*?)\1\s*\)/gi, (_full, _quote, rawTarget) => {
155
+ const target = rawTarget.trim();
156
+ const normalized = normalizeUrlForCheck(target);
157
+ if (SAFE_DATA_IMAGE_RE.test(normalized)) {
158
+ return `url("${target.replaceAll('"', '%22')}")`;
159
+ }
160
+ if (allowExternalResources && SAFE_HTTP_URL_RE.test(normalized)) {
161
+ return `url("${target.replaceAll('"', '%22')}")`;
162
+ }
163
+ return 'none';
164
+ });
165
+ return out;
166
+ }
167
+ /** Parse one HTML/SVG tag starting at `input[start] === '<'`. Returns `null` if malformed. */
168
+ function parseHtmlTag(input, start) {
169
+ const len = input.length;
170
+ let i = start + 1;
171
+ if (i >= len)
172
+ return null;
173
+ let isClosing = false;
174
+ if (input[i] === '/') {
175
+ isClosing = true;
176
+ i += 1;
177
+ }
178
+ const nameStart = i;
179
+ while (i < len && /[a-zA-Z0-9:_-]/.test(input[i])) {
180
+ i += 1;
181
+ }
182
+ if (i === nameStart)
183
+ return null;
184
+ const rawName = input.slice(nameStart, i);
185
+ const name = rawName.toLowerCase();
186
+ const attrs = [];
187
+ let selfClosing = false;
188
+ while (i < len) {
189
+ while (i < len && /\s/.test(input[i]))
190
+ i += 1;
191
+ if (i >= len)
192
+ break;
193
+ const ch = input[i];
194
+ if (ch === '>') {
195
+ return { rawName, name, isClosing, selfClosing, attrs, endIndex: i + 1 };
196
+ }
197
+ if (ch === '/' && input[i + 1] === '>') {
198
+ selfClosing = true;
199
+ return { rawName, name, isClosing, selfClosing, attrs, endIndex: i + 2 };
200
+ }
201
+ const attrStart = i;
202
+ while (i < len && !/[\s=/>"'<]/.test(input[i])) {
203
+ i += 1;
204
+ }
205
+ if (i === attrStart) {
206
+ i += 1;
207
+ continue;
208
+ }
209
+ const rawAttrName = input.slice(attrStart, i);
210
+ const attrName = rawAttrName.toLowerCase();
211
+ while (i < len && /\s/.test(input[i]))
212
+ i += 1;
213
+ let value = '';
214
+ let hasValue = false;
215
+ if (i < len && input[i] === '=') {
216
+ hasValue = true;
217
+ i += 1;
218
+ while (i < len && /\s/.test(input[i]))
219
+ i += 1;
220
+ if (i < len && (input[i] === '"' || input[i] === "'")) {
221
+ const quote = input[i];
222
+ i += 1;
223
+ const valStart = i;
224
+ while (i < len && input[i] !== quote)
225
+ i += 1;
226
+ value = input.slice(valStart, i);
227
+ if (i < len && input[i] === quote)
228
+ i += 1;
229
+ }
230
+ else {
231
+ const valStart = i;
232
+ while (i < len && !/[\s>]/.test(input[i]))
233
+ i += 1;
234
+ value = input.slice(valStart, i);
235
+ }
236
+ }
237
+ attrs.push({ rawName: rawAttrName, name: attrName, value, hasValue });
238
+ }
239
+ return null;
240
+ }
241
+ /** Find the closing tag `</tagName...>` starting from `from`, returning the index just after `>`. */
242
+ function findClosingTagEnd(input, tagName, from) {
243
+ const lower = input.toLowerCase();
244
+ const needle = `</${tagName}`;
245
+ let pos = from;
246
+ while (pos < lower.length) {
247
+ const idx = lower.indexOf(needle, pos);
248
+ if (idx === -1)
249
+ return input.length;
250
+ const afterName = idx + needle.length;
251
+ const nextChar = lower[afterName];
252
+ if (nextChar === undefined || nextChar === '>' || /\s/.test(nextChar) || nextChar === '/') {
253
+ const closeBracket = input.indexOf('>', afterName);
254
+ return closeBracket === -1 ? input.length : closeBracket + 1;
255
+ }
256
+ pos = afterName;
257
+ }
258
+ return input.length;
259
+ }
260
+ /**
261
+ * Sanitize raw HTML markup for static, script-free preview rendering.
262
+ *
263
+ * Strips dangerous container tags, void metadata tags, inline event handlers,
264
+ * unsafe URL schemes, declarative shadow roots, and unsafe CSS expressions.
265
+ */
266
+ export function sanitizeStaticHtml(rawHtml, allowExternalResources = false) {
267
+ const input = rawHtml.replaceAll('\0', '');
268
+ const len = input.length;
269
+ let i = 0;
270
+ let output = '';
271
+ while (i < len) {
272
+ const lt = input.indexOf('<', i);
273
+ if (lt === -1) {
274
+ output += input.slice(i);
275
+ break;
276
+ }
277
+ if (lt > i) {
278
+ output += input.slice(i, lt);
279
+ }
280
+ // HTML comment: strip completely to prevent IE conditional or parser-differential payloads.
281
+ if (input.startsWith('<!--', lt)) {
282
+ const end = input.indexOf('-->', lt + 4);
283
+ i = end === -1 ? len : end + 3;
284
+ continue;
285
+ }
286
+ // Doctype or XML processing instruction (`<!...` or `<?...`).
287
+ if (input[lt + 1] === '!' || input[lt + 1] === '?') {
288
+ const end = input.indexOf('>', lt + 2);
289
+ if (end === -1) {
290
+ i = len;
291
+ continue;
292
+ }
293
+ const directive = input.slice(lt, end + 1);
294
+ if (/^<!doctype\s+html\b/i.test(directive)) {
295
+ // Handled cleanly by the outer document wrapper.
296
+ }
297
+ i = end + 1;
298
+ continue;
299
+ }
300
+ const tag = parseHtmlTag(input, lt);
301
+ if (tag === null) {
302
+ output += '&lt;';
303
+ i = lt + 1;
304
+ continue;
305
+ }
306
+ // Drop dangerous container elements along with their inner content.
307
+ if (STATIC_DROP_CONTAINERS.has(tag.name)) {
308
+ if (tag.isClosing || tag.selfClosing) {
309
+ i = tag.endIndex;
310
+ }
311
+ else {
312
+ i = findClosingTagEnd(input, tag.name, tag.endIndex);
313
+ }
314
+ continue;
315
+ }
316
+ // Drop forbidden singleton/head directives.
317
+ if (STATIC_DROP_SINGLETONS.has(tag.name)) {
318
+ i = tag.endIndex;
319
+ continue;
320
+ }
321
+ // Sanitize `<style>` block bodies as raw text so inner `<` characters stay intact.
322
+ if (tag.name === 'style' && !tag.isClosing && !tag.selfClosing) {
323
+ const closeEnd = findClosingTagEnd(input, 'style', tag.endIndex);
324
+ const closeStart = input.toLowerCase().lastIndexOf('</style', closeEnd);
325
+ const body = closeStart >= tag.endIndex ? input.slice(tag.endIndex, closeStart) : '';
326
+ const cleanCss = sanitizeCss(body, allowExternalResources);
327
+ output += `<style>${cleanCss}</style>`;
328
+ i = closeEnd;
329
+ continue;
330
+ }
331
+ if (tag.isClosing) {
332
+ output += `</${tag.rawName}>`;
333
+ i = tag.endIndex;
334
+ continue;
335
+ }
336
+ // Rebuild safe attributes while preserving original casing (required for XML/SVG).
337
+ let attrOut = '';
338
+ for (const attr of tag.attrs) {
339
+ if (attr.name.startsWith('on') || FORBIDDEN_STATIC_ATTRS.has(attr.name)) {
340
+ continue;
341
+ }
342
+ if (attr.name === 'style') {
343
+ const cleanInline = sanitizeCss(attr.value, allowExternalResources).trim();
344
+ if (cleanInline.length > 0) {
345
+ attrOut += ` ${attr.rawName}="${escapeHtml(cleanInline)}"`;
346
+ }
347
+ continue;
348
+ }
349
+ if (URL_ATTRS.has(attr.name)) {
350
+ if (!isSafeStaticUrl(attr.name, attr.value, allowExternalResources)) {
351
+ continue;
352
+ }
353
+ attrOut += ` ${attr.rawName}="${escapeHtml(attr.value.trim())}"`;
354
+ continue;
355
+ }
356
+ if (attr.hasValue) {
357
+ attrOut += ` ${attr.rawName}="${escapeHtml(attr.value)}"`;
358
+ }
359
+ else {
360
+ attrOut += ` ${attr.rawName}`;
361
+ }
362
+ }
363
+ if (tag.name === 'a') {
364
+ attrOut += ' rel="noopener noreferrer"';
365
+ }
366
+ output += `<${tag.rawName}${attrOut}${tag.selfClosing ? ' /' : ''}>`;
367
+ i = tag.endIndex;
368
+ // For harmless raw-text elements (e.g. `<textarea>`, `<title>`), copy body verbatim until close.
369
+ if (!tag.selfClosing && RAW_TEXT_ELEMENTS.has(tag.name)) {
370
+ const closeEnd = findClosingTagEnd(input, tag.name, i);
371
+ const closeStart = input.toLowerCase().lastIndexOf(`</${tag.name}`, closeEnd);
372
+ if (closeStart >= i) {
373
+ output += input.slice(i, closeStart).replaceAll('<', '&lt;');
374
+ output += `</${tag.rawName}>`;
375
+ }
376
+ i = closeEnd;
377
+ }
378
+ }
379
+ return output;
380
+ }
381
+ /** Build the strict Content-Security-Policy string for static or interactive HTML sandboxes. */
382
+ export function buildSandboxCsp(mode, allowExternalResources, staticNonce) {
383
+ if (mode === 'static') {
384
+ const scriptSrc = staticNonce !== undefined ? `script-src 'nonce-${staticNonce}'` : "script-src 'none'";
385
+ if (allowExternalResources) {
386
+ return [
387
+ "default-src 'none'",
388
+ scriptSrc,
389
+ "style-src 'unsafe-inline' https:",
390
+ 'img-src data: https:',
391
+ 'font-src data: https:',
392
+ 'media-src data: https:',
393
+ "connect-src 'none'",
394
+ "frame-src 'none'",
395
+ "object-src 'none'",
396
+ "form-action 'none'",
397
+ "base-uri 'none'",
398
+ ].join('; ');
399
+ }
400
+ return [
401
+ "default-src 'none'",
402
+ scriptSrc,
403
+ "style-src 'unsafe-inline'",
404
+ 'img-src data:',
405
+ 'font-src data:',
406
+ 'media-src data:',
407
+ "connect-src 'none'",
408
+ "frame-src 'none'",
409
+ "object-src 'none'",
410
+ "form-action 'none'",
411
+ "base-uri 'none'",
412
+ ].join('; ');
413
+ }
414
+ if (allowExternalResources) {
415
+ return [
416
+ "default-src 'none'",
417
+ "script-src 'unsafe-inline' 'unsafe-eval' blob: https:",
418
+ "style-src 'unsafe-inline' blob: https:",
419
+ 'img-src data: blob: https: http:',
420
+ 'font-src data: blob: https:',
421
+ 'media-src data: blob: https:',
422
+ 'worker-src blob:',
423
+ 'connect-src https:',
424
+ "frame-src 'none'",
425
+ "object-src 'none'",
426
+ "form-action 'none'",
427
+ "base-uri 'none'",
428
+ ].join('; ');
429
+ }
430
+ return [
431
+ "default-src 'none'",
432
+ "script-src 'unsafe-inline' blob:",
433
+ "style-src 'unsafe-inline' blob:",
434
+ 'img-src data: blob:',
435
+ 'font-src data: blob:',
436
+ 'media-src data: blob:',
437
+ 'worker-src blob:',
438
+ "connect-src 'none'",
439
+ "frame-src 'none'",
440
+ "object-src 'none'",
441
+ "form-action 'none'",
442
+ "base-uri 'none'",
443
+ ].join('; ');
444
+ }
445
+ /** Build a lightweight baseline stylesheet that exposes host theme variables without overriding page CSS. */
446
+ function buildThemeBaseStyle(theme) {
447
+ const scheme = theme?.scheme === 'dark' ? 'dark' : 'light';
448
+ const bg = theme?.bg ?? (scheme === 'dark' ? '#141414' : '#ffffff');
449
+ const fg = theme?.fg ?? (scheme === 'dark' ? '#ececec' : '#1f2328');
450
+ const border = theme?.border ?? (scheme === 'dark' ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.12)');
451
+ const accent = theme?.accent ?? '#3b82f6';
452
+ return `<style data-dsh-renderer-theme>:root{color-scheme:${scheme};--dsh-bg:${escapeHtml(bg)};--dsh-fg:${escapeHtml(fg)};--dsh-border:${escapeHtml(border)};--dsh-accent:${escapeHtml(accent)};}html,body{margin:0;padding:0;}body{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--dsh-fg);background:var(--dsh-bg);}</style>`;
453
+ }
454
+ /** Inject a head preamble (CSP + theme base) into either a full HTML document or a body fragment. */
455
+ function wrapWithHeadPreamble(html, preamble, scheme) {
456
+ const headMatch = /<head\b[^>]*>/i.exec(html);
457
+ if (headMatch !== null) {
458
+ const insertAt = headMatch.index + headMatch[0].length;
459
+ const prefix = /^\s*<!doctype\b/i.test(html) ? '' : '<!doctype html>';
460
+ return `${prefix}${html.slice(0, insertAt)}${preamble}${html.slice(insertAt)}`;
461
+ }
462
+ const htmlMatch = /<html\b[^>]*>/i.exec(html);
463
+ if (htmlMatch !== null) {
464
+ const insertAt = htmlMatch.index + htmlMatch[0].length;
465
+ const prefix = /^\s*<!doctype\b/i.test(html) ? '' : '<!doctype html>';
466
+ return `${prefix}${html.slice(0, insertAt)}<head>${preamble}</head>${html.slice(insertAt)}`;
467
+ }
468
+ return `<!doctype html><html data-theme="${scheme}"><head><meta charset="utf-8">${preamble}</head><body>${html}</body></html>`;
469
+ }
470
+ /** Build the lightweight height-measurement, theme-sync, and optional error bridge script. */
471
+ function buildBridgeScript(token, options) {
472
+ const safeToken = JSON.stringify(token).replaceAll('<', '\\u003c');
473
+ const nonceAttr = options.nonce !== undefined ? ` nonce="${escapeHtml(options.nonce)}"` : '';
474
+ const errorHooks = options.forwardErrors
475
+ ? `window.addEventListener('error',(e)=>{try{parent.postMessage({token:T,type:'dsh-renderer:error',message:String(e&&e.message||'Script error')},'*');}catch{}});window.addEventListener('unhandledrejection',(e)=>{try{parent.postMessage({token:T,type:'dsh-renderer:error',message:String(e&&e.reason||'Unhandled promise rejection')},'*');}catch{}});`
476
+ : '';
477
+ return `<script${nonceAttr} data-dsh-renderer-bridge>(()=>{const T=${safeToken};let timer=0;const measure=()=>{const b=document.body;if(!b)return 0;const cs=getComputedStyle(b);const mt=parseFloat(cs.marginTop)||0;const mb=parseFloat(cs.marginBottom)||0;const rect=Math.ceil(b.getBoundingClientRect().height);return Math.ceil(Math.max(rect,b.scrollHeight)+mt+mb);};const report=()=>{try{const h=measure();if(h>0)parent.postMessage({token:T,type:'dsh-renderer:resize',height:h},'*');}catch{}};const schedule=()=>{if(timer)clearTimeout(timer);timer=setTimeout(report,40);};window.addEventListener('message',(e)=>{const m=e&&e.data;if(!m||typeof m!=='object'||m.token!==T||m.type!=='dsh-renderer:theme'||!m.theme)return;const r=document.documentElement;if(!r)return;const th=m.theme;r.dataset.theme=th.scheme==='dark'?'dark':'light';r.style.colorScheme=r.dataset.theme;if(typeof th.bg==='string')r.style.setProperty('--dsh-bg',th.bg);if(typeof th.fg==='string')r.style.setProperty('--dsh-fg',th.fg);if(typeof th.border==='string')r.style.setProperty('--dsh-border',th.border);if(typeof th.accent==='string')r.style.setProperty('--dsh-accent',th.accent);});${errorHooks}window.addEventListener('load',()=>{report();try{if(typeof ResizeObserver==='function'&&document.body){new ResizeObserver(schedule).observe(document.body);}}catch{}});document.addEventListener('DOMContentLoaded',()=>{report();try{if(typeof ResizeObserver==='function'&&document.body){new ResizeObserver(schedule).observe(document.body);}}catch{}});})();</script>`;
478
+ }
479
+ /**
480
+ * Build a complete static HTML document ready for a sandboxed iframe.
481
+ *
482
+ * When `options.staticBridge` is omitted, CSP sets `script-src 'none'` for a
483
+ * zero-script `<iframe sandbox="">`. When `options.staticBridge` is provided,
484
+ * CSP locks script execution exclusively to `script-src 'nonce-<nonce>'` so
485
+ * only the host's own height/theme bridge runs while all author scripts stay
486
+ * stripped and CSP-blocked.
487
+ */
488
+ export function buildStaticHtmlDocument(rawHtml, options) {
489
+ const clean = sanitizeStaticHtml(rawHtml, options.allowExternalResources);
490
+ const bridge = options.staticBridge;
491
+ const csp = buildSandboxCsp('static', options.allowExternalResources, bridge?.nonce);
492
+ const scheme = options.theme?.scheme === 'dark' ? 'dark' : 'light';
493
+ const bridgeScript = bridge !== undefined ? buildBridgeScript(bridge.token, { nonce: bridge.nonce, forwardErrors: false }) : '';
494
+ const preamble = `<meta http-equiv="Content-Security-Policy" content="${escapeHtml(csp)}">${buildThemeBaseStyle(options.theme)}${bridgeScript}`;
495
+ return wrapWithHeadPreamble(clean, preamble, scheme);
496
+ }
497
+ /**
498
+ * Build a complete interactive HTML document ready for a Blob URL inside
499
+ * `<iframe sandbox="allow-scripts">` (opaque origin, no `allow-same-origin`).
500
+ *
501
+ * Strips `<base>` and `<meta http-equiv="refresh"|"content-security-policy">`
502
+ * tags before prepending the renderer's own CSP and lightweight resize/theme bridge.
503
+ */
504
+ export function buildInteractiveHtmlDocument(rawHtml, options) {
505
+ // Prevent author markup from overriding our CSP or changing base URL resolution.
506
+ const stripped = rawHtml
507
+ .replaceAll('\0', '')
508
+ .replace(/<base\b[^>]*>/gi, '')
509
+ .replace(/<meta\b[^>]*http-equiv\s*=\s*(?:["']?(?:content-security-policy|refresh)["']?)[^>]*>/gi, '');
510
+ const csp = buildSandboxCsp('interactive', options.allowExternalResources);
511
+ const scheme = options.theme?.scheme === 'dark' ? 'dark' : 'light';
512
+ const bridgeScript = buildBridgeScript(options.token, { forwardErrors: true });
513
+ const preamble = `<meta http-equiv="Content-Security-Policy" content="${escapeHtml(csp)}">${buildThemeBaseStyle(options.theme)}${bridgeScript}`;
514
+ return wrapWithHeadPreamble(stripped, preamble, scheme);
515
+ }
516
+ /**
517
+ * Prepare standalone SVG markup for safe rendering inside `<img src="blob:...">`.
518
+ *
519
+ * Ensures the SVG namespace (`xmlns="http://www.w3.org/2000/svg"`) is declared
520
+ * (browsers render blank `<img>` boxes when standalone SVG omits it) and strips
521
+ * scripts, SMIL animations, foreignObject, and inline event handlers.
522
+ *
523
+ * @returns normalized SVG string, or `null` when the input contains no `<svg>` root.
524
+ */
525
+ export function prepareSvgForImage(rawSvg) {
526
+ const sanitized = sanitizeStaticHtml(rawSvg, false).trim();
527
+ const openMatch = /<svg\b([^>]*)>/i.exec(sanitized);
528
+ if (openMatch === null)
529
+ return null;
530
+ const closeIndex = sanitized.toLowerCase().lastIndexOf('</svg>');
531
+ const body = closeIndex >= openMatch.index
532
+ ? sanitized.slice(openMatch.index, closeIndex + '</svg>'.length)
533
+ : sanitized.slice(openMatch.index);
534
+ if (/\bxmlns\s*=/i.test(openMatch[1] ?? '')) {
535
+ return body;
536
+ }
537
+ const injectedOpen = `<svg xmlns="http://www.w3.org/2000/svg"${openMatch[1] ?? ''}>`;
538
+ return injectedOpen + body.slice(openMatch[0].length);
539
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * First-class Chat Conversation Node (`dsh-renderer:artifact`) promoted outside
3
+ * DSH's Process Grouping and Whole-Turn Folding (`groupTree: 'turn'`).
4
+ *
5
+ * Ensures `render_artifact` cards remain directly visible in the conversation
6
+ * flow across all DSH Work-details modes (`compact`, `standard`, `detailed`,
7
+ * `verbose`), both while streaming and after the turn completes, for native
8
+ * tool calls and PTC dispatches alike.
9
+ *
10
+ * @module dsh-renderer/client/artifact-node
11
+ */
12
+ import { type ArtifactContentKind } from '../shared/content-complexity.ts';
13
+ import type { ClientEnv } from './types.ts';
14
+ /** Conversation Node kind registered into `ctx.uiConversation.events` and `conversation.chat.node`. */
15
+ export declare const ARTIFACT_CHAT_NODE_KIND = "dsh-renderer:artifact";
16
+ /** View payload stored on each `dsh-renderer:artifact` Chat Node. */
17
+ export interface ArtifactChatNodeData {
18
+ readonly callId: string;
19
+ readonly phase: 'streaming' | 'ready' | 'error';
20
+ readonly sawStreaming: boolean;
21
+ readonly kind: ArtifactContentKind;
22
+ readonly lang: string;
23
+ readonly title: string;
24
+ readonly content: string;
25
+ readonly artifactId: string;
26
+ readonly lines: number;
27
+ readonly bytes: number;
28
+ readonly errorMessage?: string | undefined;
29
+ }
30
+ interface ConversationLocationLike {
31
+ readonly kind?: string;
32
+ readonly turn?: {
33
+ readonly turn?: number;
34
+ readonly status?: string;
35
+ };
36
+ readonly step?: {
37
+ readonly step?: number;
38
+ readonly status?: string;
39
+ };
40
+ }
41
+ /** Props received by the keyed `conversation.chat.node` renderer for `dsh-renderer:artifact`. */
42
+ export interface ArtifactChatNodeProps {
43
+ readonly node?: {
44
+ readonly key?: string;
45
+ readonly id?: string;
46
+ readonly location?: ConversationLocationLike;
47
+ readonly data?: ArtifactChatNodeData;
48
+ };
49
+ readonly sessionId?: string | undefined;
50
+ }
51
+ /**
52
+ * Create the non-exclusive DSH `ConversationNodeDefinition` that projects
53
+ * `render_artifact` tool calls (native and PTC) as top-level `groupTree: 'turn'`
54
+ * Chat nodes outside Process Grouping and Whole-Turn Folding.
55
+ */
56
+ export declare function createArtifactNodeDefinition(): Record<string, unknown>;
57
+ /**
58
+ * Create the keyed `conversation.chat.node` renderer for promoted
59
+ * `dsh-renderer:artifact` nodes.
60
+ */
61
+ export declare function createArtifactChatNodeComponent(env: ClientEnv): (props: ArtifactChatNodeProps) => unknown;
62
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Client `ctx.resources` provider for `dsh-resource://dsh-renderer/**`.
3
+ *
4
+ * Supports two address spaces:
5
+ * 1. `dsh-resource://dsh-renderer/artifact/<id>` — live in-memory / fence-backed
6
+ * artifacts served reactively from `ArtifactStore`.
7
+ * 2. `dsh-resource://dsh-renderer/call/...` — durable `render_artifact` tool calls:
8
+ * instant hit from `ArtifactStore` when warm, and automatic backwards paging
9
+ * through `ctx.remote.session` (`events` + `page`) on cold browser reload.
10
+ *
11
+ * @module dsh-renderer/client/artifact-resource
12
+ */
13
+ import { type ArtifactRecord, type ArtifactStore } from '../shared/sandbox-core.ts';
14
+ import type { ClientResourceFrame, ClientSessionHistoryRemote } from './types.ts';
15
+ /** Options for constructing the `dsh-renderer` client resource provider. */
16
+ export interface ArtifactResourceProviderOptions {
17
+ readonly artifacts: ArtifactStore;
18
+ readonly getRemoteSession?: () => ClientSessionHistoryRemote | undefined;
19
+ readonly maxContentBytes: number;
20
+ }
21
+ /**
22
+ * Create the `ResourceProvider` registered on `ctx.resources` under protocol
23
+ * `'dsh-renderer'`.
24
+ */
25
+ export declare function createArtifactResourceProvider(options: ArtifactResourceProviderOptions): {
26
+ readonly protocol: string;
27
+ open(address: string, context: {
28
+ readonly signal: AbortSignal;
29
+ }): AsyncIterable<ClientResourceFrame<ArtifactRecord>>;
30
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Custom `tool.call.toolview` renderer for the `render_artifact` Host tool.
3
+ *
4
+ * Streams from the very first token as a compact DSH-native Document Card:
5
+ * - `preparing`: reads `title`, `kind`, `lang`, and `stringLength('content', { step: 256 })`
6
+ * lazily through DSH's `PartialArguments` so the card updates live without flooding chat.
7
+ * - `start` / `result`: reads the durable tool call payload from the Session log, hydrates
8
+ * `ArtifactStore` (surviving reloads and session switches), and opens in the right Sidebar
9
+ * on click (or automatically when `autoOpenArtifact` is enabled).
10
+ *
11
+ * @module dsh-renderer/client/artifact-toolview
12
+ */
13
+ import type { ClientEnv, ToolCallSlotProps } from './types.ts';
14
+ /** Wire tool name matching `src/host/artifact-tool.ts`. */
15
+ export declare const ARTIFACT_TOOL_NAME = "render_artifact";
16
+ /** Create the React component registered into `tool.call.toolview` under `key: 'render_artifact'`. */
17
+ export declare function createArtifactToolViewComponent(env: ClientEnv): (props: ToolCallSlotProps) => unknown;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shiki-highlighted source code viewer shared by Chat fence cards, the
3
+ * right-Sidebar workbench, and fullscreen modal.
4
+ *
5
+ * Renders token lines as pure React elements styled via DSH's `--shiki-*`
6
+ * theme tokens without `dangerouslySetInnerHTML` or nested headers.
7
+ *
8
+ * @module dsh-renderer/client/code-view
9
+ */
10
+ import type { ClientEnv } from './types.ts';
11
+ /** Props accepted by the highlighted code viewer. */
12
+ export interface HighlightedCodeViewProps {
13
+ readonly code: string;
14
+ readonly lang: string;
15
+ readonly wrapped: boolean;
16
+ readonly maxHeight?: number | undefined;
17
+ readonly fillHeight?: boolean | undefined;
18
+ }
19
+ /** Copy text to the system clipboard with a textarea fallback. */
20
+ export declare function copyTextToClipboard(text: string): Promise<boolean>;
21
+ /** Create the React component rendering Shiki-highlighted HTML/SVG source. */
22
+ export declare function createHighlightedCodeViewComponent(env: ClientEnv): (props: HighlightedCodeViewProps) => unknown;