This repository was archived by the owner on Aug 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 488
Expand file tree
/
Copy pathMarkdownFromCody.tsx
More file actions
187 lines (171 loc) · 6.19 KB
/
Copy pathMarkdownFromCody.tsx
File metadata and controls
187 lines (171 loc) · 6.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { CodyIDE } from '@sourcegraph/cody-shared'
import type { ComponentProps, FunctionComponent } from 'react'
import { useMemo } from 'react'
import Markdown, { defaultUrlTransform } from 'react-markdown'
import type { Components, UrlTransform } from 'react-markdown/lib'
import rehypeHighlight, { type Options as RehypeHighlightOptions } from 'rehype-highlight'
import rehypeSanitize, { type Options as RehypeSanitizeOptions, defaultSchema } from 'rehype-sanitize'
import remarkGFM from 'remark-gfm'
import type { Pluggable } from 'unified/lib'
import { remarkAttachFilePathToCodeBlocks } from '../chat/extract-file-path'
import { SYNTAX_HIGHLIGHTING_LANGUAGES } from '../utils/highlight'
import { useConfig } from '../utils/useConfig'
/**
* Supported URIs to render as links in outputted markdown.
* - https?: Web
* - file: local file scheme
* - vscode: VS Code URL scheme (open in editor)
* - command:cody. VS Code command scheme for cody (run command)
* {@link CODY_PASSTHROUGH_VSCODE_OPEN_COMMAND_ID}
*/
const ALLOWED_URI_REGEXP = /^((https?|file|vscode):\/\/[^\s#$./?].\S*$|(command:_?cody.*))/i
const ALLOWED_ELEMENTS = [
'p',
'div',
'span',
'pre',
'i',
'em',
'b',
'strong',
'code',
'pre',
'kbd',
'blockquote',
'ul',
'li',
'ol',
'a',
'table',
'tr',
'th',
'td',
'thead',
'tbody',
'tfoot',
's',
'u',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'br',
'think',
]
function defaultUrlProcessor(url: string): string {
const processedURL = defaultUrlTransform(url)
if (!ALLOWED_URI_REGEXP.test(processedURL)) {
return ''
}
return processedURL
}
/**
* Transform URLs to opens links in assistant responses using the `_cody.vscode.open` command.
*/
function wrapLinksWithCodyOpenCommand(url: string): string {
url = defaultUrlTransform(url)
if (!ALLOWED_URI_REGEXP.test(url)) {
return ''
}
const encodedURL = encodeURIComponent(JSON.stringify(url))
return `command:_cody.vscode.open?${encodedURL}`
}
const URL_PROCESSORS: Partial<Record<CodyIDE, UrlTransform>> = {
[CodyIDE.VSCode]: wrapLinksWithCodyOpenCommand,
}
/**
* Transforms the children string by wrapping it in one extra backtick if we find '```markdown'.
* This is used to preserve the formatting of Markdown code blocks within the Markdown content.
* Such cases happen when you ask Cody to create a Markdown file or when you load a history chat
* that contains replies for creating Markdown files.
*
* @param children - The string to transform.
* @returns The transformed string.
*/
const childrenTransform = (children: string): string => {
if (children.indexOf('```markdown') === -1) {
return children
}
children = children.replace('```markdown', '````markdown')
const lastIdx = children.lastIndexOf('```')
// Replace the last three backticks with four backticks
return children.slice(0, lastIdx) + '````' + children.slice(lastIdx + 3)
}
export const MarkdownFromCody: FunctionComponent<{
className?: string
prefixRemarkPlugins?: Pluggable[]
components?: Partial<Components>
children: string
}> = ({ className, prefixRemarkPlugins, components, children }) => {
const clientType = useConfig().clientCapabilities.agentIDE
const urlTransform = useMemo(() => URL_PROCESSORS[clientType] ?? defaultUrlProcessor, [clientType])
const chatReplyTransformed = childrenTransform(children)
return (
<Markdown
className={className}
{...markdownPluginProps(prefixRemarkPlugins ?? [])}
urlTransform={urlTransform}
components={components ?? {}}
>
{chatReplyTransformed}
</Markdown>
)
}
let _markdownPluginProps: ReturnType<typeof markdownPluginProps> | undefined
function markdownPluginProps(
prefixRemarkPlugins: Pluggable[] = []
): Pick<ComponentProps<typeof Markdown>, 'rehypePlugins' | 'remarkPlugins'> {
if (_markdownPluginProps) {
return _markdownPluginProps
}
_markdownPluginProps = {
rehypePlugins: [
[
rehypeSanitize,
{
...defaultSchema,
tagNames: ALLOWED_ELEMENTS,
attributes: {
...defaultSchema.attributes,
code: [
...(defaultSchema.attributes?.code || []),
// Allow various metadata attributes for code blocks
['data-file-path'],
['data-is-code-complete'],
['data-language'],
['data-source-text'],
[
'className',
...Object.keys(SYNTAX_HIGHLIGHTING_LANGUAGES).map(
language => `language-${language}`
),
],
],
},
} satisfies RehypeSanitizeOptions,
],
[
// HACK(sqs): Need to use rehype-highlight@^6.0.0 to avoid a memory leak
// (https://github.com/remarkjs/react-markdown/issues/791), but the types are
// slightly off.
rehypeHighlight as any,
{
detect: true,
languages: {
...SYNTAX_HIGHLIGHTING_LANGUAGES,
},
// `ignoreMissing: true` is required to avoid errors when trying to highlight
// partial code blocks received from the LLM that have (e.g.) "```p" for
// "```python". This is only needed on rehype-highlight@^6.0.0, which we needed
// to downgrade to in order to avoid a memory leak
// (https://github.com/remarkjs/react-markdown/issues/791).
ignoreMissing: true,
} satisfies RehypeHighlightOptions & { ignoreMissing: boolean },
],
],
remarkPlugins: [...prefixRemarkPlugins, remarkGFM, remarkAttachFilePathToCodeBlocks],
}
return _markdownPluginProps
}