/** * Insert markup before the document's closing or , ignoring * occurrences inside inline scripts, styles, or string literals. */ function maskHtmlLiteralRegions(html) { return String(html ?? '').replace(/]*>[\s\S]*?<\/script>/gi, (match) => ' '.repeat(match.length), ).replace(/]*>[\s\S]*?<\/style>/gi, (match) => ' '.repeat(match.length)); } export function injectBeforeDocumentClosingBody(html, markup) { const source = String(html ?? ''); const injection = String(markup ?? ''); if (!injection) return source; const masked = maskHtmlLiteralRegions(source).toLowerCase(); const lastIndex = masked.lastIndexOf(''); if (lastIndex < 0) return `${source}${injection}`; return `${source.slice(0, lastIndex)}${injection}${source.slice(lastIndex)}`; } export function injectBeforeDocumentClosingHead(html, markup) { const source = String(html ?? ''); const injection = String(markup ?? ''); if (!injection) return source; const masked = maskHtmlLiteralRegions(source).toLowerCase(); const index = masked.indexOf(''); if (index < 0) return `${injection}${source}`; return `${source.slice(0, index)}${injection}${source.slice(index)}`; }