@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/CHANGELOG.md +113 -0
- package/LICENSE +21 -0
- package/LICENSE.license +3 -0
- package/README.md +241 -2
- package/bin/cli.js +82 -0
- package/cypress/support.js +70 -0
- package/lib/alpine.js +203 -0
- package/lib/browser-source.js +18 -0
- package/lib/browser.js +87 -0
- package/lib/engines-runtime.js +8 -0
- package/lib/engines.js +129 -0
- package/lib/execution.js +141 -0
- package/lib/generated-scripts.js +23 -0
- package/lib/index.js +299 -0
- package/lib/inline-scripts.js +352 -0
- package/lib/report.js +113 -0
- package/lib/statements.js +235 -0
- package/lib/template.js +31 -0
- package/package.json +82 -4
- package/package.json.license +3 -0
- package/playwright/index.d.ts +16 -0
- package/playwright/index.js +138 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
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, randomUUID } = require('node:crypto');
|
|
10
|
+
const { analyzeTemplate } = require('./template');
|
|
11
|
+
const { writeReport } = require('./report');
|
|
12
|
+
const { engines: supportedEngines } = require('./engines');
|
|
13
|
+
|
|
14
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
15
|
+
const portable = value => value.split(path.sep).join('/');
|
|
16
|
+
|
|
17
|
+
function inside(parent, child) {
|
|
18
|
+
const relative = path.relative(parent, child);
|
|
19
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function canonical(file) {
|
|
23
|
+
if (fs.existsSync(file)) return fs.realpathSync(file);
|
|
24
|
+
const parent = path.dirname(file);
|
|
25
|
+
if (parent === file) throw new Error(`Cannot resolve path: ${file}`);
|
|
26
|
+
return path.join(canonical(parent), path.basename(file));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function walk(directory, visit) {
|
|
30
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
31
|
+
const file = path.join(directory, entry.name);
|
|
32
|
+
// Never silently omit symlinked template trees from the denominator.
|
|
33
|
+
if (entry.isSymbolicLink()) throw new Error(`Symlinks are unsupported in coverage inputs: ${file}`);
|
|
34
|
+
if (entry.isDirectory()) walk(file, visit);
|
|
35
|
+
else if (entry.isFile()) visit(file);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function createManifest({ source, roots = ['app/code', 'app/design'], engines = {} }) {
|
|
40
|
+
source = fs.realpathSync(source);
|
|
41
|
+
const templates = new Map();
|
|
42
|
+
const overrides = Object.entries(engines).sort((a, b) => b[0].length - a[0].length);
|
|
43
|
+
for (const [name, engine] of overrides) {
|
|
44
|
+
if (!name || name.startsWith('/') || name.includes('\\') || name.split('/').some(p => !p || p === '.' || p === '..') || !supportedEngines.includes(engine)) {
|
|
45
|
+
throw new Error(`Invalid template engine override: ${name}=${engine}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const matched = new Set();
|
|
49
|
+
for (const root of roots) {
|
|
50
|
+
const directory = path.resolve(source, root);
|
|
51
|
+
if (path.isAbsolute(root) || !inside(source, directory) || directory === source ||
|
|
52
|
+
fs.realpathSync(directory) !== directory) {
|
|
53
|
+
throw new Error(`Inventory root must be a real directory beneath the Magento source: ${root}`);
|
|
54
|
+
}
|
|
55
|
+
walk(directory, file => {
|
|
56
|
+
if (!/\.(html|phtml)$/.test(file)) return;
|
|
57
|
+
const phtml = file.endsWith('.phtml');
|
|
58
|
+
const relative = portable(path.relative(source, file));
|
|
59
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
60
|
+
if (/<!--mtc:[a-f0-9]{32}-->|\/\*mtc_|__mtcTemplateHit/.test(content)) throw new Error(`Source is already instrumented: ${relative}`);
|
|
61
|
+
const kind = phtml ? 'browser-phtml' : 'browser-html';
|
|
62
|
+
const override = overrides.find(([name]) => relative === name || relative.startsWith(`${name}/`));
|
|
63
|
+
if (override) matched.add(override[0]);
|
|
64
|
+
const serverOnly = /\{\{(?:var|trans|depend|layout|block|store|view|media|config|template)\s/.test(content);
|
|
65
|
+
const engine = override?.[1] || (relative.includes('/email/') || serverOnly ? 'html' : 'auto');
|
|
66
|
+
const id = hash(`1.5.1\0${engine}\0${relative}\0${content}`).slice(0, 32);
|
|
67
|
+
let analysis;
|
|
68
|
+
try { analysis = analyzeTemplate(content, id, engine, {phtml}); }
|
|
69
|
+
catch (error) { throw new Error(`${relative}: ${error.message}`); }
|
|
70
|
+
// A PHP-only source has no browser markup to observe or execute.
|
|
71
|
+
if (phtml && !/<[a-zA-Z]/.test(require('./alpine').maskPhp(content).masked)) return;
|
|
72
|
+
templates.set(relative, {
|
|
73
|
+
id,
|
|
74
|
+
path: relative,
|
|
75
|
+
digest: hash(content),
|
|
76
|
+
kind,
|
|
77
|
+
area: relative.match(/\/(frontend|adminhtml|base)\//)?.[1] || 'unknown',
|
|
78
|
+
instrumented: true,
|
|
79
|
+
source: content,
|
|
80
|
+
unsupportedDirectives: analysis.unsupported,
|
|
81
|
+
statements: analysis.statements,
|
|
82
|
+
functions: analysis.functions,
|
|
83
|
+
branches: analysis.branches,
|
|
84
|
+
scripts: analysis.scripts,
|
|
85
|
+
engine,
|
|
86
|
+
engines: analysis.engines,
|
|
87
|
+
executionUnsupported: analysis.executionUnsupported || (engine === 'html' && (relative.includes('/email/') || serverOnly)
|
|
88
|
+
? 'Server-side HTML directives; DOM presence only if the resulting HTML is inserted into the tested document' : undefined)
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
for (const [name] of overrides) if (!matched.has(name)) throw new Error(`Engine override matched no inventoried template: ${name}`);
|
|
93
|
+
return {
|
|
94
|
+
schemaVersion: 2,
|
|
95
|
+
metric: 'template-execution',
|
|
96
|
+
roots: roots.map(root => portable(path.normalize(root))),
|
|
97
|
+
templates: [...templates.values()].sort((a, b) => a.path.localeCompare(b.path))
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function validateManifest(manifest) {
|
|
102
|
+
if (manifest.schemaVersion !== 2 || !['template-execution', 'template-binding-execution'].includes(manifest.metric) || !Array.isArray(manifest.templates)) {
|
|
103
|
+
throw new Error('Unsupported template coverage manifest');
|
|
104
|
+
}
|
|
105
|
+
const ids = new Set();
|
|
106
|
+
const paths = new Set();
|
|
107
|
+
for (const entry of manifest.templates) {
|
|
108
|
+
if (!/^[a-f0-9]{32}$/.test(entry.id) || !/^[a-f0-9]{64}$/.test(entry.digest) ||
|
|
109
|
+
typeof entry.path !== 'string' || entry.path.startsWith('/') || entry.path.includes('\\') ||
|
|
110
|
+
entry.path.split('/').some(part => part === '..' || part === '.' || part === '') ||
|
|
111
|
+
ids.has(entry.id) || paths.has(entry.path) || typeof entry.instrumented !== 'boolean' || !Array.isArray(entry.statements)) {
|
|
112
|
+
throw new Error('Invalid or duplicate template manifest entry');
|
|
113
|
+
}
|
|
114
|
+
if (entry.instrumented) {
|
|
115
|
+
if (typeof entry.source !== 'string' || hash(entry.source) !== entry.digest) throw new Error('Invalid template source or statement map');
|
|
116
|
+
const analysis = analyzeTemplate(entry.source, entry.id, entry.engine, {phtml: entry.kind === 'browser-phtml'});
|
|
117
|
+
if (['statements', 'functions', 'branches', 'scripts'].some(key => JSON.stringify(analysis[key]) !== JSON.stringify(entry[key]))) throw new Error('Invalid template source or statement map');
|
|
118
|
+
}
|
|
119
|
+
ids.add(entry.id);
|
|
120
|
+
paths.add(entry.path);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function instrument({ source, manifest, mappings }) {
|
|
125
|
+
validateManifest(manifest);
|
|
126
|
+
source = fs.realpathSync(source);
|
|
127
|
+
const targets = Object.entries(mappings).map(([root, target]) => {
|
|
128
|
+
root = portable(path.normalize(root));
|
|
129
|
+
target = path.resolve(target);
|
|
130
|
+
if (canonical(target) !== target) throw new Error(`Refusing a symlinked destination: ${target}`);
|
|
131
|
+
if (!manifest.roots.includes(root)) throw new Error(`Unknown inventory root: ${root}`);
|
|
132
|
+
if (inside(source, target) || inside(target, source)) {
|
|
133
|
+
throw new Error(`Refusing to instrument the original source tree: ${target}`);
|
|
134
|
+
}
|
|
135
|
+
return { root, target };
|
|
136
|
+
}).sort((a, b) => b.root.length - a.root.length);
|
|
137
|
+
|
|
138
|
+
for (let index = 0; index < targets.length; index++) {
|
|
139
|
+
for (const other of targets.slice(index + 1)) {
|
|
140
|
+
if (inside(targets[index].target, other.target) || inside(other.target, targets[index].target)) {
|
|
141
|
+
throw new Error('Disposable template destinations must not overlap');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Preflight every destination and source hash before modifying anything.
|
|
147
|
+
const writes = manifest.templates.filter(entry => entry.instrumented).map(entry => {
|
|
148
|
+
const mapping = targets.find(item => entry.path.startsWith(`${item.root}/`));
|
|
149
|
+
if (!mapping) throw new Error(`No disposable destination for ${entry.path}`);
|
|
150
|
+
const original = path.join(source, entry.path);
|
|
151
|
+
if (!inside(source, canonical(original))) throw new Error(`Source escaped inventory: ${entry.path}`);
|
|
152
|
+
const content = fs.readFileSync(original, 'utf8');
|
|
153
|
+
if (hash(content) !== entry.digest) throw new Error(`Source changed since inventory: ${entry.path}`);
|
|
154
|
+
const destination = path.join(mapping.target, entry.path.slice(mapping.root.length + 1));
|
|
155
|
+
if (canonical(destination) !== destination || !inside(mapping.target, destination)) {
|
|
156
|
+
throw new Error(`Refusing a symlinked destination: ${destination}`);
|
|
157
|
+
}
|
|
158
|
+
const analyzed = analyzeTemplate(content, entry.id, entry.engine, {phtml: entry.kind === 'browser-phtml'});
|
|
159
|
+
let output = `<!--mtc:${entry.id}-->\n${analyzed.content}`;
|
|
160
|
+
if (entry.kind === 'browser-phtml') {
|
|
161
|
+
// Preserve declare(strict_types=1) and PHP source line numbers.
|
|
162
|
+
const {masked} = require('./alpine').maskPhp(analyzed.content);
|
|
163
|
+
const firstTag = masked.search(/<[a-zA-Z]/);
|
|
164
|
+
if (firstTag < 0) throw new Error(`No HTML marker location: ${entry.path}`);
|
|
165
|
+
output = analyzed.content.slice(0, firstTag) + `<!--mtc:${entry.id}-->` + analyzed.content.slice(firstTag);
|
|
166
|
+
}
|
|
167
|
+
return { destination, content: output, mode: fs.statSync(original).mode };
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
for (const { destination, content, mode } of writes) {
|
|
171
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
172
|
+
// Rename rather than overwrite: a hardlink must never change the original.
|
|
173
|
+
const temporary = `${destination}.${randomUUID()}.tmp`;
|
|
174
|
+
fs.writeFileSync(temporary, content, { flag: 'wx', mode });
|
|
175
|
+
fs.renameSync(temporary, destination);
|
|
176
|
+
}
|
|
177
|
+
return writes.length;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function merge(manifest, records) {
|
|
181
|
+
validateManifest(manifest);
|
|
182
|
+
const entries = new Map(manifest.templates.map(entry => [entry.id, entry]));
|
|
183
|
+
const observations = new Map();
|
|
184
|
+
const hits = new Map();
|
|
185
|
+
const references = new Map();
|
|
186
|
+
const recordIds = new Map();
|
|
187
|
+
for (const record of records) {
|
|
188
|
+
if (record.schemaVersion !== 2 || typeof record.recordId !== 'string' || !Array.isArray(record.ids) ||
|
|
189
|
+
!record.hits || typeof record.hits !== 'object' || Array.isArray(record.hits)) {
|
|
190
|
+
throw new Error('Invalid template hit record');
|
|
191
|
+
}
|
|
192
|
+
if (recordIds.has(record.recordId)) {
|
|
193
|
+
if (recordIds.get(record.recordId) !== JSON.stringify(record)) throw new Error('Conflicting template hit records');
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
recordIds.set(record.recordId, JSON.stringify(record));
|
|
197
|
+
if (record.references !== undefined && !Array.isArray(record.references)) throw new Error('Invalid template references');
|
|
198
|
+
for (const reference of record.references || []) {
|
|
199
|
+
const entry = entries.get(reference?.template);
|
|
200
|
+
if (!entry?.scripts.some(script => script.generated?.some(fragment => fragment.id === reference.fragment && fragment.tracked)) ||
|
|
201
|
+
typeof reference.empty !== 'boolean' || !Array.isArray(reference.targets) ||
|
|
202
|
+
reference.targets.some(id => !entries.get(id)?.scripts.some(script => script.status === 'instrumented')) ||
|
|
203
|
+
reference.empty && reference.targets.length) throw new Error('Invalid template reference (stale manifest?)');
|
|
204
|
+
const key = `${reference.template}/${reference.fragment}`;
|
|
205
|
+
const state = references.get(key) || {targets: new Set(), empty: false, unresolved: false};
|
|
206
|
+
for (const id of reference.targets) state.targets.add(id);
|
|
207
|
+
state.empty ||= reference.empty;
|
|
208
|
+
state.unresolved ||= !reference.empty && !reference.targets.length;
|
|
209
|
+
references.set(key, state);
|
|
210
|
+
}
|
|
211
|
+
for (const id of new Set(record.ids)) {
|
|
212
|
+
if (!entries.get(id)?.instrumented) throw new Error(`Unknown or unsupported template hit (stale manifest?): ${id}`);
|
|
213
|
+
observations.set(id, (observations.get(id) || 0) + 1);
|
|
214
|
+
}
|
|
215
|
+
for (const [id, counters] of Object.entries(record.hits)) {
|
|
216
|
+
const entry = entries.get(id);
|
|
217
|
+
if (!entry?.instrumented || !counters || typeof counters !== 'object' || Array.isArray(counters)) {
|
|
218
|
+
throw new Error(`Unknown or invalid statement hits (stale manifest?): ${id}`);
|
|
219
|
+
}
|
|
220
|
+
for (const [statement, count] of Object.entries(counters)) {
|
|
221
|
+
if (![...entry.statements, ...entry.functions, ...entry.branches].some(item => item.id === statement) || !Number.isSafeInteger(count) || count < 1) {
|
|
222
|
+
throw new Error(`Invalid statement hit: ${id}/${statement}`);
|
|
223
|
+
}
|
|
224
|
+
const key = `${id}/${statement}`;
|
|
225
|
+
const sum = (hits.get(key) || 0) + count;
|
|
226
|
+
if (!Number.isSafeInteger(sum)) throw new Error('Statement hit count overflow');
|
|
227
|
+
hits.set(key, sum);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const summary = values => {
|
|
232
|
+
const total = values.length;
|
|
233
|
+
const covered = values.filter(Boolean).length;
|
|
234
|
+
return { total, covered, uncovered: total - covered, percent: total ? Math.round(10000 * covered / total) / 100 : null };
|
|
235
|
+
};
|
|
236
|
+
const templates = manifest.templates.map(entry => {
|
|
237
|
+
const scripts = entry.scripts.map(script => ({...script, generated: script.generated?.map(fragment => {
|
|
238
|
+
const reference = references.get(`${entry.id}/${fragment.id}`);
|
|
239
|
+
const status = !reference ? 'unobserved' : reference.unresolved ? 'unresolved' : reference.targets.size ? 'linked' : 'empty';
|
|
240
|
+
const targets = [...reference?.targets || []].map(id => ({id, path: entries.get(id).path})).sort((a, b) => a.path.localeCompare(b.path));
|
|
241
|
+
const reason = status === 'linked' ? 'Rendered output references instrumented child templates; execution is counted at their original source locations.'
|
|
242
|
+
: status === 'empty' ? 'PHP emitted no JavaScript in the observed renders; no execution counter is added.'
|
|
243
|
+
: status === 'unresolved' ? 'Nonempty PHP-generated output was observed without an instrumented child-template source.' : fragment.reason;
|
|
244
|
+
return {...fragment, status, targets, emptyObserved: reference?.empty || false, reason};
|
|
245
|
+
})}));
|
|
246
|
+
const statements = entry.statements.map(statement => ({ ...statement, hits: hits.get(`${entry.id}/${statement.id}`) || 0 }));
|
|
247
|
+
const functions = entry.functions.map(item => ({...item, hits: hits.get(`${entry.id}/${item.id}`) || 0}));
|
|
248
|
+
const branches = entry.branches.map(item => ({...item, hits: hits.get(`${entry.id}/${item.id}`) || 0}));
|
|
249
|
+
const lineHits = {};
|
|
250
|
+
for (const statement of statements) {
|
|
251
|
+
const line = lineHits[statement.start.line] ||= { hits: 0, statements: 0, covered: 0 };
|
|
252
|
+
line.hits += statement.hits;
|
|
253
|
+
line.statements++;
|
|
254
|
+
if (statement.hits) line.covered++;
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
...entry, scripts, statements, functions, branches, lineHits,
|
|
258
|
+
functionSummary: summary(functions.map(item => item.hits)),
|
|
259
|
+
branchSummary: summary(branches.map(item => item.hits)),
|
|
260
|
+
statementSummary: summary(statements.map(statement => statement.hits)),
|
|
261
|
+
lineSummary: summary(Object.values(lineHits).map(line => line.hits)),
|
|
262
|
+
observations: observations.get(entry.id) || 0,
|
|
263
|
+
status: !entry.instrumented ? 'unsupported' : observations.has(entry.id) ? 'observed' : 'unobserved'
|
|
264
|
+
};
|
|
265
|
+
});
|
|
266
|
+
const eligible = templates.filter(entry => entry.instrumented).length;
|
|
267
|
+
const covered = templates.filter(entry => entry.status === 'observed').length;
|
|
268
|
+
return {
|
|
269
|
+
schemaVersion: 2,
|
|
270
|
+
metric: manifest.metric,
|
|
271
|
+
roots: manifest.roots,
|
|
272
|
+
records: recordIds.size,
|
|
273
|
+
summary: {
|
|
274
|
+
eligible, covered, uncovered: eligible - covered,
|
|
275
|
+
unsupported: templates.length - eligible,
|
|
276
|
+
percent: eligible ? Math.round(10000 * covered / eligible) / 100 : null
|
|
277
|
+
},
|
|
278
|
+
statements: summary(templates.flatMap(entry => entry.statements.map(statement => statement.hits))),
|
|
279
|
+
functions: summary(templates.flatMap(entry => entry.functions.map(item => item.hits))),
|
|
280
|
+
branches: summary(templates.flatMap(entry => entry.branches.map(item => item.hits))),
|
|
281
|
+
scripts: {instrumented: templates.flatMap(entry => entry.scripts).filter(script => script.status === 'instrumented').length,
|
|
282
|
+
unsupported: templates.flatMap(entry => entry.scripts.filter(script => script.status === 'unsupported').map(script => ({path: entry.path, ...script}))),
|
|
283
|
+
generated: templates.flatMap(entry => entry.scripts.flatMap(script => (script.generated || []).filter(fragment => ['unresolved', 'unobserved'].includes(fragment.status)).map(fragment => ({path: entry.path, ...fragment})))),
|
|
284
|
+
references: templates.flatMap(entry => entry.scripts.flatMap(script => (script.generated || []).map(fragment => ({path: entry.path, ...fragment}))))},
|
|
285
|
+
lines: summary(templates.flatMap(entry => Object.values(entry.lineHits).map(line => line.hits))),
|
|
286
|
+
templates
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function readRecords(directory) {
|
|
291
|
+
const records = [];
|
|
292
|
+
if (fs.existsSync(directory)) walk(directory, file => {
|
|
293
|
+
// Deliberately not .json: these are not Istanbul maps and may share a shard volume.
|
|
294
|
+
if (file.endsWith('.mtc')) records.push(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
295
|
+
});
|
|
296
|
+
return records;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
module.exports = { createManifest, instrument, merge, readRecords, writeReport };
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: MageLens
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
// License: see LICENSE in the repository root.
|
|
4
|
+
|
|
5
|
+
'use strict';
|
|
6
|
+
|
|
7
|
+
const {hit} = require('./engines');
|
|
8
|
+
const PhpParser = require('php-parser');
|
|
9
|
+
const {parseFragment} = require('parse5');
|
|
10
|
+
const babel = require('@babel/core');
|
|
11
|
+
const generate = require('@babel/generator').default;
|
|
12
|
+
const {programVisitor} = require('istanbul-lib-instrument');
|
|
13
|
+
const {traceGeneratedOutput} = require('./generated-scripts');
|
|
14
|
+
|
|
15
|
+
// Parse PHP tokens rather than matching tags with a regexp: quoted ?>, comments
|
|
16
|
+
// and heredocs must never be mistaken for the end of an island.
|
|
17
|
+
function phpIslands(source) {
|
|
18
|
+
const islands = [];
|
|
19
|
+
let offset = 0, start = null;
|
|
20
|
+
for (const token of new PhpParser().tokenGetAll(source)) {
|
|
21
|
+
const text = Array.isArray(token) ? token[1] : token;
|
|
22
|
+
const type = Array.isArray(token) ? token[0] : '';
|
|
23
|
+
if (type === 'T_OPEN_TAG' || type === 'T_OPEN_TAG_WITH_ECHO') start = offset;
|
|
24
|
+
offset += text.length;
|
|
25
|
+
if (type === 'T_CLOSE_TAG' && start !== null) {
|
|
26
|
+
// PHP's closing token includes the following newline. Keep that
|
|
27
|
+
// newline in JavaScript so // comments and ASI retain their meaning.
|
|
28
|
+
const end = offset - (text.match(/(?:\r\n|\n|\r)$/)?.[0].length || 0);
|
|
29
|
+
islands.push({start, end, text: source.slice(start, end)});
|
|
30
|
+
start = null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (start !== null) islands.push({start, end: offset, text: source.slice(start)});
|
|
34
|
+
return islands;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function placeholderSource(source, islands, start, end, choices = new Map(), semicolons = new Set()) {
|
|
38
|
+
let code = '', cursor = start;
|
|
39
|
+
const segments = [];
|
|
40
|
+
const append = (text, from, to, island = false, structural = false) => {
|
|
41
|
+
if (!island) for (const offset of semicolons) if (offset >= from && offset < to) text = text.slice(0, offset - from) + ' ' + text.slice(offset - from + 1);
|
|
42
|
+
segments.push({start: code.length, end: code.length + text.length, from, to, island, structural});
|
|
43
|
+
code += text;
|
|
44
|
+
};
|
|
45
|
+
for (const [index, island] of islands.entries()) {
|
|
46
|
+
if (island.start < start || island.end > end) continue;
|
|
47
|
+
append(source.slice(cursor, island.start), cursor, island.start);
|
|
48
|
+
const echo = /^<\?=|^<\?php\s+(?:echo|print)\b/i.test(island.text);
|
|
49
|
+
append(choices.get(island.start) ?? (echo ? `__mtc_php_${index}__` : island.text.replace(/[^\r\n]/g, ' ')), island.start, island.end, true, choices.has(island.start));
|
|
50
|
+
cursor = island.end;
|
|
51
|
+
}
|
|
52
|
+
append(source.slice(cursor, end), cursor, end);
|
|
53
|
+
function originalOffset(offset, side = 'start') {
|
|
54
|
+
const segment = segments.find(entry => offset >= entry.start && offset < entry.end);
|
|
55
|
+
if (!segment) return end;
|
|
56
|
+
if (segment.structural) return side === 'end' && offset !== segment.start ? segment.to : segment.from;
|
|
57
|
+
if (!segment.island || segment.end - segment.start === segment.to - segment.from) return segment.from + offset - segment.start;
|
|
58
|
+
// Nodes may surround a PHP value, but may not split the placeholder.
|
|
59
|
+
if (offset !== segment.start) throw new Error('JavaScript syntax splits a PHP expression');
|
|
60
|
+
return segment.from;
|
|
61
|
+
}
|
|
62
|
+
return {code, originalOffset};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function parseScript(source, islands, start, end, options) {
|
|
66
|
+
const parse = (choices, semicolons) => {
|
|
67
|
+
const prepared = placeholderSource(source, islands, start, end, choices, semicolons);
|
|
68
|
+
return {...prepared, ast: babel.parseSync(prepared.code, options)};
|
|
69
|
+
};
|
|
70
|
+
let original, originalError;
|
|
71
|
+
try { original = parse(new Map()); } catch (error) { originalError = error; }
|
|
72
|
+
// PHP can select an initializer: `const x = <?php if ... ?> value
|
|
73
|
+
// <?php else: ?> otherValue <?php endif; ?>`. Represent those islands
|
|
74
|
+
// as a conditional only for parsing. Their original PHP is retained in
|
|
75
|
+
// the output and their server-side branches receive no JS counters.
|
|
76
|
+
const stack = [], groups = [];
|
|
77
|
+
for (const island of islands.filter(entry => entry.start >= start && entry.end <= end)) {
|
|
78
|
+
const tokens = new PhpParser().tokenGetAll(island.text).filter(token => !Array.isArray(token)
|
|
79
|
+
|| !['T_OPEN_TAG', 'T_CLOSE_TAG', 'T_WHITESPACE', 'T_COMMENT', 'T_DOC_COMMENT'].includes(token[0]));
|
|
80
|
+
const first = Array.isArray(tokens[0]) ? tokens[0][0] : tokens[0];
|
|
81
|
+
if (first === 'T_IF' && tokens.at(-1) === ':') stack.push({begin: island});
|
|
82
|
+
else if (first === 'T_ELSEIF' && stack.length) stack.at(-1).unsupported = true;
|
|
83
|
+
else if (first === 'T_ELSE' && tokens.length === 2 && tokens[1] === ':' && stack.length) stack.at(-1).alternate = island;
|
|
84
|
+
else if (first === 'T_ENDIF' && tokens.length <= 2 && stack.length) {
|
|
85
|
+
const group = {...stack.pop(), end: island};
|
|
86
|
+
if (group.alternate && !group.unsupported) groups.push(group);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// ASI can make two alternative values parse as a declaration plus a labeled
|
|
90
|
+
// block. Check every candidate, including candidates that fix a syntax error.
|
|
91
|
+
function crossings(parsed) {
|
|
92
|
+
const crossing = new Set();
|
|
93
|
+
babel.types.traverseFast(parsed.ast, node => {
|
|
94
|
+
if (!babel.types.isStatement(node)) return;
|
|
95
|
+
const effectiveEnd = node.expression?.end ?? node.declarations?.at(-1)?.end ?? node.argument?.end ?? node.end;
|
|
96
|
+
const from = parsed.originalOffset(node.start), to = parsed.originalOffset(effectiveEnd, 'end');
|
|
97
|
+
for (const group of groups) if (from < group.begin.start && to > group.begin.end && to < group.end.end) crossing.add(group);
|
|
98
|
+
});
|
|
99
|
+
return crossing;
|
|
100
|
+
}
|
|
101
|
+
let candidates = groups;
|
|
102
|
+
if (original) {
|
|
103
|
+
const crossing = crossings(original);
|
|
104
|
+
if (!crossing.size) return original;
|
|
105
|
+
candidates = [...crossing];
|
|
106
|
+
originalError = new Error('PHP conditional crosses a JavaScript statement boundary');
|
|
107
|
+
}
|
|
108
|
+
const selections = [...(candidates.length > 1 ? [candidates] : []), ...candidates.map(group => [group])];
|
|
109
|
+
for (const selection of selections) {
|
|
110
|
+
const choices = new Map(), semicolons = new Set();
|
|
111
|
+
for (const group of selection) {
|
|
112
|
+
choices.set(group.begin.start, `(__mtc_choice_${group.begin.start}__?`);
|
|
113
|
+
choices.set(group.alternate.start, ':');
|
|
114
|
+
choices.set(group.end.start, ')');
|
|
115
|
+
for (const boundary of [group.alternate.start, group.end.start]) {
|
|
116
|
+
const prefix = source.slice(0, boundary).trimEnd();
|
|
117
|
+
if (prefix.endsWith(';')) semicolons.add(prefix.length - 1);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const parsed = parse(choices, semicolons);
|
|
122
|
+
if (!crossings(parsed).size) return parsed;
|
|
123
|
+
} catch { /* Preserve the first useful syntax diagnostic. */ }
|
|
124
|
+
}
|
|
125
|
+
// PHP can also select whole declarations with the same lexical name.
|
|
126
|
+
// Separate their parse-time scopes without adding browser-side branches.
|
|
127
|
+
for (const selection of selections) {
|
|
128
|
+
const choices = new Map();
|
|
129
|
+
for (const group of selection) {
|
|
130
|
+
choices.set(group.begin.start, `if(__mtc_statements_${group.begin.start}_${group.alternate.start}_${group.end.start}__){`);
|
|
131
|
+
choices.set(group.alternate.start, '}else{');
|
|
132
|
+
choices.set(group.end.start, '}');
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
const parsed = parse(choices);
|
|
136
|
+
if (!crossings(parsed).size) return parsed;
|
|
137
|
+
} catch { /* Preserve the original diagnostic for unsupported PHP shapes. */ }
|
|
138
|
+
}
|
|
139
|
+
throw originalError;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Istanbul supplies the counters and coverage maps. Replay only its AST edits
|
|
143
|
+
// against the original text; never regenerate PHP, strings, comments or layout.
|
|
144
|
+
// This preserves PHP execution and every source newline used by PCOV.
|
|
145
|
+
function instrumentScript(source, islands, start, end, filename, module, templateId, scriptId) {
|
|
146
|
+
const parserOptions = {configFile: false, babelrc: false, sourceType: module ? 'module' : 'script', parserOpts: {createParenthesizedExpressions: true}};
|
|
147
|
+
const {ast, originalOffset} = parseScript(source, islands, start, end, parserOptions);
|
|
148
|
+
const snapshots = new WeakMap(), generated = [], traced = new Map(), serverBlocks = new WeakMap();
|
|
149
|
+
const lineStarts = [0];
|
|
150
|
+
for (let index = 0; index < source.length; index++) if (source[index] === '\n' || source[index] === '\r' && source[index + 1] !== '\n') lineStarts.push(index + 1);
|
|
151
|
+
const position = offset => {
|
|
152
|
+
let lo = 0, hi = lineStarts.length;
|
|
153
|
+
while (lo + 1 < hi) { const mid = (lo + hi) >> 1; if (lineStarts[mid] <= offset) lo = mid; else hi = mid; }
|
|
154
|
+
return {line: lo + 1, column: offset - lineStarts[lo]};
|
|
155
|
+
};
|
|
156
|
+
function snapshot(node) {
|
|
157
|
+
if (!node || snapshots.has(node)) return;
|
|
158
|
+
const opaque = node.type === 'ExpressionStatement' && node.expression.type === 'Identifier' && /^__mtc_php_\d+__$/.test(node.expression.name);
|
|
159
|
+
const serverIf = node.type === 'IfStatement' && /^__mtc_statements_(\d+)_(\d+)_(\d+)__$/.exec(node.test.name || '');
|
|
160
|
+
if (serverIf) {
|
|
161
|
+
const [begin, alternate, end] = serverIf.slice(1).map(offset => islands.find(island => island.start === Number(offset)));
|
|
162
|
+
serverBlocks.set(node.consequent, {start: begin.end, end: alternate.start});
|
|
163
|
+
serverBlocks.set(node.alternate, {start: alternate.end, end: end.start});
|
|
164
|
+
}
|
|
165
|
+
const serverChoice = node.type === 'ConditionalExpression' && node.test.type === 'Identifier' && /^__mtc_choice_\d+__$/.test(node.test.name);
|
|
166
|
+
const keys = babel.types.VISITOR_KEYS[node.type] || [];
|
|
167
|
+
const children = Object.fromEntries(keys.map(key => [key, Array.isArray(node[key]) ? [...node[key]] : node[key]]));
|
|
168
|
+
if (node.start !== undefined) {
|
|
169
|
+
const serverBlock = serverBlocks.get(node);
|
|
170
|
+
node.start = serverBlock?.start ?? originalOffset(node.start);
|
|
171
|
+
node.end = serverBlock?.end ?? originalOffset(node.end, 'end');
|
|
172
|
+
node.loc = {start: position(node.start), end: position(node.end)};
|
|
173
|
+
if (opaque) {
|
|
174
|
+
const id = `${scriptId}:g:${generated.length}`;
|
|
175
|
+
const island = islands.find(item => item.start === node.start);
|
|
176
|
+
const replacement = island && traceGeneratedOutput(island.text, templateId, id);
|
|
177
|
+
if (replacement) traced.set(island.start, {end: island.end, replacement});
|
|
178
|
+
generated.push({id, line: node.loc.start.line, tracked: !!replacement,
|
|
179
|
+
reason: replacement ? 'PHP output has not been observed; child-template attribution is unresolved.' : 'This PHP output expression cannot be traced; JavaScript source attribution is unresolved.'});
|
|
180
|
+
node.loc = null;
|
|
181
|
+
}
|
|
182
|
+
if (serverChoice || serverIf || serverBlock) node.loc = null;
|
|
183
|
+
}
|
|
184
|
+
snapshots.set(node, {start: node.start, end: node.end, children});
|
|
185
|
+
for (const child of Object.values(children).flat()) snapshot(child);
|
|
186
|
+
}
|
|
187
|
+
snapshot(ast);
|
|
188
|
+
let coverage, coverageName;
|
|
189
|
+
babel.traverse(ast, {Program(program) {
|
|
190
|
+
const visitor = programVisitor(babel.types, filename, {coverageGlobalScope: 'window', coverageGlobalScopeFunc: false});
|
|
191
|
+
visitor.enter(program);
|
|
192
|
+
program.traverse({VariableDeclarator(declaration) {
|
|
193
|
+
const init = declaration.get('init');
|
|
194
|
+
if (init.node?.type !== 'SequenceExpression') return;
|
|
195
|
+
const value = init.node.expressions.at(-1);
|
|
196
|
+
if (value.type !== 'ParenthesizedExpression' || value.expression.type !== 'ConditionalExpression'
|
|
197
|
+
|| !/^__mtc_choice_\d+__$/.test(value.expression.test.name || '')) return;
|
|
198
|
+
const statement = declaration.parentPath;
|
|
199
|
+
if (!statement.isVariableDeclaration() || !statement.inList) throw new Error('PHP-selected initializers in loop headers are unsupported');
|
|
200
|
+
// Each PHP branch may already terminate the declaration with a
|
|
201
|
+
// semicolon. Hoisting avoids wrapping those semicolons in a JS
|
|
202
|
+
// comma expression and preserves inferred function/class names.
|
|
203
|
+
statement.insertBefore(init.node.expressions.slice(0, -1).map(expression => babel.types.expressionStatement(expression)));
|
|
204
|
+
init.replaceWith(value);
|
|
205
|
+
}});
|
|
206
|
+
coverage = visitor.exit(program).fileCoverage;
|
|
207
|
+
coverageName = program.node.body.find(node => !snapshots.has(node) && node.type === 'FunctionDeclaration')?.id.name;
|
|
208
|
+
program.stop();
|
|
209
|
+
}});
|
|
210
|
+
function templateCounter(node) {
|
|
211
|
+
if (node?.type !== 'UpdateExpression' || node.operator !== '++') return;
|
|
212
|
+
let member = node.argument, branch;
|
|
213
|
+
if (member.object?.object?.property?.name === 'b') {
|
|
214
|
+
branch = member.property.value;
|
|
215
|
+
member = member.object;
|
|
216
|
+
}
|
|
217
|
+
const group = member.object?.property?.name;
|
|
218
|
+
if (!['s', 'f', 'b'].includes(group) || member.object.object?.callee?.name !== coverageName) return;
|
|
219
|
+
const id = `${scriptId}:${group}:${member.property.value}${branch === undefined ? '' : ':' + branch}`;
|
|
220
|
+
return babel.parseSync(`(${hit(templateId, id)})`, {configFile: false, babelrc: false}).program.body[0].expression;
|
|
221
|
+
}
|
|
222
|
+
function replaceCounters(node) {
|
|
223
|
+
const replacement = templateCounter(node);
|
|
224
|
+
if (replacement) return replacement;
|
|
225
|
+
for (const key of babel.types.VISITOR_KEYS[node.type] || []) {
|
|
226
|
+
if (Array.isArray(node[key])) node[key] = node[key].map(replaceCounters);
|
|
227
|
+
else if (node[key]) node[key] = replaceCounters(node[key]);
|
|
228
|
+
}
|
|
229
|
+
return node;
|
|
230
|
+
}
|
|
231
|
+
function render(node) {
|
|
232
|
+
const old = snapshots.get(node);
|
|
233
|
+
const trace = old && traced.get(old.start);
|
|
234
|
+
if (trace && node.type === 'ExpressionStatement') return trace.replacement + source.slice(trace.end, old.end);
|
|
235
|
+
if (!old) {
|
|
236
|
+
// Use the template collector directly; never create an Istanbul global
|
|
237
|
+
// or send template counters to the consuming application's JS report.
|
|
238
|
+
if (node.type === 'FunctionDeclaration' && node.id.name === coverageName ||
|
|
239
|
+
node.type === 'ExpressionStatement' && node.expression.type === 'CallExpression' && node.expression.callee.name === coverageName) return '';
|
|
240
|
+
switch (node.type) {
|
|
241
|
+
case 'BlockStatement': return `{${node.body.map(render).join('')}}`;
|
|
242
|
+
case 'ReturnStatement': return `return (${render(node.argument)});`;
|
|
243
|
+
case 'SequenceExpression': return `(${node.expressions.map(render).join(',')})`;
|
|
244
|
+
case 'ParenthesizedExpression': return `(${render(node.expression)})`;
|
|
245
|
+
default:
|
|
246
|
+
// All remaining generated nodes contain counters only. Do
|
|
247
|
+
// not silently regenerate any original child if Istanbul
|
|
248
|
+
// adds a new transformation in a future version.
|
|
249
|
+
babel.types.traverseFast(node, child => { if (snapshots.has(child)) throw new Error(`Unsupported Istanbul edit: ${node.type}`); });
|
|
250
|
+
return generate(replaceCounters(babel.types.cloneNode(node, true)), {compact: true, comments: false}).code.replace(/<\/script/gi, '<\\/script');
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const edits = [];
|
|
254
|
+
for (const [key, previous] of Object.entries(old.children)) {
|
|
255
|
+
const current = node[key];
|
|
256
|
+
if (Array.isArray(previous)) {
|
|
257
|
+
if (previous.some(child => !current.includes(child))) throw new Error(`Unsupported Istanbul list edit: ${node.type}.${key}`);
|
|
258
|
+
for (const child of previous) {
|
|
259
|
+
const text = render(child);
|
|
260
|
+
if (text !== source.slice(child.start, child.end)) edits.push({start: child.start, end: child.end, text});
|
|
261
|
+
}
|
|
262
|
+
for (let index = 0; index < current.length; index++) {
|
|
263
|
+
const child = current[index];
|
|
264
|
+
if (previous.includes(child)) continue;
|
|
265
|
+
const next = current.slice(index + 1).find(entry => previous.includes(entry));
|
|
266
|
+
let offset = next?.start ?? previous.at(-1)?.end;
|
|
267
|
+
const counterKind = child.expression?.argument?.object?.property?.name;
|
|
268
|
+
if (node.type === 'Program' && index < 2) {
|
|
269
|
+
offset = node.directives.at(-1)?.end ?? start;
|
|
270
|
+
} else if (node.type === 'BlockStatement' && (offset === undefined || ['f', 'b'].includes(counterKind))) offset = node.directives.at(-1)?.end ?? old.start + 1;
|
|
271
|
+
else if (offset === undefined && node.type === 'SwitchCase') {
|
|
272
|
+
const afterTest = node.test?.end ?? old.start + 'default'.length;
|
|
273
|
+
offset = source.indexOf(':', afterTest) + 1;
|
|
274
|
+
}
|
|
275
|
+
if (offset === undefined) throw new Error(`Unsupported empty Istanbul list: ${node.type}.${key}`);
|
|
276
|
+
edits.push({start: offset, end: offset, text: ';' + render(child)});
|
|
277
|
+
}
|
|
278
|
+
} else if (previous) {
|
|
279
|
+
const text = render(current);
|
|
280
|
+
if (text !== source.slice(previous.start, previous.end)) edits.push({start: previous.start, end: previous.end, text});
|
|
281
|
+
} else if (current) {
|
|
282
|
+
if (node.type !== 'IfStatement' || key !== 'alternate') throw new Error(`Unsupported Istanbul property: ${node.type}.${key}`);
|
|
283
|
+
edits.push({start: old.end, end: old.end, text: 'else ' + render(current)});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
edits.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
287
|
+
let result = '', cursor = old.start;
|
|
288
|
+
for (const edit of edits) {
|
|
289
|
+
if (edit.start < cursor || edit.end > old.end) throw new Error('Overlapping Istanbul edits');
|
|
290
|
+
result += source.slice(cursor, edit.start) + edit.text;
|
|
291
|
+
cursor = edit.end;
|
|
292
|
+
}
|
|
293
|
+
return result + source.slice(cursor, old.end);
|
|
294
|
+
}
|
|
295
|
+
const instrumented = render(ast.program);
|
|
296
|
+
if (instrumented.replace(/[^\r\n]/g, '') !== source.slice(start, end).replace(/[^\r\n]/g, '')) throw new Error('Instrumentation changed PHP line positions');
|
|
297
|
+
parseScript(instrumented, phpIslands(instrumented), 0, instrumented.length, parserOptions);
|
|
298
|
+
return {code: instrumented, coverage, generated};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function instrumentInline(source, templateId, {phtml = false} = {}) {
|
|
302
|
+
const islands = phtml ? phpIslands(source) : [];
|
|
303
|
+
let masked = source;
|
|
304
|
+
for (const island of [...islands].reverse()) masked = masked.slice(0, island.start) + island.text.replace(/[^\r\n]/g, ' ') + masked.slice(island.end);
|
|
305
|
+
const edits = [], scripts = [], baseline = {}, replacements = [];
|
|
306
|
+
const statements = [], functions = [], branches = [];
|
|
307
|
+
const location = offset => {
|
|
308
|
+
const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
|
|
309
|
+
return {line: lines.length, column: lines.at(-1).length};
|
|
310
|
+
};
|
|
311
|
+
function region(from, to) {
|
|
312
|
+
const tree = parseFragment(masked.slice(from, to), {sourceCodeLocationInfo: true});
|
|
313
|
+
function visit(node) {
|
|
314
|
+
const span = node.sourceCodeLocation;
|
|
315
|
+
if (node.tagName === 'script' && span?.endTag) {
|
|
316
|
+
const start = from + span.startTag.endOffset, end = from + span.endTag.startOffset;
|
|
317
|
+
const attrs = Object.fromEntries(node.attrs.map(attr => [attr.name, attr.value]));
|
|
318
|
+
const type = (attrs.type || '').trim().toLowerCase();
|
|
319
|
+
if (['text/html', 'text/x-magento-template', 'text/x-jquery-tmpl', 'text/x-template'].includes(type)) {
|
|
320
|
+
region(start, end);
|
|
321
|
+
} else if (!('src' in attrs) && ['', 'module', 'text/javascript', 'application/javascript'].includes(type) && source.slice(start, end).trim()) {
|
|
322
|
+
const id = `script:${scripts.length + 1}`;
|
|
323
|
+
const record = {id, line: location(start).line};
|
|
324
|
+
try {
|
|
325
|
+
const result = instrumentScript(source, islands, start, end, `${templateId}/${id}`, type === 'module', templateId, id);
|
|
326
|
+
edits.push({start, end, text: result.code});
|
|
327
|
+
replacements.push({original: source.slice(from + span.startOffset, from + span.endOffset),
|
|
328
|
+
instrumented: source.slice(from + span.startOffset, start) + result.code + source.slice(end, from + span.endOffset)});
|
|
329
|
+
baseline[id] = result.coverage;
|
|
330
|
+
for (const [key, loc] of Object.entries(result.coverage.statementMap)) statements.push({id: `${id}:s:${key}`, binding: 'script statement', syntax: 'inline-script', ...loc});
|
|
331
|
+
for (const [key, fn] of Object.entries(result.coverage.fnMap)) functions.push({id: `${id}:f:${key}`, name: fn.name, ...fn.loc});
|
|
332
|
+
for (const [key, branch] of Object.entries(result.coverage.branchMap)) branch.locations.forEach((loc, index) => branches.push({id: `${id}:b:${key}:${index}`, type: branch.type, ...(Number.isInteger(loc.start?.line) ? loc : {...branch.loc, implicit: true})}));
|
|
333
|
+
scripts.push({...record, status: 'instrumented', generated: result.generated});
|
|
334
|
+
} catch (error) {
|
|
335
|
+
scripts.push({...record, status: 'unsupported', reason: error.message.split('\n')[0]});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
for (const child of node.childNodes || []) visit(child);
|
|
340
|
+
// A script in a native template is measured only when the application
|
|
341
|
+
// inserts/executes it. Merely parsing or caching it produces no hit.
|
|
342
|
+
if (node.content) visit(node.content);
|
|
343
|
+
}
|
|
344
|
+
visit(tree);
|
|
345
|
+
}
|
|
346
|
+
region(0, source.length);
|
|
347
|
+
let output = source;
|
|
348
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
|
|
349
|
+
return {code: output, baseline, scripts, replacements, statements, functions, branches};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
module.exports = {instrumentInline, phpIslands};
|