summaryrefslogtreecommitdiff
path: root/dev/lib/handlebars/src/handlebars.ts
diff options
context:
space:
mode:
authorDarius Jahandarie <djahandarie@gmail.com>2023-11-09 13:30:31 +0000
committerGitHub <noreply@github.com>2023-11-09 13:30:31 +0000
commit5c5a167b4792af379cdacf633513cebf20728cd2 (patch)
tree5b6be3620a557d0b9177047003f6d742d9d2a32d /dev/lib/handlebars/src/handlebars.ts
parentb64f51c3b13a46af4dd7f1e43048ac19c781ca7b (diff)
parent0f4d36938fd0d844f548aa5a7f7e7842df8dfb41 (diff)
Merge pull request #307 from themoeway/modernize
Modernize codebase
Diffstat (limited to 'dev/lib/handlebars/src/handlebars.ts')
-rw-r--r--dev/lib/handlebars/src/handlebars.ts47
1 files changed, 47 insertions, 0 deletions
diff --git a/dev/lib/handlebars/src/handlebars.ts b/dev/lib/handlebars/src/handlebars.ts
new file mode 100644
index 00000000..358d1b73
--- /dev/null
+++ b/dev/lib/handlebars/src/handlebars.ts
@@ -0,0 +1,47 @@
+/*
+ * Elasticsearch B.V licenses this file to you under the MIT License.
+ * See `packages/kbn-handlebars/LICENSE` for more information.
+ */
+
+// The handlebars module uses `export =`, so we should technically use `import Handlebars = require('handlebars')`, but Babel will not allow this:
+// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
+import Handlebars = require('handlebars');
+
+import type { CompileOptions, RuntimeOptions, TemplateDelegate } from './types';
+import { ElasticHandlebarsVisitor } from './visitor';
+
+const originalCreate = Handlebars.create;
+
+export { Handlebars };
+
+/**
+ * Creates an isolated Handlebars environment.
+ *
+ * Each environment has its own helpers.
+ * This is only necessary for use cases that demand distinct helpers.
+ * Most use cases can use the root Handlebars environment directly.
+ *
+ * @returns A sandboxed/scoped version of the @kbn/handlebars module
+ */
+Handlebars.create = function (): typeof Handlebars {
+ const SandboxedHandlebars = originalCreate.call(Handlebars) as typeof Handlebars;
+ // When creating new Handlebars environments, ensure the custom compileAST function is present in the new environment as well
+ SandboxedHandlebars.compileAST = Handlebars.compileAST;
+ return SandboxedHandlebars;
+};
+
+Handlebars.compileAST = function (
+ input: string | hbs.AST.Program,
+ options?: CompileOptions
+): TemplateDelegate {
+ if (input == null || (typeof input !== 'string' && input.type !== 'Program')) {
+ throw new Handlebars.Exception(
+ `You must pass a string or Handlebars AST to Handlebars.compileAST. You passed ${input}`
+ );
+ }
+
+ // If `Handlebars.compileAST` is reassigned, `this` will be undefined.
+ const visitor = new ElasticHandlebarsVisitor(this ?? Handlebars, input, options);
+
+ return (context: any, runtimeOptions?: RuntimeOptions) => visitor.render(context, runtimeOptions);
+};