@amplience/dc-cli
Version:
Dynamic Content CLI Tool
49 lines (48 loc) • 2.04 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteDeliveryContentItem = rewriteDeliveryContentItem;
function matchAll(regex, string) {
const result = [];
let match;
while ((match = regex.exec(string)) != null) {
result.push(match);
}
return result;
}
function rewriteDeliveryContentItem(webhookBody, account, stagingEnvironment) {
const tagRegexG = /\{\{\#withDeliveryContentItem(?<whitespace>\s+)(?<body>.+\=.+(\s+.+\=.+)*\s*)\}\}/g;
const keyValueRegex = /(?<key>.+?)\=(?<value>.+?)\s+/g;
const tagMatches = matchAll(tagRegexG, webhookBody);
let replaceOffset = 0;
for (const tag of tagMatches) {
const tGroups = tag.groups;
const matchIndex = tag.index;
const body = tGroups.body + ' ';
const bodyIndex = matchIndex + '{{#withDeliveryContentItem'.length + tGroups.whitespace.length;
const keyValueMatches = matchAll(keyValueRegex, body);
for (const pair of keyValueMatches) {
const pGroups = pair.groups;
const key = pGroups.key;
const keyIndex = bodyIndex + pair.index + replaceOffset;
const value = pGroups.value;
const valueIndex = keyIndex + key.length + 1;
let replaceValue = null;
switch (key) {
case 'account':
replaceValue = account;
break;
case 'stagingEnvironment':
if (stagingEnvironment !== undefined) {
replaceValue = stagingEnvironment;
}
break;
}
if (replaceValue != null) {
replaceValue = `"${replaceValue.replace(/\\/g, '\\\\').replace(/"/g, '"')}"`;
webhookBody = webhookBody.substr(0, valueIndex) + replaceValue + webhookBody.substr(valueIndex + value.length);
replaceOffset += replaceValue.length - value.length;
}
}
}
return webhookBody;
}