@magelens/magento-template-coverage 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/report.js ADDED
@@ -0,0 +1,113 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { createHash } = require('node:crypto');
10
+ const escape = value => String(value).replace(/[&<>"']/g, char => ({
11
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
12
+ })[char]);
13
+ const metric = value => `${value.covered}/${value.total} (${value.percent === null ? 'N/A' : `${value.percent.toFixed(2)}%`})`;
14
+ const semantics = 'Executable lines are starting source lines of measured template expressions: Knockout binding value accessors, Underscore expressions/evaluation code, jQuery directives, Magento template literals, Alpine directive evaluations and inline JavaScript statements. Script functions and branch alternatives have separate counters. PHP execution inside PHTML is a separate metric. A binding hit does not prove its event handler ran or its condition was true. Static markup and continuation lines have no execution denominator. DOM presence is measured separately.';
15
+ const page = (title, body) => `<!doctype html>
16
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
17
+ <title>${escape(title)}</title><style>
18
+ body{font:15px system-ui;margin:24px;color:#17202a}table{border-collapse:collapse;width:100%}td,th{padding:9px;border:1px solid #dfe3e6;text-align:left}th{background:#f6f8fa}a{color:#075e67;text-underline-offset:2px}a:focus-visible{outline:3px solid #075e67}td:first-child{overflow-wrap:anywhere}.covered,.observed,.high{background:#e0f1d7}.uncovered,.unobserved,.low{background:#f8dddd}.partial,.medium{background:#fff5cd}.unsupported,.neutral{color:#59636c}input{padding:8px;min-width:260px}p{max-width:1200px;line-height:1.6}.source{font:13px ui-monospace,monospace}.source td{padding:3px 10px}.source .code{white-space:pre;min-width:600px}.source .number{width:55px}.source .hits{width:80px;text-align:right}.scroll{overflow-x:auto}h1{overflow-wrap:anywhere;font-size:26px}nav{padding:14px;background:#edf0f3;border-radius:5px;line-height:1.7;overflow-wrap:anywhere}.metric{min-width:175px;font-variant-numeric:tabular-nums}.bar{display:inline-block;width:75px;height:12px;background:#e9ecef;border-radius:3px;margin-right:10px;overflow:hidden}.bar span{display:block;height:100%;background:#29a34a}.low .bar span{background:#dc3545}.medium .bar span{background:#ffc107}.total{font-weight:600}.legend{margin-top:28px;border-top:1px solid #ddd;padding-top:18px}.legend span{padding:3px 6px}.muted{font-size:13px;color:#59636c}tfoot{font-weight:600}
19
+ </style></head><body>${body}</body></html>\n`;
20
+
21
+ const aggregate = (entries, key) => {
22
+ const total = entries.reduce((sum, entry) => sum + entry[key].total, 0);
23
+ const covered = entries.reduce((sum, entry) => sum + entry[key].covered, 0);
24
+ return { total, covered, uncovered: total - covered, percent: total ? Math.round(covered / total * 10000) / 100 : null };
25
+ };
26
+ const totals = entries => {
27
+ const eligible = entries.filter(entry => entry.instrumented);
28
+ const covered = eligible.filter(entry => entry.status === 'observed').length;
29
+ return {
30
+ lines: aggregate(entries, 'lineSummary'), statements: aggregate(entries, 'statementSummary'),
31
+ functions: aggregate(entries, 'functionSummary'), branches: aggregate(entries, 'branchSummary'),
32
+ dom: { total: eligible.length, covered, percent: eligible.length ? Math.round(covered / eligible.length * 10000) / 100 : null },
33
+ unsupported: entries.length - eligible.length
34
+ };
35
+ };
36
+ const directoryFile = directory => directory ? `directories/${createHash('sha256').update(directory).digest('hex').slice(0, 32)}.html` : 'index.html';
37
+ const href = (from, to) => path.posix.relative(path.posix.dirname(from), to).split('/').map(encodeURIComponent).join('/');
38
+ const cell = value => {
39
+ const level = value.percent === null ? 'neutral' : value.percent < 50 ? 'low' : value.percent < 90 ? 'medium' : 'high';
40
+ return `<td class="metric ${level}"><span class="bar" aria-hidden="true"><span style="width:${value.percent || 0}%"></span></span>${metric(value)}</td>`;
41
+ };
42
+ const legend = '<p class="legend"><strong>Legend</strong> · <span class="low">Low: below 50%</span> <span class="medium">Medium: 50–90%</span> <span class="high">High: 90–100%</span> · N/A: no measured statements</p>';
43
+
44
+ function writeReport(report, output) {
45
+ fs.mkdirSync(path.join(output, 'files'), { recursive: true });
46
+ fs.mkdirSync(path.join(output, 'directories'), { recursive: true });
47
+ const directories = new Map([['', []]]);
48
+ for (const entry of report.templates) {
49
+ const parts = entry.path.split('/');
50
+ for (let index = 0; index < parts.length; index++) {
51
+ const directory = parts.slice(0, index).join('/');
52
+ if (!directories.has(directory)) directories.set(directory, []);
53
+ directories.get(directory).push(entry);
54
+ }
55
+ }
56
+ const breadcrumbs = (file, directory, basename) => {
57
+ let cumulative = '';
58
+ const links = [`<a href="${href(file, 'index.html')}">All templates</a>`];
59
+ for (const part of directory.split('/').filter(Boolean)) {
60
+ cumulative += (cumulative ? '/' : '') + part;
61
+ links.push(`<a href="${href(file, directoryFile(cumulative))}">${escape(part)}</a>`);
62
+ }
63
+ if (basename) links.push(escape(basename));
64
+ return `<nav aria-label="Breadcrumb">${links.join(' / ')}</nav>`;
65
+ };
66
+ const heading = values => `<p><strong>Executable lines: ${metric(values.lines)} · Statements: ${metric(values.statements)}</strong><br>Script functions: ${metric(values.functions)} · Script branches: ${metric(values.branches)}<br>Template DOM presence: ${metric(values.dom)}; ${values.unsupported} unsupported files; ${report.records} test records.</p>`;
67
+ const limitations = entry => [entry.executionUnsupported, ...(entry.unsupportedDirectives || []), ...entry.scripts.flatMap(script => [script.status === 'unsupported' ? `Script at line ${script.line}: ${script.reason}` : '', ...(script.generated || []).filter(fragment => !['linked', 'empty'].includes(fragment.status)).map(fragment => `Line ${fragment.line}: ${fragment.reason}`)])].filter(Boolean).join(' · ');
68
+ const fileRow = (entry, file, fullPath = false) => `<tr><td>${entry.instrumented ? `<a href="${href(file, `files/${entry.id}.html`)}">${escape(fullPath ? entry.path : path.posix.basename(entry.path))}</a>` : escape(fullPath ? entry.path : path.posix.basename(entry.path))}<br><span class="muted">${escape(entry.engines?.join(', ') || entry.kind)} · ${entry.status}</span>${limitations(entry) ? `<br>${escape(limitations(entry))}` : ''}</td>${cell(entry.lineSummary)}${cell(entry.statementSummary)}${cell(entry.functionSummary)}${cell(entry.branchSummary)}${cell({total: entry.instrumented ? 1 : 0, covered: entry.status === 'observed' ? 1 : 0, percent: !entry.instrumented ? null : entry.status === 'observed' ? 100 : 0})}</tr>`;
69
+ const table = (rows, values) => `<div class="scroll"><table><thead><tr><th>Directory / file</th><th>Executable lines</th><th>Statements</th><th>Script functions</th><th>Script branches</th><th>Template DOM presence</th></tr></thead><tbody><tr class="total"><td>Total</td>${cell(values.lines)}${cell(values.statements)}${cell(values.functions)}${cell(values.branches)}${cell(values.dom)}</tr>${rows}</tbody></table></div>`;
70
+ const referenceCounts = status => (report.scripts.references || []).filter(fragment => fragment.status === status).length;
71
+ const gaps = `<p>Inline scripts: ${report.scripts.instrumented} instrumented; ${report.scripts.unsupported.length} unsupported. PHP output: ${referenceCounts('linked')} linked to child templates; ${referenceCounts('empty')} empty; ${referenceCounts('unresolved')} unresolved; ${referenceCounts('unobserved')} not observed. Rendering and source links do not imply JavaScript execution. See file notes and <a href="coverage-summary.json">the JSON report</a> for details.</p>`;
72
+ const baseline = report.records ? '' : '<p><strong>No browser observations collected. This is an inventory baseline, not a completed coverage run.</strong></p>';
73
+ const summaries = [];
74
+ for (const [directory, entries] of [...directories].sort(([a], [b]) => a.localeCompare(b))) {
75
+ const file = directoryFile(directory), values = totals(entries);
76
+ const children = [...directories.keys()].filter(name => name && path.posix.dirname(name) === (directory || '.')).sort();
77
+ const rows = children.map(child => {
78
+ const summary = totals(directories.get(child));
79
+ return `<tr><td>📁 <a href="${href(file, directoryFile(child))}">${escape(path.posix.basename(child))}</a></td>${cell(summary.lines)}${cell(summary.statements)}${cell(summary.functions)}${cell(summary.branches)}${cell(summary.dom)}</tr>`;
80
+ }).concat(entries.filter(entry => path.posix.dirname(entry.path) === (directory || '.')).sort((a, b) => a.path.localeCompare(b.path)).map(entry => fileRow(entry, file))).join('\n');
81
+ fs.writeFileSync(path.join(output, file), page(directory || 'Magento template coverage', `${breadcrumbs(file, directory)}
82
+ <h1>${escape(directory || 'Magento template coverage')}</h1>${heading(values)}${baseline}
83
+ ${table(rows, values)}${directory ? '' : gaps}<p><a href="${href(file, 'all.html')}">Search all files</a></p>${legend}<p>${semantics}</p>
84
+ <p class="muted">Inventory roots: ${escape(report.roots.join(', '))}. Physical files are counted independently; module/theme applicability is not resolved.</p>`));
85
+ summaries.push({ path: directory, report: file, ...values });
86
+ }
87
+ for (const entry of report.templates.filter(entry => entry.instrumented)) {
88
+ const file = `files/${entry.id}.html`;
89
+ const sourceRows = entry.source.split(/\r\n|\r|\n/).map((text, index) => {
90
+ const number = index + 1, line = entry.lineHits[number];
91
+ const state = !line ? 'neutral' : !line.hits ? 'uncovered' : line.covered < line.statements ? 'partial' : 'covered';
92
+ return `<tr id="L${number}" class="${state}"><td class="number"><a href="#L${number}">${number}</a></td><td class="hits">${line ? `${line.hits}×` : ''}</td><td class="code">${escape(text)}</td></tr>`;
93
+ }).join('\n');
94
+ const statements = [...entry.statements].sort((a, b) => a.start.line - b.start.line || a.start.column - b.start.column).map(statement => `<tr class="${statement.hits ? 'covered' : 'uncovered'}"><td><a href="#L${statement.start.line}">${statement.start.line}:${statement.start.column + 1}</a></td><td>${escape(statement.binding)}</td><td>${escape(statement.syntax)}</td><td>${statement.hits}</td></tr>`).join('\n');
95
+ const scriptCounters = [...entry.functions.map(item => ({...item, label: item.name, kind: 'Function'})), ...entry.branches.map(item => ({...item, label: item.type + (item.implicit ? ' (implicit alternative)' : ''), kind: 'Branch alternative'}))]
96
+ .map(item => `<tr class="${item.hits ? 'covered' : 'uncovered'}"><td><a href="#L${item.start.line}">${item.start.line}:${item.start.column + 1}</a></td><td>${escape(item.kind)}</td><td>${escape(item.label)}</td><td>${item.hits}</td></tr>`).join('');
97
+ const outputReferences = entry.scripts.flatMap(script => script.generated || []).map(fragment =>
98
+ `<tr><td><a href="#L${fragment.line}">${fragment.line}</a></td><td>${escape(fragment.status)}</td><td>${escape(fragment.reason)}${fragment.targets?.length ? '<br>' + fragment.targets.map(target => `<a href="${href(file, `files/${target.id}.html`)}">${escape(target.path)}</a>`).join('<br>') : ''}</td></tr>`).join('');
99
+ fs.writeFileSync(path.join(output, file), page(entry.path, `${breadcrumbs(file, path.posix.dirname(entry.path), path.posix.basename(entry.path))}<h1>${escape(entry.path)}</h1>
100
+ ${heading(totals([entry]))}${limitations(entry) ? `<p>${escape(limitations(entry))}</p>` : ''}<p>Engines: ${escape(entry.engines?.join(', ') || 'knockout')} · DOM: ${entry.status}; ${entry.observations} test observations.</p>
101
+ <p>${semantics}</p><p>Green: executed. Red: never executed. Amber: some statements on this line did not execute. Grey: no measured statement.</p>
102
+ <div class="scroll"><table class="source"><thead><tr><th>Line</th><th>Hits</th><th>Original source</th></tr></thead><tbody>${sourceRows}</tbody></table></div>
103
+ <h2>Template statements</h2><table><thead><tr><th>Line:column</th><th>Expression / directive</th><th>Syntax</th><th>Executions</th></tr></thead><tbody>${statements}</tbody></table>
104
+ ${scriptCounters ? `<h2>Inline script functions and branches</h2><table><thead><tr><th>Line:column</th><th>Kind</th><th>Name / type</th><th>Executions</th></tr></thead><tbody>${scriptCounters}</tbody></table>` : ''}
105
+ ${outputReferences ? `<h2>PHP output and child templates</h2><p>These links describe rendered output. Execution counters stay in each child template; rendering alone does not cover a statement. Additional generated code without mapped counters is not assigned invented source locations.</p><table><thead><tr><th>Source line</th><th>Output</th><th>Source attribution</th></tr></thead><tbody>${outputReferences}</tbody></table>` : ''}`));
106
+ }
107
+ fs.writeFileSync(path.join(output, 'all.html'), page('All template files', `${breadcrumbs('all.html', '')}<h1>All template files</h1>${baseline}
108
+ <p><label>Filter templates <input id="filter" type="search" placeholder="Path, engine or status"></label></p>${table(report.templates.map(entry => fileRow(entry, 'all.html', true)).join('\n'), totals(report.templates))}
109
+ <script>document.getElementById('filter').addEventListener('input',function(){var query=this.value.toLowerCase();document.querySelectorAll('tbody tr:not(.total)').forEach(function(row){row.hidden=!row.textContent.toLowerCase().includes(query);});});</script>`));
110
+ fs.writeFileSync(path.join(output, 'coverage-summary.json'), `${JSON.stringify({ ...report, directories: summaries }, null, 2)}\n`);
111
+ }
112
+
113
+ module.exports = { writeReport };
@@ -0,0 +1,235 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const { parseFragment } = require('parse5');
8
+ const { parse } = require('acorn');
9
+ const { decodeHTMLAttribute } = require('entities');
10
+ const { engines, hit, detectEngine, underscore, jquery, literal } = require('./engines');
11
+
12
+ const attributes = Object.fromEntries([
13
+ 'css', 'attr', 'html', 'with', 'text', 'click', 'event', 'submit', 'enable', 'disable',
14
+ 'options', 'visible', 'template', 'hasFocus', 'textInput', 'component', 'uniqueName',
15
+ 'optionsText', 'optionsValue', 'checkedValue', 'selectedOptions', 'if', 'ifnot',
16
+ 'repeat', 'range', 'resizable', 'keyboard', 'autoselect', 'tooltip', 'afterRender',
17
+ 'bindHtml', 'outerClick', 'collapsible', 'openCollapsible', 'closeCollapsible',
18
+ 'toggleCollapsible', 'staticChecked', 'simpleChecked', 'colorPicker'
19
+ ].map(name => [name.toLowerCase(), name]));
20
+ Object.assign(attributes, {
21
+ innerif: 'if', innerifnot: 'ifnot', outereach: 'foreach', each: 'foreach',
22
+ 'ko-value': 'value', 'ko-style': 'style', 'ko-checked': 'checked', 'ko-disabled': 'disable',
23
+ 'ko-focused': 'hasFocus', 'ko-scope': 'scope', 'simple-checked': 'simpleChecked',
24
+ outerfasteach: 'fastForEach', render: 'template', translate: 'i18n'
25
+ });
26
+ const nodes = { if: 'if', text: 'text', with: 'with', scope: 'scope', ifnot: 'ifnot',
27
+ each: 'foreach', component: 'component', render: 'template', repeat: 'repeat',
28
+ fastforeach: 'fastForEach', translate: 'i18n' };
29
+
30
+ // Map decoded attribute offsets back to the original file, including entities and CRLF.
31
+ function decodeWithOffsets(raw, start) {
32
+ let value = '';
33
+ const offsets = [];
34
+ for (let index = 0; index < raw.length;) {
35
+ let length = 1;
36
+ let text = raw[index];
37
+ if (text === '&') {
38
+ const match = /^&(?:#[xX][\da-fA-F]+;?|#\d+;?|[a-zA-Z][\da-zA-Z]*;?)/.exec(raw.slice(index));
39
+ if (match) {
40
+ const candidate = match[0];
41
+ // Named references without a semicolon followed by '=' remain literal in attributes.
42
+ if (!(raw[index + candidate.length] === '=' && !candidate.endsWith(';') && candidate[1] !== '#')) {
43
+ const decoded = decodeHTMLAttribute(candidate);
44
+ if (decoded !== candidate) { text = decoded; length = candidate.length; }
45
+ }
46
+ }
47
+ } else if (text === '\r') { text = '\n'; length = raw[index + 1] === '\n' ? 2 : 1; }
48
+ else if (text === '\0') text = '\uFFFD';
49
+ for (let part = 0; part < text.length; part++) offsets.push(start + index);
50
+ value += text;
51
+ index += length;
52
+ }
53
+ offsets.push(start + raw.length);
54
+ return { value, offsets };
55
+ }
56
+
57
+ function analyzeBindings(source, templateId, register, edit, masked = source, unsupported = []) {
58
+ const location = offset => {
59
+ const before = source.slice(0, offset).split(/\r\n|\r|\n/);
60
+ return { line: before.length, column: before.at(-1).length };
61
+ };
62
+ const add = (binding, syntax, start, end, insertion, suffix = '') => {
63
+ const id = register(binding, syntax, start, end);
64
+ const marker = `/*mtc_${templateId}_${id}_${Buffer.from(binding).toString('hex')}*/`;
65
+ edit(insertion, marker + suffix);
66
+ };
67
+ const bindings = (value, offsets, syntax) => {
68
+ let object;
69
+ try { object = parse(`({${value}\n})`, { ecmaVersion: 'latest' }).body[0].expression; }
70
+ catch (error) { throw new Error(`Cannot parse ${syntax} at line ${location(offsets[0]).line}: ${error.message}`); }
71
+ const keys = new Set();
72
+ for (const property of object.properties) {
73
+ const key = property.key?.name ?? property.key?.value;
74
+ if (property.type !== 'Property' || property.computed || property.method ||
75
+ property.kind !== 'init' || typeof key !== 'string' || keys.has(key)) {
76
+ throw new Error(`Unsupported or duplicate binding at line ${location(offsets[0]).line}`);
77
+ }
78
+ keys.add(key);
79
+ if (property.shorthand) {
80
+ edit(offsets[property.key.end - 2], ': ');
81
+ add(key, syntax, offsets[property.key.start - 2], offsets[property.key.end - 2],
82
+ offsets[property.key.end - 2], 'void 0');
83
+ continue;
84
+ }
85
+ add(key, syntax, offsets[property.key.start - 2], offsets[property.value.end - 2], offsets[property.value.start - 2]);
86
+ }
87
+ };
88
+ const attributeValue = (node, attribute) => {
89
+ const span = node.sourceCodeLocation.attrs[attribute.name];
90
+ const raw = source.slice(span.startOffset, span.endOffset);
91
+ const match = /^[^\s=]+\s*=\s*(["']?)/.exec(raw);
92
+ if (!match) return { value: '', offsets: [span.endOffset], span, missing: true };
93
+ const quote = match[1];
94
+ const end = quote ? raw.length - 1 : raw.length;
95
+ const decoded = decodeWithOffsets(raw.slice(match[0].length, end), span.startOffset + match[0].length);
96
+ if (decoded.value !== attribute.value) throw new Error(`Cannot map attribute at line ${location(span.startOffset).line}`);
97
+ return { ...decoded, span };
98
+ };
99
+ const shorthand = (node, attribute, binding, syntax, isRender) => {
100
+ const data = attribute ? attributeValue(node, attribute) : {
101
+ value: '', offsets: [node.sourceCodeLocation.startTag.endOffset - 1], missing: true
102
+ };
103
+ if (data.missing) {
104
+ const offset = !attribute && source[data.offsets[0] - 1] === '/' ? data.offsets[0] - 1 : data.offsets[0];
105
+ const name = attribute ? '' : ' args';
106
+ const id = register(binding, syntax, attribute ? data.span.startOffset : node.sourceCodeLocation.startOffset, offset);
107
+ const marker = `/*mtc_${templateId}_${id}_${Buffer.from(binding).toString('hex')}*/`;
108
+ edit(offset, `${name}="${marker}${isRender ? 'getTemplate()' : 'void 0'}"`);
109
+ } else {
110
+ add(binding, syntax, data.span.startOffset, data.span.endOffset, data.offsets[0],
111
+ !data.value ? (isRender ? 'getTemplate()' : 'void 0') : '');
112
+ }
113
+ };
114
+ const visit = node => {
115
+ if (node.nodeName === '#comment' && /^\s*ko\s+/.test(node.data)) {
116
+ const span = node.sourceCodeLocation;
117
+ const raw = source.slice(span.startOffset, span.endOffset);
118
+ const prefix = /^<!--\s*ko\s+/.exec(raw)[0].length;
119
+ const value = raw.slice(prefix, -3);
120
+ if (/<\?/.test(value)) { unsupported.push(`PHP-generated Knockout binding at line ${location(span.startOffset).line}`); return; }
121
+ if (/<%|\$\{|\{\{/.test(value)) return;
122
+ bindings(value, Array.from({ length: value.length + 1 }, (_, i) => span.startOffset + prefix + i), 'ko-comment');
123
+ }
124
+ if (node.tagName && node.sourceCodeLocation) {
125
+ for (const attribute of node.attrs || []) {
126
+ if (attribute.name !== 'data-bind' && !attributes[attribute.name]) continue;
127
+ const span = node.sourceCodeLocation.attrs[attribute.name];
128
+ if (/<\?/.test(source.slice(span.startOffset, span.endOffset))) { unsupported.push(`PHP-generated binding at line ${location(span.startOffset).line}`); continue; }
129
+ if (/<%|\$\{|\{\{/.test(source.slice(span.startOffset, span.endOffset))) continue;
130
+ if (attribute.name === 'data-bind') {
131
+ const data = attributeValue(node, attribute);
132
+ bindings(data.value, data.offsets, 'data-bind');
133
+ } else if (attributes[attribute.name]) {
134
+ shorthand(node, attribute, attributes[attribute.name], `magento-attribute:${attribute.name}`, attribute.name === 'render');
135
+ }
136
+ }
137
+ const args = node.attrs.find(attribute => attribute.name === 'args');
138
+ const argsSpan = args && node.sourceCodeLocation.attrs.args;
139
+ if (nodes[node.tagName] && !(argsSpan && /<%|\$\{|\{\{/.test(source.slice(argsSpan.startOffset, argsSpan.endOffset)))) {
140
+ shorthand(node, node.attrs.find(attribute => attribute.name === 'args'), nodes[node.tagName],
141
+ `magento-node:${node.tagName}`, node.tagName === 'render');
142
+ }
143
+ }
144
+ // These bodies are inert/raw-text, not binding declarations in this template's context.
145
+ if (!['script', 'style', 'textarea', 'template'].includes(node.tagName)) {
146
+ for (const child of node.childNodes || []) visit(child);
147
+ }
148
+ };
149
+ visit(parseFragment(masked, { sourceCodeLocationInfo: true }));
150
+ }
151
+
152
+ function analyzeStatements(source, templateId, requested = 'auto', options = {}) {
153
+ if (!engines.includes(requested)) throw new Error(`Unsupported template engine: ${requested}`);
154
+ const statements = [], edits = [], used = new Set(), unsupported = [];
155
+ const location = offset => {
156
+ const before = source.slice(0, offset).split(/\r\n|\r|\n/);
157
+ return { line: before.length, column: before.at(-1).length };
158
+ };
159
+ const region = (content, base, engine) => {
160
+ // Inline templates are inert until consumed. Map their bodies separately
161
+ // so merely inserting a script/template element cannot claim execution.
162
+ const nested = [], scripts = [];
163
+ const input = options.phtml ? require('./alpine').maskPhp(content).masked : content;
164
+ const tree = parseFragment(input, { sourceCodeLocationInfo: true });
165
+ const find = node => {
166
+ const type = node.attrs?.find(a => a.name === 'type')?.value.toLowerCase();
167
+ const inline = node.tagName === 'template' || (node.tagName === 'script' &&
168
+ ['text/html', 'text/x-magento-template', 'text/x-jquery-tmpl', 'text/x-template'].includes(type));
169
+ const span = node.sourceCodeLocation;
170
+ if (inline && span?.startTag && span.endTag) {
171
+ nested.push({ start: span.startTag.endOffset, end: span.endTag.startOffset,
172
+ engine: type === 'text/x-jquery-tmpl' ? 'jquery-tmpl' : node.tagName === 'template' && engine === 'alpine' ? 'alpine' : 'auto' });
173
+ return;
174
+ }
175
+ if (node.tagName === 'script' && span?.startTag && span.endTag) scripts.push({start: span.startTag.endOffset, end: span.endTag.startOffset});
176
+ // Executable JS, CSS and textareas are not separate HTML templates.
177
+ if (!['script', 'style', 'textarea'].includes(node.tagName)) (node.childNodes || []).forEach(find);
178
+ };
179
+ find(tree);
180
+ let masked = input;
181
+ for (const child of [...nested, ...scripts]) masked = masked.slice(0, child.start) +
182
+ masked.slice(child.start, child.end).replace(/[^\r\n]/g, ' ') + masked.slice(child.end);
183
+ // JavaScript template literals inside Alpine attributes are expressions,
184
+ // not jQuery/Underscore delimiters. Keep genuine engine syntax elsewhere.
185
+ let detection = masked;
186
+ const alpineAttributes = node => {
187
+ for (const attribute of node.attrs || []) {
188
+ if (!/^(?:x-|[@:])/.test(attribute.name)) continue;
189
+ const span = node.sourceCodeLocation?.attrs?.[attribute.name];
190
+ if (!span) continue;
191
+ const equal = masked.indexOf('=', span.startOffset);
192
+ if (equal < 0 || equal >= span.endOffset) continue;
193
+ detection = detection.slice(0, equal + 1) + detection.slice(equal + 1, span.endOffset).replace(/[^\r\n]/g, ' ') + detection.slice(span.endOffset);
194
+ }
195
+ for (const child of node.childNodes || []) alpineAttributes(child);
196
+ };
197
+ alpineAttributes(parseFragment(masked, {sourceCodeLocationInfo: true}));
198
+ const selected = engine === 'auto' ? detectEngine(detection) : engine;
199
+ used.add(selected);
200
+ if (['underscore', 'jquery-tmpl', 'literal'].includes(selected) && /\s(?:x-[\w:.-]+|[@:][\w:.-]+)\s*=/.test(masked)) {
201
+ unsupported.push(`Alpine attributes in a ${selected} region are not instrumented; legacy engine coverage is retained.`);
202
+ }
203
+ const register = (binding, syntax, start, end) => {
204
+ const id = String(statements.length);
205
+ statements.push({ id, binding, syntax, start: location(base + start), end: location(base + end) });
206
+ return id;
207
+ };
208
+ const add = (...args) => hit(templateId, register(...args));
209
+ const edit = (offset, text) => edits.push({ offset: base + offset, text });
210
+ if (selected === 'underscore') underscore(detection, add, edit);
211
+ if (selected === 'jquery-tmpl') jquery(detection, add, edit);
212
+ if (selected === 'literal') literal(detection, add, edit);
213
+ // Engine tokens can contain markup and quotes, so hide them from the HTML
214
+ // parser. Dynamic generated binding declarations are explicitly excluded.
215
+ const html = masked.replace(/<%[\s\S]*?%>|\{\{[\s\S]*?\}\}|\$\{[^}]*\}/g,
216
+ token => token.replace(/[^\r\n]/g, ' '));
217
+ if (selected !== 'html') analyzeBindings(content, templateId, register, edit, html, unsupported);
218
+ if (selected === 'alpine') {
219
+ let alpineSource = content;
220
+ for (const child of [...nested, ...scripts]) alpineSource = alpineSource.slice(0, child.start) + alpineSource.slice(child.start, child.end).replace(/[^\r\n]/g, ' ') + alpineSource.slice(child.end);
221
+ unsupported.push(...require('./alpine').analyzeAlpine(alpineSource, templateId, {phtml: options.phtml, register, edit}).unsupported);
222
+ }
223
+ for (const child of nested) region(content.slice(child.start, child.end), base + child.start, child.engine);
224
+ };
225
+ region(source, 0, requested);
226
+ let content = source;
227
+ // At an identical offset, later (inner) AST insertions must appear inside
228
+ // earlier wrappers. Reverse insertion order when applying edits backwards.
229
+ for (const edit of edits.map((edit, order) => ({ ...edit, order })).sort((a, b) => b.offset - a.offset || b.order - a.order)) {
230
+ content = content.slice(0, edit.offset) + edit.text + content.slice(edit.offset);
231
+ }
232
+ return { statements, content, engines: [...used].sort(), ...(unsupported.length ? {unsupported} : {}) };
233
+ }
234
+
235
+ module.exports = { analyzeStatements };
@@ -0,0 +1,31 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ "use strict";
6
+
7
+ const {analyzeStatements} = require('./statements');
8
+ const {instrumentInline} = require('./inline-scripts');
9
+
10
+ function analyzeTemplate(source, id, engine, options) {
11
+ let analysis;
12
+ try { analysis = analyzeStatements(source, id, engine, options); }
13
+ catch (error) {
14
+ if (engine !== 'auto' || !/^(Cannot parse|Unsupported or duplicate binding)/.test(error.message)) throw error;
15
+ analysis = {content: source, statements: [], engines: ['html'],
16
+ executionUnsupported: `${error.message}; binding coverage unavailable. Select the template engine explicitly or fix its expressions.`};
17
+ }
18
+ const inline = instrumentInline(source, id, options);
19
+ let content = analysis.content, cursor = 0;
20
+ for (const replacement of inline.replacements) {
21
+ const offset = content.indexOf(replacement.original, cursor);
22
+ if (offset < 0) throw new Error('Binding instrumentation changed an inline script');
23
+ content = content.slice(0, offset) + replacement.instrumented + content.slice(offset + replacement.original.length);
24
+ cursor = offset + replacement.instrumented.length;
25
+ }
26
+ return {...analysis, content, statements: [...analysis.statements, ...inline.statements],
27
+ functions: inline.functions, branches: inline.branches, scripts: inline.scripts,
28
+ engines: [...new Set([...analysis.engines, ...(inline.scripts.length ? ['inline-script'] : [])])].sort()};
29
+ }
30
+
31
+ module.exports = {analyzeTemplate};
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "@magelens/magento-template-coverage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.1",
4
+ "description": "Magento 2 HTML/PHTML template execution coverage for Cypress and Playwright, including Knockout, Hyva/Alpine and inline JavaScript",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/MageLens/magento-template-coverage.git"
9
+ },
10
+ "homepage": "https://github.com/MageLens/magento-template-coverage#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/MageLens/magento-template-coverage/issues"
13
+ },
14
+ "engines": {
15
+ "node": "^20.19.0 || >=22.12.0"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "registry": "https://registry.npmjs.org/"
20
+ },
21
+ "keywords": [
22
+ "magento",
23
+ "magento2",
24
+ "code-coverage",
25
+ "template-coverage",
26
+ "phtml",
27
+ "cypress",
28
+ "playwright",
29
+ "knockout",
30
+ "hyva",
31
+ "alpinejs",
32
+ "inline-javascript",
33
+ "end-to-end-testing"
34
+ ],
35
+ "main": "lib/index.js",
36
+ "exports": {
37
+ ".": "./lib/index.js",
38
+ "./browser": "./lib/browser.js",
39
+ "./cypress": "./cypress/support.js",
40
+ "./playwright": {
41
+ "types": "./playwright/index.d.ts",
42
+ "default": "./playwright/index.js"
43
+ }
44
+ },
45
+ "bin": {
46
+ "magento-template-coverage": "bin/cli.js"
47
+ },
48
+ "files": [
49
+ "bin",
50
+ "lib",
51
+ "cypress",
52
+ "LICENSE",
53
+ "LICENSE.license",
54
+ "package.json.license",
55
+ "README.md",
56
+ "CHANGELOG.md",
57
+ "playwright"
58
+ ],
59
+ "scripts": {
60
+ "test": "node --test test/*.test.js",
61
+ "test:browser": "node test/browser/run.js",
62
+ "prepublishOnly": "npm test",
63
+ "test:playwright": "playwright test --config=test/playwright/config.js",
64
+ "test:types": "tsc --noEmit --strict --module node16 --moduleResolution node16 --target ES2022 test/playwright/types.ts"
65
+ },
66
+ "dependencies": {
67
+ "@babel/core": "7.29.7",
68
+ "@babel/generator": "7.29.8",
69
+ "acorn": "8.19.0",
70
+ "entities": "6.0.1",
71
+ "istanbul-lib-instrument": "6.0.3",
72
+ "parse5": "8.1.1",
73
+ "php-parser": "3.7.0"
74
+ },
75
+ "devDependencies": {
76
+ "@alpinejs/csp": "3.14.3",
77
+ "@playwright/test": "1.65.0",
78
+ "@types/node": "24.19.2",
79
+ "alpinejs": "3.17.4",
80
+ "knockout": "3.5.1",
81
+ "typescript": "5.9.3",
82
+ "underscore": "1.13.8"
83
+ }
84
+ }
@@ -0,0 +1,3 @@
1
+ SPDX-FileCopyrightText: MageLens
2
+ SPDX-License-Identifier: MIT
3
+ License: see LICENSE in the repository root.
@@ -0,0 +1,16 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ import type {BrowserContext, TestType} from '@playwright/test';
6
+ export interface TemplateCoverageOptions {
7
+ outputDir?: string;
8
+ metadata?: Record<string, unknown>;
9
+ }
10
+ export function registerTemplateCoverage(context: BrowserContext, options?: TemplateCoverageOptions): Promise<{
11
+ flush(): Promise<void>;
12
+ stop(): Promise<string | undefined>;
13
+ }>;
14
+ export function withTemplateCoverage<T extends {}, W extends {}>(test: TestType<T, W>, options?: TemplateCoverageOptions): TestType<T & {templateCoverageOptions: TemplateCoverageOptions}, W>;
15
+
16
+ export function installTemplateRuntime(context: BrowserContext): Promise<void>;
@@ -0,0 +1,138 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { randomUUID } = require('node:crypto');
10
+ const { browserSource } = require('../lib/browser-source');
11
+ const registeredContexts = new WeakSet();
12
+ const runtimeContexts = new WeakSet();
13
+ const runtimeKey = 'magento-template-coverage.runtime';
14
+
15
+ /** Keep instrumented templates functional during warm-up without recording hits. */
16
+ async function installTemplateRuntime(context) {
17
+ if (runtimeContexts.has(context)) return;
18
+ runtimeContexts.add(context);
19
+ await context.addInitScript({content: `(() => {
20
+ const key = Symbol.for(${JSON.stringify(runtimeKey)});
21
+ if (window[key]) return;
22
+ const runtime = window[key] = ${browserSource()};
23
+ runtime.observeExecution(window, () => {});
24
+ })();`});
25
+ }
26
+
27
+ /** Register before creating/navigating pages. Works with any Playwright browser. */
28
+ async function registerTemplateCoverage(context, { outputDir = '.template-coverage', metadata = {} } = {}) {
29
+ if (registeredContexts.has(context)) throw new Error('Register template coverage once per context, before creating pages.');
30
+ registeredContexts.add(context);
31
+ const recordId = randomUUID();
32
+ const binding = `__mtc_${recordId.replaceAll('-', '')}`;
33
+ const documents = new Map();
34
+ let stopped = false;
35
+ await context.exposeBinding(binding, (_source, snapshot) => {
36
+ if (stopped) return;
37
+ const previous = documents.get(snapshot.document);
38
+ if (!previous || snapshot.sequence > previous.sequence) documents.set(snapshot.document, snapshot);
39
+ });
40
+ const script = `(() => {
41
+ const runtime = window[Symbol.for(${JSON.stringify(runtimeKey)})] ||= ${browserSource()};
42
+ const documentId = crypto.randomUUID?.() || Date.now() + '-' + Math.random().toString(36).slice(2);
43
+ const ids = new Set(); const hits = {}; const references = new Map(); let sequence = 0; let queued = false;
44
+ const pending = new Set();
45
+ const send = () => {
46
+ queued = false;
47
+ const promise = window[${JSON.stringify(binding)}]({document:documentId, sequence:++sequence, ids:[...ids], hits, references:[...references.values()]});
48
+ pending.add(promise); promise.catch(() => {}).finally(() => pending.delete(promise));
49
+ };
50
+ const changed = () => { if (!queued) { queued = true; queueMicrotask(send); } };
51
+ const dom = runtime.observeTemplates(window, id => {ids.add(id); changed();}, reference => {
52
+ references.set(JSON.stringify(reference), reference); changed();
53
+ });
54
+ const execution = runtime.observeExecution(window, (id, statement) => {
55
+ const counters = hits[id] ||= {}; counters[statement] = (counters[statement] || 0) + 1; changed();
56
+ });
57
+ window.addEventListener('pagehide', () => {dom.flush(); send();});
58
+ Object.defineProperty(window, ${JSON.stringify(binding + '_flush')}, {value: async () => {
59
+ dom.flush(); send(); await Promise.all([...pending]);
60
+ }});
61
+ })();`;
62
+ await context.addInitScript({ content: script });
63
+
64
+ async function flush(pages = context.pages()) {
65
+ for (const page of pages) {
66
+ for (const frame of page.frames()) {
67
+ try {
68
+ await frame.evaluate(key => window[key]?.(), binding + '_flush');
69
+ } catch (error) {
70
+ // A navigation/closed frame has already streamed its own records.
71
+ if (!/closed|detached|destroyed|navigation/i.test(error.message)) throw error;
72
+ }
73
+ }
74
+ }
75
+ }
76
+ const closeMethods = new Map();
77
+ const trackPage = page => {
78
+ const close = page.close;
79
+ const wrapped = async function (...args) {
80
+ await flush([page]);
81
+ return close.apply(this, args);
82
+ };
83
+ closeMethods.set(page, {close, wrapped});
84
+ page.close = wrapped;
85
+ };
86
+ context.on('page', trackPage);
87
+ for (const page of context.pages()) trackPage(page);
88
+
89
+ async function stop() {
90
+ if (stopped) return;
91
+ await flush();
92
+ stopped = true;
93
+ context.off('page', trackPage);
94
+ for (const [page, {close, wrapped}] of closeMethods) if (page.close === wrapped) page.close = close;
95
+ const ids = new Set(), hits = {}, references = new Map();
96
+ for (const snapshot of documents.values()) {
97
+ for (const reference of snapshot.references) references.set(JSON.stringify(reference), reference);
98
+ for (const id of snapshot.ids) ids.add(id);
99
+ for (const [id, statements] of Object.entries(snapshot.hits)) {
100
+ const counters = hits[id] ||= {};
101
+ for (const [statement, count] of Object.entries(statements)) counters[statement] = (counters[statement] || 0) + count;
102
+ }
103
+ }
104
+ const record = { ...metadata, schemaVersion: 2, recordId, ids: [...ids].sort(), hits, references: [...references.values()] };
105
+ fs.mkdirSync(outputDir, {recursive: true});
106
+ const file = path.join(outputDir, `${recordId}.mtc`);
107
+ fs.writeFileSync(file, JSON.stringify(record), {flag: 'wx'});
108
+ return file;
109
+ }
110
+ return { flush, stop };
111
+ }
112
+
113
+ /** Extend either Playwright's test or an existing suite's authenticated/guest test. */
114
+ function withTemplateCoverage(test, options = {}) {
115
+ return test.extend({
116
+ templateCoverageOptions: [options, {option: true}],
117
+ browser: [async ({browser}, use) => {
118
+ const newContext = browser.newContext;
119
+ const wrapped = async function (...args) {
120
+ const context = await newContext.apply(this, args);
121
+ try { await installTemplateRuntime(context); }
122
+ catch (error) { await context.close(); throw error; }
123
+ return context;
124
+ };
125
+ browser.newContext = wrapped;
126
+ try { await use(browser); }
127
+ finally { if (browser.newContext === wrapped) browser.newContext = newContext; }
128
+ }, {scope: 'worker'}],
129
+ context: async ({context, templateCoverageOptions}, use, testInfo) => {
130
+ const coverage = await registerTemplateCoverage(context, {...templateCoverageOptions,
131
+ metadata: {spec: testInfo.file, test: testInfo.titlePath, retry: testInfo.retry,
132
+ project: testInfo.project.name, worker: testInfo.workerIndex}});
133
+ try { await use(context); } finally { await coverage.stop(); }
134
+ }
135
+ });
136
+ }
137
+
138
+ module.exports = { installTemplateRuntime, registerTemplateCoverage, withTemplateCoverage };