-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlebars-template-engine.ts
218 lines (189 loc) · 5.48 KB
/
handlebars-template-engine.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
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
import hb from "handlebars"
import { TakomoError } from "../../utils/errors.js"
import {
expandFilePath,
fileExists,
FilePath,
readFileContents,
} from "../../utils/files.js"
import { TkmLogger } from "../../utils/logging.js"
import { buildErrorMessage } from "../../utils/templating.js"
import {
RenderTemplateFileProps,
RenderTemplateProps,
TemplateEngine,
} from "../template-engine.js"
export class PartialAlreadyRegisteredError extends TakomoError {
constructor(
name: string,
pathToPartialFile: FilePath,
pathToExistingPartialFile: FilePath,
) {
const message = `Partial with name '${name}' already registered from ${pathToExistingPartialFile}`
super(message, {
info: `Could not register partial ${name} from ${pathToPartialFile} because a partial with the same name is already registered`,
instructions: ["Use another name to register your partial"],
})
}
}
interface HandlebarsTemplateEngineProps {
readonly projectDir: FilePath
readonly logger: TkmLogger
}
/**
* See https://handlebarsjs.com/api-reference/compilation.html#handlebars-compile-template-options
*/
export interface HandlebarsCompileOptions {
data?: boolean
compat?: boolean
knownHelpersOnly?: boolean
noEscape?: boolean
strict?: boolean
assumeObjects?: boolean
preventIndent?: boolean
ignoreStandalone?: boolean
explicitPartialContext?: boolean
}
export type HandlebarsTemplateDelegate = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context: any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options?: any,
) => string
/**
* Optional last argument for Hanblebars helpers.
*/
export interface HandlebarsHelperOptions {
/**
* Helper name
*/
name: string
/**
* Hash options
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
hash: any
/**
* Data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: any
/**
* Helper location in the template
*/
loc: {
start: {
line: number
column: number
}
end: {
line: number
column: number
}
}
}
export class HandlebarsSafeString {
readonly #str: string
constructor(str: string) {
this.#str = str
}
toString(): string {
return this.#str
}
toHTML(): string {
return this.#str
}
}
export class HandlebarsTemplateEngine implements TemplateEngine {
readonly #instance = hb.create()
readonly #registeredPartials = new Map<string, string>()
readonly #projectDir: FilePath
readonly #logger: TkmLogger
constructor({ logger, projectDir }: HandlebarsTemplateEngineProps) {
this.#projectDir = projectDir
this.#logger = logger
}
compile(
templateString: string,
options?: HandlebarsCompileOptions,
): HandlebarsTemplateDelegate {
return this.#instance.compile(templateString, options)
}
safeString(str: string): HandlebarsSafeString {
return new HandlebarsSafeString(str)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
registerHelper(name: string, fn: any): void {
this.#instance.registerHelper(name, fn)
}
async registerPartial(name: string, pathToFile: FilePath): Promise<void> {
const absolutePath = expandFilePath(this.#projectDir, pathToFile)
this.#logger.debug(`Register partial '${name}' from file ${absolutePath}`)
const existingPathToFile = this.#registeredPartials.get(name)
if (existingPathToFile) {
throw new PartialAlreadyRegisteredError(
name,
absolutePath,
existingPathToFile,
)
}
const partialString = await readFileContents(absolutePath)
this.#registeredPartials.set(name, absolutePath)
const partial = this.#instance.compile(partialString)
this.#instance.registerPartial(name, partial)
}
async renderTemplate({
templateString,
variables,
sourceDescription,
}: RenderTemplateProps): Promise<string> {
this.#logger.trace(`Render template from ${sourceDescription}`)
const template = this.#instance.compile(templateString, {
noEscape: true,
strict: true,
})
this.#logger.traceText(
"Template body before rendering:",
() => templateString,
)
this.#logger.traceObject("Render template with variables:", () => variables)
try {
const renderedTemplate = template(variables)
this.#logger.traceText(
"Template body after rendering:",
() => renderedTemplate,
)
return renderedTemplate
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
this.#logger.error(
`An error occurred while rendering template from ${sourceDescription}`,
e,
)
const errorMessage = buildErrorMessage(
`An error occurred while rendering template from ${sourceDescription}`,
templateString,
e,
)
throw new TakomoError(errorMessage)
}
}
async renderTemplateFile({
pathToFile,
variables,
}: RenderTemplateFileProps): Promise<string> {
const absolutePath = expandFilePath(this.#projectDir, pathToFile)
this.#logger.trace(`Render template from file ${absolutePath}`)
if (!(await fileExists(absolutePath))) {
throw new TakomoError(
`Could not render template from file ${absolutePath} because the file doesn't exist`,
)
}
const templateString = await readFileContents(absolutePath)
return this.renderTemplate({
templateString,
variables,
sourceDescription: `file ${pathToFile}`,
})
}
}