carrick 0.3.156 → 0.3.158

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 (166) hide show
  1. package/dist/cli.d.ts +7 -0
  2. package/dist/cli.js +4 -0
  3. package/dist/cli.js.map +1 -1
  4. package/dist/contract.d.ts +8 -1
  5. package/dist/contract.js.map +1 -1
  6. package/dist/engine-ask.d.ts +21 -0
  7. package/dist/engine-ask.js +50 -0
  8. package/dist/engine-ask.js.map +1 -0
  9. package/dist/facts/diff.d.ts +14 -1
  10. package/dist/facts/diff.js +21 -8
  11. package/dist/facts/diff.js.map +1 -1
  12. package/dist/facts/enabled.d.ts +6 -0
  13. package/dist/facts/enabled.js +8 -0
  14. package/dist/facts/enabled.js.map +1 -1
  15. package/dist/facts/fetch.d.ts +7 -0
  16. package/dist/facts/fetch.js +24 -2
  17. package/dist/facts/fetch.js.map +1 -1
  18. package/dist/facts/lines.d.ts +22 -4
  19. package/dist/facts/lines.js +31 -9
  20. package/dist/facts/lines.js.map +1 -1
  21. package/dist/facts/peers.d.ts +13 -4
  22. package/dist/facts/peers.js +17 -15
  23. package/dist/facts/peers.js.map +1 -1
  24. package/dist/facts/rules/packages.js +3 -1
  25. package/dist/facts/rules/packages.js.map +1 -1
  26. package/dist/facts/rules/same-name.js +1 -1
  27. package/dist/facts/rules/same-name.js.map +1 -1
  28. package/dist/facts/store.d.ts +15 -0
  29. package/dist/facts/store.js +30 -0
  30. package/dist/facts/store.js.map +1 -1
  31. package/dist/held/backoff.d.ts +8 -0
  32. package/dist/held/backoff.js +43 -0
  33. package/dist/held/backoff.js.map +1 -0
  34. package/dist/held/build.d.ts +17 -0
  35. package/dist/held/build.js +62 -0
  36. package/dist/held/build.js.map +1 -0
  37. package/dist/held/client.d.ts +43 -0
  38. package/dist/held/client.js +200 -0
  39. package/dist/held/client.js.map +1 -0
  40. package/dist/held/daemon.d.ts +151 -0
  41. package/dist/held/daemon.js +399 -0
  42. package/dist/held/daemon.js.map +1 -0
  43. package/dist/held/early.d.ts +28 -0
  44. package/dist/held/early.js +115 -0
  45. package/dist/held/early.js.map +1 -0
  46. package/dist/held/engine.d.ts +50 -0
  47. package/dist/held/engine.js +166 -0
  48. package/dist/held/engine.js.map +1 -0
  49. package/dist/held/paths.d.ts +15 -0
  50. package/dist/held/paths.js +44 -0
  51. package/dist/held/paths.js.map +1 -0
  52. package/dist/held/place.d.ts +130 -0
  53. package/dist/held/place.js +236 -0
  54. package/dist/held/place.js.map +1 -0
  55. package/dist/held/registry.d.ts +22 -0
  56. package/dist/held/registry.js +72 -0
  57. package/dist/held/registry.js.map +1 -0
  58. package/dist/held/run.d.ts +2 -0
  59. package/dist/held/run.js +78 -0
  60. package/dist/held/run.js.map +1 -0
  61. package/dist/held/runtime.d.ts +22 -0
  62. package/dist/held/runtime.js +612 -0
  63. package/dist/held/runtime.js.map +1 -0
  64. package/dist/held/shadow.d.ts +33 -0
  65. package/dist/held/shadow.js +68 -0
  66. package/dist/held/shadow.js.map +1 -0
  67. package/dist/held/steps.d.ts +11 -0
  68. package/dist/held/steps.js +29 -0
  69. package/dist/held/steps.js.map +1 -0
  70. package/dist/hook/bash-targets.d.ts +7 -2
  71. package/dist/hook/bash-targets.js +82 -27
  72. package/dist/hook/bash-targets.js.map +1 -1
  73. package/dist/hook/confirm.d.ts +79 -0
  74. package/dist/hook/confirm.js +220 -0
  75. package/dist/hook/confirm.js.map +1 -0
  76. package/dist/hook/edit-flow.d.ts +14 -3
  77. package/dist/hook/edit-flow.js +113 -33
  78. package/dist/hook/edit-flow.js.map +1 -1
  79. package/dist/hook/generation.d.ts +19 -0
  80. package/dist/hook/generation.js +75 -0
  81. package/dist/hook/generation.js.map +1 -0
  82. package/dist/hook/late.d.ts +50 -9
  83. package/dist/hook/late.js +104 -24
  84. package/dist/hook/late.js.map +1 -1
  85. package/dist/hook/lock.d.ts +26 -0
  86. package/dist/hook/lock.js +122 -0
  87. package/dist/hook/lock.js.map +1 -0
  88. package/dist/hook/post-bash.js +17 -8
  89. package/dist/hook/post-bash.js.map +1 -1
  90. package/dist/hook/post-edit.js +2 -2
  91. package/dist/hook/post-edit.js.map +1 -1
  92. package/dist/hook/post-read.js +25 -3
  93. package/dist/hook/post-read.js.map +1 -1
  94. package/dist/hook/post-search.js +1 -1
  95. package/dist/hook/post-search.js.map +1 -1
  96. package/dist/hook/probe.js +1 -0
  97. package/dist/hook/probe.js.map +1 -1
  98. package/dist/hook/read-answer.d.ts +5 -0
  99. package/dist/hook/read-answer.js +8 -4
  100. package/dist/hook/read-answer.js.map +1 -1
  101. package/dist/hook/rechecks.d.ts +59 -2
  102. package/dist/hook/rechecks.js +129 -119
  103. package/dist/hook/rechecks.js.map +1 -1
  104. package/dist/hook/session-start.d.ts +1 -1
  105. package/dist/hook/session-start.js +19 -5
  106. package/dist/hook/session-start.js.map +1 -1
  107. package/dist/hook/similar.d.ts +1 -1
  108. package/dist/hook/similar.js +21 -8
  109. package/dist/hook/similar.js.map +1 -1
  110. package/dist/hook/stop-wait.js +35 -16
  111. package/dist/hook/stop-wait.js.map +1 -1
  112. package/dist/hook/timings.d.ts +30 -2
  113. package/dist/hook/timings.js +8 -2
  114. package/dist/hook/timings.js.map +1 -1
  115. package/dist/hook/user-prompt.js +2 -2
  116. package/dist/hook/user-prompt.js.map +1 -1
  117. package/dist/hosted-snapshot.d.ts +27 -0
  118. package/dist/hosted-snapshot.js +32 -0
  119. package/dist/hosted-snapshot.js.map +1 -1
  120. package/dist/init/hosted.js +2 -9
  121. package/dist/init/hosted.js.map +1 -1
  122. package/dist/lsp-frame.d.ts +20 -0
  123. package/dist/lsp-frame.js +47 -0
  124. package/dist/lsp-frame.js.map +1 -0
  125. package/dist/render.d.ts +15 -1
  126. package/dist/render.js +50 -4
  127. package/dist/render.js.map +1 -1
  128. package/dist/server.js +5 -29
  129. package/dist/server.js.map +1 -1
  130. package/package.json +6 -6
  131. package/plugin/.claude-plugin/plugin.json +1 -1
  132. package/sidecar/dist/src/capture/anchors.d.ts +8 -0
  133. package/sidecar/dist/src/capture/anchors.js +3 -2
  134. package/sidecar/dist/src/capture/api.d.ts +98 -1
  135. package/sidecar/dist/src/capture/check-classify.d.ts +7 -0
  136. package/sidecar/dist/src/capture/check-classify.js +24 -0
  137. package/sidecar/dist/src/capture/check-probe.d.ts +86 -11
  138. package/sidecar/dist/src/capture/check-probe.js +175 -22
  139. package/sidecar/dist/src/capture/check.js +13 -1
  140. package/sidecar/dist/src/capture/graphql-leaves.d.ts +46 -0
  141. package/sidecar/dist/src/capture/graphql-leaves.js +142 -0
  142. package/sidecar/dist/src/capture/index.d.ts +12 -3
  143. package/sidecar/dist/src/capture/index.js +11 -2
  144. package/sidecar/dist/src/capture/result-label.js +3 -1
  145. package/sidecar/dist/src/capture/type-reasons.json +78 -0
  146. package/sidecar/dist/src/definition-resolver.d.ts +6 -5
  147. package/sidecar/dist/src/definition-resolver.js +20 -15
  148. package/sidecar/dist/src/engine-stamp.json +1 -0
  149. package/sidecar/dist/src/held-shadow.d.ts +70 -0
  150. package/sidecar/dist/src/held-shadow.js +222 -0
  151. package/sidecar/dist/src/index.js +65 -2
  152. package/sidecar/dist/src/library-claims.d.ts +3 -1
  153. package/sidecar/dist/src/library-claims.js +105 -6
  154. package/sidecar/dist/src/retype.d.ts +47 -0
  155. package/sidecar/dist/src/retype.js +274 -18
  156. package/sidecar/dist/src/site-find.d.ts +27 -0
  157. package/sidecar/dist/src/site-find.js +109 -0
  158. package/sidecar/dist/src/type-home.d.ts +12 -0
  159. package/sidecar/dist/src/type-home.js +41 -1
  160. package/sidecar/dist/src/type-inferrer.d.ts +13 -3
  161. package/sidecar/dist/src/type-inferrer.js +44 -22
  162. package/sidecar/dist/src/type-structural-expander.d.ts +11 -11
  163. package/sidecar/dist/src/type-structural-expander.js +73 -4
  164. package/sidecar/dist/src/types.d.ts +91 -5
  165. package/sidecar/dist/src/validators.d.ts +621 -254
  166. package/sidecar/dist/src/validators.js +37 -0
