agent-stream-ui 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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +220 -2
  3. package/dist/adapters/openai.d.ts +42 -0
  4. package/dist/adapters/openai.d.ts.map +1 -0
  5. package/dist/agent-stream-ui.css +2 -0
  6. package/dist/agent-stream-ui.js +1418 -0
  7. package/dist/agent-stream-ui.js.map +1 -0
  8. package/dist/core/reducer.d.ts +33 -0
  9. package/dist/core/reducer.d.ts.map +1 -0
  10. package/dist/core/scheduler.d.ts +15 -0
  11. package/dist/core/scheduler.d.ts.map +1 -0
  12. package/dist/core/store.d.ts +29 -0
  13. package/dist/core/store.d.ts.map +1 -0
  14. package/dist/core/transport.d.ts +57 -0
  15. package/dist/core/transport.d.ts.map +1 -0
  16. package/dist/index.d.ts +38 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/markdown/blocks.d.ts +31 -0
  19. package/dist/markdown/blocks.d.ts.map +1 -0
  20. package/dist/markdown/inline.d.ts +13 -0
  21. package/dist/markdown/inline.d.ts.map +1 -0
  22. package/dist/markdown/render.d.ts +18 -0
  23. package/dist/markdown/render.d.ts.map +1 -0
  24. package/dist/react/agent-chat.d.ts +14 -0
  25. package/dist/react/agent-chat.d.ts.map +1 -0
  26. package/dist/react/composer.d.ts +11 -0
  27. package/dist/react/composer.d.ts.map +1 -0
  28. package/dist/react/icons.d.ts +12 -0
  29. package/dist/react/icons.d.ts.map +1 -0
  30. package/dist/react/markdown-stream.d.ts +14 -0
  31. package/dist/react/markdown-stream.d.ts.map +1 -0
  32. package/dist/react/message-body.d.ts +14 -0
  33. package/dist/react/message-body.d.ts.map +1 -0
  34. package/dist/react/message-list.d.ts +8 -0
  35. package/dist/react/message-list.d.ts.map +1 -0
  36. package/dist/react/tool-call-card.d.ts +13 -0
  37. package/dist/react/tool-call-card.d.ts.map +1 -0
  38. package/dist/react/use-agent-stream.d.ts +11 -0
  39. package/dist/react/use-agent-stream.d.ts.map +1 -0
  40. package/dist/react/use-stick-to-bottom.d.ts +14 -0
  41. package/dist/react/use-stick-to-bottom.d.ts.map +1 -0
  42. package/dist/sse/client.d.ts +60 -0
  43. package/dist/sse/client.d.ts.map +1 -0
  44. package/dist/sse/frame.d.ts +42 -0
  45. package/dist/sse/frame.d.ts.map +1 -0
  46. package/dist/types.d.ts +119 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/docs/design-notes.md +145 -0
  49. package/package.json +84 -4
  50. package/src/lib/adapters/openai.ts +112 -0
  51. package/src/lib/core/reducer.ts +417 -0
  52. package/src/lib/core/scheduler.ts +40 -0
  53. package/src/lib/core/store.ts +214 -0
  54. package/src/lib/core/transport.ts +197 -0
  55. package/src/lib/index.ts +102 -0
  56. package/src/lib/markdown/blocks.ts +201 -0
  57. package/src/lib/markdown/inline.tsx +87 -0
  58. package/src/lib/markdown/render.tsx +149 -0
  59. package/src/lib/react/agent-chat.tsx +121 -0
  60. package/src/lib/react/composer.tsx +105 -0
  61. package/src/lib/react/icons.tsx +83 -0
  62. package/src/lib/react/markdown-stream.tsx +37 -0
  63. package/src/lib/react/message-body.tsx +66 -0
  64. package/src/lib/react/message-list.tsx +109 -0
  65. package/src/lib/react/tool-call-card.tsx +117 -0
  66. package/src/lib/react/use-agent-stream.ts +14 -0
  67. package/src/lib/react/use-stick-to-bottom.ts +60 -0
  68. package/src/lib/sse/client.ts +263 -0
  69. package/src/lib/sse/frame.ts +116 -0
  70. package/src/lib/styles.css +790 -0
  71. package/src/lib/types.ts +130 -0
