carrick 0.3.146 → 0.3.148

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 (60) hide show
  1. package/dist/cli.d.ts +8 -1
  2. package/dist/cli.js +14 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/contract.d.ts +31 -0
  5. package/dist/contract.js +28 -0
  6. package/dist/contract.js.map +1 -1
  7. package/dist/hook/checked.d.ts +3 -1
  8. package/dist/hook/checked.js +9 -2
  9. package/dist/hook/checked.js.map +1 -1
  10. package/dist/hook/late.js +9 -2
  11. package/dist/hook/late.js.map +1 -1
  12. package/dist/hook/post-edit.js +29 -5
  13. package/dist/hook/post-edit.js.map +1 -1
  14. package/dist/hook/rechecks.d.ts +45 -1
  15. package/dist/hook/rechecks.js +115 -5
  16. package/dist/hook/rechecks.js.map +1 -1
  17. package/dist/hook/reuse.d.ts +30 -2
  18. package/dist/hook/reuse.js +37 -3
  19. package/dist/hook/reuse.js.map +1 -1
  20. package/dist/hook/stop-wait.d.ts +23 -0
  21. package/dist/hook/stop-wait.js +163 -28
  22. package/dist/hook/stop-wait.js.map +1 -1
  23. package/dist/hook/stop.js +5 -2
  24. package/dist/hook/stop.js.map +1 -1
  25. package/dist/init/agents-section.d.ts +10 -0
  26. package/dist/init/agents-section.js +32 -0
  27. package/dist/init/agents-section.js.map +1 -1
  28. package/dist/init/remove.d.ts +2 -0
  29. package/dist/init/remove.js +15 -1
  30. package/dist/init/remove.js.map +1 -1
  31. package/dist/init/run.js +11 -2
  32. package/dist/init/run.js.map +1 -1
  33. package/dist/init/self-update.js +31 -3
  34. package/dist/init/self-update.js.map +1 -1
  35. package/dist/render.d.ts +33 -10
  36. package/dist/render.js +105 -32
  37. package/dist/render.js.map +1 -1
  38. package/package.json +6 -6
  39. package/plugin/.claude-plugin/plugin.json +1 -1
  40. package/sidecar/dist/src/argument-modes.js +8 -34
  41. package/sidecar/dist/src/bundler.js +2 -6
  42. package/sidecar/dist/src/capture/index.d.ts +3 -1
  43. package/sidecar/dist/src/capture/index.js +3 -1
  44. package/sidecar/dist/src/capture/installed-package.d.ts +1 -0
  45. package/sidecar/dist/src/capture/installed-package.js +3 -6
  46. package/sidecar/dist/src/capture/outside-root.js +4 -7
  47. package/sidecar/dist/src/capture/service-config.d.ts +6 -0
  48. package/sidecar/dist/src/capture/service-config.js +11 -1
  49. package/sidecar/dist/src/capture/status-table.d.ts +0 -2
  50. package/sidecar/dist/src/capture/status-table.js +0 -4
  51. package/sidecar/dist/src/function-body.d.ts +26 -0
  52. package/sidecar/dist/src/function-body.js +49 -0
  53. package/sidecar/dist/src/library-claims.js +14 -0
  54. package/sidecar/dist/src/loop-element.js +6 -20
  55. package/sidecar/dist/src/origin.d.ts +3 -0
  56. package/sidecar/dist/src/origin.js +8 -0
  57. package/sidecar/dist/src/position-rows.js +4 -7
  58. package/sidecar/dist/src/stated-params.js +2 -17
  59. package/sidecar/dist/src/type-inferrer.d.ts +10 -0
  60. package/sidecar/dist/src/type-inferrer.js +67 -69
@@ -11,6 +11,12 @@
11
11
  * `lib`) is typed under that config, as the repo's own `tsc` types it; without
12
12
  * it, every import only that config resolves read `any`.
13
13
  *
