forked from tsai/budibase
36 changed files with 5122 additions and 8593 deletions
@ -1,73 +0,0 @@ |
|||||
const handlebars = require("handlebars") |
|
||||
|
|
||||
handlebars.registerHelper("object", value => { |
|
||||
return new handlebars.SafeString(JSON.stringify(value)) |
|
||||
}) |
|
||||
|
|
||||
/** |
|
||||
* When running mustache statements to execute on the context of the automation it possible user's may input mustache |
|
||||
* in a few different forms, some of which are invalid but are logically valid. An example of this would be the mustache |
|
||||
* statement "{{steps[0].revision}}" here it is obvious the user is attempting to access an array or object using array |
|
||||
* like operators. These are not supported by Mustache and therefore the statement will fail. This function will clean up |
|
||||
* the mustache statement so it instead reads as "{{steps.0.revision}}" which is valid and will work. It may also be expanded |
|
||||
* to include any other mustache statement cleanup that has been deemed necessary for the system. |
|
||||
* |
|
||||
* @param {string} string The string which *may* contain mustache statements, it is OK if it does not contain any. |
|
||||
* @returns {string} The string that was input with cleaned up mustache statements as required. |
|
||||
*/ |
|
||||
function cleanMustache(string) { |
|
||||
let charToReplace = { |
|
||||
"[": ".", |
|
||||
"]": "", |
|
||||
} |
|
||||
let regex = new RegExp(/{{[^}}]*}}/g) |
|
||||
let matches = string.match(regex) |
|
||||
if (matches == null) { |
|
||||
return string |
|
||||
} |
|
||||
for (let match of matches) { |
|
||||
let baseIdx = string.indexOf(match) |
|
||||
for (let key of Object.keys(charToReplace)) { |
|
||||
let idxChar = match.indexOf(key) |
|
||||
if (idxChar !== -1) { |
|
||||
string = |
|
||||
string.slice(baseIdx, baseIdx + idxChar) + |
|
||||
charToReplace[key] + |
|
||||
string.slice(baseIdx + idxChar + 1) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
return string |
|
||||
} |
|
||||
|
|
||||
/** |
|
||||
* Given an input object this will recurse through all props to try and update |
|
||||
* any handlebars/mustache statements within. |
|
||||
* @param {object|array} inputs 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. |
|
||||
* @returns {object|array} The structure input, as fully updated as possible. |
|
||||
*/ |
|
||||
function recurseMustache(inputs, context) { |
|
||||
// JSON stringify will fail if there are any cycles, stops infinite recursion
|
|
||||
try { |
|
||||
JSON.stringify(inputs) |
|
||||
} catch (err) { |
|
||||
throw "Unable to process inputs to JSON, cannot recurse" |
|
||||
} |
|
||||
for (let key of Object.keys(inputs)) { |
|
||||
let val = inputs[key] |
|
||||
if (typeof val === "string") { |
|
||||
val = cleanMustache(inputs[key]) |
|
||||
const template = handlebars.compile(val) |
|
||||
inputs[key] = template(context) |
|
||||
} |
|
||||
// this covers objects and arrays
|
|
||||
else if (typeof val === "object") { |
|
||||
inputs[key] = recurseMustache(inputs[key], context) |
|
||||
} |
|
||||
} |
|
||||
return inputs |
|
||||
} |
|
||||
|
|
||||
exports.recurseMustache = recurseMustache |
|
||||
File diff suppressed because it is too large
@ -0,0 +1,12 @@ |
|||||
|
{ |
||||
|
"globals": { |
||||
|
"emit": true, |
||||
|
"key": true |
||||
|
}, |
||||
|
"env": { |
||||
|
"node": true |
||||
|
}, |
||||
|
"extends": ["eslint:recommended"], |
||||
|
"rules": { |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,2 @@ |
|||||
|
dist/ |
||||
|
node_modules/ |
||||
@ -0,0 +1,194 @@ |
|||||
|
/* |
||||
|
* For a detailed explanation regarding each configuration property, visit: |
||||
|
* https://jestjs.io/docs/en/configuration.html
|
||||
|
*/ |
||||
|
|
||||
|
module.exports = { |
||||
|
// All imported modules in your tests should be mocked automatically
|
||||
|
// automock: false,
|
||||
|
|
||||
|
// Stop running tests after `n` failures
|
||||
|
// bail: 0,
|
||||
|
|
||||
|
// The directory where Jest should store its cached dependency information
|
||||
|
// cacheDirectory: "/tmp/jest_rs",
|
||||
|
|
||||
|
// Automatically clear mock calls and instances between every test
|
||||
|
clearMocks: true, |
||||
|
|
||||
|
// Indicates whether the coverage information should be collected while executing the test
|
||||
|
// collectCoverage: false,
|
||||
|
|
||||
|
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
||||
|
// collectCoverageFrom: undefined,
|
||||
|
|
||||
|
// The directory where Jest should output its coverage files
|
||||
|
coverageDirectory: "coverage", |
||||
|
|
||||
|
// An array of regexp pattern strings used to skip coverage collection
|
||||
|
// coveragePathIgnorePatterns: [
|
||||
|
// "/node_modules/"
|
||||
|
// ],
|
||||
|
|
||||
|
// Indicates which provider should be used to instrument code for coverage
|
||||
|
coverageProvider: "v8", |
||||
|
|
||||
|
// A list of reporter names that Jest uses when writing coverage reports
|
||||
|
// coverageReporters: [
|
||||
|
// "json",
|
||||
|
// "text",
|
||||
|
// "lcov",
|
||||
|
// "clover"
|
||||
|
// ],
|
||||
|
|
||||
|
// An object that configures minimum threshold enforcement for coverage results
|
||||
|
// coverageThreshold: undefined,
|
||||
|
|
||||
|
// A path to a custom dependency extractor
|
||||
|
// dependencyExtractor: undefined,
|
||||
|
|
||||
|
// Make calling deprecated APIs throw helpful error messages
|
||||
|
// errorOnDeprecated: false,
|
||||
|
|
||||
|
// Force coverage collection from ignored files using an array of glob patterns
|
||||
|
// forceCoverageMatch: [],
|
||||
|
|
||||
|
// A path to a module which exports an async function that is triggered once before all test suites
|
||||
|
// globalSetup: undefined,
|
||||
|
|
||||
|
// A path to a module which exports an async function that is triggered once after all test suites
|
||||
|
// globalTeardown: undefined,
|
||||
|
|
||||
|
// A set of global variables that need to be available in all test environments
|
||||
|
// globals: {},
|
||||
|
|
||||
|
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
||||
|
// maxWorkers: "50%",
|
||||
|
|
||||
|
// An array of directory names to be searched recursively up from the requiring module's location
|
||||
|
// moduleDirectories: [
|
||||
|
// "node_modules"
|
||||
|
// ],
|
||||
|
|
||||
|
// An array of file extensions your modules use
|
||||
|
// moduleFileExtensions: [
|
||||
|
// "js",
|
||||
|
// "json",
|
||||
|
// "jsx",
|
||||
|
// "ts",
|
||||
|
// "tsx",
|
||||
|
// "node"
|
||||
|
// ],
|
||||
|
|
||||
|
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
||||
|
// moduleNameMapper: {},
|
||||
|
|
||||
|
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
||||
|
// modulePathIgnorePatterns: [],
|
||||
|
|
||||
|
// Activates notifications for test results
|
||||
|
// notify: false,
|
||||
|
|
||||
|
// An enum that specifies notification mode. Requires { notify: true }
|
||||
|
// notifyMode: "failure-change",
|
||||
|
|
||||
|
// A preset that is used as a base for Jest's configuration
|
||||
|
// preset: undefined,
|
||||
|
|
||||
|
// Run tests from one or more projects
|
||||
|
// projects: undefined,
|
||||
|
|
||||
|
// Use this configuration option to add custom reporters to Jest
|
||||
|
// reporters: undefined,
|
||||
|
|
||||
|
// Automatically reset mock state between every test
|
||||
|
// resetMocks: false,
|
||||
|
|
||||
|
// Reset the module registry before running each individual test
|
||||
|
// resetModules: false,
|
||||
|
|
||||
|
// A path to a custom resolver
|
||||
|
// resolver: undefined,
|
||||
|
|
||||
|
// Automatically restore mock state between every test
|
||||
|
// restoreMocks: false,
|
||||
|
|
||||
|
// The root directory that Jest should scan for tests and modules within
|
||||
|
// rootDir: undefined,
|
||||
|
|
||||
|
// A list of paths to directories that Jest should use to search for files in
|
||||
|
// roots: [
|
||||
|
// "<rootDir>"
|
||||
|
// ],
|
||||
|
|
||||
|
// Allows you to use a custom runner instead of Jest's default test runner
|
||||
|
// runner: "jest-runner",
|
||||
|
|
||||
|
// The paths to modules that run some code to configure or set up the testing environment before each test
|
||||
|
// setupFiles: [],
|
||||
|
|
||||
|
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
||||
|
// setupFilesAfterEnv: [],
|
||||
|
|
||||
|
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
||||
|
// slowTestThreshold: 5,
|
||||
|
|
||||
|
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
||||
|
// snapshotSerializers: [],
|
||||
|
|
||||
|
// The test environment that will be used for testing
|
||||
|
testEnvironment: "node", |
||||
|
|
||||
|
// Options that will be passed to the testEnvironment
|
||||
|
// testEnvironmentOptions: {},
|
||||
|
|
||||
|
// Adds a location field to test results
|
||||
|
// testLocationInResults: false,
|
||||
|
|
||||
|
// The glob patterns Jest uses to detect test files
|
||||
|
// testMatch: [
|
||||
|
// "**/__tests__/**/*.[jt]s?(x)",
|
||||
|
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
||||
|
// ],
|
||||
|
|
||||
|
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
||||
|
// testPathIgnorePatterns: [
|
||||
|
// "/node_modules/"
|
||||
|
// ],
|
||||
|
|
||||
|
// The regexp pattern or array of patterns that Jest uses to detect test files
|
||||
|
// testRegex: [],
|
||||
|
|
||||
|
// This option allows the use of a custom results processor
|
||||
|
// testResultsProcessor: undefined,
|
||||
|
|
||||
|
// This option allows use of a custom test runner
|
||||
|
// testRunner: "jasmine2",
|
||||
|
|
||||
|
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
|
||||
|
// testURL: "http://localhost",
|
||||
|
|
||||
|
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
|
||||
|
// timers: "real",
|
||||
|
|
||||
|
// A map from regular expressions to paths to transformers
|
||||
|
// transform: undefined,
|
||||
|
|
||||
|
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
||||
|
// transformIgnorePatterns: [
|
||||
|
// "/node_modules/",
|
||||
|
// "\\.pnp\\.[^\\/]+$"
|
||||
|
// ],
|
||||
|
|
||||
|
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
||||
|
// unmockedModulePathPatterns: undefined,
|
||||
|
|
||||
|
// Indicates whether each individual test should be reported during the run
|
||||
|
// verbose: undefined,
|
||||
|
|
||||
|
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
||||
|
// watchPathIgnorePatterns: [],
|
||||
|
|
||||
|
// Whether to use watchman for file crawling
|
||||
|
// watchman: true,
|
||||
|
}; |
||||
@ -0,0 +1,26 @@ |
|||||
|
{ |
||||
|
"name": "@budibase/string-templates", |
||||
|
"version": "0.5.3", |
||||
|
"description": "Handlebars wrapper for Budibase templating.", |
||||
|
"main": "dist/bundle.js", |
||||
|
"module": "dist/bundle.js", |
||||
|
"license": "AGPL-3.0", |
||||
|
"types": "dist/index.d.ts", |
||||
|
"scripts": { |
||||
|
"build": "rollup -c", |
||||
|
"dev:builder": "tsc && rollup -cw", |
||||
|
"test": "jest" |
||||
|
}, |
||||
|
"dependencies": { |
||||
|
"handlebars": "^4.7.6" |
||||
|
}, |
||||
|
"devDependencies": { |
||||
|
"rollup": "^2.36.2", |
||||
|
"rollup-plugin-commonjs": "^10.1.0", |
||||
|
"rollup-plugin-node-builtins": "^2.1.2", |
||||
|
"rollup-plugin-node-globals": "^1.4.0", |
||||
|
"rollup-plugin-node-resolve": "^5.2.0", |
||||
|
"typescript": "^4.1.3", |
||||
|
"jest": "^26.6.3" |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,24 @@ |
|||||
|
import commonjs from "rollup-plugin-commonjs" |
||||
|
import nodeResolve from "rollup-plugin-node-resolve" |
||||
|
import globals from "rollup-plugin-node-globals" |
||||
|
import builtins from "rollup-plugin-node-builtins" |
||||
|
|
||||
|
export default { |
||||
|
input: "src/index.js", |
||||
|
output: { |
||||
|
file: "dist/bundle.js", |
||||
|
format: "umd", |
||||
|
name: "string-templates", |
||||
|
exports: "named", |
||||
|
globals: { |
||||
|
"fs": "fs", |
||||
|
}, |
||||
|
}, |
||||
|
external: ["fs"], |
||||
|
plugins: [ |
||||
|
nodeResolve({ preferBuiltins: false }), |
||||
|
commonjs(), |
||||
|
globals(), |
||||
|
builtins(), |
||||
|
], |
||||
|
} |
||||
@ -0,0 +1,91 @@ |
|||||
|
const { HelperFunctions } = require("./helpers/index") |
||||
|
|
||||
|
const HBS_CLEANING_REGEX = /{{[^}}]*}}/g |
||||
|
const ALPHA_NUMERIC_REGEX = /^[A-Za-z0-9]+$/g |
||||
|
|
||||
|
function isAlphaNumeric(char) { |
||||
|
return char.match(ALPHA_NUMERIC_REGEX) |
||||
|
} |
||||
|
|
||||
|
function swapStrings(string, start, length, swap) { |
||||
|
return string.slice(0, start) + swap + string.slice(start + length) |
||||
|
} |
||||
|
|
||||
|
function handleCleaner(string, match, fn) { |
||||
|
const output = fn(match) |
||||
|
const idx = string.indexOf(match) |
||||
|
return swapStrings(string, idx, match.length, output) |
||||
|
} |
||||
|
|
||||
|
function swapToDotNotation(statement) { |
||||
|
let startBraceIdx = statement.indexOf("[") |
||||
|
let lastIdx = 0 |
||||
|
while (startBraceIdx !== -1) { |
||||
|
// if the character previous to the literal specifier is alpha-numeric this should happen
|
||||
|
if (isAlphaNumeric(statement.charAt(startBraceIdx - 1))) { |
||||
|
statement = swapStrings(statement, startBraceIdx + lastIdx, 1, ".[") |
||||
|
} |
||||
|
lastIdx = startBraceIdx + 1 |
||||
|
startBraceIdx = statement.substring(lastIdx + 1).indexOf("[") |
||||
|
} |
||||
|
return statement |
||||
|
} |
||||
|
|
||||
|
function handleSpacesInProperties(statement) { |
||||
|
// exclude helpers and brackets, regex will only find double brackets
|
||||
|
const exclusions = HelperFunctions.concat(["{{", "}}"]) |
||||
|
// find all the parts split by spaces
|
||||
|
const splitBySpaces = statement.split(" ") |
||||
|
// remove the excluded elements
|
||||
|
const propertyParts = splitBySpaces.filter(part => exclusions.indexOf(part) === -1) |
||||
|
// rebuild to get the full property
|
||||
|
const fullProperty = propertyParts.join(" ") |
||||
|
// now work out the dot notation layers and split them up
|
||||
|
const propertyLayers = fullProperty.split(".") |
||||
|
// find the layers which need to be wrapped and wrap them
|
||||
|
for (let layer of propertyLayers) { |
||||
|
if (layer.indexOf(" ") !== -1) { |
||||
|
statement = swapStrings(statement, statement.indexOf(layer), layer.length, `[${layer}]`) |
||||
|
} |
||||
|
} |
||||
|
// remove the edge case of double brackets being entered (in-case user already has specified)
|
||||
|
return statement.replace(/\[\[/g, "[").replace(/]]/g, "]") |
||||
|
} |
||||
|
|
||||
|
function finalise(statement) { |
||||
|
let insideStatement = statement.slice(2, statement.length - 2) |
||||
|
if (insideStatement.charAt(0) === " ") { |
||||
|
insideStatement = insideStatement.slice(1) |
||||
|
} |
||||
|
if (insideStatement.charAt(insideStatement.length - 1) === " ") { |
||||
|
insideStatement = insideStatement.slice(0, insideStatement.length - 1) |
||||
|
} |
||||
|
return `{{ all (${insideStatement}) }}` |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* When running handlebars statements to execute on the context of the automation it possible user's may input handlebars |
||||
|
* in a few different forms, some of which are invalid but are logically valid. An example of this would be the handlebars |
||||
|
* statement "{{steps[0].revision}}" here it is obvious the user is attempting to access an array or object using array |
||||
|
* like operators. These are not supported by handlebars and therefore the statement will fail. This function will clean up |
||||
|
* the handlebars statement so it instead reads as "{{steps.0.revision}}" which is valid and will work. It may also be expanded |
||||
|
* to include any other handlebars statement cleanup that has been deemed necessary for the system. |
||||
|
* |
||||
|
* @param {string} string The string which *may* contain handlebars statements, it is OK if it does not contain any. |
||||
|
* @returns {string} The string that was input with cleaned up handlebars statements as required. |
||||
|
*/ |
||||
|
module.exports.cleanHandlebars = (string) => { |
||||
|
let cleaners = [swapToDotNotation, handleSpacesInProperties, finalise] |
||||
|
for (let cleaner of cleaners) { |
||||
|
// re-run search each time incase previous cleaner update/removed a match
|
||||
|
let regex = new RegExp(HBS_CLEANING_REGEX) |
||||
|
let matches = string.match(regex) |
||||
|
if (matches == null) { |
||||
|
continue |
||||
|
} |
||||
|
for (let match of matches) { |
||||
|
string = handleCleaner(string, match, cleaner) |
||||
|
} |
||||
|
} |
||||
|
return string |
||||
|
} |
||||
@ -0,0 +1,19 @@ |
|||||
|
class Helper { |
||||
|
constructor(name, fn) { |
||||
|
this.name = name |
||||
|
this.fn = fn |
||||
|
} |
||||
|
|
||||
|
register(handlebars) { |
||||
|
// wrap the function so that no helper can cause handlebars to break
|
||||
|
handlebars.registerHelper(this.name, value => { |
||||
|
return this.fn(value) || value |
||||
|
}) |
||||
|
} |
||||
|
|
||||
|
unregister(handlebars) { |
||||
|
handlebars.unregisterHelper(this.name) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
module.exports = Helper |
||||
@ -0,0 +1,52 @@ |
|||||
|
const Helper = require("./Helper") |
||||
|
const { SafeString } = require("handlebars") |
||||
|
|
||||
|
const HTML_SWAPS = { |
||||
|
"<": "<", |
||||
|
">": ">", |
||||
|
} |
||||
|
|
||||
|
const HelperFunctionBuiltin = [ |
||||
|
"#if", |
||||
|
"#unless", |
||||
|
"#each", |
||||
|
"#with", |
||||
|
"lookup", |
||||
|
"log" |
||||
|
] |
||||
|
|
||||
|
const HelperFunctionNames = { |
||||
|
OBJECT: "object", |
||||
|
ALL: "all", |
||||
|
} |
||||
|
|
||||
|
const HELPERS = [ |
||||
|
// external helpers
|
||||
|
new Helper(HelperFunctionNames.OBJECT, value => { |
||||
|
return new SafeString(JSON.stringify(value)) |
||||
|
}), |
||||
|
// this help is applied to all statements
|
||||
|
new Helper(HelperFunctionNames.ALL, value => { |
||||
|
let text = new SafeString(unescape(value).replace(/&/g, '&')) |
||||
|
if (text == null || typeof text !== "string") { |
||||
|
return text |
||||
|
} |
||||
|
return text.replace(/[<>]/g, tag => { |
||||
|
return HTML_SWAPS[tag] || tag |
||||
|
}) |
||||
|
}) |
||||
|
] |
||||
|
|
||||
|
module.exports.HelperFunctions = Object.values(HelperFunctionNames).concat(HelperFunctionBuiltin) |
||||
|
|
||||
|
module.exports.registerAll = handlebars => { |
||||
|
for (let helper of HELPERS) { |
||||
|
helper.register(handlebars) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
module.exports.unregisterAll = handlebars => { |
||||
|
for (let helper of HELPERS) { |
||||
|
helper.unregister(handlebars) |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,102 @@ |
|||||
|
const handlebars = require("handlebars") |
||||
|
const { registerAll } = require("./helpers/index") |
||||
|
const { cleanHandlebars } = require("./cleaning") |
||||
|
|
||||
|
const hbsInstance = handlebars.create() |
||||
|
registerAll(hbsInstance) |
||||
|
|
||||
|
/** |
||||
|
* utility function to check if the object is valid |
||||
|
*/ |
||||
|
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" |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 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. |
||||
|
* @returns {Promise<object|array>} The structure input, as fully updated as possible. |
||||
|
*/ |
||||
|
module.exports.processObject = async (object, context) => { |
||||
|
testObject(object) |
||||
|
for (let key of Object.keys(object)) { |
||||
|
let val = object[key] |
||||
|
if (typeof val === "string") { |
||||
|
object[key] = await module.exports.processString(object[key], context) |
||||
|
} else if (typeof val === "object") { |
||||
|
object[key] = await module.exports.processObject(object[key], context) |
||||
|
} |
||||
|
} |
||||
|
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. |
||||
|
* @returns {Promise<string>} The enriched string, all templates should have been replaced if they can be. |
||||
|
*/ |
||||
|
module.exports.processString = async (string, context) => { |
||||
|
// TODO: carry out any async calls before carrying out async call
|
||||
|
return module.exports.processStringSync(string, context) |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 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. |
||||
|
* @returns {object|array} The structure input, as fully updated as possible. |
||||
|
*/ |
||||
|
module.exports.processObjectSync = (object, context) => { |
||||
|
testObject(object) |
||||
|
for (let key of Object.keys(object)) { |
||||
|
let val = object[key] |
||||
|
if (typeof val === "string") { |
||||
|
object[key] = module.exports.processStringSync(object[key], context) |
||||
|
} else if (typeof val === "object") { |
||||
|
object[key] = module.exports.processObjectSync(object[key], context) |
||||
|
} |
||||
|
} |
||||
|
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. |
||||
|
* @returns {string} The enriched string, all templates should have been replaced if they can be. |
||||
|
*/ |
||||
|
module.exports.processStringSync = (string, context) => { |
||||
|
if (typeof string !== "string") { |
||||
|
throw "Cannot process non-string types." |
||||
|
} |
||||
|
console.log(string) |
||||
|
console.log(context) |
||||
|
let template |
||||
|
string = cleanHandlebars(string) |
||||
|
console.log(string) |
||||
|
// this does not throw an error when template can't be fulfilled, have to try correct beforehand
|
||||
|
template = hbsInstance.compile(string) |
||||
|
return template(context) |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Errors can occur if a user of this library attempts to use a helper that has not been added to the system, these errors |
||||
|
* can be captured to alert the user of the mistake. |
||||
|
* @param {function} handler a function which will be called every time an error occurs when processing a handlebars |
||||
|
* statement. |
||||
|
*/ |
||||
|
module.exports.errorEvents = handler => { |
||||
|
hbsInstance.registerHelper("helperMissing", handler) |
||||
|
} |
||||
@ -0,0 +1,69 @@ |
|||||
|
const { |
||||
|
processObject, |
||||
|
processString, |
||||
|
} = require("../src/index") |
||||
|
|
||||
|
describe("Test that the string processing works correctly", () => { |
||||
|
it("should process a basic template string", async () => { |
||||
|
const output = await processString("templating is {{ adjective }}", { |
||||
|
adjective: "easy" |
||||
|
}) |
||||
|
expect(output).toBe("templating is easy") |
||||
|
}) |
||||
|
|
||||
|
it("should fail gracefully when wrong type passed in", async () => { |
||||
|
let error = null |
||||
|
try { |
||||
|
await processString(null, null) |
||||
|
} catch (err) { |
||||
|
error = err |
||||
|
} |
||||
|
expect(error).not.toBeNull() |
||||
|
}) |
||||
|
}) |
||||
|
|
||||
|
describe("Test that the object processing works correctly", () => { |
||||
|
it("should be able to process an object with some template strings", async () => { |
||||
|
const output = await processObject({ |
||||
|
first: "thing is {{ adjective }}", |
||||
|
second: "thing is bad", |
||||
|
third: "we are {{ adjective }} {{ noun }}", |
||||
|
}, { |
||||
|
adjective: "easy", |
||||
|
noun: "people", |
||||
|
}) |
||||
|
expect(output.first).toBe("thing is easy") |
||||
|
expect(output.second).toBe("thing is bad") |
||||
|
expect(output.third).toBe("we are easy people") |
||||
|
}) |
||||
|
|
||||
|
it("should be able to handle arrays of string templates", async () => { |
||||
|
const output = await processObject(["first {{ noun }}", "second {{ noun }}"], { |
||||
|
noun: "person" |
||||
|
}) |
||||
|
expect(output[0]).toBe("first person") |
||||
|
expect(output[1]).toBe("second person") |
||||
|
}) |
||||
|
|
||||
|
it("should fail gracefully when object passed in has cycles", async () => { |
||||
|
let error = null |
||||
|
try { |
||||
|
const innerObj = { a: "thing {{ a }}" } |
||||
|
innerObj.b = innerObj |
||||
|
await processObject(innerObj, { a: 1 }) |
||||
|
} catch (err) { |
||||
|
error = err |
||||
|
} |
||||
|
expect(error).not.toBeNull() |
||||
|
}) |
||||
|
|
||||
|
it("should fail gracefully when wrong type is passed in", async () => { |
||||
|
let error = null |
||||
|
try { |
||||
|
await processObject(null, null) |
||||
|
} catch (err) { |
||||
|
error = err |
||||
|
} |
||||
|
expect(error).not.toBeNull() |
||||
|
}) |
||||
|
}) |
||||
@ -0,0 +1,35 @@ |
|||||
|
const { |
||||
|
processString, |
||||
|
} = require("../src/index") |
||||
|
|
||||
|
describe("Handling context properties with spaces in their name", () => { |
||||
|
it("should allow through literal specifiers", async () => { |
||||
|
const output = await processString("test {{ [test thing] }}", { |
||||
|
"test thing": 1 |
||||
|
}) |
||||
|
expect(output).toBe("test 1") |
||||
|
}) |
||||
|
|
||||
|
it("should convert to dot notation where required", async () => { |
||||
|
const output = await processString("test {{ test[0] }}", { |
||||
|
test: [2] |
||||
|
}) |
||||
|
expect(output).toBe("test 2") |
||||
|
}) |
||||
|
|
||||
|
it("should be able to handle a property with a space in its name", async () => { |
||||
|
const output = await processString("hello my name is {{ person name }}", { |
||||
|
"person name": "Mike", |
||||
|
}) |
||||
|
expect(output).toBe("hello my name is Mike") |
||||
|
}) |
||||
|
|
||||
|
it("should be able to handle an object with layers that requires escaping", async () => { |
||||
|
const output = await processString("testcase {{ testing.test case }}", { |
||||
|
testing: { |
||||
|
"test case": 1 |
||||
|
} |
||||
|
}) |
||||
|
expect(output).toBe("testcase 1") |
||||
|
}) |
||||
|
}) |
||||
@ -0,0 +1,12 @@ |
|||||
|
const { |
||||
|
processString, |
||||
|
} = require("../src/index") |
||||
|
|
||||
|
describe("test the custom helpers we have applied", () => { |
||||
|
it("should be able to use the object helper", async () => { |
||||
|
const output = await processString("object is {{ object obj }}", { |
||||
|
obj: { a: 1 }, |
||||
|
}) |
||||
|
expect(output).toBe("object is {\"a\":1}") |
||||
|
}) |
||||
|
}) |
||||
@ -0,0 +1,10 @@ |
|||||
|
{ |
||||
|
"include": ["src/**/*"], |
||||
|
|
||||
|
"compilerOptions": { |
||||
|
"allowJs": true, |
||||
|
"declaration": true, |
||||
|
"emitDeclarationOnly": true, |
||||
|
"outDir": "dist" |
||||
|
} |
||||
|
} |
||||
File diff suppressed because it is too large
@ -0,0 +1,12 @@ |
|||||
|
{ |
||||
|
"globals": { |
||||
|
"emit": true, |
||||
|
"key": true |
||||
|
}, |
||||
|
"env": { |
||||
|
"node": true |
||||
|
}, |
||||
|
"extends": ["eslint:recommended"], |
||||
|
"rules": { |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue