-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
utils-pure.ts
48 lines (45 loc) · 1.46 KB
/
utils-pure.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
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { OgImageOptions } from '../../types'
function decodeHtmlEntities(obj: Record<string, string | any>) {
Object.entries(obj).forEach(([key, value]) => {
// unescape all html tokens
if (typeof value === 'string') {
obj[key] = value
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '\'')
.replace(///g, '/')
}
})
return obj
}
export function extractOgImageOptions(html: string) {
// extract the options from our script tag
const htmlPayload = html.match(/<script id="nuxt-og-image-options" type="application\/json">(.+?)<\/script>/)?.[1]
if (!htmlPayload)
return false
let options: OgImageOptions | false
try {
options = JSON.parse(htmlPayload)
}
catch (e) {
options = false
if (process.dev)
console.warn('Failed to parse #nuxt-og-image-options', e, options)
}
if (options) {
// extract the og:description from the html
const description = html.match(/<meta property="og:description" content="(.*?)">/)?.[1]
if (description)
options.description = description
else
options.description = html.match(/<meta name="description" content="(.*?)">/)?.[1]
return decodeHtmlEntities(options)
}
return false
}
export function stripOgImageOptions(html: string) {
return html
.replace(/<script id="nuxt-og-image-options" type="application\/json">(.*?)<\/script>/, '')
}