carrick 0.3.147 → 0.3.149

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.
@@ -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
+ }
@@ -51,7 +51,7 @@ import { ts } from 'ts-morph';
51
51
  import type { ProjectLoader } from './project-loader.js';
52
52
  import type { PositionRowsCounts } from './types.js';
53
53
  /** The format's version, written in the header. */
54
- export declare const POSITION_ROWS_VERSION = 4;
54
+ export declare const POSITION_ROWS_VERSION = 5;
55
55
  /** The type is `any`, declared or inferred. Never set with the error type. */
56
56
  export declare const FLAG_ANY = 1;
57
57
  /** The type is the compiler's error type: something did not resolve. */
@@ -86,7 +86,7 @@ export declare const FLAG_RUNS_HANDED = 128;
86
86
  export declare const DECL_CAP = 16;
87
87
  /** The kinds {@link kindOf} gives a node; `decl` and `jsx` rows are written beside them. */
88
88
  export type NodeKind = 'call' | 'member' | 'compare' | 'ident';
89
- export type PositionKind = NodeKind | 'decl' | 'jsx';
89
+ export type PositionKind = NodeKind | 'decl' | 'jsx' | 'typed_decl';
90
90
  /** `[kind, start, end, symbol, decl_file, decl_line, decl_package, type_text, flags]` */
