targeted-mutation 0.0.0-stage → 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +149 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,21 @@
1
+ targeted-mutation
2
+ Copyright 2026 The targeted-mutation authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+
6
+ It includes a syntax parser generated from the TypeScript compiler
7
+ (Copyright Microsoft Corporation, Apache License 2.0). The license and
8
+ third-party notices are in build/typescript-syntax/.
9
+
10
+ The platform packages (@targeted-mutation/tmt-<os>-<cpu>) contain an
11
+ executable linked with the Lean 4 runtime and the libraries it bundles,
12
+ including GMP (LGPL-3.0-or-later or GPL-2.0-or-later) and libuv (MIT).
13
+ Their licenses are in the lean/ directory of each platform package
14
+ (LICENSES from the Lean release, GPL-3.0.txt, libuv-LICENSE.txt and
15
+ libuv-LICENSE-extra.txt). To relink the executable against another GMP
16
+ build, replace lib/libgmp.a in that Lean toolchain and run
17
+ `npm run build:lean` in the source repository.
18
+ GMP is the version bundled by the Lean release named in
19
+ proof/lean/lean-toolchain; its source is available from https://gmplib.org/. The
20
+ proof sources and build scripts needed to relink that executable are in
21
+ the source repository under proof/lean and scripts/.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # targeted-mutation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `targeted-mutation` finds the tests your suite is missing. It watches the values your tests actually pass through comparisons, tries the smallest wrong implementation those values cannot tell apart from yours, and prints the test that would catch it.
4
+
5
+ ```ts
6
+ export const isAdult = (age: number) => age >= 18;
7
+ // tests check isAdult(20) and isAdult(10)
8
+ ```
9
+
10
+ ```text
11
+ src/cart.ts:15:45 survived comparison-boundary/v1: >= -> >
12
+ src/cart.ts:15:45 survived comparison-threshold/v1: replace with 17
13
+
14
+ Test gaps:
15
+ INPUT GAP src/cart.ts:15:45
16
+ operands (18, 18): original true, edited false
17
+ suggested test: expect(isAdult(18)).toBe(true)
18
+ INPUT GAP src/cart.ts:15:45
19
+ operands (17, 18): original false, edited true
20
+ suggested test: expect(isAdult(17)).toBe(false)
21
+ ```
22
+
23
+ A conventional mutation run replaces `>=` with `>` or `<`. It does not try `age >= 17`, the nearest implementation that the inputs 10 and 20 leave open. The [shipping threshold experiment](docs/development.md#shipping-threshold-experiment) compares both approaches on the same suite.
24
+
25
+ ## How it works (and how it differs from conventional mutation testing)
26
+
27
+ Conventional mutation tools (such as StrykerJS) generate edits purely from syntax (`>=` to `>`, `+` to `-`, `{ ... }` to `{}`), run the suite, and report a list of surviving mutants. They do not know *what values* your tests passed, *why* a mutant survived (missing test input vs. weak assertion), or *what test* would kill it.
28
+
29
+ `targeted-mutation` records the actual runtime values flowing through your code during the baseline run, synthesizes the smallest undistinguished edits from those observations, and classifies every survivor into an actionable test gap.
30
+
31
+ ![How targeted-mutation works](docs/how-it-works.svg)
32
+
33
+ | Capability | Conventional mutation testing | `targeted-mutation` |
34
+ |------------|-------------------------------|---------------------|
35
+ | Mutant generation | Fixed syntactic templates only | Observation-guided synthesis (nearest open integer threshold and variable-RHS margin via Lean 4) + 20 value-aware semantic rules (spread property drop, `startsWith`/`endsWith` to `includes`, `replace`/`replaceAll`, clamp bounds, literal-set pruning, `??`/`\|\|`, `finally` cleanup drop, etc.) |
36
+ | Survivor diagnosis | `survived` (developer must investigate manually) | Separates **`INPUT GAP`** (no test passed a distinguishing input, naming the exact missing input) from **`ASSERTION GAP`** (names the exact test that had the input and asserted nothing) |
37
+ | Assertion guidance | None | `--suggest-assertions` wraps weak calls in a warm Vitest session and prints the exact assertion, narrowing multi-key objects to the single changed sibling field (`expect(res.fee).toBe(600)`) |
38
+ | Diff-based testing | Mutate changed lines only | `--since REV --undo-changes` also reverts each changed Git hunk and independent AST sub-hunk (added `&&`/`\|\|` terms, added object properties) to find `UNTESTED CHANGE` |
39
+ | Deterministic replay | Re-executes every mutant | `--deterministic` skips eligible comparison trials whose recorded safe-integer operands prove identical outcomes, verified by `tmt-decide` (extracted from Lean 4 proofs) |
40
+ | Worker isolation | Shared worker or full restart per mutant | In-worker Vitest 4 runtime switches with an immediate post-trial control run; automatically falls back to a fresh run if worker state leaks |
41
+
42
+ ## Install
43
+
44
+ ```sh
45
+ npm install --save-dev targeted-mutation
46
+ ```
47
+
48
+ Requirements:
49
+
50
+ - Node.js 22.18 or later in the 22 line, or 24.11 or later.
51
+ - [Vitest](https://vitest.dev/) or [Playwright](https://playwright.dev/) installed in the project or its workspace. Releases are tested with Vitest 4.0 and Playwright 1.65.
52
+ - Any platform supported by Node.js, including macOS, Linux (glibc and musl/Alpine), and Windows. On macOS (arm64, x64) and Linux with glibc (arm64, x64), npm installs the matching prebuilt binary package automatically as an accelerator for extraction and Lean-checked replay. On other platforms, `analyze` and `extract` fall back automatically to the bundled TypeScript parser and JavaScript threshold evaluator.
53
+
54
+ The tool copies the project to a temporary directory and runs the project's own test code and configuration there. Run it only on code you trust, as you would run the test suite.
55
+
56
+ ## Use
57
+
58
+ ```sh
59
+ npx targeted-mutation analyze # every source file in the current project (default: targeted)
60
+ npx targeted-mutation analyze . src/cart.ts # selected files
61
+ npx targeted-mutation analyze --lines src/cart.ts:10-40
62
+ npx targeted-mutation analyze --since origin/main # edits on lines changed since a revision
63
+ npx targeted-mutation analyze --since origin/main --undo-changes # also: which changes do the tests pass without?
64
+ npx targeted-mutation analyze --suggest-assertions # also: the exact value a weak assertion should compare with
65
+ npx targeted-mutation analyze --mutators full # full built-in StrykerJS-compatible mutation set (no StrykerJS required)
66
+ ```
67
+
68
+ `tmts` is a short alias for the same command. `targeted-mutation --help` lists every option.
69
+
70
+ The exit status is 0 after a completed analysis, including one that reports gaps, and 1 when the suite fails before any edit, a file cannot be parsed, or the arguments are invalid.
71
+
72
+ ### Reading the report
73
+
74
+ Each line is one source edit and what the suite did with it:
75
+
76
+ | Status | Meaning |
77
+ |--------|---------|
78
+ | `killed` | A test failed on the edit. The suite distinguishes it. |
79
+ | `survived` | Every test passed on the edit. A `Test gaps` entry shows the missing input. |
80
+ | `unreached` | No test executed the edited expression. |
81
+
82
+ A test gap gives the operand values that separate your code from the edit and, for an exported single-argument function, a ready assertion under `suggested test`.
83
+
84
+ On a terminal the report is text. When the output is piped or redirected it is JSON with a `schemaVersion`, so scripts can rely on it. `--format text` or `--format json` selects one explicitly.
85
+
86
+ ### Profiles
87
+
88
+ | Option | What it edits |
89
+ |--------|---------------|
90
+ | (default) `--mutators targeted` | `<`, `<=`, `>`, `>=` boundaries and, on Vitest, integer thresholds across constant-RHS comparisons plus variable-RHS margin shifts (`comparison-margin/v1`) and twenty value-aware rules: an equality that every test leaves true or false, an operand of `&&`, `\|\|` or `??` whose value never decides, `??` written as `\|\|`, `== null` written as `=== null`, another arithmetic operator, `Math.min` for `Math.max`, another rounding, the other end of a list, a numeric sort without its comparison, a call that is no longer awaited, a copy that is the original, a single dropped property in an object spread update, `startsWith`/`endsWith` relaxed to `includes`, `replace` swapped with `replaceAll`, a dropped `Math.min`/`Math.max` clamp bound, a pruned literal element in `[...].includes(x)`, swapped `{ ...a, ...b }` merge precedence, `every` swapped with `some`, dropped `^`/`$` regex anchors on `.test(s)`, and a skipped cleanup call inside `finally`. In a Vitest session with operand recording, each survivor is reported with the missing input or with the tests that had the input and asserted nothing. On Playwright (or when Vitest falls back to source rewrites without operand recording), edits run without operand recording, and Playwright reports survivor diagnostics only when paired with a `--spec` witness. Needs no extra package. |
91
+ | `--mutators full` | Comparison boundaries (and constant-RHS integer thresholds on Vitest), plus the complete built-in mutation set: every StrykerJS mutator (arithmetic, equality, logical, conditional, boolean, string, array, object, block, arrow function, assignment, unary, update, method, optional chaining, regular expression and call removal). Needs no extra package. Runs in one switched session on Vitest 4, or one source rewrite per mutation with Playwright. |
92
+ | `--witnesses` | Value substitutions such as a neighbouring field, the first or last index, or a sort key, each confirmed by a test that tells them apart. Reports `No edit sites` when a file has no such pattern. |
93
+
94
+ `// Stryker disable` and `// Stryker restore` comments exclude mutations in both the `targeted` and `full` profiles, with the reason you give after the colon.
95
+
96
+ On Vitest 4 the mutations are decided inside running Vitest workers, several at a time, with a control run after each one. `--concurrency N` sets the number of workers, `--verify-trials N` re-runs a sample of those decisions in fresh Vitest runs, and `--isolated-trials` starts a fresh Vitest run for every mutation instead; see [How mutations run on Vitest](docs/analysis.md#how-mutations-run-on-vitest).
97
+
98
+ `--deterministic` declares that the suite runs from the same state every time. Recorded comparison values then decide eligible comparison trials without re-running the tests, and each such decision is checked by `tmt-decide`, an executable extracted from a Lean 4 proof (with JavaScript instrumentation, observation collection, and test identity in the trusted runtime boundary). `--audit` re-runs those trials against the rewritten source and reports any disagreement.
99
+
100
+ The [analysis guide](docs/analysis.md) covers scope selection, specifications, Playwright projects and the witness profile in detail.
101
+
102
+ ## Documentation
103
+
104
+ - [Analysis guide](docs/analysis.md)
105
+ - [Parser grammar and trust boundary](docs/l1.md)
106
+ - [Performance measurements](docs/performance.md)
107
+ - [Development and verification](docs/development.md)
108
+ - [Releasing](docs/releasing.md)
109
+
110
+ ## License
111
+
112
+ [Apache-2.0](LICENSE). Third-party notices are in [NOTICE](NOTICE).
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync } from 'node:fs';
4
+ import { parseArgs } from 'node:util';
5
+ import { compile } from '../src/compiler.mjs';
6
+
7
+ try {
8
+ const { positionals, values } = parseArgs({
9
+ allowPositionals: true,
10
+ options: {
11
+ file: { type: 'string' },
12
+ target: { type: 'string' },
13
+ module: { type: 'string' },
14
+ jsx: { type: 'string' },
15
+ 'source-map': { type: 'boolean' },
16
+ strip: { type: 'boolean' },
17
+ help: { type: 'boolean', short: 'h' },
18
+ },
19
+ });
20
+ if (values.help) {
21
+ console.log('Usage: tmt-compile [--target esnext|es2018|...] [--module preserve|esm|cjs] [--jsx automatic|classic|preserve] [--source-map] [--strip] [--file NAME] <file|->');
22
+ } else {
23
+ if (positionals.length !== 1) throw new Error('Expected one source filename or - for stdin');
24
+ const [input] = positionals;
25
+ const file = values.file ?? (input === '-' ? 'stdin.ts' : input);
26
+ const result = compile(readFileSync(input === '-' ? 0 : input), {
27
+ file, target: values.target, module: values.module, jsx: values.jsx,
28
+ mode: values.strip ? 'strip' : 'transform', sourceMap: values['source-map'],
29
+ });
30
+ if (result.code === null) {
31
+ for (const diagnostic of result.diagnostics) {
32
+ console.error(`${diagnostic.file} [${diagnostic.start}..${diagnostic.end}] ${diagnostic.message}`);
33
+ }
34
+ process.exitCode = 1;
35
+ } else {
36
+ process.stdout.write(result.code);
37
+ if (result.sourceMap) {
38
+ const map = Buffer.from(JSON.stringify(result.sourceMap)).toString('base64');
39
+ process.stdout.write(`\n//# sourceMappingURL=data:application/json;base64,${map}\n`);
40
+ }
41
+ }
42
+ }
43
+ } catch (error) {
44
+ console.error(error.message);
45
+ process.exitCode = 1;
46
+ }
package/bin/tmt.mjs ADDED
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from 'node:fs';
3
+ import { parseArgs } from 'node:util';
4
+ import { chooseFormat, renderText, usage } from '../src/cli-output.mjs';
5
+ import { enablePreparedTypeScript } from '../src/typescript-compiler.mjs';
6
+
7
+ try {
8
+ const [command, ...args] = process.argv.slice(2);
9
+ const { positionals, values } = parseArgs({
10
+ args, allowPositionals: true, options: {
11
+ spec: { type: 'string' },
12
+ mode: { type: 'string' },
13
+ dialect: { type: 'string' },
14
+ lines: { type: 'string', multiple: true },
15
+ since: { type: 'string' },
16
+ deterministic: { type: 'boolean' },
17
+ audit: { type: 'boolean' },
18
+ 'displace-thresholds': { type: 'boolean' },
19
+ 'undo-changes': { type: 'boolean' },
20
+ 'suggest-assertions': { type: 'boolean' },
21
+ witnesses: { type: 'boolean' },
22
+ mutators: { type: 'string' },
23
+ concurrency: { type: 'string' },
24
+ 'isolated-trials': { type: 'boolean' },
25
+ 'verify-trials': { type: 'string' },
26
+ timeout: { type: 'string' },
27
+ runner: { type: 'string' },
28
+ project: { type: 'string', multiple: true },
29
+ config: { type: 'string' },
30
+ test: { type: 'string', multiple: true },
31
+ 'copy-exclude': { type: 'string', multiple: true },
32
+ format: { type: 'string' },
33
+ help: { type: 'boolean', short: 'h' },
34
+ version: { type: 'boolean', short: 'v' },
35
+ },
36
+ });
37
+ if (['--version', '-v'].includes(command) || values.version) {
38
+ console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
39
+ } else if (!command || ['help', '--help', '-h'].includes(command) || values.help) {
40
+ console.log(usage);
41
+ } else if (command === 'extract' && positionals.length === 1) {
42
+ enablePreparedTypeScript();
43
+ const { extract } = await import('../src/extract.mjs');
44
+ const [file] = positionals;
45
+ const result = extract(readFileSync(file), { file, mode: values.mode, dialect: values.dialect });
46
+ console.log(JSON.stringify(result, null, 2));
47
+ if (result.path === 'diagnostic') process.exitCode = 1;
48
+ } else if (command === 'analyze') {
49
+ const [project = '.', ...files] = positionals;
50
+ if (values.runner !== undefined && !['vitest', 'playwright'].includes(values.runner)) throw new Error('Expected --runner vitest|playwright');
51
+ if (values.runner === 'playwright' && values['displace-thresholds']) throw new Error('--displace-thresholds requires Vitest');
52
+ if (values.mutators !== undefined && !['targeted', 'full'].includes(values.mutators)) throw new Error('Expected --mutators targeted|full');
53
+ const session = values.runner !== 'playwright' && !values.witnesses && !values.audit;
54
+ if ((values['isolated-trials'] || values['verify-trials'] !== undefined) && !session) {
55
+ throw new Error('--isolated-trials and --verify-trials apply to Vitest sessions, which --witnesses, --audit and Playwright do not use');
56
+ }
57
+ if (values.concurrency !== undefined && !session && !values.witnesses) {
58
+ throw new Error('--concurrency applies to Vitest sessions and to --witnesses, not to --audit or Playwright');
59
+ }
60
+ if (values['undo-changes'] && (values.since === undefined || values.witnesses)) {
61
+ throw new Error('--undo-changes requires --since REV and does not apply to --witnesses');
62
+ }
63
+ if (values['suggest-assertions'] && (values.runner === 'playwright' || values.witnesses)) {
64
+ throw new Error('--suggest-assertions applies to the targeted and full profiles on Vitest');
65
+ }
66
+ if (values.timeout !== undefined) {
67
+ if (!/^[1-9]\d{0,4}$/.test(values.timeout)) throw new Error('Expected --timeout to be a number of seconds');
68
+ values.timeout = Number(values.timeout);
69
+ }
70
+ if (values['verify-trials'] !== undefined) {
71
+ if (!/^\d{1,6}$/.test(values['verify-trials'])) throw new Error('Expected --verify-trials to be a count');
72
+ values['verify-trials'] = Number(values['verify-trials']);
73
+ }
74
+ if (values.concurrency !== undefined) {
75
+ if (!/^[1-9]\d{0,3}$/.test(values.concurrency)) throw new Error('Expected --concurrency to be a positive integer');
76
+ values.concurrency = Number(values.concurrency);
77
+ }
78
+ const format = chooseFormat(values.format, process.stdout.isTTY === true);
79
+ enablePreparedTypeScript();
80
+ let result;
81
+ if (values.witnesses) {
82
+ if (values.runner === 'playwright' || values.mutators !== undefined ||
83
+ values.deterministic || values.project || values.audit || values['displace-thresholds']) throw new Error('--witnesses runs its own Vitest source trials');
84
+ const { analyzeWitnesses } = await import('../src/witness-analysis.mjs');
85
+ result = await analyzeWitnesses(project, files, values);
86
+ } else {
87
+ const { analyzeOperators } = await import('../src/operator-analysis.mjs');
88
+ result = await analyzeOperators(project, files, { ...values, mutators: values.mutators ?? 'targeted' });
89
+ }
90
+ if (!values.witnesses) {
91
+ const { strengthenAssertions, withoutSourceEdits } = await import('../src/assertion-strength.mjs');
92
+ if (values['suggest-assertions'] && result.evaluation === 'evaluated') result = await strengthenAssertions(realpathSync(project), result, values);
93
+ withoutSourceEdits(result);
94
+ }
95
+ if (values['undo-changes']) {
96
+ const { analyzeUndoneChangesAsync, withUndoneChanges } = await import('../src/change-undone.mjs');
97
+ const { baselineRunSymbol } = await import('../src/analysis.mjs');
98
+ if (result.evaluation !== 'baseline_error') {
99
+ result = withUndoneChanges(result, await analyzeUndoneChangesAsync(project, files, { ...values, existingBaseline: result[baselineRunSymbol] }));
100
+ }
101
+ }
102
+ if (format === 'json') console.log(JSON.stringify(result, null, 2));
103
+ else console.log(renderText(result));
104
+ if (['baseline_error', 'incomplete'].includes(result.evaluation) || result.extraction.some(file => file.path === 'diagnostic')) process.exitCode = 1;
105
+ } else if (command === 'prototype' && positionals.length === 2) {
106
+ enablePreparedTypeScript();
107
+ const { runPrototype } = await import('../src/prototype.mjs');
108
+ console.log(JSON.stringify(runPrototype(...positionals, values), null, 2));
109
+ } else if (['extract', 'analyze', 'prototype'].includes(command)) {
110
+ throw new Error(`Unexpected arguments for ${command}.\n\n${usage}`);
111
+ } else {
112
+ throw new Error(`Unknown command: ${command}\n\n${usage}`);
113
+ }
114
+ } catch (error) {
115
+ console.error(error.message);
116
+ process.exitCode = 1;
117
+ }
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS