mutant-cafe 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -129,6 +129,8 @@ var Baseline = Schema3.Struct({
129
129
  unreliable: Schema3.optional(Schema3.Array(SelectionIssue))
130
130
  });
131
131
  var NotMutated = Schema3.Struct({
132
+ // Optional on decode for existing schemaVersion 2 reports; discovery always supplies it.
133
+ span: Schema3.optional(Span),
132
134
  file: Schema3.String,
133
135
  functionName: Schema3.String,
134
136
  reason: Schema3.String
@@ -155,7 +157,8 @@ var RunReport = Schema3.Struct({
155
157
  baseline: Baseline,
156
158
  timeoutMs: Schema3.Int,
157
159
  results: Schema3.Array(MutantResult),
158
- failure: Schema3.optional(Schema3.String)
160
+ failure: Schema3.optional(Schema3.String),
161
+ notMutated: Schema3.optional(Schema3.Array(NotMutated))
159
162
  });
160
163
 
161
164
  // packages/core/src/Services.ts
@@ -178,6 +181,8 @@ import * as Schema4 from "effect/Schema";
178
181
  // packages/engine/src/Generate.ts
179
182
  import { createHash } from "node:crypto";
180
183
  function* generateFunction(fn9) {
184
+ const issue = fn9.generationIssue?.();
185
+ if (issue) return issue;
181
186
  const api = fn9.api;
182
187
  const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
183
188
  const pinned = `((): ${fn9.returnType} => (${expression}))()`;
@@ -185,25 +190,29 @@ function* generateFunction(fn9) {
185
190
  return makeMutant(fn9, genre, text, value.synthetic, description);
186
191
  };
187
192
  const shape = fn9.shape;
193
+ const fits = (value) => new TextEncoder().encode(value.text).byteLength <= 2048;
194
+ const values = "values" in shape ? shape.values.filter(fits) : [];
188
195
  switch (shape.kind) {
189
196
  case "Effect": {
190
197
  const succeed4 = api("Effect", "succeed");
191
198
  if (succeed4) {
192
- for (const value of shape.values) {
193
- if (!fn9.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed4}(${value.text})`, value);
199
+ for (const value of values) {
200
+ if (!fn9.equivalentValues.includes(value.text) && !(fn9.generator && value.text === fn9.literal)) yield candidate("EffectSucceed", `${succeed4}(${value.text})`, value);
194
201
  }
195
202
  }
196
203
  const fail3 = api("Effect", "fail");
197
204
  const catchTag3 = api("Effect", "catchTag");
198
205
  for (const error3 of shape.errors) {
199
- if (fail3) yield candidate("EffectFail", `${fail3}(${error3.text})`, error3, `${fail3}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
200
- const value = shape.values[0];
201
- const die3 = api("Effect", "die");
202
- const recovery = value && succeed4 ? `${succeed4}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
203
- if (catchTag3 && recovery) {
204
- const gen9 = api("Effect", "gen");
205
- const original = fn9.generator ? gen9 && `((): ${fn9.returnType} => ${gen9}(function* () ${fn9.original}))()` : fn9.block ? `((): ${fn9.returnType} => ${fn9.original})()` : `((): ${fn9.returnType} => (${fn9.original}))()`;
206
- if (original) yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))` : `turn ${error3.tag} into a defect`);
206
+ if (fail3 && fits(error3)) yield candidate("EffectFail", `${fail3}(${error3.text})`, error3, `${fail3}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
207
+ const recoveries = values.length ? shape.enumerateRecoveries ? values : values.slice(0, 1) : [void 0];
208
+ const gen9 = api("Effect", "gen");
209
+ const original = fn9.generator ? gen9 && `((): ${fn9.returnType} => ${gen9}(function* () ${fn9.original}))()` : fn9.block ? `((): ${fn9.returnType} => ${fn9.original})()` : `((): ${fn9.returnType} => (${fn9.original}))()`;
210
+ for (const value of recoveries) {
211
+ const die3 = api("Effect", "die");
212
+ const recovery = value && succeed4 ? `${succeed4}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
213
+ if (catchTag3 && recovery && original) {
214
+ yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))` : `turn ${error3.tag} into a defect`);
215
+ }
207
216
  }
208
217
  }
209
218
  const die2 = api("Effect", "die");
@@ -216,7 +225,7 @@ function* generateFunction(fn9) {
216
225
  const none = api("Option", "none");
217
226
  const some = api("Option", "some");
218
227
  if (none) yield candidate("OptionNone", `${none}()`);
219
- if (some) for (const value of shape.values) yield candidate("OptionSome", `${some}(${value.text})`, value);
228
+ if (some) for (const value of values) yield candidate("OptionSome", `${some}(${value.text})`, value);
220
229
  break;
221
230
  }
222
231
  case "Stream": {
@@ -224,8 +233,10 @@ function* generateFunction(fn9) {
224
233
  const make9 = api("Stream", "make");
225
234
  const fail3 = api("Stream", "fail");
226
235
  if (empty) yield candidate("StreamEmpty", empty);
227
- if (make9) for (const value of shape.values) yield candidate("StreamOne", `${make9}(${value.text})`, value);
228
- if (fail3) for (const error3 of shape.errors) yield candidate("StreamFail", `${fail3}(${error3.text})`, error3);
236
+ if (make9) for (const value of values) yield candidate("StreamOne", `${make9}(${value.text})`, value);
237
+ if (fail3) {
238
+ for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${fail3}(${error3.text})`, error3);
239
+ }
229
240
  break;
230
241
  }
231
242
  case "Layer": {
@@ -234,7 +245,7 @@ function* generateFunction(fn9) {
234
245
  const die2 = api("Effect", "die");
235
246
  if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
236
247
  if (layer2 && fail3) {
237
- for (const error3 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail3}(${error3.text}))`, error3);
248
+ for (const error3 of shape.errors) if (fits(error3)) yield candidate("LayerFail", `${layer2}(${fail3}(${error3.text}))`, error3);
238
249
  }
239
250
  break;
240
251
  }
@@ -243,8 +254,8 @@ function* generateFunction(fn9) {
243
254
  break;
244
255
  default: {
245
256
  const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
246
- for (const value of shape.values) {
247
- if (shape.kind === "Literal" && value.text === fn9.literal) continue;
257
+ for (const value of values) {
258
+ if (value.text === fn9.literal) continue;
248
259
  yield candidate(genre, value.text, value);
249
260
  }
250
261
  }
@@ -309,18 +320,27 @@ var ProgramSession = class {
309
320
  check(mutant) {
310
321
  const file = resolve(mutant.file);
311
322
  const source = this.originals.get(file);
312
- if (!source) throw new ProgramLoadError({ tsconfig: this.configPath, diagnostics: [`File not loaded: ${mutant.file}`] });
323
+ if (!source) return { viable: false, diagnostics: [], analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason: "analysis failed: source file was not loaded" } };
313
324
  const { startOffset, endOffset, text } = mutant.replacement;
314
325
  if (startOffset < 0 || endOffset < startOffset || endOffset > source.text.length) {
315
326
  return { viable: false, diagnostics: ["Replacement offsets are outside the original file"] };
316
327
  }
328
+ const analysisFailed = (reason) => ({
329
+ viable: false,
330
+ diagnostics: [],
331
+ analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason }
332
+ });
317
333
  this.overlay = { file, text: source.text.slice(0, startOffset) + text + source.text.slice(endOffset) };
318
334
  try {
319
335
  const mutated = ts.createProgram({ rootNames: this.program.getRootFileNames(), options: this.program.getCompilerOptions(), host: this.host, oldProgram: this.program });
320
336
  const changed = mutated.getSourceFile(file);
321
337
  if (!changed) throw new Error(`Mutated source not found: ${file}`);
338
+ const issue = typedCallIssue(changed, mutated.getTypeChecker(), true);
339
+ if (issue) return analysisFailed(issue);
322
340
  const diagnostics = [...mutated.getSyntacticDiagnostics(changed), ...mutated.getSemanticDiagnostics(changed)];
323
341
  return { viable: diagnostics.length === 0, diagnostics: diagnosticsText(diagnostics) };
342
+ } catch (error3) {
343
+ return analysisFailed(`analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`);
324
344
  } finally {
325
345
  this.overlay = void 0;
326
346
  }
@@ -351,88 +371,112 @@ function makeTypeScriptOracle() {
351
371
  if (config.exclude.some((glob) => matchesGlob(local, glob))) continue;
352
372
  owners.set(file, session);
353
373
  const api = imports(source);
374
+ const excluded = /* @__PURE__ */ new Set();
354
375
  const visit = (node) => {
355
- if (isFunction(node) && node.body && !mutable(node, checker)) {
356
- notMutated.push({ file, functionName: functionName(node, checker), reason: "unsupported function position: callback, array element or curried implementation" });
357
- }
358
- if (isFunction(node) && node.body && mutable(node, checker)) {
359
- const name = functionName(node, checker);
360
- const reason = skipped(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
361
- if (reason) notMutated.push({ file, functionName: name, reason });
362
- if (!reason && (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter)))) {
363
- const signature = checker.getSignatureFromDeclaration(node);
364
- if (signature) {
365
- const wrapped = wrappedEffect(node, checker);
366
- const type = wrapped ?? checker.getReturnTypeOfSignature(signature);
367
- const generator = wrapped && ts.isFunctionExpression(node) ? node : generatorBody(node, checker);
368
- const body = generator?.body ?? node.body;
369
- const start = body.getStart(source);
370
- const end = body.getEnd();
371
- const a = source.getLineAndCharacterOfPosition(start);
372
- const b = source.getLineAndCharacterOfPosition(end);
373
- const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
374
- const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
375
- const originals = equivalentSuccessValues(body, api);
376
- if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
377
- notMutated.push({ file, functionName: name, reason: "generic: naked or context-only type-parameter return" });
378
- } else found.push({
379
- file,
380
- name,
381
- returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
382
- displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
383
- skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
384
- equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
385
- span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
386
- startOffset: start,
387
- endOffset: end,
388
- original: body.getText(source),
389
- identityFile: local,
390
- logicalSpan: { offset: start - node.getStart(source), length: end - start },
391
- sourcePrefix: source.text.slice(0, start),
392
- importInsertionOffset: importInsertionOffset(source),
393
- extraImports: mutationImports(source),
394
- literal: literalOfBody(body, checker),
395
- block: ts.isBlock(body),
396
- generator: generator !== void 0,
397
- shape,
398
- api
399
- });
400
- } else notMutated.push({ file, functionName: name, reason: "missing callable signature" });
376
+ try {
377
+ if (isFunction(node) && node.body && !mutable(node, checker)) {
378
+ if (!ts.findAncestor(node.parent, (parent) => excluded.has(parent))) notMutated.push({ file, functionName: `${functionName(node, checker)}.<callback>`, span: nodeSpan(node), reason: "callback position (not mutated yet)" });
401
379
  }
402
- }
403
- if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
404
- const type = checker.getTypeAtLocation(node.initializer);
405
- if (family(type, checker)?.kind === "Layer") {
406
- const name = valuePath(node);
407
- const reason = skippedNode(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
408
- if (reason) notMutated.push({ file, functionName: name, reason });
409
- else if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
410
- const body = node.initializer;
411
- const a = source.getLineAndCharacterOfPosition(body.getStart(source));
412
- const b = source.getLineAndCharacterOfPosition(body.getEnd());
413
- found.push({
414
- file,
415
- name,
416
- returnType: returnTypeText(type, checker, node),
417
- displayReturnType: checker.typeToString(type, node),
418
- equivalentValues: [],
419
- span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
420
- startOffset: body.getStart(source),
421
- endOffset: body.getEnd(),
422
- original: body.getText(source),
423
- literal: void 0,
424
- identityFile: local,
425
- logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
426
- sourcePrefix: source.text.slice(0, body.getStart(source)),
427
- importInsertionOffset: importInsertionOffset(source),
428
- extraImports: mutationImports(source),
429
- block: false,
430
- generator: false,
431
- shape: shapeOf(type, checker, node, body),
432
- api
433
- });
380
+ if (isFunction(node) && node.body && mutable(node, checker)) {
381
+ const name = functionName(node, checker);
382
+ const reason = skipped(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
383
+ if (reason) {
384
+ excluded.add(node);
385
+ notMutated.push({ file, functionName: name, span: nodeSpan(node.body), reason });
386
+ }
387
+ if (!reason && (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter)))) {
388
+ const signature = checker.getSignatureFromDeclaration(node);
389
+ if (signature) {
390
+ const wrapped = wrappedEffect(node, checker);
391
+ const type = wrapped ?? checker.getReturnTypeOfSignature(signature);
392
+ const generator = wrapped && ts.isFunctionExpression(node) ? node : generatorBody(node, checker);
393
+ const body = generator?.body ?? node.body;
394
+ const start = body.getStart(source);
395
+ const end = body.getEnd();
396
+ const a = source.getLineAndCharacterOfPosition(start);
397
+ const b = source.getLineAndCharacterOfPosition(end);
398
+ const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
399
+ const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
400
+ const originals = equivalentSuccessValues(body, api);
401
+ if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
402
+ notMutated.push({ file, functionName: name, span: nodeSpan(node), reason: "generic: naked or context-only type-parameter return" });
403
+ } else found.push({
404
+ file,
405
+ name,
406
+ functionLike: true,
407
+ functionSpan: nodeSpan(body),
408
+ generationIssue: () => typedCallIssue(body, checker),
409
+ notices: shapeNotices(shape, type, checker, node),
410
+ returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
411
+ displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
412
+ skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
413
+ equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
414
+ span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
415
+ startOffset: start,
416
+ endOffset: end,
417
+ original: body.getText(source),
418
+ identityFile: local,
419
+ logicalSpan: { offset: start - node.getStart(source), length: end - start },
420
+ sourcePrefix: source.text.slice(0, start),
421
+ importInsertionOffset: importInsertionOffset(source),
422
+ extraImports: mutationImports(source),
423
+ literal: literalOfBody(body, checker),
424
+ block: ts.isBlock(body),
425
+ generator: generator !== void 0,
426
+ shape,
427
+ api
428
+ });
429
+ } else notMutated.push({ file, functionName: name, span: nodeSpan(node), reason: "missing callable signature" });
430
+ }
431
+ }
432
+ if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
433
+ const type = checker.getTypeAtLocation(node.initializer);
434
+ if (family(type, checker)?.kind === "Layer") {
435
+ const name = valuePath(node);
436
+ const reason = skippedNode(node) ? "excluded by @mutants-skip" : config.exportedOnly && !publicOwner(node, checker) ? "excluded by --exported-only" : config.functionFilter.length && !config.functionFilter.some((filter) => matchesGlob(name, filter)) ? "excluded by function filter" : void 0;
437
+ if (reason) {
438
+ excluded.add(node.initializer);
439
+ notMutated.push({ file, functionName: name, span: nodeSpan(node.initializer), reason });
440
+ }
441
+ if (!reason) {
442
+ const body = node.initializer;
443
+ const a = source.getLineAndCharacterOfPosition(body.getStart(source));
444
+ const b = source.getLineAndCharacterOfPosition(body.getEnd());
445
+ found.push({
446
+ file,
447
+ name,
448
+ functionLike: false,
449
+ generationIssue: () => typedCallIssue(body, checker),
450
+ notices: shapeNotices(shapeOf(type, checker, node, body), type, checker, node),
451
+ returnType: returnTypeText(type, checker, node),
452
+ displayReturnType: checker.typeToString(type, node),
453
+ equivalentValues: [],
454
+ span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
455
+ startOffset: body.getStart(source),
456
+ endOffset: body.getEnd(),
457
+ original: body.getText(source),
458
+ literal: void 0,
459
+ identityFile: local,
460
+ logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
461
+ sourcePrefix: source.text.slice(0, body.getStart(source)),
462
+ importInsertionOffset: importInsertionOffset(source),
463
+ extraImports: mutationImports(source),
464
+ block: false,
465
+ generator: false,
466
+ shape: shapeOf(type, checker, node, body),
467
+ api
468
+ });
469
+ }
434
470
  }
435
471
  }
472
+ } catch (error3) {
473
+ const target = isFunction(node) ? node.body : ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node) ? node.initializer : void 0;
474
+ if (target) notMutated.push({
475
+ file,
476
+ functionName: valuePath(node),
477
+ span: nodeSpan(target),
478
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
479
+ });
436
480
  }
437
481
  ts.forEachChild(node, visit);
438
482
  };
@@ -451,15 +495,37 @@ function makeTypeScriptOracle() {
451
495
  const outside = target === ".." || target.startsWith("../");
452
496
  return `No source file matched ${JSON.stringify(glob)}${outside ? " (path is outside the package root)" : ""}`;
453
497
  }) });
454
- return { functions, notMutated };
498
+ return { functions, notMutated: [...new Map(notMutated.map((item) => [JSON.stringify(item), item])).values()] };
455
499
  },
456
500
  checkViable(mutant) {
457
501
  const session = owners.get(resolve(mutant.file));
458
- if (!session) throw new ProgramLoadError({ tsconfig: "", diagnostics: ["Generate mutants before checking viability"] });
502
+ if (!session) return { viable: false, diagnostics: [], analysisFailed: { file: mutant.file, functionName: mutant.functionName, span: mutant.span, reason: "analysis failed: generate mutants before checking viability" } };
459
503
  return session.check(mutant);
460
504
  }
461
505
  };
462
506
  }
507
+ function typedCallIssue(body, checker, includeNested = false) {
508
+ let issue;
509
+ const visit = (node) => {
510
+ if (isFunction(node) && !includeNested) return;
511
+ if (ts.isCallExpression(node) && node.typeArguments?.length) {
512
+ const signature = checker.getResolvedSignature(node);
513
+ if (!signature || !signature.declaration && checker.getTypeAtLocation(node.expression).flags & ts.TypeFlags.Any) {
514
+ issue = `analysis failed: compiler supplied no declaration for typed call ${node.expression.getText()}; check its import or receiver type`;
515
+ return;
516
+ }
517
+ }
518
+ ts.forEachChild(node, visit);
519
+ };
520
+ visit(body);
521
+ return issue;
522
+ }
523
+ function nodeSpan(node) {
524
+ const source = node.getSourceFile();
525
+ const a = source.getLineAndCharacterOfPosition(node.getStart(source));
526
+ const b = source.getLineAndCharacterOfPosition(node.getEnd());
527
+ return { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } };
528
+ }
463
529
  function isFunction(node) {
464
530
  return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
465
531
  }
@@ -615,8 +681,8 @@ function nameableContract(contract, checker, node) {
615
681
  return contract.types.every((type) => !hasUnnameableType(type, checker, node));
616
682
  }
617
683
  function hasUnnameableType(type, checker, location) {
618
- const printed = checker.typeToTypeNode(type, location, ts.NodeBuilderFlags.NoTruncation);
619
- if (!printed) return true;
684
+ if (isFunction(location) && location.type && !location.asteriskToken) return false;
685
+ const printed = ts.createSourceFile("contract.ts", `type Contract = ${returnTypeText(type, checker, location)};`, ts.ScriptTarget.Latest, true);
620
686
  let missing = false;
621
687
  const visit = (node) => {
622
688
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !checker.resolveName(node.typeName.text, location, ts.SymbolFlags.Type, false)) missing = true;
@@ -641,7 +707,7 @@ function generatorContract(node, checker) {
641
707
  return {
642
708
  types: [success, ...effects.flatMap((effect5) => effect5.args.slice(1))],
643
709
  text: `import("effect/Effect").Effect<${print(success)}, ${union(1)}, ${union(2)}>`,
644
- shape: { kind: "Effect", values: valuesOf(success, checker, node), errors: [...new Map(effects.flatMap((f) => f.args[1] ? taggedValues(f.args[1], checker, node) : []).map((e) => [e.tag, e])).values()] }
710
+ shape: { kind: "Effect", values: boundedValues(success, checker, node).values, omittedValues: boundedValues(success, checker, node).omitted, synthesisIssues: boundedValues(success, checker, node).issues, enumerateRecoveries: smallFinite(success), errors: [...new Map(effects.flatMap((f) => f.args[1] ? taggedValues(f.args[1], checker, node) : []).map((e) => [e.tag, e])).values()] }
645
711
  };
646
712
  }
647
713
  function literalOfBody(body, checker) {
@@ -649,7 +715,7 @@ function literalOfBody(body, checker) {
649
715
  const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
650
716
  if (!expression) return void 0;
651
717
  const type = checker.getTypeAtLocation(expression);
652
- return type.isStringLiteral() ? JSON.stringify(type.value) : type.isNumberLiteral() ? String(type.value) : void 0;
718
+ return type.isStringLiteral() ? JSON.stringify(type.value) : type.isNumberLiteral() ? String(type.value) : type.flags & ts.TypeFlags.BooleanLiteral ? checker.typeToString(type) : void 0;
653
719
  }
654
720
  function generatorBody(node, checker) {
655
721
  if (!node.body) return void 0;
@@ -741,34 +807,40 @@ function family(type, checker) {
741
807
  function shapeOf(type, checker, node, body) {
742
808
  if (type.isUnion() && type.types.every((member) => family(member, checker)?.kind === "Effect")) {
743
809
  const shapes = type.types.map((member) => shapeOf(member, checker, node, body));
744
- const values2 = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
810
+ const successes = type.types.flatMap((member) => family(member, checker)?.args[0] ?? []);
811
+ const bounded2 = boundCandidates(successes.flatMap((success) => valuesOf(success, checker, node)), successes, node);
745
812
  const errors = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.errors : []);
746
813
  return {
747
814
  kind: "Effect",
748
- values: [...new Map(values2.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
815
+ values: bounded2.values,
816
+ omittedValues: bounded2.omitted,
817
+ synthesisIssues: shapes.flatMap((shape) => shape.synthesisIssues ?? []),
818
+ enumerateRecoveries: bounded2.values.length <= 4 && successes.every(smallFinite),
749
819
  errors: [...new Map(errors.map((error3) => [error3.tag, error3])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
750
820
  };
751
821
  }
752
822
  const detected = family(type, checker);
753
823
  if (detected) {
754
824
  const [a, e] = detected.args;
755
- const values2 = a ? valuesOf(a, checker, node) : [];
756
- if (detected.kind === "Option") return { kind: "Option", values: values2 };
825
+ if (detected.kind === "Layer") return { kind: "Layer", errors: e ? taggedValues(e, checker, node) : [] };
826
+ const bounded2 = a ? boundedValues(a, checker, node) : { values: [], omitted: 0, issues: [] };
827
+ const values2 = bounded2.values;
828
+ if (detected.kind === "Option") return { kind: "Option", values: values2, omittedValues: bounded2.omitted, synthesisIssues: bounded2.issues };
757
829
  const errors = e ? taggedValues(e, checker, node) : [];
758
- if (detected.kind === "Layer") return { kind: "Layer", errors };
759
- return { kind: detected.kind, values: values2, errors };
830
+ return { kind: detected.kind, values: values2, errors, omittedValues: bounded2.omitted, synthesisIssues: bounded2.issues, enumerateRecoveries: a !== void 0 && smallFinite(a) };
760
831
  }
761
832
  if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
762
833
  const members = type.isUnion() ? type.types : [type];
763
834
  const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
764
835
  const literal = members.every((t) => t.isLiteral());
765
- const values = valuesOf(type, checker, node);
836
+ const bounded = boundedValues(type, checker, node);
837
+ const values = bounded.values;
766
838
  if (isFunction(node)) for (const parameter of node.parameters) {
767
- if (ts.isIdentifier(parameter.name) && !parameter.questionToken && !parameter.dotDotDotToken && checker.getTypeAtLocation(parameter) === type) {
839
+ if (ts.isIdentifier(parameter.name) && checker.isTypeAssignableTo(checker.getTypeAtLocation(parameter), type)) {
768
840
  values.push({ text: parameter.name.text, synthetic: false });
769
841
  }
770
842
  }
771
- return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values };
843
+ return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values, omittedValues: bounded.omitted, synthesisIssues: bounded.issues };
772
844
  }
773
845
  function taggedValues(type, checker, location) {
774
846
  return (type.isUnion() ? type.types : [type]).flatMap((member) => {
@@ -781,32 +853,60 @@ function taggedValues(type, checker, location) {
781
853
  });
782
854
  }
783
855
  function constructError(type, checker, location, tag) {
856
+ const synthetic = (reason) => ({
857
+ text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${returnTypeText(type, checker, location)})`,
858
+ synthetic: true,
859
+ ...reason ? { reason } : {}
860
+ });
784
861
  const symbol = type.getSymbol();
785
862
  if (symbol) {
786
863
  const visible = checker.getSymbolsInScope(location, ts.SymbolFlags.Value | ts.SymbolFlags.Alias).find((candidate) => {
787
- if (candidate.declarations?.some((declaration) => ts.isImportSpecifier(declaration) && (declaration.isTypeOnly || declaration.parent.parent.isTypeOnly))) return false;
864
+ if (candidate.declarations?.some((declaration) => ts.isImportClause(declaration) && declaration.isTypeOnly || ts.isImportSpecifier(declaration) && (declaration.isTypeOnly || declaration.parent.parent.isTypeOnly))) return false;
788
865
  const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
789
866
  return target === symbol || (symbol.declarations?.some((declaration) => target.declarations?.includes(declaration)) ?? false);
790
867
  });
791
868
  if (visible) {
792
869
  const constructor = checker.getTypeOfSymbolAtLocation(visible, location).getConstructSignatures()[0];
793
870
  if (constructor) {
794
- const param = constructor.parameters[0];
795
- if (!param) return { text: `new ${visible.name}()`, synthetic: false };
796
- const fields = checker.getTypeOfSymbolAtLocation(param, location);
797
- if (fields.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) return { text: `new ${visible.name}()`, synthetic: false };
798
- const value = valuesOf(fields, checker, location)[0];
799
- if (value && !value.synthetic) {
800
- const rest = param.valueDeclaration && ts.isParameter(param.valueDeclaration) && param.valueDeclaration.dotDotDotToken;
801
- return { text: `new ${visible.name}(${rest ? "..." : ""}${value.text})`, synthetic: false };
871
+ const arguments_ = [];
872
+ for (const param of constructor.parameters) {
873
+ const fields = checker.getTypeOfSymbolAtLocation(param, location);
874
+ if (fields.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) continue;
875
+ const issues = /* @__PURE__ */ new Set();
876
+ const value = valuesOf(fields, checker, location, /* @__PURE__ */ new Set(), 0, issues)[0];
877
+ if (!value || value.synthetic) {
878
+ const reason = synthesisReason(fields, checker, location);
879
+ const field = /\(field ([^)]+)\)/.exec(reason)?.[1];
880
+ const detail = field ? `field ${field}` : `argument ${param.name} is not synthesizable`;
881
+ return synthetic(detail + (issues.size ? ` (${[...issues].join("; ")})` : ""));
882
+ }
883
+ const declaration = param.valueDeclaration;
884
+ const rest = declaration && ts.isParameter(declaration) && declaration.dotDotDotToken;
885
+ arguments_.push(`${rest ? "..." : ""}${value.text}`);
802
886
  }
887
+ return { text: `new ${visible.name}(${arguments_.join(", ")})`, synthetic: false };
803
888
  }
804
889
  }
890
+ if (symbol.declarations?.some(ts.isClassDeclaration)) {
891
+ return synthetic(visible ? "constructor arguments are not synthesizable" : "class is not available as a value; import its constructor");
892
+ }
805
893
  }
806
- return { text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${checker.typeToString(type, location, ts.TypeFormatFlags.NoTruncation)})`, synthetic: true };
894
+ return synthetic();
807
895
  }
808
896
  function returnTypeText(type, checker, node) {
809
- const print = (t) => checker.typeToString(t, node, ts.TypeFormatFlags.NoTruncation);
897
+ if (isFunction(node) && node.type && !node.asteriskToken && checker.getTypeFromTypeNode(node.type) === type) return node.type.getText();
898
+ const print = (t) => {
899
+ if (t.isUnion()) return t.types.map(print).join(" | ");
900
+ const symbol = t.getSymbol();
901
+ if (symbol && !checker.resolveName(symbol.name, node, ts.SymbolFlags.Type, false)) {
902
+ const alias = checker.getSymbolsInScope(node, ts.SymbolFlags.Type | ts.SymbolFlags.Alias).find((candidate) => {
903
+ const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
904
+ return !!target.declarations?.length && checker.getDeclaredTypeOfSymbol(target) === t;
905
+ });
906
+ if (alias) return alias.name;
907
+ }
908
+ return checker.typeToString(t, node, ts.TypeFormatFlags.NoTruncation);
909
+ };
810
910
  if (type.isUnion()) {
811
911
  const members = type.types.map((member) => family(member, checker));
812
912
  if (members.every((member) => member?.kind === "Effect")) {
@@ -814,11 +914,19 @@ function returnTypeText(type, checker, node) {
814
914
  return `import("effect/Effect").Effect<${args.join(", ")}>`;
815
915
  }
816
916
  }
917
+ const detected = family(type, checker);
918
+ if (detected) return `import("effect/${detected.kind}").${detected.kind}<${detected.args.map(print).join(", ")}>`;
817
919
  return print(type);
818
920
  }
819
921
  function literalData(node) {
820
922
  if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return literalData(node.expression);
821
923
  if (ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return [node.kind, node.text];
924
+ if (ts.isIdentifier(node) && node.text === "undefined") return ["undefined"];
925
+ if (ts.isPrefixUnaryExpression(node)) return [node.operator, literalData(node.operand)];
926
+ if (ts.isArrayLiteralExpression(node)) {
927
+ const items = node.elements.map(literalData);
928
+ return items.every((item) => item !== void 0) ? ["array", items] : void 0;
929
+ }
822
930
  if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword) return [node.kind];
823
931
  if (ts.isObjectLiteralExpression(node)) {
824
932
  const fields = [];
@@ -853,23 +961,102 @@ function isEquivalentSuccess(text, values) {
853
961
  }
854
962
  function synthesisReason(type, checker, node) {
855
963
  if (type.flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess)) return "generic return cannot be synthesized";
856
- const detected = family(type, checker);
857
- const valueType = detected?.args[0] ?? type;
858
- for (const field of valueType.getProperties()) {
859
- if (!(field.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field, node), checker, node).length) {
860
- return `no synthesizable value for field ${field.name}`;
861
- }
964
+ const valueType = family(type, checker)?.args[0] ?? type;
965
+ const field = valueType.getProperties().find((field2) => /^[$\w]+$/.test(field2.name) && !(field2.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field2, node), checker, node).length);
966
+ const symbol = valueType.aliasSymbol ?? valueType.getSymbol();
967
+ const name = symbol && !symbol.name.startsWith("__") ? symbol.name : valueType.isUnion() ? "union" : valueType.flags & ts.TypeFlags.Object || valueType.isIntersection() ? "object" : checker.typeToString(valueType, node);
968
+ return field ? `return not synthesizable (field ${field.name})` : `return not synthesizable (type ${name})`;
969
+ }
970
+ function valueKey(text) {
971
+ const source = ts.createSourceFile("value.ts", `(${text})`, ts.ScriptTarget.Latest, true);
972
+ const statement = source.statements[0];
973
+ const data = statement && ts.isExpressionStatement(statement) ? literalData(statement.expression) : void 0;
974
+ return data === void 0 ? text : JSON.stringify(data);
975
+ }
976
+ function boundedValues(type, checker, node) {
977
+ const issues = /* @__PURE__ */ new Set();
978
+ return { ...boundCandidates(valuesOf(type, checker, node, /* @__PURE__ */ new Set(), 0, issues), [type], node), issues: [...issues] };
979
+ }
980
+ function smallFinite(type) {
981
+ const members = type.isUnion() ? type.types : [type];
982
+ return members.length <= 4 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
983
+ }
984
+ function boundCandidates(candidates, types2, node) {
985
+ const unique = [...new Map(candidates.map((value) => [valueKey(value.text), value])).values()];
986
+ const members = types2.flatMap((type) => type.isUnion() ? type.types : [type]);
987
+ const finite = members.length <= 8 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
988
+ if (finite || unique.length <= 6) return { values: unique, omitted: 0 };
989
+ const absence = unique.find((value) => value.text === "undefined");
990
+ const defined = unique.filter((value) => value !== absence);
991
+ const preferred = ["null", '""', "0", "false", "[]", "({ })"].flatMap((text) => {
992
+ const candidate = defined.find((value) => valueKey(value.text) === valueKey(text));
993
+ return candidate ? [candidate] : [];
994
+ });
995
+ const original = returnedDiscriminants(node);
996
+ const priority = defined.filter((candidate) => {
997
+ const source = ts.createSourceFile("value.ts", `(${candidate.text})`, ts.ScriptTarget.Latest, true);
998
+ const statement = source.statements[0];
999
+ return statement && ts.isExpressionStatement(statement) && objectDiscriminants(statement.expression).some((key) => original.has(key));
1000
+ });
1001
+ const selected = [.../* @__PURE__ */ new Set([...priority, ...preferred, ...defined])].slice(0, 6);
1002
+ if (absence) selected.push(absence);
1003
+ return { values: selected, omitted: unique.length - selected.length };
1004
+ }
1005
+ function objectDiscriminants(node) {
1006
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) node = node.expression;
1007
+ if (!ts.isObjectLiteralExpression(node)) return [];
1008
+ return node.properties.flatMap((field) => {
1009
+ if (!ts.isPropertyAssignment(field) || ts.isComputedPropertyName(field.name)) return [];
1010
+ let value = field.initializer;
1011
+ while (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isSatisfiesExpression(value)) value = value.expression;
1012
+ return ts.isStringLiteral(value) || ts.isNumericLiteral(value) ? [JSON.stringify([field.name.getText().replace(/^["']|["']$/g, ""), value.text])] : [];
1013
+ });
1014
+ }
1015
+ function returnedDiscriminants(node) {
1016
+ if (!isFunction(node) || !node.body) return /* @__PURE__ */ new Set();
1017
+ const result2 = new Set(objectDiscriminants(node.body));
1018
+ const visit = (child) => {
1019
+ if (isFunction(child)) return;
1020
+ if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression)) result2.add(key);
1021
+ ts.forEachChild(child, visit);
1022
+ };
1023
+ visit(node.body);
1024
+ return result2;
1025
+ }
1026
+ function shapeNotices(shape, type, checker, node) {
1027
+ const notices = [...shape.synthesisIssues ?? []];
1028
+ const valueType = family(type, checker)?.args[0] ?? type;
1029
+ if ("values" in shape && shape.values.some((value) => new TextEncoder().encode(value.text).byteLength > 2048)) notices.push("synthesized value exceeds 2048 bytes");
1030
+ const omitted = shape.omittedValues ?? 0;
1031
+ if (omitted) notices.push(`${omitted} more values not generated (representative cap)`);
1032
+ if ("errors" in shape) for (const error3 of shape.errors) {
1033
+ if (error3.reason !== void 0) notices.push(`cannot construct ${error3.tag}: ${error3.reason}`);
1034
+ if (new TextEncoder().encode(error3.text).byteLength > 2048) notices.push(`cannot construct ${error3.tag}: synthesized value exceeds 2048 bytes`);
1035
+ }
1036
+ if ("values" in shape && !shape.values.length && !(valueType.flags & ts.TypeFlags.Never) && shape.kind !== "Void") {
1037
+ notices.push(synthesisReason(type, checker, node));
862
1038
  }
863
- return `opaque return: ${checker.typeToString(type, node)}`;
1039
+ return notices;
864
1040
  }
865
- function valuesOf(type, checker, location, depth = 0) {
866
- if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
1041
+ function valuesOf(type, checker, location, ancestors = /* @__PURE__ */ new Set(), depth = 0, issues = /* @__PURE__ */ new Set()) {
1042
+ if (depth > 4) {
1043
+ issues.add("synthesis depth limit (4) reached");
1044
+ return [];
1045
+ }
1046
+ if (ancestors.has(type) || type.flags & ts.TypeFlags.Never) return [];
1047
+ const values = synthesizeValues(type, checker, location, ancestors, depth, issues);
1048
+ const bounded = values.filter((value) => new TextEncoder().encode(value.text).byteLength <= 2048);
1049
+ if (bounded.length !== values.length) issues.add("synthesized value exceeds 2048 bytes");
1050
+ return bounded;
1051
+ }
1052
+ function synthesizeValues(type, checker, location, ancestors, depth, issues) {
1053
+ const descend = (inner) => valuesOf(inner, checker, location, /* @__PURE__ */ new Set([...ancestors, type]), depth + 1, issues);
867
1054
  const value = (text) => ({ text, synthetic: false });
868
1055
  const detected = family(type, checker);
869
1056
  if (detected && (detected.kind === "Option" || detected.kind === "Effect")) {
870
1057
  const api = imports(location.getSourceFile());
871
1058
  const inner = detected.args[0];
872
- const values = inner ? valuesOf(inner, checker, location, depth + 1) : [];
1059
+ const values = inner ? descend(inner) : [];
873
1060
  const wrap = api(detected.kind, detected.kind === "Option" ? "some" : "succeed");
874
1061
  const none = detected.kind === "Option" ? api("Option", "none") : void 0;
875
1062
  return [
@@ -880,13 +1067,19 @@ function valuesOf(type, checker, location, depth = 0) {
880
1067
  if (type.isIntersection()) {
881
1068
  const primitive = type.types.find((member) => member.flags & (ts.TypeFlags.String | ts.TypeFlags.Number));
882
1069
  const brand = type.types.some((member) => member.getProperties().some((prop) => prop.name.includes("Brand")));
883
- if (primitive && brand) return valuesOf(primitive, checker, location, depth + 1).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
1070
+ if (primitive && brand) return descend(primitive).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
884
1071
  }
885
1072
  const symbol = type.getSymbol();
886
1073
  if ((symbol?.name === "ReadonlySet" || symbol?.name === "Set" || symbol?.name === "ReadonlyMap" || symbol?.name === "Map") && symbol.declarations?.some((d) => /\/lib\.es.*\.d\.ts$/.test(d.getSourceFile().fileName))) {
887
1074
  return [value(symbol.name.endsWith("Set") ? "new Set()" : "new Map()")];
888
1075
  }
889
- if (type.isUnion()) return [...type.types].sort((a, b) => a.isNumberLiteral() && b.isNumberLiteral() ? a.value - b.value : checker.typeToString(a).localeCompare(checker.typeToString(b), "en")).flatMap((member) => valuesOf(member, checker, location, depth + 1));
1076
+ if (type.isUnion()) {
1077
+ const members = [...type.types];
1078
+ if (members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)))) {
1079
+ members.sort((a, b) => a.isNumberLiteral() && b.isNumberLiteral() ? a.value - b.value : checker.typeToString(a).localeCompare(checker.typeToString(b), "en"));
1080
+ }
1081
+ return members.flatMap((member) => descend(member));
1082
+ }
890
1083
  if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
891
1084
  if (type.isNumberLiteral()) return [value(String(type.value))];
892
1085
  if (type.flags & ts.TypeFlags.BooleanLiteral) return [value(checker.typeToString(type))];
@@ -898,34 +1091,48 @@ function valuesOf(type, checker, location, depth = 0) {
898
1091
  if (type.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) return [value("undefined")];
899
1092
  if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) return [value("undefined")];
900
1093
  if (checker.isTupleType(type)) {
901
- const elements = checker.getTypeArguments(type).map((t) => valuesOf(t, checker, location, depth + 1)[0]);
1094
+ const elements = checker.getTypeArguments(type).map((t) => descend(t)[0]);
902
1095
  return elements.every((v) => v !== void 0) ? [value(`[${elements.map((v) => v.text).join(", ")}]`)] : [];
903
1096
  }
904
1097
  if (checker.isArrayType(type) || checker.isArrayLikeType(type)) {
905
1098
  const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
906
- const elements = element ? valuesOf(element, checker, location, depth + 1) : [];
1099
+ const elements = element ? descend(element) : [];
907
1100
  return [value("[]"), ...elements.map((v) => ({ text: `[${v.text}]`, synthetic: v.synthetic }))];
908
1101
  }
909
- if (type.flags & ts.TypeFlags.Object && !type.getCallSignatures().length && !type.getConstructSignatures().length) {
1102
+ if ((type.flags & ts.TypeFlags.Object || type.isIntersection()) && !type.getCallSignatures().length && !type.getConstructSignatures().length) {
910
1103
  const fields = [];
911
1104
  for (const prop of type.getProperties()) {
912
1105
  if (prop.flags & ts.SymbolFlags.Optional) continue;
913
1106
  if (!/^[$\w]+$/.test(prop.name)) return [];
914
- const values = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1);
1107
+ const values = descend(checker.getTypeOfSymbolAtLocation(prop, location));
915
1108
  if (!values.length) return [];
916
1109
  fields.push({ name: prop.name, values });
917
1110
  }
918
1111
  const literalFields = fields.filter((field) => {
919
1112
  const prop = type.getProperty(field.name);
1113
+ if (!prop) return false;
920
1114
  const t = checker.getTypeOfSymbolAtLocation(prop, location);
921
1115
  return (t.isUnion() ? t.types : [t]).every((member) => member.isLiteral() || !!(member.flags & ts.TypeFlags.BooleanLiteral));
922
1116
  });
923
- const render = (changed, replacement) => value(`({ ${fields.map((field) => {
924
- const v = (field === changed ? replacement : field.values[0]).text;
925
- return `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
926
- }).join(", ")} })`);
1117
+ const render = (changed, replacement) => {
1118
+ const parts = [];
1119
+ let bytes = 6;
1120
+ for (const field of fields) {
1121
+ const v = (field === changed ? replacement : field.values[0]).text;
1122
+ const part = `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
1123
+ bytes += new TextEncoder().encode(part).byteLength + (parts.length ? 2 : 0);
1124
+ if (bytes > 2048) {
1125
+ issues.add("synthesized value exceeds 2048 bytes");
1126
+ return void 0;
1127
+ }
1128
+ parts.push(part);
1129
+ }
1130
+ return value(`({ ${parts.join(", ")} })`);
1131
+ };
1132
+ const first = render();
1133
+ if (!first) return [];
927
1134
  const anonymous = !type.aliasSymbol && (!type.getSymbol() || ["__type", "__object"].includes(type.getSymbol().name));
928
- return [render(), ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))) : []];
1135
+ return [first, ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))).filter((value2) => value2 !== void 0) : []];
929
1136
  }
930
1137
  return [];
931
1138
  }
@@ -941,30 +1148,70 @@ function makeMutantSource(oracle) {
941
1148
  const discovered = oracle.discover(config);
942
1149
  const notMutated = [...discovered.notMutated];
943
1150
  const mutants = [];
944
- for (const fn9 of discovered.functions) {
945
- const generated = [...generateFunction(fn9)];
946
- if (!generated.length) notMutated.push({ file: fn9.file, functionName: fn9.name, reason: fn9.skipReason ?? `opaque return or no synthesizable value: ${fn9.displayReturnType}` });
1151
+ const failed = /* @__PURE__ */ new Set();
1152
+ const generatedFunctions = discovered.functions.map((fn9) => {
1153
+ try {
1154
+ const iterator = generateFunction(fn9);
1155
+ const generated = [];
1156
+ let step = iterator.next();
1157
+ while (!step.done) {
1158
+ generated.push(step.value);
1159
+ step = iterator.next();
1160
+ }
1161
+ if (step.value) {
1162
+ failed.add(fn9);
1163
+ notMutated.push({ file: fn9.file, functionName: fn9.name, span: fn9.span, reason: step.value });
1164
+ return { fn: fn9, generated: [] };
1165
+ }
1166
+ return { fn: fn9, generated };
1167
+ } catch (error3) {
1168
+ failed.add(fn9);
1169
+ notMutated.push({
1170
+ file: fn9.file,
1171
+ functionName: fn9.name,
1172
+ span: fn9.span,
1173
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
1174
+ });
1175
+ return { fn: fn9, generated: [] };
1176
+ }
1177
+ });
1178
+ for (const { fn: fn9, generated } of generatedFunctions) {
1179
+ if (failed.has(fn9)) continue;
1180
+ {
1181
+ const reasons = [...fn9.notices ?? []];
1182
+ if (!generated.length && !reasons.length) reasons.push(fn9.skipReason ?? `return not synthesizable (type ${fn9.displayReturnType})`);
1183
+ const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file === fn9.file && inner.startOffset > fn9.startOffset && inner.endOffset < fn9.endOffset && generated2.length > 0);
1184
+ if (innerMutated && !generated.length) {
1185
+ for (let i = 0; i < reasons.length; i++) if (reasons[i].startsWith("return not synthesizable")) reasons[i] += "; inner functions mutated";
1186
+ }
1187
+ if (reasons.length) notMutated.push({ file: fn9.file, functionName: fn9.name, span: fn9.span, reason: [...new Set(reasons)].join("; ") });
1188
+ }
947
1189
  mutants.push(...generated);
948
1190
  }
949
- return { mutants, notMutated };
1191
+ return { mutants, notMutated: [...new Map(notMutated.map((item) => [JSON.stringify(item), item])).values()] };
950
1192
  },
951
- catch: (error3) => loadError(config.tsconfig, error3)
1193
+ catch: (error3) => {
1194
+ if (Schema4.is(ProgramLoadError)(error3)) return error3;
1195
+ throw error3;
1196
+ }
952
1197
  });
953
1198
  return {
954
1199
  notMutated: (config) => discover(config).pipe(Effect.map((result2) => result2.notMutated)),
955
1200
  generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result2) => Stream.fromIterable(result2.mutants)))),
956
- checkViable: (mutant) => Effect.try({
957
- try: () => oracle.checkViable(mutant),
958
- catch: (error3) => loadError("", error3)
1201
+ checkViable: (mutant) => Effect.sync(() => {
1202
+ try {
1203
+ return oracle.checkViable(mutant);
1204
+ } catch (error3) {
1205
+ return { viable: false, diagnostics: [], analysisFailed: {
1206
+ file: mutant.file,
1207
+ functionName: mutant.functionName,
1208
+ span: mutant.span,
1209
+ reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
1210
+ } };
1211
+ }
959
1212
  })
960
1213
  };
961
1214
  }
962
- function loadError(tsconfig, error3) {
963
- return Schema4.is(ProgramLoadError)(error3) ? error3 : new ProgramLoadError({
964
- tsconfig,
965
- diagnostics: [error3 instanceof Error ? error3.message : String(error3)]
966
- });
967
- }
968
1215
 
969
1216
  // packages/runner/src/Scratch.ts
970
1217
  import * as Effect2 from "effect/Effect";
@@ -1395,6 +1642,7 @@ var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
1395
1642
  baseline: state2.baseline,
1396
1643
  timeoutMs: state2.timeoutMs,
1397
1644
  results: state2.results,
1645
+ notMutated: state2.notMutated,
1398
1646
  ...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${state2.failure.command.join(" ")}
1399
1647
  ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1400
1648
  });
@@ -1433,6 +1681,10 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1433
1681
  yield* Stream3.fromIterable(input.state.pending).pipe(
1434
1682
  Stream3.mapEffect((mutant) => Effect5.scoped(Effect5.gen(function* () {
1435
1683
  const viability = yield* source.checkViable(mutant);
1684
+ if (viability.analysisFailed) {
1685
+ yield* input.skip(viability.analysisFailed);
1686
+ return;
1687
+ }
1436
1688
  if (!viability.viable) {
1437
1689
  const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
1438
1690
  yield* input.record(result3);
@@ -1476,7 +1728,7 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1476
1728
  const machine = setupEffect({
1477
1729
  schemas: {
1478
1730
  context: types(),
1479
- events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }) }
1731
+ events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }), SKIP: Schema7.Struct({ entry: NotMutated }) }
1480
1732
  },
1481
1733
  actors: { copying, baselining, generating, testing, reporting }
1482
1734
  }).createMachine({
@@ -1487,12 +1739,14 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1487
1739
  pool: void 0,
1488
1740
  pending: [],
1489
1741
  results: [],
1490
- reported: false
1742
+ reported: false,
1743
+ notMutated: []
1491
1744
  },
1492
1745
  output: ({ context }) => context,
1493
- initial: "copying",
1746
+ initial: "generating",
1494
1747
  on: {
1495
1748
  CANCEL: { target: ".interrupted" },
1749
+ SKIP: ({ context, event }) => ({ context: { ...context, notMutated: [...new Map([...context.notMutated, event.entry].map((entry) => [JSON.stringify(entry), entry])).values()] } }),
1496
1750
  RESULT: ({ context, event }) => ({ context: { ...context, results: [...context.results, event.result] } })
1497
1751
  },
1498
1752
  states: {
@@ -1500,20 +1754,21 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
1500
1754
  baseline: { invoke: {
1501
1755
  src: "baselining",
1502
1756
  input: ({ context }) => context.pool,
1503
- onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
1757
+ onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "testing", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
1504
1758
  ...context,
1505
1759
  failure: event.output.failure,
1506
1760
  baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
1507
1761
  } }
1508
1762
  } },
1509
- generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "testing", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
1763
+ generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: event.output.success.length ? "copying" : "reporting", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
1510
1764
  testing: { invoke: {
1511
1765
  src: "testing",
1512
1766
  input: ({ context, self }) => ({
1513
1767
  state: context,
1514
1768
  // Queue completion before progress can trigger CANCEL. The parent's
1515
1769
  // FIFO mailbox commits this result before handling that cancellation.
1516
- record: (result2) => send(self, { type: "RESULT", result: result2 })
1770
+ record: (result2) => send(self, { type: "RESULT", result: result2 }),
1771
+ skip: (entry) => send(self, { type: "SKIP", entry })
1517
1772
  }),
1518
1773
  onDone: ({ context, event }) => ({ target: "reporting", context: {
1519
1774
  ...context,
@@ -1845,8 +2100,7 @@ var markdownSummary = (options) => {
1845
2100
  ...report.failure === void 0 ? [] : [`Failure: ${cell(report.failure)}`, ""],
1846
2101
  options.advisory ? `Advisory: would exit ${exit} without --advisory.` : `Exit code: ${exit}.`,
1847
2102
  "",
1848
- "| File:line | Function | Description | Outcome |",
1849
- "| --- | --- | --- | --- |",
2103
+ ...rows.length ? ["| File:line | Function | Description | Outcome |", "| --- | --- | --- | --- |"] : report.failure === void 0 ? ["No actionable mutants."] : [],
1850
2104
  ...rows.slice(0, 50).map(({ mutant, outcome }) => `| ${cell(path.relative(options.gitRoot, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))}:${mutant.span.start.line} | ${cell(mutant.functionName)} | ${cell(mutant.description)} | ${outcome} |`),
1851
2105
  ...rows.length > 50 ? ["", `and ${rows.length - 50} more`] : [],
1852
2106
  ""
@@ -1898,7 +2152,7 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1898
2152
  }).pipe(Effect7.mapError(writeError));
1899
2153
  const encodedMutants = yield* Schema9.encodeEffect(Schema9.fromJsonString(Schema9.Array(Mutant)))(options.mutants).pipe(Effect7.mapError(writeError));
1900
2154
  yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect7.mapError(writeError));
1901
- yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}: ${item.functionName}: ${item.reason}
2155
+ yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
1902
2156
  `).join("")).pipe(Effect7.mapError(writeError));
1903
2157
  yield* Effect7.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect7.mapError(writeError));
1904
2158
  for (const mutant of options.mutants) {
@@ -1926,8 +2180,12 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1926
2180
  })),
1927
2181
  write: (report) => semaphore.withPermit(Effect7.gen(function* () {
1928
2182
  if (pendingError !== void 0) return yield* pendingError;
2183
+ const notMutated = [...new Map([...options.notMutated ?? [], ...report.notMutated ?? []].map((item) => [JSON.stringify(item), item])).values()];
2184
+ yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), notMutated.map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
2185
+ `).join("")).pipe(Effect7.mapError(writeError));
1929
2186
  const counted = {
1930
2187
  ...report,
2188
+ notMutated,
1931
2189
  selected: options.selected ?? options.mutants.length,
1932
2190
  run: report.results.length,
1933
2191
  budgetSkipped: options.budgetSkipped ?? 0
@@ -1941,7 +2199,7 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1941
2199
  yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect7.mapError(writeError));
1942
2200
  }
1943
2201
  if (options.markdown !== void 0) {
1944
- const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: options.notMutated?.length ?? 0 });
2202
+ const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: notMutated.length });
1945
2203
  for (const file of new Set(options.markdown.files)) {
1946
2204
  yield* fs.writeFileString(file, markdown).pipe(Effect7.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) })));
1947
2205
  }
@@ -1951,7 +2209,7 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
1951
2209
  summarized = true;
1952
2210
  if (report.results.some((result2) => result2.outcome === "unreliable")) yield* Console2.warn("Unreliable: the configured Vitest run cannot see all tests. See unreliable.txt and per-mutant diagnostics; these are not missed mutants.");
1953
2211
  const elapsed = (yield* Clock2.currentTimeMillis) - started;
1954
- if (!options.markdown?.stdout) yield* Console2.log(countsLine(counted, options.notMutated?.length ?? 0) + `; ${(elapsed / 1e3).toFixed(2)}s`);
2212
+ if (!options.markdown?.stdout) yield* Console2.log(countsLine(counted, notMutated.length) + `; ${(elapsed / 1e3).toFixed(2)}s`);
1955
2213
  if (options.markdown === void 0 && report.failure !== void 0) yield* Console2.warn(report.failure);
1956
2214
  }))
1957
2215
  });
@@ -2062,6 +2320,10 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
2062
2320
  const mutants = ordered.slice(0, maxMutants);
2063
2321
  const notMutated = selected.notMutated;
2064
2322
  const counts = { selected: ordered.length, run: 0, budgetSkipped: ordered.length - mutants.length };
2323
+ if (mutants.length === 0) {
2324
+ const cause = ordered.length > 0 ? "budget" : range !== void 0 ? "range" : inDiff !== void 0 || diffText !== void 0 ? "diff" : config.functionFilter.length || config.exportedOnly ? "filter" : "file selection";
2325
+ yield* Console3.error(`0 mutants selected (${counts.selected} before budget); cause: ${cause}. Baseline skipped.`);
2326
+ }
2065
2327
  const markdown = input.format === "github" || summaryMd !== void 0 ? {
2066
2328
  gitRoot,
2067
2329
  marker: input.summaryMarker,
@@ -2107,7 +2369,14 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
2107
2369
  return;
2108
2370
  }
2109
2371
  const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated, selected: counts.selected, budgetSkipped: counts.budgetSkipped, ...markdown === void 0 ? {} : { markdown } });
2110
- const report = yield* options.run(config, mutants).pipe(
2372
+ const report = yield* (mutants.length === 0 ? Effect9.succeed({
2373
+ schemaVersion: 2,
2374
+ tool: "mutant.cafe",
2375
+ root,
2376
+ baseline: { durationMs: 0, testCommand: [] },
2377
+ timeoutMs: 0,
2378
+ results: []
2379
+ }) : options.run(config, mutants)).pipe(
2111
2380
  Effect9.provideService(Reporter, reporter),
2112
2381
  Effect9.catchTag("BaselineFailed", (error3) => Effect9.gen(function* () {
2113
2382
  const failed = {
@@ -2133,7 +2402,7 @@ ${error3.output.slice(-8e3)}`
2133
2402
  var runCli = Effect9.fn("runCli")(function* (options) {
2134
2403
  const code = yield* Ref.make(0);
2135
2404
  const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
2136
- yield* Command.runWith(command, { version: "0.1.4" })(options.args).pipe(
2405
+ yield* Command.runWith(command, { version: "0.1.5" })(options.args).pipe(
2137
2406
  Effect9.catch((error3) => Effect9.gen(function* () {
2138
2407
  yield* Console3.error(error3._tag === "ProgramLoadError" ? `${error3.tsconfig}:
2139
2408
  ${error3.diagnostics.join("\n")}` : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${error3.command.join(" ")}