-
Notifications
You must be signed in to change notification settings - Fork 67.6k
Expand file tree
/
Copy pathindex.ts
More file actions
69 lines (62 loc) · 2.29 KB
/
Copy pathindex.ts
File metadata and controls
69 lines (62 loc) · 2.29 KB
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 { renderLiquid } from './liquid/index'
import { renderMarkdown, renderUnified } from './unified/index'
import { engine } from './liquid/engine'
import type { Context } from '@/types'
import { createLogger } from '@/observability/logger'
const logger = createLogger(import.meta.url)
interface RenderOptions {
cache?: boolean | ((template: string, context: Context) => string)
filename?: string
textOnly?: boolean
}
const globalCache = new Map<string, string>()
// parse multiple times because some templates contain more templates. :]
export async function renderContent(
template = '',
context: Context = {} as Context,
options: RenderOptions = {},
): Promise<string> {
// If called with a falsy template, it can't ever become something
// when rendered. We can exit early to save some pointless work.
if (!template) return template
let cacheKey: string | null = null
if (options && options.cache) {
if (!context) throw new Error("If setting 'cache' in options, the 'context' must be set too")
if (typeof options.cache === 'function') {
cacheKey = options.cache(template, context)
} else {
cacheKey = getDefaultCacheKey(template, context)
}
if (cacheKey && typeof cacheKey !== 'string') {
throw new Error('cache option must return a string if truthy')
}
if (globalCache.has(cacheKey)) {
return globalCache.get(cacheKey) as string
}
}
try {
template = await renderLiquid(template, context)
if (context.markdownRequested) {
// Skip the remark pipeline when there are no internal links to rewrite,
// since link rewriting is the only transformation the pipeline performs.
if (!/\]\(\s*<?\//.test(template) && !/\]:\s*\//.test(template)) {
return template.trim()
}
return await renderMarkdown(template, context)
}
const html = await renderUnified(template, context, options)
if (cacheKey) {
globalCache.set(cacheKey, html)
}
return html
} catch (error) {
if (options.filename) {
logger.error('renderContent failed on file', { filename: options.filename })
}
throw error
}
}
function getDefaultCacheKey(template: string, context: Context): string {
return `${template}:${context.currentVersion}:${context.currentLanguage}`
}
export const liquid = engine