2021-10-14 12:51:05 +02:00
|
|
|
const handlebars = require("handlebars")
|
2022-02-07 18:56:01 +01:00
|
|
|
const { registerAll, registerMinimum } = require("./helpers/index")
|
2021-10-14 12:51:05 +02:00
|
|
|
const processors = require("./processors")
|
2021-12-06 18:58:43 +01:00
|
|
|
const { atob, btoa } = require("./utilities")
|
2021-10-14 12:51:05 +02:00
|
|
|
const manifest = require("../manifest.json")
|
2022-03-02 18:40:50 +01:00
|
|
|
const {
|
|
|
|
FIND_HBS_REGEX,
|
|
|
|
FIND_ANY_HBS_REGEX,
|
|
|
|
findDoubleHbsInstances,
|
|
|
|
} = require("./utilities")
|
2022-07-28 21:20:53 +02:00
|
|
|
const { convertHBSBlock } = require("./conversion")
|
2021-10-14 12:51:05 +02:00
|
|
|
|
|
|
|
const hbsInstance = handlebars.create()
|
|
|
|
registerAll(hbsInstance)
|
2021-10-26 21:04:36 +02:00
|
|
|
const hbsInstanceNoHelpers = handlebars.create()
|
2022-02-07 18:56:01 +01:00
|
|
|
registerMinimum(hbsInstanceNoHelpers)
|
2022-02-07 10:50:17 +01:00
|
|
|
const defaultOpts = {
|
|
|
|
noHelpers: false,
|
|
|
|
cacheTemplates: false,
|
|
|
|
noEscaping: false,
|
2022-02-09 16:18:44 +01:00
|
|
|
escapeNewlines: false,
|
|
|
|
noFinalise: false,
|
2022-02-07 10:50:17 +01:00
|
|
|
}
|
2021-10-14 12:51:05 +02:00
|
|
|
|
|
|
|
/**
|
2022-01-29 19:53:21 +01:00
|
|
|
* Utility function to check if the object is valid.
|
2021-10-14 12:51:05 +02:00
|
|
|
*/
|
|
|
|
function testObject(object) {
|
|
|
|
// JSON stringify will fail if there are any cycles, stops infinite recursion
|
|
|
|
try {
|
|
|
|
JSON.stringify(object)
|
|
|
|
} catch (err) {
|
|
|
|
throw "Unable to process inputs to JSON, cannot recurse"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-29 19:53:21 +01:00
|
|
|
/**
|
|
|
|
* Creates a HBS template function for a given string, and optionally caches it.
|
|
|
|
*/
|
|
|
|
let templateCache = {}
|
2022-02-07 10:50:17 +01:00
|
|
|
function createTemplate(string, opts) {
|
|
|
|
opts = { ...defaultOpts, ...opts }
|
|
|
|
|
2022-01-29 19:53:21 +01:00
|
|
|
// Finalising adds a helper, can't do this with no helpers
|
2022-02-09 16:18:44 +01:00
|
|
|
const key = `${string}-${JSON.stringify(opts)}`
|
2022-01-29 19:53:21 +01:00
|
|
|
|
|
|
|
// Reuse the cached template is possible
|
2022-02-07 10:50:17 +01:00
|
|
|
if (opts.cacheTemplates && templateCache[key]) {
|
2022-01-29 19:53:21 +01:00
|
|
|
return templateCache[key]
|
|
|
|
}
|
|
|
|
|
2022-02-09 16:18:44 +01:00
|
|
|
string = processors.preprocess(string, opts)
|
2022-01-29 19:53:21 +01:00
|
|
|
|
2022-02-07 10:50:17 +01:00
|
|
|
// Optionally disable built in HBS escaping
|
|
|
|
if (opts.noEscaping) {
|
|
|
|
string = exports.disableEscaping(string)
|
|
|
|
}
|
|
|
|
|
2022-01-29 19:53:21 +01:00
|
|
|
// This does not throw an error when template can't be fulfilled,
|
|
|
|
// have to try correct beforehand
|
2022-02-07 10:50:17 +01:00
|
|
|
const instance = opts.noHelpers ? hbsInstanceNoHelpers : hbsInstance
|
2022-01-29 19:53:21 +01:00
|
|
|
const template = instance.compile(string, {
|
|
|
|
strict: false,
|
|
|
|
})
|
|
|
|
templateCache[key] = template
|
|
|
|
return template
|
|
|
|
}
|
|
|
|
|
2021-10-14 12:51:05 +02:00
|
|
|
/**
|
|
|
|
* Given an input object this will recurse through all props to try and update any handlebars statements within.
|
|
|
|
* @param {object|array} object The input structure which is to be recursed, it is important to note that
|
|
|
|
* if the structure contains any cycles then this will fail.
|
|
|
|
* @param {object} context The context that handlebars should fill data from.
|
2022-05-04 13:14:01 +02:00
|
|
|
* @param {object|undefined} [opts] optional - specify some options for processing.
|
2021-10-14 12:51:05 +02:00
|
|
|
* @returns {Promise<object|array>} The structure input, as fully updated as possible.
|
|
|
|
*/
|
2021-12-06 18:58:43 +01:00
|
|
|
module.exports.processObject = async (object, context, opts) => {
|
2021-10-14 12:51:05 +02:00
|
|
|
testObject(object)
|
|
|
|
for (let key of Object.keys(object || {})) {
|
|
|
|
if (object[key] != null) {
|
|
|
|
let val = object[key]
|
|
|
|
if (typeof val === "string") {
|
2021-10-26 21:04:36 +02:00
|
|
|
object[key] = await module.exports.processString(
|
|
|
|
object[key],
|
|
|
|
context,
|
|
|
|
opts
|
|
|
|
)
|
2021-10-14 12:51:05 +02:00
|
|
|
} else if (typeof val === "object") {
|
2021-10-26 21:04:36 +02:00
|
|
|
object[key] = await module.exports.processObject(
|
|
|
|
object[key],
|
|
|
|
context,
|
|
|
|
opts
|
|
|
|
)
|
2021-10-14 12:51:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return object
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This will process a single handlebars containing string. If the string passed in has no valid handlebars statements
|
|
|
|
* then nothing will occur.
|
|
|
|
* @param {string} string The template string which is the filled from the context object.
|
|
|
|
* @param {object} context An object of information which will be used to enrich the string.
|
2022-05-04 13:14:01 +02:00
|
|
|
* @param {object|undefined} [opts] optional - specify some options for processing.
|
2021-10-14 12:51:05 +02:00
|
|
|
* @returns {Promise<string>} The enriched string, all templates should have been replaced if they can be.
|
|
|
|
*/
|
2021-12-06 18:58:43 +01:00
|
|
|
module.exports.processString = async (string, context, opts) => {
|
2021-10-14 12:51:05 +02:00
|
|
|
// TODO: carry out any async calls before carrying out async call
|
2021-10-26 21:04:36 +02:00
|
|
|
return module.exports.processStringSync(string, context, opts)
|
2021-10-14 12:51:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given an input object this will recurse through all props to try and update any handlebars statements within. This is
|
|
|
|
* a pure sync call and therefore does not have the full functionality of the async call.
|
|
|
|
* @param {object|array} object The input structure which is to be recursed, it is important to note that
|
|
|
|
* if the structure contains any cycles then this will fail.
|
|
|
|
* @param {object} context The context that handlebars should fill data from.
|
2022-05-04 13:14:01 +02:00
|
|
|
* @param {object|undefined} [opts] optional - specify some options for processing.
|
2021-10-14 12:51:05 +02:00
|
|
|
* @returns {object|array} The structure input, as fully updated as possible.
|
|
|
|
*/
|
2021-12-06 18:58:43 +01:00
|
|
|
module.exports.processObjectSync = (object, context, opts) => {
|
2021-10-14 12:51:05 +02:00
|
|
|
testObject(object)
|
|
|
|
for (let key of Object.keys(object || {})) {
|
|
|
|
let val = object[key]
|
|
|
|
if (typeof val === "string") {
|
2021-10-26 21:04:36 +02:00
|
|
|
object[key] = module.exports.processStringSync(object[key], context, opts)
|
2021-10-14 12:51:05 +02:00
|
|
|
} else if (typeof val === "object") {
|
2021-10-26 21:04:36 +02:00
|
|
|
object[key] = module.exports.processObjectSync(object[key], context, opts)
|
2021-10-14 12:51:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return object
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This will process a single handlebars containing string. If the string passed in has no valid handlebars statements
|
|
|
|
* then nothing will occur. This is a pure sync call and therefore does not have the full functionality of the async call.
|
|
|
|
* @param {string} string The template string which is the filled from the context object.
|
|
|
|
* @param {object} context An object of information which will be used to enrich the string.
|
2022-05-04 13:14:01 +02:00
|
|
|
* @param {object|undefined} [opts] optional - specify some options for processing.
|
2021-10-14 12:51:05 +02:00
|
|
|
* @returns {string} The enriched string, all templates should have been replaced if they can be.
|
|
|
|
*/
|
2021-12-06 18:58:43 +01:00
|
|
|
module.exports.processStringSync = (string, context, opts) => {
|
2022-02-07 10:50:17 +01:00
|
|
|
// Take a copy of input in case of error
|
2021-10-14 12:51:05 +02:00
|
|
|
const input = string
|
|
|
|
if (typeof string !== "string") {
|
|
|
|
throw "Cannot process non-string types."
|
|
|
|
}
|
|
|
|
try {
|
2022-02-07 10:50:17 +01:00
|
|
|
const template = createTemplate(string, opts)
|
2022-01-20 20:37:01 +01:00
|
|
|
const now = Math.floor(Date.now() / 1000) * 1000
|
2021-10-14 12:51:05 +02:00
|
|
|
return processors.postprocess(
|
|
|
|
template({
|
2022-01-20 20:37:01 +01:00
|
|
|
now: new Date(now).toISOString(),
|
2022-02-07 18:56:01 +01:00
|
|
|
__opts: opts,
|
2021-10-14 12:51:05 +02:00
|
|
|
...context,
|
|
|
|
})
|
|
|
|
)
|
|
|
|
} catch (err) {
|
2021-12-06 18:58:43 +01:00
|
|
|
return input
|
2021-10-14 12:51:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-03 19:26:26 +01:00
|
|
|
/**
|
|
|
|
* By default with expressions like {{ name }} handlebars will escape various
|
|
|
|
* characters, which can be problematic. To fix this we use the syntax {{{ name }}},
|
|
|
|
* this function will find any double braces and switch to triple.
|
|
|
|
* @param string the string to have double HBS statements converted to triple.
|
|
|
|
*/
|
|
|
|
module.exports.disableEscaping = string => {
|
2022-02-15 15:48:32 +01:00
|
|
|
const matches = findDoubleHbsInstances(string)
|
2022-02-03 19:26:26 +01:00
|
|
|
if (matches == null) {
|
|
|
|
return string
|
|
|
|
}
|
2022-02-17 14:22:36 +01:00
|
|
|
|
|
|
|
// find the unique set
|
|
|
|
const unique = [...new Set(matches)]
|
|
|
|
for (let match of unique) {
|
|
|
|
// add a negative lookahead to exclude any already
|
|
|
|
const regex = new RegExp(`${match}(?!})`, "g")
|
|
|
|
string = string.replace(regex, `{${match}}`)
|
2022-02-03 19:26:26 +01:00
|
|
|
}
|
|
|
|
return string
|
|
|
|
}
|
|
|
|
|
2021-10-14 12:51:05 +02:00
|
|
|
/**
|
|
|
|
* Simple utility function which makes sure that a templating property has been wrapped in literal specifiers correctly.
|
|
|
|
* @param {string} property The property which is to be wrapped.
|
|
|
|
* @returns {string} The wrapped property ready to be added to a templating string.
|
|
|
|
*/
|
|
|
|
module.exports.makePropSafe = property => {
|
|
|
|
return `[${property}]`.replace("[[", "[").replace("]]", "]")
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks whether or not a template string contains totally valid syntax (simply tries running it)
|
|
|
|
* @param string The string to test for valid syntax - this may contain no templates and will be considered valid.
|
2022-05-04 13:14:01 +02:00
|
|
|
* @param [opts] optional - specify some options for processing.
|
2021-10-14 12:51:05 +02:00
|
|
|
* @returns {boolean} Whether or not the input string is valid.
|
|
|
|
*/
|
2021-12-06 18:58:43 +01:00
|
|
|
module.exports.isValid = (string, opts) => {
|
2021-10-14 12:51:05 +02:00
|
|
|
const validCases = [
|
|
|
|
"string",
|
|
|
|
"number",
|
|
|
|
"object",
|
|
|
|
"array",
|
|
|
|
"cannot read property",
|
|
|
|
"undefined",
|
2022-05-04 13:14:01 +02:00
|
|
|
"json at position 0",
|
2021-10-14 12:51:05 +02:00
|
|
|
]
|
|
|
|
// this is a portion of a specific string always output by handlebars in the case of a syntax error
|
|
|
|
const invalidCases = [`expecting '`]
|
|
|
|
// don't really need a real context to check if its valid
|
|
|
|
const context = {}
|
|
|
|
try {
|
2022-02-09 16:18:44 +01:00
|
|
|
const template = createTemplate(string, {
|
|
|
|
...opts,
|
|
|
|
noFinalise: true,
|
|
|
|
})
|
2022-01-29 19:53:21 +01:00
|
|
|
template(context)
|
2021-10-14 12:51:05 +02:00
|
|
|
return true
|
|
|
|
} catch (err) {
|
|
|
|
const msg = err && err.message ? err.message : err
|
|
|
|
if (!msg) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
const invalidCase = invalidCases.some(invalidCase =>
|
|
|
|
msg.toLowerCase().includes(invalidCase)
|
|
|
|
)
|
|
|
|
const validCase = validCases.some(validCase =>
|
|
|
|
msg.toLowerCase().includes(validCase)
|
|
|
|
)
|
|
|
|
// special case for maths functions - don't have inputs yet
|
|
|
|
return validCase && !invalidCase
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* We have generated a static manifest file from the helpers that this string templating package makes use of.
|
|
|
|
* This manifest provides information about each of the helpers and how it can be used.
|
|
|
|
* @returns The manifest JSON which has been generated from the helpers.
|
|
|
|
*/
|
|
|
|
module.exports.getManifest = () => {
|
|
|
|
return manifest
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if a HBS expression is a valid JS HBS expression
|
|
|
|
* @param handlebars the HBS expression to check
|
|
|
|
* @returns {boolean} whether the expression is JS or not
|
|
|
|
*/
|
|
|
|
module.exports.isJSBinding = handlebars => {
|
|
|
|
return module.exports.decodeJSBinding(handlebars) != null
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encodes a raw JS string as a JS HBS expression
|
|
|
|
* @param javascript the JS code to encode
|
|
|
|
* @returns {string} the JS HBS expression
|
|
|
|
*/
|
|
|
|
module.exports.encodeJSBinding = javascript => {
|
|
|
|
return `{{ js "${btoa(javascript)}" }}`
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Decodes a JS HBS expression to the raw JS code
|
|
|
|
* @param handlebars the JS HBS expression
|
|
|
|
* @returns {string|null} the raw JS code
|
|
|
|
*/
|
|
|
|
module.exports.decodeJSBinding = handlebars => {
|
|
|
|
if (!handlebars || typeof handlebars !== "string") {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
// JS is only valid if it is the only HBS expression
|
|
|
|
if (!handlebars.trim().startsWith("{{ js ")) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
const captureJSRegex = new RegExp(/{{ js "(.*)" }}/)
|
|
|
|
const match = handlebars.match(captureJSRegex)
|
|
|
|
if (!match || match.length < 2) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
return atob(match[1])
|
|
|
|
}
|
2022-01-21 17:24:24 +01:00
|
|
|
|
|
|
|
/**
|
2022-01-24 19:22:59 +01:00
|
|
|
* Same as the doesContainString function, but will check for all the strings
|
|
|
|
* before confirming it contains.
|
|
|
|
* @param {string} template The template string to search.
|
|
|
|
* @param {string[]} strings The strings to look for.
|
|
|
|
* @returns {boolean} Will return true if all strings found in HBS statement.
|
2022-01-21 17:24:24 +01:00
|
|
|
*/
|
2022-01-24 19:22:59 +01:00
|
|
|
module.exports.doesContainStrings = (template, strings) => {
|
2022-01-21 17:24:24 +01:00
|
|
|
let regexp = new RegExp(FIND_HBS_REGEX)
|
|
|
|
let matches = template.match(regexp)
|
|
|
|
if (matches == null) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for (let match of matches) {
|
|
|
|
let hbs = match
|
|
|
|
if (exports.isJSBinding(match)) {
|
|
|
|
hbs = exports.decodeJSBinding(match)
|
|
|
|
}
|
2022-01-24 19:22:59 +01:00
|
|
|
let allFound = true
|
|
|
|
for (let string of strings) {
|
|
|
|
if (!hbs.includes(string)) {
|
|
|
|
allFound = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (allFound) {
|
2022-01-21 17:24:24 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2022-01-24 19:22:59 +01:00
|
|
|
|
2022-03-02 18:40:50 +01:00
|
|
|
/**
|
|
|
|
* Given a string, this will return any {{ binding }} or {{{ binding }}} type
|
|
|
|
* statements.
|
|
|
|
* @param {string} string The string to search within.
|
|
|
|
* @return {string[]} The found HBS blocks.
|
|
|
|
*/
|
|
|
|
module.exports.findHBSBlocks = string => {
|
2022-10-21 11:32:32 +02:00
|
|
|
if (!string || typeof string !== "string") {
|
|
|
|
return []
|
|
|
|
}
|
2022-03-02 18:40:50 +01:00
|
|
|
let regexp = new RegExp(FIND_ANY_HBS_REGEX)
|
|
|
|
let matches = string.match(regexp)
|
|
|
|
if (matches == null) {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
return matches
|
|
|
|
}
|
|
|
|
|
2022-01-24 19:22:59 +01:00
|
|
|
/**
|
|
|
|
* This function looks in the supplied template for handlebars instances, if they contain
|
|
|
|
* JS the JS will be decoded and then the supplied string will be looked for. For example
|
|
|
|
* if the template "Hello, your name is {{ related }}" this function would return that true
|
|
|
|
* for the string "related" but not for "name" as it is not within the handlebars statement.
|
|
|
|
* @param {string} template A template string to search for handlebars instances.
|
|
|
|
* @param {string} string The word or sentence to search for.
|
|
|
|
* @returns {boolean} The this return true if the string is found, false if not.
|
|
|
|
*/
|
|
|
|
module.exports.doesContainString = (template, string) => {
|
|
|
|
return exports.doesContainStrings(template, [string])
|
|
|
|
}
|
2022-07-28 21:20:53 +02:00
|
|
|
|
|
|
|
module.exports.convertToJS = hbs => {
|
|
|
|
const blocks = exports.findHBSBlocks(hbs)
|
|
|
|
let js = "return `",
|
|
|
|
prevBlock = null
|
|
|
|
const variables = {}
|
|
|
|
if (blocks.length === 0) {
|
|
|
|
js += hbs
|
|
|
|
}
|
|
|
|
let count = 1
|
|
|
|
for (let block of blocks) {
|
|
|
|
let stringPart = hbs
|
|
|
|
if (prevBlock) {
|
|
|
|
stringPart = stringPart.split(prevBlock)[1]
|
|
|
|
}
|
|
|
|
stringPart = stringPart.split(block)[0]
|
|
|
|
prevBlock = block
|
|
|
|
const { variable, value } = convertHBSBlock(block, count++)
|
|
|
|
variables[variable] = value
|
|
|
|
js += `${stringPart.split()}\${${variable}}`
|
|
|
|
}
|
|
|
|
let varBlock = ""
|
|
|
|
for (let [variable, value] of Object.entries(variables)) {
|
|
|
|
varBlock += `const ${variable} = ${value};\n`
|
|
|
|
}
|
|
|
|
js += "`;"
|
|
|
|
return `${varBlock}${js}`
|
|
|
|
}
|