@@ -0,0 +1,214 @@
1
+ /**
2
+ * 会话 store:把 transport 的事件折叠成快照,并做「一帧一次」的通知。
3
+ *
4
+ * 为什么不用 `useState` 直接接事件:流式场景下一步事件就是一次 setState,
5
+ * 一秒钟几十次,React 会把时间全花在重复渲染上。这里的做法是
6
+ * **状态立刻更新、通知按帧合并**——getSnapshot 永远返回最新状态,
7
+ * 订阅者每帧最多被叫醒一次。
8
+ */
9
+
10
+ import type {
11
+ AgentEvent,
12
+ ConversationSnapshot,
13
+ Message,
14
+ SseStatus,
15
+ SseStatusInfo,
16
+ } from '../types'
17
+ import type { SseFrame } from '../sse/frame'
18
+ import type { Transport } from './transport'
19
+ import type { FlushScheduler } from './scheduler'
20
+ import { defaultScheduler } from './scheduler'
21
+ import {
22
+ appendUserMessage,
23
+ applySseStatus,
24
+ decodeAgentEvent,
25
+ initialLiveTurn,
26
+ initialSnapshot,
27
+ reduceAgentEvent,
28
+ settleOrphanLiveTurn,
29
+ stopLiveTurn,
30
+ } from './reducer'
31
+
32
+ export interface AgentStreamOptions {
33
+ transport: Transport
34
+ scheduler?: FlushScheduler
35
+ now?: () => number
36
+ /** 调试钩子:每个被识别的事件(含 ping)都会回调一次。 */
37
+ onEvent?: (event: AgentEvent, frame: SseFrame) => void
38
+ }
39
+
40
+ export interface AgentStreamStore {
41
+ readonly subscribe: (listener: () => void) => () => void
42
+ readonly getSnapshot: () => ConversationSnapshot
43
+ readonly send: (text: string) => void
44
+ readonly stop: () => void
45
+ readonly retry: () => void
46
+ readonly reset: () => void
47
+ }
48
+
49
+ export function createAgentStream(options: AgentStreamOptions): AgentStreamStore {
50
+ const { transport, now = Date.now, onEvent } = options
51
+ const scheduler = options.scheduler ?? defaultScheduler()
52
+
53
+ let snapshot = initialSnapshot()
54
+ let controller: AbortController | null = null
55
+ let pending: unknown = null
56
+ let scheduled = false
57
+ const listeners = new Set<() => void>()
58
+
59
+ const notify = () => {
60
+ scheduled = false
61
+ pending = null
62
+ for (const listener of [...listeners]) listener()
63
+ }
64
+
65
+ /** 合并一帧内的多次状态变更;scheduler 保证 notify 每帧最多一次。 */
66
+ const scheduleFlush = () => {
67
+ if (scheduled) return
68
+ scheduled = true
69
+ pending = scheduler.schedule(notify)
70
+ }
71
+
72
+ const cancelFlush = () => {
73
+ if (!scheduled) return
74
+ scheduler.cancel(pending)
75
+ scheduled = false
76
+ pending = null
77
+ }
78
+
79
+ const closeTransport = () => {
80
+ controller?.abort()
81
+ controller = null
82
+ }
83
+
84
+ const handleStatus = (status: SseStatus, info?: SseStatusInfo) => {
85
+ // 已经收尾的回合不要再被 "stopped" 覆盖(那是我们自己 abort 引发的)
86
+ if (status === 'stopped' && snapshot.live === null) return
87
+
88
+ snapshot = applySseStatus(snapshot, status, info)
89
+
90
+ // 服务端把流关了但没发 turn.end(或重连耗尽):不能让它永远转圈
91
+ if (
92
+ (status === 'closed' || status === 'error') &&
93
+ snapshot.live &&
94
+ snapshot.live.status === 'running'
95
+ ) {
96
+ snapshot = settleOrphanLiveTurn(snapshot, now())
97
+ }
98
+
99
+ scheduleFlush()
100
+ }
101
+
102
+ const handleFrame = (frame: SseFrame) => {
103
+ const event = decodeAgentEvent(frame.event, frame.data)
104
+ if (!event) return
105
+
106
+ onEvent?.(event, frame)
107
+ snapshot = reduceAgentEvent(snapshot, event, now())
108
+ scheduleFlush()
109
+
110
+ if (event.type === 'turn.end') {
111
+ snapshot = { ...snapshot, status: 'closed' }
112
+ scheduleFlush()
113
+ // 回合已结束,主动关流,避免服务端保持长连接
114
+ closeTransport()
115
+ }
116
+ }
117
+
118
+ const openTransport = (text: string, history: readonly Message[]) => {
119
+ closeTransport()
120
+ const next = new AbortController()
121
+ controller = next
122
+
123
+ transport.open({
124
+ text,
125
+ history,
126
+ signal: next.signal,
127
+ onFrame: handleFrame,
128
+ onStatus: handleStatus,
129
+ })
130
+ }
131
+
132
+ const store: AgentStreamStore = {
133
+ subscribe(listener) {
134
+ listeners.add(listener)
135
+ return () => {
136
+ listeners.delete(listener)
137
+ }
138
+ },
139
+
140
+ getSnapshot() {
141
+ return snapshot
142
+ },
143
+
144
+ send(text) {
145
+ const live = snapshot.live
146
+ if (live && live.status === 'running') return
147
+
148
+ const trimmed = text.trim()
149
+ if (trimmed === '') return
150
+
151
+ const at = now()
152
+ const history = snapshot.messages
153
+
154
+ snapshot = appendUserMessage({ ...snapshot, live: null }, trimmed, at)
155
+ snapshot = {
156
+ ...snapshot,
157
+ live: initialLiveTurn(at),
158
+ status: 'connecting',
159
+ reconnect: null,
160
+ }
161
+ scheduleFlush()
162
+
163
+ openTransport(trimmed, history)
164
+ },
165
+
166
+ stop() {
167
+ if (snapshot.live) {
168
+ snapshot = stopLiveTurn(snapshot, now())
169
+ scheduleFlush()
170
+ }
171
+ closeTransport()
172
+ },
173
+
174
+ retry() {
175
+ const failed = snapshot.live
176
+ const canRetry =
177
+ (failed && failed.status === 'error') ||
178
+ snapshot.status === 'error' ||
179
+ snapshot.messages.at(-1)?.status === 'error'
180
+ if (!canRetry) return
181
+
182
+ const lastUser = [...snapshot.messages].reverse().find((item) => item.role === 'user')
183
+ if (!lastUser) return
184
+
185
+ const text = lastUser.parts
186
+ .filter((part): part is { kind: 'text'; text: string } => part.kind === 'text')
187
+ .map((part) => part.text)
188
+ .join('\n')
189
+
190
+ const index = snapshot.messages.lastIndexOf(lastUser)
191
+ const history = snapshot.messages.slice(0, index)
192
+
193
+ const at = now()
194
+ snapshot = {
195
+ ...snapshot,
196
+ live: initialLiveTurn(at),
197
+ status: 'connecting',
198
+ reconnect: null,
199
+ }
200
+ scheduleFlush()
201
+
202
+ openTransport(text, history)
203
+ },
204
+
205
+ reset() {
206
+ closeTransport()
207
+ cancelFlush()
208
+ snapshot = initialSnapshot()
209
+ scheduleFlush()
210
+ },
211
+ }
212
+
213
+ return store
214
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * 传输层抽象。
3
+ *
4
+ * 上层只认 `Transport`,不认 fetch。好处有三个:
5
+ * 1. demo 可以在没有后端时用脚本回放,事件仍然走真实的分帧/折叠路径;
6
+ * 2. 测试可以注入确定性的"服务端",不用起 HTTP;
7
+ * 3. 真要换成 WebSocket / gRPC / 本地 IPC,只加一个实现,不动 reducer 和组件。
8
+ */
9
+
10
+ import type { Message, SseStatus, SseStatusInfo } from '../types'
11
+ import type { SseFrame } from '../sse/frame'
12
+ import { createSseClient } from '../sse/client'
13
+ import { parseSseChunk } from '../sse/frame'
14
+
15
+ export interface TransportOpenContext {
16
+ /** 本轮用户输入。 */
17
+ text: string
18
+ /** 本轮之前的会话历史(不含本轮输入)。 */
19
+ history: readonly Message[]
20
+ signal: AbortSignal
21
+ onFrame: (frame: SseFrame) => void
22
+ onStatus: (status: SseStatus, info?: SseStatusInfo) => void
23
+ }
24
+
25
+ export interface Transport {
26
+ open(context: TransportOpenContext): void
27
+ }
28
+
29
+ export interface HttpTransportOptions {
30
+ url: string
31
+ headers?: Record<string, string>
32
+ /** 自定义请求体,默认 `{ text, history }`。 */
33
+ buildBody?: (context: Pick<TransportOpenContext, 'text' | 'history'>) => unknown
34
+ fetch?: typeof fetch
35
+ /** 空闲多久没帧就判定连接已死并重连;0 = 关闭(默认)。 */
36
+ idleTimeoutMs?: number
37
+ /** 连续失败上限,默认 8。 */
38
+ maxAttempts?: number
39
+ /** 首次重连退避,默认 500ms(测试里会调小)。 */
40
+ backoffBaseMs?: number
41
+ }
42
+
43
+ /** 把消息压成给服务端的纯文本历史,避免把 UI 状态(工具卡)回传。 */
44
+ export function toWireHistory(history: readonly Message[]) {
45
+ return history.map((message) => ({
46
+ role: message.role,
47
+ text: message.parts
48
+ .filter((part): part is { kind: 'text'; text: string } => part.kind === 'text')
49
+ .map((part) => part.text)
50
+ .join('\n'),
51
+ }))
52
+ }
53
+
54
+ function randomId(): string {
55
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
56
+ return crypto.randomUUID()
57
+ }
58
+ return `t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
59
+ }
60
+
61
+ export function createHttpTransport(options: HttpTransportOptions): Transport {
62
+ const {
63
+ url,
64
+ headers,
65
+ fetch: fetchImpl,
66
+ buildBody,
67
+ idleTimeoutMs,
68
+ maxAttempts,
69
+ backoffBaseMs,
70
+ } = options
71
+
72
+ return {
73
+ open(context) {
74
+ // 同一个 clientTurnId 会随 SseClient 的重连一起重发,
75
+ // 服务端据此把请求认成"同一轮"并从游标处续传。
76
+ const clientTurnId = randomId()
77
+ const payload = (buildBody ?? defaultBuildBody)({
78
+ text: context.text,
79
+ history: context.history,
80
+ })
81
+
82
+ const body =
83
+ payload !== null && typeof payload === 'object' && !Array.isArray(payload)
84
+ ? { clientTurnId, ...(payload as Record<string, unknown>) }
85
+ : payload
86
+
87
+ const client = createSseClient({
88
+ url,
89
+ method: 'POST',
90
+ headers,
91
+ body,
92
+ fetch: fetchImpl,
93
+ ...(idleTimeoutMs === undefined ? {} : { idleTimeoutMs }),
94
+ ...(maxAttempts === undefined ? {} : { maxAttempts }),
95
+ ...(backoffBaseMs === undefined ? {} : { backoffBaseMs }),
96
+ onEvent: context.onFrame,
97
+ onStatus: context.onStatus,
98
+ })
99
+
100
+ context.signal.addEventListener('abort', () => client.close(), { once: true })
101
+ },
102
+ }
103
+ }
104
+
105
+ function defaultBuildBody({
106
+ text,
107
+ history,
108
+ }: Pick<TransportOpenContext, 'text' | 'history'>) {
109
+ return { text, history: toWireHistory(history) }
110
+ }
111
+
112
+ /* ------------------------------------------------------------------ *
113
+ * 脚本化传输:没有后端也能演示(GitHub Pages 上也能跑)
114
+ * ------------------------------------------------------------------ */
115
+
116
+ export interface ScriptedChunk {
117
+ /** 相对上一块的延迟(毫秒)。 */
118
+ delayMs: number
119
+ /** 原始 SSE 文本,必须是完整帧(以空行结尾)。 */
120
+ chunk: string
121
+ }
122
+
123
+ export interface ScriptedTransportOptions {
124
+ /**
125
+ * 在第 N 块之后模拟一次断流:先报 reconnecting,等待一段时间再继续。
126
+ * 用来演示"断点续传"——注意这里仍然是同一条事件流,顺序不变。
127
+ */
128
+ dropAfterChunk?: number
129
+ reconnectDelayMs?: number
130
+ }
131
+
132
+ export function createScriptedTransport(
133
+ script: readonly ScriptedChunk[],
134
+ options: ScriptedTransportOptions = {},
135
+ ): Transport {
136
+ const { dropAfterChunk = -1, reconnectDelayMs = 1200 } = options
137
+
138
+ return {
139
+ open({ signal, onFrame, onStatus }) {
140
+ let index = 0
141
+ let dropped = false
142
+
143
+ const schedule = (fn: () => void, delay: number) => {
144
+ if (signal.aborted) return
145
+ timers.push(setTimeout(fn, delay))
146
+ }
147
+ const timers: ReturnType<typeof setTimeout>[] = []
148
+
149
+ const cleanup = () => {
150
+ for (const timer of timers) clearTimeout(timer)
151
+ timers.length = 0
152
+ }
153
+ signal.addEventListener('abort', cleanup, { once: true })
154
+
155
+ const push = (chunk: string) => {
156
+ const { frames } = parseSseChunk(chunk)
157
+ for (const frame of frames) onFrame(frame)
158
+ }
159
+
160
+ const tick = () => {
161
+ if (signal.aborted) return
162
+ const step = script[index]
163
+
164
+ if (!step) {
165
+ onStatus('closed', { attempt: 0, delayMs: 0, reason: 'script-finished' })
166
+ cleanup()
167
+ return
168
+ }
169
+
170
+ index += 1
171
+
172
+ if (!dropped && dropAfterChunk >= 0 && index - 1 === dropAfterChunk) {
173
+ dropped = true
174
+ onStatus('reconnecting', {
175
+ attempt: 1,
176
+ delayMs: reconnectDelayMs,
177
+ reason: 'simulated-disconnect',
178
+ })
179
+ schedule(() => {
180
+ onStatus('open', { attempt: 1, delayMs: 0 })
181
+ tick()
182
+ }, reconnectDelayMs)
183
+ return
184
+ }
185
+
186
+ push(step.chunk)
187
+ schedule(tick, step.delayMs)
188
+ }
189
+
190
+ onStatus('connecting', { attempt: 0, delayMs: 0 })
191
+ schedule(() => {
192
+ onStatus('open', { attempt: 0, delayMs: 0 })
193
+ tick()
194
+ }, 120)
195
+ },
196
+ }
197
+ }
@@ -0,0 +1,102 @@
1
+ import './styles.css'
2
+
3
+ /**
4
+ * 库入口。组件和纯逻辑都在这里导出——纯函数部分可以单独在服务端/Node 里测。
5
+ */
6
+
7
+ // 类型
8
+ export type {
9
+ AgentError,
10
+ AgentEvent,
11
+ AgentEventPayloads,
12
+ AgentEventType,
13
+ ConversationSnapshot,
14
+ ErrorStage,
15
+ LiveTurn,
16
+ Message,
17
+ MessagePart,
18
+ SseStatus,
19
+ SseStatusInfo,
20
+ ToolCallState,
21
+ ToolStatus,
22
+ TurnStatus,
23
+ } from './types'
24
+ export { AGENT_EVENT_TYPES } from './types'
25
+
26
+ // SSE
27
+ export { formatSseFrame, isNewerEventId, parseSseChunk, parseSseFrame } from './sse/frame'
28
+ export type { SseFrame } from './sse/frame'
29
+ export {
30
+ computeBackoff,
31
+ createSseClient,
32
+ DEFAULT_BACKOFF_BASE_MS,
33
+ DEFAULT_BACKOFF_FACTOR,
34
+ DEFAULT_BACKOFF_MAX_MS,
35
+ shouldRetryStatus,
36
+ } from './sse/client'
37
+ export type {
38
+ RetryContext,
39
+ SseClient,
40
+ SseClientOptions,
41
+ } from './sse/client'
42
+
43
+ // 核心
44
+ export {
45
+ appendUserMessage,
46
+ applySseStatus,
47
+ decodeAgentEvent,
48
+ initialLiveTurn,
49
+ initialSnapshot,
50
+ isAgentEventType,
51
+ reduceAgentEvent,
52
+ repairPartialJson,
53
+ settleOrphanLiveTurn,
54
+ stopLiveTurn,
55
+ } from './core/reducer'
56
+ export { createAgentStream } from './core/store'
57
+ export type { AgentStreamOptions, AgentStreamStore } from './core/store'
58
+ export {
59
+ createHttpTransport,
60
+ createScriptedTransport,
61
+ toWireHistory,
62
+ } from './core/transport'
63
+ export type {
64
+ HttpTransportOptions,
65
+ ScriptedChunk,
66
+ ScriptedTransportOptions,
67
+ Transport,
68
+ TransportOpenContext,
69
+ } from './core/transport'
70
+ export { defaultScheduler, immediateScheduler, rafScheduler } from './core/scheduler'
71
+ export type { FlushScheduler } from './core/scheduler'
72
+
73
+ // 适配器
74
+ export { createOpenAIStreamTranslator } from './adapters/openai'
75
+ export type {
76
+ OpenAIStreamChunk,
77
+ OpenAIStreamTranslator,
78
+ OpenAIToolCallDelta,
79
+ OpenAIToolCallRef,
80
+ } from './adapters/openai'
81
+
82
+ // Markdown
83
+ export { listItemText, splitBlocks } from './markdown/blocks'
84
+ export type { BlockKind, MdBlock } from './markdown/blocks'
85
+ export { isSafeHref, parseInline, parseInlineLines } from './markdown/inline'
86
+ export { clearBlockCache, MarkdownBlockView, renderBlock } from './markdown/render'
87
+
88
+ // React
89
+ export { AgentChat } from './react/agent-chat'
90
+ export type { AgentChatProps } from './react/agent-chat'
91
+ export { Composer } from './react/composer'
92
+ export type { ComposerProps } from './react/composer'
93
+ export { MarkdownStream } from './react/markdown-stream'
94
+ export type { MarkdownStreamProps } from './react/markdown-stream'
95
+ export { MessageBody, ErrorNote } from './react/message-body'
96
+ export type { MessageBodyProps } from './react/message-body'
97
+ export { MessageList } from './react/message-list'
98
+ export type { MessageListProps } from './react/message-list'
99
+ export { ToolCallCard } from './react/tool-call-card'
100
+ export type { ToolCallCardProps } from './react/tool-call-card'
101
+ export { useAgentStream } from './react/use-agent-stream'
102
+ export { useStickToBottom } from './react/use-stick-to-bottom'
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Markdown 分块:把流式文本切成「已经定型的块」和「还在长的尾块」。
3
+ *
4
+ * 这是流式渲染性能的关键:每来一个 token 都全量 parse 整段 markdown,
5
+ * 长回答下会明显掉帧。按块切开以后,已闭合的块可以命中缓存,只有尾块
6
+ * 需要重新解析——通常它只有一两行。
7
+ *
8
+ * 只支持对话场景够用的子集:标题、段落、围栏代码、列表、引用、分割线。
9
+ * 表格和 HTML 明确不支持(见 docs/design-notes.md)。
10
+ */
11
+
12
+ export type BlockKind = 'heading' | 'paragraph' | 'code' | 'list' | 'quote' | 'hr'
13
+
14
+ export interface MdBlock {
15
+ /** 位置 + 类型,保证流式追加时 key 稳定。 */
16
+ key: string
17
+ kind: BlockKind
18
+ text: string
19
+ /** true = 后面已经出现别的块或空行,内容不会再变,可以缓存。 */
20
+ closed: boolean
21
+ /** 标题级别 1–6。 */
22
+ level?: number
23
+ /** 代码块语言。 */
24
+ lang?: string
25
+ /** 列表是否有序。 */
26
+ ordered?: boolean
27
+ }
28
+
29
+ const HEADING = /^(#{1,6})\s+(.*)$/
30
+ const FENCE = /^(```|~~~)\s*([\w+#.-]*)\s*$/
31
+ const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/
32
+ const QUOTE = /^\s*>\s?/
33
+ const HR = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/
34
+
35
+ interface Pending {
36
+ kind: Exclude<BlockKind, 'hr'>
37
+ lines: string[]
38
+ level?: number
39
+ lang?: string
40
+ ordered?: boolean
41
+ }
42
+
43
+ function flush(blocks: MdBlock[], pending: Pending | null, closed: boolean) {
44
+ if (!pending || pending.lines.length === 0) return
45
+ const text = pending.lines.join('\n')
46
+ blocks.push({
47
+ key: `${pending.kind}-${blocks.length}`,
48
+ kind: pending.kind,
49
+ text,
50
+ closed,
51
+ ...(pending.level === undefined ? {} : { level: pending.level }),
52
+ ...(pending.lang === undefined ? {} : { lang: pending.lang }),
53
+ ...(pending.ordered === undefined ? {} : { ordered: pending.ordered }),
54
+ })
55
+ pending.lines = []
56
+ }
57
+
58
+ export function splitBlocks(text: string): MdBlock[] {
59
+ const lines = text.split('\n')
60
+ const blocks: MdBlock[] = []
61
+ let pending: Pending | null = null
62
+
63
+ let index = 0
64
+ while (index < lines.length) {
65
+ const line = lines[index] ?? ''
66
+ const fenceMatch = FENCE.exec(line.trim())
67
+
68
+ // 围栏代码:整体吞掉,内部不再做任何解析
69
+ if (fenceMatch) {
70
+ flush(blocks, pending, true)
71
+ pending = null
72
+
73
+ const marker = fenceMatch[1] ?? '```'
74
+ const lang = fenceMatch[2] ?? ''
75
+ const body: string[] = []
76
+ let closed = false
77
+ index += 1
78
+
79
+ for (; index < lines.length; index += 1) {
80
+ const inner = lines[index] ?? ''
81
+ if (inner.trim().startsWith(marker)) {
82
+ closed = true
83
+ index += 1
84
+ break
85
+ }
86
+ body.push(inner)
87
+ }
88
+
89
+ blocks.push({
90
+ key: `code-${blocks.length}`,
91
+ kind: 'code',
92
+ text: body.join('\n'),
93
+ closed,
94
+ lang,
95
+ })
96
+ continue
97
+ }
98
+
99
+ // 空行:结束当前块
100
+ if (line.trim() === '') {
101
+ flush(blocks, pending, true)
102
+ pending = null
103
+ index += 1
104
+ continue
105
+ }
106
+
107
+ const heading = HEADING.exec(line)
108
+ if (heading) {
109
+ flush(blocks, pending, true)
110
+ pending = null
111
+ blocks.push({
112
+ key: `heading-${blocks.length}`,
113
+ kind: 'heading',
114
+ text: heading[2] ?? '',
115
+ closed: true,
116
+ level: (heading[1] ?? '#').length,
117
+ })
118
+ index += 1
119
+ continue
120
+ }
121
+
122
+ if (HR.test(line)) {
123
+ flush(blocks, pending, true)
124
+ pending = null
125
+ blocks.push({
126
+ key: `hr-${blocks.length}`,
127
+ kind: 'hr',
128
+ text: '',
129
+ closed: true,
130
+ })
131
+ index += 1
132
+ continue
133
+ }
134
+
135
+ if (QUOTE.test(line)) {
136
+ if (pending && pending.kind !== 'quote') {
137
+ flush(blocks, pending, true)
138
+ pending = null
139
+ }
140
+ pending ??= { kind: 'quote', lines: [] }
141
+ pending.lines.push(line.replace(QUOTE, ''))
142
+ index += 1
143
+ continue
144
+ }
145
+
146
+ if (LIST_ITEM.test(line)) {
147
+ const ordered = /^\s*\d+[.)]\s+/.test(line)
148
+ if (pending && pending.kind !== 'list') {
149
+ flush(blocks, pending, true)
150
+ pending = null
151
+ }
152
+ if (pending && pending.ordered !== ordered) {
153
+ flush(blocks, pending, true)
154
+ pending = null
155
+ }
156
+ pending ??= { kind: 'list', lines: [], ordered }
157
+ pending.lines.push(line)
158
+ index += 1
159
+ continue
160
+ }
161
+
162
+ // 普通段落
163
+ if (pending && pending.kind !== 'paragraph') {
164
+ flush(blocks, pending, true)
165
+ pending = null
166
+ }
167
+ pending ??= { kind: 'paragraph', lines: [] }
168
+ pending.lines.push(line)
169
+ index += 1
170
+ }
171
+
172
+ // 末尾还在长的块:不闭合,交给尾块渲染(不进缓存)
173
+ flush(blocks, pending, false)
174
+
175
+ return blocks
176
+ }
177
+
178
+ /** 列表项文本:去掉 marker / 缩进。 */
179
+ export function listItemText(line: string): string {
180
+ return line.replace(LIST_ITEM, '')
181
+ }
182
+
183
+ /** 复制按钮展示用:把语言名规整成人能看的标签。 */
184
+ export function languageLabel(lang: string | undefined): string {
185
+ if (!lang) return 'text'
186
+ const map: Record<string, string> = {
187
+ ts: 'ts',
188
+ tsx: 'tsx',
189
+ typescript: 'ts',
190
+ js: 'js',
191
+ javascript: 'js',
192
+ json: 'json',
193
+ bash: 'bash',
194
+ sh: 'sh',
195
+ python: 'py',
196
+ py: 'py',
197
+ css: 'css',
198
+ html: 'html',
199
+ }
200
+ return map[lang.toLowerCase()] ?? lang
201
+ }