91
91
  export type PositionRow = [
92
92
  PositionKind,
@@ -247,6 +247,16 @@ export declare class PositionWalker {
247
247
  * A throw writes one row flagged {@link FLAG_CHECKER_THREW}.
248
248
  */
249
249
  private declRows;
250
+ /**
251
+ * The `typed_decl` row of a call (carrick#2448): the callee is a value
252
+ * (a parameter, a property, a local) whose type is a named function's own
253
+ * (`send: typeof fetch`), so the compiler gives the type a symbol whose
254
+ * declaration is that function's. Written only when the callee symbol is
255
+ * not already that declaration and the type's symbol is named (an
256
+ * anonymous function or type literal is `__function` / `__type`), so a
257
+ * direct call or a method call writes none.
258
+ */
259
+ private typedDeclRow;
250
260
  /** The row's symbol, following aliases to a target that has a declaration. */
251
261
  symbolOf(kind: PositionKind, node: ts.Node): ts.Symbol | undefined;
252
262
  /**
@@ -52,11 +52,11 @@ 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. */
59
- export const POSITION_ROWS_VERSION = 4;
59
+ export const POSITION_ROWS_VERSION = 5;
60
60
  /** The type is `any`, declared or inferred. Never set with the error type. */
61
61
  export const FLAG_ANY = 1;
62
62
  /** The type is the compiler's error type: something did not resolve. */
@@ -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
@@ -429,6 +426,11 @@ export class PositionWalker {
429
426
  for (const decl of this.declRows(kind, node))
430
427
  rows.push(['decl', row[1], row[2], ...tail(decl)]);
431
428
  }
429
+ if (kind === 'call' && !(row[8] & FLAG_CHECKER_THREW)) {
430
+ const typed = this.typedDeclRow(node, row[1], row[2]);
431
+ if (typed)
432
+ rows.push(typed);
433
+ }
432
434
  }
433
435
  if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
434
436
  rows.push(this.row('jsx', node.tagName, sourceFile));
@@ -746,6 +748,45 @@ export class PositionWalker {
746
748
  rows.sort((a, b) => compareNames(a.row[4], b.row[4]) || a.start - b.start);
747
749
  return rows.map(({ row }) => row);
748
750
  }
751
+ /**
752
+ * The `typed_decl` row of a call (carrick#2448): the callee is a value
753
+ * (a parameter, a property, a local) whose type is a named function's own
754
+ * (`send: typeof fetch`), so the compiler gives the type a symbol whose
755
+ * declaration is that function's. Written only when the callee symbol is
756
+ * not already that declaration and the type's symbol is named (an
757
+ * anonymous function or type literal is `__function` / `__type`), so a
758
+ * direct call or a method call writes none.
759
+ */
760
+ typedDeclRow(node, start, end) {
761
+ if (!ts.isCallExpression(node))
762
+ return undefined;
763
+ try {
764
+ const symbol = this.symbolOf('call', node);
765
+ if (!symbol)
766
+ return undefined;
767
+ const type = this.checker.getNonNullableType(this.checker.getTypeAtLocation(node.expression));
768
+ const typeSymbol = type.symbol;
769
+ if (!typeSymbol || typeSymbol.name.startsWith('__'))
770
+ return undefined;
771
+ if (type.getCallSignatures().length === 0)
772
+ return undefined;
773
+ const declaration = this.typeDeclaration(type);
774
+ if (!declaration)
775
+ return undefined;
776
+ const own = symbol.declarations ?? [];
777
+ if (own.some((d) => (typeSymbol.declarations ?? []).includes(d)))
778
+ return undefined;
779
+ const file = declaration.getSourceFile();
780
+ const { declFile, declLine, declPackage } = this.located(file, declaration.getStart(file));
781
+ let flags = this.publication(typeSymbol, declaration);
782
+ if (declFile === null)
783
+ flags |= FLAG_DECLARATION_UNNAMED;
784
+ return ['typed_decl', start, end, ts.symbolName(typeSymbol), declFile, declLine, declPackage, null, flags];
785
+ }
786
+ catch {
787
+ return undefined;
788
+ }
789
+ }
749
790
  /** The row's symbol, following aliases to a target that has a declaration. */
750
791
  symbolOf(kind, node) {
751
792
  let symbol;
@@ -932,6 +973,7 @@ function nameNodeOf(kind, node) {
932
973
  case 'ident':
933
974
  return node;
934
975
  case 'decl':
976
+ case 'typed_decl':
935
977
  return undefined;
936
978
  case 'jsx':
937
979
  // The tag: `<Badge>`, `<ui.Button>`, `<this.Panel>`; a namespaced
@@ -81,17 +81,12 @@ export declare class ProjectLoader {
81
81
  /** The tsconfig the service names, when the project is built from one. */
82
82
  private namedTsconfigPath;
83
83
  /**
84
- * Set when the service has no config at or above its root: each file is then
85
- * typed under the nearest `tsconfig.json`/`jsconfig.json` on its way up to
86
- * the service root (carrick#1604), and the default project holds the rest.
84
+ * The config each file is typed under (carrick#1604, carrick#3497): set for
85
+ * a service built from a tsconfig, with it as the fallback, and for one
86
+ * with no config at or above its root, with none. Unset (a snapshot or a
87
+ * Deno project), every file is the default project's.
87
88
  */
88
- private inferredService;
89
- /** The per-directory answers of `fileConfigPath` for this service. */
90
- private readonly fileConfigs;
91
- /** The reference owner rule of each config a file was found under. */
92
- private readonly ownerRules;
93
- /** Each file's owning config (carrick#1604), resolved on first use. */
94
- private configPathFor;
89
+ private governing;
95
90
  /** Programs built for owning projects other than the named tsconfig. */
96
91
  private readonly ownerProjects;
97
92
  private readonly repoRoot;
@@ -128,22 +123,15 @@ export declare class ProjectLoader {
128
123
  */
129
124
  private projectFromConfig;
130
125
  /**
131
- * Which project types `file` (carrick#1604): the key of its owning
132
- * project's program, or `''` for the default one. In a tsconfig that
133
- * references other projects, a file belongs to the first project in search
134
- * order (the named config, then its references depth-first, in declared
135
- * order) that lists it while none of its own references does (carrick#2418),
136
- * and is typed under that project's options. A file no project includes, and every request that
137
- * names no file, uses the default project, built from the named tsconfig
138
- * as before.
126
+ * Which project types `file` (carrick#1604, carrick#3497): the key of its
127
+ * owning project's program, or `''` for the default one. The owner is the
128
+ * config `GoverningConfigs` picks: the nearest config inside the service
129
+ * whose program, or a project it references (carrick#2418's search order),
130
+ * lists the file, else the service's tsconfig. The service's own tsconfig,
131
+ * every request that names no file, and a file no config governs use the
132
+ * default project.
139
133
  */
140
134
  projectKeyFor(file?: string): string;
141
- /**
142
- * `projectKeyFor` for a service with no config at its root: the owner of the
143
- * nearest config on the file's way up to the service root, or `''` (the
144
- * default project, under the inferred options) for a file with none.
145
- */
146
- private inferredKeyFor;
147
135
  /**
148
136
  * The project behind a key from `projectKeyFor`, built on first use and
149
137
  * kept: a service whose files all belong to one project builds one.
@@ -13,7 +13,7 @@ import { Project, getCompilerOptionsFromTsConfig } from 'ts-morph';
13
13
  import * as path from 'node:path';
14
14
  import ts from 'typescript';
15
15
  import * as fs from 'node:fs';
16
- import { DenoProject, findDenoConfig, fileConfigPath, findServiceTsconfig, referenceRedirectOf, serviceConfigPath, sidecarCompilerOptions, untrustedReadBound, } from './capture/index.js';
16
+ import { DenoProject, findDenoConfig, findServiceTsconfig, GoverningConfigs, referenceRedirectOf, sidecarCompilerOptions, untrustedReadBound, } from './capture/index.js';
17
17
  import { moduleFormatResolutionHost } from './module-format.js';
18
18
  import { ExternalImports, registerExternalImports } from './origin.js';
19
19
  import { pinProgramRoots } from './program-files.js';
@@ -141,17 +141,12 @@ export class ProjectLoader {
141
141
  /** The tsconfig the service names, when the project is built from one. */
142
142
  namedTsconfigPath;
143
143
  /**
144
- * Set when the service has no config at or above its root: each file is then
145
- * typed under the nearest `tsconfig.json`/`jsconfig.json` on its way up to
146
- * the service root (carrick#1604), and the default project holds the rest.
144
+ * The config each file is typed under (carrick#1604, carrick#3497): set for
145
+ * a service built from a tsconfig, with it as the fallback, and for one
146
+ * with no config at or above its root, with none. Unset (a snapshot or a
147
+ * Deno project), every file is the default project's.
147
148
  */
148
- inferredService = false;
149
- /** The per-directory answers of `fileConfigPath` for this service. */
150
- fileConfigs = new Map();
151
- /** The reference owner rule of each config a file was found under. */
152
- ownerRules = new Map();
153
- /** Each file's owning config (carrick#1604), resolved on first use. */
154
- configPathFor;
149
+ governing;
155
150
  /** Programs built for owning projects other than the named tsconfig. */
156
151
  ownerProjects = new Map();
157
152
  repoRoot;
@@ -253,11 +248,12 @@ export class ProjectLoader {
253
248
  else if (tsconfigPath) {
254
249
  this.log(`Project will load with tsconfig: ${tsconfigPath}`);
255
250
  this.namedTsconfigPath = tsconfigPath;
251
+ this.governing = new GoverningConfigs(this.repoRoot, tsconfigPath, (d) => this.logError(d));
256
252
  this.buildProject = (kind) => this.projectFromConfig(tsconfigPath, kind);
257
253
  }
258
254
  else {
259
255
  this.log('No tsconfig.json found, using default compiler options');
260
- this.inferredService = true;
256
+ this.governing = new GoverningConfigs(this.repoRoot, undefined, (d) => this.logError(d));
261
257
  this.buildProject = (kind) => {
262
258
  const project = new Project({
263
259
  ...this.fileSystemOption(),
@@ -379,7 +375,7 @@ export class ProjectLoader {
379
375
  // TypeScript reads a `jsconfig.json` with an implicit depth of 2, which
380
376
  // loads the JavaScript sources of installed packages; every other program
381
377
  // here reads 0. A depth the config states is kept (carrick#1604).
382
- if (this.inferredService && path.basename(configPath) === 'jsconfig.json' && !statesJsDepth(configPath)) {
378
+ if (configPath !== this.namedTsconfigPath && path.basename(configPath) === 'jsconfig.json' && !statesJsDepth(configPath)) {
383
379
  options.maxNodeModuleJsDepth = 0;
384
380
  }
385
381
  const project = new Project({
@@ -403,42 +399,19 @@ export class ProjectLoader {
403
399
  return project;
404
400
  }
405
401
  /**
406
- * Which project types `file` (carrick#1604): the key of its owning
407
- * project's program, or `''` for the default one. In a tsconfig that
408
- * references other projects, a file belongs to the first project in search
409
- * order (the named config, then its references depth-first, in declared
410
- * order) that lists it while none of its own references does (carrick#2418),
411
- * and is typed under that project's options. A file no project includes, and every request that
412
- * names no file, uses the default project, built from the named tsconfig
413
- * as before.
402
+ * Which project types `file` (carrick#1604, carrick#3497): the key of its
403
+ * owning project's program, or `''` for the default one. The owner is the
404
+ * config `GoverningConfigs` picks: the nearest config inside the service
405
+ * whose program, or a project it references (carrick#2418's search order),
406
+ * lists the file, else the service's tsconfig. The service's own tsconfig,
407
+ * every request that names no file, and a file no config governs use the
408
+ * default project.
414
409
  */
415
410
  projectKeyFor(file) {
416
- if (this.inferredService)
417
- return this.inferredKeyFor(file);
418
- if (!this.namedTsconfigPath || file === undefined)
411
+ if (file === undefined || this.governing === undefined)
419
412
  return '';
420
- this.configPathFor ??= serviceConfigPath(this.namedTsconfigPath, (d) => this.logError(d));
421
- const config = this.configPathFor(path.resolve(this.repoRoot, file));
422
- return config === this.namedTsconfigPath ? '' : config;
423
- }
424
- /**
425
- * `projectKeyFor` for a service with no config at its root: the owner of the
426
- * nearest config on the file's way up to the service root, or `''` (the
427
- * default project, under the inferred options) for a file with none.
428
- */
429
- inferredKeyFor(file) {
430
- if (file === undefined)
431
- return '';
432
- const absolute = path.resolve(this.repoRoot, file);
433
- const config = fileConfigPath(absolute, this.repoRoot, this.fileConfigs);
434
- if (config === undefined)
435
- return '';
436
- let owner = this.ownerRules.get(config);
437
- if (!owner) {
438
- owner = serviceConfigPath(config, (d) => this.logError(d));
439
- this.ownerRules.set(config, owner);
440
- }
441
- return owner(absolute);
413
+ const config = this.governing.configFor(path.resolve(this.repoRoot, file));
414
+ return config === undefined || config === this.namedTsconfigPath ? '' : config;
442
415
  }
443
416
  /**
444
417
  * The project behind a key from `projectKeyFor`, built on first use and
@@ -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
  *