supercov 0.0.9 → 0.0.12

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.
Files changed (156) hide show
  1. package/README.md +28 -23
  2. package/bin/native.js +87 -0
  3. package/bin/supercov.js +10 -4
  4. package/package.json +39 -25
  5. package/{dist → runtime/javascript}/atomic.js +0 -1
  6. package/{dist → runtime/javascript}/launchSupervisor.js +3 -1
  7. package/{dist → runtime/javascript}/nodeAssert.js +0 -1
  8. package/{dist → runtime/javascript}/nodeAssertAdapter.js +0 -1
  9. package/{dist → runtime/javascript}/nodeAssertStrict.js +0 -1
  10. package/{dist → runtime/javascript}/nodeTest.js +13 -5
  11. package/{dist → runtime/javascript}/playwright.js +177 -90
  12. package/{dist → runtime/javascript}/playwrightReporter.js +0 -1
  13. package/{dist → runtime/javascript}/provenance.js +0 -1
  14. package/{dist → runtime/javascript}/register.mjs +52 -1
  15. package/{dist → runtime/javascript}/resolve-loader.mjs +0 -36
  16. package/{dist → runtime/javascript}/runnerEvidence.js +6 -5
  17. package/{dist → runtime/javascript}/runtime.js +308 -27
  18. package/{dist → runtime/javascript}/transport.js +2 -3
  19. package/{dist → runtime/javascript}/vitest.js +38 -8
  20. package/{dist → runtime/javascript}/vitestReporter.js +0 -1
  21. package/dist/agentJson.d.ts +0 -44
  22. package/dist/agentJson.d.ts.map +0 -1
  23. package/dist/agentJson.js +0 -84
  24. package/dist/agentJson.js.map +0 -1
  25. package/dist/analyze.d.ts +0 -12
  26. package/dist/analyze.d.ts.map +0 -1
  27. package/dist/analyze.js +0 -699
  28. package/dist/analyze.js.map +0 -1
  29. package/dist/atomic.d.ts +0 -6
  30. package/dist/atomic.d.ts.map +0 -1
  31. package/dist/atomic.js.map +0 -1
  32. package/dist/buildCache.d.ts +0 -14
  33. package/dist/buildCache.d.ts.map +0 -1
  34. package/dist/buildCache.js +0 -84
  35. package/dist/buildCache.js.map +0 -1
  36. package/dist/cli.d.ts +0 -2
  37. package/dist/cli.d.ts.map +0 -1
  38. package/dist/cli.js +0 -706
  39. package/dist/cli.js.map +0 -1
  40. package/dist/directInstrumenter.d.ts +0 -8
  41. package/dist/directInstrumenter.d.ts.map +0 -1
  42. package/dist/directInstrumenter.js +0 -92
  43. package/dist/directInstrumenter.js.map +0 -1
  44. package/dist/esmInterceptor.d.ts +0 -6
  45. package/dist/esmInterceptor.d.ts.map +0 -1
  46. package/dist/esmInterceptor.js +0 -63
  47. package/dist/esmInterceptor.js.map +0 -1
  48. package/dist/evidenceArchive.d.ts +0 -37
  49. package/dist/evidenceArchive.d.ts.map +0 -1
  50. package/dist/evidenceArchive.js +0 -110
  51. package/dist/evidenceArchive.js.map +0 -1
  52. package/dist/instrumenter.d.ts +0 -11
  53. package/dist/instrumenter.d.ts.map +0 -1
  54. package/dist/instrumenter.js +0 -1246
  55. package/dist/instrumenter.js.map +0 -1
  56. package/dist/integrity.d.ts +0 -10
  57. package/dist/integrity.d.ts.map +0 -1
  58. package/dist/integrity.js +0 -205
  59. package/dist/integrity.js.map +0 -1
  60. package/dist/launchSupervisor.d.ts +0 -38
  61. package/dist/launchSupervisor.d.ts.map +0 -1
  62. package/dist/launchSupervisor.js.map +0 -1
  63. package/dist/merge.d.ts +0 -2
  64. package/dist/merge.d.ts.map +0 -1
  65. package/dist/merge.js +0 -116
  66. package/dist/merge.js.map +0 -1
  67. package/dist/nodeAssert.d.ts +0 -31
  68. package/dist/nodeAssert.d.ts.map +0 -1
  69. package/dist/nodeAssert.js.map +0 -1
  70. package/dist/nodeAssertAdapter.d.ts +0 -6
  71. package/dist/nodeAssertAdapter.d.ts.map +0 -1
  72. package/dist/nodeAssertAdapter.js.map +0 -1
  73. package/dist/nodeAssertStrict.d.ts +0 -31
  74. package/dist/nodeAssertStrict.d.ts.map +0 -1
  75. package/dist/nodeAssertStrict.js.map +0 -1
  76. package/dist/nodeAssertionInstrumenter.d.ts +0 -8
  77. package/dist/nodeAssertionInstrumenter.d.ts.map +0 -1
  78. package/dist/nodeAssertionInstrumenter.js +0 -263
  79. package/dist/nodeAssertionInstrumenter.js.map +0 -1
  80. package/dist/nodeTest.d.ts +0 -15
  81. package/dist/nodeTest.d.ts.map +0 -1
  82. package/dist/nodeTest.js.map +0 -1
  83. package/dist/playwright.d.ts +0 -9
  84. package/dist/playwright.d.ts.map +0 -1
  85. package/dist/playwright.js.map +0 -1
  86. package/dist/playwrightReporter.d.ts +0 -6
  87. package/dist/playwrightReporter.d.ts.map +0 -1
  88. package/dist/playwrightReporter.js.map +0 -1
  89. package/dist/project.d.ts +0 -20
  90. package/dist/project.d.ts.map +0 -1
  91. package/dist/project.js +0 -296
  92. package/dist/project.js.map +0 -1
  93. package/dist/provenance.d.ts +0 -9
  94. package/dist/provenance.d.ts.map +0 -1
  95. package/dist/provenance.js.map +0 -1
  96. package/dist/query.d.ts +0 -70
  97. package/dist/query.d.ts.map +0 -1
  98. package/dist/query.js +0 -1443
  99. package/dist/query.js.map +0 -1
  100. package/dist/queryCache.d.ts +0 -15
  101. package/dist/queryCache.d.ts.map +0 -1
  102. package/dist/queryCache.js +0 -95
  103. package/dist/queryCache.js.map +0 -1
  104. package/dist/queueAdapters.d.ts +0 -15
  105. package/dist/queueAdapters.d.ts.map +0 -1
  106. package/dist/queueAdapters.js +0 -55
  107. package/dist/queueAdapters.js.map +0 -1
  108. package/dist/register.d.mts +0 -2
  109. package/dist/register.d.mts.map +0 -1
  110. package/dist/register.mjs.map +0 -1
  111. package/dist/reporter.d.ts +0 -13
  112. package/dist/reporter.d.ts.map +0 -1
  113. package/dist/reporter.js +0 -252
  114. package/dist/reporter.js.map +0 -1
  115. package/dist/resolve-loader.d.mts +0 -3
  116. package/dist/resolve-loader.d.mts.map +0 -1
  117. package/dist/resolve-loader.mjs.map +0 -1
  118. package/dist/runAnalysis.d.ts +0 -19
  119. package/dist/runAnalysis.d.ts.map +0 -1
  120. package/dist/runAnalysis.js +0 -169
  121. package/dist/runAnalysis.js.map +0 -1
  122. package/dist/runnerEvidence.d.ts +0 -19
  123. package/dist/runnerEvidence.d.ts.map +0 -1
  124. package/dist/runnerEvidence.js.map +0 -1
  125. package/dist/runtime.d.ts +0 -88
  126. package/dist/runtime.d.ts.map +0 -1
  127. package/dist/runtime.js.map +0 -1
  128. package/dist/runtimeIsolation.d.ts +0 -3
  129. package/dist/runtimeIsolation.d.ts.map +0 -1
  130. package/dist/runtimeIsolation.js +0 -9
  131. package/dist/runtimeIsolation.js.map +0 -1
  132. package/dist/sourceDiscovery.d.ts +0 -9
  133. package/dist/sourceDiscovery.d.ts.map +0 -1
  134. package/dist/sourceDiscovery.js +0 -238
  135. package/dist/sourceDiscovery.js.map +0 -1
  136. package/dist/transport.d.ts +0 -17
  137. package/dist/transport.d.ts.map +0 -1
  138. package/dist/transport.js.map +0 -1
  139. package/dist/types.d.ts +0 -378
  140. package/dist/types.d.ts.map +0 -1
  141. package/dist/types.js +0 -2
  142. package/dist/types.js.map +0 -1
  143. package/dist/vitePlugin.d.ts +0 -13
  144. package/dist/vitePlugin.d.ts.map +0 -1
  145. package/dist/vitePlugin.js +0 -125
  146. package/dist/vitePlugin.js.map +0 -1
  147. package/dist/vitest.d.ts +0 -2
  148. package/dist/vitest.d.ts.map +0 -1
  149. package/dist/vitest.js.map +0 -1
  150. package/dist/vitestReporter.d.ts +0 -43
  151. package/dist/vitestReporter.d.ts.map +0 -1
  152. package/dist/vitestReporter.js.map +0 -1
  153. package/dist/workspace.d.ts +0 -81
  154. package/dist/workspace.d.ts.map +0 -1
  155. package/dist/workspace.js +0 -504
  156. package/dist/workspace.js.map +0 -1
