aegon-lv97 1.0.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 (78) hide show
  1. package/gen-ai/build-report/chartStreamRefs.ts +227 -0
  2. package/gen-ai/build-report/coherence-check/index.vue +559 -0
  3. package/gen-ai/build-report/components/ReportChapterWorkspace.vue +4571 -0
  4. package/gen-ai/build-report/components/ReportConfigPanel.vue +727 -0
  5. package/gen-ai/build-report/components/ReportGenerateSettingsPanel.vue +2361 -0
  6. package/gen-ai/build-report/components/ReportGeneratingPanel.vue +1765 -0
  7. package/gen-ai/build-report/components/ReportPromptPanel.vue +625 -0
  8. package/gen-ai/build-report/components/ReportSourceFileSummary.vue +665 -0
  9. package/gen-ai/build-report/components/ReportSourcesPanel.vue +1327 -0
  10. package/gen-ai/build-report/components/ReportTemplateDetail.vue +191 -0
  11. package/gen-ai/build-report/components/ReportTemplateEditorFormPanel.vue +667 -0
  12. package/gen-ai/build-report/components/ReportTemplatePicker.vue +302 -0
  13. package/gen-ai/build-report/components/ReportWorkflowSidebar.vue +148 -0
  14. package/gen-ai/build-report/components/paramsSetting.vue +886 -0
  15. package/gen-ai/build-report/components/reportEdit.vue +2283 -0
  16. package/gen-ai/build-report/index.vue +856 -0
  17. package/gen-ai/build-report/report-domain.ts +1133 -0
  18. package/gen-ai/build-report/report-template-data.ts +295 -0
  19. package/gen-ai/build-report/useReportWorkflow.ts +1386 -0
  20. package/gen-ai/common/assets/NotoSans-SC.woff2 +0 -0
  21. package/gen-ai/common/assets/NotoSans-TC.woff2 +0 -0
  22. package/gen-ai/common/assets/NotoSans.woff2 +0 -0
  23. package/gen-ai/common/assets/fonts.css +278 -0
  24. package/gen-ai/common/assets/pagination.css +163 -0
  25. package/gen-ai/common/directives/btnLoading.ts +455 -0
  26. package/gen-ai/common/directives/debounce.ts +98 -0
  27. package/gen-ai/common/directives/index.ts +30 -0
  28. package/gen-ai/common/en.md +417 -0
  29. package/gen-ai/common/index.ts +36 -0
  30. package/gen-ai/common/types/component-expose.ts +9 -0
  31. package/gen-ai/common/utils/api-res-status.ts +7 -0
  32. package/gen-ai/common/utils/navigation.ts +59 -0
  33. package/gen-ai/common/utils/remote-request.ts +45 -0
  34. package/gen-ai/common/utils/scroll.ts +577 -0
  35. package/gen-ai/components/AIExport/docx-export.ts +950 -0
  36. package/gen-ai/components/AIExport/docxExport.ts +2566 -0
  37. package/gen-ai/components/AIExport/index.ts +52 -0
  38. package/gen-ai/components/AIExport/parseMarkdownHtml.ts +653 -0
  39. package/gen-ai/components/CapsuleScrollbar.vue +149 -0
  40. package/gen-ai/components/ChapterTitleScroll.vue +468 -0
  41. package/gen-ai/components/EntryHeroNavCards.vue +379 -0
  42. package/gen-ai/components/GenAiPagination.vue +52 -0
  43. package/gen-ai/components/ModelCard.vue +1114 -0
  44. package/gen-ai/components/Preview/FilePreviewPage.vue +949 -0
  45. package/gen-ai/components/Preview/PreviewCapsuleScroll.vue +205 -0
  46. package/gen-ai/components/Preview/PreviewOutlineTree.vue +148 -0
  47. package/gen-ai/components/Preview/index.ts +11 -0
  48. package/gen-ai/components/Preview/preview.ts +724 -0
  49. package/gen-ai/components/PromptField.vue +505 -0
  50. package/gen-ai/components/RecentReportsTable.vue +974 -0
  51. package/gen-ai/components/ReportCollapsibleSection.vue +172 -0
  52. package/gen-ai/components/ReportHistoryList.vue +637 -0
  53. package/gen-ai/components/ReportSectionConfirmPopover.vue +251 -0
  54. package/gen-ai/components/editor/ChapterTiptapEditor.vue +3718 -0
  55. package/gen-ai/components/editor/StructureBlockView.vue +441 -0
  56. package/gen-ai/components/editor/TiptapToolbar.vue +1036 -0
  57. package/gen-ai/components/editor/TypewriterDocEditor.vue +422 -0
  58. package/gen-ai/components/editor/_StructureOrgNode.vue +326 -0
  59. package/gen-ai/components/editor/index.ts +28 -0
  60. package/gen-ai/components/editor/parseMarkdownHtml.ts +754 -0
  61. package/gen-ai/components/editor/reviewCitationTip.ts +163 -0
  62. package/gen-ai/gen-entry/api/index.ts +32 -0
  63. package/gen-ai/gen-entry/index.vue +287 -0
  64. package/gen-ai/gen-entry/types/index.ts +4 -0
  65. package/gen-ai/i.mark +2 -0
  66. package/gen-ai/management-center/index.vue +1815 -0
  67. package/gen-ai/management-center/mockData.ts +248 -0
  68. package/gen-ai/management-center/types/index.ts +37 -0
  69. package/gen-ai/model-manager/TemplateEditorFormPanel.vue +661 -0
  70. package/gen-ai/model-manager/api/index.ts +32 -0
  71. package/gen-ai/model-manager/api/mockApi.ts +33 -0
  72. package/gen-ai/model-manager/index.vue +1583 -0
  73. package/gen-ai/model-manager/mockData.ts +177 -0
  74. package/gen-ai/model-manager/template-detail-shared.ts +154 -0
  75. package/gen-ai/model-manager/template-editor.vue +345 -0
  76. package/gen-ai/model-manager/types/index.ts +40 -0
  77. package/gen-ai/model-manager/utils.ts +25 -0
  78. package/package.json +12 -0
