Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions actions/lib/validateHtml.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* Validates HTML syntax by checking for balanced opening and closing tags
* @param {string} html - The HTML string to validate
* @returns {Object} - { valid: boolean, reason: string }
*/
function validateHtml(html) {
if (typeof html !== 'string') {
return { valid: false, reason: 'Input must be a string' };
}

if (html.trim() === '') {
return { valid: true, reason: 'Empty string is valid' };
}

const stack = [];
const selfClosingTags = new Set([
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr'
]);

// Regular expression to match HTML tags
const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g;
let match;
let lineNumber = 1;
let charPosition = 0;

while ((match = tagRegex.exec(html)) !== null) {
const fullTag = match[0];
const tagName = match[1].toLowerCase();
const isClosingTag = fullTag.startsWith('</');
const isSelfClosing = fullTag.endsWith('/>') || selfClosingTags.has(tagName);

// Calculate position for error reporting
const beforeMatch = html.substring(0, match.index);
lineNumber = beforeMatch.split('\n').length;
charPosition = match.index - beforeMatch.lastIndexOf('\n') - 1;

if (isSelfClosing) {
// Self-closing tags don't need to be balanced
continue;
}

if (isClosingTag) {
// Check if we have a matching opening tag
if (stack.length === 0) {
return {
valid: false,
reason: `Unexpected closing tag </${tagName}> at line ${lineNumber}, position ${charPosition}`
};
}

const lastOpenTag = stack.pop();
if (lastOpenTag !== tagName) {
return {
valid: false,
reason: `Mismatched tags: expected </${lastOpenTag}> but found </${tagName}> at line ${lineNumber}, position ${charPosition}`
};
}
} else {
// Opening tag - push onto stack
stack.push(tagName);
}
}

// Check if any opening tags weren't closed
if (stack.length > 0) {
const unclosedTags = stack.reverse().join(', ');
return {
valid: false,
reason: `Unclosed tags: ${unclosedTags}`
};
}

return { valid: true, reason: 'HTML is valid' };
}

module.exports = { validateHtml }
17 changes: 15 additions & 2 deletions actions/pdp-renderer/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ const { findDescription, prepareBaseTemplate, getPrimaryImage, generatePriceStri
const { generateLdJson } = require('./ldJson');
const { requestSaaS, getProductUrl } = require('../utils');
const { ProductQuery, ProductByUrlKeyQuery } = require('../queries');
const { validateHtml } = require('../lib/validateHtml');

const productTemplateCache = {};

function toTemplateProductData(baseProduct) {
function toTemplateProductData(baseProduct, context) {
const templateProductData = { ...baseProduct };
const primaryImage = getPrimaryImage(baseProduct)?.url;

Expand All @@ -20,6 +21,18 @@ function toTemplateProductData(baseProduct) {
templateProductData.primaryImage = primaryImage;
templateProductData.metaTitle = baseProduct.metaTitle || baseProduct.name || 'Product Details';

const fieldValidations = {
metaDescription: validateHtml(templateProductData.metaDescription),
shortDescription: validateHtml(templateProductData.shortDescription),
description: validateHtml(templateProductData.description)
}

Object.entries(fieldValidations).forEach(([field, validation]) => {
if (!validation.valid) {
context.logger.warn(`Validation failed for "${field}" field: ${validation.reason}`);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this log sufficient to inform the user? Hopefully users do not have to experience what I did - tracing backwards from malformed UX through EDS CDN, Azure, and finally realizing it is the data itself that is the problem.

@duynguyen let me know if there's a better way to alert users to bad data.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the log message is good but it will potentially get lost among other logs.
IMO this should be tackled in a generic way, created #197

}
})

return templateProductData;
}

Expand Down Expand Up @@ -65,7 +78,7 @@ async function generateProductHtml(sku, urlKey, context) {
}

// Assign meta tag data for template
const templateProductData = toTemplateProductData(baseProduct);
const templateProductData = toTemplateProductData(baseProduct, context);

// Generate LD-JSON
const ldJson = await generateLdJson(baseProduct, context);
Expand Down
Loading