14
+ * A service-root `jsconfig.json` ranks after those names and before an
15
+ * ancestor `tsconfig.json` (carrick#3497): tsserver types a JavaScript file
16
+ * under the jsconfig beside it, not under a config above. Where no ancestor
17
+ * config exists the answer stays undefined, as before: the service is then
18
+ * typed per file by `fileConfigPath`, which reads the same jsconfig.
19
+ *
14
20
  * The walk stops at the scan root, inclusive: a config outside the scanned
15
21
  * tree is never read. With no scan root, or a service outside it, only the
16
22
  * service root is searched.
@@ -19,6 +25,8 @@ import * as fs from 'node:fs';
19
25
  import * as path from 'node:path';
20
26
  /** The names a service root is searched for, in order. */
21
27
  const SERVICE_ROOT_NAMES = ['tsconfig.json', 'tsconfig.build.json', 'tsconfig.app.json'];
28
+ /** The root config tsserver types a JavaScript service under, after the names above. */
29
+ const SERVICE_ROOT_JSCONFIG = 'jsconfig.json';
22
30
  /** The name an ancestor directory is searched for, as `tsc` searches. */
23
31
  const ANCESTOR_NAME = 'tsconfig.json';
24
32
  /** Absolute path of the config that types the service, or undefined for none. */
@@ -29,6 +37,8 @@ export function findServiceTsconfig(serviceRoot, scanRoot) {
29
37
  if (fs.existsSync(candidate))
30
38
  return candidate;
31
39
  }
40
+ const jsconfig = path.join(root, SERVICE_ROOT_JSCONFIG);
41
+ const ownJsconfig = fs.existsSync(jsconfig) ? jsconfig : undefined;
32
42
  if (scanRoot === undefined)
33
43
  return undefined;
34
44
  // Containment is decided on real paths, so a symlink on either end cannot
@@ -42,7 +52,7 @@ export function findServiceTsconfig(serviceRoot, scanRoot) {
42
52
  dir = path.dirname(dir);
43
53
  const candidate = path.join(dir, ANCESTOR_NAME);
44
54
  if (fs.existsSync(candidate))
45
- return candidate;
55
+ return ownJsconfig ?? candidate;
46
56
  }
47
57
  return undefined;
48
58
  }
@@ -75,5 +75,3 @@ export declare function statusTableBody(checker: ts.TypeChecker, type: ts.Type,
75
75
  kind: 'no_body';
76
76
  entries: StatusTableEntry[];
77
77
  } | undefined;
78
- /** The members of a union, or the type itself: what a set comparison reads. */
79
- export declare function constituents(type: ts.Type): ts.Type[];
@@ -124,7 +124,3 @@ export function statusTableBody(checker, type, at) {
124
124
  }
125
125
  return { kind: 'body', entries: success, types };
126
126
  }
