@aqian0/dsh-renderer 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 +21 -0
- package/README.md +119 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +5 -0
- package/lib/client.js +738 -0
- package/lib/config.js +92 -0
- package/lib/host/artifact-tool.js +141 -0
- package/lib/host/media-bridge.js +102 -0
- package/lib/index.js +101 -0
- package/lib/shared/config-defaults.js +88 -0
- package/lib/shared/content-complexity.js +748 -0
- package/lib/shared/media-extractor.js +154 -0
- package/lib/shared/sandbox-core.js +217 -0
- package/lib/shared/sanitize.js +539 -0
- package/lib/types/client/artifact-toolview.d.ts +17 -0
- package/lib/types/client/code-view.d.ts +22 -0
- package/lib/types/client/document-card.d.ts +33 -0
- package/lib/types/client/fence-layer.d.ts +26 -0
- package/lib/types/client/highlight.d.ts +24 -0
- package/lib/types/client/icons.d.ts +10 -0
- package/lib/types/client/locales.d.ts +54 -0
- package/lib/types/client/sandbox.d.ts +23 -0
- package/lib/types/client/styles.d.ts +20 -0
- package/lib/types/client/svg-view.d.ts +19 -0
- package/lib/types/client/theme.d.ts +20 -0
- package/lib/types/client/turn-media.d.ts +10 -0
- package/lib/types/client/types.d.ts +181 -0
- package/lib/types/client/workbench.d.ts +24 -0
- package/lib/types/client.d.ts +10 -0
- package/lib/types/config.d.ts +48 -0
- package/lib/types/host/artifact-tool.d.ts +53 -0
- package/lib/types/host/media-bridge.d.ts +47 -0
- package/lib/types/index.d.ts +29 -0
- package/lib/types/shared/config-defaults.d.ts +54 -0
- package/lib/types/shared/content-complexity.d.ts +88 -0
- package/lib/types/shared/media-extractor.d.ts +42 -0
- package/lib/types/shared/sandbox-core.d.ts +101 -0
- package/lib/types/shared/sanitize.d.ts +97 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +91 -4
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure content complexity analysis, document title extraction, language labels,
|
|
3
|
+
* and deterministic artifact identity helpers across HTML, SVG, Markdown, data,
|
|
4
|
+
* and general code fences.
|
|
5
|
+
*
|
|
6
|
+
* Used to decide when a Markdown fence in the Chat flow is too complex or long
|
|
7
|
+
* for comfortable inline reading and should instead render as a DSH-styled
|
|
8
|
+
* Document Expand Card that opens in the right Sidebar workbench.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-renderer/shared/content-complexity
|
|
11
|
+
*/
|
|
12
|
+
import { utf8ByteLength } from './sanitize.js';
|
|
13
|
+
/** Minimum composite score required to collapse a fence into a Sidebar document card. */
|
|
14
|
+
export const COMPLEX_CONTENT_SCORE_THRESHOLD = 6;
|
|
15
|
+
const GENERIC_TITLES = new Set(['document', 'untitled', 'html', 'svg', 'index', 'page', 'preview', 'demo']);
|
|
16
|
+
// HTML patterns
|
|
17
|
+
const LANDMARK_TAG_RE = /<(?:header|nav|main|aside|section|article|footer|dialog|form|table)(?=[\s/>])/gi;
|
|
18
|
+
const ELEMENT_TAG_RE = /<[a-z][a-z0-9-]*(?=[\s/>])/gi;
|
|
19
|
+
const FULL_DOC_RE = /<!doctype\s+html\b/i;
|
|
20
|
+
const HTML_TAG_RE = /<html\b/i;
|
|
21
|
+
const BODY_TAG_RE = /<body\b/i;
|
|
22
|
+
const SCRIPT_BLOCK_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
|
23
|
+
const STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
|
24
|
+
const EXTERNAL_ASSET_RE = /<script\b[^>]*\bsrc\s*=|<link\b[^>]*\brel\s*=\s*["']?[^"'>]*stylesheet\b[^>]*\bhref\s*=|<link\b[^>]*\bhref\s*=[^>]*\brel\s*=\s*["']?[^"'>]*stylesheet\b/i;
|
|
25
|
+
const CANVAS_OR_SVG_RE = /<(?:canvas|svg)(?=[\s/>])/i;
|
|
26
|
+
const VIEWPORT_LAYOUT_RE = /(?:min-)?height\s*:\s*(?:100|9\d)(?:d|s|l)?v[hw]\b|position\s*:\s*fixed\b/i;
|
|
27
|
+
const HEAVY_RUNTIME_API_RE = /\b(?:requestAnimationFrame|getContext\s*\(|WebGL|AudioContext|IntersectionObserver|MutationObserver|ResizeObserver|localStorage|sessionStorage|THREE\.|echarts|Chart\s*\(|d3\.|ReactDOM|createApp)\b/i;
|
|
28
|
+
const RESPONSIVE_OR_ANIM_CSS_RE = /@(?:media|keyframes|container)\b/i;
|
|
29
|
+
// SVG patterns
|
|
30
|
+
const SVG_PRIMITIVE_RE = /<(?:path|rect|circle|ellipse|polygon|polyline|line|text|tspan|use|image|g)(?=[\s/>])/gi;
|
|
31
|
+
const SVG_DEFS_FEATURE_RE = /<(?:linearGradient|radialGradient|filter|marker|pattern|clipPath|mask)(?=[\s/>])/gi;
|
|
32
|
+
const SVG_TEXT_RE = /<text(?=[\s/>])/gi;
|
|
33
|
+
const SVG_VIEWBOX_RE = /\bviewBox\s*=\s*["']?\s*[-\d.]+\s+[-\d.]+\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)/i;
|
|
34
|
+
const SVG_WIDTH_RE = /<svg\b[^>]*\bwidth\s*=\s*["']?(\d+(?:\.\d+)?)(?:px)?["']?/i;
|
|
35
|
+
const SVG_HEIGHT_RE = /<svg\b[^>]*\bheight\s*=\s*["']?(\d+(?:\.\d+)?)(?:px)?["']?/i;
|
|
36
|
+
// General code/doc/data patterns
|
|
37
|
+
const MARKDOWN_LANGS = new Set(['md', 'markdown', 'mdx', 'rst', 'adoc', 'asciidoc', 'tex', 'latex']);
|
|
38
|
+
const DATA_LANGS = new Set(['json', 'jsonc', 'json5', 'yaml', 'yml', 'toml', 'xml', 'csv', 'tsv', 'ini', 'graphql']);
|
|
39
|
+
const DIFF_LANGS = new Set(['diff', 'patch']);
|
|
40
|
+
const CODE_SYMBOL_RE = /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|let|var|def|fn|pub\s+(?:fn|struct|enum|trait|mod)|struct|enum|trait|impl|func|package|module|CREATE\s+(?:TABLE|VIEW|FUNCTION|INDEX))\b/gim;
|
|
41
|
+
const DATA_ENTRY_RE = /^\s*(?:"[^"]+"\s*:|[a-zA-Z0-9_.-]+\s*:|<[a-zA-Z][\w:-]*[\s>])/gm;
|
|
42
|
+
const MARKDOWN_HEADING_RE = /^#{1,6}\s+\S/gm;
|
|
43
|
+
const DIFF_FILE_RE = /^(?:diff --git |\+\+\+ )/gm;
|
|
44
|
+
const DIFF_HUNK_RE = /^@@\s+-\d+/gm;
|
|
45
|
+
const LANGUAGE_LABELS = {
|
|
46
|
+
html: 'HTML',
|
|
47
|
+
svg: 'SVG',
|
|
48
|
+
xml: 'XML',
|
|
49
|
+
css: 'CSS',
|
|
50
|
+
scss: 'SCSS',
|
|
51
|
+
less: 'Less',
|
|
52
|
+
js: 'JavaScript',
|
|
53
|
+
javascript: 'JavaScript',
|
|
54
|
+
jsx: 'JSX',
|
|
55
|
+
mjs: 'JavaScript',
|
|
56
|
+
cjs: 'JavaScript',
|
|
57
|
+
ts: 'TypeScript',
|
|
58
|
+
typescript: 'TypeScript',
|
|
59
|
+
tsx: 'TSX',
|
|
60
|
+
mts: 'TypeScript',
|
|
61
|
+
cts: 'TypeScript',
|
|
62
|
+
py: 'Python',
|
|
63
|
+
python: 'Python',
|
|
64
|
+
json: 'JSON',
|
|
65
|
+
jsonc: 'JSONC',
|
|
66
|
+
json5: 'JSON5',
|
|
67
|
+
yaml: 'YAML',
|
|
68
|
+
yml: 'YAML',
|
|
69
|
+
toml: 'TOML',
|
|
70
|
+
md: 'Markdown',
|
|
71
|
+
markdown: 'Markdown',
|
|
72
|
+
mdx: 'MDX',
|
|
73
|
+
sh: 'Shell',
|
|
74
|
+
bash: 'Bash',
|
|
75
|
+
zsh: 'Shell',
|
|
76
|
+
shell: 'Shell',
|
|
77
|
+
sql: 'SQL',
|
|
78
|
+
go: 'Go',
|
|
79
|
+
rs: 'Rust',
|
|
80
|
+
rust: 'Rust',
|
|
81
|
+
java: 'Java',
|
|
82
|
+
kt: 'Kotlin',
|
|
83
|
+
kotlin: 'Kotlin',
|
|
84
|
+
swift: 'Swift',
|
|
85
|
+
c: 'C',
|
|
86
|
+
h: 'C',
|
|
87
|
+
cpp: 'C++',
|
|
88
|
+
cxx: 'C++',
|
|
89
|
+
cc: 'C++',
|
|
90
|
+
cs: 'C#',
|
|
91
|
+
csharp: 'C#',
|
|
92
|
+
php: 'PHP',
|
|
93
|
+
rb: 'Ruby',
|
|
94
|
+
ruby: 'Ruby',
|
|
95
|
+
diff: 'Diff',
|
|
96
|
+
patch: 'Patch',
|
|
97
|
+
csv: 'CSV',
|
|
98
|
+
graphql: 'GraphQL',
|
|
99
|
+
dockerfile: 'Dockerfile',
|
|
100
|
+
txt: 'Text',
|
|
101
|
+
text: 'Text',
|
|
102
|
+
};
|
|
103
|
+
const EXTENSION_BY_LANG = {
|
|
104
|
+
html: 'html',
|
|
105
|
+
svg: 'svg',
|
|
106
|
+
xml: 'xml',
|
|
107
|
+
css: 'css',
|
|
108
|
+
scss: 'scss',
|
|
109
|
+
less: 'less',
|
|
110
|
+
js: 'js',
|
|
111
|
+
javascript: 'js',
|
|
112
|
+
jsx: 'jsx',
|
|
113
|
+
mjs: 'mjs',
|
|
114
|
+
cjs: 'cjs',
|
|
115
|
+
ts: 'ts',
|
|
116
|
+
typescript: 'ts',
|
|
117
|
+
tsx: 'tsx',
|
|
118
|
+
py: 'py',
|
|
119
|
+
python: 'py',
|
|
120
|
+
json: 'json',
|
|
121
|
+
jsonc: 'jsonc',
|
|
122
|
+
json5: 'json5',
|
|
123
|
+
yaml: 'yaml',
|
|
124
|
+
yml: 'yml',
|
|
125
|
+
toml: 'toml',
|
|
126
|
+
md: 'md',
|
|
127
|
+
markdown: 'md',
|
|
128
|
+
mdx: 'mdx',
|
|
129
|
+
sh: 'sh',
|
|
130
|
+
bash: 'sh',
|
|
131
|
+
zsh: 'sh',
|
|
132
|
+
shell: 'sh',
|
|
133
|
+
sql: 'sql',
|
|
134
|
+
go: 'go',
|
|
135
|
+
rs: 'rs',
|
|
136
|
+
rust: 'rs',
|
|
137
|
+
java: 'java',
|
|
138
|
+
kt: 'kt',
|
|
139
|
+
swift: 'swift',
|
|
140
|
+
c: 'c',
|
|
141
|
+
cpp: 'cpp',
|
|
142
|
+
cs: 'cs',
|
|
143
|
+
php: 'php',
|
|
144
|
+
rb: 'rb',
|
|
145
|
+
diff: 'diff',
|
|
146
|
+
patch: 'patch',
|
|
147
|
+
csv: 'csv',
|
|
148
|
+
};
|
|
149
|
+
/** Decode common HTML entities in extracted `<title>` / `<h1>` text. */
|
|
150
|
+
function decodeBasicEntities(raw) {
|
|
151
|
+
return raw
|
|
152
|
+
.replaceAll('&', '&')
|
|
153
|
+
.replaceAll('<', '<')
|
|
154
|
+
.replaceAll('>', '>')
|
|
155
|
+
.replaceAll('"', '"')
|
|
156
|
+
.replaceAll(''', "'")
|
|
157
|
+
.replaceAll(''', "'")
|
|
158
|
+
.replaceAll(' ', ' ');
|
|
159
|
+
}
|
|
160
|
+
/** Collapse whitespace and clamp length for a single-line UI title. */
|
|
161
|
+
function cleanTitleText(raw) {
|
|
162
|
+
return decodeBasicEntities(raw.replace(/<[^>]*>/g, ' '))
|
|
163
|
+
.replace(/\s+/g, ' ')
|
|
164
|
+
.trim()
|
|
165
|
+
.slice(0, 80);
|
|
166
|
+
}
|
|
167
|
+
/** Extract standalone flag tokens from fence `meta` (outside `key=value` pairs). */
|
|
168
|
+
function extractMetaTokens(meta) {
|
|
169
|
+
const tokens = new Set();
|
|
170
|
+
if (meta === undefined)
|
|
171
|
+
return tokens;
|
|
172
|
+
const stripped = meta.replace(/\b[a-z_-]+\s*=\s*(?:"[^"]*"|'[^']*'|\S+)/gi, ' ');
|
|
173
|
+
for (const part of stripped.split(/\s+/)) {
|
|
174
|
+
const normalized = part.trim().toLowerCase();
|
|
175
|
+
if (normalized.length > 0)
|
|
176
|
+
tokens.add(normalized);
|
|
177
|
+
}
|
|
178
|
+
return tokens;
|
|
179
|
+
}
|
|
180
|
+
/** Compute line count and longest line length in one pass. */
|
|
181
|
+
function measureLines(code) {
|
|
182
|
+
const trimmed = code.trim();
|
|
183
|
+
if (trimmed.length === 0)
|
|
184
|
+
return { lines: 0, maxLineLength: 0 };
|
|
185
|
+
const split = trimmed.split(/\r?\n/);
|
|
186
|
+
let maxLineLength = 0;
|
|
187
|
+
for (const line of split) {
|
|
188
|
+
if (line.length > maxLineLength)
|
|
189
|
+
maxLineLength = line.length;
|
|
190
|
+
}
|
|
191
|
+
return { lines: split.length, maxLineLength };
|
|
192
|
+
}
|
|
193
|
+
/** Classify a lowercased fence language into a coarse content category. */
|
|
194
|
+
export function classifyContentCategory(lang) {
|
|
195
|
+
const normalized = lang.trim().toLowerCase();
|
|
196
|
+
if (normalized === 'html')
|
|
197
|
+
return 'html';
|
|
198
|
+
if (normalized === 'svg')
|
|
199
|
+
return 'svg';
|
|
200
|
+
if (MARKDOWN_LANGS.has(normalized))
|
|
201
|
+
return 'markdown';
|
|
202
|
+
if (DATA_LANGS.has(normalized))
|
|
203
|
+
return 'data';
|
|
204
|
+
if (DIFF_LANGS.has(normalized))
|
|
205
|
+
return 'diff';
|
|
206
|
+
return 'code';
|
|
207
|
+
}
|
|
208
|
+
/** Return a clean human-facing label for a fence language identifier. */
|
|
209
|
+
export function formatFenceLanguageLabel(lang) {
|
|
210
|
+
const normalized = lang.trim().toLowerCase();
|
|
211
|
+
if (normalized.length === 0)
|
|
212
|
+
return 'Text';
|
|
213
|
+
return LANGUAGE_LABELS[normalized] ?? normalized.toUpperCase();
|
|
214
|
+
}
|
|
215
|
+
/** Return an appropriate download file extension for an artifact kind + language. */
|
|
216
|
+
export function fileExtensionForFence(kind, lang) {
|
|
217
|
+
if (kind === 'html')
|
|
218
|
+
return 'html';
|
|
219
|
+
if (kind === 'svg')
|
|
220
|
+
return 'svg';
|
|
221
|
+
const normalized = lang?.trim().toLowerCase() ?? '';
|
|
222
|
+
return EXTENSION_BY_LANG[normalized] ?? 'txt';
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Analyze an HTML snippet to determine whether it is complex enough to display
|
|
226
|
+
* as a compact Document Expand Card in the Chat flow instead of an inline iframe.
|
|
227
|
+
*/
|
|
228
|
+
export function analyzeHtmlComplexity(code, meta) {
|
|
229
|
+
const bytes = utf8ByteLength(code);
|
|
230
|
+
const { lines, maxLineLength } = measureLines(code);
|
|
231
|
+
let scriptChars = 0;
|
|
232
|
+
let scriptText = '';
|
|
233
|
+
let hasExternalScript = false;
|
|
234
|
+
const withoutScripts = code.replace(SCRIPT_BLOCK_RE, (_full, attrs, body) => {
|
|
235
|
+
if (/\bsrc\s*=/i.test(attrs))
|
|
236
|
+
hasExternalScript = true;
|
|
237
|
+
const cleanBody = body.trim();
|
|
238
|
+
scriptChars += cleanBody.length;
|
|
239
|
+
if (cleanBody.length > 0)
|
|
240
|
+
scriptText += `${cleanBody}\n`;
|
|
241
|
+
return ' ';
|
|
242
|
+
});
|
|
243
|
+
let styleChars = 0;
|
|
244
|
+
let styleText = '';
|
|
245
|
+
const markupOnly = withoutScripts.replace(STYLE_BLOCK_RE, (_full, body) => {
|
|
246
|
+
const cleanBody = body.trim();
|
|
247
|
+
styleChars += cleanBody.length;
|
|
248
|
+
if (cleanBody.length > 0)
|
|
249
|
+
styleText += `${cleanBody}\n`;
|
|
250
|
+
return ' ';
|
|
251
|
+
});
|
|
252
|
+
const isFullDocument = FULL_DOC_RE.test(code) || (HTML_TAG_RE.test(code) && BODY_TAG_RE.test(code));
|
|
253
|
+
const hasExternalAssets = hasExternalScript || EXTERNAL_ASSET_RE.test(code);
|
|
254
|
+
const hasScript = scriptChars > 0 || hasExternalScript;
|
|
255
|
+
const hasCanvasOrSvg = CANVAS_OR_SVG_RE.test(markupOnly);
|
|
256
|
+
const hasViewportLayout = VIEWPORT_LAYOUT_RE.test(styleText) || VIEWPORT_LAYOUT_RE.test(markupOnly);
|
|
257
|
+
const hasHeavyRuntimeApi = scriptChars > 0 && HEAVY_RUNTIME_API_RE.test(scriptText);
|
|
258
|
+
const hasResponsiveOrAnimCss = styleChars >= 600 && RESPONSIVE_OR_ANIM_CSS_RE.test(styleText);
|
|
259
|
+
const tagCount = markupOnly.match(ELEMENT_TAG_RE)?.length ?? 0;
|
|
260
|
+
const landmarkCount = markupOnly.match(LANDMARK_TAG_RE)?.length ?? 0;
|
|
261
|
+
const metrics = {
|
|
262
|
+
bytes,
|
|
263
|
+
lines,
|
|
264
|
+
maxLineLength,
|
|
265
|
+
tagCount,
|
|
266
|
+
landmarkCount,
|
|
267
|
+
scriptChars,
|
|
268
|
+
styleChars,
|
|
269
|
+
};
|
|
270
|
+
const metaTokens = extractMetaTokens(meta);
|
|
271
|
+
if (metaTokens.has('inline')) {
|
|
272
|
+
return { isComplex: false, category: 'html', score: 0, reasons: ['meta-override'], metrics };
|
|
273
|
+
}
|
|
274
|
+
if (metaTokens.has('sidebar') || metaTokens.has('artifact') || metaTokens.has('document')) {
|
|
275
|
+
return {
|
|
276
|
+
isComplex: true,
|
|
277
|
+
category: 'html',
|
|
278
|
+
score: COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
279
|
+
reasons: ['meta-override'],
|
|
280
|
+
metrics,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
let score = 0;
|
|
284
|
+
const reasons = [];
|
|
285
|
+
if (bytes >= 8192) {
|
|
286
|
+
score += 5;
|
|
287
|
+
reasons.push('large-size');
|
|
288
|
+
}
|
|
289
|
+
else if (bytes >= 4096) {
|
|
290
|
+
score += 3;
|
|
291
|
+
reasons.push('large-size');
|
|
292
|
+
}
|
|
293
|
+
else if (bytes >= 2500) {
|
|
294
|
+
score += 1;
|
|
295
|
+
}
|
|
296
|
+
if (lines >= 150) {
|
|
297
|
+
score += 4;
|
|
298
|
+
reasons.push('many-lines');
|
|
299
|
+
}
|
|
300
|
+
else if (lines >= 90) {
|
|
301
|
+
score += 2;
|
|
302
|
+
reasons.push('many-lines');
|
|
303
|
+
}
|
|
304
|
+
else if (lines >= 60) {
|
|
305
|
+
score += 1;
|
|
306
|
+
}
|
|
307
|
+
if (isFullDocument) {
|
|
308
|
+
score += 2;
|
|
309
|
+
reasons.push('full-document');
|
|
310
|
+
}
|
|
311
|
+
if (scriptChars >= 2000) {
|
|
312
|
+
score += 3;
|
|
313
|
+
reasons.push('substantial-script');
|
|
314
|
+
}
|
|
315
|
+
else if (scriptChars >= 800) {
|
|
316
|
+
score += 2;
|
|
317
|
+
reasons.push('substantial-script');
|
|
318
|
+
}
|
|
319
|
+
else if (hasScript) {
|
|
320
|
+
score += 1;
|
|
321
|
+
}
|
|
322
|
+
if (hasHeavyRuntimeApi) {
|
|
323
|
+
score += 2;
|
|
324
|
+
reasons.push('heavy-runtime-api');
|
|
325
|
+
}
|
|
326
|
+
if (hasExternalAssets) {
|
|
327
|
+
score += 2;
|
|
328
|
+
reasons.push('external-assets');
|
|
329
|
+
}
|
|
330
|
+
if (styleChars >= 2500) {
|
|
331
|
+
score += 3;
|
|
332
|
+
reasons.push('substantial-style');
|
|
333
|
+
}
|
|
334
|
+
else if (styleChars >= 1000) {
|
|
335
|
+
score += 2;
|
|
336
|
+
reasons.push('substantial-style');
|
|
337
|
+
}
|
|
338
|
+
if (hasViewportLayout) {
|
|
339
|
+
score += 2;
|
|
340
|
+
reasons.push('viewport-layout');
|
|
341
|
+
}
|
|
342
|
+
if (hasResponsiveOrAnimCss) {
|
|
343
|
+
score += 1;
|
|
344
|
+
}
|
|
345
|
+
if (tagCount >= 60) {
|
|
346
|
+
score += 3;
|
|
347
|
+
reasons.push('rich-dom');
|
|
348
|
+
}
|
|
349
|
+
else if (tagCount >= 35) {
|
|
350
|
+
score += 2;
|
|
351
|
+
reasons.push('rich-dom');
|
|
352
|
+
}
|
|
353
|
+
if (landmarkCount >= 3) {
|
|
354
|
+
score += 2;
|
|
355
|
+
reasons.push('app-landmarks');
|
|
356
|
+
}
|
|
357
|
+
if (hasCanvasOrSvg && hasScript) {
|
|
358
|
+
score += 2;
|
|
359
|
+
reasons.push('interactive-graphics');
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
isComplex: score >= COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
363
|
+
category: 'html',
|
|
364
|
+
score,
|
|
365
|
+
reasons,
|
|
366
|
+
metrics,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Analyze an SVG graphic to determine whether it is a large or dense diagram/illustration
|
|
371
|
+
* better inspected in the full-width right Sidebar workbench.
|
|
372
|
+
*/
|
|
373
|
+
export function analyzeSvgComplexity(code, meta) {
|
|
374
|
+
const bytes = utf8ByteLength(code);
|
|
375
|
+
const { lines, maxLineLength } = measureLines(code);
|
|
376
|
+
let styleChars = 0;
|
|
377
|
+
const markupOnly = code.replace(STYLE_BLOCK_RE, (_full, body) => {
|
|
378
|
+
styleChars += body.trim().length;
|
|
379
|
+
return ' ';
|
|
380
|
+
});
|
|
381
|
+
const primitiveCount = markupOnly.match(SVG_PRIMITIVE_RE)?.length ?? 0;
|
|
382
|
+
const textNodeCount = markupOnly.match(SVG_TEXT_RE)?.length ?? 0;
|
|
383
|
+
const defsFeatureCount = markupOnly.match(SVG_DEFS_FEATURE_RE)?.length ?? 0;
|
|
384
|
+
let canvasWidth = 0;
|
|
385
|
+
let canvasHeight = 0;
|
|
386
|
+
const vb = SVG_VIEWBOX_RE.exec(code);
|
|
387
|
+
if (vb !== null) {
|
|
388
|
+
canvasWidth = Number.parseFloat(vb[1] ?? '0') || 0;
|
|
389
|
+
canvasHeight = Number.parseFloat(vb[2] ?? '0') || 0;
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
canvasWidth = Number.parseFloat(SVG_WIDTH_RE.exec(code)?.[1] ?? '0') || 0;
|
|
393
|
+
canvasHeight = Number.parseFloat(SVG_HEIGHT_RE.exec(code)?.[1] ?? '0') || 0;
|
|
394
|
+
}
|
|
395
|
+
const metrics = {
|
|
396
|
+
bytes,
|
|
397
|
+
lines,
|
|
398
|
+
maxLineLength,
|
|
399
|
+
primitiveCount,
|
|
400
|
+
textNodeCount,
|
|
401
|
+
styleChars,
|
|
402
|
+
};
|
|
403
|
+
const metaTokens = extractMetaTokens(meta);
|
|
404
|
+
if (metaTokens.has('inline')) {
|
|
405
|
+
return { isComplex: false, category: 'svg', score: 0, reasons: ['meta-override'], metrics };
|
|
406
|
+
}
|
|
407
|
+
if (metaTokens.has('sidebar') || metaTokens.has('artifact') || metaTokens.has('document')) {
|
|
408
|
+
return {
|
|
409
|
+
isComplex: true,
|
|
410
|
+
category: 'svg',
|
|
411
|
+
score: COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
412
|
+
reasons: ['meta-override'],
|
|
413
|
+
metrics,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
let score = 0;
|
|
417
|
+
const reasons = [];
|
|
418
|
+
if (bytes >= 8192) {
|
|
419
|
+
score += 5;
|
|
420
|
+
reasons.push('large-size');
|
|
421
|
+
}
|
|
422
|
+
else if (bytes >= 4096) {
|
|
423
|
+
score += 3;
|
|
424
|
+
reasons.push('large-size');
|
|
425
|
+
}
|
|
426
|
+
else if (bytes >= 2500) {
|
|
427
|
+
score += 1;
|
|
428
|
+
}
|
|
429
|
+
if (lines >= 120) {
|
|
430
|
+
score += 4;
|
|
431
|
+
reasons.push('many-lines');
|
|
432
|
+
}
|
|
433
|
+
else if (lines >= 75) {
|
|
434
|
+
score += 2;
|
|
435
|
+
reasons.push('many-lines');
|
|
436
|
+
}
|
|
437
|
+
else if (lines >= 45) {
|
|
438
|
+
score += 1;
|
|
439
|
+
}
|
|
440
|
+
if (primitiveCount >= 55) {
|
|
441
|
+
score += 4;
|
|
442
|
+
reasons.push('rich-vector');
|
|
443
|
+
}
|
|
444
|
+
else if (primitiveCount >= 30) {
|
|
445
|
+
score += 2;
|
|
446
|
+
reasons.push('rich-vector');
|
|
447
|
+
}
|
|
448
|
+
else if (primitiveCount >= 18) {
|
|
449
|
+
score += 1;
|
|
450
|
+
}
|
|
451
|
+
if (textNodeCount >= 12) {
|
|
452
|
+
score += 2;
|
|
453
|
+
reasons.push('text-heavy-diagram');
|
|
454
|
+
}
|
|
455
|
+
else if (textNodeCount >= 6) {
|
|
456
|
+
score += 1;
|
|
457
|
+
}
|
|
458
|
+
if (canvasWidth >= 900 || canvasHeight >= 650) {
|
|
459
|
+
score += 2;
|
|
460
|
+
reasons.push('large-canvas');
|
|
461
|
+
}
|
|
462
|
+
if (defsFeatureCount >= 3) {
|
|
463
|
+
score += 2;
|
|
464
|
+
reasons.push('vector-defs');
|
|
465
|
+
}
|
|
466
|
+
else if (defsFeatureCount >= 1) {
|
|
467
|
+
score += 1;
|
|
468
|
+
}
|
|
469
|
+
if (styleChars >= 400) {
|
|
470
|
+
score += 1;
|
|
471
|
+
}
|
|
472
|
+
return {
|
|
473
|
+
isComplex: score >= COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
474
|
+
category: 'svg',
|
|
475
|
+
score,
|
|
476
|
+
reasons,
|
|
477
|
+
metrics,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Analyze a general code, Markdown, structured-data, or diff fence to decide
|
|
482
|
+
* whether it is overly long/complex for the Chat flow and should move to the Sidebar.
|
|
483
|
+
*/
|
|
484
|
+
export function analyzeCodeComplexity(lang, code, meta) {
|
|
485
|
+
const normalizedLang = lang.trim().toLowerCase();
|
|
486
|
+
const category = classifyContentCategory(normalizedLang);
|
|
487
|
+
const bytes = utf8ByteLength(code);
|
|
488
|
+
const { lines, maxLineLength } = measureLines(code);
|
|
489
|
+
const metaTokens = extractMetaTokens(meta);
|
|
490
|
+
const baseMetrics = { bytes, lines, maxLineLength };
|
|
491
|
+
if (metaTokens.has('inline')) {
|
|
492
|
+
return { isComplex: false, category, score: 0, reasons: ['meta-override'], metrics: baseMetrics };
|
|
493
|
+
}
|
|
494
|
+
if (metaTokens.has('sidebar') || metaTokens.has('artifact') || metaTokens.has('document')) {
|
|
495
|
+
return {
|
|
496
|
+
isComplex: true,
|
|
497
|
+
category,
|
|
498
|
+
score: COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
499
|
+
reasons: ['meta-override'],
|
|
500
|
+
metrics: baseMetrics,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
// Keep KaTeX math formulas inline unless the author explicitly requested a sidebar card.
|
|
504
|
+
if (normalizedLang === 'math') {
|
|
505
|
+
return { isComplex: false, category, score: 0, reasons: [], metrics: baseMetrics };
|
|
506
|
+
}
|
|
507
|
+
let score = 0;
|
|
508
|
+
const reasons = [];
|
|
509
|
+
let symbolCount;
|
|
510
|
+
let headingCount;
|
|
511
|
+
if (bytes >= 10_240) {
|
|
512
|
+
score += 5;
|
|
513
|
+
reasons.push('large-size');
|
|
514
|
+
}
|
|
515
|
+
else if (bytes >= 6144) {
|
|
516
|
+
score += 3;
|
|
517
|
+
reasons.push('large-size');
|
|
518
|
+
}
|
|
519
|
+
else if (bytes >= 3584) {
|
|
520
|
+
score += 1;
|
|
521
|
+
}
|
|
522
|
+
if (lines >= 180) {
|
|
523
|
+
score += 5;
|
|
524
|
+
reasons.push('many-lines');
|
|
525
|
+
}
|
|
526
|
+
else if (lines >= 120) {
|
|
527
|
+
score += 3;
|
|
528
|
+
reasons.push('many-lines');
|
|
529
|
+
}
|
|
530
|
+
else if (lines >= 80) {
|
|
531
|
+
score += 1;
|
|
532
|
+
}
|
|
533
|
+
if (maxLineLength >= 240 && bytes >= 4096) {
|
|
534
|
+
score += 2;
|
|
535
|
+
reasons.push('wide-lines');
|
|
536
|
+
}
|
|
537
|
+
if (category === 'markdown') {
|
|
538
|
+
headingCount = code.match(MARKDOWN_HEADING_RE)?.length ?? 0;
|
|
539
|
+
if (headingCount >= 4) {
|
|
540
|
+
score += 2;
|
|
541
|
+
reasons.push('multi-section-doc');
|
|
542
|
+
}
|
|
543
|
+
else if (headingCount >= 2) {
|
|
544
|
+
score += 1;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
else if (category === 'data') {
|
|
548
|
+
const entries = code.match(DATA_ENTRY_RE)?.length ?? 0;
|
|
549
|
+
if (entries >= 40 || (bytes >= 4096 && maxLineLength >= 240)) {
|
|
550
|
+
score += 2;
|
|
551
|
+
reasons.push('structured-data');
|
|
552
|
+
}
|
|
553
|
+
else if (entries >= 20) {
|
|
554
|
+
score += 1;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
else if (category === 'diff') {
|
|
558
|
+
const files = code.match(DIFF_FILE_RE)?.length ?? 0;
|
|
559
|
+
const hunks = code.match(DIFF_HUNK_RE)?.length ?? 0;
|
|
560
|
+
if (files >= 3 || hunks >= 6) {
|
|
561
|
+
score += 2;
|
|
562
|
+
reasons.push('large-diff');
|
|
563
|
+
}
|
|
564
|
+
else if (files >= 2 || hunks >= 4) {
|
|
565
|
+
score += 1;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
symbolCount = code.match(CODE_SYMBOL_RE)?.length ?? 0;
|
|
570
|
+
if (symbolCount >= 10) {
|
|
571
|
+
score += 2;
|
|
572
|
+
reasons.push('dense-code');
|
|
573
|
+
}
|
|
574
|
+
else if (symbolCount >= 5) {
|
|
575
|
+
score += 1;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return {
|
|
579
|
+
isComplex: score >= COMPLEX_CONTENT_SCORE_THRESHOLD,
|
|
580
|
+
category,
|
|
581
|
+
score,
|
|
582
|
+
reasons,
|
|
583
|
+
metrics: {
|
|
584
|
+
bytes,
|
|
585
|
+
lines,
|
|
586
|
+
maxLineLength,
|
|
587
|
+
symbolCount,
|
|
588
|
+
headingCount,
|
|
589
|
+
},
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
/** Unified complexity analyzer dispatching HTML, SVG, and general code/document fences. */
|
|
593
|
+
export function analyzeFenceComplexity(lang, code, meta) {
|
|
594
|
+
const normalized = lang.trim().toLowerCase();
|
|
595
|
+
if (normalized === 'html')
|
|
596
|
+
return analyzeHtmlComplexity(code, meta);
|
|
597
|
+
if (normalized === 'svg')
|
|
598
|
+
return analyzeSvgComplexity(code, meta);
|
|
599
|
+
return analyzeCodeComplexity(normalized, code, meta);
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Decide whether a still-streaming fence should collapse early into a "Generating…"
|
|
603
|
+
* Document Expand Card instead of flooding the Chat flow with hundreds of raw lines.
|
|
604
|
+
*
|
|
605
|
+
* Triggers immediately on explicit `sidebar`/`artifact`/`document` meta hints, full
|
|
606
|
+
* HTML document openings (`<!doctype html>` or `<html>` + `<head>`/`<style>`), large
|
|
607
|
+
* SVG canvases, or as soon as the partial body crosses the standard complexity threshold.
|
|
608
|
+
*/
|
|
609
|
+
export function shouldCollapseWhileStreaming(lang, code, meta) {
|
|
610
|
+
const metaTokens = extractMetaTokens(meta);
|
|
611
|
+
if (metaTokens.has('inline'))
|
|
612
|
+
return false;
|
|
613
|
+
if (metaTokens.has('sidebar') || metaTokens.has('artifact') || metaTokens.has('document'))
|
|
614
|
+
return true;
|
|
615
|
+
const normalized = lang.trim().toLowerCase();
|
|
616
|
+
if (normalized === 'math')
|
|
617
|
+
return false;
|
|
618
|
+
if (normalized === 'html') {
|
|
619
|
+
if (FULL_DOC_RE.test(code))
|
|
620
|
+
return true;
|
|
621
|
+
if (HTML_TAG_RE.test(code) && /<(?:head|style|body)\b/i.test(code))
|
|
622
|
+
return true;
|
|
623
|
+
return analyzeHtmlComplexity(code, meta).isComplex;
|
|
624
|
+
}
|
|
625
|
+
if (normalized === 'svg') {
|
|
626
|
+
const vb = SVG_VIEWBOX_RE.exec(code);
|
|
627
|
+
if (vb !== null) {
|
|
628
|
+
const w = Number.parseFloat(vb[1] ?? '0') || 0;
|
|
629
|
+
const h = Number.parseFloat(vb[2] ?? '0') || 0;
|
|
630
|
+
if (w >= 900 || h >= 650)
|
|
631
|
+
return true;
|
|
632
|
+
}
|
|
633
|
+
return analyzeSvgComplexity(code, meta).isComplex;
|
|
634
|
+
}
|
|
635
|
+
return analyzeCodeComplexity(normalized, code, meta).isComplex;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Derive a concise human-readable document title from fence metadata or content structure
|
|
639
|
+
* (`title`/`file`/`filename`/`path` meta, `<title>`, `<h1>`, Markdown `# Heading`, or
|
|
640
|
+
* leading path comment / primary symbol) before falling back to a localized default.
|
|
641
|
+
*/
|
|
642
|
+
export function deriveFenceDocumentTitle(lang, code, meta, fallback) {
|
|
643
|
+
const normalized = lang.trim().toLowerCase();
|
|
644
|
+
const defaultFallback = fallback ?? formatFenceLanguageLabel(normalized);
|
|
645
|
+
const trimmedMeta = meta?.trim();
|
|
646
|
+
if (trimmedMeta !== undefined && trimmedMeta.length > 0) {
|
|
647
|
+
const namedAttr = /\b(?:title|file|filename|path)\s*=\s*(?:"([^"]+)"|'([^']+)'|(\S+))/i.exec(trimmedMeta);
|
|
648
|
+
const extracted = namedAttr?.[1] ?? namedAttr?.[2] ?? namedAttr?.[3];
|
|
649
|
+
if (extracted !== undefined) {
|
|
650
|
+
const cleaned = cleanTitleText(extracted);
|
|
651
|
+
if (cleaned.length > 0)
|
|
652
|
+
return cleaned;
|
|
653
|
+
}
|
|
654
|
+
// Support bare filename hints such as ```ts src/server.ts
|
|
655
|
+
const bareFile = /(?:^|\s)([\w./-]+\.[a-z0-9]{1,8})(?=\s|$)/i.exec(trimmedMeta);
|
|
656
|
+
if (bareFile?.[1] !== undefined) {
|
|
657
|
+
const cleaned = cleanTitleText(bareFile[1]);
|
|
658
|
+
if (cleaned.length > 0)
|
|
659
|
+
return cleaned;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (normalized === 'html' || normalized === 'svg') {
|
|
663
|
+
const titleTag = /<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(code);
|
|
664
|
+
const tagTitle = titleTag?.[1] !== undefined ? cleanTitleText(titleTag[1]) : '';
|
|
665
|
+
if (tagTitle.length > 0 && !GENERIC_TITLES.has(tagTitle.toLowerCase())) {
|
|
666
|
+
return tagTitle;
|
|
667
|
+
}
|
|
668
|
+
if (normalized === 'html') {
|
|
669
|
+
const headingTag = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(code);
|
|
670
|
+
const headingTitle = headingTag?.[1] !== undefined ? cleanTitleText(headingTag[1]) : '';
|
|
671
|
+
if (headingTitle.length > 0)
|
|
672
|
+
return headingTitle;
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
const ariaLabel = /<svg\b[^>]*\baria-label\s*=\s*(?:"([^"]+)"|'([^']+)')/i.exec(code);
|
|
676
|
+
const svgLabel = ariaLabel?.[1] ?? ariaLabel?.[2];
|
|
677
|
+
if (svgLabel !== undefined) {
|
|
678
|
+
const cleaned = cleanTitleText(svgLabel);
|
|
679
|
+
if (cleaned.length > 0)
|
|
680
|
+
return cleaned;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (tagTitle.length > 0)
|
|
684
|
+
return tagTitle;
|
|
685
|
+
return defaultFallback;
|
|
686
|
+
}
|
|
687
|
+
if (MARKDOWN_LANGS.has(normalized)) {
|
|
688
|
+
const mdHeading = /^#\s+(.+)$/m.exec(code);
|
|
689
|
+
if (mdHeading?.[1] !== undefined) {
|
|
690
|
+
const cleaned = cleanTitleText(mdHeading[1].replace(/[#*`~_]+/g, ''));
|
|
691
|
+
if (cleaned.length > 0)
|
|
692
|
+
return cleaned;
|
|
693
|
+
}
|
|
694
|
+
return defaultFallback;
|
|
695
|
+
}
|
|
696
|
+
if (DIFF_LANGS.has(normalized)) {
|
|
697
|
+
const diffPath = /^\+\+\+\s+(?:b\/)?([^\s\t]+)/m.exec(code);
|
|
698
|
+
if (diffPath?.[1] !== undefined && diffPath[1] !== '/dev/null') {
|
|
699
|
+
return cleanTitleText(diffPath[1]);
|
|
700
|
+
}
|
|
701
|
+
return defaultFallback;
|
|
702
|
+
}
|
|
703
|
+
// Leading file-path comment on line 1 (e.g. `// src/app.ts` or `# scripts/run.py`)
|
|
704
|
+
const firstLine = code.trimStart().split(/\r?\n/, 1)[0] ?? '';
|
|
705
|
+
const pathComment = /^(?:\/\/|#|--|\/\*)\s*(?:file:\s*)?([\w./-]+\.[a-z0-9]{1,8})(?:\s*\*\/)?\s*$/i.exec(firstLine);
|
|
706
|
+
if (pathComment?.[1] !== undefined) {
|
|
707
|
+
return cleanTitleText(pathComment[1]);
|
|
708
|
+
}
|
|
709
|
+
return defaultFallback;
|
|
710
|
+
}
|
|
711
|
+
/** Format a UTF-8 byte count into a compact human-readable size label (e.g. `9.4 KB`). */
|
|
712
|
+
export function formatByteSize(bytes) {
|
|
713
|
+
if (!Number.isFinite(bytes) || bytes <= 0)
|
|
714
|
+
return '0 B';
|
|
715
|
+
if (bytes < 1024)
|
|
716
|
+
return `${Math.round(bytes)} B`;
|
|
717
|
+
const kb = bytes / 1024;
|
|
718
|
+
if (kb < 100)
|
|
719
|
+
return `${kb.toFixed(1)} KB`;
|
|
720
|
+
if (kb < 1024)
|
|
721
|
+
return `${Math.round(kb)} KB`;
|
|
722
|
+
return `${(kb / 1024).toFixed(1)} MB`;
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Compute a deterministic, collision-resistant artifact id from kind, language, and code.
|
|
726
|
+
*
|
|
727
|
+
* Ensures re-clicking the same document card focuses the existing right-Sidebar tab
|
|
728
|
+
* instead of spawning duplicates, and lets restored tabs reconnect across reloads.
|
|
729
|
+
*/
|
|
730
|
+
export function computeArtifactId(kind, code, lang) {
|
|
731
|
+
const normalizedLang = (lang ?? kind)
|
|
732
|
+
.trim()
|
|
733
|
+
.toLowerCase()
|
|
734
|
+
.replace(/[^a-z0-9_-]/g, '') || kind;
|
|
735
|
+
const seed = `${kind}:${normalizedLang}\0${code}`;
|
|
736
|
+
let h1 = 0x811c9dc5;
|
|
737
|
+
let h2 = 0x9e3779b9;
|
|
738
|
+
for (let i = 0; i < seed.length; i += 1) {
|
|
739
|
+
const ch = seed.charCodeAt(i);
|
|
740
|
+
h1 ^= ch;
|
|
741
|
+
h1 = Math.imul(h1, 0x01000193);
|
|
742
|
+
h2 ^= ch + (i & 0xff);
|
|
743
|
+
h2 = Math.imul(h2, 0x85ebca6b);
|
|
744
|
+
}
|
|
745
|
+
const part1 = (h1 >>> 0).toString(16).padStart(8, '0');
|
|
746
|
+
const part2 = (h2 >>> 0).toString(16).padStart(8, '0');
|
|
747
|
+
return `${normalizedLang}-${part1}${part2}-${code.length.toString(36)}`;
|
|
748
|
+
}
|