feat(dynamic-secret): Minor improvements on usernameTemplate

This commit is contained in:
carlosmonastyrski
2025-06-06 14:34:32 -03:00
parent ac5bfbb6c9
commit 5406871c30
@@ -23,26 +23,13 @@ export const compileUsernameTemplate = ({
// Create isolated handlebars instance // Create isolated handlebars instance
const hbs = handlebars.create(); const hbs = handlebars.create();
// Pre-process template to replace {{random N}} patterns using RE2 // Register random helper on local instance
let processedTemplate = usernameTemplate; hbs.registerHelper("random", function (length: number) {
if (typeof length !== "number" || length <= 0 || length > 100) {
try { return "";
const randomPattern = new RE2("\\{\\{random (\\d+)\\}\\}", "g"); }
return alphaNumericNanoId(length);
// Use RE2's replace with callback function });
processedTemplate = randomPattern.replace(processedTemplate, (fullMatch: string, lengthStr: string) => {
const length = parseInt(lengthStr, 10);
if (length > 0 && length <= 100) {
return alphaNumericNanoId(length);
}
// Return original match if invalid length
return fullMatch;
});
} catch (error) {
logger.error(error, "RE2 pattern failed, using original template");
}
// Register replace helper on local instance // Register replace helper on local instance
hbs.registerHelper("replace", function (text: string, searchValue: string, replaceValue: string) { hbs.registerHelper("replace", function (text: string, searchValue: string, replaceValue: string) {
@@ -55,7 +42,7 @@ export const compileUsernameTemplate = ({
try { try {
const re2Pattern = new RE2(searchValue, "g"); const re2Pattern = new RE2(searchValue, "g");
// Replace all occurrences // Replace all occurrences
return textStr.replace(re2Pattern, replaceValue); return re2Pattern.replace(textStr, replaceValue);
} catch (error) { } catch (error) {
logger.error(error, "RE2 pattern failed, using original template"); logger.error(error, "RE2 pattern failed, using original template");
return textStr; return textStr;
@@ -83,7 +70,7 @@ export const compileUsernameTemplate = ({
} }
}; };
const result = hbs.compile(processedTemplate)(context); const result = hbs.compile(usernameTemplate)(context);
if (options?.toUpperCase) { if (options?.toUpperCase) {
return result.toUpperCase(); return result.toUpperCase();