-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdx_parser.js
349 lines (328 loc) · 14.9 KB
/
mdx_parser.js
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
const {readFile} = require('fs')
const speakers =require('./speakermap.js');
const emoji_map = require('./emoji_map.js');
class MDX_PARSER{
constructor(narrator){
this.narrator=narrator
this.html_head=`<html><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title>Namshub Et'Tulpa</title>
<link rel="stylesheet" href="style.css">
<body>`
this.html_end=`</p></body></html>`
}
async PARSE_MD(cwd,res){ //incomplete and basic
return readFile(cwd,"utf-8",(err,data)=>{
if(data==undefined||err){
return res.send("<h1>there is no file here</h1>");
}
data=this.escapeHtml(data)
data=data.replaceAll(/(\`\`\`(.*?)\`\`\`)/gms,'<pre class="code">$2</pre>')
data=data.replaceAll(/####(.*)/gm,'<h4>$1</h4>')
data=data.replaceAll(/###(.*)/gm,'<h3>$1</h3>')
data=data.replaceAll(" ","</p><p> ")
data=`${this.html_head}${data}${this.html_end}`
return res.send(data)
})
}
trim_deliminator(data){
return data.slice(1,data.length-1)
}
transform_headers(data){
const headers = data?.match(/^[#]+\s.*/gm)||[]; // matches lines with # at start
headers.forEach(head=>{
const count = head.match(/^#+/)[0].length;
const htext = head.replace(/^#+/,"");
const replace = `<h${count}>${htext}</h${count}>`
data=data.replace(head,replace);
})
return data
}
transform_links(data){
var re = /\[(.*?)\]/g
var re2 = /\((.*?)\)/g
const links = data?.match(/\[.*?\]\(.*?\)/g) ||[]
links.forEach(link=>{
const m1 = link.match(re2)[0].replace("(","").replace(")","");
const m2 = link.match(re)[0].replace("]","").replace("[","");
const replace = `<a href="${m1}">${m2}</a>`
data=data.replace(link,replace)
});
return data;
}
transform_images(data){
var re = /\[(.*?)\]/g
var re2 = /\((.*?)\)/g
var re3 = /\{(.*?)\}/g
const images = data?.match(/[!](\[(.*?)\]\(.*?\)\{?.*?\})/g) ||[]
images.forEach(img=>{
const urlandhover = img.match(re2)[0].replace("(","").replace(")","");
const style = img.match(re3)[0]?.replace("{","")?.replace("}","");
const url = urlandhover.slice(0,urlandhover.indexOf(" "))
const altText = img.match(re)[0].replace("]","").replace("[","");
const replace = `<img src="${url}" alt="${altText}" style="${style}"/>`
data=data.replace(img,replace)
})
return data;
}
transform_ordered_lists(data){
const lines = data?.match(/^[0-9]+[.].*?$/gm)||[]
lines.forEach((line,i,arr)=>{
const split_line = line.replace(/^[0-9]+[.]/gm,"")
if(i==0){
data=data.replace(line,`<ol><li >${split_line}</li>`)
}else if(i==arr.length-1){
data=data.replace(line,`<li>${split_line}</li></ol>`)
}else{
data=data.replace(line,`<li>${split_line}</li>`)
}
})
return data;
}
transform_unordered_lists(data){
const unordered_lines = data?.match(/^[-]+.*?$/gm)||[]
unordered_lines.reduce((_last,line,i,arr)=>{
const len = line.match(/^[-]+/gm)[0].length//no need for ||[]
const split_line = line.replace(/^[-]+/gm,"")
if(i==0){
data=data.replace(line,`<ul><li>${split_line}</li>`)
}
else if(len==_last){
if(i==arr.length-1) data=data.replace(line,`<li>${split_line}</li>${`</ul>`.repeat(_last)}`)
else data=data.replace(line,`<li>${split_line}</li>`)
}
else if(len>_last){
if(i==arr.length-1) data=data.replace(line,`<ul><li>${split_line}</li>${`</ul>`.repeat(_last)}`)
else data=data.replace(line,`<ul><li>${split_line}</li>`)
}else if(len<_last){
if(i==arr.length-1) data=data.replace(line,`${`</ul>`.repeat(_last-len)}<li>${split_line}</li>${`</ul>`.repeat(_last)}`)
else data=data.replace(line,`${`</ul>`.repeat(_last-len)}<li>${split_line}</li>`)
}
return len;
},1)
return data;
}
async Parse(cwd,callback){
return readFile(cwd,"utf-8",(err,data)=>{
if(data==undefined||err) return callback("<h1>there is no file here</h1>",null);
const script_bypass={data:""}
const script = data.match(/<script[^>]*>[\s\S]*?<\/script>/gim)
script_bypass.data=script?script[0]:"";``
data=data.replaceAll(script,"");
const div_bypass={data:[],keys:[]};
div_bypass.data = data.match(/[<][d][i][v].*[>].*[<][\/][d][i][v][>]/gm)||[];
div_bypass.keys = div_bypass.data.map((x,i)=>`$;$${i}$;$`)
data=data.replaceAll(div_bypass.data,div_bypass.keys);
const blocks =this.parse_mdx(data)
if(blocks){
const start=data.indexOf("{");
const end = data.lastIndexOf("}");
const start_str = data.slice(0,start);
const end_str = data.slice(end+1);
data= start_str+blocks+end_str
}
data = this.transform_headers(data);
data = this.transform_images(data);
data = this.transform_ordered_lists(data);
data = this.transform_unordered_lists(data);
data = this.transform_links(data);
data=`${this.html_head}${data}</body>
${script_bypass.data}
</html>`
data=data.replace(/([\<][\p][\>][\<][\/][\p][\>])/gm, "")
data=data.replaceAll(div_bypass.keys,div_bypass.data);
callback(null,data);
})
}
parse_mdx(text){
const data = this.get_mdx_data(text);
const blocks = this.separate_blocks(data);
const parsed = blocks.reduce((p,item)=>p+this.mdx_block_parser(item),`<block class="block">`)+`</block>`
return parsed;
}
get_mdx_data(text){
return text.slice(text.indexOf("{"),text.lastIndexOf("}")+1)
}
separate_blocks(data){
let token_maker = "";
const delimiters=["\"","\'","\~","\`","\*"];
const delimiters_stack =[];
const blocks = data.split("").reduce((acc,char,i)=>{
if(char=="}"){
if(delimiters_stack.length==0){
acc.push(token_maker);
token_maker="";
}else{
token_maker=token_maker+String(char)
}
}else if(char == "{" && delimiters_stack.length==0){
}else if(delimiters.includes(char)){
if(char ==delimiters_stack[delimiters_stack.length-1] &&delimiters_stack.length==1){
delimiters_stack.pop()
}else if(delimiters_stack.length==0){
delimiters_stack.push(char);
}
token_maker=token_maker+String(char);
}else{
token_maker=token_maker+String(char);
}
return acc
},[])
return blocks;
}
get_narrator(key){
let narrator;
if(key.includes("__")){
const [k1,k2]=[key.slice(0,key.indexOf("__")),key.slice(key.indexOf("__")+2)]
narrator = speakers["___"](k1,k2);
}else if(key.includes("_")){
const [k1,k2]=[key.slice(0,key.indexOf("_")),key.slice(key.indexOf("_"))]
narrator = speakers["__"](k1,k2);
}
else narrator = speakers[key];
return narrator;
}
mdx_block_parser(block){
let ref=block;
const regex_settings = ref.match(/^\s*[m][n][:](.*)/gm)
block = block.replace(regex_settings,"")
if(regex_settings!=null &®ex_settings.length!=0){
const key=regex_settings[0].slice(regex_settings[0].indexOf(":")+1);
this.narrator= this.get_narrator(key);
}
const pw = ref.match(/\\{0}\`([^`]*)\`/gm)||[];
pw.forEach(r=>ref=ref.replace(r,""))
const aw = ref.match(/\\{0}\*([^*]*)\*/gm)||[];
aw.forEach(r=>ref=ref.replace(r,""))
const dw = ref.match(/\\{0}\~([^~]*)\~/gm)||[];
dw.forEach(r=>ref=ref.replace(r,""))
const sw = ref.match(/\\{0}\"([^"]*)\"/gm)||[];
sw.forEach(r=>ref=ref.replace(r,""))
const tw = ref.match(/\\{0}\'([^']*)\'/gm)||[];
tw.forEach(r=>ref=ref.replace(r,""));
const lines_types = [...sw,...tw,...aw,...dw];
const transforms_words = lines_types.map(x=>{
return {
o:x,
t:this.scp(x,false),
}
})
let transforms_data = pw.map(x=>{
return {
o:x,
t:x
}
})
transforms_data = transforms_data.map((obj,i)=>{
let ref = obj.t;
const aw = ref.match(/\*([^*]*)\*/gm)||[];
const dw = ref.match(/\~([^~]*)\~/gm)||[];
const sw = ref.match(/\"([^"]*)\"/gm)||[];
const tw = ref.match(/\'([^']*)\'/gm)||[];
//handle links inside code section - need to be extracted
var re = /(\[.*?\])/g
var re2 = /(\(.*?\))/g
const html_links =(ref.match(/\<a.*\>/gm)||[]);
const html_transform_box = html_links.map(x=>({o:x,t:x}))
const md_links = (ref.match(/[^!](\[(.*?)\]\(.*?\))/g))||[]
const md_html = md_links.map(link=>{
const m1 = link.match(re2)[0].replace("(","").replace(")","");
const m2 = link.match(re)[0].replace("]","").replace("[","");
return {o:link,t:`<a href="${m1}">${m2}</a>`}
});
const links = [...md_html,...html_transform_box]
const fake_links = links.map((link,i)=>`!!@@!${i}!@@!!`)
links.forEach((l,i)=>{
obj.t=obj.t.replaceAll(links[i].o,fake_links[i])})
const internal_data_matches = [...aw,...dw,...sw,...tw];
internal_data_matches.forEach(match=>ref=ref.replace(match,""));
const internal_data_matches_unique = internal_data_matches.reduce((acc,item)=>{
if(!acc.includes(item))acc.push(item)
return acc
},[])
// that felt unclean - to fix
internal_data_matches_unique.forEach(match=>{
obj.t=obj.t.replaceAll(match,this.scp(match,true))
})
obj.t=obj.t.replaceAll(/([t][r][u][e]|[f][a][l][s][e])/gm,`<span class="boolean">$1</span>`)
obj.t=obj.t.replaceAll(/([=][>]|[<][=]|[e][x][e]|[|][|]|[W][I][T][H]|[W][H][I][L][E]|[T][R][Y]|[C][A][T][C][H])/gm,`<span class="cli">$1</span>`)
obj.t=obj.t.replaceAll(/([\{]|[\}]|[\[]|[\]]|[\(]|[\)])/gm,`<span class="bracket">$1</span>`)
obj.t=obj.t.replaceAll(/([\s][-][\w]+)/gm,`<span class="cli-option">$1</span>`)
obj.t=obj.t.replaceAll(/([-][-][\w][\w-]*)/gm,`<span class="cli-option-long">$1</span>`)
obj.t=obj.t.replaceAll(/([.][\w]+)/gm,`<span class="cli-object">$1</span>`)
fake_links.forEach((fl,i)=>obj.t=obj.t.replaceAll(fl,links[i].t))
return obj;
})
transforms_data = transforms_data.map(x=>{
const text = x.t.slice(1,x.t.length-1)
return {
o:x.o,
t:`<pre class="code"><span>${text}</span></pre>`
}
})
const transforms = [...transforms_data,...transforms_words].reduce((acc,t)=>{
if (acc.includes(y=>y.o==t.o)){}
else {acc.push(t)}
return acc
},[])
transforms.forEach(t=>{
block=block.replaceAll(t.o,t.t)
if(t.o[0]=="`"){
}
})
block=block.replaceAll(/([\<][\p][\>][\<][\/][\p][\>])/gm, "")
block=block.replaceAll(/([\^]+)/gm,`<span class="indicator">$1</span>`)
block=block.replaceAll(/([%][%][%][%])/gm,`<br /><div class="section_break">%%%%</div><br /><br />`);
return block;
}
scp(txt,internal_data_flag){
const speaker_regex = txt.match(/\w+[:][:]/gm);
const emoji_regex = txt.match(/[$][E][\w]*[:]/gm);
if(emoji_regex){
for(const match of emoji_regex){
let key = match.slice(2,emoji_regex.indexOf(":"));
let emoji = emoji_map[key];
txt=txt.replace(match, emoji);
}
}
switch(txt[0]){
case "\"":
if(internal_data_flag) return `<span class="speech">${txt}</span>`;
if(speaker_regex){
let key = speaker_regex[0].slice(0,speaker_regex.indexOf(":")-1);
const speaker = this.get_narrator(key);
const mainFlag = speaker == this.narrator;
const dialouge = txt[0]+txt.slice(txt.indexOf("::")+2)
const d = `<span>${dialouge}</span>`
return this.speaker_bubble_div(d,mainFlag,speaker,"speech");
}
return `<span>${txt}</span>`;
case "\'":
if(internal_data_flag) return `<span class="thought">${txt}</span>`;
if(speaker_regex){
let key = speaker_regex[0].slice(0,speaker_regex.indexOf(":")-1);
const speaker = this.get_narrator(key);
const mainFlag = speaker== this.narrator;
const dialouge = txt[0]+txt.slice(txt.indexOf("::")+2)
const d = `<span>${dialouge}</span>`
return this.speaker_bubble_div(d,mainFlag,speaker,"thought");
}else{
const d = `<span>${txt}</span>`
return this.speaker_bubble_div(d,true,this.narrator,"thought")
}
case "\~": return `<span class="description">${this.trim_deliminator(txt)}</span>`;
case "\*": return `<span class="action">${this.trim_deliminator(txt)}</span>`;
case "\`": return `<code class="code";>${this.trim_deliminator(txt)}</code>`;
}
}
speaker_bubble_div(txt,mainNB,speaker,type) {
return`<div class=" bubble ${mainNB?"narrator":"other"} ${mainNB?type:`${type}2`}">
<div class="bubble_label">${speaker}</div>
<div class="type" style="padding-${mainNB?'left':'right'}: 15;">${txt}</div>
</div>`
}
escapeHtml (unsafe) {
return unsafe.replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
}
}
module.exports={MDX_PARSER};