-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
micromark-encode.ts
35 lines (29 loc) · 875 Bytes
/
micromark-encode.ts
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
import type { HtmlExtension, Token, Tokenize } from 'micromark/dist/shared-types';
const characterReferences = {
'"': 'quot',
'&': 'amp',
'<': 'lt',
'>': 'gt',
'{': 'lbrace',
'}': 'rbrace',
};
type EncodedChars = '"' | '&' | '<' | '>' | '{' | '}';
function encode(value: string): string {
return value.replace(/["&<>{}]/g, (raw: string) => {
return '&' + characterReferences[raw as EncodedChars] + ';';
});
}
function encodeToken(this: Record<string, () => void>) {
const token: Token = arguments[0];
const serialize = (this.sliceSerialize as unknown) as (t: Token) => string;
const raw = (this.raw as unknown) as (s: string) => void;
const value = serialize(token);
raw(encode(value));
}
const plugin: HtmlExtension = {
exit: {
codeTextData: encodeToken,
codeFlowValue: encodeToken,
},
};
export { plugin as encodeMarkdown };