@@ -1,1246 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import generate from "@babel/generator";
3
- import { parse } from "@babel/parser";
4
- import traverse from "@babel/traverse";
5
- import * as t from "@babel/types";
6
- const RUNTIME_MODULE = "virtual:supercov-runtime";
7
- const BEGIN = "__supercovMcdcBegin";
8
- const CONDITION = "__supercovMcdcCondition";
9
- const END = "__supercovMcdcEnd";
10
- const HIT = "__supercovCoverageHit";
11
- const SELECTION_BEGIN = "__supercovSelectionBegin";
12
- const SELECTION_RIGHT = "__supercovSelectionRight";
13
- const SELECTION_END = "__supercovSelectionEnd";
14
- const WITH_REQUEST_PHASE = "__supercovWithRequestPhase";
15
- const OPTIONAL_SELECT = "__supercovOptionalSelect";
16
- const OPTIONAL_CALL_BEGIN = "__supercovOptionalCallBegin";
17
- const OPTIONAL_CALL_REACHED = "__supercovOptionalCallReached";
18
- const OPTIONAL_CALL_CONTINUED = "__supercovOptionalCallContinued";
19
- const OPTIONAL_CALL_END = "__supercovOptionalCallEnd";
20
- const DEFAULT_SELECTED = "__supercovDefaultSelected";
21
- const DEFAULT_ENTERED = "__supercovDefaultEntered";
22
- const TRY_BEGIN = "__supercovTryBegin";
23
- const TRY_CATCH = "__supercovTryCatch";
24
- const TRY_END = "__supercovTryEnd";
25
- const LOOP_BEGIN = "__supercovLoopBegin";
26
- const LOOP_ENTERED = "__supercovLoopEntered";
27
- const LOOP_END = "__supercovLoopEnd";
28
- function isRequestHandlerName(file, name) {
29
- if (name === "loader" || name === "action")
30
- return /^app\/routes\//.test(file);
31
- return (/(?:^|\/)app\/.*\/route\.[cm]?[jt]sx?$/.test(file) &&
32
- ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"].includes(name ?? ""));
33
- }
34
- function sourceFor(code, node) {
35
- if (node.start !== null &&
36
- node.start !== undefined &&
37
- node.end !== null &&
38
- node.end !== undefined) {
39
- return code.slice(node.start, node.end);
40
- }
41
- return generate(node).code;
42
- }
43
- function stableId(file, kind, node, suffix = "") {
44
- return createHash("sha256")
45
- .update(`${file}:${kind}:${node.start ?? 0}:${node.end ?? 0}:${suffix}`)
46
- .digest("hex")
47
- .slice(0, 16);
48
- }
49
- function hasCompoundBooleanDecision(node) {
50
- if (t.isLogicalExpression(node) &&
51
- (node.operator === "&&" || node.operator === "||")) {
52
- return true;
53
- }
54
- return (t.isUnaryExpression(node, { operator: "!" }) &&
55
- hasCompoundBooleanDecision(node.argument));
56
- }
57
- function collectConditions(node, conditions) {
58
- if (t.isLogicalExpression(node) &&
59
- (node.operator === "&&" || node.operator === "||")) {
60
- collectConditions(node.left, conditions);
61
- collectConditions(node.right, conditions);
62
- return;
63
- }
64
- if (t.isUnaryExpression(node, { operator: "!" }) &&
65
- hasCompoundBooleanDecision(node.argument)) {
66
- collectConditions(node.argument, conditions);
67
- return;
68
- }
69
- conditions.push(node);
70
- }
71
- function instrumentConditions(node, frameId, nextIndex, decisionLogicalNodes, conditionRuntimeName) {
72
- if (t.isLogicalExpression(node) &&
73
- (node.operator === "&&" || node.operator === "||")) {
74
- const logical = t.logicalExpression(node.operator, instrumentConditions(node.left, frameId, nextIndex, decisionLogicalNodes, conditionRuntimeName), instrumentConditions(node.right, frameId, nextIndex, decisionLogicalNodes, conditionRuntimeName));
75
- decisionLogicalNodes.add(logical);
76
- return logical;
77
- }
78
- if (t.isUnaryExpression(node, { operator: "!" }) &&
79
- hasCompoundBooleanDecision(node.argument)) {
80
- return t.unaryExpression("!", instrumentConditions(node.argument, frameId, nextIndex, decisionLogicalNodes, conditionRuntimeName), true);
81
- }
82
- const index = nextIndex.value;
83
- nextIndex.value += 1;
84
- return t.callExpression(t.identifier(conditionRuntimeName), [
85
- t.cloneNode(frameId),
86
- t.numericLiteral(index),
87
- node,
88
- ]);
89
- }
90
- function hitStatement(id, hitRuntimeName) {
91
- return t.expressionStatement(t.callExpression(t.identifier(hitRuntimeName), [t.stringLiteral(id)]));
92
- }
93
- function allocatedRuntimeNames(code) {
94
- const preferred = [
95
- BEGIN,
96
- CONDITION,
97
- END,
98
- HIT,
99
- SELECTION_BEGIN,
100
- SELECTION_RIGHT,
101
- SELECTION_END,
102
- WITH_REQUEST_PHASE,
103
- OPTIONAL_SELECT,
104
- OPTIONAL_CALL_BEGIN,
105
- OPTIONAL_CALL_REACHED,
106
- OPTIONAL_CALL_CONTINUED,
107
- OPTIONAL_CALL_END,
108
- DEFAULT_SELECTED,
109
- DEFAULT_ENTERED,
110
- TRY_BEGIN,
111
- TRY_CATCH,
112
- TRY_END,
113
- LOOP_BEGIN,
114
- LOOP_ENTERED,
115
- LOOP_END,
116
- ];
117
- const names = {};
118
- const used = new Set();
119
- for (const base of preferred) {
120
- let candidate = base;
121
- while (used.has(candidate) || code.includes(candidate))
122
- candidate = `_${candidate}`;
123
- names[base] = candidate;
124
- used.add(candidate);
125
- }
126
- return names;
127
- }
128
- function functionLabel(path) {
129
- if ("id" in path.node && t.isIdentifier(path.node.id))
130
- return path.node.id.name;
131
- const parent = path.parentPath;
132
- if (parent.isObjectProperty() ||
133
- parent.isObjectMethod() ||
134
- parent.isClassMethod()) {
135
- const key = parent.node.key;
136
- if (t.isIdentifier(key))
137
- return key.name;
138
- if (t.isStringLiteral(key))
139
- return key.value;
140
- }
141
- if (parent.isVariableDeclarator() && t.isIdentifier(parent.node.id))
142
- return parent.node.id.name;
143
- return undefined;
144
- }
145
- function isExecutableStatement(node) {
146
- if (t.isBlockStatement(node) ||
147
- t.isEmptyStatement(node) ||
148
- t.isFunctionDeclaration(node) ||
149
- node.type.startsWith("TS")) {
150
- return false;
151
- }
152
- return !("declare" in node && node.declare === true);
153
- }
154
- function isAnonymousFunctionDefinition(node) {
155
- return (t.isArrowFunctionExpression(node) ||
156
- (t.isFunctionExpression(node) && node.id === null) ||
157
- (t.isClassExpression(node) && node.id === null));
158
- }
159
- function isSourceSensitiveFunction(path) {
160
- let child = path;
161
- for (let parent = path.parentPath; parent; parent = parent.parentPath) {
162
- const candidate = parent.node;
163
- const value = child.node;
164
- if ((t.isParenthesizedExpression(candidate) ||
165
- t.isTSAsExpression(candidate) ||
166
- t.isTSTypeAssertion(candidate) ||
167
- t.isTSNonNullExpression(candidate)) &&
168
- candidate.expression === value) {
169
- child = parent;
170
- continue;
171
- }
172
- if ((t.isConditionalExpression(candidate) &&
173
- (candidate.consequent === value || candidate.alternate === value)) ||
174
- (t.isLogicalExpression(candidate) &&
175
- (candidate.left === value || candidate.right === value)) ||
176
- (t.isSequenceExpression(candidate) &&
177
- candidate.expressions.at(-1) === value) ||
178
- (t.isAssignmentExpression(candidate) && candidate.right === value)) {
179
- child = parent;
180
- continue;
181
- }
182
- if (((t.isClassMethod(candidate) ||
183
- t.isClassProperty(candidate) ||
184
- t.isObjectMethod(candidate) ||
185
- t.isObjectProperty(candidate)) &&
186
- candidate.computed &&
187
- candidate.key === value) ||
188
- ((t.isMemberExpression(candidate) ||
189
- t.isOptionalMemberExpression(candidate)) &&
190
- candidate.computed &&
191
- candidate.property === value))
192
- return true;
193
- if (t.isCallExpression(candidate) &&
194
- t.isIdentifier(candidate.callee, { name: "String" }) &&
195
- candidate.arguments.includes(value))
196
- return true;
197
- if (t.isBinaryExpression(candidate) &&
198
- ["+", "<", "<=", ">", ">="].includes(candidate.operator) &&
199
- (candidate.left === value || candidate.right === value))
200
- return true;
201
- if ((t.isMemberExpression(candidate) ||
202
- t.isOptionalMemberExpression(candidate)) &&
203
- !candidate.computed &&
204
- t.isIdentifier(candidate.property, { name: "toString" }) &&
205
- candidate.object === value)
206
- return true;
207
- // Any other operation consumes or stores the function value. Static
208
- // ancestry can no longer prove that this exact function is coerced.
209
- return false;
210
- }
211
- return false;
212
- }
213
- function isInsideWithStatement(path) {
214
- return Boolean(path.findParent((parent) => parent.isWithStatement()));
215
- }
216
- function isInsideFunctionParameter(path) {
217
- let current = path;
218
- while (current?.parentPath) {
219
- if (current.parentPath.isFunction())
220
- return current.listKey === "params";
221
- current = current.parentPath;
222
- }
223
- return false;
224
- }
225
- export function instrumentMcdc(code, file) {
226
- const names = allocatedRuntimeNames(code);
227
- const BEGIN = names["__supercovMcdcBegin"];
228
- const CONDITION = names["__supercovMcdcCondition"];
229
- const END = names["__supercovMcdcEnd"];
230
- const HIT = names["__supercovCoverageHit"];
231
- const SELECTION_BEGIN = names["__supercovSelectionBegin"];
232
- const SELECTION_RIGHT = names["__supercovSelectionRight"];
233
- const SELECTION_END = names["__supercovSelectionEnd"];
234
- const WITH_REQUEST_PHASE = names["__supercovWithRequestPhase"];
235
- const OPTIONAL_SELECT = names["__supercovOptionalSelect"];
236
- const OPTIONAL_CALL_BEGIN = names["__supercovOptionalCallBegin"];
237
- const OPTIONAL_CALL_REACHED = names["__supercovOptionalCallReached"];
238
- const OPTIONAL_CALL_CONTINUED = names["__supercovOptionalCallContinued"];
239
- const OPTIONAL_CALL_END = names["__supercovOptionalCallEnd"];
240
- const DEFAULT_SELECTED = names["__supercovDefaultSelected"];
241
- const DEFAULT_ENTERED = names["__supercovDefaultEntered"];
242
- const TRY_BEGIN = names["__supercovTryBegin"];
243
- const TRY_CATCH = names["__supercovTryCatch"];
244
- const TRY_END = names["__supercovTryEnd"];
245
- const LOOP_BEGIN = names["__supercovLoopBegin"];
246
- const LOOP_ENTERED = names["__supercovLoopEntered"];
247
- const LOOP_END = names["__supercovLoopEnd"];
248
- const parserPlugins = [
249
- "typescript",
250
- "decorators-legacy",
251
- "sourcePhaseImports",
252
- ...(file.endsWith("x") ? ["jsx"] : []),
253
- ];
254
- const ast = parse(code, {
255
- sourceType: "unambiguous",
256
- sourceFilename: file,
257
- errorRecovery: true,
258
- plugins: parserPlugins,
259
- });
260
- const decisions = [];
261
- const points = [];
262
- const branches = [];
263
- const limitations = [];
264
- const generatedStatements = new WeakSet();
265
- const decisionLogicalNodes = new WeakSet();
266
- let usesRequestPhaseHandler = false;
267
- // Instrumentation necessarily changes a function's source text. When code
268
- // directly observes or coerces that source, keep the entire function body
269
- // untouched and report the resulting coverage boundary explicitly.
270
- const sourceSensitiveFunctions = new WeakSet();
271
- traverse(ast, {
272
- Function(path) {
273
- if (!isSourceSensitiveFunction(path))
274
- return;
275
- sourceSensitiveFunctions.add(path.node);
276
- if (!path.node.loc)
277
- return;
278
- limitations.push({
279
- id: stableId(file, "semantic-safety", path.node, "function-source"),
280
- kind: "semantic-safety",
281
- file,
282
- line: path.node.loc.start.line,
283
- column: path.node.loc.start.column + 1,
284
- source: sourceFor(code, path.node),
285
- reason: "function body is left uninstrumented because this expression observes or coerces Function source text",
286
- });
287
- },
288
- });
289
- const isWithinSourceSensitiveFunction = (path) => (path.isFunction() && sourceSensitiveFunctions.has(path.node)) ||
290
- Boolean(path.findParent((parent) => parent.isFunction() && sourceSensitiveFunctions.has(parent.node)));
291
- traverse(ast, {
292
- WithStatement(path) {
293
- if (!path.node.loc)
294
- return;
295
- limitations.push({
296
- id: stableId(file, "semantic-safety", path.node, "with-environment"),
297
- kind: "semantic-safety",
298
- file,
299
- line: path.node.loc.start.line,
300
- column: path.node.loc.start.column + 1,
301
- source: sourceFor(code, path.node),
302
- reason: "with-statement body is left uninstrumented because its object environment can intercept probe identifiers",
303
- });
304
- },
305
- });
306
- const isUnsafeInstrumentationContext = (path) => isWithinSourceSensitiveFunction(path) || isInsideWithStatement(path);
307
- // Record executable statements before adding any instrumentation statements.
308
- traverse(ast, {
309
- Statement(path) {
310
- const node = path.node;
311
- if (!node.loc ||
312
- isUnsafeInstrumentationContext(path) ||
313
- generatedStatements.has(node) ||
314
- !isExecutableStatement(node))
315
- return;
316
- if (path.parentPath.isLabeledStatement())
317
- return;
318
- const id = stableId(file, "statement", node);
319
- points.push({
320
- id,
321
- kind: "statement",
322
- file,
323
- line: node.loc.start.line,
324
- column: node.loc.start.column + 1,
325
- source: sourceFor(code, node),
326
- });
327
- const probe = hitStatement(id, HIT);
328
- generatedStatements.add(probe);
329
- if (path.parentPath.isProgram() ||
330
- path.parentPath.isBlockStatement() ||
331
- path.parentPath.isSwitchCase()) {
332
- path.insertBefore(probe);
333
- return;
334
- }
335
- // Bare control-flow bodies become blocks. This preserves dangling-else,
336
- // break, continue, return, and throw semantics while giving the body an
337
- // independently observable statement entry.
338
- if (path.key === "body" ||
339
- path.key === "consequent" ||
340
- path.key === "alternate") {
341
- path.replaceWith(t.blockStatement([probe, node]));
342
- path.skip();
343
- }
344
- },
345
- });
346
- // Optional links are measured at the exact nullish operand. Unlike checking
347
- // the chain's final value, this remains accurate when a successful property
348
- // access or function call legitimately returns undefined.
349
- const instrumentOptionalOperand = (path, operand) => {
350
- const node = path.node;
351
- if (!node.loc)
352
- return operand;
353
- const id = stableId(file, "optional-chain", node);
354
- const shortId = `${id}:short`;
355
- const continuedId = `${id}:continued`;
356
- branches.push({
357
- id,
358
- kind: "optional-chain",
359
- file,
360
- line: node.loc.start.line,
361
- column: node.loc.start.column + 1,
362
- source: sourceFor(code, node),
363
- alternatives: [
364
- { id: shortId, label: "nullish / short-circuited" },
365
- { id: continuedId, label: "non-nullish / continued" },
366
- ],
367
- });
368
- return t.callExpression(t.identifier(OPTIONAL_SELECT), [
369
- t.stringLiteral(shortId),
370
- t.stringLiteral(continuedId),
371
- operand,
372
- ]);
373
- };
374
- traverse(ast, {
375
- OptionalMemberExpression(path) {
376
- if (isUnsafeInstrumentationContext(path))
377
- return;
378
- if (!path.node.optional || !t.isExpression(path.node.object))
379
- return;
380
- path.node.object = instrumentOptionalOperand(path, path.node.object);
381
- },
382
- });
383
- const optionalCallChains = new Map();
384
- traverse(ast, {
385
- OptionalCallExpression(path) {
386
- if (isUnsafeInstrumentationContext(path) ||
387
- !path.node.optional ||
388
- !path.node.loc ||
389
- !t.isExpression(path.node.callee))
390
- return;
391
- const callee = path.node.callee;
392
- if (t.isOptionalMemberExpression(callee) &&
393
- t.isPrivateName(callee.property)) {
394
- limitations.push({
395
- id: stableId(file, "semantic-safety", path.node, "optional-private-call"),
396
- kind: "semantic-safety",
397
- file,
398
- line: path.node.loc.start.line,
399
- column: path.node.loc.start.column + 1,
400
- source: sourceFor(code, path.node),
401
- reason: "optional private-method calls are left native because private names cannot be wrapped as computed reference keys",
402
- });
403
- return;
404
- }
405
- let root = path;
406
- while ((root.parentPath.isOptionalCallExpression() &&
407
- root.parentPath.node.callee === root.node) ||
408
- (root.parentPath.isOptionalMemberExpression() &&
409
- root.parentPath.node.object === root.node))
410
- root = root.parentPath;
411
- if (root.parentPath.isUnaryExpression({ operator: "delete" }) &&
412
- root.parentPath.node.argument === root.node)
413
- root = root.parentPath;
414
- const id = stableId(file, "optional-chain", path.node, "call");
415
- const shortId = `${id}:short`;
416
- const continuedId = `${id}:continued`;
417
- branches.push({
418
- id,
419
- kind: "optional-chain",
420
- file,
421
- line: path.node.loc.start.line,
422
- column: path.node.loc.start.column + 1,
423
- source: sourceFor(code, path.node),
424
- alternatives: [
425
- { id: shortId, label: "nullish / short-circuited" },
426
- { id: continuedId, label: "non-nullish / continued" },
427
- ],
428
- });
429
- const chain = optionalCallChains.get(root.node) ?? {
430
- path: root,
431
- sites: [],
432
- };
433
- chain.sites.push({
434
- node: path.node,
435
- frame: root.scope.generateUidIdentifier("optionalCall"),
436
- shortId,
437
- continuedId,
438
- });
439
- optionalCallChains.set(root.node, chain);
440
- },
441
- });
442
- for (const chain of optionalCallChains.values()) {
443
- for (const site of chain.sites) {
444
- chain.path.scope.push({ id: t.cloneNode(site.frame), kind: "let" });
445
- const callee = site.node.callee;
446
- if (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) {
447
- if (t.isPrivateName(callee.property)) {
448
- if (t.isExpression(callee.object))
449
- callee.object = t.callExpression(t.identifier(OPTIONAL_CALL_REACHED), [t.cloneNode(site.frame), callee.object]);
450
- continue;
451
- }
452
- const property = callee.computed
453
- ? callee.property
454
- : t.isIdentifier(callee.property)
455
- ? t.stringLiteral(callee.property.name)
456
- : callee.property;
457
- callee.computed = true;
458
- callee.property = t.callExpression(t.identifier(OPTIONAL_CALL_REACHED), [t.cloneNode(site.frame), property]);
459
- }
460
- else {
461
- site.node.callee = t.callExpression(t.identifier(OPTIONAL_CALL_REACHED), [t.cloneNode(site.frame), callee]);
462
- }
463
- site.node.arguments.unshift(t.spreadElement(t.callExpression(t.identifier(OPTIONAL_CALL_CONTINUED), [
464
- t.cloneNode(site.frame),
465
- ])));
466
- }
467
- let measured = chain.path.node;
468
- for (const site of [...chain.sites].reverse())
469
- measured = t.callExpression(t.identifier(OPTIONAL_CALL_END), [
470
- t.cloneNode(site.frame),
471
- measured,
472
- ]);
473
- chain.path.replaceWith(t.sequenceExpression([
474
- ...chain.sites.map((site) => t.assignmentExpression("=", t.cloneNode(site.frame), t.callExpression(t.identifier(OPTIONAL_CALL_BEGIN), [
475
- t.stringLiteral(site.shortId),
476
- t.stringLiteral(site.continuedId),
477
- ]))),
478
- measured,
479
- ]));
480
- }
481
- // Logical assignments have the same short/right split as value-selection
482
- // expressions, but wrapping only the RHS preserves one-time LHS evaluation.
483
- traverse(ast, {
484
- AssignmentExpression: {
485
- exit(path) {
486
- if (isUnsafeInstrumentationContext(path))
487
- return;
488
- const node = path.node;
489
- if (!node.loc ||
490
- (node.operator !== "&&=" &&
491
- node.operator !== "||=" &&
492
- node.operator !== "??="))
493
- return;
494
- const id = stableId(file, "logical-assignment", node, node.operator);
495
- const shortId = `${id}:short`;
496
- const rightId = `${id}:right`;
497
- branches.push({
498
- id,
499
- kind: "logical-assignment",
500
- file,
501
- line: node.loc.start.line,
502
- column: node.loc.start.column + 1,
503
- source: sourceFor(code, node),
504
- alternatives: [
505
- { id: shortId, label: "assignment skipped" },
506
- { id: rightId, label: "right evaluated / assigned" },
507
- ],
508
- });
509
- const frameId = path.scope.generateUidIdentifier("supercovSelectionFrame");
510
- const frameScope = path.scope.getFunctionParent() ?? path.scope.getProgramParent();
511
- frameScope.push({ id: t.cloneNode(frameId), kind: "let" });
512
- const assignFrame = t.assignmentExpression("=", t.cloneNode(frameId), t.callExpression(t.identifier(SELECTION_BEGIN), [
513
- t.stringLiteral(shortId),
514
- t.stringLiteral(rightId),
515
- ]));
516
- const assignment = t.assignmentExpression(node.operator, t.cloneNode(node.left), t.callExpression(t.identifier(SELECTION_RIGHT), [
517
- t.cloneNode(frameId),
518
- node.right,
519
- ...(t.isIdentifier(node.left) &&
520
- !node.left.extra?.parenthesized &&
521
- isAnonymousFunctionDefinition(node.right)
522
- ? [t.stringLiteral(node.left.name)]
523
- : []),
524
- ]));
525
- path.replaceWith(t.sequenceExpression([
526
- assignFrame,
527
- t.callExpression(t.identifier(SELECTION_END), [
528
- t.cloneNode(frameId),
529
- assignment,
530
- ]),
531
- ]));
532
- path.skip();
533
- },
534
- },
535
- });
536
- // Parameter defaults execute before a function body. A tiny per-default
537
- // token lets the body distinguish an evaluated default from a supplied
538
- // value without comparing values or evaluating either expression twice.
539
- traverse(ast, {
540
- Function(path) {
541
- if (isUnsafeInstrumentationContext(path))
542
- return;
543
- if (!t.isBlockStatement(path.node.body))
544
- return;
545
- const entries = [];
546
- const visitPattern = (pattern) => {
547
- if (t.isTSParameterProperty(pattern)) {
548
- visitPattern(pattern.parameter);
549
- return;
550
- }
551
- if (t.isAssignmentPattern(pattern)) {
552
- if (!pattern.loc)
553
- return;
554
- const id = stableId(file, "default-value", pattern);
555
- const defaultId = `${id}:default`;
556
- const providedId = `${id}:provided`;
557
- branches.push({
558
- id,
559
- kind: "default-value",
560
- file,
561
- line: pattern.loc.start.line,
562
- column: pattern.loc.start.column + 1,
563
- source: sourceFor(code, pattern),
564
- alternatives: [
565
- { id: defaultId, label: "default evaluated" },
566
- { id: providedId, label: "value provided" },
567
- ],
568
- });
569
- pattern.right = t.callExpression(t.identifier(DEFAULT_SELECTED), [
570
- t.stringLiteral(defaultId),
571
- pattern.right,
572
- ...(t.isIdentifier(pattern.left) &&
573
- isAnonymousFunctionDefinition(pattern.right)
574
- ? [t.stringLiteral(pattern.left.name)]
575
- : []),
576
- ]);
577
- entries.push(t.expressionStatement(t.callExpression(t.identifier(DEFAULT_ENTERED), [
578
- t.stringLiteral(defaultId),
579
- t.stringLiteral(providedId),
580
- ])));
581
- visitPattern(pattern.left);
582
- return;
583
- }
584
- if (t.isRestElement(pattern))
585
- return visitPattern(pattern.argument);
586
- if (t.isObjectPattern(pattern)) {
587
- for (const property of pattern.properties) {
588
- if (t.isRestElement(property))
589
- visitPattern(property.argument);
590
- else
591
- visitPattern(property.value);
592
- }
593
- return;
594
- }
595
- if (t.isArrayPattern(pattern)) {
596
- for (const element of pattern.elements)
597
- if (element)
598
- visitPattern(element);
599
- }
600
- };
601
- for (const parameter of path.node.params)
602
- visitPattern(parameter);
603
- path.node.body.body.unshift(...entries);
604
- },
605
- });
606
- // Destructuring declarations use the same token protocol. For loop-binding
607
- // declarations consume the token at the start of each iteration, directly
608
- // after JavaScript has completed the binding operation.
609
- traverse(ast, {
610
- VariableDeclaration(path) {
611
- if (isUnsafeInstrumentationContext(path))
612
- return;
613
- const parent = path.parentPath;
614
- if (parent.isForStatement() && path.key === "init") {
615
- let hasDefault = false;
616
- t.traverseFast(path.node, (node) => {
617
- if (t.isAssignmentPattern(node))
618
- hasDefault = true;
619
- });
620
- const loc = path.node.loc;
621
- if (hasDefault && loc) {
622
- const node = path.node;
623
- limitations.push({
624
- id: stableId(file, "dynamic-code", node, "for-init-default"),
625
- kind: "dynamic-code",
626
- file,
627
- line: loc.start.line,
628
- column: loc.start.column + 1,
629
- source: sourceFor(code, node),
630
- reason: "destructuring defaults in a classic for initializer cannot yet be finalized without restructuring control flow",
631
- });
632
- }
633
- return;
634
- }
635
- const entries = [];
636
- const visitPattern = (pattern) => {
637
- if (t.isAssignmentPattern(pattern)) {
638
- if (!pattern.loc)
639
- return;
640
- const id = stableId(file, "default-value", pattern);
641
- const defaultId = `${id}:default`;
642
- const providedId = `${id}:provided`;
643
- branches.push({
644
- id,
645
- kind: "default-value",
646
- file,
647
- line: pattern.loc.start.line,
648
- column: pattern.loc.start.column + 1,
649
- source: sourceFor(code, pattern),
650
- alternatives: [
651
- { id: defaultId, label: "default evaluated" },
652
- { id: providedId, label: "value provided" },
653
- ],
654
- });
655
- pattern.right = t.callExpression(t.identifier(DEFAULT_SELECTED), [
656
- t.stringLiteral(defaultId),
657
- pattern.right,
658
- ...(t.isIdentifier(pattern.left) &&
659
- isAnonymousFunctionDefinition(pattern.right)
660
- ? [t.stringLiteral(pattern.left.name)]
661
- : []),
662
- ]);
663
- entries.push(t.expressionStatement(t.callExpression(t.identifier(DEFAULT_ENTERED), [
664
- t.stringLiteral(defaultId),
665
- t.stringLiteral(providedId),
666
- ])));
667
- visitPattern(pattern.left);
668
- return;
669
- }
670
- if (t.isRestElement(pattern))
671
- return visitPattern(pattern.argument);
672
- if (t.isObjectPattern(pattern)) {
673
- for (const property of pattern.properties)
674
- visitPattern(t.isRestElement(property) ? property.argument : property.value);
675
- return;
676
- }
677
- if (t.isArrayPattern(pattern)) {
678
- for (const element of pattern.elements)
679
- if (element)
680
- visitPattern(element);
681
- }
682
- };
683
- for (const declaration of path.node.declarations)
684
- visitPattern(declaration.id);
685
- if (entries.length === 0)
686
- return;
687
- if ((parent.isForOfStatement() || parent.isForInStatement()) &&
688
- path.key === "left") {
689
- const body = parent.node.body;
690
- parent.node.body = t.isBlockStatement(body)
691
- ? body
692
- : t.blockStatement([body]);
693
- parent.node.body.body.unshift(...entries);
694
- return;
695
- }
696
- if (parent.isExportNamedDeclaration())
697
- parent.insertAfter(entries);
698
- else
699
- path.insertAfter(entries);
700
- },
701
- });
702
- // Try/catch and enumeration loops use frames finalized in `finally`, so
703
- // return, break, continue, rejection, and throw paths remain observable.
704
- traverse(ast, {
705
- TryStatement(path) {
706
- if (isUnsafeInstrumentationContext(path))
707
- return;
708
- const node = path.node;
709
- if (!node.loc || !node.handler)
710
- return;
711
- const id = stableId(file, "try-catch", node);
712
- const successId = `${id}:success`;
713
- const catchId = `${id}:catch`;
714
- branches.push({
715
- id,
716
- kind: "try-catch",
717
- file,
718
- line: node.loc.start.line,
719
- column: node.loc.start.column + 1,
720
- source: "try / catch",
721
- alternatives: [
722
- { id: successId, label: "try completed without catch" },
723
- { id: catchId, label: "catch entered" },
724
- ],
725
- });
726
- const frameId = path.scope.generateUidIdentifier("supercovTryFrame");
727
- const frameScope = path.scope.getFunctionParent() ?? path.scope.getProgramParent();
728
- frameScope.push({ id: t.cloneNode(frameId), kind: "let" });
729
- path.insertBefore(t.expressionStatement(t.assignmentExpression("=", t.cloneNode(frameId), t.callExpression(t.identifier(TRY_BEGIN), [
730
- t.stringLiteral(successId),
731
- t.stringLiteral(catchId),
732
- ]))));
733
- node.handler.body.body.unshift(t.expressionStatement(t.callExpression(t.identifier(TRY_CATCH), [
734
- t.cloneNode(frameId),
735
- t.identifier("undefined"),
736
- ])));
737
- const end = t.expressionStatement(t.callExpression(t.identifier(TRY_END), [t.cloneNode(frameId)]));
738
- if (node.finalizer)
739
- node.finalizer.body.unshift(end);
740
- else
741
- node.finalizer = t.blockStatement([end]);
742
- path.skip();
743
- },
744
- "ForInStatement|ForOfStatement"(path) {
745
- if (isUnsafeInstrumentationContext(path))
746
- return;
747
- const node = path.node;
748
- if (!node.loc)
749
- return;
750
- const kind = t.isForOfStatement(node) ? "for-of" : "for-in";
751
- const id = stableId(file, kind, node);
752
- const zeroId = `${id}:zero`;
753
- const enteredId = `${id}:entered`;
754
- branches.push({
755
- id,
756
- kind,
757
- file,
758
- line: node.loc.start.line,
759
- column: node.loc.start.column + 1,
760
- source: sourceFor(code, node.right),
761
- alternatives: [
762
- { id: zeroId, label: "zero iterations" },
763
- { id: enteredId, label: "one or more iterations" },
764
- ],
765
- });
766
- const frameId = path.scope.generateUidIdentifier("supercovLoopFrame");
767
- const frameScope = path.scope.getFunctionParent() ?? path.scope.getProgramParent();
768
- frameScope.push({ id: t.cloneNode(frameId), kind: "let" });
769
- const assignment = t.expressionStatement(t.assignmentExpression("=", t.cloneNode(frameId), t.callExpression(t.identifier(LOOP_BEGIN), [
770
- t.stringLiteral(zeroId),
771
- t.stringLiteral(enteredId),
772
- ])));
773
- const loop = t.cloneNode(node, true);
774
- loop.body = t.isBlockStatement(loop.body)
775
- ? loop.body
776
- : t.blockStatement([loop.body]);
777
- loop.body.body.unshift(t.expressionStatement(t.callExpression(t.identifier(LOOP_ENTERED), [
778
- t.cloneNode(frameId),
779
- ])));
780
- let loopStatement = loop;
781
- let replacementPath = path;
782
- while (replacementPath.parentPath?.isLabeledStatement() &&
783
- replacementPath.parentPath.node.body === replacementPath.node) {
784
- loopStatement = t.labeledStatement(t.cloneNode(replacementPath.parentPath.node.label), loopStatement);
785
- replacementPath = replacementPath.parentPath;
786
- }
787
- const wrapped = t.tryStatement(t.blockStatement([loopStatement]), null, t.blockStatement([
788
- t.expressionStatement(t.callExpression(t.identifier(LOOP_END), [t.cloneNode(frameId)])),
789
- ]));
790
- if (replacementPath === path) {
791
- path.insertBefore(assignment);
792
- path.replaceWith(wrapped);
793
- path.skip();
794
- }
795
- else {
796
- replacementPath.replaceWith(t.blockStatement([assignment, wrapped]));
797
- replacementPath.skip();
798
- }
799
- },
800
- });
801
- // Function entry is separate from statement coverage so empty functions and
802
- // expression-bodied arrows remain visible in the completeness denominator.
803
- traverse(ast, {
804
- Function(path) {
805
- const node = path.node;
806
- if (!node.loc || !node.body)
807
- return;
808
- if (isUnsafeInstrumentationContext(path))
809
- return;
810
- const id = stableId(file, "function", node);
811
- points.push({
812
- id,
813
- kind: "function",
814
- file,
815
- line: node.loc.start.line,
816
- column: node.loc.start.column + 1,
817
- source: sourceFor(code, node),
818
- ...(functionLabel(path) ? { label: functionLabel(path) } : {}),
819
- });
820
- const probe = hitStatement(id, HIT);
821
- generatedStatements.add(probe);
822
- if (t.isBlockStatement(node.body)) {
823
- node.body.body.unshift(probe);
824
- }
825
- else {
826
- node.body = t.blockStatement([probe, t.returnStatement(node.body)]);
827
- }
828
- },
829
- });
830
- const instrumentDecision = (path, kind) => {
831
- if (!path.node.loc)
832
- return;
833
- const originalConditions = [];
834
- collectConditions(path.node, originalConditions);
835
- if (originalConditions.length === 0)
836
- return;
837
- const id = stableId(file, "decision", path.node, kind);
838
- const meta = {
839
- id,
840
- file,
841
- line: path.node.loc.start.line,
842
- column: path.node.loc.start.column + 1,
843
- source: sourceFor(code, path.node),
844
- conditions: originalConditions.map((condition) => sourceFor(code, condition)),
845
- kind,
846
- };
847
- decisions.push(meta);
848
- // A loop predicate's path scope may be represented by Babel as the loop
849
- // body's block. Declaring the frame there puts it after the predicate that
850
- // uses it (and is especially visible in async generators). Hoist scratch
851
- // frames to the nearest function/program scope instead.
852
- const inlineFrame = isInsideFunctionParameter(path);
853
- const evaluationScope = (path.isFunctionExpression() ||
854
- path.isArrowFunctionExpression() ||
855
- path.isClassExpression()) &&
856
- path.scope.parent
857
- ? path.scope.parent
858
- : path.scope;
859
- const frameScope = evaluationScope.getFunctionParent() ??
860
- evaluationScope.getProgramParent();
861
- const frameId = frameScope.generateUidIdentifier("supercovMcdcFrame");
862
- if (!inlineFrame)
863
- frameScope.push({ id: t.cloneNode(frameId), kind: "let" });
864
- const instrumented = instrumentConditions(path.node, frameId, { value: 0 }, decisionLogicalNodes, CONDITION);
865
- const begin = t.callExpression(t.identifier(BEGIN), [
866
- t.stringLiteral(id),
867
- t.valueToNode(meta),
868
- ]);
869
- const assignFrame = t.assignmentExpression("=", t.cloneNode(frameId), begin);
870
- const end = t.callExpression(t.identifier(END), [
871
- t.cloneNode(frameId),
872
- instrumented,
873
- ]);
874
- path.replaceWith(inlineFrame
875
- ? t.callExpression(t.arrowFunctionExpression([], t.blockStatement([
876
- t.variableDeclaration("let", [
877
- t.variableDeclarator(t.cloneNode(frameId), begin),
878
- ]),
879
- t.returnStatement(end),
880
- ])), [])
881
- : t.sequenceExpression([assignFrame, end]));
882
- path.skip();
883
- };
884
- traverse(ast, {
885
- IfStatement(path) {
886
- if (isUnsafeInstrumentationContext(path))
887
- return;
888
- instrumentDecision(path.get("test"), "if");
889
- },
890
- ConditionalExpression(path) {
891
- if (isUnsafeInstrumentationContext(path))
892
- return;
893
- instrumentDecision(path.get("test"), "ternary");
894
- },
895
- WhileStatement(path) {
896
- if (isUnsafeInstrumentationContext(path))
897
- return;
898
- instrumentDecision(path.get("test"), "while");
899
- },
900
- DoWhileStatement(path) {
901
- if (isUnsafeInstrumentationContext(path))
902
- return;
903
- instrumentDecision(path.get("test"), "do-while");
904
- },
905
- ForStatement(path) {
906
- if (isUnsafeInstrumentationContext(path))
907
- return;
908
- const test = path.get("test");
909
- if (test.node)
910
- instrumentDecision(test, "for");
911
- },
912
- });
913
- // A logical expression outside a control predicate selects a value or
914
- // render path. Record whether it short-circuited or evaluated its RHS;
915
- // Boolean MC/DC would be misleading when both selected values are truthy.
916
- traverse(ast, {
917
- LogicalExpression: {
918
- exit(path) {
919
- if (isUnsafeInstrumentationContext(path))
920
- return;
921
- const node = path.node;
922
- if (!node.loc || decisionLogicalNodes.has(node))
923
- return;
924
- const id = stableId(file, "logical-value", node, node.operator);
925
- const shortId = `${id}:short`;
926
- const rightId = `${id}:right`;
927
- branches.push({
928
- id,
929
- kind: "logical-value",
930
- file,
931
- line: node.loc.start.line,
932
- column: node.loc.start.column + 1,
933
- source: sourceFor(code, node),
934
- alternatives: [
935
- { id: shortId, label: "short-circuit / left selected" },
936
- { id: rightId, label: "right evaluated / selected" },
937
- ],
938
- });
939
- const frameId = path.scope.generateUidIdentifier("supercovSelectionFrame");
940
- const frameScope = path.scope.getFunctionParent() ?? path.scope.getProgramParent();
941
- frameScope.push({ id: t.cloneNode(frameId), kind: "let" });
942
- const begin = t.callExpression(t.identifier(SELECTION_BEGIN), [
943
- t.stringLiteral(shortId),
944
- t.stringLiteral(rightId),
945
- ]);
946
- const assign = t.assignmentExpression("=", t.cloneNode(frameId), begin);
947
- const right = t.callExpression(t.identifier(SELECTION_RIGHT), [
948
- t.cloneNode(frameId),
949
- node.right,
950
- ]);
951
- const selection = t.logicalExpression(node.operator, node.left, right);
952
- const end = t.callExpression(t.identifier(SELECTION_END), [
953
- t.cloneNode(frameId),
954
- selection,
955
- ]);
956
- path.replaceWith(t.sequenceExpression([assign, end]));
957
- path.skip();
958
- },
959
- },
960
- });
961
- // Switch alternatives are observable independently of whether their bodies
962
- // are empty or fall through to another case. An implicit no-match probe must
963
- // live after the switch rather than in a synthetic default: a matched case
964
- // can legally fall through to the end and must not be counted as no-match.
965
- traverse(ast, {
966
- SwitchStatement(path) {
967
- if (isUnsafeInstrumentationContext(path))
968
- return;
969
- const node = path.node;
970
- if (!node.loc)
971
- return;
972
- const id = stableId(file, "switch", node);
973
- const hasDefault = node.cases.some((switchCase) => switchCase.test === null);
974
- const enteredId = hasDefault
975
- ? undefined
976
- : path.scope.generateUidIdentifier("supercovSwitchEntered");
977
- const alternatives = node.cases.map((switchCase, index) => {
978
- const alternativeId = `${id}:case:${index}`;
979
- const label = switchCase.test
980
- ? `case ${sourceFor(code, switchCase.test)}`
981
- : "default";
982
- const probe = hitStatement(alternativeId, HIT);
983
- generatedStatements.add(probe);
984
- switchCase.consequent.unshift(...(enteredId
985
- ? [
986
- t.expressionStatement(t.assignmentExpression("=", t.cloneNode(enteredId), t.booleanLiteral(true))),
987
- ]
988
- : []), probe);
989
- return { id: alternativeId, label };
990
- });
991
- let noMatchId;
992
- if (!hasDefault) {
993
- const alternativeId = `${id}:no-match`;
994
- noMatchId = alternativeId;
995
- alternatives.push({
996
- id: alternativeId,
997
- label: "no matching case",
998
- });
999
- }
1000
- branches.push({
1001
- id,
1002
- kind: "switch",
1003
- file,
1004
- line: node.loc.start.line,
1005
- column: node.loc.start.column + 1,
1006
- source: sourceFor(code, node.discriminant),
1007
- alternatives,
1008
- });
1009
- if (!enteredId || !noMatchId)
1010
- return;
1011
- let switchStatement = node;
1012
- let replacementPath = path;
1013
- while (replacementPath.parentPath?.isLabeledStatement() &&
1014
- replacementPath.parentPath.node.body === replacementPath.node) {
1015
- switchStatement = t.labeledStatement(t.cloneNode(replacementPath.parentPath.node.label), switchStatement);
1016
- replacementPath = replacementPath.parentPath;
1017
- }
1018
- const noMatchProbe = hitStatement(noMatchId, HIT);
1019
- generatedStatements.add(noMatchProbe);
1020
- replacementPath.replaceWith(t.blockStatement([
1021
- t.variableDeclaration("let", [
1022
- t.variableDeclarator(t.cloneNode(enteredId), t.booleanLiteral(false)),
1023
- ]),
1024
- switchStatement,
1025
- t.ifStatement(t.unaryExpression("!", t.cloneNode(enteredId)), noMatchProbe),
1026
- ]));
1027
- replacementPath.skip();
1028
- },
1029
- });
1030
- // Runtime-generated source cannot be assigned a truthful static
1031
- // denominator without parsing and instrumenting the generated program in
1032
- // its own execution realm. Discover it and block a completeness verdict
1033
- // instead of silently claiming 100% for only the surrounding file.
1034
- traverse(ast, {
1035
- CallExpression(path) {
1036
- if (isUnsafeInstrumentationContext(path))
1037
- return;
1038
- const callee = path.node.callee;
1039
- if (!path.node.loc || !t.isIdentifier(callee, { name: "eval" }))
1040
- return;
1041
- limitations.push({
1042
- id: stableId(file, "dynamic-code", path.node, "eval"),
1043
- kind: "dynamic-code",
1044
- file,
1045
- line: path.node.loc.start.line,
1046
- column: path.node.loc.start.column + 1,
1047
- source: sourceFor(code, path.node),
1048
- reason: "eval-generated source has no stable pre-run coverage denominator",
1049
- });
1050
- },
1051
- NewExpression(path) {
1052
- if (isUnsafeInstrumentationContext(path))
1053
- return;
1054
- if (!path.node.loc ||
1055
- !t.isIdentifier(path.node.callee, { name: "Function" }))
1056
- return;
1057
- limitations.push({
1058
- id: stableId(file, "dynamic-code", path.node, "Function"),
1059
- kind: "dynamic-code",
1060
- file,
1061
- line: path.node.loc.start.line,
1062
- column: path.node.loc.start.column + 1,
1063
- source: sourceFor(code, path.node),
1064
- reason: "Function-generated source has no stable pre-run coverage denominator",
1065
- });
1066
- },
1067
- });
1068
- // Route requests carry the Playwright phase as a private test-only header.
1069
- // Wrap Remix request entry points so Node's AsyncLocalStorage can propagate
1070
- // that exact phase through every awaited helper without application edits.
1071
- // This runs after source instrumentation so generated wrappers never become
1072
- // coverage obligations themselves.
1073
- if (/^app\/routes\//.test(file) ||
1074
- /(?:^|\/)app\/.*\/route\.[cm]?[jt]sx?$/.test(file)) {
1075
- traverse(ast, {
1076
- ExportNamedDeclaration(path) {
1077
- const declaration = path.node.declaration;
1078
- if (t.isVariableDeclaration(declaration)) {
1079
- for (const declarator of declaration.declarations) {
1080
- if (t.isIdentifier(declarator.id) &&
1081
- isRequestHandlerName(file, declarator.id.name) &&
1082
- declarator.init) {
1083
- declarator.init = t.callExpression(t.identifier(WITH_REQUEST_PHASE), [declarator.init]);
1084
- usesRequestPhaseHandler = true;
1085
- }
1086
- }
1087
- return;
1088
- }
1089
- if (t.isFunctionDeclaration(declaration) &&
1090
- declaration.id &&
1091
- isRequestHandlerName(file, declaration.id.name)) {
1092
- const exportedName = declaration.id.name;
1093
- const originalId = path.scope.generateUidIdentifier(`${exportedName}CoverageOriginal`);
1094
- declaration.id = originalId;
1095
- const wrappedExport = t.exportNamedDeclaration(t.variableDeclaration("const", [
1096
- t.variableDeclarator(t.identifier(exportedName), t.callExpression(t.identifier(WITH_REQUEST_PHASE), [
1097
- t.cloneNode(originalId),
1098
- ])),
1099
- ]));
1100
- path.replaceWithMultiple([declaration, wrappedExport]);
1101
- usesRequestPhaseHandler = true;
1102
- return;
1103
- }
1104
- if (!path.node.source)
1105
- return;
1106
- const handlerSpecifiers = path.node.specifiers.filter((specifier) => t.isExportSpecifier(specifier) &&
1107
- t.isIdentifier(specifier.exported) &&
1108
- isRequestHandlerName(file, specifier.exported.name));
1109
- if (handlerSpecifiers.length === 0)
1110
- return;
1111
- const replacements = [];
1112
- const untouched = path.node.specifiers.filter((specifier) => !handlerSpecifiers.includes(specifier));
1113
- if (untouched.length > 0) {
1114
- replacements.push(t.exportNamedDeclaration(null, untouched, t.cloneNode(path.node.source)));
1115
- }
1116
- for (const specifier of handlerSpecifiers) {
1117
- const exportedName = specifier.exported.name;
1118
- const importedId = path.scope.generateUidIdentifier(`${exportedName}CoverageOriginal`);
1119
- replacements.push(t.importDeclaration([
1120
- t.importSpecifier(t.cloneNode(importedId), t.cloneNode(specifier.local)),
1121
- ], t.cloneNode(path.node.source)), t.exportNamedDeclaration(t.variableDeclaration("const", [
1122
- t.variableDeclarator(t.identifier(exportedName), t.callExpression(t.identifier(WITH_REQUEST_PHASE), [
1123
- t.cloneNode(importedId),
1124
- ])),
1125
- ])));
1126
- }
1127
- path.replaceWithMultiple(replacements);
1128
- usesRequestPhaseHandler = true;
1129
- },
1130
- });
1131
- }
1132
- if (/^app\/entry\.server\.[cm]?[jt]sx?$/.test(file)) {
1133
- traverse(ast, {
1134
- ExportDefaultDeclaration(path) {
1135
- const declaration = path.node.declaration;
1136
- if (t.isFunctionDeclaration(declaration)) {
1137
- const originalId = path.scope.generateUidIdentifier("handleRequestCoverageOriginal");
1138
- declaration.id = originalId;
1139
- path.replaceWithMultiple([
1140
- declaration,
1141
- t.exportDefaultDeclaration(t.callExpression(t.identifier(WITH_REQUEST_PHASE), [
1142
- t.cloneNode(originalId),
1143
- ])),
1144
- ]);
1145
- }
1146
- else {
1147
- path.node.declaration = t.callExpression(t.identifier(WITH_REQUEST_PHASE), [declaration]);
1148
- }
1149
- usesRequestPhaseHandler = true;
1150
- },
1151
- });
1152
- }
1153
- // HTTP servers and WebSocket libraries expose request-bearing callbacks
1154
- // outside framework route exports. Wrap well-known listener boundaries and
1155
- // let the runtime scan callback arguments for Fetch or Node request headers.
1156
- traverse(ast, {
1157
- CallExpression(path) {
1158
- if (isUnsafeInstrumentationContext(path))
1159
- return;
1160
- const callee = path.node.callee;
1161
- const property = (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) &&
1162
- !callee.computed &&
1163
- t.isIdentifier(callee.property)
1164
- ? callee.property.name
1165
- : undefined;
1166
- const identifier = t.isIdentifier(callee) ? callee.name : property;
1167
- let callbackIndex = -1;
1168
- if ((property === "on" || property === "once" || property === "addListener") &&
1169
- t.isStringLiteral(path.node.arguments[0]) &&
1170
- ["request", "upgrade", "connection"].includes(path.node.arguments[0].value)) {
1171
- callbackIndex = 1;
1172
- }
1173
- else if (identifier === "createServer") {
1174
- for (let index = path.node.arguments.length - 1; index >= 0; index -= 1) {
1175
- const argument = path.node.arguments[index];
1176
- if (t.isFunctionExpression(argument) ||
1177
- t.isArrowFunctionExpression(argument) ||
1178
- t.isIdentifier(argument) ||
1179
- t.isMemberExpression(argument)) {
1180
- callbackIndex = index;
1181
- break;
1182
- }
1183
- }
1184
- }
1185
- if (callbackIndex < 0)
1186
- return;
1187
- const callback = path.node.arguments[callbackIndex];
1188
- if (!callback || !t.isExpression(callback))
1189
- return;
1190
- if (t.isCallExpression(callback) &&
1191
- t.isIdentifier(callback.callee, { name: WITH_REQUEST_PHASE }))
1192
- return;
1193
- path.node.arguments[callbackIndex] = t.callExpression(t.identifier(WITH_REQUEST_PHASE), [callback]);
1194
- usesRequestPhaseHandler = true;
1195
- },
1196
- });
1197
- const manifest = {
1198
- decisions,
1199
- points,
1200
- branches,
1201
- ...(limitations.length > 0 ? { limitations } : {}),
1202
- };
1203
- if (decisions.length > 0 ||
1204
- points.length > 0 ||
1205
- branches.length > 0 ||
1206
- usesRequestPhaseHandler) {
1207
- ast.program.body.unshift(t.importDeclaration([
1208
- t.importSpecifier(t.identifier(BEGIN), t.identifier("mcdcBegin")),
1209
- t.importSpecifier(t.identifier(CONDITION), t.identifier("mcdcCondition")),
1210
- t.importSpecifier(t.identifier(END), t.identifier("mcdcEnd")),
1211
- t.importSpecifier(t.identifier(HIT), t.identifier("coverageHit")),
1212
- t.importSpecifier(t.identifier(SELECTION_BEGIN), t.identifier("selectionBegin")),
1213
- t.importSpecifier(t.identifier(SELECTION_RIGHT), t.identifier("selectionRight")),
1214
- t.importSpecifier(t.identifier(SELECTION_END), t.identifier("selectionEnd")),
1215
- t.importSpecifier(t.identifier(OPTIONAL_SELECT), t.identifier("optionalSelect")),
1216
- t.importSpecifier(t.identifier(OPTIONAL_CALL_BEGIN), t.identifier("optionalCallBegin")),
1217
- t.importSpecifier(t.identifier(OPTIONAL_CALL_REACHED), t.identifier("optionalCallReached")),
1218
- t.importSpecifier(t.identifier(OPTIONAL_CALL_CONTINUED), t.identifier("optionalCallContinued")),
1219
- t.importSpecifier(t.identifier(OPTIONAL_CALL_END), t.identifier("optionalCallEnd")),
1220
- t.importSpecifier(t.identifier(DEFAULT_SELECTED), t.identifier("defaultSelected")),
1221
- t.importSpecifier(t.identifier(DEFAULT_ENTERED), t.identifier("defaultEntered")),
1222
- t.importSpecifier(t.identifier(TRY_BEGIN), t.identifier("tryBegin")),
1223
- t.importSpecifier(t.identifier(TRY_CATCH), t.identifier("tryCatch")),
1224
- t.importSpecifier(t.identifier(TRY_END), t.identifier("tryEnd")),
1225
- t.importSpecifier(t.identifier(LOOP_BEGIN), t.identifier("loopBegin")),
1226
- t.importSpecifier(t.identifier(LOOP_ENTERED), t.identifier("loopEntered")),
1227
- t.importSpecifier(t.identifier(LOOP_END), t.identifier("loopEnd")),
1228
- ...(usesRequestPhaseHandler
1229
- ? [
1230
- t.importSpecifier(t.identifier(WITH_REQUEST_PHASE), t.identifier("withRequestPhase")),
1231
- ]
1232
- : []),
1233
- ], t.stringLiteral(RUNTIME_MODULE)));
1234
- }
1235
- const output = generate({
1236
- ...ast,
1237
- }, {
1238
- sourceMaps: true,
1239
- sourceFileName: file,
1240
- retainLines: true,
1241
- comments: true,
1242
- }, code);
1243
- return { code: output.code, map: output.map, manifest, decisions };
1244
- }
1245
- export const mcdcRuntimeModuleId = RUNTIME_MODULE;
1246
- //# sourceMappingURL=instrumenter.js.map