-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
orga-util.ts
69 lines (58 loc) · 1.86 KB
/
orga-util.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import _ from 'lodash/fp'
import { Parser } from 'orga'
import { selectAll } from 'unist-util-select'
export const getProperties = headline => {
const drawer = selectAll(`drawer`, headline).find(d => d.name === `PROPERTIES`)
if (!drawer) return {}
const regex = /\s*:(.+):\s*(.+)\s*$/
return drawer.value.split(`\n`).reduce((accu, current) => {
const m = current.match(regex)
return { ...accu, [m[1].toLowerCase()]: m[2] }
}, {})
}
const shouldBeArray = (key: string) => [`keywords`, `tags`].includes(key)
export const processMeta = _.mapValues.convert({ cap: false })((v, k) => {
if (shouldBeArray(k) && typeof v === `string`) {
return v.match(/[^ ]+/g)
}
return v
})
export const sanitise = (title: string) => {
return title.replace(/\s+/g, '-').replace(/[^a-z0-9-]/gi, '').toLowerCase()
}
const astCacheKey = node =>
`transformer-orga-ast-${
node.internal.contentDigest
}`
const ASTPromiseMap = new Map()
export const getAST = async ({ node, cache }) => {
const cacheKey = astCacheKey(node)
const cachedAST = await cache.get(cacheKey)
if (cachedAST) {
return cachedAST
}
if (ASTPromiseMap.has(cacheKey)) return await ASTPromiseMap.get(cacheKey)
const ASTGenerationPromise = getOrgAST(node)
ASTGenerationPromise.then(ast => {
cache.set(cacheKey, ast)
ASTPromiseMap.delete(cacheKey)
}).catch(err => {
ASTPromiseMap.delete(cacheKey)
return err
})
// Save new AST to cache and return
// We can now release promise, as we cached result
ASTPromiseMap.set(cacheKey, ASTGenerationPromise)
return ASTGenerationPromise
}
async function getOrgAST(node) {
return new Promise(resolve => {
const parser = new Parser()
const ast = parser.parse(node.internal.content)
resolve(ast)
})
}
export const cacheAST = ({ node, cache, ast }) => {
const cacheKey = astCacheKey(node)
cache.set(cacheKey, ast)
}