@@ -0,0 +1,653 @@
1
+ /**
2
+ * 接口 sectionContent → HTML
3
+ *
4
+ * //0918 tip 兼容顺序:Markdown → HTML → Element Plus
5
+ * +link 继续走原解析:Markdown [text](url) / HTML <a> / el-link → a.report-tiptap-link
6
+ * tip 转成原 citation 标记(点击弹出 report-chapter-review-popover)
7
+ */
8
+ import { Marked } from 'marked'
9
+ //0918 tip / REF:与 editor 共用 resolve,避免导出侧半套迁移
10
+ import { REF_MARKER_RE, REF_ANY_MARKER_RE, resolveRefMarker } from '../editor/reviewCitationTip'
11
+ //0918
12
+
13
+ function escapeHtml(value: string) {
14
+ return value
15
+ .replace(/&/g, '&amp;')
16
+ .replace(/</g, '&lt;')
17
+ .replace(/>/g, '&gt;')
18
+ .replace(/"/g, '&quot;')
19
+ }
20
+
21
+ function escapeAttr(value: string) {
22
+ return escapeHtml(String(value).replace(/\s+/g, ' ').trim())
23
+ }
24
+
25
+ function splitTipLink(tip: string) {
26
+ const raw = String(tip || '').trim()
27
+ const md = raw.match(/\[([^\]]+)\]\((https?:[^)\s]+)(?:\s+"[^"]*")?\)/i)
28
+ if (md?.[1] != null && md[2] != null) {
29
+ return {
30
+ text: raw.replace(md[0], '').replace(/\s+/g, ' ').trim(),
31
+ href: md[2].trim(),
32
+ linkLabel: md[1].trim(),
33
+ }
34
+ }
35
+ const html = raw.match(/<a\b[^>]*href=["'](https?:[^"']+)["'][^>]*>([\s\S]*?)<\/a>/i)
36
+ if (html?.[1] != null && html[2] != null) {
37
+ return {
38
+ text: raw.replace(html[0], '').replace(/\s+/g, ' ').trim(),
39
+ href: html[1].trim(),
40
+ linkLabel: html[2].replace(/<[^>]+>/g, '').trim(),
41
+ }
42
+ }
43
+ const paren = raw.match(/^(.*?)\s*\((https?:[^)\s]+)\)\s*$/i)
44
+ if (paren?.[1] != null && paren[2] != null) {
45
+ return {
46
+ text: paren[1].replace(/\s+/g, ' ').trim(),
47
+ href: paren[2].trim(),
48
+ linkLabel: paren[2].trim(),
49
+ }
50
+ }
51
+ return { text: raw, href: '', linkLabel: '' }
52
+ }
53
+
54
+ //0918 tip citation + REF 直鏈屬性
55
+ function citationHtml(
56
+ id: string,
57
+ tip = '',
58
+ extra?: {
59
+ sourceName?: string
60
+ filePath?: string
61
+ filePreviewUrl?: string
62
+ chunkId?: string
63
+ }
64
+ ) {
65
+ const n = String(id).trim() || '1'
66
+ const { text, href, linkLabel } = splitTipLink(tip)
67
+ const tipAttr = text ? ` data-tip="${escapeAttr(text)}"` : ''
68
+ const hrefAttr = href ? ` data-href="${escapeAttr(href)}"` : ''
69
+ const labelAttr = linkLabel ? ` data-link-label="${escapeAttr(linkLabel)}"` : ''
70
+ const sourceNameAttr = extra?.sourceName
71
+ ? ` data-source-name="${escapeAttr(extra.sourceName)}"`
72
+ : ''
73
+ const filePathAttr = extra?.filePath ? ` data-file-path="${escapeAttr(extra.filePath)}"` : ''
74
+ const filePreviewAttr = extra?.filePreviewUrl
75
+ ? ` data-file-preview-url="${escapeAttr(extra.filePreviewUrl)}"`
76
+ : ''
77
+ const chunkIdAttr = extra?.chunkId ? ` data-chunk-id="${escapeAttr(extra.chunkId)}"` : ''
78
+ return `<span class="report-tiptap-citation" data-citation="${escapeHtml(n)}"${tipAttr}${hrefAttr}${labelAttr}${sourceNameAttr}${filePathAttr}${filePreviewAttr}${chunkIdAttr}>${escapeHtml(n)}</span>`
79
+ }
80
+
81
+ // REF_MARKER_RE / resolveRefMarker → ../editor/reviewCitationTip(0918 归类)
82
+
83
+ function isRealHref(href: string) {
84
+ const value = String(href || '').trim()
85
+ if (!value || value === '#') return false
86
+ if (/^#(?:fn|footnote|cite|ref)/i.test(value)) return false
87
+ return /^(https?:|mailto:|tel:|\/|\.\/|\.\.\/|#\/)/i.test(value) || /^[a-z][a-z0-9+.-]*:/i.test(value)
88
+ }
89
+
90
+ function isCitationLabel(text: string) {
91
+ const label = text.replace(/<[^>]+>/g, '').trim()
92
+ return /^\[?\d+\]?$/.test(label) || /^[+*]?\d+$/.test(label)
93
+ }
94
+
95
+ function idFromLabel(label: string, fallback: string) {
96
+ const m = String(label).replace(/<[^>]+>/g, '').trim().match(/(\d+)/)
97
+ return m?.[1] ?? fallback
98
+ }
99
+
100
+ let citationSeq = 0
101
+ function nextId(label: string) {
102
+ const fromLabel = idFromLabel(label, '')
103
+ if (fromLabel) return fromLabel
104
+ citationSeq += 1
105
+ return String(citationSeq)
106
+ }
107
+
108
+ function extractAttr(tag: string, name: string) {
109
+ const m = tag.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'))
110
+ return (m?.[1] ?? m?.[2] ?? m?.[3] ?? '').trim()
111
+ }
112
+
113
+ const PLACEHOLDER = '%%GENAI_BLOCK_'
114
+
115
+ function protectBlocks(source: string) {
116
+ const slots: string[] = []
117
+ const stash = (html: string) => {
118
+ const i = slots.length
119
+ slots.push(html)
120
+ return `${PLACEHOLDER}${i}%%`
121
+ }
122
+ let text = source.replace(
123
+ /<span\b[^>]*class="[^"]*report-tiptap-citation[^"]*"[^>]*>[\s\S]*?<\/span>/gi,
124
+ (m) => stash(m)
125
+ )
126
+ text = text.replace(/<(table|pre|blockquote|details)[\s\S]*?<\/\1>/gi, (m) => stash(m))
127
+ text = text.replace(/<(el-(?:tooltip|popover|link))\b[\s\S]*?<\/\1>/gi, (m) => stash(m))
128
+ return { text, slots }
129
+ }
130
+
131
+ function restoreBlocks(html: string, slots: string[]) {
132
+ return html.replace(new RegExp(`${PLACEHOLDER}(\\d+)%%`, 'g'), (_, i) => slots[Number(i)] ?? '')
133
+ }
134
+
135
+ /** Markdown 层 tip:脚注定义、[^n]、[+n]、[ref:uuid];[+link] / [text](url) 不在此当 tip */
136
+ //0918:先 REF(未命中删除),再旧 [+n]/[^n]
137
+ function applyMarkdownTips(source: string) {
138
+ const footnotes = new Map<string, string>()
139
+ let text = source.replace(/^\[\^(\d+)\]:\s*(.+)$/gm, (_, id: string, tip: string) => {
140
+ footnotes.set(id, tip.trim())
141
+ return ''
142
+ })
143
+ text = text.replace(REF_MARKER_RE, (_full, chunkId: string) => {
144
+ const resolved = resolveRefMarker(chunkId)
145
+ // 未命中:删除占位,只显示已命中 tip;REF 入库后重解析
146
+ if (!resolved) return ''
147
+ return citationHtml(resolved.id, resolved.tip, resolved.extra)
148
+ })
149
+ //0918-1:匹配不到的 [ref:…] 一律过滤为空
150
+ text = text.replace(REF_ANY_MARKER_RE, '')
151
+ REF_MARKER_RE.lastIndex = 0
152
+ REF_ANY_MARKER_RE.lastIndex = 0
153
+ //0918-1
154
+ text = text.replace(/\[\+(\d+)\]/g, (_, id: string) => citationHtml(id))
155
+ text = text.replace(/\[\^(\d+)\](?!:)/g, (_, id: string) =>
156
+ citationHtml(id, footnotes.get(id) || '')
157
+ )
158
+ return { text, footnotes }
159
+ }
160
+ //0918
161
+
162
+ function linkHtml(href: string, inner: string, title = '') {
163
+ const titleAttr = title ? ` title="${escapeAttr(title)}"` : ''
164
+ return `<a href="${escapeHtml(href)}" class="report-tiptap-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${inner}</a>`
165
+ }
166
+
167
+ function isTipHref(href: string, title: string, _label?: string) {
168
+ if (isRealHref(href)) return false
169
+ if (title) return true
170
+ return /^#(?:fn|footnote|cite|ref)/i.test(href)
171
+ }
172
+
173
+ const markedParser = new Marked({
174
+ gfm: true,
175
+ breaks: true,
176
+ renderer: {
177
+ link({ href, title, tokens }) {
178
+ const text = this.parser.parseInline(tokens)
179
+ const tip = String(title || '').trim()
180
+ if (isTipHref(String(href || ''), tip)) {
181
+ return citationHtml(nextId(text), tip)
182
+ }
183
+ return linkHtml(String(href || '#'), text, tip)
184
+ },
185
+ },
186
+ })
187
+
188
+ /** HTML 层:已有 citation / title / 脚注 a / 数字 sup → tip;真实 a → +link */
189
+ function applyHtmlTipsAndLinks(html: string) {
190
+ let out = html.replace(/<a\b([^>]*)>([\s\S]*?)<\/a>/gi, (m, attrs: string, inner: string) => {
191
+ if (/report-tiptap-citation/i.test(attrs)) return m
192
+ const href = extractAttr(attrs, 'href')
193
+ const title = extractAttr(attrs, 'title') || extractAttr(attrs, 'data-tip')
194
+ const label = inner.replace(/<[^>]+>/g, '').trim()
195
+ if (isTipHref(href, title) && !isRealHref(href)) {
196
+ return citationHtml(nextId(label || '1'), title)
197
+ }
198
+ if (/report-tiptap-link/i.test(attrs) && isRealHref(href)) return m
199
+ return linkHtml(href || '#', inner, title)
200
+ })
201
+
202
+ out = out.replace(/<(?:abbr|span)\b([^>]*)>([\s\S]*?)<\/(?:abbr|span)>/gi, (m, attrs: string, inner: string) => {
203
+ if (/report-tiptap-citation/i.test(attrs) || /report-tiptap-link/i.test(attrs)) return m
204
+ const citationId = extractAttr(attrs, 'data-citation')
205
+ const tip = extractAttr(attrs, 'data-tip') || extractAttr(attrs, 'title')
206
+ const label = inner.replace(/<[^>]+>/g, '').trim()
207
+ if (citationId) return citationHtml(citationId, tip)
208
+ if (tip && isCitationLabel(label)) return citationHtml(nextId(label), tip)
209
+ return m
210
+ })
211
+
212
+ out = out.replace(/<sup\b([^>]*)>([\s\S]*?)<\/sup>/gi, (m, attrs: string, inner: string) => {
213
+ const tip = extractAttr(attrs, 'title') || extractAttr(attrs, 'data-tip')
214
+ const label = inner.replace(/<[^>]+>/g, '').trim()
215
+ if (!tip || !isCitationLabel(label)) return m
216
+ return citationHtml(nextId(label), tip)
217
+ })
218
+
219
+ return out
220
+ }
221
+
222
+ /** Element Plus 层:el-tooltip / el-popover → 原 tip;el-link → +link */
223
+ function applyElementPlusTipsAndLinks(html: string) {
224
+ let out = html.replace(
225
+ /<el-tooltip\b([^>]*)>([\s\S]*?)<\/el-tooltip>/gi,
226
+ (_m, attrs: string, inner: string) => {
227
+ const tip = extractAttr(attrs, 'content') || extractAttr(attrs, 'title')
228
+ const label = inner.replace(/<[^>]+>/g, '').trim()
229
+ if (!tip) return inner
230
+ return citationHtml(nextId(label || '1'), tip)
231
+ }
232
+ )
233
+ out = out.replace(
234
+ /<el-popover\b([^>]*)>([\s\S]*?)<\/el-popover>/gi,
235
+ (_m, attrs: string, inner: string) => {
236
+ const slotTip =
237
+ inner
238
+ .match(/<template[^>]*(?:#|v-slot:|slot=)[^>]*(?:content|default)[^>]*>([\s\S]*?)<\/template>/i)?.[1]
239
+ ?.replace(/<[^>]+>/g, ' ')
240
+ .replace(/\s+/g, ' ')
241
+ .trim() || ''
242
+ const tip = extractAttr(attrs, 'content') || extractAttr(attrs, 'title') || slotTip
243
+ const label = inner.replace(/<template[\s\S]*?<\/template>/gi, '').replace(/<[^>]+>/g, '').trim()
244
+ if (!tip) return inner.replace(/<template[\s\S]*?<\/template>/gi, '')
245
+ return citationHtml(nextId(label || '1'), tip)
246
+ }
247
+ )
248
+ out = out.replace(/<el-link\b([^>]*)>([\s\S]*?)<\/el-link>/gi, (_m, attrs: string, inner: string) => {
249
+ const href = extractAttr(attrs, 'href')
250
+ const title = extractAttr(attrs, 'title') || extractAttr(attrs, 'content')
251
+ const label = inner.replace(/<[^>]+>/g, '').trim()
252
+ if (!isRealHref(href) && title) {
253
+ return citationHtml(nextId(label || '1'), title)
254
+ }
255
+ return linkHtml(href || '#', inner, title)
256
+ })
257
+ return out
258
+ }
259
+
260
+ function applyFootnoteTips(html: string, footnotes: Map<string, string>) {
261
+ if (!footnotes.size) return html
262
+ return html.replace(
263
+ /<span class="report-tiptap-citation" data-citation="(\d+)"([^>]*)>([\s\S]*?)<\/span>/gi,
264
+ (m, id: string, rest: string, inner: string) => {
265
+ const raw = footnotes.get(id)
266
+ if (!raw) return m
267
+ const { text, href, linkLabel } = splitTipLink(raw)
268
+ if (/data-href=/.test(rest) && /data-tip=/.test(rest)) return m
269
+ const cleaned = String(rest).replace(/\sdata-(?:tip|href|link-label)="[^"]*"/gi, '')
270
+ const tipAttr = text ? ` data-tip="${escapeAttr(text)}"` : ''
271
+ const hrefAttr = href ? ` data-href="${escapeAttr(href)}"` : ''
272
+ const labelAttr = linkLabel ? ` data-link-label="${escapeAttr(linkLabel)}"` : ''
273
+ return `<span class="report-tiptap-citation" data-citation="${id}"${tipAttr}${hrefAttr}${labelAttr}${cleaned}>${inner}</span>`
274
+ }
275
+ )
276
+ }
277
+
278
+ const UNCLOSED_BLOCK_RE =
279
+ /<(table|thead|tbody|tr|td|th|pre|blockquote|ul|ol|li|p|h[1-6]|think|strong|b|em|i|u|s|code|mark|div|section|article|figure|figcaption|header|footer|details|summary|font|ins|del|caption|el-tooltip|el-popover|el-link|span|a)\b[^>]*>(?:(?!<\/\1>)[\s\S])*$/i
280
+
281
+ export function stripThinkBlocks(source: string) {
282
+ return source
283
+ .replace(/<think\b[^>]*>[\s\S]*?<\/think>/gi, '')
284
+ .replace(/<think\b[\s\S]*$/i, '')
285
+ }
286
+
287
+ const CJK_CHAR =
288
+ /[\u3400-\u9FFF\uF900-\uFAFF\u3000-\u303F\u3040-\u30FF\uAC00-\uD7AF]/
289
+
290
+ /** 補回可讀空格:空白規範化、中西交界(保留換行);英文分詞交由後端保證 */
291
+ export function normalizeReadableSpacing(source: string): string {
292
+ let text = String(source ?? '')
293
+ if (!text) return ''
294
+ text = text.replace(/\u00a0/g, ' ')
295
+ // 0914:空白規範化 + 中西交界(英文粘詞由後端輸出正常空格)
296
+ text = text.replace(/[^\S\n\r]+/g, ' ')
297
+ text = text.replace(
298
+ new RegExp(`(${CJK_CHAR.source})([A-Za-z0-9])`, 'g'),
299
+ '$1 $2'
300
+ )
301
+ text = text.replace(
302
+ new RegExp(`([A-Za-z0-9])(${CJK_CHAR.source})`, 'g'),
303
+ '$1 $2'
304
+ )
305
+ // 0914
306
+ return text
307
+ }
308
+
309
+ /** 是否像 Markdown(ATX 標題 / 列表 / 加粗),用於決定要不要拆 <p>/<br>/字面 \\n */
310
+ function looksLikeMarkdown(text: string) {
311
+ const probe = String(text || '')
312
+ .replace(/<(?:br)\s*\/?>/gi, '\n')
313
+ .replace(/<\/(?:p|div)\s*>/gi, '\n')
314
+ .replace(/<(?:p|div)\b[^>]*>/gi, '')
315
+ return /(?:^|\n)\s{0,3}#{1,6}\s|(?:^|\n)\s{0,3}(?:[-*+]|\d{1,9}[.)])\s|\*{3}[^*\n]+\*{3}|\*{2}[^*\n]+\*{2}/m.test(
316
+ probe
317
+ )
318
+ }
319
+
320
+ /**
321
+ * 接口正文常把 Markdown 塞进 <p>/<br> 或字面 \\n,
322
+ * marked 無法把行首 ### / * 認成標題與列表,畫面就會打出原始符號。
323
+ * 閉合 HTML 結構保留;僅在「像 Markdown」時拆開陷阱標籤。
324
+ */
325
+ function normalizeMarkdownSource(source: string) {
326
+ let text = String(source ?? '')
327
+ if (!text) return ''
328
+
329
+ const realNl = (text.match(/\r?\n/g) || []).length
330
+ const escapedNl = (text.match(/\\n/g) || []).length
331
+ if (escapedNl > 0 && escapedNl >= realNl) {
332
+ const unescaped = text.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n').replace(/\\t/g, '\t')
333
+ if (looksLikeMarkdown(unescaped)) text = unescaped
334
+ }
335
+
336
+ if (!looksLikeMarkdown(text)) {
337
+ return normalizeReadableSpacing(text)
338
+ }
339
+
340
+ if (/<br\s*\/?>/i.test(text)) {
341
+ text = text.replace(/<br\s*\/?>/gi, '\n')
342
+ }
343
+
344
+ if (/<(?:p|div)\b/i.test(text)) {
345
+ const unwrapped = text
346
+ .replace(/<\/(?:p|div)\s*>\s*<(?:p|div)\b[^>]*>/gi, '\n\n')
347
+ .replace(/<(?:p|div)\b[^>]*>/gi, '')
348
+ .replace(/<\/(?:p|div)\s*>/gi, '\n')
349
+ if (looksLikeMarkdown(unwrapped)) text = unwrapped
350
+ }
351
+
352
+ return normalizeReadableSpacing(text)
353
+ }
354
+
355
+ /**
356
+ * 在 source 上掃描,自動跳過 ```fence``` 與行內 `code`,
357
+ * 避免代碼裡的 ** / * / # 被當成未閉合 Markdown。
358
+ */
359
+ function scanMarkdownOutsideCode(
360
+ source: string,
361
+ visit: (i: number, ch: string) => number | void
362
+ ) {
363
+ let i = 0
364
+ let inFence = false
365
+ while (i < source.length) {
366
+ if (source.startsWith('```', i)) {
367
+ inFence = !inFence
368
+ i += 3
369
+ continue
370
+ }
371
+ if (inFence) {
372
+ i += 1
373
+ continue
374
+ }
375
+ if (source.charAt(i) === '`') {
376
+ let n = 0
377
+ while (source.charAt(i + n) === '`') n += 1
378
+ const open = source.slice(i, i + n)
379
+ const closeAt = source.indexOf(open, i + n)
380
+ if (closeAt < 0) {
381
+ // 半截行內 code:剩餘整段視為 code,不再掃描標記
382
+ return
383
+ }
384
+ i = closeAt + n
385
+ continue
386
+ }
387
+ const step = visit(i, source.charAt(i))
388
+ i += typeof step === 'number' && step > 0 ? step : 1
389
+ }
390
+ }
391
+
392
+ function lastUnpairedFence(source: string, fence: string) {
393
+ let odd = false
394
+ let last = -1
395
+ scanMarkdownOutsideCode(source, (i) => {
396
+ // 統計 ** 時整段跳過 ***,避免三星被拆成 ** + *
397
+ if (fence === '**' && source.startsWith('***', i)) return 3
398
+ if (fence === '__' && source.startsWith('___', i)) return 3
399
+ if (source.startsWith(fence, i)) {
400
+ odd = !odd
401
+ last = i
402
+ return fence.length
403
+ }
404
+ })
405
+ return odd ? last : -1
406
+ }
407
+
408
+ function lastUnpairedInlineTick(source: string) {
409
+ let odd = false
410
+ let last = -1
411
+ let i = 0
412
+ let inFence = false
413
+ while (i < source.length) {
414
+ if (source.startsWith('```', i)) {
415
+ inFence = !inFence
416
+ i += 3
417
+ continue
418
+ }
419
+ if (inFence) {
420
+ i += 1
421
+ continue
422
+ }
423
+ if (source.charAt(i) === '`') {
424
+ odd = !odd
425
+ last = i
426
+ }
427
+ i += 1
428
+ }
429
+ return odd ? last : -1
430
+ }
431
+
432
+ function lastUnpairedSingleStar(source: string) {
433
+ let odd = false
434
+ let last = -1
435
+ scanMarkdownOutsideCode(source, (i) => {
436
+ if (source.startsWith('***', i)) return 3
437
+ if (source.startsWith('**', i)) return 2
438
+ if (source.charAt(i) !== '*') return
439
+ const atLineStart = i === 0 || source.charAt(i - 1) === '\n'
440
+ const next = source.charAt(i + 1)
441
+ if (atLineStart && (next === ' ' || next === '\t')) return 1
442
+ odd = !odd
443
+ last = i
444
+ })
445
+ return odd ? last : -1
446
+ }
447
+
448
+ function lastUnpairedSingleUnderscore(source: string) {
449
+ let odd = false
450
+ let last = -1
451
+ scanMarkdownOutsideCode(source, (i) => {
452
+ if (source.startsWith('__', i)) return 2
453
+ if (source.charAt(i) !== '_') return
454
+ const prev = i === 0 ? ' ' : source.charAt(i - 1)
455
+ const next = source.charAt(i + 1)
456
+ if (/[A-Za-z0-9]/.test(prev) && /[A-Za-z0-9]/.test(next)) return 1
457
+ odd = !odd
458
+ last = i
459
+ })
460
+ return odd ? last : -1
461
+ }
462
+
463
+ /** 完整主題分隔線(HR),不應當半截標記 */
464
+ function isCompleteThematicBreak(text: string) {
465
+ return /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(text)
466
+ }
467
+
468
+ /** 打字机:切开已闭合前缀 vs 半截标记;半截内文继续打出,避免整段闪没 */
469
+ function splitStreamStablePrefix(source: string) {
470
+ const cuts: number[] = []
471
+ const lastLt = source.lastIndexOf('<')
472
+ const lastGt = source.lastIndexOf('>')
473
+ if (lastLt > lastGt && /[a-zA-Z/!]/.test(source.charAt(lastLt + 1) || '')) {
474
+ cuts.push(lastLt)
475
+ }
476
+ const block = source.match(UNCLOSED_BLOCK_RE)
477
+ if (block && block.index != null) cuts.push(block.index)
478
+ const linkOpen = source.search(/\[[^\]]*$|\[[^\]]*\]\([^)]*$/)
479
+ if (linkOpen >= 0) cuts.push(linkOpen)
480
+ const plusOpen = source.search(/\[\+(?:\d+)?$|\[\^\d*$/)
481
+ if (plusOpen >= 0) cuts.push(plusOpen)
482
+ for (const fence of ['```', '***', '**', '__', '~~'] as const) {
483
+ const at = lastUnpairedFence(source, fence)
484
+ if (at >= 0) cuts.push(at)
485
+ }
486
+ const tick = lastUnpairedInlineTick(source)
487
+ if (tick >= 0) cuts.push(tick)
488
+ const star = lastUnpairedSingleStar(source)
489
+ if (star >= 0) cuts.push(star)
490
+ const under = lastUnpairedSingleUnderscore(source)
491
+ if (under >= 0) cuts.push(under)
492
+ const mdBlock = lastIncompleteMarkdownCut(source)
493
+ if (mdBlock >= 0) cuts.push(mdBlock)
494
+ if (!cuts.length) return { stable: source, rest: '' }
495
+ const at = Math.min(...cuts)
496
+ const stable = source.slice(0, at)
497
+ const rest = source.slice(at)
498
+ // 誤切:rest 本身已是完整 HR,應併入 stable 交給 marked
499
+ if (rest && isCompleteThematicBreak(rest.trim())) {
500
+ return { stable: source, rest: '' }
501
+ }
502
+ return { stable, rest }
503
+ }
504
+
505
+ /** 半截标题 / 列表 / 引用 / 表格 / setext 先不交给 marked,避免结构来回跳 */
506
+ function lastIncompleteMarkdownCut(source: string) {
507
+ const cuts: number[] = []
508
+ const pushMarker = (re: RegExp) => {
509
+ const m = source.match(re)
510
+ if (!m || m.index == null) return
511
+ cuts.push(m[0].startsWith('\n') ? m.index + 1 : m.index)
512
+ }
513
+ // 僅標題符號、尚無正文
514
+ pushMarker(/(?:^|\n) {0,3}#{1,6}$/)
515
+ // ### 後只有空格、標題字還在打
516
+ pushMarker(/(?:^|\n) {0,3}#{1,6}[ \t]+$/)
517
+ pushMarker(/(?:^|\n) {0,3}(?:[-*+]|\d{1,9}[.)])$/)
518
+ pushMarker(/(?:^|\n) {0,3}>$/)
519
+ // 僅 1~2 個 -/_(等第 3 個才成 HR);完整 --- 不切
520
+ pushMarker(/(?:^|\n) {0,3}(?:-{1,2}|_{1,2})$/)
521
+ // setext 下劃線未完成(1~2);≥3 交給 marked 解析為標題/HR
522
+ const setext = source.match(/\n[ \t]*([-=])\1{0,1}$/)
523
+ if (setext && setext.index != null) cuts.push(setext.index + 1)
524
+ const table = incompleteTableCut(source)
525
+ if (table >= 0) cuts.push(table)
526
+ return cuts.length ? Math.min(...cuts) : -1
527
+ }
528
+
529
+ function incompleteTableCut(source: string) {
530
+ const lines = source.split('\n')
531
+ const lastLine = lines[lines.length - 1]
532
+ if (!lines.length || lastLine == null || !/^\s*\|/.test(lastLine)) return -1
533
+ let i = lines.length - 1
534
+ while (i > 0 && /^\s*\|/.test(lines[i - 1] ?? '')) i -= 1
535
+ const block = lines.slice(i)
536
+ const hasSep = block.some((line) => /^\s*\|?\s*:?-{2,}/.test(line))
537
+ const last = block[block.length - 1] || ''
538
+ const lastComplete = /\|.+\|/.test(last.trim())
539
+ if (hasSep && lastComplete && block.length >= 3) return -1
540
+ return i === 0 ? 0 : lines.slice(0, i).join('\n').length + 1
541
+ }
542
+
543
+ function htmlInnerPlain(rest: string) {
544
+ const gt = rest.indexOf('>')
545
+ if (gt < 0) return ''
546
+ let inner = rest.slice(gt + 1)
547
+ inner = inner.replace(/<\/[a-zA-Z][^>]*>/g, '').replace(/<[a-zA-Z][^>]*\/?>/g, '')
548
+ const lastLt = inner.lastIndexOf('<')
549
+ const lastGt = inner.lastIndexOf('>')
550
+ if (lastLt > lastGt) inner = inner.slice(0, lastLt)
551
+ return inner
552
+ }
553
+
554
+ /**
555
+ * 半截标记不把内文藏掉:`**xxx` / `<strong>xxx` 继续打字,只不画出 ** / 标签本身。
556
+ * 闭合后走正式解析变成粗体,与打字机进度同步、避免整段闪没。
557
+ */
558
+ function visiblePlainFromIncomplete(rest: string) {
559
+ if (!rest) return ''
560
+ const leadWs = rest.match(/^[ \t]*/)?.[0] ?? ''
561
+ const t = rest.slice(leadWs.length)
562
+ if (!t) return ''
563
+ if (isCompleteThematicBreak(t)) return ''
564
+ if (t.startsWith('```')) {
565
+ const nl = t.indexOf('\n')
566
+ return nl < 0 ? '' : leadWs + t.slice(nl + 1)
567
+ }
568
+ if (t.startsWith('***')) return leadWs + t.slice(3)
569
+ if (t.startsWith('**')) return leadWs + t.slice(2)
570
+ if (t.startsWith('__')) return leadWs + t.slice(2)
571
+ if (t.startsWith('~~')) return leadWs + t.slice(2)
572
+ if (/^#{1,6}$/.test(t)) return ''
573
+ if (/^#{1,6}[ \t]+$/.test(t)) return ''
574
+ if (/^#{1,6}[ \t]+/.test(t)) return leadWs + t.replace(/^#{1,6}[ \t]+/, '')
575
+ if (/^([-*+]|\d{1,9}[.)])$/.test(t)) return ''
576
+ if (/^([-*+]|\d{1,9}[.)]) /.test(t)) return leadWs + t.replace(/^([-*+]|\d{1,9}[.)]) /, '')
577
+ if (t === '>') return ''
578
+ if (/^\s*\|/.test(t)) return leadWs + t.replace(/^\s*\|/, '').replace(/\|/g, ' ')
579
+ if (t.startsWith('`')) return leadWs + t.slice(1).replace(/`/g, '')
580
+ if (t.startsWith('[') || t.startsWith('![')) {
581
+ const inner = t.replace(/^!?\[/, '')
582
+ const close = inner.indexOf(']')
583
+ return leadWs + (close < 0 ? inner : inner.slice(0, close))
584
+ }
585
+ if (t.startsWith('<')) return leadWs + htmlInnerPlain(t)
586
+ if (t.startsWith('*')) return leadWs + t.slice(1)
587
+ if (t.startsWith('_')) return leadWs + t.slice(1)
588
+ return leadWs + t
589
+ }
590
+
591
+ function appendPlainTail(html: string, rest: string) {
592
+ if (!rest) return html
593
+ const escaped = escapeHtml(rest).replace(/\n/g, '<br>')
594
+ if (!html) return `<p>${escaped}</p>`
595
+ // 表格 / 标题半截单独成段,避免塞进上一块后再整体跳结构
596
+ if (/^\s*\|/.test(rest.trimStart()) || /^\s*#{1,6}(?:\s|$)/.test(rest.trimStart())) {
597
+ return `${html}<p>${escaped}</p>`
598
+ }
599
+ const closeRe = /<\/(?:p|li|h[1-6]|td|th)\b[^>]*>/gi
600
+ let last = -1
601
+ let m: RegExpExecArray | null
602
+ while ((m = closeRe.exec(html))) last = m.index
603
+ if (last >= 0) return html.slice(0, last) + escaped + html.slice(last)
604
+ return `${html}<p>${escaped}</p>`
605
+ }
606
+
607
+ /** 将 Markdown / HTML / Element Plus 解析为 TipTap 可 setContent 的片段 */
608
+ export function parseMarkdownToHtml(source: string): string {
609
+ const text = normalizeMarkdownSource(String(source ?? ''))
610
+ if (!text.trim()) return ''
611
+ citationSeq = 0
612
+ try {
613
+ const withoutThink = stripThinkBlocks(text)
614
+ if (!withoutThink.trim()) return ''
615
+ const mdTips = applyMarkdownTips(withoutThink)
616
+ const protectedSrc = protectBlocks(mdTips.text)
617
+ const parsed = markedParser.parse(protectedSrc.text, { async: false })
618
+ let html = typeof parsed === 'string' ? parsed.trim() : ''
619
+ html = restoreBlocks(html, protectedSrc.slots)
620
+ html = applyHtmlTipsAndLinks(html)
621
+ html = applyElementPlusTipsAndLinks(html)
622
+ html = applyFootnoteTips(html, mdTips.footnotes)
623
+ return html
624
+ } catch {
625
+ return `<p>${escapeHtml(stripThinkBlocks(text))}</p>`
626
+ }
627
+ }
628
+
629
+ let streamStableCacheKey = ''
630
+ let streamStableCacheHtml = ''
631
+
632
+ /** 打字机逐帧:完整语法走解析;半截 ** / 标签不画,内文继续打出,打完再灌全文 */
633
+ export function parseMarkdownToHtmlStream(source: string): string {
634
+ const text = stripThinkBlocks(normalizeMarkdownSource(String(source ?? '')))
635
+ if (!text) return ''
636
+ const { stable, rest } = splitStreamStablePrefix(text)
637
+ if (!rest) {
638
+ const html = parseMarkdownToHtml(text)
639
+ streamStableCacheKey = text
640
+ streamStableCacheHtml = html
641
+ return html
642
+ }
643
+ let html = ''
644
+ if (stable) {
645
+ if (stable === streamStableCacheKey) html = streamStableCacheHtml
646
+ else {
647
+ html = parseMarkdownToHtml(stable)
648
+ streamStableCacheKey = stable
649
+ streamStableCacheHtml = html
650
+ }
651
+ }
652
+ return appendPlainTail(html, visiblePlainFromIncomplete(rest))
653
+ }