127
- /** The members of a union, or the type itself: what a set comparison reads. */
128
- export function constituents(type) {
129
- return type.isUnion() ? type.types : [type];
130
- }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The function body a call runs (carrick#3500). One answer for the helpers
3
+ * that ask it: a declaration that has a body is that body; an overloaded
4
+ * function is its one implementation (the signatures carry no body); a
5
+ * variable or property initialised with an arrow or function expression is
6
+ * that function, through the wrappers that leave a value as it is
7
+ * (parentheses, `as`, `<T>`, `!`, `satisfies`).
8
+ *
9
+ * A name with two bodies, or with none, has no one body and answers
10
+ * undefined.
11
+ */
12
+ import { Node, type ArrowFunction, type FunctionDeclaration, type FunctionExpression, type MethodDeclaration } from 'ts-morph';
13
+ export type PlainFunctionBody = FunctionDeclaration | ArrowFunction | FunctionExpression;
14
+ export type FunctionBody = PlainFunctionBody | MethodDeclaration;
15
+ /** An expression without the wrappers that leave its value as it is. */
16
+ export declare function peelValueWrappers(node: Node): Node;
17
+ /**
18
+ * The one function with a body among `declarations`, or undefined for none
19
+ * or several. `methods: false` leaves method declarations out.
20
+ */
21
+ export declare function functionBodyOf(declarations: readonly Node[], options: {
22
+ methods: false;
23
+ }): PlainFunctionBody | undefined;
24
+ export declare function functionBodyOf(declarations: readonly Node[], options?: {
25
+ methods?: boolean;
26
+ }): FunctionBody | undefined;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The function body a call runs (carrick#3500). One answer for the helpers
3
+ * that ask it: a declaration that has a body is that body; an overloaded
4
+ * function is its one implementation (the signatures carry no body); a
5
+ * variable or property initialised with an arrow or function expression is
6
+ * that function, through the wrappers that leave a value as it is
7
+ * (parentheses, `as`, `<T>`, `!`, `satisfies`).
8
+ *
9
+ * A name with two bodies, or with none, has no one body and answers
10
+ * undefined.
11
+ */
12
+ import { Node, } from 'ts-morph';
13
+ /** An expression without the wrappers that leave its value as it is. */
14
+ export function peelValueWrappers(node) {
15
+ let current = node;
16
+ while (Node.isParenthesizedExpression(current) ||
17
+ Node.isAsExpression(current) ||
18
+ Node.isTypeAssertion(current) ||
19
+ Node.isSatisfiesExpression(current) ||
20
+ Node.isNonNullExpression(current)) {
21
+ current = current.getExpression();
22
+ }
23
+ return current;
24
+ }
25
+ function bodyOfDeclaration(declaration, methods) {
26
+ if (Node.isFunctionDeclaration(declaration))
27
+ return declaration.getBody() ? declaration : undefined;
28
+ if (Node.isMethodDeclaration(declaration))
29
+ return methods && declaration.getBody() ? declaration : undefined;
30
+ if (Node.isArrowFunction(declaration) || Node.isFunctionExpression(declaration))
31
+ return declaration;
32
+ if (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {
33
+ const initializer = declaration.getInitializer();
34
+ const value = initializer ? peelValueWrappers(initializer) : undefined;
35
+ if (value && (Node.isArrowFunction(value) || Node.isFunctionExpression(value)))
36
+ return value;
37
+ }
38
+ return undefined;
39
+ }
40
+ export function functionBodyOf(declarations, options = {}) {
41
+ const methods = options.methods ?? true;
42
+ const bodies = new Set();
43
+ for (const declaration of declarations) {
44
+ const body = bodyOfDeclaration(declaration, methods);
45
+ if (body)
46
+ bodies.add(body);
47
+ }
48
+ return bodies.size === 1 ? [...bodies][0] : undefined;
49
+ }
@@ -1864,6 +1864,20 @@ class DeclarationReader {
1864
1864
  if (claim.kind !== 'op' || claim.op !== 'request' || claim.handler || claim.ack || claim.path !== undefined) {
1865
1865
  return unchecked('claim_invalid');
1866
1866
  }
1867
+ const outcome = this.judgeHttpOp(receiver, claim);
1868
+ if (outcome.verdict !== 'verified')
1869
+ return outcome;
1870
+ // The member it judged (carrick#3044 S1): the position row of a call of
1871
+ // that member joins on it, whatever holds the call's receiver.
1872
+ const callable = claim.member === null ? this.callSignatures(receiver) : this.callableProperty(receiver, claim.member);
1873
+ if ('failure' in callable)
1874
+ return outcome;
1875
+ const property = claim.member === null ? undefined : this.declaredProperty(receiver, claim.member);
1876
+ const declarations = this.declarationsOf(property ? { ...callable, named: { property, holder: receiver } } : callable);
1877
+ return declarations.length > 0 ? { ...outcome, declarations } : outcome;
1878
+ }
1879
+ /** The #1564 request check of an `op` claim already known to be an HTTP request shape. */
1880
+ judgeHttpOp(receiver, claim) {
1867
1881
  const name = claim.name;
1868
1882
  if (name !== undefined && !('arg' in name))
1869
1883
  return unchecked('claim_invalid');
@@ -34,6 +34,7 @@
34
34
  * Anything else returns `undefined`, and the request is typed as before.
35
35
  */
36
36
  import { Node, SyntaxKind } from 'ts-morph';
37
+ import { peelValueWrappers } from './function-body.js';
37
38
  import { stringLiteral } from './response-modes.js';
38
39
  /** Methods of an array that change it in place. */
39
40
  const MUTATORS = new Set([
@@ -57,7 +58,7 @@ export function loopElementPick(registration, routePath) {
57
58
  const pathArg = registration.getArguments()[0];
58
59
  if (!pathArg)
59
60
  return undefined;
60
- const template = unwrap(pathArg);
61
+ const template = peelValueWrappers(pathArg);
61
62
  if (!Node.isTemplateExpression(template))
62
63
  return undefined;
63
64
  const holes = template.getTemplateSpans().map((span) => span.getExpression());
@@ -111,21 +112,6 @@ export function loopElementPick(registration, routePath) {
111
112
  of: elements.length,
112
113
  };
113
114
  }
114
- /** `node` through parentheses, `as` and `satisfies`. */
115
- function unwrap(node) {
116
- let at = node;
117
- for (;;) {
118
- if (Node.isParenthesizedExpression(at) ||
119
- Node.isAsExpression(at) ||
120
- Node.isSatisfiesExpression(at) ||
121
- Node.isTypeAssertion(at)) {
122
- at = at.getExpression();
123
- }
124
- else {
125
- return at;
126
- }
127
- }
128
- }
129
115
  /** The name node a declaration binds, for a name declared by a variable, a parameter or a binding element. */
130
116
  function declarationName(declared) {
131
117
  if (Node.isVariableDeclaration(declared) ||
@@ -199,7 +185,7 @@ function enclosingLoop(registration, holes) {
199
185
  * else, a spread included.
200
186
  */
201
187
  function listElements(list) {
202
- let literal = unwrap(list);
188
+ let literal = peelValueWrappers(list);
203
189
  if (Node.isIdentifier(literal)) {
204
190
  const declared = literal.getSymbol()?.getDeclarations()[0];
205
191
  if (!declared || !Node.isVariableDeclaration(declared))
@@ -216,7 +202,7 @@ function listElements(list) {
216
202
  return undefined;
217
203
  if (!readonly && declared.isExported())
218
204
  return undefined;
219
- literal = unwrap(initializer);
205
+ literal = peelValueWrappers(initializer);
220
206
  }
221
207
  if (!Node.isArrayLiteralExpression(literal))
222
208
  return undefined;
@@ -224,7 +210,7 @@ function listElements(list) {
224
210
  if (elements.some((element) => Node.isSpreadElement(element) || Node.isOmittedExpression(element))) {
225
211
  return undefined;
226
212
  }
227
- return elements.map(unwrap);
213
+ return elements.map((element) => peelValueWrappers(element));
228
214
  }
229
215
  function hasConstAssertion(node) {
230
216
  let at = node;
@@ -280,7 +266,7 @@ function elementValue(element, position) {
280
266
  if (items.some((item) => Node.isSpreadElement(item)))
281
267
  return undefined;
282
268
  const item = items[position];
283
- return item ? stringLiteral(unwrap(item)) : undefined;
269
+ return item ? stringLiteral(peelValueWrappers(item)) : undefined;
284
270
  }
285
271
  /** A path segment that is a parameter, in either spelling. */
286
272
  function isParam(segment) {
@@ -14,6 +14,7 @@
14
14
  * rather than by sharing this module.
15
15
  */
16
16
  import type { Project, ResolutionHostFactory, ts } from 'ts-morph';
17
+ import type { ExpandOrigin } from './type-structural-expander.js';
17
18
  /**
18
19
  * True when a declaration's source file is runtime/library origin rather than
19
20
  * user source. Four answers, in order:
@@ -87,3 +88,5 @@ export declare function registerExternalImports(project: Project, imports: Exter
87
88
  * `undefined` for any other project, which reads the compiler's flag alone.
88
89
  */
89
90
  export declare function externalImportsOf(project: Project): ExternalImports | undefined;
91
+ /** The program, service root and import record the printer decides library origin from. */
92
+ export declare function expandOriginOf(project: Project, repoRoot: string): ExpandOrigin;
@@ -132,3 +132,11 @@ export function registerExternalImports(project, imports) {
132
132
  export function externalImportsOf(project) {
133
133
  return externalImportsByProject.get(project);
134
134
  }
135
+ /** The program, service root and import record the printer decides library origin from. */
136
+ export function expandOriginOf(project, repoRoot) {
137
+ return {
138
+ program: project.getProgram().compilerObject,
139
+ repoRoot,
140
+ imports: externalImportsOf(project),
141
+ };
142
+ }
@@ -52,7 +52,7 @@ import * as fs from 'node:fs';
52
52
  import * as path from 'node:path';
53
53
  import * as zlib from 'node:zlib';
54
54
  import { ts } from 'ts-morph';
55
- import { WriteGuard, installedPackageDirectory, isDeclarationFileName, moduleExport } from './capture/index.js';
55
+ import { WriteGuard, installedPackageDirectory, isDeclarationFileName, moduleExport, toPosix } from './capture/index.js';
56
56
  import { attributedDeclaration, installedPackageOf, typeDeclaration } from './declaration-attribution.js';
57
57
  import { typeToStringAsDeclared } from './print-type.js';
58
58
  /** The format's version, written in the header. */
@@ -310,7 +310,7 @@ export class PathNames {
310
310
  /** A request file's name: relative to the root, which every file the scanner sends is inside. */
311
311
  relative(file) {
312
312
  const inside = this.inside(path.resolve(file));
313
- return toSlashes(inside ? inside.rel : path.basename(file));
313
+ return toPosix(inside ? inside.rel : path.basename(file));
314
314
  }
315
315
  /** What a declaring file is written as, or `null` when nothing names it. */
316
316
  declaringFile(fileName) {
@@ -324,10 +324,10 @@ export class PathNames {
324
324
  nameDeclaringFile(fileName) {
325
325
  const inside = this.inside(fileName);
326
326
  if (inside)
327
- return toSlashes(inside.rel);
327
+ return toPosix(inside.rel);
328
328
  const installed = installedPackageDirectory(this.roots[0], fileName) ?? this.packageDirectoryOf(fileName);
329
329
  if (installed && fs.existsSync(path.join(installed.directory, 'package.json'))) {
330
- return `pkg:${installed.name}/${toSlashes(path.relative(installed.directory, fileName))}`;
330
+ return `pkg:${installed.name}/${toPosix(path.relative(installed.directory, fileName))}`;
331
331
  }
332
332
  return null;
333
333
  }
@@ -397,9 +397,6 @@ export class PathNames {
397
397
  });
398
398
  }
399
399
  }
400
- function toSlashes(p) {
401
- return p.split(path.sep).join('/');
402
- }
403
400
  /**
404
401
  * The rows of one program's files. The `implementations` action
405
402
  * (`implementations.ts`, carrick#2432) reads a call's symbol and names its
@@ -15,6 +15,7 @@
15
15
  * type parameter of the reply type. A union of success and error bodies is
16
16
  * cut to the variants a success-status send through the parameter carries.
17
17
  */
18
+ import { functionBodyOf } from './function-body.js';
18
19
  import { Node, SyntaxKind, ts, } from 'ts-morph';
19
20
  import { declarationKey } from './library-claims.js';
20
21
  /** Type flags of a value that cannot hold a request body: a string, number, boolean and the like. */
@@ -283,23 +284,7 @@ export class StatedParams {
283
284
  let symbol = callee.getSymbol();
284
285
  if (symbol?.isAlias())
285
286
  symbol = symbol.getAliasedSymbol() ?? symbol;
286
- for (const declaration of symbol?.getDeclarations() ?? []) {
287
- if (!this.isRepoFile(declaration.getSourceFile()))
288
- continue;
289
- if (Node.isFunctionDeclaration(declaration) ||
290
- Node.isMethodDeclaration(declaration) ||
291
- Node.isArrowFunction(declaration) ||
292
- Node.isFunctionExpression(declaration)) {
293
- return declaration.getBody() ? declaration : undefined;
294
- }
295
- if (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {
296
- const initializer = declaration.getInitializer();
297
- if (initializer && (Node.isArrowFunction(initializer) || Node.isFunctionExpression(initializer))) {
298
- return initializer;
299
- }
300
- }
301
- }
302
- return undefined;
287
+ return functionBodyOf((symbol?.getDeclarations() ?? []).filter((d) => this.isRepoFile(d.getSourceFile())));
303
288
  }
304
289
  // ===========================================================================
305
290
  // Reply
@@ -1584,6 +1584,16 @@ export declare class TypeInferrer {
1584
1584
  * annotates; see `recoverPayloadFromReturnStatements`.
1585
1585
  */
1586
1586
  private responseHelperPayloadNode;
1587
+ /**
1588
+ * True when a call's callee is a function this repository declares whose
1589
+ * every returned branch is a send stating an error or redirect status, or a
1590
+ * call to another such function (carrick#3523). `return failure(result)` is
1591
+ * then an error branch, as `json({ error }, { status: 400 })` written inline
1592
+ * is, and the value handed to it is never the success body. A callee that
1593
+ * returns anything else (a success send, a status the source does not fix,
1594
+ * a non-send) keeps the ordinary argument reading.
1595
+ */
1596
+ private callsFailureHelper;
1587
1597
  /**
1588
1598
  * True when a node's type reads as a response payload.
1589
1599
  *
@@ -20,11 +20,12 @@
20
20
  import * as path from 'node:path';
21
21
  import { Node, SyntaxKind, VariableDeclarationKind, ts, } from 'ts-morph';
22
22
  import { typeToStringAsDeclared } from './print-type.js';
23
+ import { functionBodyOf, peelValueWrappers } from './function-body.js';
23
24
  import { validateInferRequestItem } from './validators.js';
24
25
  import { declarationSite } from './bundler.js';
25
26
  import { printedTypeHoldsTopType, relateSymbolToRead } from './symbol-relation.js';
26
27
  import { notePrintedType, PrintedTypes } from './printed-names.js';
27
- import { externalImportsOf, isExternalOrigin } from './origin.js';
28
+ import { expandOriginOf, externalImportsOf, isExternalOrigin } from './origin.js';
28
29
  import { BINARY_BODY_READS, isPlatformBodyRead, JSON_READ, RAW_TEXT_FORMAT, WHOLE_BODY_READS, } from './platform-body-read.js';
29
30
  import { reachedOnlyOnFailure } from './failure-path.js';
30
31
  import { readResponseModes } from './response-modes.js';
@@ -35,11 +36,12 @@ import { endLineOf, startLineOf } from './line-index.js';
35
36
  import { callsOf, descendantsOf, descendantsOnLine, descendantsOnLines, wrap, } from './node-index.js';
36
37
  import { elapsedMs, inferTiming, phaseClock, timedPhase } from './infer-timing.js';
37
38
  import { importedNameOf, packageNameOf } from './library-claims.js';
39
+ import { constituentsOf } from './capture/index.js';
38
40
  import { StatedParams } from './stated-params.js';
39
41
  import { bindingToleratesAbsence, handlerToleratesAbsentBody } from './absent-body.js';
40
42
  import { replaceFileText } from './program-files.js';
41
43
  import { loopElementPick } from './loop-element.js';
42
- import { classifyStatusCodes, constituents, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, } from './capture/index.js';
44
+ import { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, } from './capture/index.js';
43
45
  import { addedDiagnostics, applyInsertions, fileDiagnostics, literalInsertions, mapBack, mapForward, normalise, pathOf, } from './unwidened.js';
44
46
  import { expandTypeStructural, jsonWireType, } from './type-structural-expander.js';
45
47
  /**
@@ -458,11 +460,7 @@ export class TypeInferrer {
458
460
  * classify one declaration two ways.
459
461
  */
460
462
  expandOrigin() {
461
- return {
462
- program: this.project.getProgram().compilerObject,
463
- repoRoot: this.repoRoot,
464
- imports: externalImportsOf(this.project),
465
- };
463
+ return expandOriginOf(this.project, this.repoRoot);
466
464
  }
467
465
  /**
468
466
  * Infer types for the given requests
@@ -4131,7 +4129,7 @@ export class TypeInferrer {
4131
4129
  for (const arg of args) {
4132
4130
  const entries = statusTableOf(checker, arg.compilerType);
4133
4131
  if (entries) {
4134
- tableValues.set(arg, new Set(entries.flatMap((entry) => constituents(checker.getTypeOfSymbolAtLocation(entry.symbol, at.compilerNode)))));
4132
+ tableValues.set(arg, new Set(entries.flatMap((entry) => constituentsOf(checker.getTypeOfSymbolAtLocation(entry.symbol, at.compilerNode)))));
4135
4133
  }
4136
4134
  }
4137
4135
  const bodies = new Map();
@@ -4145,7 +4143,7 @@ export class TypeInferrer {
4145
4143
  if (held.getText() === arg.getText())
4146
4144
  return true;
4147
4145
  const values = tableValues.get(arg);
4148
- const heldTypes = constituents(held.compilerType);
4146
+ const heldTypes = constituentsOf(held.compilerType);
4149
4147
  if (values &&
4150
4148
  heldTypes.length === values.size &&
4151
4149
  heldTypes.every((member) => values.has(member))) {
@@ -6367,19 +6365,7 @@ export class TypeInferrer {
6367
6365
  * expression.
6368
6366
  */
6369
6367
  builderFunctionOf(symbol) {
6370
- const bodies = [];
6371
- for (const declaration of symbol.getDeclarations()) {
6372
- if (Node.isFunctionDeclaration(declaration) && declaration.getBody()) {
6373
- bodies.push(declaration);
6374
- }
6375
- else if (Node.isVariableDeclaration(declaration)) {
6376
- const initializer = declaration.getInitializer();
6377
- const fn = initializer ? this.peelTransparentExpression(initializer) : undefined;
6378
- if (fn && (Node.isArrowFunction(fn) || Node.isFunctionExpression(fn)))
6379
- bodies.push(fn);
6380
- }
6381
- }
6382
- return bodies.length === 1 ? bodies[0] : undefined;
6368
+ return functionBodyOf(symbol.getDeclarations(), { methods: false });
6383
6369
  }
6384
6370
  /**
6385
6371
  * The payload a builder call serialises. The source states it, and the
@@ -6562,6 +6548,8 @@ export class TypeInferrer {
6562
6548
  const status = this.responseSiteStatus(call);
6563
6549
  if (status === 'error' || status === 'redirect')
6564
6550
  return undefined;
6551
+ if (Node.isCallExpression(call) && this.callsFailureHelper(call, depth))
6552
+ return undefined;
6565
6553
  // carrick#3053: a send the service's labels name carries its body in the
6566
6554
  // slot the label states, read as a labelled call send reads it.
6567
6555
  const labelled = this.statedParams.sendAt(call);
@@ -6590,6 +6578,37 @@ export class TypeInferrer {
6590
6578
  }
6591
6579
  return undefined;
6592
6580
  }
6581
+ /**
6582
+ * True when a call's callee is a function this repository declares whose
6583
+ * every returned branch is a send stating an error or redirect status, or a
6584
+ * call to another such function (carrick#3523). `return failure(result)` is
6585
+ * then an error branch, as `json({ error }, { status: 400 })` written inline
6586
+ * is, and the value handed to it is never the success body. A callee that
6587
+ * returns anything else (a success send, a status the source does not fix,
6588
+ * a non-send) keeps the ordinary argument reading.
6589
+ */
6590
+ callsFailureHelper(call, depth) {
6591
+ if (depth > RESPONSE_HELPER_MAX_DEPTH)
6592
+ return false;
6593
+ let symbol = call.getExpression().getSymbol();
6594
+ if (symbol?.isAlias())
6595
+ symbol = symbol.getAliasedSymbol() ?? symbol;
6596
+ if (!symbol || this.symbolIsLibOrExternalOrigin(symbol))
6597
+ return false;
6598
+ const helper = this.builderFunctionOf(symbol);
6599
+ if (!helper)
6600
+ return false;
6601
+ const branches = this.returnedExpressions(helper).flatMap((expression) => this.expandResponseBranches(expression, 0));
6602
+ if (branches.length === 0)
6603
+ return false;
6604
+ return branches.every((branch) => {
6605
+ const status = this.responseSiteStatus(branch);
6606
+ if (status === 'error' || status === 'redirect')
6607
+ return true;
6608
+ const inner = this.peelTransparentExpression(branch);
6609
+ return Node.isCallExpression(inner) && this.callsFailureHelper(inner, depth + 1);
6610
+ });
6611
+ }
6593
6612
  /**
6594
6613
  * True when a node's type reads as a response payload.
6595
6614
  *
@@ -7425,9 +7444,9 @@ export class TypeInferrer {
7425
7444
  */
7426
7445
  asHandlerFunction(node, followWrapperCalls = true) {
7427
7446
  const expr = this.unwrapExpressionNode(node);
7428
- if (Node.isArrowFunction(expr) || Node.isFunctionExpression(expr)) {
7429
- return expr;
7430
- }
7447
+ const inline = functionBodyOf([peelValueWrappers(expr)], { methods: false });
7448
+ if (inline)
7449
+ return inline;
7431
7450
  if (Node.isIdentifier(expr)) {
7432
7451
  for (const def of expr.getDefinitionNodes()) {
7433
7452
  const func = this.functionFromDeclaration(def, followWrapperCalls);
@@ -7450,7 +7469,9 @@ export class TypeInferrer {
7450
7469
  */
7451
7470
  functionFromDeclaration(decl, followWrapperCalls = true) {
7452
7471
  if (Node.isFunctionDeclaration(decl)) {
7453
- return decl;
7472
+ // A declaration with no body anywhere (`declare function`) is still the
7473
+ // handler's function; its body is out of reach, which callers read.
7474
+ return functionBodyOf(decl.getSymbol()?.getDeclarations() ?? [decl], { methods: false }) ?? decl;
7454
7475
  }
7455
7476
  if (Node.isArrowFunction(decl) || Node.isFunctionExpression(decl)) {
7456
7477
  return decl;
@@ -7469,10 +7490,10 @@ export class TypeInferrer {
7469
7490
  if (varDecl) {
7470
7491
  const initializer = varDecl.getInitializer();
7471
7492
  if (initializer) {
7493
+ const direct = functionBodyOf([varDecl], { methods: false });
7494
+ if (direct)
7495
+ return direct;
7472
7496
  const inner = this.unwrapExpressionNode(initializer);
7473
- if (Node.isArrowFunction(inner) || Node.isFunctionExpression(inner)) {
7474
- return inner;
7475
- }
7476
7497
  if (followWrapperCalls && Node.isCallExpression(inner)) {
7477
7498
  return this.functionWrappedBy(inner, 0);
7478
7499
  }
@@ -9245,47 +9266,24 @@ export class TypeInferrer {
9245
9266
  let symbol = call.getExpression().getSymbol();
9246
9267
  if (symbol?.isAlias())
9247
9268
  symbol = symbol.getAliasedSymbol() ?? symbol;
9248
- for (const declaration of symbol?.getDeclarations() ?? []) {
9249
- const fn = Node.isFunctionDeclaration(declaration) || Node.isMethodDeclaration(declaration)
9250
- ? declaration
9251
- : Node.isVariableDeclaration(declaration)
9252
- ? this.unwrapExpressionNode(declaration.getInitializer())
9253
- : undefined;
9254
- if (!fn ||
9255
- !(Node.isFunctionDeclaration(fn) ||
9256
- Node.isMethodDeclaration(fn) ||
9257
- Node.isArrowFunction(fn) ||
9258
- Node.isFunctionExpression(fn)) ||
9259
- !fn.getBody() ||
9260
- fn.getSourceFile().isDeclarationFile() ||
9261
- fn.getSourceFile().isInNodeModules()) {
9262
- continue;
9263
- }
9264
- const parameter = fn.getParameters()[index];
9265
- const parameterSymbol = parameter?.getNameNode().getSymbol()?.compilerSymbol;
9266
- if (!parameter || parameter.isRestParameter() || !parameterSymbol)
9267
- continue;
9268
- const returned = this.returnedExpressions(fn);
9269
- let returnsArgument = false;
9270
- const everyReturnPasses = returned.every((expression) => {
9271
- let node = expression;
9272
- while (Node.isParenthesizedExpression(node) ||
9273
- Node.isAsExpression(node) ||
9274
- Node.isTypeAssertion(node) ||
9275
- Node.isSatisfiesExpression(node) ||
9276
- Node.isNonNullExpression(node)) {
9277
- node = node.getExpression();
9278
- }
9279
- if (Node.isIdentifier(node) && node.getSymbol()?.compilerSymbol === parameterSymbol) {
9280
- returnsArgument = true;
9281
- return true;
9282
- }
9283
- return this.isEmptyDefault(node);
9284
- });
9285
- if (everyReturnPasses && returnsArgument)
9286
- return fn;
9269
+ const fn = functionBodyOf(symbol?.getDeclarations() ?? []);
9270
+ if (!fn || fn.getSourceFile().isDeclarationFile() || fn.getSourceFile().isInNodeModules()) {
9271
+ return undefined;
9287
9272
  }
9288
- return undefined;
9273
+ const parameter = fn.getParameters()[index];
9274
+ const parameterSymbol = parameter?.getNameNode().getSymbol()?.compilerSymbol;
9275
+ if (!parameter || parameter.isRestParameter() || !parameterSymbol)
9276
+ return undefined;
9277
+ let returnsArgument = false;
9278
+ const everyReturnPasses = this.returnedExpressions(fn).every((expression) => {
9279
+ const node = peelValueWrappers(expression);
9280
+ if (Node.isIdentifier(node) && node.getSymbol()?.compilerSymbol === parameterSymbol) {
9281
+ returnsArgument = true;
9282
+ return true;
9283
+ }
9284
+ return this.isEmptyDefault(node);
9285
+ });
9286
+ return everyReturnPasses && returnsArgument ? fn : undefined;
9289
9287
  }
9290
9288
  /** `{}`, `[]`, `null` or `undefined`: a default that states no member. */
9291
9289
  isEmptyDefault(node) {