From 04d6828ef0495965a2bfbcda3a926534366d7921 Mon Sep 17 00:00:00 2001 From: Felipe Lalanne Date: Fri, 10 Jan 2025 13:51:38 -0300 Subject: [PATCH] Improve promised-handlebars types Change-type: patch --- lib/partials.ts | 8 +++----- typings/promised-handlebars.d.ts | 27 +++++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/partials.ts b/lib/partials.ts index 616bb8f..d9d3c3b 100644 --- a/lib/partials.ts +++ b/lib/partials.ts @@ -167,8 +167,8 @@ hb.registerHelper('import', async (options) => { const safeContent = new hb.SafeString( partialContent.slice(0, partialContent.length - 1), ); - const builtContent = await Promise.resolve( - hb.compile(safeContent.toString())(options.data.root), + const builtContent = await hb.compile(safeContent.toString())( + options.data.root, ); return new hb.SafeString(builtContent); } catch (err) { @@ -248,7 +248,5 @@ export const buildTemplate = async ( context.toJSON().children, ); - return stripExtraBlankLines( - await Promise.resolve(hb.compile(template)(data)), - ); + return stripExtraBlankLines(await hb.compile(template)(data)); }; diff --git a/typings/promised-handlebars.d.ts b/typings/promised-handlebars.d.ts index e2a100e..27f9cc1 100644 --- a/typings/promised-handlebars.d.ts +++ b/typings/promised-handlebars.d.ts @@ -1,6 +1,29 @@ declare module 'promised-handlebars' { - import type Handlebars from 'handlebars'; + import type HandlebarsNS from 'handlebars'; - const fn: (hb: typeof Handlebars) => typeof Handlebars; + // Extend the Handlebars type to include an async `compile` method + type Handlebars = typeof HandlebarsNS; + + // Convert the template delegate to async + // Note: this was tested with handlebars 4.7.8 + type HandlebarsTemplateDelegate = Handlebars.TemplateDelegate; + type HandlebarsTemplateDelegateArgs = Parameters< + HandlebarsTemplateDelegate + >; + type HandlebarsTemplateDelegateReturn = ReturnType< + HandlebarsTemplateDelegate + >; + type HandlebarsTemplateDelegateAsync = ( + ...args: HandlebarsTemplateDelegateArgs + ) => Promise>; + + // Create a new Handlebars interface with an updated compile function + type CompileArgs = Parameters; + interface HandlebarsAsync extends Handlebars { + compile: (...args: CompileArgs) => HandlebarsTemplateDelegateAsync; + } + + // Define the function exported by the module + const fn: (hb: Handlebars) => HandlebarsAsync; export = fn; }