@@ -93,6 +93,8 @@ export class Retyper {
93
93
  // comment over the rest of the call.
94
94
  return abstain(item, "the producer's response type carries a comment");
95
95
  }
96
+ if (item.procedure_path)
97
+ return this.runProcedure(item, producer, before);
96
98
  const found = this.beforeRewrite(item);
97
99
  if (typeof found === 'string')
98
100
  return abstain(item, found);
@@ -339,14 +341,7 @@ export class Retyper {
339
341
  // Appended only when the rewrite names them: an alias nothing references
340
342
  // is a TS6196 under `noUnusedLocals`, which would read as the producer's
341
343
  // type failing to resolve.
342
- const appendix = rewrite.wire
343
- ? '\n' +
344
- [
345
- ...this.jsonWire(PREFIX),
346
- `type ${WIRE}<P> = ${PREFIX}JsonWireSame<${PREFIX}JsonWire<P>, P> extends true ? P : ${PREFIX}JsonWire<P>;`,
347
- ].join('\n') +
348
- '\n'
349
- : '';
344
+ const appendix = rewrite.wire ? '\n' + this.wireDeclarations().join('\n') + '\n' : '';
350
345
  const rewritten = applyEdits(original, rewrite.edits) + appendix;
351
346
  const bodyEnd = rewritten.length - appendix.length;
352
347
  const originOf = (pos) => pos >= bodyEnd ? { kind: 'inserted' } : mapBack(pos, rewrite.edits);
@@ -455,10 +450,223 @@ export class Retyper {
455
450
  const deciding = unknowns.length > 0 ? unknowns : diagnosed ? [] : anys;
456
451
  if (deciding.length === 0)
457
452
  return undefined;
458
- const members = deciding
459
- .map(({ kind, path }) => (path === '' ? `'${kind}'` : `'${kind}' at '${path}'`))
460
- .join(', ');
461
- return `the producer's response reads as ${members} in the consumer's program, so it was not compared`;
453
+ return `the producer's response reads as ${membersText(deciding)} in the consumer's program, so it was not compared`;
454
+ }
455
+ /**
456
+ * The JSON wire transform's declarations and the `${WIRE}<P>` alias that
457
+ * states a type in its wire form, as appended to a file that names them.
458
+ */
459
+ wireDeclarations() {
460
+ return [
461
+ ...this.jsonWire(PREFIX),
462
+ `type ${WIRE}<P> = ${PREFIX}JsonWireSame<${PREFIX}JsonWire<P>, P> extends true ? P : ${PREFIX}JsonWire<P>;`,
463
+ ];
464
+ }
465
+ /**
466
+ * The procedure form (carrick#937): judge a procedure call by the
467
+ * consumer's own code against the call's own type.
468
+ *
469
+ * A procedure call's type IS the producer's router type, read by the
470
+ * consumer's compiler, so stating the producer's output at the call would
471
+ * compare one type with itself. What breaks is the consumer's use of it.
472
+ * The file is type-checked as it is and again with only the call's result
473
+ * erased (`(<call> as any)`): a diagnostic present as-is and gone when
474
+ * erased is a place the consumer uses what the procedure does not return.
475
+ *
476
+ * A guard runs first: the call's result (or one member of it, for a hook's
477
+ * envelope such as `{ data }`) must be the producer's published output, as
478
+ * declared or in its JSON wire form. A call whose result is something else
479
+ * (an options builder's `{ key }`), or a router on disk that no longer
480
+ * returns what the producer published, is not compared: erasing it would
481
+ * agree about nothing.
482
+ */
483
+ runProcedure(item, producer, before) {
484
+ const located = this.locateProcedureCall(item, item.procedure_path);
485
+ if (typeof located === 'string')
486
+ return abstain(item, located);
487
+ const { sourceFile, call } = located;
488
+ if (resultIsDiscarded(call))
489
+ return abstain(item, 'the consumer never reads the response');
490
+ const escape = resultEscapes(call);
491
+ if (escape)
492
+ return abstain(item, escape);
493
+ // Read now: every text replacement makes ts-morph forget the file's
494
+ // nodes, `call` included.
495
+ const start = call.getStart();
496
+ const end = call.getEnd();
497
+ const original = sourceFile.getFullText();
498
+ let pre = before.get(sourceFile);
499
+ if (!pre) {
500
+ pre = fileDiagnostics(sourceFile);
501
+ before.set(sourceFile, pre);
502
+ }
503
+ const top = this.procedureTopTypes(call);
504
+ if (typeof top === 'string')
505
+ return abstain(item, top);
506
+ const carried = this.carriesProducerOutput(sourceFile, original, producer, start, end);
507
+ if (typeof carried === 'string')
508
+ return abstain(item, carried);
509
+ // Erase only what carries the output. A result that IS the output is
510
+ // erased to `any`. A result that carries it in one member (a hook's
511
+ // `{ data: O | undefined }`) keeps its envelope, and that member keeps its
512
+ // `null`/`undefined`: an error the client's own envelope raises
513
+ // (`result.data` possibly undefined) is the same with any output, so it
514
+ // must stay when the output is erased, not read as a break.
515
+ const edits = carried.member === undefined
516
+ ? [
517
+ { start, end: start, text: '(' },
518
+ { start: end, end, text: ' as any)' },
519
+ ]
520
+ : [
521
+ { start, end: start, text: `${ERASE_MEMBER}(` },
522
+ { start: end, end, text: `, ${JSON.stringify(carried.member)})` },
523
+ ];
524
+ const appendix = carried.member === undefined ? '' : '\n' + eraseMemberDeclarations().join('\n') + '\n';
525
+ const body = applyEdits(original, edits);
526
+ let erased;
527
+ replaceFileText(sourceFile, body + appendix);
528
+ try {
529
+ erased = fileDiagnostics(sourceFile).flatMap((d) => {
530
+ if (d.start >= body.length)
531
+ return [];
532
+ const origin = mapBack(d.start, edits);
533
+ return origin.kind === 'inserted' ? [] : [{ ...d, start: origin.pos }];
534
+ });
535
+ }
536
+ finally {
537
+ replaceFileText(sourceFile, original);
538
+ }
539
+ // Present as-is and gone once the result is erased: the reverse of
540
+ // `check`, which counts what a stated type adds.
541
+ const remaining = new Map();
542
+ for (const d of erased)
543
+ remaining.set(key(d), (remaining.get(key(d)) ?? 0) + 1);
544
+ const added = [];
545
+ for (const d of pre) {
546
+ if (UNUSED_DECLARATION_CODES.has(d.code))
547
+ continue;
548
+ const left = remaining.get(key(d)) ?? 0;
549
+ if (left > 0) {
550
+ remaining.set(key(d), left - 1);
551
+ continue;
552
+ }
553
+ added.push(d);
554
+ }
555
+ added.sort((a, b) => a.start - b.start || a.code - b.code);
556
+ if (added.length === 0) {
557
+ if (top.length > 0) {
558
+ return abstain(item, `the procedure call's result reads as ${membersText(top)} in the consumer's program, so it was not compared`);
559
+ }
560
+ return { item_id: item.item_id, outcome: 'agrees', diagnostics: [] };
561
+ }
562
+ const lineOf = lineIndex(original);
563
+ return {
564
+ item_id: item.item_id,
565
+ outcome: 'mismatch',
566
+ diagnostics: added.map((d) => ({ line: lineOf(d.start), code: d.code, message: d.message })),
567
+ };
568
+ }
569
+ /**
570
+ * The one call to the procedure `procedurePath` names that starts on the
571
+ * item's line: a call whose callee is `R.s1.….sk.m`, with `s1..sk` the key
572
+ * path's segments, `m` any name (the client's operation) and `R` any
573
+ * expression (the client). Or why there is not exactly one.
574
+ */
575
+ locateProcedureCall(item, procedurePath) {
576
+ const sourceFile = this.inferrer.sourceFileOf(item.file_path);
577
+ if (!sourceFile)
578
+ return 'the procedure call could not be located on its line';
579
+ const segments = procedurePath.split('.');
580
+ const calls = sourceFile
581
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
582
+ .filter((c) => c.getStartLineNumber() === item.line_number && namesProcedure(c, segments));
583
+ if (calls.length === 0)
584
+ return 'the procedure call could not be located on its line';
585
+ if (calls.length > 1) {
586
+ return 'two calls to the procedure start on one line, so the call cannot be told apart';
587
+ }
588
+ return { sourceFile, call: calls[0] };
589
+ }
590
+ /**
591
+ * The `any` members of the call's awaited result, which can only hide a
592
+ * diagnostic and so decide only an empty diff, or why the result cannot be
593
+ * compared at all (`any`/`unknown` as a whole, `unknown` at a member). The
594
+ * walk's budget sentinel is dropped, as {@link unresolvedMembers} drops it.
595
+ */
596
+ procedureTopTypes(call) {
597
+ const program = this.project.getProgram().compilerObject;
598
+ const checker = program.getTypeChecker();
599
+ const own = awaitedResult(checker, call.compilerNode);
600
+ for (const [flag, kind] of [
601
+ [ts.TypeFlags.Any, 'any'],
602
+ [ts.TypeFlags.Unknown, 'unknown'],
603
+ ]) {
604
+ if (own.flags & flag) {
605
+ return `the procedure call's result reads as '${kind}' in the consumer's program, so it was not compared`;
606
+ }
607
+ }
608
+ const found = this.topTypes(own, program, checker, call.compilerNode);
609
+ const unknowns = found.filter((finding) => finding.kind === 'unknown');
610
+ if (unknowns.length > 0) {
611
+ return `the procedure call's result reads as ${membersText(unknowns)} in the consumer's program, so it was not compared`;
612
+ }
613
+ return found.filter((finding) => finding.kind === 'any');
614
+ }
615
+ /**
616
+ * Guard (carrick#937): what carries the producer's published output,
617
+ * declared or in its JSON wire form (each way assignable to the other),
618
+ * read in the consumer's own program: the call's awaited result as a whole
619
+ * (`member` unset), or for an object result the string-named member that
620
+ * does once `null`/`undefined` are removed. Else why the call is not
621
+ * compared.
622
+ */
623
+ carriesProducerOutput(sourceFile, original, producer, start, end) {
624
+ const out = `${PREFIX}ProcOut`;
625
+ const wire = `${PREFIX}ProcWire`;
626
+ const appendix = '\n' +
627
+ [
628
+ ...this.wireDeclarations(),
629
+ `type ${out} = (${producer});`,
630
+ `type ${wire} = ${WIRE}<(${producer})>;`,
631
+ ].join('\n') +
632
+ '\n';
633
+ replaceFileText(sourceFile, original + appendix);
634
+ try {
635
+ const unresolved = fileDiagnostics(sourceFile).find((d) => d.start >= original.length && !UNUSED_DECLARATION_CODES.has(d.code));
636
+ if (unresolved) {
637
+ return ("the producer's output does not resolve in the consumer's program: " +
638
+ `TS${unresolved.code}: ${unresolved.message}`);
639
+ }
640
+ const call = callAt(sourceFile, start, end);
641
+ if (!call)
642
+ return 'the procedure call could not be found again after the rewrite';
643
+ const checker = this.project.getProgram().compilerObject.getTypeChecker();
644
+ const stated = [out, wire].flatMap((name) => {
645
+ const alias = sourceFile.getTypeAlias(name);
646
+ return alias ? [checker.getTypeAtLocation(alias.getNameNode().compilerNode)] : [];
647
+ });
648
+ const own = awaitedResult(checker, call.compilerNode);
649
+ const candidates = [{ type: own }];
650
+ if (own.flags & ts.TypeFlags.Object && !checker.isArrayType(own) && !checker.isTupleType(own)) {
651
+ for (const property of checker.getPropertiesOfType(own)) {
652
+ // A symbol-keyed member has no name the erase can write.
653
+ if (property.escapedName.toString().startsWith('__@'))
654
+ continue;
655
+ candidates.push({
656
+ type: checker.getNonNullableType(checker.getTypeOfSymbol(property)),
657
+ member: property.getName(),
658
+ });
659
+ }
660
+ }
661
+ const same = (a, b) => checker.isTypeAssignableTo(a, b) && checker.isTypeAssignableTo(b, a);
662
+ const carrier = candidates.find((c) => stated.some((t) => same(t, c.type)));
663
+ if (carrier)
664
+ return { member: carrier.member };
665
+ return "the call's result does not carry the procedure's output as the producer publishes it";
666
+ }
667
+ finally {
668
+ replaceFileText(sourceFile, original);
669
+ }
462
670
  }
463
671
  /**
464
672
  * The stated type argument must be what the call RETURNS (or a type
@@ -468,9 +676,7 @@ export class Retyper {
468
676
  * consumer against the wrong thing, so the item abstains.
469
677
  */
470
678
  typeArgumentReachesResult(sourceFile, at) {
471
- const call = sourceFile
472
- .getDescendantsOfKind(SyntaxKind.CallExpression)
473
- .find((c) => c.getStart() === at.start && c.getEnd() === at.end);
679
+ const call = callAt(sourceFile, at.start, at.end);
474
680
  if (!call)
475
681
  return 'the retyped call could not be found again after the rewrite';
476
682
  const stated = call.getTypeArguments()[0]?.getType();
@@ -499,9 +705,7 @@ export class Retyper {
499
705
  }
500
706
  /** What the call yields once awaited: the type the reach test compares. */
501
707
  resultOf(call) {
502
- const checker = this.project.getTypeChecker().compilerObject;
503
- const returned = call.getType().compilerType;
504
- return checker.getAwaitedType(returned) ?? returned;
708
+ return awaitedResult(this.project.getTypeChecker().compilerObject, call.compilerNode);
505
709
  }
506
710
  /**
507
711
  * The abstention for a call whose type argument is not in its result. The
@@ -515,6 +719,58 @@ export class Retyper {
515
719
  `('${checker.typeToString(this.resultOf(call))}'), so it does not state the response`);
516
720
  }
517
721
  }
722
+ const ERASE_MEMBER = `${PREFIX}eraseMember`;
723
+ /**
724
+ * `${ERASE_MEMBER}(value, key)` types as `value` (awaited or not) with member
725
+ * `key` erased: any read of it passes, but the `null`/`undefined` it held
726
+ * stays, so a read the envelope itself rejects is still rejected. The
727
+ * erased part is an object that answers every property and index read with
728
+ * `any`, since `any | undefined` would collapse to `any`.
729
+ */
730
+ function eraseMemberDeclarations() {
731
+ const loose = `${PREFIX}Loose`;
732
+ const erasedIn = `${PREFIX}EraseIn`;
733
+ return [
734
+ `type ${loose} = { [key: string]: any; [index: number]: any };`,
735
+ `type ${erasedIn}<T, K extends PropertyKey> = Omit<T, K> & { [P in K & keyof T]: ${loose} | Exclude<T[P], NonNullable<T[P]>> };`,
736
+ `declare function ${ERASE_MEMBER}<T, K extends PropertyKey>(value: T, key: K): T extends PromiseLike<infer U> ? Promise<${erasedIn}<U, K>> : ${erasedIn}<T, K>;`,
737
+ ];
738
+ }
739
+ /** Top-type findings as a reason names them: `'any'`, `'unknown' at 'a.b'`. */
740
+ function membersText(findings) {
741
+ return findings
742
+ .map(({ kind, path }) => (path === '' ? `'${kind}'` : `'${kind}' at '${path}'`))
743
+ .join(', ');
744
+ }
745
+ /** What a call yields once awaited, read with `checker`. */
746
+ function awaitedResult(checker, call) {
747
+ const returned = checker.getTypeAtLocation(call);
748
+ return checker.getAwaitedType(returned) ?? returned;
749
+ }
750
+ /**
751
+ * `call`'s callee is `R.s1.….sk.m` with `[s1..sk]` equal to `segments`
752
+ * (`m` any name, `R` any expression).
753
+ */
754
+ function namesProcedure(call, segments) {
755
+ const callee = call.getExpression();
756
+ if (!Node.isPropertyAccessExpression(callee))
757
+ return false;
758
+ let at = callee.getExpression();
759
+ for (let i = segments.length - 1; i >= 0; i--) {
760
+ if (!Node.isPropertyAccessExpression(at) || at.getName() !== segments[i])
761
+ return false;
762
+ at = at.getExpression();
763
+ }
764
+ return true;
765
+ }
766
+ /** The call expression that spans exactly `start`..`end` in `sourceFile` now. */
767
+ function callAt(sourceFile, start, end) {
768
+ for (let at = sourceFile.getDescendantAtStartWithWidth(start, end - start); at && at.getStart() === start && at.getEnd() === end; at = at.getParent()) {
769
+ if (Node.isCallExpression(at))
770
+ return at;
771
+ }
772
+ return undefined;
773
+ }
518
774
  function abstain(item, reason) {
519
775
  return { item_id: item.item_id, outcome: 'abstain', diagnostics: [], reason };
520
776
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `find_site`: the capture's own site finder, asked by a caller that held a
3
+ * value's span in one text and needs its node in another (a held check whose
4
+ * bounds an edit crossed). The value is found by its parent slot, never by its
5
+ * text: the node of the old span sits in a slot of its parent (the n-th child
6
+ * of a call, a `return`'s expression, an arrow's body), and the answer is the
7
+ * node in that slot of the new text nearest the old position carried through
8
+ * the edit, so an edit to the value's own text, or the same text elsewhere
9
+ * (another handler's send, a binding of the same name), cannot move it. A call's
10
+ * slot also needs the callee to read as before unless the edit reaches the call.
11
+ * A node must be one the capture reads a value type at (`isPreferredTarget`).
12
+ * No program is loaded and nothing is read from disk: both texts are the
13
+ * caller's.
14
+ */
15
+ export type SiteAnswer = {
16
+ start: number;
17
+ end: number;
18
+ } | {
19
+ reason: 'value_not_a_node' | 'not_wrappable';
20
+ };
21
+ export declare function findSite(request: {
22
+ file: string;
23
+ oldText: string;
24
+ newText: string;
25
+ start: number;
26
+ end: number;
27
+ }): SiteAnswer;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `find_site`: the capture's own site finder, asked by a caller that held a
3
+ * value's span in one text and needs its node in another (a held check whose
4
+ * bounds an edit crossed). The value is found by its parent slot, never by its
5
+ * text: the node of the old span sits in a slot of its parent (the n-th child
6
+ * of a call, a `return`'s expression, an arrow's body), and the answer is the
7
+ * node in that slot of the new text nearest the old position carried through
8
+ * the edit, so an edit to the value's own text, or the same text elsewhere
9
+ * (another handler's send, a binding of the same name), cannot move it. A call's
10
+ * slot also needs the callee to read as before unless the edit reaches the call.
11
+ * A node must be one the capture reads a value type at (`isPreferredTarget`).
12
+ * No program is loaded and nothing is read from disk: both texts are the
13
+ * caller's.
14
+ */
15
+ import { ts } from 'ts-morph';
16
+ import { isPreferredTarget } from './capture/index.js';
17
+ /** The text a call's callee reads as, without whitespace. */
18
+ function headOf(parent, sourceFile) {
19
+ if (ts.isCallExpression(parent) || ts.isNewExpression(parent))
20
+ return parent.expression.getText(sourceFile).replace(/\s+/g, '');
21
+ return undefined;
22
+ }
23
+ function slotOf(node, sourceFile) {
24
+ const parent = node.parent;
25
+ if (!parent)
26
+ return undefined;
27
+ let index = -1;
28
+ let at = 0;
29
+ parent.forEachChild((child) => {
30
+ if (child === node)
31
+ index = at;
32
+ at += 1;
33
+ });
34
+ return index < 0 ? undefined : { parentKind: parent.kind, index, head: headOf(parent, sourceFile) };
35
+ }
36
+ /** The outermost value-space node whose span is exactly `[start, end)`. */
37
+ function nodeAtSpan(sourceFile, start, end) {
38
+ let found;
39
+ const visit = (node) => {
40
+ if (found || node.getEnd() < end || node.getStart(sourceFile) > start)
41
+ return;
42
+ if (node.getStart(sourceFile) === start && node.getEnd() === end && ts.isExpression(node)) {
43
+ found = node;
44
+ return;
45
+ }
46
+ node.forEachChild(visit);
47
+ };
48
+ visit(sourceFile);
49
+ return found;
50
+ }
51
+ /** The one region the edit changed, the common prefix and suffix cut off (the caller's `regionOfEdit`). */
52
+ function editRegion(oldText, newText) {
53
+ const limit = Math.min(oldText.length, newText.length);
54
+ let prefix = 0;
55
+ while (prefix < limit && oldText.charCodeAt(prefix) === newText.charCodeAt(prefix))
56
+ prefix += 1;
57
+ let suffix = 0;
58
+ while (suffix < limit - prefix && oldText.charCodeAt(oldText.length - 1 - suffix) === newText.charCodeAt(newText.length - 1 - suffix))
59
+ suffix += 1;
60
+ return { oldStart: prefix, oldEnd: oldText.length - suffix, newStart: prefix, newEnd: newText.length - suffix };
61
+ }
62
+ /** Where `position` of the old text lands in the new: shifted past the edit, kept before it, scaled inside it. */
63
+ function carried(position, region) {
64
+ if (position <= region.oldStart)
65
+ return position;
66
+ if (position >= region.oldEnd)
67
+ return position + (region.newEnd - region.newStart) - (region.oldEnd - region.oldStart);
68
+ return Math.min(region.newEnd, region.newStart + (position - region.oldStart));
69
+ }
70
+ export function findSite(request) {
71
+ const oldFile = ts.createSourceFile(request.file, request.oldText, ts.ScriptTarget.Latest, true);
72
+ const sourceFile = ts.createSourceFile(request.file, request.newText, ts.ScriptTarget.Latest, true);
73
+ const held = nodeAtSpan(oldFile, request.start, request.end);
74
+ const slot = held && slotOf(held, oldFile);
75
+ if (!slot)
76
+ return { reason: 'value_not_a_node' };
77
+ const region = editRegion(request.oldText, request.newText);
78
+ const target = carried(request.start, region);
79
+ let best;
80
+ let bestDistance = Infinity;
81
+ const visit = (node) => {
82
+ const parent = node.parent;
83
+ if (parent && parent.kind === slot.parentKind && isPreferredTarget(node) && ts.isExpression(node)) {
84
+ const at = slotOf(node, sourceFile);
85
+ if (at && at.index === slot.index) {
86
+ const start = node.getStart(sourceFile);
87
+ // The callee is how the slot is told from its namesakes; an edit that reaches the call may have changed it.
88
+ const reached = parent.getEnd() > region.newStart && parent.getStart(sourceFile) < region.newEnd;
89
+ if (at.head === slot.head || reached) {
90
+ const distance = Math.abs(start - target);
91
+ if (distance < bestDistance) {
92
+ best = node;
93
+ bestDistance = distance;
94
+ }
95
+ }
96
+ }
97
+ }
98
+ node.forEachChild(visit);
99
+ };
100
+ visit(sourceFile);
101
+ const node = best;
102
+ if (!node)
103
+ return { reason: 'value_not_a_node' };
104
+ // A call cannot wrap a spread, or the name a shorthand property is also the value of.
105
+ if (ts.isSpreadElement(node) || (ts.isIdentifier(node) && node.parent && ts.isShorthandPropertyAssignment(node.parent))) {
106
+ return { reason: 'not_wrappable' };
107
+ }
108
+ return { start: node.getStart(sourceFile), end: node.getEnd() };
109
+ }
@@ -28,3 +28,15 @@ export declare function declaredTypeName(name: string, declaration: Node): strin
28
28
  * - a declaration with no name to point at (`export default class {}`).
29
29
  */
30
30
  export declare function homeOfTypeDeclaration(name: string, declaration: Node, program: ts.Program): TypeHome | undefined;
31
+ /**
32
+ * carrick#2148 H3: the home of a schema value a contract was read off, where
33
+ * the value is one name for a `const` the repository declares
34
+ * (`guard('json', NewTicket)`, `NewTicket.safeParse(body)`). The schema is
35
+ * where that contract is written, so the home is the const's name, marked
36
+ * `kind: "schema"`: it is a value, never a type a reader can import as one.
37
+ *
38
+ * None for a schema built at its use (`record({ … })`), a name that is not a
39
+ * `const` (it can be reassigned, so the declaration is not the contract), an
40
+ * ambient `declare const`, and a declaration in a package or a `.d.ts`.
41
+ */
42
+ export declare function homeOfSchemaValue(value: Node): TypeHome | undefined;
@@ -3,7 +3,7 @@
3
3
  * The compiler engine's answers (`type_home`, `stated_body.root_home`) and
4
4
  * the bundle's manifest (`home`) read it from here.
5
5
  */
6
- import { Node } from 'ts-morph';
6
+ import { Node, VariableDeclarationKind } from 'ts-morph';
7
7
  import { startLineOf } from './line-index.js';
8
8
  /** A declaration that names a type: an interface, a type alias, a class or an enum. */
9
9
  export function isTypeSpaceDeclaration(declaration) {
@@ -52,3 +52,43 @@ export function homeOfTypeDeclaration(name, declaration, program) {
52
52
  return undefined;
53
53
  return { symbol, file_path: sourceFile.getFilePath(), line: startLineOf(nameNode) };
54
54
  }
55
+ /**
56
+ * carrick#2148 H3: the home of a schema value a contract was read off, where
57
+ * the value is one name for a `const` the repository declares
58
+ * (`guard('json', NewTicket)`, `NewTicket.safeParse(body)`). The schema is
59
+ * where that contract is written, so the home is the const's name, marked
60
+ * `kind: "schema"`: it is a value, never a type a reader can import as one.
61
+ *
62
+ * None for a schema built at its use (`record({ … })`), a name that is not a
63
+ * `const` (it can be reassigned, so the declaration is not the contract), an
64
+ * ambient `declare const`, and a declaration in a package or a `.d.ts`.
65
+ */
66
+ export function homeOfSchemaValue(value) {
67
+ if (!Node.isIdentifier(value))
68
+ return undefined;
69
+ let symbol = value.getSymbol();
70
+ if (symbol?.isAlias())
71
+ symbol = symbol.getAliasedSymbol() ?? symbol;
72
+ const declarations = symbol?.getDeclarations() ?? [];
73
+ if (declarations.length !== 1)
74
+ return undefined;
75
+ const [declaration] = declarations;
76
+ if (!Node.isVariableDeclaration(declaration) || !declaration.hasInitializer())
77
+ return undefined;
78
+ const list = declaration.getParent();
79
+ if (!Node.isVariableDeclarationList(list) || list.getDeclarationKind() !== VariableDeclarationKind.Const) {
80
+ return undefined;
81
+ }
82
+ const sourceFile = declaration.getSourceFile();
83
+ if (sourceFile.isDeclarationFile() || sourceFile.isInNodeModules())
84
+ return undefined;
85
+ const nameNode = declaration.getNameNode();
86
+ if (!Node.isIdentifier(nameNode))
87
+ return undefined;
88
+ return {
89
+ symbol: nameNode.getText(),
90
+ file_path: sourceFile.getFilePath(),
91
+ line: startLineOf(nameNode),
92
+ kind: 'schema',
93
+ };
94
+ }
@@ -21,9 +21,10 @@ import { Project, SourceFile, type CallExpression } from 'ts-morph';
21
21
  import type { InferRequestItem, InferResult, ModelSymbol, ExtractionConfig } from './types.js';
22
22
  import { type LabelledMembers } from './library-claims.js';
23
23
  /**
24
- * The reasons an `unknown` answer is a decision, not a failure to read: the
25
- * list `DECIDED_ABSTAIN_REASONS` in `src/engine/type_compat_v2.rs` holds
26
- * final. A stated reply never replaces one (carrick#2674).
24
+ * The reasons an `unknown` answer is a decision, not a failure to read, on the
25
+ * response path that reads this set: the words `capture/type-reasons.json`
26
+ * marks `always` (carrick#4231). A stated reply never replaces one
27
+ * (carrick#2674).
27
28
  */
28
29
  export declare const DECIDED_ABSTAIN_REASONS: ReadonlySet<string>;
29
30
  /**
@@ -263,6 +264,11 @@ export declare class TypeInferrer {
263
264
  sourceFile: SourceFile;
264
265
  call: CallExpression;
265
266
  } | undefined;
267
+ /**
268
+ * The source file a locator's `file_path` names (absolute, or relative to
269
+ * the repo root), added to the project when it is not loaded yet.
270
+ */
271
+ sourceFileOf(filePath: string): SourceFile | undefined;
266
272
  /**
267
273
  * Get or add a source file to the project
268
274
  */
@@ -2749,6 +2755,10 @@ export declare class TypeInferrer {
2749
2755
  * `unknown`.
2750
2756
  */
2751
2757
  private schemaContract;
2758
+ /**
2759
+ * `schemaContract`'s text and provenance, read off the schema's types.
2760
+ */
2761
+ private schemaContractText;
2752
2762
  /**
2753
2763
  * Print a schema's input with each coerced position replaced by the output's
2754
2764
  * type at that position (carrick#1105). Null when any position cannot be