@t09tanaka/test-gates 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,594 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/vitest.ts
31
+ var vitest_exports = {};
32
+ __export(vitest_exports, {
33
+ createVitestGatesConfig: () => createVitestGatesConfig
34
+ });
35
+ module.exports = __toCommonJS(vitest_exports);
36
+
37
+ // src/load.ts
38
+ var import_node_fs2 = __toESM(require("fs"), 1);
39
+ var import_node_path2 = __toESM(require("path"), 1);
40
+
41
+ // src/core/manifest.ts
42
+ var MANIFEST_FILE = "test-gates.json";
43
+ var ManifestError = class extends Error {
44
+ };
45
+ function isRecord(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ function isFilled(value) {
49
+ return typeof value === "string" && value.trim() !== "";
50
+ }
51
+ function allowanceProblems(entry) {
52
+ if (!isRecord(entry)) {
53
+ return [" must be an object"];
54
+ }
55
+ const problems = [];
56
+ if (!isFilled(entry.mutator)) {
57
+ problems.push(': "mutator" is missing');
58
+ }
59
+ if (!isFilled(entry.original)) {
60
+ problems.push(': "original" is missing');
61
+ }
62
+ if (typeof entry.replacement !== "string") {
63
+ problems.push(': "replacement" is missing');
64
+ }
65
+ if (!isFilled(entry.reason)) {
66
+ problems.push(': "reason" is missing (say why the mutant cannot be observed)');
67
+ }
68
+ if (entry.occurrence !== void 0 && !(Number.isInteger(entry.occurrence) && entry.occurrence >= 1)) {
69
+ problems.push(': "occurrence" must be an integer >= 1');
70
+ }
71
+ return problems;
72
+ }
73
+ function validateEquivalentMutants(gatePath, value) {
74
+ if (value === void 0) {
75
+ return [];
76
+ }
77
+ if (!Array.isArray(value)) {
78
+ return [{ file: MANIFEST_FILE, message: `${gatePath}: equivalentMutants must be an array` }];
79
+ }
80
+ return value.flatMap(
81
+ (entry, index) => allowanceProblems(entry).map((problem) => ({
82
+ file: MANIFEST_FILE,
83
+ message: `${gatePath}: equivalentMutants[${index}]${problem}`
84
+ }))
85
+ );
86
+ }
87
+ function parseEntries(kind, entries, fields, violations) {
88
+ const usable = [];
89
+ const seen = /* @__PURE__ */ new Set();
90
+ entries.forEach((entry, index) => {
91
+ const at = `${kind}[${index}]`;
92
+ if (!isRecord(entry)) {
93
+ violations.push({ file: MANIFEST_FILE, message: `${at} must be an object` });
94
+ return;
95
+ }
96
+ if (!isFilled(entry.path)) {
97
+ violations.push({ file: MANIFEST_FILE, message: `${at}: "path" is missing` });
98
+ return;
99
+ }
100
+ for (const field of fields) {
101
+ if (!isFilled(entry[field])) {
102
+ violations.push({
103
+ file: MANIFEST_FILE,
104
+ message: `${entry.path}: "${field}" is missing in ${kind}`
105
+ });
106
+ }
107
+ }
108
+ if (seen.has(entry.path)) {
109
+ violations.push({ file: MANIFEST_FILE, message: `${entry.path}: listed twice in ${kind}` });
110
+ return;
111
+ }
112
+ seen.add(entry.path);
113
+ usable.push(entry);
114
+ });
115
+ return usable;
116
+ }
117
+ function parseManifest(text) {
118
+ let raw;
119
+ try {
120
+ raw = JSON.parse(text);
121
+ } catch (error) {
122
+ throw new ManifestError(`${MANIFEST_FILE} is not valid JSON: ${error.message}`);
123
+ }
124
+ if (!isRecord(raw)) {
125
+ throw new ManifestError(`${MANIFEST_FILE} must be a JSON object`);
126
+ }
127
+ if (!Array.isArray(raw.gates)) {
128
+ throw new ManifestError(`${MANIFEST_FILE}: "gates" must be an array`);
129
+ }
130
+ if (raw.candidates !== void 0 && !Array.isArray(raw.candidates)) {
131
+ throw new ManifestError(`${MANIFEST_FILE}: "candidates" must be an array`);
132
+ }
133
+ for (const key of Object.keys(raw)) {
134
+ if (!["$schema", "gates", "candidates", "settings"].includes(key)) {
135
+ throw new ManifestError(`${MANIFEST_FILE}: unknown top-level key ${JSON.stringify(key)}`);
136
+ }
137
+ }
138
+ const violations = [];
139
+ if (raw.gates.length === 0) {
140
+ violations.push({
141
+ file: MANIFEST_FILE,
142
+ message: "gates is empty. A project with nothing to gate should not have this file"
143
+ });
144
+ }
145
+ const gates = parseEntries("gates", raw.gates, ["decides", "impact"], violations);
146
+ const candidates = parseEntries(
147
+ "candidates",
148
+ raw.candidates ?? [],
149
+ ["decides", "blocker"],
150
+ violations
151
+ );
152
+ const gatePaths = new Set(gates.map((gate) => gate.path));
153
+ for (const candidate of candidates) {
154
+ if (gatePaths.has(candidate.path)) {
155
+ violations.push({
156
+ file: MANIFEST_FILE,
157
+ message: `${candidate.path}: listed in both gates and candidates`
158
+ });
159
+ }
160
+ }
161
+ for (const gate of gates) {
162
+ violations.push(...validateEquivalentMutants(gate.path, gate.equivalentMutants));
163
+ }
164
+ return { gates, candidates, settings: raw.settings, violations };
165
+ }
166
+
167
+ // src/core/settings.ts
168
+ var DEFAULT_REPORT_FILE = "reports/mutation/mutation.json";
169
+ var DEFAULT_GATE_EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
170
+ var DEFAULT_IMPURE_IMPORTS = [
171
+ { pattern: "^@nestjs/", reason: "NestJS runtime (DI, decorators)" },
172
+ { pattern: "^class-(validator|transformer)$", reason: "decorator-based DTO library" },
173
+ {
174
+ pattern: "^(typeorm|sequelize|mongoose|knex|pg|mysql|mysql2|ioredis|redis)(/|$)",
175
+ reason: "database client"
176
+ },
177
+ { pattern: "^@prisma/adapter-", reason: "database client" },
178
+ { pattern: "^(react|react-dom)(/|$)", reason: "React runtime" },
179
+ { pattern: "^next(/|$)", reason: "Next.js runtime" },
180
+ { pattern: "^(server-only|client-only)$", reason: "Next.js execution environment" },
181
+ { pattern: "^(vue|vue-router|vue-i18n|pinia)(/|$)", reason: "Vue runtime" },
182
+ { pattern: "^nuxt(/|$)", reason: "Nuxt runtime" },
183
+ { pattern: "^#(app|imports)(/|$)", reason: "Nuxt runtime" },
184
+ { pattern: "\\.vue$", reason: "component" },
185
+ {
186
+ pattern: "^(express|express-jwt|fastify|koa|rxjs|passport)(/|$)",
187
+ reason: "HTTP framework runtime"
188
+ },
189
+ { pattern: "^passport-", reason: "HTTP framework runtime" },
190
+ {
191
+ pattern: "^(axios|openapi-fetch|stripe|nodemailer|firebase-admin)(/|$)",
192
+ reason: "HTTP client / external service SDK"
193
+ },
194
+ { pattern: "^@(aws-sdk|sentry|slack|stripe)/", reason: "external service SDK" },
195
+ {
196
+ pattern: "^(node:)?(fs|http|https|http2|net|tls|dgram|dns|child_process|worker_threads)(/|$)",
197
+ reason: "file system / network / process access"
198
+ }
199
+ ];
200
+ var DEFAULT_IMPURE_NAMED_IMPORTS = [
201
+ { module: "@prisma/client", names: ["PrismaClient"], reason: "connects to the database" }
202
+ ];
203
+ var DEFAULT_IMPURE_PATHS = [
204
+ { pattern: "\\.(vue|jsx|tsx)$", reason: "component file" },
205
+ { pattern: "\\.d\\.[cm]?ts$", reason: "type declaration file" }
206
+ ];
207
+ var DEFAULT_FORBIDDEN_SOURCE = [
208
+ {
209
+ pattern: `^\\s*(['"])use (client|server)\\1`,
210
+ reason: "'use client' / 'use server' directive (not a pure module)"
211
+ }
212
+ ];
213
+ var SettingsError = class extends Error {
214
+ };
215
+ function isRecord2(value) {
216
+ return typeof value === "object" && value !== null && !Array.isArray(value);
217
+ }
218
+ function compile(pattern, flags, where) {
219
+ try {
220
+ return new RegExp(pattern, flags);
221
+ } catch (error) {
222
+ throw new SettingsError(
223
+ `${where}: invalid regular expression ${JSON.stringify(pattern)} (${error.message})`
224
+ );
225
+ }
226
+ }
227
+ function stringArray(value, where) {
228
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === "")) {
229
+ throw new SettingsError(`${where}: must be an array of non-empty strings`);
230
+ }
231
+ return value;
232
+ }
233
+ function optionalString(value, where) {
234
+ if (value === void 0) {
235
+ return null;
236
+ }
237
+ if (typeof value !== "string" || value === "") {
238
+ throw new SettingsError(`${where}: must be a non-empty string`);
239
+ }
240
+ return value;
241
+ }
242
+ function rejectUnknownKeys(value, known, where) {
243
+ for (const key of Object.keys(value)) {
244
+ if (!known.includes(key)) {
245
+ throw new SettingsError(`${where}: unknown key ${JSON.stringify(key)}`);
246
+ }
247
+ }
248
+ }
249
+ function section(value, known, where) {
250
+ if (value === void 0) {
251
+ return {};
252
+ }
253
+ if (!isRecord2(value)) {
254
+ throw new SettingsError(`${where}: must be an object`);
255
+ }
256
+ rejectUnknownKeys(value, known, where);
257
+ return value;
258
+ }
259
+ function compileRules(defaults, raw, where, extraKeys = []) {
260
+ const config = section(raw, ["defaults", "add", ...extraKeys], where);
261
+ if (config.defaults !== void 0 && typeof config.defaults !== "boolean") {
262
+ throw new SettingsError(`${where}.defaults: must be a boolean`);
263
+ }
264
+ const added = config.add ?? [];
265
+ if (!Array.isArray(added)) {
266
+ throw new SettingsError(`${where}.add: must be an array`);
267
+ }
268
+ const all = [];
269
+ if (config.defaults !== false) {
270
+ defaults.forEach((rule) => all.push({ rule, where: `${where} (default)` }));
271
+ }
272
+ added.forEach((item, index) => {
273
+ const at = `${where}.add[${index}]`;
274
+ if (typeof item === "string" && item !== "") {
275
+ all.push({ rule: { pattern: item }, where: at });
276
+ return;
277
+ }
278
+ if (!isRecord2(item) || typeof item.pattern !== "string" || item.pattern === "") {
279
+ throw new SettingsError(`${at}: must be a pattern string or { pattern, flags?, reason? }`);
280
+ }
281
+ rejectUnknownKeys(item, ["pattern", "flags", "reason"], at);
282
+ if (item.flags !== void 0 && typeof item.flags !== "string") {
283
+ throw new SettingsError(`${at}.flags: must be a string`);
284
+ }
285
+ if (item.reason !== void 0 && typeof item.reason !== "string") {
286
+ throw new SettingsError(`${at}.reason: must be a string`);
287
+ }
288
+ all.push({ rule: item, where: at });
289
+ });
290
+ return {
291
+ rules: all.map(({ rule, where: at }) => ({
292
+ regex: compile(rule.pattern, rule.flags, at),
293
+ reason: rule.reason ?? `matches ${rule.pattern}`
294
+ })),
295
+ section: config
296
+ };
297
+ }
298
+ function resolveSettings(raw) {
299
+ const settings = section(
300
+ raw,
301
+ [
302
+ "gateExtensions",
303
+ "spec",
304
+ "impureImports",
305
+ "impureNamedImports",
306
+ "impurePaths",
307
+ "forbiddenSource",
308
+ "importAliases",
309
+ "gateCommand",
310
+ "selfcheck",
311
+ "stryker",
312
+ "lcov"
313
+ ],
314
+ "settings"
315
+ );
316
+ const gateExtensions = settings.gateExtensions === void 0 ? DEFAULT_GATE_EXTENSIONS : stringArray(settings.gateExtensions, "settings.gateExtensions");
317
+ if (gateExtensions.length === 0 || gateExtensions.some((ext) => !ext.startsWith("."))) {
318
+ throw new SettingsError(
319
+ 'settings.gateExtensions: must list at least one extension starting with "."'
320
+ );
321
+ }
322
+ const spec = section(settings.spec, ["suffixes", "rewrite"], "settings.spec");
323
+ const specSuffixes = spec.suffixes === void 0 ? null : stringArray(spec.suffixes, "settings.spec.suffixes");
324
+ const rewriteRaw = spec.rewrite ?? [];
325
+ if (!Array.isArray(rewriteRaw)) {
326
+ throw new SettingsError("settings.spec.rewrite: must be an array");
327
+ }
328
+ const specRewrite = rewriteRaw.map((item, index) => {
329
+ const at = `settings.spec.rewrite[${index}]`;
330
+ if (!isRecord2(item) || typeof item.from !== "string" || typeof item.to !== "string") {
331
+ throw new SettingsError(`${at}: must be { from, to }`);
332
+ }
333
+ rejectUnknownKeys(item, ["from", "to"], at);
334
+ return { regex: compile(item.from, void 0, at), to: item.to };
335
+ });
336
+ const imports = compileRules(
337
+ DEFAULT_IMPURE_IMPORTS,
338
+ settings.impureImports,
339
+ "settings.impureImports",
340
+ ["allow"]
341
+ );
342
+ const allowedImports = imports.section.allow === void 0 ? [] : stringArray(imports.section.allow, "settings.impureImports.allow").map(
343
+ (pattern, index) => compile(pattern, void 0, `settings.impureImports.allow[${index}]`)
344
+ );
345
+ const named = section(
346
+ settings.impureNamedImports,
347
+ ["defaults", "add"],
348
+ "settings.impureNamedImports"
349
+ );
350
+ if (named.defaults !== void 0 && typeof named.defaults !== "boolean") {
351
+ throw new SettingsError("settings.impureNamedImports.defaults: must be a boolean");
352
+ }
353
+ const namedAdd = named.add ?? [];
354
+ if (!Array.isArray(namedAdd)) {
355
+ throw new SettingsError("settings.impureNamedImports.add: must be an array");
356
+ }
357
+ const impureNamedImports = [
358
+ ...named.defaults === false ? [] : DEFAULT_IMPURE_NAMED_IMPORTS,
359
+ ...namedAdd.map((item, index) => {
360
+ const at = `settings.impureNamedImports.add[${index}]`;
361
+ if (!isRecord2(item) || typeof item.module !== "string" || item.module === "") {
362
+ throw new SettingsError(`${at}: must be { module, names, reason? }`);
363
+ }
364
+ rejectUnknownKeys(item, ["module", "names", "reason"], at);
365
+ const names = stringArray(item.names, `${at}.names`);
366
+ if (names.length === 0) {
367
+ throw new SettingsError(`${at}.names: must list at least one name`);
368
+ }
369
+ if (item.reason !== void 0 && typeof item.reason !== "string") {
370
+ throw new SettingsError(`${at}.reason: must be a string`);
371
+ }
372
+ return {
373
+ module: item.module,
374
+ names,
375
+ reason: item.reason ?? "not allowed in a pure module"
376
+ };
377
+ })
378
+ ];
379
+ const aliasesRaw = settings.importAliases ?? [];
380
+ if (!Array.isArray(aliasesRaw)) {
381
+ throw new SettingsError("settings.importAliases: must be an array");
382
+ }
383
+ const importAliases = aliasesRaw.map((item, index) => {
384
+ const at = `settings.importAliases[${index}]`;
385
+ if (!isRecord2(item) || typeof item.prefix !== "string" || item.prefix === "" || typeof item.target !== "string") {
386
+ throw new SettingsError(`${at}: must be { prefix, target }`);
387
+ }
388
+ rejectUnknownKeys(item, ["prefix", "target"], at);
389
+ return { prefix: item.prefix, target: item.target };
390
+ });
391
+ let gateCommand = null;
392
+ if (settings.gateCommand !== void 0) {
393
+ gateCommand = stringArray(settings.gateCommand, "settings.gateCommand");
394
+ if (gateCommand.length === 0) {
395
+ throw new SettingsError("settings.gateCommand: must not be empty");
396
+ }
397
+ }
398
+ const selfcheck = section(settings.selfcheck, ["mode", "failurePattern"], "settings.selfcheck");
399
+ if (selfcheck.mode !== void 0 && selfcheck.mode !== "all" && selfcheck.mode !== "first") {
400
+ throw new SettingsError('settings.selfcheck.mode: must be "all" or "first"');
401
+ }
402
+ const selfcheckFailurePattern = optionalString(
403
+ selfcheck.failurePattern,
404
+ "settings.selfcheck.failurePattern"
405
+ );
406
+ if (selfcheckFailurePattern !== null) {
407
+ compile(
408
+ selfcheckFailurePattern.split("{gate}").join("x"),
409
+ void 0,
410
+ "settings.selfcheck.failurePattern"
411
+ );
412
+ }
413
+ const stryker = section(settings.stryker, ["configFile", "reportFile"], "settings.stryker");
414
+ const lcov = section(settings.lcov, ["file", "summaryExclude"], "settings.lcov");
415
+ return {
416
+ gateExtensions,
417
+ specSuffixes,
418
+ specRewrite,
419
+ impureImports: imports.rules,
420
+ allowedImports,
421
+ impureNamedImports,
422
+ impurePaths: compileRules(DEFAULT_IMPURE_PATHS, settings.impurePaths, "settings.impurePaths").rules,
423
+ forbiddenSource: compileRules(
424
+ DEFAULT_FORBIDDEN_SOURCE,
425
+ settings.forbiddenSource,
426
+ "settings.forbiddenSource"
427
+ ).rules,
428
+ importAliases,
429
+ gateCommand,
430
+ selfcheckMode: selfcheck.mode ?? "all",
431
+ selfcheckFailurePattern,
432
+ strykerConfigFile: optionalString(stryker.configFile, "settings.stryker.configFile"),
433
+ strykerReportFile: optionalString(stryker.reportFile, "settings.stryker.reportFile") ?? DEFAULT_REPORT_FILE,
434
+ lcovFile: optionalString(lcov.file, "settings.lcov.file"),
435
+ lcovSummaryExclude: lcov.summaryExclude === void 0 ? [] : stringArray(lcov.summaryExclude, "settings.lcov.summaryExclude").map(
436
+ (pattern, index) => compile(pattern, void 0, `settings.lcov.summaryExclude[${index}]`)
437
+ )
438
+ };
439
+ }
440
+
441
+ // src/core/selfcheck.ts
442
+ var EXCLUDE_ENV = "TEST_GATES_EXCLUDE_SPEC";
443
+
444
+ // src/core/spec-path.ts
445
+ function gateExtensionOf(gatePath, gateExtensions) {
446
+ const matching = gateExtensions.filter((extension) => gatePath.endsWith(extension)).sort((a, b) => b.length - a.length);
447
+ return matching[0] ?? null;
448
+ }
449
+ function suffixesFor(extension, settings) {
450
+ return settings.specSuffixes ?? [`.spec${extension}`, `.test${extension}`];
451
+ }
452
+ function specCandidatesFor(gatePath, settings) {
453
+ const extension = gateExtensionOf(gatePath, settings.gateExtensions);
454
+ if (extension === null) {
455
+ return [];
456
+ }
457
+ let base = gatePath.slice(0, -extension.length);
458
+ for (const { regex, to } of settings.specRewrite) {
459
+ base = base.replace(regex, to);
460
+ }
461
+ return suffixesFor(extension, settings).map((suffix) => base + suffix);
462
+ }
463
+
464
+ // src/fs.ts
465
+ var import_node_fs = __toESM(require("fs"), 1);
466
+ var import_node_path = __toESM(require("path"), 1);
467
+ function existsExact(rootDir, relativePath, kind = "file") {
468
+ let current = rootDir;
469
+ for (const segment of relativePath.split("/")) {
470
+ if (segment === "" || segment === ".") {
471
+ continue;
472
+ }
473
+ let entries;
474
+ try {
475
+ entries = import_node_fs.default.readdirSync(current);
476
+ } catch {
477
+ return false;
478
+ }
479
+ if (!entries.includes(segment)) {
480
+ return false;
481
+ }
482
+ current = import_node_path.default.join(current, segment);
483
+ }
484
+ try {
485
+ return kind === "any" || import_node_fs.default.statSync(current).isFile();
486
+ } catch {
487
+ return false;
488
+ }
489
+ }
490
+
491
+ // src/load.ts
492
+ function readManifest(dir) {
493
+ const absoluteDir = import_node_path2.default.resolve(dir);
494
+ const manifestPath = import_node_path2.default.join(absoluteDir, MANIFEST_FILE);
495
+ let text;
496
+ try {
497
+ text = import_node_fs2.default.readFileSync(manifestPath, "utf8");
498
+ } catch (error) {
499
+ if (error.code === "ENOENT") {
500
+ throw new ManifestError(`${MANIFEST_FILE} not found in ${absoluteDir}`);
501
+ }
502
+ throw new ManifestError(`cannot read ${manifestPath}: ${error.message}`);
503
+ }
504
+ const parsed = parseManifest(text);
505
+ let settings;
506
+ try {
507
+ settings = resolveSettings(parsed.settings);
508
+ } catch (error) {
509
+ if (error instanceof SettingsError) {
510
+ throw new ManifestError(`${MANIFEST_FILE}: ${error.message}`);
511
+ }
512
+ throw error;
513
+ }
514
+ const gates = parsed.gates.map((gate) => {
515
+ const specCandidates = specCandidatesFor(gate.path, settings);
516
+ const existingSpecs = specCandidates.filter((candidate) => existsExact(absoluteDir, candidate));
517
+ return {
518
+ ...gate,
519
+ specCandidates,
520
+ existingSpecs,
521
+ spec: existingSpecs[0] ?? specCandidates[0] ?? null
522
+ };
523
+ });
524
+ return {
525
+ dir: absoluteDir,
526
+ gates,
527
+ candidates: parsed.candidates,
528
+ settings,
529
+ violations: parsed.violations
530
+ };
531
+ }
532
+ function loadGates(dir = process.cwd()) {
533
+ const manifest = readManifest(dir);
534
+ if (manifest.violations.length > 0) {
535
+ throw new ManifestError(
536
+ `${MANIFEST_FILE} has problems (run "test-gates check"):
537
+ ` + manifest.violations.map((violation) => ` - ${violation.message}`).join("\n")
538
+ );
539
+ }
540
+ return manifest;
541
+ }
542
+ function gateSpecs(manifest, env = process.env) {
543
+ const excluded = env[EXCLUDE_ENV];
544
+ return manifest.gates.map((gate) => gate.spec).filter((spec) => spec !== null && spec !== excluded);
545
+ }
546
+ var NO_SPEC_PATTERN = "__test_gates_no_spec_left__";
547
+
548
+ // src/shared.ts
549
+ var import_node_path3 = __toESM(require("path"), 1);
550
+ var import_node_url = require("url");
551
+ var FULL_COVERAGE = { statements: 100, branches: 100, functions: 100, lines: 100 };
552
+ function resolveRootDir(rootDir) {
553
+ if (rootDir === void 0) {
554
+ return process.cwd();
555
+ }
556
+ if (rootDir.startsWith("file:")) {
557
+ return import_node_path3.default.dirname((0, import_node_url.fileURLToPath)(rootDir));
558
+ }
559
+ return import_node_path3.default.resolve(rootDir);
560
+ }
561
+
562
+ // src/vitest.ts
563
+ function createVitestGatesConfig(options = {}) {
564
+ const { rootDir: rootDirOption, test = {}, ...overrides } = options;
565
+ const rootDir = resolveRootDir(rootDirOption);
566
+ const manifest = loadGates(rootDir);
567
+ const { coverage = {}, ...testOverrides } = test;
568
+ const specs = gateSpecs(manifest);
569
+ return {
570
+ ...overrides,
571
+ root: rootDir,
572
+ test: {
573
+ environment: "node",
574
+ ...testOverrides,
575
+ include: specs.length > 0 ? specs : [NO_SPEC_PATTERN],
576
+ // `test-gates selfcheck` leaves out the only spec of a single-gate project; the run must
577
+ // then fail on the coverage threshold, not on "no test files found".
578
+ passWithNoTests: true,
579
+ coverage: {
580
+ provider: "v8",
581
+ reporter: ["text"],
582
+ reportsDirectory: "coverage/gates",
583
+ ...coverage,
584
+ enabled: true,
585
+ include: manifest.gates.map((gate) => gate.path),
586
+ thresholds: { perFile: true, ...FULL_COVERAGE }
587
+ }
588
+ }
589
+ };
590
+ }
591
+ // Annotate the CommonJS export names for ESM import in node:
592
+ 0 && (module.exports = {
593
+ createVitestGatesConfig
594
+ });
@@ -0,0 +1,20 @@
1
+ interface VitestGatesOptions {
2
+ /** Directory of test-gates.json: `__dirname`, or `import.meta.url` of the config file. */
3
+ rootDir?: string;
4
+ /** `test` options of Vitest. `include` and `coverage.include/thresholds/enabled` are owned by the helper. */
5
+ test?: Record<string, unknown> & {
6
+ coverage?: Record<string, unknown>;
7
+ };
8
+ /** Any other Vite option: resolve.alias, esbuild, plugins, … */
9
+ [option: string]: unknown;
10
+ }
11
+ /**
12
+ * Vitest config for the gate run: only the specs of the gates, only the gates measured, every
13
+ * gate at 100% on all four metrics (`thresholds.perFile`).
14
+ *
15
+ * Glob or path keys are deliberately not used in `thresholds`: Vitest passes when such a key
16
+ * matches no file. Pass the result to `defineConfig`.
17
+ */
18
+ declare function createVitestGatesConfig(options?: VitestGatesOptions): Record<string, unknown>;
19
+
20
+ export { type VitestGatesOptions, createVitestGatesConfig };
@@ -0,0 +1,20 @@
1
+ interface VitestGatesOptions {
2
+ /** Directory of test-gates.json: `__dirname`, or `import.meta.url` of the config file. */
3
+ rootDir?: string;
4
+ /** `test` options of Vitest. `include` and `coverage.include/thresholds/enabled` are owned by the helper. */
5
+ test?: Record<string, unknown> & {
6
+ coverage?: Record<string, unknown>;
7
+ };
8
+ /** Any other Vite option: resolve.alias, esbuild, plugins, … */
9
+ [option: string]: unknown;
10
+ }
11
+ /**
12
+ * Vitest config for the gate run: only the specs of the gates, only the gates measured, every
13
+ * gate at 100% on all four metrics (`thresholds.perFile`).
14
+ *
15
+ * Glob or path keys are deliberately not used in `thresholds`: Vitest passes when such a key
16
+ * matches no file. Pass the result to `defineConfig`.
17
+ */
18
+ declare function createVitestGatesConfig(options?: VitestGatesOptions): Record<string, unknown>;
19
+
20
+ export { type VitestGatesOptions, createVitestGatesConfig };
package/dist/vitest.js ADDED
@@ -0,0 +1,42 @@
1
+ import {
2
+ FULL_COVERAGE,
3
+ resolveRootDir
4
+ } from "./chunk-4HAJIKDZ.js";
5
+ import {
6
+ NO_SPEC_PATTERN,
7
+ gateSpecs,
8
+ loadGates
9
+ } from "./chunk-LMD3ANJ2.js";
10
+
11
+ // src/vitest.ts
12
+ function createVitestGatesConfig(options = {}) {
13
+ const { rootDir: rootDirOption, test = {}, ...overrides } = options;
14
+ const rootDir = resolveRootDir(rootDirOption);
15
+ const manifest = loadGates(rootDir);
16
+ const { coverage = {}, ...testOverrides } = test;
17
+ const specs = gateSpecs(manifest);
18
+ return {
19
+ ...overrides,
20
+ root: rootDir,
21
+ test: {
22
+ environment: "node",
23
+ ...testOverrides,
24
+ include: specs.length > 0 ? specs : [NO_SPEC_PATTERN],
25
+ // `test-gates selfcheck` leaves out the only spec of a single-gate project; the run must
26
+ // then fail on the coverage threshold, not on "no test files found".
27
+ passWithNoTests: true,
28
+ coverage: {
29
+ provider: "v8",
30
+ reporter: ["text"],
31
+ reportsDirectory: "coverage/gates",
32
+ ...coverage,
33
+ enabled: true,
34
+ include: manifest.gates.map((gate) => gate.path),
35
+ thresholds: { perFile: true, ...FULL_COVERAGE }
36
+ }
37
+ }
38
+ };
39
+ }
40
+ export {
41
+ createVitestGatesConfig
42
+ };