carrick 0.3.157 → 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 (142) 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/fetch.d.ts +7 -0
  13. package/dist/facts/fetch.js +22 -1
  14. package/dist/facts/fetch.js.map +1 -1
  15. package/dist/facts/lines.d.ts +22 -4
  16. package/dist/facts/lines.js +31 -9
  17. package/dist/facts/lines.js.map +1 -1
  18. package/dist/facts/peers.d.ts +13 -4
  19. package/dist/facts/peers.js +17 -15
  20. package/dist/facts/peers.js.map +1 -1
  21. package/dist/facts/rules/packages.js +3 -1
  22. package/dist/facts/rules/packages.js.map +1 -1
  23. package/dist/facts/rules/same-name.js +1 -1
  24. package/dist/facts/rules/same-name.js.map +1 -1
  25. package/dist/facts/store.d.ts +15 -0
  26. package/dist/facts/store.js +30 -0
  27. package/dist/facts/store.js.map +1 -1
  28. package/dist/held/backoff.d.ts +8 -0
  29. package/dist/held/backoff.js +43 -0
  30. package/dist/held/backoff.js.map +1 -0
  31. package/dist/held/build.d.ts +17 -0
  32. package/dist/held/build.js +62 -0
  33. package/dist/held/build.js.map +1 -0
  34. package/dist/held/client.d.ts +12 -3
  35. package/dist/held/client.js +123 -8
  36. package/dist/held/client.js.map +1 -1
  37. package/dist/held/daemon.d.ts +47 -2
  38. package/dist/held/daemon.js +115 -23
  39. package/dist/held/daemon.js.map +1 -1
  40. package/dist/held/early.d.ts +28 -0
  41. package/dist/held/early.js +115 -0
  42. package/dist/held/early.js.map +1 -0
  43. package/dist/held/paths.d.ts +6 -0
  44. package/dist/held/paths.js +17 -0
  45. package/dist/held/paths.js.map +1 -1
  46. package/dist/held/place.d.ts +76 -30
  47. package/dist/held/place.js +121 -83
  48. package/dist/held/place.js.map +1 -1
  49. package/dist/held/run.js +24 -6
  50. package/dist/held/run.js.map +1 -1
  51. package/dist/held/runtime.d.ts +22 -0
  52. package/dist/held/runtime.js +612 -0
  53. package/dist/held/runtime.js.map +1 -0
  54. package/dist/held/shadow.d.ts +33 -0
  55. package/dist/held/shadow.js +68 -0
  56. package/dist/held/shadow.js.map +1 -0
  57. package/dist/held/steps.d.ts +11 -0
  58. package/dist/held/steps.js +29 -0
  59. package/dist/held/steps.js.map +1 -0
  60. package/dist/hook/confirm.d.ts +79 -0
  61. package/dist/hook/confirm.js +220 -0
  62. package/dist/hook/confirm.js.map +1 -0
  63. package/dist/hook/edit-flow.d.ts +14 -3
  64. package/dist/hook/edit-flow.js +113 -33
  65. package/dist/hook/edit-flow.js.map +1 -1
  66. package/dist/hook/generation.d.ts +19 -0
  67. package/dist/hook/generation.js +75 -0
  68. package/dist/hook/generation.js.map +1 -0
  69. package/dist/hook/late.d.ts +50 -9
  70. package/dist/hook/late.js +104 -24
  71. package/dist/hook/late.js.map +1 -1
  72. package/dist/hook/post-bash.js +3 -3
  73. package/dist/hook/post-bash.js.map +1 -1
  74. package/dist/hook/post-edit.js +2 -2
  75. package/dist/hook/post-edit.js.map +1 -1
  76. package/dist/hook/post-read.js +25 -3
  77. package/dist/hook/post-read.js.map +1 -1
  78. package/dist/hook/post-search.js +1 -1
  79. package/dist/hook/post-search.js.map +1 -1
  80. package/dist/hook/probe.js +1 -0
  81. package/dist/hook/probe.js.map +1 -1
  82. package/dist/hook/read-answer.d.ts +5 -0
  83. package/dist/hook/read-answer.js +8 -4
  84. package/dist/hook/read-answer.js.map +1 -1
  85. package/dist/hook/rechecks.d.ts +58 -2
  86. package/dist/hook/rechecks.js +132 -9
  87. package/dist/hook/rechecks.js.map +1 -1
  88. package/dist/hook/session-start.d.ts +1 -1
  89. package/dist/hook/session-start.js +19 -5
  90. package/dist/hook/session-start.js.map +1 -1
  91. package/dist/hook/similar.d.ts +1 -1
  92. package/dist/hook/similar.js +21 -8
  93. package/dist/hook/similar.js.map +1 -1
  94. package/dist/hook/stop-wait.js +35 -16
  95. package/dist/hook/stop-wait.js.map +1 -1
  96. package/dist/hook/timings.d.ts +29 -1
  97. package/dist/hook/timings.js +7 -1
  98. package/dist/hook/timings.js.map +1 -1
  99. package/dist/hook/user-prompt.js +2 -2
  100. package/dist/hook/user-prompt.js.map +1 -1
  101. package/dist/hosted-snapshot.d.ts +27 -0
  102. package/dist/hosted-snapshot.js +32 -0
  103. package/dist/hosted-snapshot.js.map +1 -1
  104. package/dist/init/hosted.js +2 -9
  105. package/dist/init/hosted.js.map +1 -1
  106. package/dist/render.d.ts +15 -1
  107. package/dist/render.js +50 -4
  108. package/dist/render.js.map +1 -1
  109. package/dist/server.js +1 -1
  110. package/dist/server.js.map +1 -1
  111. package/package.json +6 -6
  112. package/plugin/.claude-plugin/plugin.json +1 -1
  113. package/sidecar/dist/src/capture/anchors.d.ts +8 -0
  114. package/sidecar/dist/src/capture/anchors.js +3 -2
  115. package/sidecar/dist/src/capture/api.d.ts +70 -3
  116. package/sidecar/dist/src/capture/check-classify.d.ts +7 -0
  117. package/sidecar/dist/src/capture/check-classify.js +24 -0
  118. package/sidecar/dist/src/capture/check-probe.d.ts +76 -7
  119. package/sidecar/dist/src/capture/check-probe.js +147 -19
  120. package/sidecar/dist/src/capture/check.js +13 -1
  121. package/sidecar/dist/src/capture/graphql-leaves.d.ts +46 -0
  122. package/sidecar/dist/src/capture/graphql-leaves.js +142 -0
  123. package/sidecar/dist/src/capture/index.d.ts +4 -1
  124. package/sidecar/dist/src/capture/index.js +3 -1
  125. package/sidecar/dist/src/definition-resolver.d.ts +2 -1
  126. package/sidecar/dist/src/definition-resolver.js +15 -9
  127. package/sidecar/dist/src/engine-stamp.json +1 -1
  128. package/sidecar/dist/src/held-shadow.d.ts +12 -2
  129. package/sidecar/dist/src/held-shadow.js +9 -9
  130. package/sidecar/dist/src/index.js +18 -1
  131. package/sidecar/dist/src/library-claims.js +26 -3
  132. package/sidecar/dist/src/retype.d.ts +47 -0
  133. package/sidecar/dist/src/retype.js +274 -18
  134. package/sidecar/dist/src/site-find.d.ts +27 -0
  135. package/sidecar/dist/src/site-find.js +109 -0
  136. package/sidecar/dist/src/type-inferrer.d.ts +5 -0
  137. package/sidecar/dist/src/type-inferrer.js +8 -4
  138. package/sidecar/dist/src/type-structural-expander.d.ts +10 -0
  139. package/sidecar/dist/src/type-structural-expander.js +73 -4
  140. package/sidecar/dist/src/types.d.ts +50 -2
  141. package/sidecar/dist/src/validators.d.ts +328 -8
  142. package/sidecar/dist/src/validators.js +29 -0
