-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcms.js
703 lines (612 loc) · 21.7 KB
/
cms.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import { marked } from "marked";
import { gfmHeadingId } from "marked-gfm-heading-id";
import { parse as qsParse, stringify as qsStringify } from "qs";
import hljs from "highlight.js";
marked.use(gfmHeadingId());
marked.use({ gfm: true });
const TYPES = {
articles: {
markdown: ["content"],
},
"key-terms": {
markdown: ["content"],
},
};
const tableOfContentsRegex = /{{( )?tableofcontents( )?}}/gi;
const ctaOneRegex = /{{( )?ctaone( )?}}/gi;
const ctaTwoRegex = /{{( )?ctatwo( )?}}/gi;
const populateMediaField = {
fields: [
"name",
"alternativeText",
"caption",
"width",
"height",
"url",
"formats",
"mime",
"provider_metadata",
],
};
const populateTableComponentField = {
fields: ["title", "tableContent"],
};
const populateReviewComponentField = {
fields: [
"reviewTitle",
"reviewLink",
"sourceName",
"sourceLink",
"userName",
"userLink",
"userDesignation",
"content",
],
};
const sanitize = (text = "") => {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/`/g, "`");
};
const tableOfContents = (html) => {
const toc = [];
var level = 0;
html.replace(
/<h([1-6]) id="([^"]+)">(<a[^>]+>)?([^<]+)(<\/a>)?<\/h([1-6])>/g,
function (match, _level, id, _2, text) {
_level = parseInt(_level, 10);
while (level > _level) {
level--;
}
while (level < _level) {
level++;
}
toc.push({ id, level, text });
},
);
return toc;
};
function createIndentedList(items) {
let html = "";
let currentLevel = 1;
let stack = [];
for (const item of items) {
const { id, level, text } = item;
while (level < currentLevel) {
html += `</li></${stack.pop()}>`;
currentLevel--;
}
while (level > currentLevel) {
html += `<ol><li>`;
stack.push("ol");
currentLevel++;
}
if (level === currentLevel) {
html += `</li><li><NuxtLink to="#${id}">${text}</NuxtLink>`;
} else {
html += `<li><NuxtLink to="#${id}">${text}</NuxtLink>`;
}
}
while (stack.length > 0) {
html += `</li></${stack.pop()}>`;
}
// Remove empty list items
html = html.replace(/<li>(\n)?<\/li>/g, "");
// replace multiple \n with a single \n
html = html.replace(/\n{2,}/g, "\n");
return html;
}
const preconvert = (
markdown,
{ showIndex = false, inlineMedia, doFollowLinks = false } = {},
) => {
// Replace HTML tags with < and > except in ``` blocks in markdown
markdown = markdown
.split("```")
.map((nonCode, index) => {
if (index % 2 === 0) {
return nonCode
.split("`")
.map((part, index) => {
if (index % 2 === 0) {
// Sanitize the text outside of the code blocks
// Change ![optional text](<https://example.com>) into ![optional text](https://example.com)
part = part.replace(/\[([^\]]*)\]\(<([^\>]+)>\)/g, "[$1]($2)");
// Sanitize only the p, img, and a tags
part = part.replace(
/<((?!\/?(span|details|summary|code|mark|p|img|a|br|hr))[^>]+)>/g,
"<$1>",
);
// A underscore direct after a new line after an image.
// this markdown:
// ![image](https://example.com/image.png)
// caption (source [link](https://exmaple.com))
//
// is converted to this:
// ![image](https://example.com/image.png)
// _caption (source [link](https://exmaple.com))_
part = part.replace(
/(\n|^)(!?\[[^\]]+\]\([^\)]+\))\n(.+)\n/g,
"$1$2\n<em>$3</em>\n",
);
for (const { id, attributes } of inlineMedia?.data || []) {
// Replace `![alt text](url)` with `![alt text](id)`
part = part.replace(
/!\[(?:[^\]]*)\]\(([^\)]+)\)/g,
(match, url) => {
if (
url === attributes.url &&
attributes.mime === "image/gif"
) {
const metadata = attributes.provider_metadata;
const medium = metadata?.formats?.medium;
const file =
medium?.webp?.url || medium?.gif?.url || attributes.url;
const poster =
medium?.poster?.webp?.url || medium?.poster?.png?.url;
const color = metadata?.meta?.averageColorHex || "";
return `<Gif width="${medium?.width || ""}" height="${
medium?.height || ""
}" poster="${
poster || ""
}" background="${color}" src="${file}" />`;
}
return match;
},
);
part = part.replace(
/\[(?:[^\]]*)\]\(([^\)]+)\)/g,
(match, url) => {
if (
url === attributes.url &&
attributes.mime?.startsWith("video/")
) {
const metadata = attributes.provider_metadata;
const xlarge = metadata?.formats?.xlarge;
const file =
xlarge?.webp?.url || xlarge?.gif?.url || attributes.url;
const poster =
xlarge?.poster?.webp?.url ||
xlarge?.poster?.png?.url ||
"";
const color = metadata?.meta?.averageColorHex || "";
const brightness =
metadata?.meta?.averageColorBrightness || "";
return `<Video width="${xlarge?.width || ""}" height="${
xlarge?.height || ""
}" background="${color}" brightness="${brightness}" poster="${poster}"><source src="${
xlarge?.mp4?.url || attributes.url
}" type="video/mp4" />${
xlarge?.webm?.url
? `<source src="${xlarge?.webm?.url}" type="video/webm" />`
: ""
}Video not supported, you can <a href="${file}">download it</a>.</Video>`;
}
return match;
},
);
}
// Replace [^1]: and [^string]: with - [^1]: and - [^string]:
part = part.replace(
/(\n|^)(\[\^)([^\]]+)(\]:)/g,
function (match, _1, _2, id, _3) {
return `${_1}- ${_2}${id}${_3}`;
},
);
part = part.replace(
/{% include gif\.html slug="([^"]+)" alt="([^"]+)"(?:.*?)%}/g,
"![$2](https://assets.simpleanalytics.com/gifs/$1.gif)",
);
// Replace markdown footnotes like [^1] or [^note] with <sup id="ref-1"><a href="#note-1">1</a></sup>
// make sure it does not match [^1]: or [^1](
part = part.replace(
/(?<!\[\^)(\[\^)([^\]]+)(\])(?!\:|\()/g,
function (match, _1, id, _2) {
const ref = id.replace(/[^a-z0-9]/gi, "-");
return `<sup id="ref-${ref}"><a class="no-underline p-1" href="#note-${ref}">${id}</a></sup>`;
},
);
// Replace \n\n>>text\n\n with <blockquote>text</blockquote>
part = part.replace(
/(\n\n|^)(\>\>)(.+?)(\n\n)/g,
function (match, prefix, _indent, text, suffix) {
return `${prefix}<blockquote class="warning"><p>${text}</p></blockquote>${suffix}`;
},
);
return part;
} else {
// Leave the code block unchanged
return "`" + part + "`";
}
})
.join("");
} else {
const languages = hljs.listLanguages();
const firstLine = nonCode.split("\n")[0];
const language = firstLine === "html" ? "xml" : firstLine;
const validLanuage = languages.includes(language);
// Remove the first line if it is a language
if (validLanuage) nonCode = nonCode.split("\n").slice(1).join("\n");
const code = validLanuage
? hljs.highlight(nonCode, { language })?.value
: hljs.highlightAuto(nonCode)?.value;
// Remove first and last \n
const trimmedCode = code.replace(/^\n/, "").replace(/\n$/, "");
return `<pre class="not-prose px-2 py-1 rounded-lg whitespace-pre-wrap text-base bg-gray-100 dark:bg-gray-700"><code class="hljs">${trimmedCode}</code></pre>`;
}
})
.join("");
// In the markdown links are formatted like this: [text](<url>), replace those with [text](url)
markdown = markdown.replace(
/\[([^\]]+)\]\((<|<)(>|.+?(?=>))(>|>)\)/g,
"[$1]($3)",
);
// Convert markdown to html
let html = marked.parse(markdown);
// Replace external links with target="_blank"
html = html.replace(
/<a href="([^"]+)"([^>]*)>([^<]+)<\/a>/g,
function (match, href, attributes, text) {
try {
const url = new URL(href, "https://www.simpleanalytics.com");
const isHttp = /^https?:\/\//i.test(href);
if (url.hostname === "www.simpleanalytics.com") {
const path = href.split("/").slice(3).join("/");
return `<a href="/${path}" ${attributes}>${text}</a>`;
}
if (isHttp && url.hostname.includes("simpleanalytics"))
return `<a href="${href}"${attributes} referrerpolicy="unsafe-url" rel="">${text}</a>`;
if (isHttp) {
if (!url.searchParams.has("utm_source"))
url.searchParams.set("utm_source", "simpleanalytics.com");
const rels = ["noopener"];
if (!doFollowLinks) rels.push("nofollow");
const referrerpolicy = doFollowLinks
? "unsafe-url"
: "strict-origin-when-cross-origin";
return `<a referrerpolicy="${referrerpolicy}" href="${url.toString()}"${attributes} target="_blank" rel="${rels.join(
" ",
)}">${text}</a>`;
}
return match;
} catch (error) {
console.error(error);
return match;
}
},
);
// Replace GIF images with VueFreezeframe component
html = html.replace(/<img src="([^"]+)"([^>]*)>/g, function (match, src) {
if (src.endsWith(".gif"))
return `<img class="mx-auto rounded-lg" src="${src}" />`;
return match;
});
// Replace markdown footnotes like [^1]: or [^note] with <li id="note-1"><a href="#ref-1">1</a></li>
html = html.replace(
/(\[\^)([^\]]+)(\]:)(.+)(?=\n)/g,
function (match, _1, id, _2, text) {
const ref = id.replace(/[^a-z0-9]/gi, "-");
return `<a id="note-${ref}" class="no-underline" href="#ref-${ref}">#${id}</a> ${text.trim()}`;
},
);
// Add classes
html = html.replace(
/<ul>\s?<li>\s?<a\sid\=\"note\-/,
'<ul class="not-prose list-none mt-8 pt-6 border-t-2 border-gray-300 dark:border-gray-600 pl-0 text-sm text-red-600"><li><a id="note-',
);
html = html.replace(
/<li>\s?<a\sid\=\"note\-/g,
'<li class="text-gray-400 dark:text-gray-500 mb-2"><a id="note-',
);
// Remove <p> tags around `<p>{{tableofcontents}}</p>`
html = html.replace(/<p>{{([a-z0-9\.]+)}}<\/p>/gi, "{{$1}}");
// Remove <p> tags around `<p><Video>...</Video></p>`
html = html.replace(
/<p><Video((?:(?!<\/Video>).)*)<\/Video>(\n.+)?<\/p>/gi,
"<Video$1</Video>$2",
);
// Remove <p> tags around `<p><Gif...</Gif></p>`
html = html.replace(
/<p><Gif((?:(?!<\/Gif>).)*)<\/Gif>(\n.+)?<\/p>/gi,
"<Gif$1</Gif>$2",
);
if (!showIndex) {
if (tableOfContentsRegex.test(html))
return html.replace(tableOfContentsRegex, "");
return html;
}
const toc = tableOfContents(html);
if (toc.length === 0) return html;
// Add class to first <ol> to make it a counter
const index = createIndentedList(toc).replace(
"<ol>",
'<ol class="counters">',
);
const ctaOne = ctaOneRegex.test(html) ? "" : "{{ctaone}}";
// Check if html contains "{{tableofcontents}}"
if (tableOfContentsRegex.test(html))
return html.replace(tableOfContentsRegex, `${index}${ctaOne}`);
const firstH2Index = html.search(/<h2/);
const hasPBeforeH2 = firstH2Index
? html
.slice(0, firstH2Index + "<h2".length)
.match(/<p>([^<]{0,100})<\/p>\n<h2/)
: false;
// Check if paragraph before <h2> is less than 100 characters
if (hasPBeforeH2)
return html.replace(
/(<p>([^<]{0,100})<\/p>\n)<h2/,
`${index}${ctaOne}$1<h2`,
);
// Insert before first <h2> if it exists
if (/<h2/.test(html)) return html.replace(/<h2/, `${index}${ctaOne}<h2`);
return `${index}${ctaOne}${html}`;
};
const replacer = ({
match,
tag,
attributes,
content,
parent,
parentAttributes,
id,
}) => {
if (/(<img|ContentEditable|<ol class|<Video )/i.test(match)) return match;
const html = `<ContentEditable ${attributes} parent="${parent || ""}" tag="${
tag || ""
}" articleId="${id || ""}">${content}</ContentEditable>`;
if (parent)
return `<${parent}${
parentAttributes ? ` ${parentAttributes}` : ""
}>${html}</${parent}>`;
return html;
};
const getReviews = ({ matchedValue, reviews }) => {
let html = "";
if (reviews) {
for (const review of reviews) {
if (
review.reviewTitle?.trim().toLowerCase() ===
matchedValue?.trim().toLowerCase()
) {
html = `
<div class="border-2 border-red-600 rounded-lg h-auto w-auto mb-4">
<div class="px-4 md:px-8 lg:px-12 mb-12">
<div class="px-3 py-1.5 text-white text-base w-auto max-w-full font-semibold bg-gradient-to-b from-red-400 to-red-500 dark:from-red-600 dark:to-red-600 rounded-b-lg inline-block truncate">
<span>${sanitize(review.reviewTitle.trim())}</span>
</div>
${preconvert(review.content.trim())}
</div>
<div class="flex items-center justify-between w-full px-4 md:px-8 lg:px-12 py-2 rounded-b-md bg-gradient-to-b from-red-400 to-red-500 dark:from-red-600 dark:to-red-600">
<div class="font-semibold text-base text-white max-w-[50%] truncate">
${
review.userLink
? `
<NuxtLink
target="_blank"
to="${sanitize(review.userLink)}"
class="font-semibold text-base text-white truncate"
>${sanitize(review.userName.trim())}</NuxtLink>
`
: `
<span class="font-semibold text-base text-white/75 truncate">
${sanitize(review.userName.trim())}
</span>
`
}
${
review.userDesignation
? `<span class="font-semibold text-base text-white/75 truncate">, ${sanitize(
review.userDesignation.trim(),
)}</span>`
: ""
}
</div>
${
review.sourceName
? `
<div class="text-base text-white font-semibold inline-flex items-center max-w-[50%]">
<span class="truncate max-w-[calc(100%-1.5rem)]">Source: ${sanitize(
review.sourceName.trim(),
)}</span>
${
review.sourceLink
? `
<NuxtLink
target="_blank"
to="${sanitize(review.sourceLink)}"
class="ml-1 w-5 h-5 text-white"
>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-full w-full">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
</svg>
</NuxtLink>
`
: ""
}
</div>
`
: ""
}
</div>
</div>
`;
}
}
}
return html;
};
const convert = (markdown, attributes) => {
let html = preconvert(markdown, attributes);
const randomCta = Math.random() < 0.5 ? "CtaOne" : "CtaTwo";
const ctas = attributes.showCallToActions !== false;
html = html.replace(ctaOneRegex, ctas ? `<${randomCta} />` : "");
html = html.replace(ctaTwoRegex, ctas ? `<${randomCta} />` : "");
const id = attributes.id;
const tables = attributes?.tables;
const reviews = attributes?.reviews;
html = html
// Replace handlebar variables with html characters
.replace(/{{/g, "{{")
.replace(/}}/g, "}}")
.replace(
/<a href="([^"]+)"([^>]*)>((?:(?!<\/a>).)*)<\/a>/g,
(match, href, attributes, text) => {
return `<NuxtLink to="${href}"${
attributes ? ` ${attributes}` : ""
}>${text}</NuxtLink>`;
},
)
// replace and add review tags as per there occurence
.replace(
/<p>{{review "([^&]+)"}}<\/p>/g,
(_, matchedValue) => {
return getReviews({
matchedValue,
reviews,
});
},
)
.replace(
/(?<!(?:<blockquote(?:[^>]*)>\n?))<(p)([^>]*)>((?:(?!<\/p>).)*)<\/p>/g,
(match, tag, attributes, content) =>
replacer({ match, tag, attributes, content, id }),
)
.replace(
/<(summary)([^>]*)>((?:(?!<\/summary>).)*)<\/summary>/g,
(match, tag, attributes, content) =>
replacer({ match, tag, attributes, content, id }),
)
.replace(
/<(blockquote)([^>]*)>(?:[ \r\n]*)<(p)([^>]*)>((?:(?!<\/p>).)*)<\/p>(?:[ \r\n]*)<\/blockquote>/g,
(match, parent, parentAttributes, tag, attributes, content) =>
replacer({
match,
parent,
parentAttributes,
tag,
attributes,
content,
id,
}),
)
.replace(
/<(h[1-9])([^>]*)>((?:(?!<\/h[1-9]>).)*)<\/h[1-9]>/g,
(match, tag, attributes, content) =>
replacer({ match, tag, attributes, content, id }),
);
return html;
};
const parse = ({ type, response }) => {
response.data = response.data.map((item) => {
// Add ID to attributes
if (item.id) item.attributes.id = item.id;
for (const iterator of TYPES[type].markdown) {
if (item.attributes[iterator]) {
item.attributes[iterator + "Html"] = convert(
item.attributes[iterator],
item.attributes,
);
}
}
if (item.attributes.localizations.data.length > 0) {
item.attributes.localizations.data.forEach((localization) => {
for (const iterator of TYPES[type].markdown) {
if (localization.attributes[iterator]) {
localization.attributes[iterator + "Html"] = convert(
localization.attributes[iterator],
item.attributes,
);
}
}
});
}
return item;
});
return response;
};
export default defineEventHandler(async (event) => {
const { strapiToken, cmsUrl } = useRuntimeConfig();
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${strapiToken}`,
};
const url = new URL(event.node?.req.url, cmsUrl);
const path = url.searchParams.get("path");
const type = path.slice(1);
url.pathname = "/api" + path;
const fields = url.searchParams.has("fields")
? url.searchParams.get("fields").split(",").filter(Boolean)
: [];
const nonRelationFields = fields.filter(
(field) =>
![
"coverImageWithoutText",
"coverImageWithText",
"inlineMedia",
"contentHtml",
"languages",
].includes(field),
);
const populate =
fields.includes("coverImageWithoutText") ||
fields.includes("coverImageWithText") ||
fields.includes("inlineMedia") ||
fields.includes("tables") ||
fields.includes("reviews")
? {
coverImageWithoutText: populateMediaField,
coverImageWithText: populateMediaField,
inlineMedia: populateMediaField,
tables: populateTableComponentField,
reviews: populateReviewComponentField,
}
: {};
const userAgent = url.searchParams.get("userAgent");
url.searchParams.delete("userAgent");
const userPath = url.searchParams.get("userPath");
url.searchParams.delete("userPath");
const params = {
...qsParse(url.search.slice(1)),
locale: url.searchParams.has("locale")
? url.searchParams.get("locale")
: "all",
sort: url.searchParams.has("sort")
? url.searchParams.get("sort")
: "publishedAt:desc",
fields: nonRelationFields,
populate: {
localizations: {
fields: nonRelationFields,
populate,
},
...populate,
},
pagination: {
pageSize: url.searchParams.has("pagination[pageSize]")
? url.searchParams.get("pagination[pageSize]")
: "500",
},
publicationState: url.searchParams.has("drafts") ? "preview" : "live", // preview
};
const query = qsStringify(params, {
encodeValuesOnly: true, // prettify URL
});
url.search = query;
if (!path || !TYPES[type]) throw new Error("Invalid type, add to TYPES");
const response = await $fetch(url, {
method: "GET",
headers,
ignoreResponseError: true,
});
if (response?.error) {
const error = response.error.message || response.error;
console.error(error, { userPath });
throw new Error(error);
}
return parse({ type, response });
});