@@ -58,7 +58,7 @@ export class DefinitionResolver {
58
58
  * both extensionless and `.js`-suffixed specifiers — the same policy the
59
59
  * check-phase workspace uses.
60
60
  */
61
- resolveFromStub(stubDir, aliases) {
61
+ resolveFromStub(stubDir, aliases, graphqlTypes) {
62
62
  const typesDir = path.join(stubDir, 'types');
63
63
  const surfacePath = path.join(typesDir, 'surface.d.ts');
64
64
  if (!fs.existsSync(surfacePath)) {
@@ -98,7 +98,7 @@ export class DefinitionResolver {
98
98
  const result = this.resolveAlias(surface, alias, {
99
99
  program: stubProject.getProgram().compilerObject,
100
100
  repoRoot: stubDir,
101
- });
101
+ }, graphqlTypes);
102
102
  if (result) {
103
103
  results.push(result);
104
104
  }
@@ -117,7 +117,7 @@ export class DefinitionResolver {
117
117
  /**
118
118
  * Resolve a single alias: the original text and the structural form.
119
119
  */
120
- resolveAlias(sourceFile, payload, origin) {
120
+ resolveAlias(sourceFile, payload, origin, graphqlTypes) {
121
121
  const alias = payload.alias;
122
122
  const decl = sourceFile.getTypeAlias(alias) ??
123
123
  sourceFile.getInterface(alias) ??
@@ -154,12 +154,18 @@ export class DefinitionResolver {
154
154
  }
155
155
  // Structural form — every named member inlined to its shape, in the
156
156
  // form the payload travels in where the judge compares that form. An
157
- // RPC procedure fails closed to the declared form: its router's
158
- // transformer, not JSON, decides what travels (carrick#4275).
159
- const wire = payload.procedure
160
- ? 'declared'
161
- : wireFormFor(payload.protocol, payload.type_kind, payload.side);
162
- const expanded = expandTypeStructural(type, origin, { wire });
157
+ // An RPC procedure's form is unknown, which prints as declared
158
+ // (carrick#4402). A GraphQL producer response prints each built-in
159
+ // scalar leaf in the type its scalar sends, read from the service's
160
+ // SDL types (carrick#4403).
161
+ const graphql = graphqlTypes !== undefined && payload.graphql_root !== undefined
162
+ ? { types: graphqlTypes, root: payload.graphql_root }
163
+ : undefined;
164
+ const wire = wireFormFor(payload.protocol, payload.type_kind, payload.side, {
165
+ procedure: payload.procedure,
166
+ graphql,
167
+ });
168
+ const expanded = expandTypeStructural(type, origin, { wire, graphql });
163
169
  return { type_alias: alias, definition, expanded };
164
170
  }
165
171
  catch (err) {
@@ -1 +1 @@
1
- {"inputs_sha256":"c1246197a0eb92ca60d59fba5847424f2654dcf52c08307d5badee9f3e8b3314"}
1
+ {"inputs_sha256":"3fc9f213dacc4a7d63e6080c37215e872e71359eb337c6f47ebc84c0833301d0"}
@@ -24,6 +24,7 @@
24
24
  * shadow).
25
25
  */
26
26
  import type { ProjectLoader } from './project-loader.js';
27
+ import { type JudgeTolerances } from './capture/index.js';
27
28
  /** What `write_shadow` answers. */
28
29
  export interface ShadowResult {
29
30
  /** Absolute path of the generated `w/tsconfig.json`. */
@@ -45,8 +46,15 @@ export interface ShadowResult {
45
46
  }>;
46
47
  /** The bare specifiers the own files use, as written to `paths`. */
47
48
  bare_specifiers: string[];
48
- /** Some own file imports a package named `hono` that resolved into the program. */
49
- hono: boolean;
49
+ /**
50
+ * The judge's JSON wire form as declarations a caller appends to a file:
51
+ * `jsonWireDeclarations('__carrick_')` and `type __carrick_Wire<S, E>`, the
52
+ * judge's own rule (`jsonWireRule`). One writer, so a held check and the
53
+ * scan's judge answer "what travels" the same way.
54
+ */
55
+ wire: string[];
56
+ /** The judge's three tolerances, read from its own code (`judgeTolerances('__carrick_')`): declarations to append beside `wire`. */
57
+ tolerances: JudgeTolerances;
50
58
  /** The native TypeScript 7 executable, or null when only TypeScript 6's tsc is installed. */
51
59
  native_tsc: string | null;
52
60
  }
@@ -58,3 +66,5 @@ export declare function nativeTscPath(tscPath?: string): string | null;
58
66
  * checkout.
59
67
  */
60
68
  export declare function writeShadow(loader: ProjectLoader, outDir: string): ShadowResult;
69
+ /** The wire declarations and the one rule type a held check appends (prefix `__carrick_`). */
70
+ export declare function heldWire(): string[];
@@ -26,7 +26,7 @@
26
26
  import * as fs from 'node:fs';
27
27
  import * as path from 'node:path';
28
28
  import { ts } from 'ts-morph';
29
- import { WriteGuard, judgeTscPath } from './capture/index.js';
29
+ import { WriteGuard, judgeTscPath, jsonWireDeclarations, jsonWireRule, judgeTolerances } from './capture/index.js';
30
30
  /** The platform package's executable, `@typescript/typescript-<platform>-<arch>/lib/tsc`. */
31
31
  const NATIVE_TSC = /[\\/]@typescript[\\/]typescript-[^\\/]+[\\/]lib[\\/]tsc(\.exe)?$/;
32
32
  /** `judgeTscPath()` when it is the native executable, else null (no held compiler). */
@@ -78,7 +78,6 @@ export function writeShadow(loader, outDir) {
78
78
  let vendored = 0;
79
79
  let rewritten = 0;
80
80
  let unresolved = 0;
81
- let hono = false;
82
81
  for (const sf of program.getSourceFiles()) {
83
82
  const file = sf.fileName;
84
83
  if (isLibraryFile(program, file))
@@ -97,7 +96,6 @@ export function writeShadow(loader, outDir) {
97
96
  node,
98
97
  text: node.text,
99
98
  to: resolved?.resolvedFileName,
100
- pkg: resolved?.packageId?.name,
101
99
  augmentation,
102
100
  synthesized: node.pos < 0 || node.end < 0 || !node.parent,
103
101
  });
@@ -112,8 +110,6 @@ export function writeShadow(loader, outDir) {
112
110
  continue;
113
111
  if (!lit.to || !inProgram.has(lit.to))
114
112
  continue; // unresolved stays unresolved: no `paths` entry
115
- if (isHonoFile(loader, lit.to, lit.pkg))
116
- hono = true;
117
113
  const target = shadowPath(lit.to);
118
114
  const known = paths[lit.text];
119
115
  if (known && known[0] !== target)
@@ -204,13 +200,17 @@ export function writeShadow(loader, outDir) {
204
200
  unresolved,
205
201
  path_conflicts: pathConflicts,
206
202
  bare_specifiers: Object.keys(paths).sort(),
207
- hono,
203
+ wire: heldWire(),
204
+ tolerances: judgeTolerances('__carrick_'),
208
205
  native_tsc: nativeTscPath(),
209
206
  };
210
207
  }
211
- /** The resolved file belongs to a package named `hono`: by the resolver's package id, the Deno graph, or the install path. */
212
- function isHonoFile(loader, file, packageId) {
213
- return packageId === 'hono' || loader.packageDirectoryOf(file)?.name === 'hono' || /[\\/]node_modules[\\/]hono[\\/]/.test(file);
208
+ /** The wire declarations and the one rule type a held check appends (prefix `__carrick_`). */
209
+ export function heldWire() {
210
+ return [
211
+ ...jsonWireDeclarations('__carrick_'),
212
+ `type __carrick_Wire<S, E> = ${jsonWireRule('S', 'E', '__carrick_')};`,
213
+ ];
214
214
  }
215
215
  function safeRealpath(p) {
216
216
  try {
@@ -32,6 +32,7 @@ import { PROGRESS_INTERVAL_MS, atMostEvery } from './progress.js';
32
32
  import { mergeInferTimings } from './infer-timing.js';
33
33
  import { addProgramFiles, listProgramFiles } from './program-files.js';
34
34
  import { writeShadow } from './held-shadow.js';
35
+ import { findSite } from './site-find.js';
35
36
  import { changedSource, inferCacheDir, keepable, programDifference, programRecord, readEntry, requestDigest, writeEntry, } from './infer-cache.js';
36
37
  import { writePositionRows } from './position-rows.js';
37
38
  import { findImplementations } from './implementations.js';
@@ -711,7 +712,7 @@ function handleListLibrarySurface(request) {
711
712
  function handleResolveDefinitions(request) {
712
713
  try {
713
714
  log(`Resolving ${request.aliases.length} type alias(es) from ${request.stub_dir}`);
714
- const results = definitionResolver.resolveFromStub(request.stub_dir, request.aliases);
715
+ const results = definitionResolver.resolveFromStub(request.stub_dir, request.aliases, request.graphql_types);
715
716
  return {
716
717
  request_id: request.request_id,
717
718
  status: 'success',
@@ -774,6 +775,20 @@ function handleWriteShadow(request) {
774
775
  return { request_id: request.request_id, status: 'error', errors: [error] };
775
776
  }
776
777
  }
778
+ /**
779
+ * Handle the 'find_site' action: the capture's own site finder over the
780
+ * caller's two texts (site-find.ts). Reads no program and no disk.
781
+ */
782
+ function handleFindSite(request) {
783
+ try {
784
+ return { request_id: request.request_id, status: 'success', ...findSite(request) };
785
+ }
786
+ catch (err) {
787
+ const error = err instanceof Error ? err.message : String(err);
788
+ logError(`Finding the site failed: ${error}`);
789
+ return { request_id: request.request_id, status: 'error', errors: [error] };
790
+ }
791
+ }
777
792
  /**
778
793
  * Handle the 'reach_graph' action - the import graph of every program the
779
794
  * process has built, the default one and each owning project's (carrick#3100).
@@ -959,6 +974,8 @@ function handleRequest(request) {
959
974
  return handleListProgramFiles(request);
960
975
  case 'write_shadow':
961
976
  return handleWriteShadow(request);
977
+ case 'find_site':
978
+ return handleFindSite(request);
962
979
  case 'reach_graph':
963
980
  return handleReachGraph(request);
964
981
  case 'reach':
@@ -1158,13 +1158,15 @@ export function fullSurfaceSha256(surfaces) {
1158
1158
  // A member's `handlers` (carrick#2674), a signature's `result_candidates`
1159
1159
  // (carrick#2817) and a member's `scope_receiver` (carrick#2774) are out of
1160
1160
  // the hash at every depth, and so is a member's `runtime_events`
1161
- // (carrick#3032), and a receiver's `properties` (carrick#3696), so a
1162
- // package's key does not change when the lister learns to list them.
1161
+ // (carrick#3032), a receiver's `properties` (carrick#3696) and a construct
1162
+ // signature's `abstract` (L2, R5), so a package's key does not change when
1163
+ // the lister learns to list them.
1163
1164
  const text = JSON.stringify(listed, (key, value) => key === 'handlers' ||
1164
1165
  key === 'result_candidates' ||
1165
1166
  key === 'scope_receiver' ||
1166
1167
  key === 'runtime_events' ||
1167
- key === 'properties'
1168
+ key === 'properties' ||
1169
+ key === 'abstract'
1168
1170
  ? undefined
1169
1171
  : value);
1170
1172
  return crypto.createHash('sha256').update(text).digest('hex');
@@ -5519,6 +5521,25 @@ class DeclarationReader {
5519
5521
  this.handlerMembers.set(type, listed);
5520
5522
  return listed;
5521
5523
  }
5524
+ /**
5525
+ * A construct signature of an abstract class: `new` on it is a type error.
5526
+ * Read from the class declaration, which the written constructor sits in or
5527
+ * the instance type names when the class writes none. A call signature, or
5528
+ * a construct signature written in an interface, is never abstract.
5529
+ */
5530
+ isAbstractConstruct(signature) {
5531
+ const declaration = signature.getDeclaration();
5532
+ const abstractClass = (node) => node !== undefined &&
5533
+ ts.isClassLike(node) &&
5534
+ (ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Abstract) !== 0;
5535
+ if (declaration !== undefined && ts.isConstructorDeclaration(declaration))
5536
+ return abstractClass(declaration.parent);
5537
+ if (declaration !== undefined && ts.isClassLike(declaration))
5538
+ return abstractClass(declaration);
5539
+ if (declaration !== undefined)
5540
+ return false;
5541
+ return (this.checker.getReturnTypeOfSignature(signature).symbol?.declarations ?? []).some(abstractClass);
5542
+ }
5522
5543
  listSignatures(signatures, holder, take) {
5523
5544
  const listed = [];
5524
5545
  for (const signature of signatures) {
@@ -5560,6 +5581,8 @@ class DeclarationReader {
5560
5581
  const candidates = this.listResultCandidates ? resultCandidatesOf(this.checker, signature) : undefined;
5561
5582
  if (candidates !== undefined)
5562
5583
  entry.result_candidates = candidates;
5584
+ if (this.isAbstractConstruct(signature))
5585
+ entry.abstract = true;
5563
5586
  listed.push(entry);
5564
5587
  }
5565
5588
  return listed;
@@ -129,6 +129,53 @@ export declare class Retyper {
129
129
  * than the budget allows; the compiler's diagnostics stand.
130
130
  */
131
131
  private unresolvedMembers;
132
+ /**
133
+ * The JSON wire transform's declarations and the `${WIRE}<P>` alias that
134
+ * states a type in its wire form, as appended to a file that names them.
135
+ */
136
+ private wireDeclarations;
137
+ /**
138
+ * The procedure form (carrick#937): judge a procedure call by the
139
+ * consumer's own code against the call's own type.
140
+ *
141
+ * A procedure call's type IS the producer's router type, read by the
142
+ * consumer's compiler, so stating the producer's output at the call would
143
+ * compare one type with itself. What breaks is the consumer's use of it.
144
+ * The file is type-checked as it is and again with only the call's result
145
+ * erased (`(<call> as any)`): a diagnostic present as-is and gone when
146
+ * erased is a place the consumer uses what the procedure does not return.
147
+ *
148
+ * A guard runs first: the call's result (or one member of it, for a hook's
149
+ * envelope such as `{ data }`) must be the producer's published output, as
150
+ * declared or in its JSON wire form. A call whose result is something else
151
+ * (an options builder's `{ key }`), or a router on disk that no longer
152
+ * returns what the producer published, is not compared: erasing it would
153
+ * agree about nothing.
154
+ */
155
+ private runProcedure;
156
+ /**
157
+ * The one call to the procedure `procedurePath` names that starts on the
158
+ * item's line: a call whose callee is `R.s1.….sk.m`, with `s1..sk` the key
159
+ * path's segments, `m` any name (the client's operation) and `R` any
160
+ * expression (the client). Or why there is not exactly one.
161
+ */
162
+ private locateProcedureCall;
163
+ /**
164
+ * The `any` members of the call's awaited result, which can only hide a
165
+ * diagnostic and so decide only an empty diff, or why the result cannot be
166
+ * compared at all (`any`/`unknown` as a whole, `unknown` at a member). The
167
+ * walk's budget sentinel is dropped, as {@link unresolvedMembers} drops it.
168
+ */
169
+ private procedureTopTypes;
170
+ /**
171
+ * Guard (carrick#937): what carries the producer's published output,
172
+ * declared or in its JSON wire form (each way assignable to the other),
173
+ * read in the consumer's own program: the call's awaited result as a whole
174
+ * (`member` unset), or for an object result the string-named member that
175
+ * does once `null`/`undefined` are removed. Else why the call is not
176
+ * compared.
177
+ */
178
+ private carriesProducerOutput;
132
179
  /**
133
180
  * The stated type argument must be what the call RETURNS (or a type
134
181
  * argument or member of it): the rewrite is only a statement about the
@@ -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;